code
stringlengths 2
1.05M
|
---|
// -------------------------------------------------------------
// WARNING: this file is used by both the client and the server.
// Do not use any browser or node-specific API!
// -------------------------------------------------------------
/* eslint hammerhead/proto-methods: 2 */
import reEscape from '../utils/regexp-escape';
import INTERNAL_ATTRS from '../processing/dom/internal-attributes';
import { isSpecialPage } from '../utils/url';
const SOURCE_MAP_RE = /#\s*sourceMappingURL\s*=\s*[^\s]+(\s|\*\/)/i;
const CSS_URL_PROPERTY_VALUE_PATTERN = /(url\s*\(\s*)(?:(')([^\s']*)(')|(")([^\s"]*)(")|([^\s\)]*))(\s*\))|(@import\s+)(?:(')([^\s']*)(')|(")([^\s"]*)("))/g;
const STYLESHEET_PROCESSING_START_COMMENT = '/*hammerhead|stylesheet|start*/';
const STYLESHEET_PROCESSING_END_COMMENT = '/*hammerhead|stylesheet|end*/';
const HOVER_PSEUDO_CLASS_RE = /\s*:\s*hover(\W)/gi;
const PSEUDO_CLASS_RE = new RegExp(`\\[${ INTERNAL_ATTRS.hoverPseudoClass }\\](\\W)`, 'ig');
const IS_STYLE_SHEET_PROCESSED_RE = new RegExp(`^\\s*${ reEscape(STYLESHEET_PROCESSING_START_COMMENT) }`, 'gi');
const STYLESHEET_PROCESSING_COMMENTS_RE = new RegExp(`^\\s*${ reEscape(STYLESHEET_PROCESSING_START_COMMENT) }\n?|` +
`\n?${ reEscape(STYLESHEET_PROCESSING_END_COMMENT) }\\s*$`, 'gi');
class StyleProcessor {
constructor () {
this.STYLESHEET_PROCESSING_START_COMMENT = STYLESHEET_PROCESSING_START_COMMENT;
this.STYLESHEET_PROCESSING_END_COMMENT = STYLESHEET_PROCESSING_END_COMMENT;
}
process (css, urlReplacer, isStylesheetTable) {
if (!css || typeof css !== 'string' || IS_STYLE_SHEET_PROCESSED_RE.test(css))
return css;
var prefix = isStylesheetTable ? STYLESHEET_PROCESSING_START_COMMENT + '\n' : '';
var postfix = isStylesheetTable ? '\n' + STYLESHEET_PROCESSING_END_COMMENT : '';
// NOTE: Replace the :hover pseudo-class.
css = css.replace(HOVER_PSEUDO_CLASS_RE, '[' + INTERNAL_ATTRS.hoverPseudoClass + ']$1');
// NOTE: Remove the ‘source map’ directive.
css = css.replace(SOURCE_MAP_RE, '$1');
// NOTE: Replace URLs in CSS rules with proxy URLs.
return prefix + this._replaceStylsheetUrls(css, urlReplacer) + postfix;
}
cleanUp (css, parseProxyUrl) {
if (typeof css !== 'string')
return css;
css = css
.replace(PSEUDO_CLASS_RE, ':hover$1')
.replace(STYLESHEET_PROCESSING_COMMENTS_RE, '');
return this._replaceStylsheetUrls(css, url => {
var parsedProxyUrl = parseProxyUrl(url);
return parsedProxyUrl ? parsedProxyUrl.destUrl : url;
});
}
_replaceStylsheetUrls (css, processor) {
return css.replace(
CSS_URL_PROPERTY_VALUE_PATTERN,
(match, prefix1, openQuote1, url1, closeQuote1, openQuote2, url2, closeQuote2, url3, postfix,
prefix2, openQuote3, url4, closeQuote3, openQuote4, url5, closeQuote4) => {
var prefix = prefix1 || prefix2;
var openQuote = openQuote1 || openQuote2 || openQuote3 || openQuote4 || '';
var url = url1 || url2 || url3 || url4 || url5;
var closeQuote = closeQuote1 || closeQuote2 || closeQuote3 || closeQuote4 || '';
postfix = postfix || '';
var processedUrl = isSpecialPage(url) ? url : processor(url);
return url ? prefix + openQuote + processedUrl + closeQuote + postfix : match;
}
);
}
}
export default new StyleProcessor();
|
import announcements from './announcements'
import delegates from './delegates'
import fees from './fees'
import ledger from './ledger'
import market from './market'
import peer from './peer'
import wallets from './wallets'
export {
announcements,
delegates,
fees,
ledger,
market,
peer,
wallets
}
|
/**
* @flow
* @module ProductPropertyInput
* @extends React.PureComponent
*
* @author Oleg Nosov <[email protected]>
* @license MIT
*
* @description
* React form for product property(options select only).
*
*/
import React, { PureComponent } from "react";
import { isObject } from "../../../helpers";
import type {
GetLocalization,
InputEvent,
ProductPropertyOption,
Prices,
} from "../../../types";
/**
* @typedef {Object.<string, number>} OptionIndex
*/
export type OptionIndex = {
[propertyName: string]: number,
};
/**
* @typedef {Object} OptionObject
*/
export type OptionObject = {|
onSelect?: (option: OptionObject) => void,
additionalCost?: Prices,
value: ProductPropertyOption,
|};
/** @ */
export type PropertyOption = ProductPropertyOption | OptionObject;
/** @ */
export type PropertyOptions = Array<PropertyOption>;
/** @ */
export type OnChange = (obj: { value: OptionIndex }) => void;
export type Props = {|
name: string,
options: PropertyOptions,
selectedOptionIndex: number,
currency: string,
onChange: OnChange,
getLocalization: GetLocalization,
|};
const defaultProps = {
selectedOptionIndex: 0,
};
export default class ProductPropertyInput extends PureComponent<Props, void> {
props: Props;
static defaultProps = defaultProps;
static displayName = "ProductPropertyInput";
/*
* If option value is an object, we need to extract primitive value
*/
static getOptionValue = (value: PropertyOption): ProductPropertyOption =>
isObject(value) ? ProductPropertyInput.getOptionValue(value.value) : value;
/*
* Generate select input options based on options values
*/
static generateOptionsSelectionList = (
options: PropertyOptions,
getLocalization: GetLocalization,
currency: string,
localizationScope: Object = {},
): Array<React$Element<*>> =>
options
.map(ProductPropertyInput.getOptionValue)
.map((optionValue, index) => (
<option key={optionValue} value={optionValue}>
{typeof optionValue === "string"
? getLocalization(optionValue, {
...localizationScope,
...(isObject(options[index])
? {
cost:
(isObject(options[index].additionalCost) &&
options[index].additionalCost[currency]) ||
0,
}
: {}),
})
: optionValue}
</option>
));
handleSelectInputValueChange = ({ currentTarget }: InputEvent) => {
const { value: optionValue } = currentTarget;
const { name, options, onChange } = this.props;
const { getOptionValue } = ProductPropertyInput;
const selectedOptionIndex = options
.map(getOptionValue)
.indexOf(optionValue);
const selectedOption = options[selectedOptionIndex];
if (
isObject(selectedOption) &&
typeof selectedOption.onSelect === "function"
)
selectedOption.onSelect(selectedOption);
onChange({
value: { [name]: selectedOptionIndex },
});
};
render() {
const {
name,
options,
selectedOptionIndex,
currency,
getLocalization,
} = this.props;
const { handleSelectInputValueChange } = this;
const {
generateOptionsSelectionList,
getOptionValue,
} = ProductPropertyInput;
const localizationScope = {
name,
currency,
get localizedName() {
return getLocalization(name, localizationScope);
},
get localizedCurrency() {
return getLocalization(currency, localizationScope);
},
};
return (
<div className="form-group row">
<label
htmlFor={name}
className="col-xs-3 col-sm-3 col-md-3 col-lg-3 col-form-label"
>
{getLocalization("propertyLabel", localizationScope)}
</label>
<div className="col-xs-9 col-sm-9 col-md-9 col-lg-9">
<select
onChange={handleSelectInputValueChange}
className="form-control"
value={getOptionValue(options[selectedOptionIndex | 0])}
>
{generateOptionsSelectionList(
options,
getLocalization,
currency,
localizationScope,
)}
</select>
</div>
</div>
);
}
}
|
let BASE_DIR = '/masn01-archive/';
const TAG_OPTIONS = ['meteor', 'cloud', 'bug', 'misc'];
let CURR_DIR = null;
let CURR_FILES = null;
let INIT_CMAP = null;
let CURR_IDX = 0;
let PREV_IDX = null;
$(async function() {
let cameras = JSON.parse(await $.get('cameras.php'));
cameras.forEach((camera) => {
$('#masn-switch').append(`<option value='${camera}/'>${camera}</option>`);
});
BASE_DIR = $('#masn-switch').val();
JS9.ResizeDisplay(750, 750);
TAG_OPTIONS.forEach(tag => $('#tag-select').append(`<option value='${tag}'>${tag}</option>`));
$('#datepicker').prop('disabled', true);
let result = await $.get(BASE_DIR);
let years = getDirectories(result, /\d{4}/);
console.log(years);
new Pikaday({
field: document.getElementById('datepicker'),
format: 'YYYY-MM-DD',
minDate: moment(`${years[0]}-01-01`, 'YYYY-MM-DD').toDate(),
maxDate: moment(`${years[years.length-1]}-12-31`, 'YYYY-MM-DD').toDate(),
defaultDate: moment(`2018-11-20`).toDate(),
onSelect: renderDate,
onDraw: async function(evt) {
let { year, month } = evt.calendars[0];
let { tabs, days } = await $.get(`stats.php?y=${year}&m=${String(month + 1).padStart(2, '0')}`);
let renderedDays = $('.pika-lendar tbody td').filter('[data-day]');
renderedDays.each((_, elem) => {
let dateStr = moment({
day: $(elem).data('day'),
month: month,
year: year
}).format('YYYY-MM-DD');
if (days.indexOf(dateStr) !== -1) {
let dateTab = tabs[days.indexOf(dateStr)];
$(elem).attr('data-tab', dateTab);
if (0 <= dateTab && dateTab < POOR_LIM) $(elem).addClass('day-poor');
else if (POOR_LIM <= dateTab && dateTab < MEDIUM_LIM) $(elem).addClass('day-medium');
else if (MEDIUM_LIM <= dateTab && dateTab < GOOD_LIM) $(elem).addClass('day-good');
}
});
}
});
$('#datepicker').prop('disabled', false);
$('#fileprev').click(function() {
if (CURR_FILES == null) return;
CURR_IDX = CURR_IDX - 1 < 0 ? CURR_FILES.length - 1 : CURR_IDX - 1;
$('#slider').slider('value', CURR_IDX + 1);
renderCurrentFile();
});
$('#filenext').click(function() {
if (CURR_FILES == null) return;
CURR_IDX = CURR_IDX + 1 >= CURR_FILES.length - 1 ? 0 : CURR_IDX + 1;
$('#slider').slider('value', CURR_IDX + 1);
renderCurrentFile();
});
$('#action-tag').click(function() {
let selectedRegions = JS9.GetRegions('selected');
if (selectedRegions.length === 1) {
$('#tag-select')[0].selectedIndex = 0;
$('#tag-modal').show();
} else if (selectedRegions.length > 1) {
alert('Please select only one region.');
} else {
alert('Please select a region.');
}
});
$('#tag-select').change(function(evt) {
let tag = $(this).val();
if (tag.trim() != '') {
JS9.ChangeRegions('selected', { text: tag, data: { tag: tag } });
saveCurrentRegions();
}
$('#tag-modal').hide();
});
$('#action-reset').click(function() {
if (INIT_CMAP == null) return;
JS9.SetColormap(INIT_CMAP.colormap, INIT_CMAP.contrast, INIT_CMAP.bias);
});
$('#action-save').click(function() {
saveCurrentRegions();
alert('All changes saved.');
});
$('#action-info').click(function() {
$('#info-modal').show();
});
$('.modal-close').click(function() {
$('.modal').hide();
});
$(window).keydown(function(evt) {
if (evt.which === 8 && JS9.GetImageData(true)) saveCurrentRegions();
if (evt.which === 27) $('.modal').hide();
});
});
function createSlider() {
let handle = $('#fits-handle');
handle.text(1);
$('#slider').slider({
value: 1,
min: 1,
max: CURR_FILES.length,
change: function(evt, ui) {
handle.text(ui.value);
CURR_IDX = ui.value - 1;
renderCurrentFile();
},
slide: function(evt, ui) {
handle.text(ui.value);
}
});
}
function getDirectories(html, regex) {
let parser = new DOMParser();
let root = parser.parseFromString(html, 'text/html');
let links = [].slice.call(root.getElementsByTagName('a'));
let hrefs = links.map(link => {
let directory = link.href.endsWith('/');
let dest = (directory ? link.href.slice(0, -1) : link.href).split('/').pop();
return dest.match(regex) ? dest : null;
}).filter(e => e != null);
return hrefs;
}
function renderCurrentFile() {
if (PREV_IDX == CURR_IDX) return;
if (CURR_FILES == null) return;
PREV_IDX = CURR_IDX;
let currentFile = CURR_FILES[CURR_IDX];
let currPath = `${CURR_DIR}/${currentFile}`;
JS9.CloseImage();
PREV_ZOOM = null;
PREV_PAN = null;
$('.JS9PluginContainer').each((idx, elem) => {
if($(elem).find('.tag-toggle, #tag-overlay').length === 0) {
$(elem).append(`<div class='tag-toggle'></div>`);
}
});
JS9.globalOpts.menuBar = ['scale'];
JS9.globalOpts.toolBar = ['box', 'circle', 'ellipse', 'zoom+', 'zoom-', 'zoomtofit'];
JS9.SetToolbar('init');
JS9.Load(currPath, {
zoom: 'ToFit',
onload: async function() {
let fileData = JSON.parse(await $.get({
url: 'regions.php',
cache: false
}, {
action: 'list',
path: currentFile
}));
if (Object.keys(fileData).length > 0) {
fileData.params = JSON.parse(fileData.params);
fileData.params.map(region => {
if (region.data.tag) region.text = region.data.tag;
return region;
});
JS9.AddRegions(fileData.params);
}
JS9.SetZoom('ToFit');
if (JS9.GetFlip() === 'none') JS9.SetFlip('x');
CENTER_PAN = JS9.GetPan();
INIT_CMAP = JS9.GetColormap();
console.log(CENTER_PAN);
$('#viewer-container').show();
$('#actions').show();
$('#filename').text(`${currentFile} (${CURR_IDX + 1}/${CURR_FILES.length})`);
$('#filetime').show();
updateSkymap(currentFile);
}
});
}
async function renderDate(date) {
$('#filename').text('Loading...');
let dateStr = moment(date).format('YYYY-MM-DD');
let yearDir = dateStr.substring(0, 4);
let monthDir = dateStr.substring(0, 7);
let parentDir = `${BASE_DIR}${yearDir}/${monthDir}/${dateStr}`
let list;
try {
list = await $.get(parentDir);
} catch (error) {
list = null;
}
let entries = getDirectories(list, /\.fits?/);
console.log(entries);
PREV_IDX = null;
CURR_IDX = 0;
CURR_DIR = parentDir;
CURR_FILES = entries;
if (list) {
$('#skytab').show().attr('src', `${parentDir}/sky.tab.thumb.png`);
createSlider();
renderCurrentFile();
} else {
$('#skytab').hide();
$('#filename').text('No data.');
$('#filetime').hide();
$('#viewer-container').hide();
$('#actions').hide();
}
}
function saveCurrentRegions() {
let regions = JS9.GetRegions('all');
let tags = JS9.GetRegions('all').map(region => region.data ? region.data.tag : null).filter(tag => tag != null);
$.get({
url: 'regions.php',
cache: false
}, {
action: 'update',
path: CURR_FILES[CURR_IDX],
tags: tags.join(','),
params: JSON.stringify(regions)
}).then(response => {
if (response.trim() !== '') {
alert(`Error saving regions: ${response}`);
}
});
}
|
import React, { Component, PropTypes } from 'react'
import { Search, Grid } from 'semantic-ui-react'
import { browserHistory } from 'react-router'
import Tag from './Tag'
import { search, setQuery, clearSearch } from '../actions/entities'
import { MIN_CHARACTERS, DONE_TYPING_INTERVAL } from '../constants/search'
const propTypes = {
dispatch: PropTypes.func.isRequired,
search: PropTypes.object.isRequired
}
const resultRenderer = ({ name, type, screenshots }) => {
return (
<Grid>
<Grid.Column floated="left" width={12}>
<Tag name={name} type={type} />
</Grid.Column>
<Grid.Column floated="right" width={4} textAlign="right">
<small className="text grey">{screenshots.length}</small>
</Grid.Column>
</Grid>
)
}
class GlobalSearch extends Component {
state = {
typingTimer: null
}
handleSearchChange = (e, value) => {
clearTimeout(this.state.typingTimer)
this.setState({
typingTimer: setTimeout(
() => this.handleDoneTyping(value.trim()),
DONE_TYPING_INTERVAL
)
})
const { dispatch } = this.props
dispatch(setQuery(value))
}
handleDoneTyping = value => {
if (value.length < MIN_CHARACTERS) return
const { dispatch } = this.props
dispatch(search({ query: value }))
}
handleResultSelect = (e, item) => {
const { dispatch } = this.props
const { name } = item
dispatch(clearSearch())
browserHistory.push(`/tag/${name}`)
}
render() {
const { search } = this.props
const { query, results } = search
return (
<Search
minCharacters={MIN_CHARACTERS}
onSearchChange={this.handleSearchChange}
onResultSelect={this.handleResultSelect}
resultRenderer={resultRenderer}
results={results}
value={query}
/>
)
}
}
GlobalSearch.propTypes = propTypes
export default GlobalSearch
|
<<<<<<< HEAD
var xmlDoc;
var xmlloaded = false;
var _finalUrl;
/*
* input: none
* output: none
* gets zipcode from the zipcode text field
*/
function createURL() {
var zip = document.getElementById("zipcode").value;
var format = "&format=xml"
var _clientId = "&client_id=API KEY";
var _url = "https://api.seatgeek.com/2/recommendations?events.id=1162104&postal_code=";
_finalUrl = _url + zip + _clientId + format;
// document.getElementById("displayURL").innerHTML = _finalUrl; // debugging
}
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
// ready states 1-4 & status 200 = okay
// 0: uninitialized
// 1: loading
// 2: loaded
// 3: interactive
// 4: complete
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp);
}
};
var zip = document.getElementById("zipcode").value;
var format = "&format=xml"
var _clientId = "&client_id=API KEY";
var _url = "https://api.seatgeek.com/2/recommendations?events.id=1162104&postal_code=";
_finalUrl = _url + zip + _clientId + format;
xhttp.open("GET", _finalUrl, true);
xhttp.send();
}
function myFunction(xml) {
var i, buyTickets;
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName("recommendations");
for (i = 0; i < x.length; i++) {
buyTickets = x[i].getElementsByTagName("url")[2].childNodes[0].nodeValue;
}
document.getElementById("demo").innerHTML = window.open(buyTickets);
}
|
// Copyright 2015 LastLeaf, LICENSE: github.lastleaf.me/MIT
'use strict';
var fs = require('fs');
var fse = require('fs-extra');
var async = require('async');
var User = fw.module('/db_model').User;
var exports = module.exports = function(conn, res, args){
User.checkPermission(conn, 'admin', function(perm){
if(!perm) return res.err('noPermission');
res.next();
});
};
exports.list = function(conn, res){
// read site list
var sitesDir = conn.app.config.app.siteRoot + '/xbackup/';
fs.readdir(sitesDir, function(err, files){
if(err) return res.err('system');
var sites = files.sort();
// list available backup files
var details = [];
var local = null;
async.eachSeries(sites, function(site, cb){
var siteDir = sitesDir + site;
if(site !== 'local' && site.slice(-5) !== '.site') return cb();
fs.readdir(siteDir, function(err, files){
if(err) return cb('system');
var zips = [];
for(var i=0; i<files.length; i++) {
var match = files[i].match(/^(.*?)\.xbackup\.zip(\.enc|)$/);
if(match) {
var ft = match[1].replace(/^([0-9]+)-([0-9]+)-([0-9]+)_([0-9]+)-([0-9]+)-([0-9]+)/, function(m, m1, m2, m3, m4, m5, m6){
return m1 + '-' + m2 + '-' + m3 + ' ' + m4 + ':' + m5 + ':' + m6;
});
zips.push({
file: files[i],
timeString: ft
});
}
}
if(site === 'local') {
local = zips;
} else details.push({
domain: site.slice(0, -5),
files: zips
});
cb();
});
}, function(err){
if(err) return res.err('system');
res({
local: local,
sites: details
});
});
});
};
exports.modify = function(conn, res, args){
var addSites = String(args.add).match(/\S+/g) || [];
var removeSites = String(args.remove).match(/\S+/g) || [];
async.eachSeries(removeSites, function(site, cb){
var dir = conn.app.config.app.siteRoot + '/xbackup/' + site + '.site';
fse.remove(dir, function(){
cb();
});
}, function(){
async.eachSeries(addSites, function(site, cb){
var dir = conn.app.config.app.siteRoot + '/xbackup/' + site + '.site';
fs.mkdir(dir, function(){
cb();
});
}, function(){
res();
});
});
};
|
$( document ).ready( function () {
$( "#form" ).validate( {
rules: {
company: { required: true },
truckType: { required: true },
materialType: { required: true },
fromSite: { required: true },
toSite: { required: true },
hourIn: { required: true },
hourOut: { required: true },
payment: { required: true },
plate: { minlength: 3, maxlength:15 }
},
errorElement: "em",
errorPlacement: function ( error, element ) {
// Add the `help-block` class to the error element
error.addClass( "help-block" );
error.insertAfter( element );
},
highlight: function ( element, errorClass, validClass ) {
$( element ).parents( ".col-sm-5" ).addClass( "has-error" ).removeClass( "has-success" );
},
unhighlight: function (element, errorClass, validClass) {
$( element ).parents( ".col-sm-5" ).addClass( "has-success" ).removeClass( "has-error" );
},
submitHandler: function (form) {
return true;
}
});
$("#btnClose").click(function(){
if(window.confirm('Are you sure you want to close this Hauling Report?'))
{
$.ajax({
type: "POST",
url: base_url + "hauling/update_hauling_state",
data: $("#form").serialize(),
dataType: "json",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
cache: false,
success: function(data){
if( data.result == "error" )
{
//alert(data.mensaje);
$("#div_cargando").css("display", "none");
$('#btnSubmit').removeAttr('disabled');
$("#span_msj").html(data.mensaje);
$("#div_msj").css("display", "inline");
return false;
}
if( data.result )//true
{
$("#div_cargando").css("display", "none");
$("#div_guardado").css("display", "inline");
$('#btnSubmit').removeAttr('disabled');
var url = base_url + "hauling/add_hauling/" + data.idHauling;
$(location).attr("href", url);
}
else
{
alert('Error. Reload the web page.');
$("#div_cargando").css("display", "none");
$("#div_error").css("display", "inline");
$('#btnSubmit').removeAttr('disabled');
}
},
error: function(result) {
alert('Error. Reload the web page.');
$("#div_cargando").css("display", "none");
$("#div_error").css("display", "inline");
$('#btnSubmit').removeAttr('disabled');
}
});
}
});
$("#btnSubmit").click(function(){
if ($("#form").valid() == true){
//Activa icono guardando
$('#btnSubmit').attr('disabled','-1');
$("#div_guardado").css("display", "none");
$("#div_error").css("display", "none");
$("#div_msj").css("display", "none");
$("#div_cargando").css("display", "inline");
$.ajax({
type: "POST",
url: base_url + "hauling/save_hauling",
data: $("#form").serialize(),
dataType: "json",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
cache: false,
success: function(data){
if( data.result == "error" )
{
//alert(data.mensaje);
$("#div_cargando").css("display", "none");
$('#btnSubmit').removeAttr('disabled');
$("#div_error").css("display", "inline");
$("#span_msj").html(data.mensaje);
return false;
}
if( data.result )//true
{
$("#div_cargando").css("display", "none");
$("#div_guardado").css("display", "inline");
$('#btnSubmit').removeAttr('disabled');
var url = base_url + "hauling/add_hauling/" + data.idHauling;
$(location).attr("href", url);
}
else
{
alert('Error. Reload the web page.');
$("#div_cargando").css("display", "none");
$("#div_error").css("display", "inline");
$('#btnSubmit').removeAttr('disabled');
}
},
error: function(result) {
alert('Error. Reload the web page.');
$("#div_cargando").css("display", "none");
$("#div_error").css("display", "inline");
$('#btnSubmit').removeAttr('disabled');
}
});
}//if
});
$("#btnEmail").click(function(){
if ($("#form").valid() == true){
//Activa icono guardando
$('#btnSubmit').attr('disabled','-1');
$('#btnEmail').attr('disabled','-1');
$("#div_guardado").css("display", "none");
$("#div_error").css("display", "none");
$("#div_msj").css("display", "none");
$("#div_cargando").css("display", "inline");
$.ajax({
type: "POST",
url: base_url + "hauling/save_hauling_and_send_email",
data: $("#form").serialize(),
dataType: "json",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
cache: false,
success: function(data){
if( data.result == "error" )
{
//alert(data.mensaje);
$("#div_cargando").css("display", "none");
$('#btnSubmit').removeAttr('disabled');
$('#btnEmail').removeAttr('disabled');
$("#div_error").css("display", "inline");
$("#span_msj").html(data.mensaje);
return false;
}
if( data.result )//true
{
$("#div_cargando").css("display", "none");
$("#div_guardado").css("display", "inline");
$('#btnSubmit').removeAttr('disabled');
$('#btnEmail').removeAttr('disabled');
var url = base_url + "hauling/add_hauling/" + data.idHauling;
$(location).attr("href", url);
}
else
{
alert('Error. Reload the web page.');
$("#div_cargando").css("display", "none");
$("#div_error").css("display", "inline");
$('#btnSubmit').removeAttr('disabled');
$('#btnEmail').removeAttr('disabled');
}
},
error: function(result) {
alert('Error. Reload the web page.');
$("#div_cargando").css("display", "none");
$("#div_error").css("display", "inline");
$('#btnSubmit').removeAttr('disabled');
$('#btnEmail').removeAttr('disabled');
}
});
}//if
});
}); |
var axios = require("axios");
var expect = require("chai").expect;
var MockAdapter = require("../src");
describe("MockAdapter asymmetric matchers", function () {
var instance;
var mock;
beforeEach(function () {
instance = axios.create();
mock = new MockAdapter(instance);
});
it("mocks a post request with a body matching the matcher", function () {
mock
.onPost("/anyWithBody", {
asymmetricMatch: function (actual) {
return actual.params === "1";
},
})
.reply(200);
return instance
.post("/anyWithBody", { params: "1" })
.then(function (response) {
expect(response.status).to.equal(200);
});
});
it("mocks a post request with a body not matching the matcher", function () {
mock
.onPost("/anyWithBody", {
asymmetricMatch: function (actual) {
return actual.params === "1";
},
})
.reply(200);
return instance
.post("/anyWithBody", { params: "2" })
.catch(function (error) {
expect(error.message).to.eq("Request failed with status code 404");
});
});
});
|
'use strict';
var intlNameInitials = function () {
};
var pattern = '{0}{1}';
function _firstLetter(text) {
return text.charAt(0);
}
function _upperCase(letter) {
if (letter === 'ı'){
return 'I';
}
return letter.toUpperCase();
}
function _isHangul(l){
if ((l > 44032) && (l < 55203)) {
return true;
}
return false;
}
function _initials(letter) {
var l = letter.charCodeAt(0);
// Generated by regenerate and unicode-8.0.0
// Greek 117
// Latin 991
// Cyrillic 302
var alphaRegex = '[A-Za-z\xAA\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02E0-\u02E4\u0370-\u0373\u0375-\u0377\u037A-\u037D\u037F\u0384\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03E1\u03F0-\u0484\u0487-\u052F\u1D00-\u1D25\u1D2C-\u1D5C\u1D62-\u1D65\u1D6B-\u1D77\u1D79-\u1DBE\u1E00-\u1EFE]';
var re = new RegExp(alphaRegex,'i');
if (re.test(letter)){
return letter;
}
return '';
}
function _isSupportedInitials(letter) {
var alphaRegex = '[A-Za-z\xAA\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02E0-\u02E4\u0370-\u0373\u0375-\u0377\u037A-\u037D\u037F\u0384\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03E1\u03F0-\u0484\u0487-\u052F\u1D00-\u1D25\u1D2C-\u1D5C\u1D62-\u1D65\u1D6B-\u1D77\u1D79-\u1DBE\u1E00-\u1EFE]';
var re = new RegExp(alphaRegex,'i');
if (re.test(letter)){
return true;
}
return false;
}
function isThai(a){
var thaiRegex = '[\u0E01-\u0E3A\u0E40-\u0E5B]';
var re = new RegExp(thaiRegex,'i');
if (a.length === 1){
return true;
} else {
var letter = _firstLetter(a);
if (re.test(a)) {
return true;
}
}
return false;
}
function isCJK(a){
// HANGUL SYLLABLES
// We want to be sure the full name is Hangul
if (a.length < 3){
var i = 0;
for(var c=0;c< a.length;c++){
if (_isHangul(a.charCodeAt(c)) )
{
i++;
}
}
if (i === a.length){
return true;
}
}
return false;
}
intlNameInitials.prototype.format = function (name, options) {
var initials = '',
a = '',
b = '';
var fields = ['firstName', 'lastName'],
initialName = { firstName : '', lastName: '' };
if (name === null || typeof name !== 'object' ) {
return undefined;
}
fields.forEach(function(field){
if (name.hasOwnProperty(field)) {
if (name[field] === null || name[field].length === 0){
// Nothing to do. but keeping it as placeholder
} else {
if (_isSupportedInitials(_firstLetter(name[field]))) {
initialName[field] = _firstLetter(name[field]);
initials = initials + _upperCase(_initials(initialName[field]));
}
}
}
});
// for CJK
if (name.hasOwnProperty("lastName")){
if (name.lastName === null || name.lastName.length === 0){
} else {
if (isCJK(name.lastName)) {
initials = name.lastName;
}
}
}
if (initials.length === 0){
return undefined;
}
return initials;
};
module.exports = intlNameInitials;
|
export default [
{
radius: 6,
sizeReduction: .85,
branchProbability: 0.12,
rotation: new THREE.Vector3(0, 1, 0),
color: 'blue'
},{
radius: 6,
sizeReduction: .85,
branchProbability: 0.21,
rotation: new THREE.Vector3(0, 1, 0),
color: 'blue'
},{
radius: 3,
sizeReduction: .87,
branchProbability: 0.25,
rotation: new THREE.Vector3(0, 1, 0),
color: 'blue'
}, {
radius: 7,
sizeReduction: .82,
branchProbability: 0.22,
rotation: new THREE.Vector3(0, 1, 0),
color: 'blue'
},{
radius: 7,
sizeReduction: .82,
branchProbability: 0.22,
rotation: new THREE.Vector3(0, 1, 0),
color: 'blue'
},{
radius: 7,
sizeReduction: .82,
branchProbability: 0.27,
rotation: new THREE.Vector3(0, 1, 0),
color: 'blue'
},
{
radius: 10,
sizeReduction: .9,
branchProbability: 0.2,
rotation: new THREE.Vector3(0, 1, 0),
color: 'pink'
},{
radius: 10,
sizeReduction: .75,
branchProbability: 0.3,
rotation: new THREE.Vector3(0, 1, 0),
color: 'pink'
}
];
|
setTimeout(() => {
import(/* webpackPreload: true */ "./lazy-chunk-2.js").then((mod) =>
mod.test()
);
}, 750);
|
var Purest = require('purest');
function Facebook(opts) {
this._opts = opts || {};
this._opts.provider = 'facebook';
this._purest = new Purest(this._opts);
this._group = 'LIB:SOCIAL:FACEBOOK';
return this;
}
Facebook.prototype.user = function (cb) {
var self = this;
this._purest.query()
.get('me')
.auth(this._opts.auth.token)
.request(function (err, res, body) {
if (err) {
console.log(err);
return cb(err);
}
cb(null, body);
});
};
Facebook.prototype.post = function (endpoint, form, cb) {
// form = {message: 'post message'}
this._purest.query()
.post(endpoint || 'me/feed')
.auth(this._opts.auth.token)
.form(form)
.request(function (err, res, body) {
if (err) {
console.log(err);
return cb(err);
}
cb(null, body);
});
};
module.exports = function(app) {
return Facebook;
};
|
describe('controllers/home', function () {
var di,
Core,
Home,
Type,
contentModel = {
findOne: function() {
}
},
widgetHooks = [],
widgetHook = {
load: function (a, b, c) {
widgetHooks.push({
name: a,
alias: b,
method: c
});
},
handle: function () {
}
};
beforeEach(function () {
di = require('mvcjs');
di.setAlias('cp', __dirname + '/../../app/controllers/');
Type = di.load('typejs');
Core = di.mock('@{cp}/core', {
'typejs': Type,
'core/controller': {
inherit: function () {
return Type.create.apply(Type, arguments);
}
},
'@{core}/widget-hook': widgetHook
});
Home = di.mock('@{cp}/home', {
'typejs': Type,
'promise': di.load('promise'),
'@{controllersPath}/core': Core,
'@{modelsPath}/content': contentModel
});
});
it('construct', function () {
var api = {};
var controller = new Home(api);
expect(controller.locals.scripts.length).toBe(0);
expect(controller.locals.brand).toBe('MVCJS');
expect(controller.locals.pageTitle).toBe('Mvcjs nodejs framework');
expect(controller.locals.pageDesc).toBe('Mvcjs fast, opinionated lightweight mvc framework for Node.js inspired by Yii framework');
expect(controller.menu.length).toBe(0);
});
it('action_index', function () {
var api = {
locals: {
scripts: []
},
renderFile: function(route, locals) {
return 'RENDERED';
}
};
spyOn(api, 'renderFile').and.callThrough();
di.setAlias('basePath', __dirname + '/../../');
var controller = new Home(api);
var result = controller.action_index.call(api);
expect(api.renderFile).toHaveBeenCalledWith( 'home/index', {
scripts : [ {
src : 'https://buttons.github.io/buttons.js',
id : 'github-bjs',
async : true
} ],
version : '0.1.0-beta-15'
});
expect(result).toBe('RENDERED');
expect(api.locals.scripts.length).toBe(1);
});
it('action_content', function () {
var api = {
locals: {
content: '',
pageTitle: '',
pageDesc: ''
},
renderFile: function(route, locals) {
return 'RENDERED';
}
};
spyOn(api, 'renderFile').and.callThrough();
di.setAlias('basePath', __dirname + '/../../');
var controller = new Home(api);
var result = controller.action_content.call(api, {}, {
text: 'TEXT',
pageTitle: 'TITLE',
pageDesc: 'DESC'
});
expect(api.renderFile).toHaveBeenCalledWith( 'home/content', {
pageTitle: 'TITLE',
pageDesc: 'DESC',
content : 'TEXT'
});
expect(result).toBe('RENDERED');
});
it('before_content', function (done) {
var api = {
getParsedUrl: function(route, locals) {
return {
pathname: '/home/index'
};
}
};
contentModel.findOne = function(data, callback) {
expect(data.url).toBe('/home/index');
callback(null, {
id: 1,
text: 'yes'
});
};
spyOn(api, 'getParsedUrl').and.callThrough();
spyOn(contentModel, 'findOne').and.callThrough();
di.setAlias('basePath', __dirname + '/../../');
var controller = new Home(api);
var result = controller.before_content.call(api);
result.then(function(data) {
expect(api.getParsedUrl).toHaveBeenCalled();
expect(contentModel.findOne).toHaveBeenCalled();
expect(data.id).toBe(1);
expect(data.text).toBe('yes');
done();
});
});
it('before_content error', function (done) {
var api = {
getParsedUrl: function(route, locals) {
return {
pathname: '/home/index'
};
}
};
contentModel.findOne = function(data, callback) {
expect(data.url).toBe('/home/index');
callback(true, {
id: 1,
text: 'yes'
});
};
spyOn(api, 'getParsedUrl').and.callThrough();
spyOn(contentModel, 'findOne').and.callThrough();
di.setAlias('basePath', __dirname + '/../../');
var controller = new Home(api);
var result = controller.before_content.call(api);
result.then(null, function(error) {
console.log('error', error);
done();
});
});
it('beforeEach', function () {
var api = {};
widgetHook.handle = function(hooks) {
expect(hooks.indexOf('menu-hook')).toBe(0);
return hooks.shift();
};
var controller = new Home(api);
expect(controller.beforeEach()).toBe('menu-hook');
expect(controller.locals.scripts.length).toBe(1);
});
it('action_error', function () {
var api = {
locals: {},
setStatusCode: function(code) {
expect(code).toBe(500);
},
renderFile: function(name, locals) {
expect(name).toBe('home/error');
expect(locals.pageTitle).toBe('Error - mvcjs nodejs framework');
expect(locals.text).toBe('ERROR');
return 'RENDER';
}
};
spyOn(api, 'setStatusCode').and.callThrough();
spyOn(api, 'renderFile').and.callThrough();
var controller = new Home({});
var response = controller.action_error.call(api, {
code: 500,
toString: function() {
return "ERROR";
}
});
expect(api.setStatusCode).toHaveBeenCalled();
expect(api.renderFile).toHaveBeenCalled();
expect(response).toBe('RENDER');
});
}); |
/* vim: set syntax=javascript ts=8 sts=8 sw=8 noet: */
/*
* Copyright 2016, Joyent, Inc.
*/
var BINDING = require('./lockfd_binding');
function
check_arg(pos, name, value, type)
{
if (typeof (value) !== type) {
throw (new Error('argument #' + pos + ' (' + name +
') must be of type ' + type));
}
}
function
lockfd(fd, callback)
{
check_arg(1, 'fd', fd, 'number');
check_arg(2, 'callback', callback, 'function');
BINDING.lock_fd(fd, 'write', false, function (ret, errmsg, errno) {
var err = null;
if (ret === -1) {
err = new Error('File Locking Error: ' + errmsg);
err.code = errno;
}
setImmediate(callback, err);
});
}
function
lockfdSync(fd)
{
var cb_fired = false;
var err;
check_arg(1, 'fd', fd, 'number');
BINDING.lock_fd(fd, 'write', true, function (ret, errno, errmsg) {
cb_fired = true;
if (ret === -1) {
err = new Error('File Locking Error: ' + errmsg);
err.__errno = errno;
return;
}
});
if (!cb_fired) {
throw (new Error('lockfdSync: CALLBACK NOT FIRED'));
} else if (err) {
throw (err);
}
return (null);
}
function
flock(fd, op, callback)
{
check_arg(1, 'fd', fd, 'number');
check_arg(2, 'op', op, 'number');
check_arg(3, 'callback', callback, 'function');
BINDING.flock(fd, op, false, function (ret, errmsg, errno) {
var err = null;
if (ret === -1) {
err = new Error('File Locking Error: ' + errmsg);
err.code = errno;
}
setImmediate(callback, err);
});
}
function
flockSync(fd, op)
{
var cb_fired = false;
var err;
check_arg(1, 'fd', fd, 'number');
check_arg(2, 'op', op, 'number');
BINDING.flock(fd, op, true, function (ret, errmsg, errno) {
cb_fired = true;
if (ret === -1) {
err = new Error('File Locking Error: ' + errmsg);
err.code = errno;
return;
}
});
if (!cb_fired) {
throw (new Error('flockSync: CALLBACK NOT FIRED'));
} else if (err) {
throw (err);
}
return (null);
}
module.exports = {
LOCK_SH: 1,
LOCK_EX: 2,
LOCK_NB: 4,
LOCK_UN: 8,
flock: flock,
flockSync: flockSync,
lockfd: lockfd,
lockfdSync: lockfdSync
};
|
'use strict';
angular.module('depthyApp')
.controller('DrawCtrl', function ($scope, $element, depthy, $window, $timeout) {
var drawer = depthy.drawMode,
viewer = depthy.getViewer(),
lastPointerPos = null,
oldViewerOpts = angular.extend({}, depthy.viewer);
drawer.setOptions(depthy.drawOptions || {
depth: 0.5,
size: 0.05,
hardness: 0.5,
opacity: 0.25,
});
angular.extend(depthy.viewer, {
animate: false,
fit: 'contain',
upscale: 2,
// depthPreview: 0.75,
// orient: false,
// hover: false,
});
$scope.drawer = drawer;
$scope.drawOpts = drawer.getOptions();
$scope.preview = 1;
$scope.brushMode = false;
$scope.$watch('drawOpts', function(options) {
if (drawer && options) {
drawer.setOptions(options);
}
}, true);
$scope.$watch('preview', function(preview) {
depthy.viewer.orient = preview === 2;
depthy.viewer.hover = preview === 2;
depthy.viewer.animate = preview === 2 && oldViewerOpts.animate;
depthy.viewer.quality = preview === 2 ? false : 1;
depthy.animateOption(depthy.viewer, {
depthPreview: preview === 0 ? 1 : preview === 1 ? 0.75 : 0,
depthScale: preview === 2 ? oldViewerOpts.depthScale : 0,
depthBlurSize: preview === 2 ? oldViewerOpts.depthBlurSize : 0,
enlarge: 1.0,
}, 250);
});
$scope.togglePreview = function() {
console.log('togglePreview', $scope.preview);
// $scope.preview = ++$scope.preview % 3;
$scope.preview = $scope.preview === 1 ? 2 : 1;
};
$scope.done = function() {
$window.history.back();
};
$scope.cancel = function() {
drawer.cancel();
$window.history.back();
};
$scope.brushIcon = function() {
switch($scope.brushMode) {
case 'picker':
return 'target';
case 'level':
return 'magnet';
default:
return 'draw';
}
};
$element.on('touchstart mousedown', function(e) {
console.log('mousedown');
var event = e.originalEvent,
pointerEvent = event.touches ? event.touches[0] : event;
if (event.target.id !== 'draw') return;
lastPointerPos = viewer.screenToImagePos({x: pointerEvent.pageX, y: pointerEvent.pageY});
if ($scope.brushMode === 'picker' || $scope.brushMode === 'level') {
$scope.drawOpts.depth = drawer.getDepthAtPos(lastPointerPos);
console.log('Picked %s', $scope.drawOpts.depth);
if ($scope.brushMode === 'picker') {
$scope.brushMode = false;
lastPointerPos = null;
$scope.$safeApply();
event.preventDefault();
event.stopPropagation();
return;
} else {
$scope.$safeApply();
}
}
drawer.drawBrush(lastPointerPos);
// updateDepthMap();
event.preventDefault();
event.stopPropagation();
});
$element.on('touchmove mousemove', function(e) {
if (lastPointerPos) {
var event = e.originalEvent,
pointerEvent = event.touches ? event.touches[0] : event,
pointerPos = viewer.screenToImagePos({x: pointerEvent.pageX, y: pointerEvent.pageY});
drawer.drawBrushTo(pointerPos);
lastPointerPos = pointerPos;
}
});
$element.on('touchend mouseup', function(event) {
console.log('mouseup', event);
if (lastPointerPos) {
lastPointerPos = null;
$scope.$safeApply();
}
// if(window.location.href.indexOf('preview')<0){
// updateDepthMap();
// }
});
$element.on('click', function(e) {
console.log('click');
// updateDepthMap();
});
function getSliderForKey(e) {
var id = 'draw-brush-depth';
if (e.shiftKey && e.altKey) {
id = 'draw-brush-hardness';
} else if (e.altKey) {
id = 'draw-brush-opacity';
} else if (e.shiftKey) {
id = 'draw-brush-size';
}
var el = $element.find('.' + id + ' [range-stepper]');
el.click(); // simulate click to notify change
return el.controller('rangeStepper');
}
function onKeyDown(e) {
console.log('keydown', e);
var s, handled = false;
console.log('keydown which %d shift %s alt %s ctrl %s', e.which, e.shiftKey, e.altKey, e.ctrlKey);
if (e.which === 48) { // 0
getSliderForKey(e).percent(0.5);
handled = true;
} else if (e.which >= 49 && e.which <= 57) { // 1-9
getSliderForKey(e).percent((e.which - 49) / 8);
handled = true;
} else if (e.which === 189) { // -
s = getSliderForKey(e);
s.percent(s.percent() - 0.025);
handled = true;
} else if (e.which === 187) { // +
s = getSliderForKey(e);
s.percent(s.percent() + 0.025);
handled = true;
} else if (e.which === 32) {
$element.find('.draw-preview').click();
handled = true;
} else if (e.which === 90) { // z
$element.find('.draw-undo').click();
handled = true;
} else if (e.which === 80) { // p
$element.find('.draw-picker').click();
handled = true;
} else if (e.which === 76) { // l
$element.find('.draw-level').click();
handled = true;
} else if (e.which === 81) { // l
$scope.preview = $scope.preview === 1 ? 2 : 1;
handled = true;
}
if (handled) {
e.preventDefault();
$scope.$safeApply();
}
}
$($window).on('keydown', onKeyDown);
$element.find('.draw-brush-depth').on('touchstart mousedown click', function() {
$scope.brushMode = false;
});
$element.on('$destroy', function() {
$element.off('touchstart mousedown');
$element.off('touchmove mousemove');
$($window).off('keydown', onKeyDown);
depthy.animateOption(depthy.viewer, {
depthPreview: oldViewerOpts.depthPreview,
depthScale: oldViewerOpts.depthScale,
depthBlurSize: oldViewerOpts.depthBlurSize,
enlarge: oldViewerOpts.enlarge,
}, 250);
$timeout(function() {
angular.extend(depthy.viewer, oldViewerOpts);
}, 251);
if (drawer.isCanceled()) {
// restore opened depthmap
viewer.setDepthmap(depthy.opened.depthSource, depthy.opened.depthUsesAlpha);
} else {
if (drawer.isModified()) {
updateDepthMap();
}
}
drawer.destroy(true);
});
function updateDepthMap(){
depthy.drawOptions = drawer.getOptions();
// remember drawn depthmap
// store it as jpg
console.log('updateDepthMap',viewer);
viewer.exportDepthmap().then(function(url) {
depthy.opened.markAsModified();
depthy.opened.depthSource = url; //viewer.getDepthmap().texture;
depthy.opened.depthUsesAlpha = false;
viewer.setDepthmap(url);
depthy.opened.onDepthmapOpened();
localStorage.depthMapUrl = url;
var intercom = Intercom.getInstance();
intercom.emit('depthMapUrl', {message: url});
});
}
}); |
/* eslint-disable node/no-deprecated-api */
module.exports.pathBasename = pathBasename
module.exports.hasSuffix = hasSuffix
module.exports.serialize = serialize
module.exports.translate = translate
module.exports.stringToStream = stringToStream
module.exports.debrack = debrack
module.exports.stripLineEndings = stripLineEndings
module.exports.fullUrlForReq = fullUrlForReq
module.exports.routeResolvedFile = routeResolvedFile
module.exports.getQuota = getQuota
module.exports.overQuota = overQuota
module.exports.getContentType = getContentType
module.exports.parse = parse
const fs = require('fs')
const path = require('path')
const util = require('util')
const $rdf = require('rdflib')
const from = require('from2')
const url = require('url')
const debug = require('./debug').fs
const getSize = require('get-folder-size')
const ns = require('solid-namespace')($rdf)
/**
* Returns a fully qualified URL from an Express.js Request object.
* (It's insane that Express does not provide this natively.)
*
* Usage:
*
* ```
* console.log(util.fullUrlForReq(req))
* // -> https://example.com/path/to/resource?q1=v1
* ```
*
* @param req {IncomingRequest}
*
* @return {string}
*/
function fullUrlForReq (req) {
const fullUrl = url.format({
protocol: req.protocol,
host: req.get('host'),
pathname: url.resolve(req.baseUrl, req.path),
query: req.query
})
return fullUrl
}
/**
* Removes the `<` and `>` brackets around a string and returns it.
* Used by the `allow` handler in `verifyDelegator()` logic.
* @method debrack
*
* @param s {string}
*
* @return {string}
*/
function debrack (s) {
if (!s || s.length < 2) {
return s
}
if (s[0] !== '<') {
return s
}
if (s[s.length - 1] !== '>') {
return s
}
return s.substring(1, s.length - 1)
}
async function parse (data, baseUri, contentType) {
const graph = $rdf.graph()
return new Promise((resolve, reject) => {
try {
return $rdf.parse(data, graph, baseUri, contentType, (err, str) => {
if (err) {
return reject(err)
}
resolve(str)
})
} catch (err) {
return reject(err)
}
})
}
function pathBasename (fullpath) {
let bname = ''
if (fullpath) {
bname = (fullpath.lastIndexOf('/') === fullpath.length - 1)
? ''
: path.basename(fullpath)
}
return bname
}
function hasSuffix (path, suffixes) {
for (const i in suffixes) {
if (path.indexOf(suffixes[i], path.length - suffixes[i].length) !== -1) {
return true
}
}
return false
}
function serialize (graph, baseUri, contentType) {
return new Promise((resolve, reject) => {
try {
// target, kb, base, contentType, callback
$rdf.serialize(null, graph, baseUri, contentType, function (err, result) {
if (err) {
return reject(err)
}
if (result === undefined) {
return reject(new Error('Error serializing the graph to ' +
contentType))
}
resolve(result)
})
} catch (err) {
reject(err)
}
})
}
function translate (stream, baseUri, from, to) {
return new Promise((resolve, reject) => {
let data = ''
stream
.on('data', function (chunk) {
data += chunk
})
.on('end', function () {
const graph = $rdf.graph()
$rdf.parse(data, graph, baseUri, from, function (err) {
if (err) return reject(err)
resolve(serialize(graph, baseUri, to))
})
})
})
}
function stringToStream (string) {
return from(function (size, next) {
// if there's no more content
// left in the string, close the stream.
if (!string || string.length <= 0) {
return next(null, null)
}
// Pull in a new chunk of text,
// removing it from the string.
const chunk = string.slice(0, size)
string = string.slice(size)
// Emit "chunk" from the stream.
next(null, chunk)
})
}
/**
* Removes line endings from a given string. Used for WebID TLS Certificate
* generation.
*
* @param obj {string}
*
* @return {string}
*/
function stripLineEndings (obj) {
if (!obj) { return obj }
return obj.replace(/(\r\n|\n|\r)/gm, '')
}
/**
* Adds a route that serves a static file from another Node module
*/
function routeResolvedFile (router, path, file, appendFileName = true) {
const fullPath = appendFileName ? path + file.match(/[^/]+$/) : path
const fullFile = require.resolve(file)
router.get(fullPath, (req, res) => res.sendFile(fullFile))
}
/**
* Returns the number of bytes that the user owning the requested POD
* may store or Infinity if no limit
*/
async function getQuota (root, serverUri) {
const filename = path.join(root, 'settings/serverSide.ttl')
let prefs
try {
prefs = await _asyncReadfile(filename)
} catch (error) {
debug('Setting no quota. While reading serverSide.ttl, got ' + error)
return Infinity
}
const graph = $rdf.graph()
const storageUri = serverUri + '/'
try {
$rdf.parse(prefs, graph, storageUri, 'text/turtle')
} catch (error) {
throw new Error('Failed to parse serverSide.ttl, got ' + error)
}
return Number(graph.anyValue($rdf.sym(storageUri), ns.solid('storageQuota'))) || Infinity
}
/**
* Returns true of the user has already exceeded their quota, i.e. it
* will check if new requests should be rejected, which means they
* could PUT a large file and get away with it.
*/
async function overQuota (root, serverUri) {
const quota = await getQuota(root, serverUri)
if (quota === Infinity) {
return false
}
// TODO: cache this value?
const size = await actualSize(root)
return (size > quota)
}
/**
* Returns the number of bytes that is occupied by the actual files in
* the file system. IMPORTANT NOTE: Since it traverses the directory
* to find the actual file sizes, this does a costly operation, but
* neglible for the small quotas we currently allow. If the quotas
* grow bigger, this will significantly reduce write performance, and
* so it needs to be rewritten.
*/
function actualSize (root) {
return util.promisify(getSize)(root)
}
function _asyncReadfile (filename) {
return util.promisify(fs.readFile)(filename, 'utf-8')
}
/**
* Get the content type from a headers object
* @param headers An Express or Fetch API headers object
* @return {string} A content type string
*/
function getContentType (headers) {
const value = headers.get ? headers.get('content-type') : headers['content-type']
return value ? value.replace(/;.*/, '') : 'application/octet-stream'
}
|
Template.postSubmit.onCreated(function() {
Session.set('postSubmitErrors', {});
});
Template.postSubmit.helpers({
errorMessage: function(field) {
return Session.get('postSubmitErrors')[field];
},
errorClass: function (field) {
return !!Session.get('postSubmitErrors')[field] ? 'has-error' : '';
}
});
Template.postSubmit.onRendered(function(){
// AutoForm.hooks({
// postSubmitForm: hooksObject
// });
});
// Template.postSubmit.events({
// 'submit form': function(e) {
// e.preventDefault();
// var post = {
// url: $(e.target).find('[name=url]').val(),
// title: $(e.target).find('[name=title]').val()
// };
// var errors = validatePost(post);
// if (errors.title || errors.url)
// return Session.set('postSubmitErrors', errors);
// Meteor.call('postInsert', post, function(error, result) {
// // display the error to the user and abort
// if (error)
// return throwError(error.reason);
// // show this result but route anyway
// if (result.postExists)
// throwError('This link has already been posted');
// Router.go('postPage', {_id: result._id});
// });
// }
// }); |
version https://git-lfs.github.com/spec/v1
oid sha256:c4d5490597798effaf63d11e546f0b200f196f28e17c69d39ce236de0c6683f0
size 64139
|
/* omega - node.js server
http://code.google.com/p/theomega/
Copyright 2011, Jonathon Fillmore
Licensed under the MIT license. See LICENSE file.
http://www.opensource.org/licenses/mit-license.php */
var http=require("http");var om=require("./omlib");
var Omega={Request:function(req){var req;req={api:null};req._sock=req;req._answer=function(){return"foo!"};return req},Response:function(res){var resp;resp={_sock:res,data:null,result:false,encoding:"json",headers:{"Content-Type":"text/plain","Cache-Control":"no-cache"},return_code:"200"};resp.set_result=function(result){resp.result=result?true:false};resp.encode=function(){var answer={result:resp.result};if(resp.result)answer.data=resp.data;else{answer.reason=resp.data;answer.data=null}return om.json.encode(answer)};
return resp},Server:function(conf){var omega;omega={_session_id:null,_session:null,_conf:conf,config:null,request:null,response:null,service:null,service_name:""};omega.answer=function(req,res){var answer;omega.request=Omega.Request(req);omega.response=Omega.Response(res);try{omega.response.data=omega.request._answer();omega.response.result=true}catch(e){omega.response.data=e;omega.response.return_code="500"}res.writeHead(omega.response.return_code,omega.response.headers);res.end(omega.response.encode())};
omega._server=http.createServer(omega.answer);omega._server.listen(conf.port,conf.iface);if(omega._conf.verbose)console.log(om.sprintf("Server running at http://%s:%d/",conf.iface,conf.port));return omega}};exports.Server=Omega.Server;
|
(function() {
var $, expect, fruits;
$ = require('../');
expect = require('expect.js');
/*
Examples
*/
fruits = '<ul id = "fruits">\n <li class = "apple">Apple</li>\n <li class = "orange">Orange</li>\n <li class = "pear">Pear</li>\n</ul>'.replace(/(\n|\s{2})/g, '');
/*
Tests
*/
describe('$(...)', function() {
describe('.find', function() {
it('() : should return this', function() {
return expect($('ul', fruits).find()[0].name).to.equal('ul');
});
it('(single) : should find one descendant', function() {
return expect($('#fruits', fruits).find('.apple')[0].attribs["class"]).to.equal('apple');
});
it('(many) : should find all matching descendant', function() {
return expect($('#fruits', fruits).find('li')).to.have.length(3);
});
it('(many) : should merge all selected elems with matching descendants');
it('(invalid single) : should return empty if cant find', function() {
return expect($('ul', fruits).find('blah')).to.have.length(0);
});
return it('should return empty if search already empty result', function() {
return expect($('#fruits').find('li')).to.have.length(0);
});
});
describe('.children', function() {
it('() : should get all children', function() {
return expect($('ul', fruits).children()).to.have.length(3);
});
it('(selector) : should return children matching selector', function() {
return expect($('ul', fruits).children('.orange').hasClass('orange')).to.be.ok;
});
it('(invalid selector) : should return empty', function() {
return expect($('ul', fruits).children('.lulz')).to.have.length(0);
});
return it('should only match immediate children, not ancestors');
});
describe('.next', function() {
it('() : should return next element', function() {
return expect($('.orange', fruits).next().hasClass('pear')).to.be.ok;
});
return it('(no next) : should return null (?)');
});
describe('.prev', function() {
it('() : should return previous element', function() {
return expect($('.orange', fruits).prev().hasClass('apple')).to.be.ok;
});
return it('(no prev) : should return null (?)');
});
describe('.siblings', function() {
it('() : should get all the siblings', function() {
return expect($('.orange', fruits).siblings()).to.have.length(2);
});
return it('(selector) : should get all siblings that match the selector', function() {
return expect($('.orange', fruits).siblings('li')).to.have.length(2);
});
});
describe('.each', function() {
return it('( (i, elem) -> ) : should loop selected returning fn with (i, elem)', function() {
var items;
items = [];
$('li', fruits).each(function(i, elem) {
return items[i] = elem;
});
expect(items[0].attribs["class"]).to.equal('apple');
expect(items[1].attribs["class"]).to.equal('orange');
return expect(items[2].attribs["class"]).to.equal('pear');
});
});
describe('.first', function() {
it('() : should return the first item', function() {
var elem, src;
src = $("<span>foo</span><span>bar</span><span>baz</span>");
elem = src.first();
expect(elem.length).to.equal(1);
return expect(elem.html()).to.equal('foo');
});
return it('() : should return an empty object for an empty object', function() {
var first, src;
src = $();
first = src.first();
expect(first.length).to.equal(0);
return expect(first.html()).to.be(null);
});
});
describe('.last', function() {
it('() : should return the last element', function() {
var elem, src;
src = $("<span>foo</span><span>bar</span><span>baz</span>");
elem = src.last();
expect(elem.length).to.equal(1);
return expect(elem.html()).to.equal('baz');
});
return it('() : should return an empty object for an empty object', function() {
var last, src;
src = $();
last = src.last();
expect(last.length).to.equal(0);
return expect(last.html()).to.be(null);
});
});
describe('.first & .last', function() {
return it('() : should return same object if only one object', function() {
var first, last, src;
src = $("<span>bar</span>");
first = src.first();
last = src.last();
expect(first.html()).to.equal(last.html());
expect(first.length).to.equal(1);
expect(first.html()).to.equal('bar');
expect(last.length).to.equal(1);
return expect(last.html()).to.equal('bar');
});
});
return describe('.eq', function() {
return it('(i) : should return the element at the specified index', function() {
expect($('li', fruits).eq(0).text()).to.equal('Apple');
expect($('li', fruits).eq(1).text()).to.equal('Orange');
expect($('li', fruits).eq(2).text()).to.equal('Pear');
expect($('li', fruits).eq(3).text()).to.equal('');
return expect($('li', fruits).eq(-1).text()).to.equal('Pear');
});
});
});
}).call(this);
|
(function(){
'use strict';
function ListService($http){
this.getList = function(list_id){
return $http.get('/lists/' + list_id + ".json")
}
}
ListService.$inject = ['$http']
angular
.module('app')
.service('ListService', ListService)
}()) |
angular.module('movieApp')
.directive('movieResult', function () {
var directive = {
restrict: 'E',
replace: true,
scope: {
result: '=result'
},
template: [
'<div class="row">',
'<div class="col-sm-4">',
'<img ng-src="{{result.Poster}}" alt="{{result.Title}}" width="220px">',
'</div>',
'<div class="col-sm-8">',
'<h3>{{result.Title}}</h3>',
'<p>{{result.Plot}}</p>',
'<p><strong>Director:</strong> {{result.Director}}</p>',
'<p><strong>Actors:</strong> {{result.Actors}}</p>',
'<p><strong>Released:</strong> {{result.Released}} ({{result.Released | fromNow}})</p>',
'<p><strong>Genre:</strong> {{result.Genre}}</p>',
'</div>',
'</div>'
].join('')
};
return directive;
}); |
/* eslint-env mocha */
const { expect } = chai;
import React from './React';
import TestUtils from './TestUtils';
describe('React components', () => {
it('should find valid xpath in react component', () => {
const component = TestUtils.renderIntoDocument(<blink>hi</blink>);
expect(component).to.have.xpath('//blink');
});
it('should find valid xpath in react component twice', () => {
const component = TestUtils.renderIntoDocument(<blink>hi</blink>);
expect(component).to.have.xpath('//blink');
expect(component).to.have.xpath('//blink');
});
describe('when it does not find valid xpath in react component', () => {
it('should throw', () => {
const component = TestUtils.renderIntoDocument(<blink>hi</blink>);
expect(() => {
expect(component).to.have.xpath('//h1');
}).to.throw('to have xpath \'//h1\'');
});
it('should throw with outerHTML of the component', () => {
const component = TestUtils.renderIntoDocument(<blink>hi</blink>);
expect(() => {
expect(component).to.have.xpath('//h1');
}).to.throw('hi</blink>');
});
});
});
|
const getAllMatchers = require("./getAllMatchers");
describe("unit: getAllMatchers", () => {
let handler;
let matcherStore;
beforeEach(() => {
matcherStore = [{}, {}, {}];
handler = getAllMatchers(matcherStore);
});
test("it should return all matchers", () => {
expect(handler()).toHaveProperty("body", matcherStore);
});
test("it should return a status of 200", () => {
expect(handler()).toHaveProperty("status", 200);
});
});
|
black = '#202427';
red = '#EB6A58'; // red
green = '#49A61D'; // green
yellow = '#959721'; // yellow
blue = '#798FB7'; // blue
magenta = '#CD7B7E'; // pink
cyan = '#4FA090'; // cyan
white = '#909294'; // light gray
lightBlack = '#292B35'; // medium gray
lightRed = '#DB7824'; // red
lightGreen = '#09A854'; // green
lightYellow = '#AD8E4B'; // yellow
lightBlue = '#309DC1'; // blue
lightMagenta= '#C874C2'; // pink
lightCyan = '#1BA2A0'; // cyan
lightWhite = '#8DA3B8'; // white
t.prefs_.set('color-palette-overrides',
[ black , red , green , yellow,
blue , magenta , cyan , white,
lightBlack , lightRed , lightGreen , lightYellow,
lightBlue , lightMagenta , lightCyan , lightWhite ]);
t.prefs_.set('cursor-color', lightWhite);
t.prefs_.set('foreground-color', lightWhite);
t.prefs_.set('background-color', black);
|
var createSubmit = function(name, primus, keyDict) {
return function(event) {
var message = $('#message').val();
if (message.length === 0) {
event.preventDefault();
return;
}
$('#message').val('');
$('#message').focus();
var BigInteger = forge.jsbn.BigInteger;
var data = JSON.parse(sessionStorage[name]);
var pem = data.pem;
var privateKey = forge.pki.privateKeyFromPem(pem);
var ownPublicKey = forge.pki.setRsaPublicKey(new BigInteger(data.n), new BigInteger(data.e));
var keys = [];
var iv = forge.random.getBytesSync(16);
var key = forge.random.getBytesSync(16);
var cipher = forge.cipher.createCipher('AES-CBC', key);
cipher.start({iv: iv});
cipher.update(forge.util.createBuffer(message, 'utf8'));
cipher.finish();
var encryptedMessage = cipher.output.getBytes();
var encryptedKey = ownPublicKey.encrypt(key, 'RSA-OAEP');
keys.push({
'name': name,
'key': encryptedKey
});
var md = forge.md.sha1.create();
md.update(message, 'utf8');
var signature = privateKey.sign(md);
var recipients = $.map($("#recipients").tokenfield("getTokens"), function(o) {return o.value;});
var deferredRequests = [];
for (var i = 0; i < recipients.length; i++) {
(function (index) {
var retrieveKey = function(pk) {
if (pk === false) {
return;
}
if (keyDict[recipients[i]] === undefined) {
keyDict[recipients[i]] = pk;
}
var publicKey = forge.pki.setRsaPublicKey(new BigInteger(pk.n), new BigInteger(pk.e));
var encryptedKey = publicKey.encrypt(key, 'RSA-OAEP');
keys.push({
'name': recipients[index],
'key': encryptedKey
});
}
if (keyDict[recipients[i]] === undefined) {
deferredRequests.push($.post('/user/getpublickey', {'name' : recipients[i]}, retrieveKey));
} else {
retrieveKey(keyDict[recipients[i]]);
}
})(i);
}
$.when.apply(null, deferredRequests).done(function() {
primus.substream('messageStream').write({'message': encryptedMessage, 'keys': keys, 'iv': iv,
'signature': signature, 'recipients': recipients});
});
event.preventDefault();
};
};
|
// Copyright (c) 2012 Ecma International. All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms"). Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.
/*---
es5id: 15.4.4.21-2-15
description: Array.prototype.reduce - 'length' is property of the global object
includes:
- runTestCase.js
- fnGlobalObject.js
---*/
function testcase() {
function callbackfn(prevVal, curVal, idx, obj) {
return (obj.length === 2);
}
try {
var oldLen = fnGlobalObject().length;
fnGlobalObject()[0] = 12;
fnGlobalObject()[1] = 11;
fnGlobalObject()[2] = 9;
fnGlobalObject().length = 2;
return Array.prototype.reduce.call(fnGlobalObject(), callbackfn, 1) === true;
} finally {
delete fnGlobalObject()[0];
delete fnGlobalObject()[1];
delete fnGlobalObject()[2];
fnGlobalObject().length = oldLen;
}
}
runTestCase(testcase);
|
$(function () {
var $container = $('#container');
var certificatesInfo = $container.data('certinfo');
var runDate = $container.data('rundate');
$('#created_date').html(runDate);
var sorted_certificates = Object.keys(certificatesInfo)
.sort(function( a, b ) {
return certificatesInfo[a].info.days_left - certificatesInfo[b].info.days_left;
}).map(function(sortedKey) {
return certificatesInfo[sortedKey];
});
var card_html = String()
+'<div class="col-xs-12 col-md-6 col-xl-4">'
+' <div class="card text-xs-center" style="border-color:#333;">'
+' <div class="card-header" style="overflow:hidden;">'
+' <h4 class="text-muted" style="margin-bottom:0;">{{server}}</h4>'
+' </div>'
+' <div class="card-block {{background}}">'
+' <h1 class="card-text display-4" style="margin-top:0;margin-bottom:-1rem;">{{days_left}}</h1>'
+' <p class="card-text" style="margin-bottom:.75rem;"><small>days left</small></p>'
+' </div>'
+' <div class="card-footer">'
+' <h6 class="text-muted" style="margin-bottom:.5rem;">Issued by: {{issuer}}</h6>'
+' <h6 class="text-muted" style=""><small>{{issuer_cn}}</small></h6>'
+' <h6 class="text-muted" style="margin-bottom:0;"><small>{{common_name}}</small></h6>'
+' </div>'
+' </div>'
+'</div>';
function insert_card(json) {
var card_template = Handlebars.compile(card_html),
html = card_template(json);
$('#panel').append(html);
};
sorted_certificates.forEach(function(element, index, array){
var json = {
'server': element.server,
'days_left': element.info.days_left,
'issuer': element.issuer.org,
'common_name': element.subject.common_name,
'issuer_cn': element.issuer.common_name
}
if (element.info.days_left <= 30 ){
json.background = 'card-inverse card-danger';
} else if (element.info.days_left > 30 && element.info.days_left <= 60 ) {
json.background = 'card-inverse card-warning';
} else if (element.info.days_left === "??") {
json.background = 'card-inverse card-info';
} else {
json.background = 'card-inverse card-success';
}
insert_card(json);
});
});
|
'use strict';
//Setting up route
angular.module('socketio-area').config(['$stateProvider',
function($stateProvider) {
// Socketio area state routing
$stateProvider.
state('socketio-area', {
url: '/socketio',
templateUrl: 'modules/socketio-area/views/socketio-area.client.view.html'
});
}
]); |
/**
* configuration for grunt tasks
* @module Gruntfile
*/
module.exports = function(grunt) {
/** load tasks */
require('load-grunt-tasks')(grunt);
/** config for build paths */
var config = {
dist: {
dir: 'dist/',
StoreFactory: 'dist/StoreFactory.js',
ngStoreFactory: 'dist/ngStore.js'
},
src: {
dir: 'src/'
},
tmp: {
dir: 'tmp/'
}
};
/** paths to files */
var files = {
/** src files */
Factory: [
'StoreFactory.js'
],
/** src files */
Store: [
'Store.js'
],
};
/* # # # # # # # # # # # # # # # # # # # # */
/* # # # # # # # # # # # # # # # # # # # # */
/* # # # # # # # # # # # # # # # # # # # # */
/* # # # # # # # # # # # # # # # # # # # # */
/** config for grunt tasks */
var taskConfig = {
/** concatentation tasks for building the source files */
concat: {
StoreFactory: {
options: {
// stripBanners: true
banner: '',
footer: '',
},
src: (function() {
var
cwd = config.src.dir,
queue = [].concat(files.Factory, files.Store);
return queue.map(function(path) {
return cwd + path;
});
})(),
dest: config.dist.StoreFactory,
},
ngSession: {
options: {
banner: 'angular.module("ngStore", [])\n' +
'.service("ngStore", [\n' +
'function() {\n\n',
footer: '\n\n' +
'return new StoreFactory();\n\n}' +
'\n]);'
},
src: (function() {
return [
config.dist.StoreFactory,
];
})(),
dest: config.dist.ngStoreFactory
}
},
/** uglify (javascript minification) config */
uglify: {
StoreFactory: {
options: {},
files: [
{
src: config.dist.StoreFactory,
dest: (function() {
var split = config.dist.StoreFactory.split('.');
split.pop(); // removes `js` extension
split.push('min'); // adds `min` extension
split.push('js'); // adds `js` extension
return split.join('.');
})()
}
]
},
ngStoreFactory: {
options: {},
files: [
{
src: config.dist.ngStoreFactory,
dest: (function() {
var split = config.dist.ngStoreFactory.split('.');
split.pop(); // removes `js` extension
split.push('min'); // adds `min` extension
split.push('js'); // adds `js` extension
return split.join('.');
})()
}
]
}
}
};
/* # # # # # # # # # # # # # # # # # # # # */
/* # # # # # # # # # # # # # # # # # # # # */
/* # # # # # # # # # # # # # # # # # # # # */
/* # # # # # # # # # # # # # # # # # # # # */
// register default & custom tasks
grunt.initConfig(taskConfig);
grunt.registerTask('default', [
'build'
]);
grunt.registerTask('build', [
'concat',
'uglify'
]);
}; |
/**
* Module dependencies.
*/
var express = require('express');
var path = require('path');
var api = require('./lib/api');
var seo = require('./lib/seo');
var app = module.exports = express();
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('change this value to something unique'));
app.use(express.cookieSession());
app.use(express.compress());
app.use(api);
app.use(seo);
app.use(express.static(path.join(__dirname, '../build')));
app.use(app.router);
app.get('/loaderio-995e64d5aae415e1f10d60c9391e37ac/', function(req, res, next) {
res.send('loaderio-995e64d5aae415e1f10d60c9391e37ac');
});
if ('development' === app.get('env')) {
app.use(express.errorHandler());
}
var cacheBuster = function(req, res, next){
res.header("Cache-Control", "no-cache, no-store, must-revalidate");
res.header("Pragma", "no-cache");
res.header("Expires", 0);
next();
};
// @todo isolate to api routes...
app.use(cacheBuster);
// catch all which sends all urls to index page, thus starting our app
// @note that because Express routes are registered in order, and we already defined our api routes
// this catch all will not effect prior routes.
app.use(function(req, res, next) {
app.get('*', function(req, res, next) {
//return res.ok('catch all');
res.redirect('/#!' + req.url);
});
});
|
var score = 0;
var scoreText;
var map_x = 14;
var map_y = 10;
var game = new Phaser.Game(map_x * 16, map_y * 16, Phaser.AUTO, '', { preload: preload, create: create, update: update });
function preload() {
// game.scale.maxWidth = 600;
// game.scale.maxHeight = 600;
game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
game.scale.setScreenSize();
game.load.image('cat', 'assets/cat.png', 16, 16);
game.load.image('ground', 'assets/darkfloor.png', 16, 16);
game.load.image('l_wall', 'assets/l_wall.png', 16, 16);
game.load.image('r_wall', 'assets/r_wall.png', 16, 16);
game.load.image('t_wall', 'assets/t_wall.png', 16, 16);
game.load.image('tr_wall', 'assets/tr_wall_iso.png', 16, 16);
game.load.image('tl_wall', 'assets/tl_wall_iso.png', 16, 16);
game.load.image('bl_wall', 'assets/bl_wall.png', 16, 16);
game.load.image('br_wall', 'assets/br_wall.png', 16, 16);
game.load.image('stone_door', 'assets/door_stone.png', 16, 16);
game.load.image('star', 'assets/star.png');
}
function create() {
game.physics.startSystem(Phaser.Physics.ARCADE);
// the game world
gmap = game.add.tilemap();
gmap.addTilesetImage('ground', 'ground', 16, 16, null, null, 0);
gmap.addTilesetImage('l_wall', 'l_wall', 16, 16, null, null, 1);
gmap.addTilesetImage('r_wall', 'r_wall', 16, 16, null, null, 2);
gmap.addTilesetImage('tr_wall', 'tr_wall', 16, 16, null, null, 3);
gmap.addTilesetImage('tl_wall', 'tl_wall', 16, 16, null, null, 4);
gmap.addTilesetImage('br_wall', 'br_wall', 16, 16, null, null, 5);
gmap.addTilesetImage('bl_wall', 'bl_wall', 16, 16, null, null, 6);
gmap.addTilesetImage('t_wall', 't_wall', 16, 16, null, null, 7);
gmap.addTilesetImage('stone_door', 'stone_door', 16, 16, null, null, 8);
ground_layer = gmap.create('ground_layer', map_x, map_y, 16, 16);
wall_layer = gmap.create('wall_layer', map_x, map_y, 16, 16);
for (var i=0; i<map_x; i++) {
for(var j=0; j<map_y; j++) {
if (i==0 && j==0) {
gmap.putTile(4, i, j, wall_layer);
} else if (i==map_x/2 && j==0) {
gmap.putTile(8, i, j, wall_layer);
} else if (i==map_x-1 && j == map_y-1) {
gmap.putTile(5, i, j, wall_layer);
} else if (i==0 && j == map_y-1) {
gmap.putTile(6, i, j, wall_layer);
} else if (i==map_x-1 && j == 0) {
gmap.putTile(3, i, j, wall_layer);
} else if (i==map_x-1 && j == map_y-1) {
gmap.putTile(6, i, j, wall_layer);
} else if (i==0) {
gmap.putTile(1, i, j, wall_layer);
} else if(i==map_x-1) {
gmap.putTile(2, i, j, wall_layer);
} else if(j==map_y-1) {
gmap.putTile(7, i, j, wall_layer);
} else if(j==0) {
gmap.putTile(7, i, j, wall_layer);
} else {
gmap.putTile(0, i, j, ground_layer);
}
}
}
wall_layer.resizeWorld();
game.physics.arcade.enable(wall_layer);
gmap.setCollision(wall_layer);
// the player
player = game.add.sprite(32, 32, 'cat');
game.physics.arcade.enable(player);
player.body.collideWorldBounds = true;
// gmap.setCollisionBetween(0, 100, true, wall_layer);
cursors = game.input.keyboard.createCursorKeys();
}
function update() {
game.physics.arcade.collide(player, wall_layer);
player.body.velocity.x = 0;
player.body.velocity.y = 0;
if (cursors.left.isDown) {
player.body.velocity.x = -150;
} else if (cursors.right.isDown) {
player.body.velocity.x = 150;
} else if (cursors.down.isDown) {
player.body.velocity.y = 150;
} else if (cursors.up.isDown) {
player.body.velocity.y = -150;
} else {
}
}
|
export { default } from 'ember-flexberry-gis/services/map-store';
|
var Keyboard_Space = new function(){
this.initKeyboard = function(testing){
testmode = testing;
return new Keyboard();
}
var Keyboard = function(){
for(var i = 0; i < numChains; i++)
currentSounds.push([]);
var this_obj = this;
Zip_Space.loadZip(currentSongData["filename"], function() {
this_obj.loadSounds(currentSongData["mappings"]["chain1"], currentSounds[0], 1);
this_obj.loadSounds(currentSongData["mappings"]["chain2"], currentSounds[1], 2);
this_obj.loadSounds(currentSongData["mappings"]["chain3"], currentSounds[2], 3);
this_obj.loadSounds(currentSongData["mappings"]["chain4"], currentSounds[3], 4);
this_obj.backend = BackendSpace.init();
this_obj.keyboardUI = Keyboard_UI_Space.initKeyboardUI();
console.log("New keyboard created");
})
}
// link the keyboard and the editor
Keyboard.prototype.linkEditor = function(editor){
this.editor = editor;
var mainObj = this;
setTimeout(function(){mainObj.editor.setBPM(currentSongData.bpm)},500);
}
Keyboard.prototype.getCurrentSounds = function(){
return currentSounds;
}
// loads sounds from srcArray for given chain into soundArr
Keyboard.prototype.loadSounds = function(srcArr, soundArr, chain){
for(var i = 0; i < srcArr.length; i++)
soundArr.push(null);
for(var i = 0; i < srcArr.length; i++){
if(srcArr[i] == "")
this.checkLoaded();
else
this.requestSound(i, srcArr, soundArr, chain);
}
}
// makes request for sounds
// if offline version, gets from local files
// if online version, gets from public folder
Keyboard.prototype.requestSound = function(i, srcArr, soundArr, chain){
var thisObj = this;
soundArr[i] = new Howl({
// for online version
urls: [Zip_Space.dataArray['sounds/chain'+chain+'/'+srcArr[i]+'.mp3']],
// old
// urls: [currentSongData["soundUrls"]["chain"+chain][srcArr[i]].replace("www.dropbox.com","dl.dropboxusercontent.com").replace("?dl=0","")],
// for offline version
// urls: ["audio/chain"+chain+"/"+srcArr[i]+".mp3"],
onload: function(){
thisObj.checkLoaded();
},
onloaderror: function(id, error){
console.log('error: '+id)
console.log(error);
console.log('sounds/chain'+chain+'/'+srcArr[i]+'.mp3');
$("#error_msg").html("There was an error. Please try clearing your browser's cache and reload the page.");
}
});
}
// checks if all of the sounds have loaded
// if they have, load the keyboard
Keyboard.prototype.checkLoaded = function(){
numSoundsLoaded++;
$(".soundPack").html("Loading sounds ("+numSoundsLoaded+"/"+(4*12*numChains)+")");
if(numSoundsLoaded == 4*12*numChains){
loadingSongs = false;
this.keyboardUI.loadKeyboard(this, currentSongData, currentSoundPack);
}
}
Keyboard.prototype.getKeyInd = function(kc){
var keyInd = keyPairs.indexOf(kc);
if(keyInd == -1)
keyInd = backupPairs.indexOf(kc);
return keyInd;
}
Keyboard.prototype.switchSoundPackCheck = function(kc){
// up
if(kc == 39){
this.switchSoundPack(3);
return true;
}
// left
else if(kc == 37){
this.switchSoundPack(0);
return true;
}
// down
else if(kc == 38){
this.switchSoundPack(1);
return true;
}
// right
else if(kc == 40){
this.switchSoundPack(2);
return true;
}
}
// switch sound pack and update pressures
Keyboard.prototype.switchSoundPack = function(sp){
// release all keys
for(var i = 0; i < 4; i++)
for(var j = 0; j < 12; j++)
if($(".button-"+(i*12+j)+"").attr("released") == "false")
this.releaseKey(keyPairs[i*12+j]);
// set the new soundpack
currentSoundPack = sp;
$(".sound_pack_button").css("background-color","white");
$(".sound_pack_button_"+(currentSoundPack+1)).css("background-color","rgb(255,160,0)");
$(".soundPack").html("Sound Pack: "+(currentSoundPack+1));
// set pressures for buttons in new sound pack
for(var i = 0; i < 4; i++){
for(var j = 0; j < 12; j++){
var press = false;
if(currentSongData["holdToPlay"]["chain"+(currentSoundPack+1)].indexOf((i*12+j)) != -1)
press = true;
$('.button-'+(i*12+j)+'').attr("pressure", ""+press+"");
// holdToPlay coloring, turned off for now
//$('.button-'+(i*12+j)+'').css("background-color", $('.button-'+(i*12+j)+'').attr("pressure") == "true" ? "lightgray" : "white");
}
}
}
// key released
// stop playing sound if holdToPlay
Keyboard.prototype.releaseKey = function(kc){
var keyInd = this.getKeyInd(kc);
if(currentSounds[currentSoundPack][keyInd] != null){
this.midiKeyUp(kc);
// send key code to MIDI editor
this.editor.recordKeyUp(kc);
}
}
Keyboard.prototype.midiKeyUp = function(kc){
if(this.switchSoundPackCheck(kc)){
// do nothing
}
else{
var kcInd = this.getKeyInd(kc);
if(currentSounds[currentSoundPack][kcInd] != null){
if($(".button-"+(kcInd)+"").attr("pressure") == "true")
currentSounds[currentSoundPack][kcInd].stop();
$(".button-"+(kcInd)+"").attr("released","true");
// holdToPlay coloring, turned off for now
// Removes Style Attribute to clean up HTML
$(".button-"+(kcInd)+"").removeAttr("style");
if($(".button-"+(kcInd)+"").hasClass("pressed") == true)
$(".button-"+(kcInd)+"").removeClass("pressed");
//$(".button-"+(kcInd)+"").css("background-color", $(".button-"+(kcInd)+"").attr("pressure") == "true" ? "lightgray" : "white");
}
}
}
// play the key by finding the mapping,
// stopping all sounds in key's linkedArea
// and then playing sound
Keyboard.prototype.playKey = function(kc){
var keyInd = this.getKeyInd(kc);
if(currentSounds[currentSoundPack][keyInd] != null){
this.midiKeyDown(kc);
// send key code to midi editor
this.editor.recordKeyDown(kc);
}
}
Keyboard.prototype.midiKeyDown = function(kc){
if(this.switchSoundPackCheck(kc)){
// do nothing
}
else{
var kcInd = this.getKeyInd(kc);
if(currentSounds[currentSoundPack][kcInd] != null){
currentSounds[currentSoundPack][kcInd].stop();
currentSounds[currentSoundPack][kcInd].play();
// go through all linked Areas in current chain
currentSongData["linkedAreas"]["chain"+(currentSoundPack+1)].forEach(function(el, ind, arr){
// for ever linked area array
for(var j = 0; j < el.length; j++){
// if key code is in linked area array
if(kcInd == el[j]){
// stop all other sounds in linked area array
for(var k = 0; k < el.length; k++){
if(k != j)
currentSounds[currentSoundPack][el[k]].stop();
}
break;
}
}
});
// set button color and attribute
$(".button-"+(kcInd)+"").addClass("pressed");
$(".button-"+(kcInd)+"").attr("released","false");
//$(".button-"+(kcInd)+"").css("background-color","rgb(255,160,0)");
}
}
}
// shows and formats all of the UI elements
Keyboard.prototype.initUI = function(){
// create new editor and append it to the body element
if(testmode)
BasicMIDI.init("#editor_container_div", this, 170);
else
MIDI_Editor.init("#editor_container_div", this, 170);
// info and links buttons
// $(".click_button").css("display", "inline-block");
for(var s in songDatas)
$("#songs_container").append("<div class='song_selection' songInd='"+s+"'>"+songDatas[s].song_name+"</div>");
$("[songInd='"+currentSongInd+"']").css("background-color","rgb(220,220,220)");
var mainObj = this;
$(".song_selection").click(function() {
var tempS = parseInt($(this).attr("songInd"));
if(tempS != currentSongInd && !loadingSongs){
loadingSongs = true;
currentSongInd = tempS
currentSongData = songDatas[currentSongInd];
$(".song_selection").css("background-color","white");
$("[songInd='"+currentSongInd+"']").css("background-color","rgb(220,220,220)");
$(".button-row").remove();
for(var i = 0; i < currentSounds.length; i++){
for(var k = 0; k < currentSounds[i].length; k++){
if(currentSounds[i][k] != null)
currentSounds[i][k].unload();
}
}
currentSounds = [];
for(var i = 0; i < numChains; i++)
currentSounds.push([]);
mainObj.editor.notesLoaded([],-1);
mainObj.editor.setBPM(currentSongData.bpm)
numSoundsLoaded = 0;
Zip_Space.loadZip(currentSongData["filename"], function() {
mainObj.loadSounds(currentSongData["mappings"]["chain1"], currentSounds[0], 1);
mainObj.loadSounds(currentSongData["mappings"]["chain2"], currentSounds[1], 2);
mainObj.loadSounds(currentSongData["mappings"]["chain3"], currentSounds[2], 3);
mainObj.loadSounds(currentSongData["mappings"]["chain4"], currentSounds[3], 4);
})
}
});
}
// send request to server to save the notes to the corresponding projectId (pid)
Keyboard.prototype.saveNotes = function(notes, pid){
var saveNote = [];
for(var n in notes)
saveNote.push({"note":notes[n].note, "beat":notes[n].beat, "length":notes[n].length});
//console.log(saveNote);
this.backend.saveSong(JSON.stringify(saveNote), pid, this.editor, currentSongData.song_number);
}
// ask the user for the project they would like to load and then load that project from the server
// send back a notes array of the loaded project with note,beat,and length and the project id
Keyboard.prototype.loadNotes = function(){
this.backend.loadSongs(this.editor, currentSongData.song_number);
}
// current soundpack (0-3)
var currentSoundPack = 0;
// number of sounds loaded
var numSoundsLoaded = 0;
// howl objects for current song
var currentSounds = [];
// reference to current song data
var songDatas = [equinoxData, animalsData, electroData, ghetData, kyotoData, aeroData];
var currentSongInd = 0;
var currentSongData = equinoxData;
// number of chains
var numChains = 4;
var testmode = false;
var loadingSongs = true;
}
// Global Variables
// ascii key mappings to array index
var keyPairs = [49,50,51,52,53,54,55,56,57,48,189,187,
81,87,69,82,84,89,85,73,79,80,219,221,
65,83,68,70,71,72,74,75,76,186,222,13,
90,88,67,86,66,78,77,188,190,191,16,-1];
// alternate keys for firefox
var backupPairs = [49,50,51,52,53,54,55,56,57,48,173,61,
81,87,69,82,84,89,85,73,79,80,219,221,
65,83,68,70,71,72,74,75,76,59,222,13,
90,88,67,86,66,78,77,188,190,191,16,-1];
// letter to show in each button
var letterPairs = ["1","2","3","4","5","6","7","8","9","0","-","=",
"Q","W","E","R","T","Y","U","I","O","P","[","]",
"A","S","D","F","G","H","J","K","L",";","'","\\n",
"Z","X","C","V","B","N","M",",",".","/","\\s","NA"]; |
angular.module('booksAR')
.directive('userNavbar', function(){
return{
restrict: 'E',
templateUrl: './app/components/directives/user/user-navbar.html'
};
})
.directive('userBooksTable', function(){
return{
restrict: 'E',
templateUrl: './app/components/directives/user/user-books-table.html'
};
})
.directive('userTable', function(){
return{
restrict: 'E',
templateUrl: './app/components/directives/user/user-table.html'
};
})
.directive('userProfileInfo', function(){
return{
restrict: 'E',
templateUrl: './app/components/directives/user/user-profile-info.html'
};
})
.directive('ngConfirmClick', [
function(){
return {
link: function (scope, element, attr) {
var msg = attr.ngConfirmClick || "Are you sure?";
var clickAction = attr.confirmedClick;
element.bind('click',function (event) {
if ( window.confirm(msg) ) {
scope.$eval(clickAction)
}
});
}
};
}]); |
const test = require('tap').test
const GF = require('core/galois-field')
test('Galois Field', function (t) {
t.throw(function () { GF.log(0) }, 'Should throw for log(n) with n < 1')
for (let i = 1; i < 255; i++) {
t.equal(GF.log(GF.exp(i)), i, 'log and exp should be one the inverse of the other')
t.equal(GF.exp(GF.log(i)), i, 'exp and log should be one the inverse of the other')
}
t.equal(GF.mul(0, 1), 0, 'Should return 0 if first param is 0')
t.equal(GF.mul(1, 0), 0, 'Should return 0 if second param is 0')
t.equal(GF.mul(0, 0), 0, 'Should return 0 if both params are 0')
for (let j = 1; j < 255; j++) {
t.equal(GF.mul(j, 255 - j), GF.mul(255 - j, j), 'Multiplication should be commutative')
}
t.end()
})
|
'use strict';
// Test dependencies are required and exposed in common/bootstrap.js
require('../../common/bootstrap');
process.on('uncaughtException', function(err) {
console.error(err.stack);
});
var codeContents = 'console.log("testing deploy");';
var reference = new Buffer(codeContents);
var lists = deployment.js.lists;
var listRuleLength = lists.includes.length + lists.ignores.length + lists.blacklist.length;
var sandbox = sinon.sandbox.create();
var FIXTURE_PATH = path.join(__dirname, '/../../../test/unit/fixtures');
exports['Deployment: JavaScript'] = {
setUp(done) {
this.deploy = sandbox.spy(Tessel.prototype, 'deploy');
this.appStop = sandbox.spy(commands.app, 'stop');
this.appStart = sandbox.spy(commands.app, 'start');
this.deleteFolder = sandbox.spy(commands, 'deleteFolder');
this.createFolder = sandbox.spy(commands, 'createFolder');
this.untarStdin = sandbox.spy(commands, 'untarStdin');
this.execute = sandbox.spy(commands.js, 'execute');
this.openStdinToFile = sandbox.spy(commands, 'openStdinToFile');
this.chmod = sandbox.spy(commands, 'chmod');
this.push = sandbox.spy(deploy, 'push');
this.createShellScript = sandbox.spy(deploy, 'createShellScript');
this.injectBinaryModules = sandbox.stub(deployment.js, 'injectBinaryModules').callsFake(() => Promise.resolve());
this.resolveBinaryModules = sandbox.stub(deployment.js, 'resolveBinaryModules').callsFake(() => Promise.resolve());
this.tarBundle = sandbox.stub(deployment.js, 'tarBundle').callsFake(() => Promise.resolve(reference));
this.warn = sandbox.stub(log, 'warn');
this.info = sandbox.stub(log, 'info');
this.tessel = TesselSimulator();
this.end = sandbox.spy(this.tessel._rps.stdin, 'end');
this.fetchCurrentBuildInfo = sandbox.stub(this.tessel, 'fetchCurrentBuildInfo').returns(Promise.resolve('40b2b46a62a34b5a26170c75f7e717cea673d1eb'));
this.fetchNodeProcessVersions = sandbox.stub(this.tessel, 'fetchNodeProcessVersions').returns(Promise.resolve(processVersions));
this.requestBuildList = sandbox.stub(updates, 'requestBuildList').returns(Promise.resolve(tesselBuilds));
this.pWrite = sandbox.stub(Preferences, 'write').returns(Promise.resolve());
this.exists = sandbox.stub(fs, 'exists').callsFake((fpath, callback) => callback(true));
this.spinnerStart = sandbox.stub(log.spinner, 'start');
this.spinnerStop = sandbox.stub(log.spinner, 'stop');
deleteTemporaryDeployCode()
.then(done);
},
tearDown(done) {
this.tessel.mockClose();
sandbox.restore();
deleteTemporaryDeployCode()
.then(done)
.catch(function(err) {
throw err;
});
},
bundling(test) {
test.expect(1);
this.tarBundle.restore();
createTemporaryDeployCode().then(() => {
var tb = deployment.js.tarBundle({
target: DEPLOY_DIR_JS
});
tb.then(bundle => {
/*
$ t2 run app.js
INFO Looking for your Tessel...
INFO Connected to arnold over LAN
INFO Writing app.js to RAM on arnold (2.048 kB)...
INFO Deployed.
INFO Running app.js...
testing deploy
INFO Stopping script...
*/
test.equal(bundle.length, 2048);
test.done();
})
.catch(error => {
test.ok(false, error.toString());
test.done();
});
});
},
createShellScriptDefaultEntryPoint(test) {
test.expect(1);
var shellScript = `#!/bin/sh
exec node --harmony /app/remote-script/index.js --key=value`;
var opts = {
lang: deployment.js,
resolvedEntryPoint: 'index.js',
binopts: ['--harmony'],
subargs: ['--key=value'],
};
this.end.restore();
this.end = sandbox.stub(this.tessel._rps.stdin, 'end').callsFake((buffer) => {
test.equal(buffer.toString(), shellScript);
test.done();
});
this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => {
return callback(null, this.tessel._rps);
});
deploy.createShellScript(this.tessel, opts);
},
createShellScriptDefaultEntryPointNoSubargs(test) {
test.expect(1);
var shellScript = `#!/bin/sh
exec node --harmony /app/remote-script/index.js`;
var opts = {
lang: deployment.js,
resolvedEntryPoint: 'index.js',
binopts: ['--harmony'],
subargs: [],
};
this.end.restore();
this.end = sandbox.stub(this.tessel._rps.stdin, 'end').callsFake((buffer) => {
test.equal(buffer.toString(), shellScript);
test.done();
});
this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => {
return callback(null, this.tessel._rps);
});
deploy.createShellScript(this.tessel, opts);
},
createShellScriptDefaultEntryPointNoExtraargs(test) {
test.expect(1);
var shellScript = `#!/bin/sh
exec node /app/remote-script/index.js`;
var opts = {
lang: deployment.js,
resolvedEntryPoint: 'index.js',
binopts: [],
subargs: [],
};
this.end.restore();
this.end = sandbox.stub(this.tessel._rps.stdin, 'end').callsFake((buffer) => {
test.equal(buffer.toString(), shellScript);
test.done();
});
this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => {
return callback(null, this.tessel._rps);
});
deploy.createShellScript(this.tessel, opts);
},
createShellScriptSendsCorrectEntryPoint(test) {
test.expect(1);
var shellScript = `#!/bin/sh
exec node /app/remote-script/index.js --key=value`;
var opts = {
lang: deployment.js,
resolvedEntryPoint: 'index.js',
binopts: [],
subargs: ['--key=value'],
};
this.end.restore();
this.end = sandbox.stub(this.tessel._rps.stdin, 'end').callsFake((buffer) => {
test.equal(buffer.toString(), shellScript);
test.done();
});
this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => {
return callback(null, this.tessel._rps);
});
deploy.createShellScript(this.tessel, opts);
},
processCompletionOrder(test) {
// Array of processes we've started but haven't completed yet
var processesAwaitingCompletion = [];
this.tessel._rps.on('control', (data) => {
// Push new commands into the queue
processesAwaitingCompletion.push(data);
});
// Create the temporary folder with example code
createTemporaryDeployCode()
.then(() => {
var closeAdvance = (event) => {
// If we get an event listener for the close event of a process
if (event === 'close') {
// Wait some time before actually closing it
setTimeout(() => {
// We should only have one process waiting for completion
test.equal(processesAwaitingCompletion.length, 1);
// Pop that process off
processesAwaitingCompletion.shift();
// Emit the close event to keep it going
this.tessel._rps.emit('close');
}, 200);
}
};
// When we get a listener that the Tessel process needs to close before advancing
this.tessel._rps.on('newListener', closeAdvance);
// Actually deploy the script
this.tessel.deploy({
entryPoint: path.relative(process.cwd(), DEPLOY_FILE_JS),
compress: true,
push: false,
single: false
})
// If it finishes, it was successful
.then(() => {
this.tessel._rps.removeListener('newListener', closeAdvance);
test.done();
})
// If not, there was an issue
.catch(function(err) {
test.equal(err, undefined, 'We hit a catch statement that we should not have.');
});
});
}
};
exports['deployment.js.compress with uglify.es.minify()'] = {
setUp(done) {
this.minify = sandbox.spy(uglify.es, 'minify');
this.spinnerStart = sandbox.stub(log.spinner, 'start');
this.spinnerStop = sandbox.stub(log.spinner, 'stop');
done();
},
tearDown(done) {
sandbox.restore();
done();
},
minifySuccess(test) {
test.expect(1);
deployment.js.compress('es', 'let f = 1');
test.equal(this.minify.callCount, 1);
test.done();
},
minifyFailureReturnsOriginalSource(test) {
test.expect(2);
const result = deployment.js.compress('es', '#$%^');
// Assert that we tried to minify
test.equal(this.minify.callCount, 1);
// Assert that compress just gave back
// the source as-is, even though the
// parser failed.
test.equal(result, '#$%^');
test.done();
},
ourOptionsParse(test) {
test.expect(2);
const ourExplicitSettings = {
toplevel: true,
warnings: false,
};
const ourExplicitSettingsKeys = Object.keys(ourExplicitSettings);
try {
// Force the acorn parse step of the
// compress operation to fail. This
// will ensure that that the uglify
// attempt is made.
deployment.js.compress('es', '#$%^');
} catch (error) {
// there is nothing we can about this.
}
const optionsSeen = this.minify.lastCall.args[1];
ourExplicitSettingsKeys.forEach(key => {
test.equal(optionsSeen[key], ourExplicitSettings[key]);
});
test.done();
},
noOptionsCompress(test) {
test.expect(23);
const optionsCompress = {
// ------
booleans: true,
cascade: true,
conditionals: true,
comparisons: true,
ecma: 6,
evaluate: true,
hoist_funs: true,
hoist_vars: true,
if_return: true,
join_vars: true,
loops: true,
passes: 3,
properties: true,
sequences: true,
unsafe: true,
// ------
dead_code: true,
unsafe_math: true,
keep_infinity: true,
// ------
arrows: false,
keep_fargs: false,
keep_fnames: false,
warnings: false,
drop_console: false,
};
const optionsCompressKeys = Object.keys(optionsCompress);
deployment.js.compress('es', 'var a = 1;', {});
const optionsSeen = this.minify.lastCall.args[1].compress;
optionsCompressKeys.forEach(key => {
test.equal(optionsSeen[key], optionsCompress[key]);
});
test.done();
},
ourOptionsCompress(test) {
test.expect(23);
const ourExplicitSettings = {
// ------
booleans: true,
cascade: true,
conditionals: true,
comparisons: true,
ecma: 6,
evaluate: true,
hoist_funs: true,
hoist_vars: true,
if_return: true,
join_vars: true,
loops: true,
passes: 3,
properties: true,
sequences: true,
unsafe: true,
// ------
dead_code: true,
unsafe_math: true,
keep_infinity: true,
// ------
arrows: false,
keep_fargs: false,
keep_fnames: false,
warnings: false,
drop_console: false,
};
const ourExplicitSettingsKeys = Object.keys(ourExplicitSettings);
deployment.js.compress('es', 'var a = 1;');
const optionsSeen = this.minify.lastCall.args[1].compress;
ourExplicitSettingsKeys.forEach(key => {
test.equal(optionsSeen[key], ourExplicitSettings[key]);
});
test.done();
},
theirOptionsCompress(test) {
test.expect(20);
var theirExplicitSettings = {
// ------
booleans: false,
cascade: false,
conditionals: false,
comparisons: false,
evaluate: false,
hoist_funs: false,
hoist_vars: false,
if_return: false,
join_vars: false,
loops: false,
properties: false,
sequences: false,
unsafe: false,
// ------
dead_code: false,
unsafe_math: false,
keep_infinity: false,
// ------
keep_fargs: true,
keep_fnames: true,
warnings: true,
drop_console: true,
};
var theirExplicitSettingsKeys = Object.keys(theirExplicitSettings);
deployment.js.compress('es', 'var a = 1;', {
compress: theirExplicitSettings
});
const optionsSeen = this.minify.lastCall.args[1].compress;
theirExplicitSettingsKeys.forEach(key => {
test.equal(optionsSeen[key], theirExplicitSettings[key]);
});
test.done();
},
minifyFromBuffer(test) {
test.expect(1);
test.equal(deployment.js.compress('es', new Buffer(codeContents)), codeContents);
test.done();
},
minifyFromString(test) {
test.expect(1);
test.equal(deployment.js.compress('es', codeContents), codeContents);
test.done();
},
minifyWithBareReturns(test) {
test.expect(1);
deployment.js.compress('es', 'return;');
test.equal(this.minify.lastCall.args[1].parse.bare_returns, true);
test.done();
},
avoidCompleteFailure(test) {
test.expect(1);
this.minify.restore();
this.minify = sandbox.stub(uglify.js, 'minify').callsFake(() => {
return {
error: new SyntaxError('whatever')
};
});
test.equal(deployment.js.compress('es', 'return;'), 'return;');
test.done();
},
};
exports['deployment.js.compress with uglify.js.minify()'] = {
setUp(done) {
this.minify = sandbox.spy(uglify.js, 'minify');
this.spinnerStart = sandbox.stub(log.spinner, 'start');
this.spinnerStop = sandbox.stub(log.spinner, 'stop');
done();
},
tearDown(done) {
sandbox.restore();
done();
},
minifySuccess(test) {
test.expect(1);
deployment.js.compress('js', 'let f = 1');
test.equal(this.minify.callCount, 1);
test.done();
},
minifyFailureReturnsOriginalSource(test) {
test.expect(2);
const result = deployment.js.compress('js', '#$%^');
// Assert that we tried to minify
test.equal(this.minify.callCount, 1);
// Assert that compress just gave back
// the source as-is, even though the
// parser failed.
test.equal(result, '#$%^');
test.done();
},
ourOptionsParse(test) {
test.expect(2);
const ourExplicitSettings = {
toplevel: true,
warnings: false,
};
const ourExplicitSettingsKeys = Object.keys(ourExplicitSettings);
try {
// Force the acorn parse step of the
// compress operation to fail. This
// will ensure that that the uglify
// attempt is made.
deployment.js.compress('js', '#$%^');
} catch (error) {
// there is nothing we can about this.
}
const optionsSeen = this.minify.lastCall.args[1];
ourExplicitSettingsKeys.forEach(key => {
test.equal(optionsSeen[key], ourExplicitSettings[key]);
});
test.done();
},
noOptionsCompress(test) {
test.expect(15);
const optionsCompress = {
// ------
booleans: true,
cascade: true,
conditionals: true,
comparisons: true,
hoist_funs: true,
if_return: true,
join_vars: true,
loops: true,
passes: 2,
properties: true,
sequences: true,
// ------ explicitly false
keep_fargs: false,
keep_fnames: false,
warnings: false,
drop_console: false,
};
const optionsCompressKeys = Object.keys(optionsCompress);
deployment.js.compress('js', 'var a = 1;', {});
const optionsSeen = this.minify.lastCall.args[1].compress;
optionsCompressKeys.forEach(key => {
test.equal(optionsSeen[key], optionsCompress[key]);
});
test.done();
},
ourOptionsCompress(test) {
test.expect(15);
const ourExplicitSettings = {
// ------
booleans: true,
cascade: true,
conditionals: true,
comparisons: true,
hoist_funs: true,
if_return: true,
join_vars: true,
loops: true,
passes: 2,
properties: true,
sequences: true,
// ------ explicitly false
keep_fargs: false,
keep_fnames: false,
warnings: false,
drop_console: false,
};
const ourExplicitSettingsKeys = Object.keys(ourExplicitSettings);
deployment.js.compress('js', 'var a = 1;');
const optionsSeen = this.minify.lastCall.args[1].compress;
ourExplicitSettingsKeys.forEach(key => {
test.equal(optionsSeen[key], ourExplicitSettings[key]);
});
test.done();
},
theirOptionsCompress(test) {
test.expect(15);
var theirExplicitSettings = {
// ------
booleans: true,
cascade: true,
conditionals: true,
comparisons: true,
hoist_funs: true,
if_return: true,
join_vars: true,
loops: true,
passes: 2,
properties: true,
sequences: true,
// ------ explicitly false
keep_fargs: false,
keep_fnames: false,
warnings: false,
drop_console: false,
};
var theirExplicitSettingsKeys = Object.keys(theirExplicitSettings);
deployment.js.compress('js', 'var a = 1;', {
compress: theirExplicitSettings
});
const optionsSeen = this.minify.lastCall.args[1].compress;
theirExplicitSettingsKeys.forEach(key => {
test.equal(optionsSeen[key], theirExplicitSettings[key]);
});
test.done();
},
minifyFromBuffer(test) {
test.expect(1);
test.equal(deployment.js.compress('js', new Buffer(codeContents)), codeContents);
test.done();
},
minifyFromString(test) {
test.expect(1);
test.equal(deployment.js.compress('js', codeContents), codeContents);
test.done();
},
minifyWithBareReturns(test) {
test.expect(1);
deployment.js.compress('js', 'return;');
test.equal(this.minify.lastCall.args[1].parse.bare_returns, true);
test.done();
},
avoidCompleteFailure(test) {
test.expect(1);
this.minify.restore();
this.minify = sandbox.stub(uglify.js, 'minify').callsFake(() => {
return {
error: new SyntaxError('whatever')
};
});
const result = deployment.js.compress('js', 'return;');
test.equal(result, 'return;');
test.done();
},
theReasonForUsingBothVersionsOfUglify(test) {
test.expect(2);
this.minify.restore();
this.es = sandbox.spy(uglify.es, 'minify');
this.js = sandbox.spy(uglify.js, 'minify');
const code = tags.stripIndents `
var Class = function() {};
Class.prototype.method = function() {};
module.exports = Class;
`;
deployment.js.compress('es', code);
deployment.js.compress('js', code);
test.equal(this.es.callCount, 1);
test.equal(this.js.callCount, 1);
test.done();
},
};
exports['deployment.js.tarBundle'] = {
setUp(done) {
this.copySync = sandbox.spy(fs, 'copySync');
this.outputFileSync = sandbox.spy(fs, 'outputFileSync');
this.writeFileSync = sandbox.spy(fs, 'writeFileSync');
this.remove = sandbox.spy(fs, 'remove');
this.readdirSync = sandbox.spy(fs, 'readdirSync');
this.globSync = sandbox.spy(glob, 'sync');
this.collect = sandbox.spy(Project.prototype, 'collect');
this.exclude = sandbox.spy(Project.prototype, 'exclude');
this.mkdirSync = sandbox.spy(fsTemp, 'mkdirSync');
this.addIgnoreRules = sandbox.spy(Ignore.prototype, 'addIgnoreRules');
this.project = sandbox.spy(deployment.js, 'project');
this.compress = sandbox.spy(deployment.js, 'compress');
this.warn = sandbox.stub(log, 'warn');
this.info = sandbox.stub(log, 'info');
this.spinnerStart = sandbox.stub(log.spinner, 'start');
this.spinnerStop = sandbox.stub(log.spinner, 'stop');
done();
},
tearDown(done) {
sandbox.restore();
done();
},
actionsGlobRules(test) {
test.expect(1);
const target = 'test/unit/fixtures/ignore';
const rules = glob.rules(target, '.tesselignore');
test.deepEqual(
rules.map(path.normalize), [
// Found in "test/unit/fixtures/ignore/.tesselignore"
'a/**/*.*',
'mock-foo.js',
// Found in "test/unit/fixtures/ignore/nested/.tesselignore"
'nested/b/**/*.*',
'nested/file.js'
].map(path.normalize)
);
test.done();
},
actionsGlobFiles(test) {
test.expect(1);
const target = 'test/unit/fixtures/ignore';
const rules = glob.rules(target, '.tesselignore');
const files = glob.files(target, rules);
test.deepEqual(files, ['mock-foo.js']);
test.done();
},
actionsGlobFilesNested(test) {
test.expect(1);
const target = 'test/unit/fixtures/ignore';
const files = glob.files(target, ['**/.tesselignore']);
test.deepEqual(files, [
'.tesselignore',
'nested/.tesselignore'
]);
test.done();
},
actionsGlobFilesNonNested(test) {
test.expect(1);
const target = 'test/unit/fixtures/ignore';
const files = glob.files(target, ['.tesselignore']);
test.deepEqual(files, ['.tesselignore']);
test.done();
},
noOptionsTargetFallbackToCWD(test) {
test.expect(2);
const target = path.normalize('test/unit/fixtures/project');
sandbox.stub(process, 'cwd').returns(target);
sandbox.spy(path, 'relative');
/*
project
├── .tesselignore
├── index.js
├── mock-foo.js
├── nested
│ └── another.js
├── node_modules
│ └── foo
│ ├── .tesselignore
│ ├── index.js
│ └── package.json
├── other.js
└── package.json
3 directories, 9 files
*/
deployment.js.tarBundle({
compress: true,
full: true,
}).then(() => {
test.equal(path.relative.firstCall.args[0], path.normalize('test/unit/fixtures/project'));
test.equal(path.relative.firstCall.args[1], path.normalize('test/unit/fixtures/project'));
test.done();
});
},
full(test) {
test.expect(8);
const target = 'test/unit/fixtures/project';
/*
project
├── .tesselignore
├── index.js
├── mock-foo.js
├── nested
│ └── another.js
├── node_modules
│ └── foo
│ ├── .tesselignore
│ ├── index.js
│ └── package.json
├── other.js
└── package.json
3 directories, 9 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
compress: true,
full: true,
}).then(bundle => {
// One call for .tesselinclude
// One call for the single rule found within
// Three calls for the deploy lists
// * 2 (We need all ignore rules ahead of time for ignoring binaries)
test.equal(this.globSync.callCount, 5 + listRuleLength);
// addIgnoreRules might be called many times, but we only
// care about tracking the call that's explicitly made by
// tessel's deploy operation
test.deepEqual(this.addIgnoreRules.getCall(0).args[0], [
'**/.tesselignore',
'**/.tesselinclude',
]);
// These things don't happen in the --full path
test.equal(this.project.callCount, 0);
test.equal(this.exclude.callCount, 0);
test.equal(this.compress.callCount, 0);
test.equal(this.writeFileSync.callCount, 0);
test.equal(this.remove.callCount, 0);
// End
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
test.deepEqual(entries, [
'index.js',
'nested/another.js',
'node_modules/foo/index.js',
'package.json',
]);
test.done();
});
});
},
fullHitsErrorFromFstreamIgnore(test) {
test.expect(1);
// Need to stub function in _actual_ fs (but we use fs-extra)
const fs = require('fs');
sandbox.stub(fs, 'readFile').callsFake((file, callback) => {
callback('foo');
});
const target = 'test/unit/fixtures/project';
deployment.js.tarBundle({
target: path.normalize(target),
compress: true,
full: true,
})
.then(() => {
test.ok(false, 'tarBundle should not resolve');
test.done();
})
.catch(error => {
test.equal(error.toString(), 'foo');
test.done();
});
},
slim(test) {
test.expect(9);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project';
/*
project
├── .tesselignore
├── index.js
├── mock-foo.js
├── nested
│ └── another.js
├── node_modules
│ └── foo
│ ├── .tesselignore
│ ├── index.js
│ └── package.json
├── other.js
└── package.json
3 directories, 9 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then(bundle => {
// These things happen in the --slim path
test.equal(this.project.callCount, 1);
test.equal(this.compress.callCount, 2);
test.equal(this.mkdirSync.callCount, 1);
test.equal(this.outputFileSync.callCount, 3);
// End
/*
$ find . -type f -name .tesselignore -exec cat {} \+
mock-foo.js
other.js
package.json
*/
test.equal(this.exclude.callCount, 1);
test.deepEqual(this.exclude.lastCall.args[0], [
'mock-foo.js',
'test/unit/fixtures/project/mock-foo.js',
'other.js',
'test/unit/fixtures/project/other.js',
'node_modules/foo/package.json',
'test/unit/fixtures/project/node_modules/foo/package.json'
].map(path.normalize));
const minified = this.compress.lastCall.returnValue;
test.equal(this.compress.callCount, 2);
test.equal(minified.indexOf('!!mock-foo!!') === -1, true);
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
test.deepEqual(entries, [
'index.js',
'node_modules/foo/index.js',
'package.json'
]);
test.done();
});
});
},
slimHitsErrorFromFstreamReader(test) {
test.expect(1);
const pipe = fstream.Reader.prototype.pipe;
// Need to stub function in _actual_ fs (but we use fs-extra)
this.readerPipe = sandbox.stub(fstream.Reader.prototype, 'pipe').callsFake(function() {
this.emit('error', new Error('foo'));
return pipe.apply(this, arguments);
});
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project';
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
})
.then(() => {
test.ok(false, 'tarBundle should not resolve');
test.done();
})
.catch(error => {
test.equal(error.toString(), 'Error: foo');
test.done();
});
},
slimHitsErrorInfsRemove(test) {
test.expect(1);
this.remove.restore();
this.remove = sandbox.stub(fs, 'remove').callsFake((temp, handler) => {
handler(new Error('foo'));
});
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project';
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
})
.then(() => {
this.remove.reset();
test.ok(false, 'tarBundle should not resolve');
test.done();
})
.catch(error => {
test.equal(error.toString(), 'Error: foo');
test.done();
});
},
slimHitsErrorFromCompress(test) {
test.expect(1);
this.compress.restore();
this.compress = sandbox.stub(deployment.js, 'compress').callsFake(() => {
throw new Error('foo');
});
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project';
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
})
.then(() => {
test.ok(false, 'tarBundle should not resolve');
test.done();
})
.catch(error => {
test.equal(error.toString(), 'Error: foo');
test.done();
});
},
slimHitsErrorFromProjectCollect(test) {
test.expect(1);
this.collect.restore();
this.collect = sandbox.stub(Project.prototype, 'collect').callsFake((handler) => {
handler(new Error('foo'));
});
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project';
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
})
.then(() => {
test.ok(false, 'tarBundle should not resolve');
test.done();
})
.catch(error => {
test.equal(error.toString(), 'Error: foo');
test.done();
});
},
slimHitsErrorFromProject(test) {
test.expect(1);
this.collect.restore();
this.collect = sandbox.stub(Project.prototype, 'collect').callsFake(function() {
this.emit('error', new Error('foo'));
});
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project';
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
})
.then(() => {
test.ok(false, 'tarBundle should not resolve');
test.done();
})
.catch(error => {
test.equal(error.toString(), 'Error: foo');
test.done();
});
},
compressionProducesNoErrors(test) {
test.expect(1);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/syntax-error';
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then(bundle => {
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
test.deepEqual(entries, [
'arrow.js',
'index.js',
'package.json',
]);
test.done();
});
}).catch(() => {
test.ok(false, 'Compression should not produce errors');
test.done();
});
},
compressionIsSkipped(test) {
test.expect(2);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/syntax-error';
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: false,
slim: true,
}).then(bundle => {
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
// compression mechanism is never called when --compress=false
test.equal(this.compress.callCount, 0);
test.deepEqual(entries, [
'arrow.js',
'index.js',
'package.json',
]);
test.done();
});
}).catch(() => {
test.ok(false, 'Compression should not produce errors');
test.done();
});
},
slimTesselInit(test) {
test.expect(5);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/init';
/*
init
├── index.js
└── package.json
0 directories, 2 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then(bundle => {
test.equal(this.project.callCount, 1);
test.equal(this.compress.callCount, 1);
test.equal(this.mkdirSync.callCount, 1);
const minified = this.compress.lastCall.returnValue;
test.equal(minified, 'const e=require("tessel"),{2:o,3:l}=e.led;o.on(),setInterval(()=>{o.toggle(),l.toggle()},100),console.log("I\'m blinking! (Press CTRL + C to stop)");');
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
test.deepEqual(entries, ['index.js', 'package.json']);
test.done();
});
});
},
slimSingle(test) {
test.expect(4);
const target = 'test/unit/fixtures/project';
const entryPoint = 'index.js';
deployment.js.tarBundle({
target: path.normalize(target),
entryPoint: entryPoint,
compress: true,
resolvedEntryPoint: entryPoint,
single: true,
slim: true,
}).then(bundle => {
test.equal(this.project.callCount, 1);
test.equal(this.compress.callCount, 1);
test.equal(bundle.length, 2048);
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
test.deepEqual(entries, ['index.js']);
test.done();
});
});
},
slimSingleNested(test) {
test.expect(4);
const target = 'test/unit/fixtures/project';
const entryPoint = 'another.js';
deployment.js.tarBundle({
target: path.normalize(target),
entryPoint: entryPoint,
compress: true,
resolvedEntryPoint: path.join('nested', entryPoint),
single: true,
slim: true,
}).then(bundle => {
test.equal(this.project.callCount, 1);
test.equal(this.compress.callCount, 1);
test.equal(bundle.length, 2560);
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
test.deepEqual(entries, ['nested/another.js']);
test.done();
});
});
},
fullSingle(test) {
test.expect(3);
const target = 'test/unit/fixtures/project';
const entryPoint = 'index.js';
deployment.js.tarBundle({
target: path.normalize(target),
entryPoint: entryPoint,
compress: true,
resolvedEntryPoint: entryPoint,
single: true,
full: true,
}).then(bundle => {
test.equal(this.addIgnoreRules.callCount, 3);
test.equal(bundle.length, 2048);
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
test.deepEqual(entries, ['index.js']);
test.done();
});
});
},
fullSingleNested(test) {
test.expect(2);
const target = 'test/unit/fixtures/project';
const entryPoint = 'another.js';
deployment.js.tarBundle({
target: path.normalize(target),
entryPoint: entryPoint,
compress: true,
resolvedEntryPoint: path.join('nested', entryPoint),
single: true,
full: true,
}).then(bundle => {
test.equal(bundle.length, 2560);
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
test.deepEqual(entries, ['nested/another.js']);
test.done();
});
});
},
slimIncludeOverridesIgnore(test) {
test.expect(9);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project-include-overrides-ignore';
/*
project-include-overrides-ignore
├── .tesselignore
├── .tesselinclude
├── index.js
├── mock-foo.js
├── nested
│ └── another.js
├── node_modules
│ └── foo
│ ├── .tesselignore
│ ├── .tesselinclude
│ ├── index.js
│ └── package.json
├── other.js
└── package.json
3 directories, 11 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then(bundle => {
test.equal(this.globSync.callCount, 8 + listRuleLength);
/*
All .tesselignore rules are negated by all .tesselinclude rules:
$ find . -type f -name .tesselignore -exec cat {} \+
mock-foo.js
other.js
package.json
$ find . -type f -name .tesselinclude -exec cat {} \+
mock-foo.js
other.js
package.json
*/
// 'other.js' doesn't appear in the source, but is explicitly included
test.equal(this.copySync.callCount, 1);
test.equal(this.copySync.lastCall.args[0].endsWith('other.js'), true);
// Called, but without any arguments
test.equal(this.exclude.callCount, 1);
test.equal(this.exclude.lastCall.args[0].length, 0);
test.equal(this.project.callCount, 1);
// 3 js files are compressed
test.equal(this.compress.callCount, 3);
test.equal(this.remove.callCount, 1);
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
// Since the .tesselignore rules are ALL negated by .tesselinclude rules,
// the additional files are copied into the temporary bundle dir, and
// then included in the tarred bundle.
test.deepEqual(entries, [
'index.js',
'mock-foo.js',
'node_modules/foo/index.js',
'node_modules/foo/package.json',
'other.js',
'package.json',
]);
test.done();
});
});
},
fullIncludeOverridesIgnore(test) {
test.expect(8);
const target = 'test/unit/fixtures/project-include-overrides-ignore';
/*
project-include-overrides-ignore
├── .tesselignore
├── .tesselinclude
├── index.js
├── mock-foo.js
├── nested
│ └── another.js
├── node_modules
│ └── foo
│ ├── .tesselignore
│ ├── .tesselinclude
│ ├── index.js
│ └── package.json
├── other.js
└── package.json
3 directories, 11 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
compress: true,
full: true,
}).then(bundle => {
test.equal(this.globSync.callCount, 8 + listRuleLength);
// addIgnoreRules might be called many times, but we only
// care about tracking the call that's explicitly made by
// tessel's deploy operation
test.deepEqual(this.addIgnoreRules.getCall(0).args[0], [
'**/.tesselignore',
'**/.tesselinclude',
]);
/*
$ find . -type f -name .tesselignore -exec cat {} \+
mock-foo.js
other.js
package.json
*/
test.equal(this.exclude.callCount, 0);
// These things don't happen in the --full path
test.equal(this.project.callCount, 0);
test.equal(this.compress.callCount, 0);
test.equal(this.writeFileSync.callCount, 0);
test.equal(this.remove.callCount, 0);
// End
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
// The .tesselignore rules are ALL overridden by .tesselinclude rules
test.deepEqual(entries, [
'index.js',
'mock-foo.js',
'nested/another.js',
'node_modules/foo/index.js',
'other.js',
'package.json'
]);
test.done();
});
});
},
slimIncludeWithoutIgnore(test) {
test.expect(9);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project-include-without-ignore';
/*
project-include-without-ignore
├── .tesselinclude
├── index.js
├── mock-foo.js
├── nested
│ └── another.js
├── node_modules
│ └── foo
│ ├── .tesselinclude
│ ├── index.js
│ └── package.json
├── other.js
└── package.json
3 directories, 9 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then(bundle => {
test.equal(this.globSync.callCount, 5 + listRuleLength);
/*
There are NO .tesselignore rules, but there are .tesselinclude rules:
$ find . -type f -name .tesselignore -exec cat {} \+
(no results)
$ find . -type f -name .tesselinclude -exec cat {} \+
mock-foo.js
other.js
package.json
*/
// Called, but without any arguments
test.equal(this.exclude.callCount, 1);
test.equal(this.exclude.lastCall.args[0].length, 0);
// 'other.js' doesn't appear in the source, but is explicitly included
test.equal(this.copySync.callCount, 1);
test.equal(this.copySync.lastCall.args[0].endsWith('other.js'), true);
test.equal(this.project.callCount, 1);
test.equal(this.compress.callCount, 3);
test.equal(this.remove.callCount, 1);
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
// There are no .tesselignore rules, all .tesselinclude rules are
// respected the additional files are copied into the temporary
// bundle dir, and then included in the tarred bundle.
test.deepEqual(entries, [
'index.js',
'mock-foo.js',
'node_modules/foo/index.js',
'node_modules/foo/package.json',
'other.js',
'package.json'
]);
test.done();
});
});
},
fullIncludeWithoutIgnore(test) {
test.expect(8);
/*
!! TAKE NOTE!!
This is actually the default behavior. That is to say:
these files would be included, whether they are listed
in the .tesselinclude file or not.
*/
const target = 'test/unit/fixtures/project-include-without-ignore';
/*
project-include-without-ignore
├── .tesselinclude
├── index.js
├── mock-foo.js
├── nested
│ └── another.js
├── node_modules
│ └── foo
│ ├── .tesselinclude
│ ├── index.js
│ └── package.json
├── other.js
└── package.json
3 directories, 9 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
compress: true,
full: true,
}).then(bundle => {
test.equal(this.globSync.callCount, 5 + listRuleLength);
// addIgnoreRules might be called many times, but we only
// care about tracking the call that's explicitly made by
// tessel's deploy operation
test.deepEqual(this.addIgnoreRules.getCall(0).args[0], [
'**/.tesselignore',
'**/.tesselinclude',
]);
/*
There are NO .tesselignore rules, but there are .tesselinclude rules:
$ find . -type f -name .tesselignore -exec cat {} \+
(no results)
$ find . -type f -name .tesselinclude -exec cat {} \+
mock-foo.js
other.js
package.json
*/
test.equal(this.exclude.callCount, 0);
// These things don't happen in the --full path
test.equal(this.project.callCount, 0);
test.equal(this.compress.callCount, 0);
test.equal(this.writeFileSync.callCount, 0);
test.equal(this.remove.callCount, 0);
// End
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
// There are no .tesselignore rules, all .tesselinclude rules are
// respected the additional files are copied into the temporary
// bundle dir, and then included in the tarred bundle.
test.deepEqual(entries, [
'index.js',
'mock-foo.js',
'nested/another.js',
'node_modules/foo/index.js',
'node_modules/foo/package.json',
'other.js',
'package.json'
]);
test.done();
});
});
},
slimIncludeHasNegateRules(test) {
test.expect(8);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project-include-has-negate-rules';
/*
project-include-has-negate-rules
.
├── .tesselinclude
├── index.js
├── mock-foo.js
├── nested
│ └── another.js
├── node_modules
│ └── foo
│ ├── .tesselinclude
│ ├── index.js
│ └── package.json
├── other.js
└── package.json
3 directories, 9 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then(bundle => {
test.equal(this.globSync.callCount, 6 + listRuleLength);
/*
There are NO .tesselignore rules, but there are .tesselinclude rules:
$ find . -type f -name .tesselignore -exec cat {} \+
(no results)
$ find . -type f -name .tesselinclude -exec cat {} \+
!mock-foo.js
other.js
package.json
The negated rule will be transferred.
*/
test.equal(this.exclude.callCount, 1);
// Called once for the extra file matching
// the .tesselinclude rules
test.equal(this.copySync.callCount, 1);
test.equal(this.project.callCount, 1);
test.equal(this.compress.callCount, 2);
// The 4 files discovered and listed in the dependency graph
// See bundle extraction below.
test.equal(this.outputFileSync.callCount, 4);
test.equal(this.remove.callCount, 1);
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
// There are no .tesselignore rules, but the .tesselinclude rules
// include a negated pattern. The additional, non-negated files
// are copied into the temporary bundle dir, and then included
// in the tarred bundle.
test.deepEqual(entries, [
'index.js',
// mock-foo.js MUST NOT BE PRESENT
'node_modules/foo/index.js',
'node_modules/foo/package.json',
'other.js',
'package.json',
]);
test.done();
});
});
},
fullIncludeHasNegateRules(test) {
test.expect(8);
const target = 'test/unit/fixtures/project-include-has-negate-rules';
/*
project-include-has-negate-rules
.
├── .tesselinclude
├── index.js
├── mock-foo.js
├── nested
│ └── another.js
├── node_modules
│ └── foo
│ ├── .tesselinclude
│ ├── index.js
│ └── package.json
├── other.js
└── package.json
3 directories, 9 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
compress: true,
full: true,
}).then(bundle => {
test.equal(this.globSync.callCount, 6 + listRuleLength);
// addIgnoreRules might be called many times, but we only
// care about tracking the call that's explicitly made by
// tessel's deploy operation
test.deepEqual(this.addIgnoreRules.getCall(0).args[0], [
'**/.tesselignore',
'**/.tesselinclude',
]);
// This is where the negated rule is transferred.
test.deepEqual(this.addIgnoreRules.getCall(1).args[0], [
// Note that the "!" was stripped from the rule
'mock-foo.js',
]);
/*
There are NO .tesselignore rules, but there are .tesselinclude rules:
$ find . -type f -name .tesselignore -exec cat {} \+
(no results)
$ find . -type f -name .tesselinclude -exec cat {} \+
!mock-foo.js
other.js
package.json
The negated rule will be transferred.
*/
// These things don't happen in the --full path
test.equal(this.project.callCount, 0);
test.equal(this.compress.callCount, 0);
test.equal(this.writeFileSync.callCount, 0);
test.equal(this.remove.callCount, 0);
// End
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
// There are no .tesselignore rules, all .tesselinclude rules are
// respected the additional files are copied into the temporary
// bundle dir, and then included in the tarred bundle.
test.deepEqual(entries, [
'index.js',
// mock-foo.js is NOT present
'nested/another.js',
'node_modules/foo/index.js',
'node_modules/foo/package.json',
'other.js',
'package.json'
]);
test.done();
});
});
},
slimSingleInclude(test) {
test.expect(2);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project-include-without-ignore';
/*
project-include-without-ignore
├── .tesselinclude
├── index.js
├── mock-foo.js
├── nested
│ └── another.js
├── node_modules
│ └── foo
│ ├── .tesselinclude
│ ├── index.js
│ └── package.json
├── other.js
└── package.json
3 directories, 9 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
single: true,
}).then(bundle => {
test.equal(this.globSync.callCount, 5 + listRuleLength);
/*
There are .tesselinclude rules, but the single flag is present
so they don't matter. The only file sent must be the file specified.
*/
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
// Only the explicitly specified `index.js` will
// be included in the deployed code.
test.deepEqual(entries, [
'index.js',
]);
test.done();
});
});
},
detectAssetsWithoutInclude(test) {
test.expect(4);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project-assets-without-include';
/*
project-assets-without-include
├── index.js
├── mock-foo.js
├── nested
│ └── another.js
├── node_modules
│ └── foo
│ ├── index.js
│ └── package.json
├── other.js
└── package.json
3 directories, 7 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then(() => {
test.equal(this.readdirSync.callCount, 1);
test.equal(this.readdirSync.lastCall.args[0], path.normalize(target));
test.equal(this.warn.callCount, 1);
test.equal(this.warn.firstCall.args[0], 'Some assets in this project were not deployed (see: t2 run --help)');
test.done();
});
},
detectAssetsWithoutIncludeEliminatedByDepGraph(test) {
test.expect(3);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project-assets-without-include-eliminated-by-dep-graph';
/*
project-assets-without-include
├── index.js
├── mock-foo.js
├── nested
│ └── another.js
├── node_modules
│ └── foo
│ ├── index.js
│ └── package.json
└── package.json
3 directories, 6 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then(() => {
test.equal(this.readdirSync.callCount, 1);
test.equal(this.readdirSync.lastCall.args[0], path.normalize(target));
test.equal(this.warn.callCount, 0);
// Ultimately, all assets were accounted for, even though
// no tesselinclude existed.
test.done();
});
},
alwaysExplicitlyProvideProjectDirname(test) {
test.expect(1);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project';
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then(() => {
test.deepEqual(this.project.lastCall.args[0], {
entry: path.join(target, entryPoint),
dirname: path.normalize(target),
});
test.done();
});
},
detectAndEliminateBlacklistedAssets(test) {
test.expect(1);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project-ignore-blacklisted';
/*
project-ignore-blacklisted
├── index.js
├── node_modules
│ └── tessel
│ ├── index.js
│ └── package.json
└── package.json
2 directories, 4 files
*/
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
}).then((bundle) => {
// Extract and inspect the bundle...
extract(bundle, (error, entries) => {
if (error) {
test.ok(false, error.toString());
test.done();
}
test.deepEqual(entries, [
'index.js',
'package.json'
]);
test.done();
});
});
},
iteratesBinaryModulesUsed(test) {
test.expect(5);
const entryPoint = 'index.js';
const target = 'test/unit/fixtures/project';
const details = {
modulePath: ''
};
this.minimatch = sandbox.stub(deployment.js, 'minimatch').returns(true);
this.rules = sandbox.stub(glob, 'rules').callsFake(() => {
return [
'a', 'b',
];
});
this.forEach = sandbox.stub(Map.prototype, 'forEach').callsFake((handler) => {
handler(details);
});
deployment.js.tarBundle({
target: path.normalize(target),
resolvedEntryPoint: entryPoint,
compress: true,
slim: true,
})
.then(() => {
test.equal(this.forEach.callCount, 2);
test.equal(this.minimatch.callCount, 3);
test.deepEqual(this.minimatch.getCall(0).args, ['', 'a', {
matchBase: true,
dot: true
}]);
test.deepEqual(this.minimatch.getCall(1).args, ['', 'b', {
matchBase: true,
dot: true
}]);
test.deepEqual(this.minimatch.getCall(2).args, ['', 'node_modules/**/tessel/**/*', {
matchBase: true,
dot: true
}]);
test.done();
});
},
};
var fixtures = {
project: path.join(FIXTURE_PATH, '/find-project'),
explicit: path.join(FIXTURE_PATH, '/find-project-explicit-main')
};
exports['deploy.findProject'] = {
setUp(done) {
done();
},
tearDown(done) {
sandbox.restore();
done();
},
home(test) {
test.expect(1);
var fake = path.normalize('/fake/test/home/dir');
this.homedir = sandbox.stub(os, 'homedir').returns(fake);
this.lstatSync = sandbox.stub(fs, 'lstatSync').callsFake((file) => {
return {
isDirectory: () => {
// naive for testing.
return file.slice(-1) === '/';
}
};
});
this.realpathSync = sandbox.stub(fs, 'realpathSync').callsFake((arg) => {
// Ensure that "~" was transformed
test.equal(arg, path.normalize('/fake/test/home/dir/foo'));
test.done();
return '';
});
deploy.findProject({
lang: deployment.js,
entryPoint: '~/foo/',
compress: true,
});
},
byFile(test) {
test.expect(1);
var target = 'test/unit/fixtures/find-project/index.js';
deploy.findProject({
lang: deployment.js,
entryPoint: target,
compress: true,
}).then(project => {
test.deepEqual(project, {
pushdir: fixtures.project,
program: path.join(fixtures.project, 'index.js'),
entryPoint: 'index.js'
});
test.done();
});
},
byDirectory(test) {
test.expect(1);
var target = 'test/unit/fixtures/find-project/';
deploy.findProject({
lang: deployment.js,
entryPoint: target
}).then(project => {
test.deepEqual(project, {
pushdir: fixtures.project,
program: path.join(fixtures.project, 'index.js'),
entryPoint: 'index.js'
});
test.done();
});
},
byDirectoryBWExplicitMain(test) {
test.expect(1);
var target = 'test/unit/fixtures/find-project-explicit-main/';
deploy.findProject({
lang: deployment.js,
entryPoint: target
}).then(project => {
test.deepEqual(project, {
pushdir: fixtures.explicit,
program: path.join(fixtures.explicit, 'app.js'),
entryPoint: 'app.js'
});
test.done();
});
},
byDirectoryMissingIndex(test) {
test.expect(1);
var target = 'test/unit/fixtures/find-project-no-index/index.js';
deploy.findProject({
lang: deployment.js,
entryPoint: target
}).then(() => {
test.ok(false, 'findProject should not find a valid project here');
test.done();
}).catch(error => {
test.ok(error.includes('ENOENT'));
test.done();
});
},
byFileInSubDirectory(test) {
test.expect(1);
var target = 'test/unit/fixtures/find-project/test/index.js';
deploy.findProject({
lang: deployment.js,
entryPoint: target
}).then(project => {
test.deepEqual(project, {
pushdir: fixtures.project,
program: path.join(fixtures.project, 'test/index.js'),
entryPoint: path.normalize('test/index.js')
});
test.done();
});
},
noPackageJsonSingle(test) {
test.expect(1);
var pushdir = path.normalize('test/unit/fixtures/project-no-package.json/');
var entryPoint = path.normalize('test/unit/fixtures/project-no-package.json/index.js');
var opts = {
entryPoint: entryPoint,
single: true,
slim: true,
lang: deployment.js,
};
deploy.findProject(opts).then(project => {
// Without the `single` flag, this would've continued upward
// until it found a directory with a package.json.
test.equal(project.pushdir, fs.realpathSync(pushdir));
test.done();
});
},
noPackageJsonUseProgramDirname(test) {
test.expect(1);
// This is no package.json here
var entryPoint = path.normalize('test/unit/fixtures/project-no-package.json/index.js');
var opts = {
entryPoint: entryPoint,
lang: deployment.js,
single: false,
};
this.endOfLookup = sandbox.stub(deploy, 'endOfLookup').returns(true);
deploy.findProject(opts).then(project => {
test.equal(project.pushdir, path.dirname(path.join(process.cwd(), entryPoint)));
test.done();
});
},
};
exports['deploy.sendBundle, error handling'] = {
setUp(done) {
this.tessel = TesselSimulator();
this.fetchCurrentBuildInfo = sandbox.stub(this.tessel, 'fetchCurrentBuildInfo').returns(Promise.resolve('40b2b46a62a34b5a26170c75f7e717cea673d1eb'));
this.fetchNodeProcessVersions = sandbox.stub(this.tessel, 'fetchNodeProcessVersions').returns(Promise.resolve(processVersions));
this.requestBuildList = sandbox.stub(updates, 'requestBuildList').returns(Promise.resolve(tesselBuilds));
this.pathResolve = sandbox.stub(path, 'resolve');
this.failure = 'FAIL';
done();
},
tearDown(done) {
this.tessel.mockClose();
sandbox.restore();
done();
},
findProject(test) {
test.expect(1);
this.findProject = sandbox.stub(deploy, 'findProject').callsFake(() => Promise.reject(this.failure));
deploy.sendBundle(this.tessel, {
lang: deployment.js
}).catch(error => {
test.equal(error, this.failure);
test.done();
});
},
resolveBinaryModules(test) {
test.expect(1);
this.pathResolve.restore();
this.pathResolve = sandbox.stub(path, 'resolve').returns('');
this.exists = sandbox.stub(fs, 'exists').callsFake((fpath, callback) => callback(true));
this.findProject = sandbox.stub(deploy, 'findProject').callsFake(() => Promise.resolve({
pushdir: '',
entryPoint: ''
}));
this.resolveBinaryModules = sandbox.stub(deployment.js, 'resolveBinaryModules').callsFake(() => Promise.reject(this.failure));
deploy.sendBundle(this.tessel, {
lang: deployment.js
}).catch(error => {
test.equal(error, this.failure);
test.done();
});
},
tarBundle(test) {
test.expect(1);
this.pathResolve.restore();
this.pathResolve = sandbox.stub(path, 'resolve').returns('');
this.exists = sandbox.stub(fs, 'exists').callsFake((fpath, callback) => callback(true));
this.findProject = sandbox.stub(deploy, 'findProject').callsFake(() => Promise.resolve({
pushdir: '',
entryPoint: ''
}));
this.resolveBinaryModules = sandbox.stub(deployment.js, 'resolveBinaryModules').callsFake(() => Promise.resolve());
this.tarBundle = sandbox.stub(deployment.js, 'tarBundle').callsFake(() => Promise.reject(this.failure));
deploy.sendBundle(this.tessel, {
lang: deployment.js
}).catch(error => {
test.equal(error, this.failure);
test.done();
});
},
};
exports['deployment.js.preBundle'] = {
setUp(done) {
this.tessel = TesselSimulator();
this.info = sandbox.stub(log, 'info');
this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => {
callback(null, this.tessel._rps);
});
this.receive = sandbox.stub(this.tessel, 'receive').callsFake((rps, callback) => {
rps.emit('close');
callback();
});
this.fetchCurrentBuildInfo = sandbox.stub(this.tessel, 'fetchCurrentBuildInfo').returns(Promise.resolve('40b2b46a62a34b5a26170c75f7e717cea673d1eb'));
this.fetchNodeProcessVersions = sandbox.stub(this.tessel, 'fetchNodeProcessVersions').returns(Promise.resolve(processVersions));
this.requestBuildList = sandbox.stub(updates, 'requestBuildList').returns(Promise.resolve(tesselBuilds));
this.findProject = sandbox.stub(deploy, 'findProject').returns(Promise.resolve({
pushdir: '',
entryPoint: ''
}));
this.resolveBinaryModules = sandbox.stub(deployment.js, 'resolveBinaryModules').returns(Promise.resolve());
this.tarBundle = sandbox.stub(deployment.js, 'tarBundle').returns(Promise.resolve(new Buffer([0x00])));
this.pathResolve = sandbox.stub(path, 'resolve');
this.preBundle = sandbox.spy(deployment.js, 'preBundle');
done();
},
tearDown(done) {
this.tessel.mockClose();
sandbox.restore();
done();
},
preBundleChecksForNpmrc(test) {
test.expect(1);
const warning = tags.stripIndents `This project is missing an ".npmrc" file!
To prepare your project for deployment, use the command:
t2 init
Once complete, retry:`;
this.exists = sandbox.stub(fs, 'exists').callsFake((fpath, callback) => callback(false));
deployment.js.preBundle({
target: '/',
}).catch(error => {
test.equal(error.startsWith(warning), true);
test.done();
});
},
preBundleReceivesTessel(test) {
test.expect(1);
this.pathResolve.restore();
this.pathResolve = sandbox.stub(path, 'resolve').returns('');
this.exists = sandbox.stub(fs, 'exists').callsFake((fpath, callback) => callback(true));
deploy.sendBundle(this.tessel, {
target: '/',
entryPoint: 'foo.js',
lang: deployment.js
}).then(() => {
test.equal(this.preBundle.lastCall.args[0].tessel, this.tessel);
test.done();
});
},
// // We need to find a way to provde the build version directly from the
// // Tessel 2 itself. This approach makes deployment slow with a network
// // connection, or impossible without one.
// preBundleCallsfetchCurrentBuildInfoAndForwardsResult(test) {
// test.expect(4);
// deploy.sendBundle(this.tessel, {
// target: '/',
// entryPoint: 'foo.js',
// lang: deployment.js
// }).then(() => {
// test.equal(this.fetchCurrentBuildInfo.callCount, 1);
// test.equal(this.resolveBinaryModules.callCount, 1);
// var args = this.resolveBinaryModules.lastCall.args[0];
// test.equal(args.tessel, this.tessel);
// test.equal(args.tessel.versions, processVersions);
// test.done();
// });
// },
// preBundleCallsrequestBuildListAndForwardsResult(test) {
// test.expect(4);
// deploy.sendBundle(this.tessel, {
// target: '/',
// entryPoint: 'foo.js',
// lang: deployment.js
// }).then(() => {
// test.equal(this.requestBuildList.callCount, 1);
// test.equal(this.resolveBinaryModules.callCount, 1);
// var args = this.resolveBinaryModules.lastCall.args[0];
// test.equal(args.tessel, this.tessel);
// test.equal(args.tessel.versions, processVersions);
// test.done();
// });
// },
// preBundleCallsfetchNodeProcessVersionsAndForwardsResult(test) {
// test.expect(4);
// deploy.sendBundle(this.tessel, {
// target: '/',
// entryPoint: 'foo.js',
// lang: deployment.js
// }).then(() => {
// test.equal(this.fetchNodeProcessVersions.callCount, 1);
// test.equal(this.resolveBinaryModules.callCount, 1);
// var args = this.resolveBinaryModules.lastCall.args[0];
// test.equal(args.tessel, this.tessel);
// test.equal(args.tessel.versions, processVersions);
// test.done();
// });
// },
};
exports['deployment.js.resolveBinaryModules'] = {
setUp(done) {
this.target = path.normalize('test/unit/fixtures/project-binary-modules');
this.relative = sandbox.stub(path, 'relative').callsFake(() => {
return path.join(FIXTURE_PATH, '/project-binary-modules/');
});
this.globFiles = sandbox.spy(glob, 'files');
this.globSync = sandbox.stub(glob, 'sync').callsFake(() => {
return [
path.normalize('node_modules/release/build/Release/release.node'),
];
});
this.readGypFileSync = sandbox.stub(deployment.js.resolveBinaryModules, 'readGypFileSync').callsFake(() => {
return '{"targets": [{"target_name": "missing"}]}';
});
this.getRoot = sandbox.stub(bindings, 'getRoot').callsFake((file) => {
var pathPart = '';
if (file.includes('debug')) {
pathPart = 'debug';
}
if (file.includes('linked')) {
pathPart = 'linked';
}
if (file.includes('missing')) {
pathPart = 'missing';
}
if (file.includes('release')) {
pathPart = 'release';
}
return path.normalize(`node_modules/${pathPart}/`);
});
this.ifReachable = sandbox.stub(remote, 'ifReachable').callsFake(() => Promise.resolve());
done();
},
tearDown(done) {
sandbox.restore();
done();
},
bailOnSkipBinary(test) {
test.expect(2);
this.target = path.normalize('test/unit/fixtures/project-skip-binary');
this.relative.restore();
this.relative = sandbox.stub(path, 'relative').callsFake(() => {
return path.join(FIXTURE_PATH, '/project-skip-binary/');
});
// We WANT to read the actual gyp files if necessary
this.readGypFileSync.restore();
// We WANT to glob the actual target directory
this.globSync.restore();
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.equal(this.exists.callCount, 1);
// test/unit/fixtures/skip-binary/ has the corresponding
// dependencies for the following binary modules:
//
// debug-1.1.1-Debug-node-v46-linux-mipsel
// release-1.1.1-Release-node-v46-linux-mipsel
//
// However, the latter has a "tessel.skipBinary = true" key in its package.json
//
//
test.equal(this.exists.lastCall.args[0].endsWith(path.normalize('.tessel/binaries/debug-1.1.1-Debug-node-v46-linux-mipsel')), true);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
buildPathExpWindow(test) {
test.expect(1);
let descriptor = Object.getOwnPropertyDescriptor(process, 'platform');
Object.defineProperty(process, 'platform', {
value: 'win32'
});
this.match = sandbox.spy(String.prototype, 'match');
this.target = path.normalize('test/unit/fixtures/project-skip-binary');
this.relative.restore();
this.relative = sandbox.stub(path, 'relative').callsFake(() => {
return path.join(FIXTURE_PATH, '/project-skip-binary/');
});
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.equal(
this.match.lastCall.args[0].toString(),
'/(?:build\\\\(Debug|Release|bindings)\\\\)/'
);
// Restore this descriptor
Object.defineProperty(process, 'platform', descriptor);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
noOptionsTargetFallbackToCWD(test) {
test.expect(3);
const target = path.normalize('test/unit/fixtures/project');
sandbox.stub(process, 'cwd').returns(target);
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
deployment.js.resolveBinaryModules({
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.equal(this.relative.callCount, 1);
test.equal(this.relative.lastCall.args[0], target);
test.equal(this.relative.lastCall.args[1], target);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
noOptionsTargetFallbackToCWDNoRelative(test) {
test.expect(1);
this.relative.restore();
this.relative = sandbox.stub(path, 'relative').returns('');
this.cwd = sandbox.stub(process, 'cwd').returns('');
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
deployment.js.resolveBinaryModules({
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.ok(false, 'resolveBinaryModules should not resolve');
test.done();
}).catch(error => {
// The thing to be found:
//
// node_modules/release/package.json
//
// Will not be found, because it doesn't exist,
// but in this case, that's exactly what we want.
test.equal(error.toString(), `Error: Cannot find module '${path.normalize('node_modules/release/package.json')}'`);
test.done();
});
},
findsModulesMissingBinaryNodeFiles(test) {
test.expect(2);
this.globSync.restore();
this.globSync = sandbox.stub(glob, 'sync').callsFake(() => {
return [
path.normalize('node_modules/release/build/Release/release.node'),
path.normalize('node_modules/release/binding.gyp'),
path.normalize('node_modules/missing/binding.gyp'),
];
});
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.deepEqual(
this.globFiles.lastCall.args[1], ['node_modules/**/*.node', 'node_modules/**/binding.gyp']
);
test.equal(this.readGypFileSync.callCount, 1);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
spawnPythonScriptReturnsNull(test) {
test.expect(1);
this.readGypFileSync.restore();
this.readGypFileSync = sandbox.spy(deployment.js.resolveBinaryModules, 'readGypFileSync');
this.globSync.restore();
this.globSync = sandbox.stub(glob, 'sync').callsFake(() => {
return [
path.normalize('node_modules/release/build/Release/release.node'),
path.normalize('node_modules/release/binding.gyp'),
path.normalize('node_modules/missing/binding.gyp'),
];
});
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
this.spawnSync = sandbox.stub(cp, 'spawnSync').callsFake(() => {
return {
output: null
};
});
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.equal(this.readGypFileSync.lastCall.returnValue, '');
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
spawnPythonScript(test) {
test.expect(7);
this.readGypFileSync.restore();
this.readGypFileSync = sandbox.spy(deployment.js.resolveBinaryModules, 'readGypFileSync');
this.globSync.restore();
this.globSync = sandbox.stub(glob, 'sync').callsFake(() => {
return [
path.normalize('node_modules/release/build/Release/release.node'),
path.normalize('node_modules/release/binding.gyp'),
path.normalize('node_modules/missing/binding.gyp'),
];
});
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
this.spawnSync = sandbox.stub(cp, 'spawnSync').callsFake(() => {
return {
output: [
null, new Buffer('{"targets": [{"target_name": "missing","sources": ["capture.c", "missing.cc"]}]}', 'utf8')
]
};
});
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.deepEqual(
this.globFiles.lastCall.args[1], ['node_modules/**/*.node', 'node_modules/**/binding.gyp']
);
test.equal(this.readGypFileSync.callCount, 1);
test.equal(this.spawnSync.callCount, 1);
test.equal(this.spawnSync.lastCall.args[0], 'python');
var python = this.spawnSync.lastCall.args[1][1];
test.equal(python.startsWith('import ast, json; print json.dumps(ast.literal_eval(open('), true);
test.equal(python.endsWith(').read()));'), true);
test.equal(python.includes('missing'), true);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
failsWithMessage(test) {
test.expect(1);
this.globSync.restore();
this.globSync = sandbox.stub(glob, 'sync').callsFake(() => {
return [
path.normalize('node_modules/missing/binding.gyp'),
];
});
this.readGypFileSync.restore();
this.readGypFileSync = sandbox.stub(deployment.js.resolveBinaryModules, 'readGypFileSync').callsFake(() => {
return '{"targets": [{"target_name": "missing",}]}';
// ^
// That's intentional.
});
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(binaryModulesUsed => {
test.equal(binaryModulesUsed.get('[email protected]').resolved, false);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
existsInLocalCache(test) {
test.expect(2);
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.equal(this.globFiles.callCount, 1);
test.equal(this.exists.callCount, 1);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
existsInLocalCacheNodeGypLinkedBinPath(test) {
test.expect(1);
this.readGypFileSync.restore();
this.globSync.restore();
this.globSync = sandbox.stub(glob, 'sync').callsFake(() => {
return [
path.normalize('node_modules/release/build/Release/release.node'),
path.normalize('node_modules/linked/build/bindings/linked.node'),
];
});
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.equal(this.exists.callCount, 2);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
resolveFromRealDirFixtures(test) {
test.expect(5);
// We WANT to read the actual gyp files if necessary
this.readGypFileSync.restore();
// We WANT to glob the actual target directory
this.globSync.restore();
// To avoid making an actual network request,
// make the program think these things are already
// cached. The test to pass is that it calls fs.existsSync
// with the correct things from the project directory (this.target)
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.equal(this.exists.callCount, 4);
// test/unit/fixtures/project-binary-modules/ has the corresponding
// dependencies for the following binary modules:
var cachedBinaryPaths = [
'.tessel/binaries/debug-1.1.1-Debug-node-v46-linux-mipsel',
'.tessel/binaries/linked-1.1.1-Release-node-v46-linux-mipsel',
'.tessel/binaries/release-1.1.1-Release-node-v46-linux-mipsel',
'.tessel/binaries/missing-1.1.1-Release-node-v46-linux-mipsel',
];
cachedBinaryPaths.forEach((cbp, callIndex) => {
test.equal(this.exists.getCall(callIndex).args[0].endsWith(path.normalize(cbp)), true);
});
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
requestsRemote(test) {
test.expect(12);
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => false);
this.mkdirp = sandbox.stub(fs, 'mkdirp').callsFake((dir, handler) => {
handler();
});
this.transform = new Transform();
this.transform.stubsUsed = [];
this.rstream = null;
this.pipe = sandbox.stub(stream.Stream.prototype, 'pipe').callsFake(() => {
// After the second transform is piped, emit the end
// event on the request stream;
if (this.pipe.callCount === 2) {
process.nextTick(() => this.rstream.emit('end'));
}
return this.rstream;
});
this.createGunzip = sandbox.stub(zlib, 'createGunzip').callsFake(() => {
this.transform.stubsUsed.push('createGunzip');
return this.transform;
});
this.Extract = sandbox.stub(tar, 'Extract').callsFake(() => {
this.transform.stubsUsed.push('Extract');
return this.transform;
});
this.request = sandbox.stub(request, 'Request').callsFake((opts) => {
this.rstream = new Request(opts);
return this.rstream;
});
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.equal(this.globFiles.callCount, 1);
test.equal(this.exists.callCount, 1);
test.equal(this.mkdirp.callCount, 1);
test.equal(this.mkdirp.lastCall.args[0].endsWith(path.normalize('.tessel/binaries/release-1.1.1-Release-node-v46-linux-mipsel')), true);
test.equal(this.request.callCount, 1);
var requestArgs = this.request.lastCall.args[0];
test.equal(requestArgs.url, 'http://packages.tessel.io/npm/release-1.1.1-Release-node-v46-linux-mipsel.tgz');
test.equal(requestArgs.gzip, true);
test.equal(this.pipe.callCount, 2);
test.equal(this.createGunzip.callCount, 1);
test.equal(this.Extract.callCount, 1);
test.equal(this.transform.stubsUsed.length, 2);
test.deepEqual(this.transform.stubsUsed, ['createGunzip', 'Extract']);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
requestsRemoteGunzipErrors(test) {
test.expect(9);
this.removeSync = sandbox.stub(fs, 'removeSync');
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => false);
this.mkdirp = sandbox.stub(fs, 'mkdirp').callsFake((dir, handler) => {
handler();
});
this.transform = new Transform();
this.transform.stubsUsed = [];
this.rstream = null;
this.pipe = sandbox.stub(stream.Stream.prototype, 'pipe').callsFake(() => {
// After the second transform is piped, emit the end
// event on the request stream;
if (this.pipe.callCount === 2) {
process.nextTick(() => this.rstream.emit('end'));
}
return this.rstream;
});
this.createGunzip = sandbox.stub(zlib, 'createGunzip').callsFake(() => {
this.transform.stubsUsed.push('createGunzip');
return this.transform;
});
this.Extract = sandbox.stub(tar, 'Extract').callsFake(() => {
this.transform.stubsUsed.push('Extract');
return this.transform;
});
this.request = sandbox.stub(request, 'Request').callsFake((opts) => {
this.rstream = new Request(opts);
return this.rstream;
});
// Hook into the ifReachable call to trigger an error at the gunzip stream
this.ifReachable.restore();
this.ifReachable = sandbox.stub(remote, 'ifReachable').callsFake(() => {
this.transform.emit('error', {
code: 'Z_DATA_ERROR',
});
return Promise.resolve();
});
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
test.equal(this.globFiles.callCount, 1);
test.equal(this.exists.callCount, 1);
test.equal(this.mkdirp.callCount, 1);
test.equal(this.mkdirp.lastCall.args[0].endsWith(path.normalize('.tessel/binaries/release-1.1.1-Release-node-v46-linux-mipsel')), true);
// The result of gunzip emitting an error:
test.equal(this.removeSync.callCount, 1);
test.equal(this.removeSync.lastCall.args[0].endsWith(path.normalize('.tessel/binaries/release-1.1.1-Release-node-v46-linux-mipsel')), true);
test.equal(this.request.callCount, 1);
test.equal(this.createGunzip.callCount, 1);
test.deepEqual(this.transform.stubsUsed, ['createGunzip', 'Extract']);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
};
exports['deployment.js.injectBinaryModules'] = {
setUp(done) {
this.target = path.normalize('test/unit/fixtures/project-binary-modules');
this.relative = sandbox.stub(path, 'relative').callsFake(() => {
return path.join(FIXTURE_PATH, '/project-binary-modules/');
});
this.globFiles = sandbox.spy(glob, 'files');
this.globSync = sandbox.stub(glob, 'sync').callsFake(() => {
return [
path.normalize('node_modules/release/build/Release/release.node'),
];
});
this.getRoot = sandbox.stub(bindings, 'getRoot').callsFake((file) => {
var pathPart = '';
if (file.includes('debug')) {
pathPart = 'debug';
}
if (file.includes('linked')) {
pathPart = 'linked';
}
if (file.includes('missing')) {
pathPart = 'missing';
}
if (file.includes('release')) {
pathPart = 'release';
}
return path.normalize(`node_modules/${pathPart}/`);
});
this.globRoot = path.join(FIXTURE_PATH, '/project-binary-modules/');
this.copySync = sandbox.stub(fs, 'copySync');
this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true);
done();
},
tearDown(done) {
sandbox.restore();
done();
},
copies(test) {
test.expect(17);
this.globSync.restore();
this.globSync = sandbox.stub(glob, 'sync').callsFake(() => {
return [
path.normalize('node_modules/debug/build/Debug/debug.node'),
path.normalize('node_modules/debug/binding.gyp'),
path.normalize('node_modules/linked/build/bindings/linked.node'),
path.normalize('node_modules/linked/binding.gyp'),
path.normalize('node_modules/missing/build/Release/missing.node'),
path.normalize('node_modules/missing/binding.gyp'),
path.normalize('node_modules/release/build/Release/release.node'),
path.normalize('node_modules/release/binding.gyp'),
];
});
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync(), {}).then(() => {
test.equal(this.copySync.callCount, 8);
var args = this.copySync.args;
/*
This is an abbreviated view of what should be copied by this operation:
[
[
'debug-1.1.1-Release-node-v46-linux-mipsel/Debug/debug.node',
'debug/build/Debug/debug.node'
],
[
'debug/package.json',
'debug/package.json'
],
[
'linked-1.1.1-Release-node-v46-linux-mipsel/bindings/linked.node',
'linked/build/bindings/linked.node'
],
[
'linked/package.json',
'linked/package.json'
],
[
'missing-1.1.1-Release-node-v46-linux-mipsel/Release/missing.node',
'missing/build/Release/missing.node'
],
[
'missing/package.json',
'missing/package.json'
],
[
'release-1.1.1-Release-node-v46-linux-mipsel/Release/release.node',
'release/build/Release/release.node'
],
[
'release/package.json',
'release/package.json'
]
]
*/
// ----- fixtures/project-binary-modules/node_modules/debug
test.equal(
args[0][0].endsWith(path.normalize('debug-1.1.1-Debug-node-v46-linux-mipsel/Debug/debug.node')),
true
);
test.equal(
args[0][1].endsWith(path.normalize('debug/build/Debug/debug.node')),
true
);
test.equal(
args[1][0].endsWith(path.normalize('debug/package.json')),
true
);
test.equal(
args[1][1].endsWith(path.normalize('debug/package.json')),
true
);
// ----- fixtures/project-binary-modules/node_modules/linked
test.equal(
args[2][0].endsWith(path.normalize('linked-1.1.1-Release-node-v46-linux-mipsel/bindings/linked.node')),
true
);
test.equal(
args[2][1].endsWith(path.normalize('linked/build/bindings/linked.node')),
true
);
test.equal(
args[3][0].endsWith(path.normalize('linked/package.json')),
true
);
test.equal(
args[3][1].endsWith(path.normalize('linked/package.json')),
true
);
// ----- fixtures/project-binary-modules/node_modules/missing
test.equal(
args[4][0].endsWith(path.normalize('missing-1.1.1-Release-node-v46-linux-mipsel/Release/missing.node')),
true
);
test.equal(
args[4][1].endsWith(path.normalize('missing/build/Release/missing.node')),
true
);
test.equal(
args[5][0].endsWith(path.normalize('missing/package.json')),
true
);
test.equal(
args[5][1].endsWith(path.normalize('missing/package.json')),
true
);
// ----- fixtures/project-binary-modules/node_modules/release
test.equal(
args[6][0].endsWith(path.normalize('release-1.1.1-Release-node-v46-linux-mipsel/Release/release.node')),
true
);
test.equal(
args[6][1].endsWith(path.normalize('release/build/Release/release.node')),
true
);
test.equal(
args[7][0].endsWith(path.normalize('release/package.json')),
true
);
test.equal(
args[7][1].endsWith(path.normalize('release/package.json')),
true
);
test.done();
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
}).catch(error => {
test.ok(false, error.toString());
test.done();
});
},
doesNotCopyIgnoredBinaries(test) {
test.expect(1);
this.target = path.normalize('test/unit/fixtures/project-ignore-binary');
this.relative.restore();
this.relative = sandbox.stub(path, 'relative').callsFake(() => {
return path.join(FIXTURE_PATH, '/project-ignore-binary/');
});
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync(), {}).then(() => {
// Nothing gets copied!
test.equal(this.copySync.callCount, 0);
test.done();
});
});
},
usesBinaryHighestInTreeWhenEncounteringDuplicates(test) {
test.expect(6);
this.target = path.normalize('test/unit/fixtures/project-binary-modules-duplicate-lower-deps');
this.relative.restore();
this.relative = sandbox.stub(path, 'relative').callsFake(() => {
return path.join(FIXTURE_PATH, '/project-binary-modules-duplicate-lower-deps/');
});
// We WANT to glob the actual target directory
this.globSync.restore();
this.mapHas = sandbox.spy(Map.prototype, 'has');
this.mapGet = sandbox.spy(Map.prototype, 'get');
this.mapSet = sandbox.spy(Map.prototype, 'set');
this.arrayMap = sandbox.spy(Array.prototype, 'map');
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(binaryModulesUsed => {
// Ensure that 2 modules with the same name and version were found!
for (var i = 0; i < this.arrayMap.callCount; i++) {
let call = this.arrayMap.getCall(i);
if (call.thisValue.UNRESOLVED_BINARY_LIST) {
test.equal(call.thisValue.length, 2);
}
}
test.equal(this.mapHas.callCount, 2);
test.equal(this.mapHas.getCall(0).args[0], '[email protected]');
test.equal(this.mapHas.getCall(1).args[0], '[email protected]');
// Ensure that only one of the two were included in the
// final list of binary modules to bundle
test.equal(binaryModulesUsed.size, 1);
// Ensure that the swap has occurred
test.equal(
path.normalize(binaryModulesUsed.get('[email protected]').globPath),
path.normalize('node_modules/release/build/Release/release.node')
);
test.done();
});
},
fallbackWhenOptionsMissing(test) {
test.expect(1);
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(binaryModulesUsed => {
binaryModulesUsed.clear();
// We need something to look at...
sandbox.stub(binaryModulesUsed, 'forEach');
deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync()).then(() => {
test.equal(binaryModulesUsed.forEach.callCount, 1);
test.done();
});
});
},
doesNotCopyWhenOptionsSingleTrue(test) {
test.expect(1);
// This would normally result in 8 calls to this.copySync
this.globSync.restore();
this.globSync = sandbox.stub(glob, 'sync').callsFake(() => {
return [
path.normalize('node_modules/debug/build/Debug/debug.node'),
path.normalize('node_modules/debug/binding.gyp'),
path.normalize('node_modules/linked/build/bindings/linked.node'),
path.normalize('node_modules/linked/binding.gyp'),
path.normalize('node_modules/missing/build/Release/missing.node'),
path.normalize('node_modules/missing/binding.gyp'),
path.normalize('node_modules/release/build/Release/release.node'),
path.normalize('node_modules/release/binding.gyp'),
];
});
deployment.js.resolveBinaryModules({
target: this.target,
tessel: {
versions: {
modules: 46
},
},
}).then(() => {
deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync(), {
single: true
}).then(() => {
// Nothing gets copied!
test.equal(this.copySync.callCount, 0);
test.done();
});
});
},
rewriteBinaryBuildPlatformPaths(test) {
test.expect(2);
this.forEach = sandbox.stub(Map.prototype, 'forEach').callsFake((handler) => {
handler({
binName: 'serialport.node',
buildPath: path.normalize('/build/Release/node-v46-FAKE_PLATFORM-FAKE_ARCH/'),
buildType: 'Release',
globPath: path.normalize('node_modules/serialport/build/Release/node-v46-FAKE_PLATFORM-FAKE_ARCH/serialport.node'),
ignored: false,
name: 'serialport',
modulePath: path.normalize('node_modules/serialport'),
resolved: true,
version: '2.0.6',
extractPath: path.normalize('~/.tessel/binaries/serialport-2.0.6-Release-node-v46-linux-mipsel')
});
});
var find = lists.binaryPathTranslations['*'][0].find;
lists.binaryPathTranslations['*'][0].find = 'FAKE_PLATFORM-FAKE_ARCH';
deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync(), {}).then(() => {
// If the replacement operation did not work, these would still be
// "FAKE_PLATFORM-FAKE_ARCH"
test.equal(this.copySync.firstCall.args[0].endsWith(path.normalize('linux-mipsel/serialport.node')), true);
test.equal(this.copySync.firstCall.args[1].endsWith(path.normalize('linux-mipsel/serialport.node')), true);
// Restore the path translation...
lists.binaryPathTranslations['*'][0].find = find;
test.done();
});
},
tryTheirPathAndOurPath(test) {
test.expect(3);
this.copySync.restore();
this.copySync = sandbox.stub(fs, 'copySync').callsFake(() => {
// Fail the first try/catch on THEIR PATH
if (this.copySync.callCount === 1) {
throw new Error('ENOENT: no such file or directory');
}
});
this.forEach = sandbox.stub(Map.prototype, 'forEach').callsFake((handler) => {
handler({
binName: 'node_sqlite3.node',
// This path doesn't match our precompiler's output paths.
// Will result in:
// ERR! Error: ENOENT: no such file or directory, stat '~/.tessel/binaries/sqlite3-3.1.4-Release/node-v46-something-else/node_sqlite3.node'
buildPath: path.normalize('/lib/binding/node-v46-something-else/'),
buildType: 'Release',
globPath: path.normalize('node_modules/sqlite3/lib/binding/node-v46-something-else/node_sqlite3.node'),
ignored: false,
name: 'sqlite3',
modulePath: path.normalize('node_modules/sqlite3'),
resolved: true,
version: '3.1.4',
extractPath: path.normalize('~/.tessel/binaries/sqlite3-3.1.4-Release'),
});
});
deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync(), {}).then(() => {
// 2 calls: 1 call for each try/catch fs.copySync
// 1 call: copy the package.json
test.equal(fs.copySync.callCount, 3);
// THEIR PATH
test.equal(this.copySync.getCall(0).args[0].endsWith(path.normalize('node-v46-something-else/node_sqlite3.node')), true);
// OUR PATH
test.equal(this.copySync.getCall(1).args[0].endsWith(path.normalize('Release/node_sqlite3.node')), true);
test.done();
});
},
tryCatchTwiceAndFailGracefullyWithMissingBinaryMessage(test) {
test.expect(4);
this.copySync.restore();
this.copySync = sandbox.stub(fs, 'copySync').callsFake(() => {
throw new Error('E_THIS_IS_NOT_REAL');
});
this.forEach = sandbox.stub(Map.prototype, 'forEach').callsFake((handler) => {
handler({
binName: 'not-a-thing.node',
// This path doesn't match our precompiler's output paths.
// Will result in:
// ERR! Error: ENOENT: no such file or directory, stat '~/.tessel/binaries/not-a-thing-3.1.4-Release/node-v46-something-else/not-a-thing.node'
buildPath: path.normalize('/lib/binding/node-v46-something-else/'),
buildType: 'Release',
globPath: path.normalize('node_modules/not-a-thing/lib/binding/node-v46-something-else/not-a-thing.node'),
ignored: false,
name: 'not-a-thing',
modulePath: path.normalize('node_modules/not-a-thing'),
resolved: true,
version: '3.1.4',
extractPath: path.normalize('~/.tessel/binaries/not-a-thing-3.1.4-Release'),
});
});
this.error = sandbox.stub(log, 'error');
this.logMissingBinaryModuleWarning = sandbox.stub(deployment.js, 'logMissingBinaryModuleWarning');
deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync(), {}).then(() => {
// 2 calls: 1 call for each try/catch fs.copySync
test.equal(this.copySync.callCount, 2);
// Result of failing both attempts to copy
test.equal(this.logMissingBinaryModuleWarning.callCount, 1);
test.equal(this.error.callCount, 1);
test.equal(String(this.error.lastCall.args[0]).includes('E_THIS_IS_NOT_REAL'), true);
test.done();
});
}
};
exports['deploy.createShellScript'] = {
setUp(done) {
this.info = sandbox.stub(log, 'info');
this.tessel = TesselSimulator();
done();
},
tearDown(done) {
this.tessel.mockClose();
sandbox.restore();
done();
},
remoteShellScriptPathIsNotPathNormalized(test) {
test.expect(2);
this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => {
callback(null, this.tessel._rps);
this.tessel._rps.emit('close');
});
var opts = {
lang: deployment.js,
resolvedEntryPoint: 'foo',
binopts: [],
subargs: [],
};
deploy.createShellScript(this.tessel, opts).then(() => {
test.deepEqual(this.exec.firstCall.args[0], ['dd', 'of=/app/start']);
test.deepEqual(this.exec.lastCall.args[0], ['chmod', '+x', '/app/start']);
test.done();
});
},
remoteShellScriptPathIsNotPathNormalizedWithSubargs(test) {
test.expect(2);
this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => {
callback(null, this.tessel._rps);
this.tessel._rps.emit('close');
});
var opts = {
lang: deployment.js,
resolvedEntryPoint: 'foo',
binopts: ['--harmony'],
subargs: ['--key=value'],
};
deploy.createShellScript(this.tessel, opts).then(() => {
test.deepEqual(this.exec.firstCall.args[0], ['dd', 'of=/app/start']);
test.deepEqual(this.exec.lastCall.args[0], ['chmod', '+x', '/app/start']);
test.done();
});
}
};
// Test dependencies are required and exposed in common/bootstrap.js
exports['deployment.js.lists'] = {
setUp(done) {
done();
},
tearDown(done) {
done();
},
checkIncludes(test) {
test.expect(1);
var includes = [
'node_modules/**/aws-sdk/apis/*.json',
'node_modules/**/mime/types/*.types',
'node_modules/**/negotiator/**/*.js',
'node_modules/**/socket.io-client/socket.io.js',
'node_modules/**/socket.io-client/dist/socket.io.min.js',
'node_modules/**/socket.io-client/dist/socket.io.js',
];
test.deepEqual(lists.includes, includes);
test.done();
},
checkIgnores(test) {
test.expect(1);
var ignores = [
'node_modules/**/tessel/**/*',
];
test.deepEqual(lists.ignores, ignores);
test.done();
},
checkCompression(test) {
test.expect(1);
/*
This test just ensures that no one accidentally
messes up the contents of the deploy-lists file,
specifically for the compression options field
*/
var compressionOptions = {
extend: {
compress: {
keep_fnames: true
},
mangle: {}
},
};
test.deepEqual(lists.compressionOptions, compressionOptions);
test.done();
}
};
exports['deployment.js.postRun'] = {
setUp(done) {
this.info = sandbox.stub(log, 'info');
this.originalProcessStdinProperties = {
pipe: process.stdin.pipe,
setRawMode: process.stdin.setRawMode,
};
this.stdinPipe = sandbox.spy();
this.setRawMode = sandbox.spy();
process.stdin.pipe = this.stdinPipe;
process.stdin.setRawMode = this.setRawMode;
this.notRealTessel = {
connection: {
connectionType: 'LAN',
},
};
done();
},
tearDown(done) {
process.stdin.pipe = this.originalProcessStdinProperties.pipe;
process.stdin.setRawMode = this.originalProcessStdinProperties.setRawMode;
sandbox.restore();
done();
},
postRunLAN(test) {
test.expect(2);
deployment.js.postRun(this.notRealTessel, {
remoteProcess: {
stdin: null
}
}).then(() => {
test.equal(process.stdin.pipe.callCount, 1);
test.equal(process.stdin.setRawMode.callCount, 1);
test.done();
});
},
postRunUSB(test) {
test.expect(2);
this.notRealTessel.connection.connectionType = 'USB';
deployment.js.postRun(this.notRealTessel, {
remoteProcess: {
stdin: null
}
}).then(() => {
test.equal(process.stdin.pipe.callCount, 0);
test.equal(process.stdin.setRawMode.callCount, 0);
test.done();
});
},
};
exports['deployment.js.logMissingBinaryModuleWarning'] = {
setUp(done) {
this.warn = sandbox.stub(log, 'warn');
this.details = {
binName: 'compiled-binary.node',
buildPath: path.normalize('/build/Release/node-v46-FAKE_PLATFORM-FAKE_ARCH/'),
buildType: 'Release',
globPath: path.normalize('node_modules/compiled-binary/build/Release/node-v46-FAKE_PLATFORM-FAKE_ARCH/compiled-binary.node'),
ignored: false,
name: 'compiled-binary',
modulePath: path.normalize('node_modules/compiled-binary'),
resolved: true,
version: '2.0.6',
extractPath: path.normalize('~/.tessel/binaries/compiled-binary-2.0.6-Release-node-v46-linux-mipsel')
};
done();
},
tearDown(done) {
sandbox.restore();
done();
},
callsThroughToLogWarn(test) {
test.expect(1);
deployment.js.logMissingBinaryModuleWarning(this.details);
test.equal(this.warn.callCount, 1);
test.done();
},
includesModuleNameAndVersion(test) {
test.expect(1);
deployment.js.logMissingBinaryModuleWarning(this.details);
var output = this.warn.lastCall.args[0];
test.equal(output.includes('Pre-compiled module is missing: [email protected]'), true);
test.done();
},
};
exports['deployment.js.minimatch'] = {
setUp(done) {
done();
},
tearDown(done) {
done();
},
callsThroughToMinimatch(test) {
test.expect(1);
const result = deployment.js.minimatch('', '', {});
test.equal(result, true);
test.done();
},
};
|
import test from 'ava';
import escapeStringRegexp from './index.js';
test('main', t => {
t.is(
escapeStringRegexp('\\ ^ $ * + ? . ( ) | { } [ ]'),
'\\\\ \\^ \\$ \\* \\+ \\? \\. \\( \\) \\| \\{ \\} \\[ \\]'
);
});
test('escapes `-` in a way compatible with PCRE', t => {
t.is(
escapeStringRegexp('foo - bar'),
'foo \\x2d bar'
);
});
test('escapes `-` in a way compatible with the Unicode flag', t => {
t.regex(
'-',
new RegExp(escapeStringRegexp('-'), 'u')
);
});
|
const { InventoryError,
NotFoundError } = require('../../errors')
const checkExists = (data) => {
return (entity) => {
if (!entity) throw new NotFoundError(`${data} not found`)
return entity
}
}
module.exports = (sequelize, DataTypes) => {
const Pokemon = sequelize.define('Pokemon', {
name: DataTypes.STRING,
price: DataTypes.FLOAT,
stock: DataTypes.INTEGER
}, { tableName: 'pokemons' })
Pokemon.getByIdWithLock = function (pokemonId, transaction) {
return Pokemon.findOne({
where: {
id: pokemonId
},
lock: {
level: transaction.LOCK.UPDATE
}
})
}
Pokemon.getByName = function (name) {
return Pokemon.findOne({
where: {
name
}
}).then(checkExists(name))
}
Pokemon.prototype.decreaseStock = function (quantity) {
if (this.stock < quantity) {
return Promise.reject(new InventoryError(this.name, this.stock))
}
this.stock -= quantity
return this.save()
}
Pokemon.prototype.increaseStock = function (quantity) {
this.stock += quantity
return this.save()
}
return Pokemon
}
|
import hbs from 'htmlbars-inline-precompile';
import { moduleForComponent, test } from 'ember-qunit';
moduleForComponent('advanced-form/integer', {
integration: true
});
test('Render component with attributes', function(assert) {
this.render(
hbs`{{advanced-form/integer min=10 max=20 value=5}}`
);
var $componentInput = this.$('.integer input');
assert.equal($componentInput.val(), '10');
});
|
import React from 'react'
import { Hero } from '../../components'
const HeroContainer = () => (
<Hero />
)
export default HeroContainer
|
'use strict';
let sounds = new Map();
let playSound = path => {
let sound = sounds.get(path);
if (sound) {
sound.play();
} else {
sound = new Audio(path);
sound.play();
}
};
export default playSound;
|
/**
* Wheel, copyright (c) 2017 - present by Arno van der Vegt
* Distributed under an MIT license: https://arnovandervegt.github.io/wheel/license.txt
**/
const testLogs = require('../../utils').testLogs;
describe(
'Test repeat',
() => {
testLogs(
it,
'Should repeat ten times',
[
'proc main()',
' number i',
' i = 0',
' repeat',
' addr i',
' mod 0, 1',
' i += 1',
' if i > 9',
' break',
' end',
' end',
'end'
],
[
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
]
);
testLogs(
it,
'Should break to outer loop',
[
'proc main()',
' number x = 0',
' repeat loop',
' x += 1',
' repeat',
' x += 1',
' if (x > 10)',
' break loop',
' end',
' addr x',
' mod 0, 1',
' end',
' end',
'end'
],
[
2, 3, 4, 5, 6, 7, 8, 9, 10
]
);
}
);
|
var mongoose = require('mongoose');
var statuses = ['open', 'closed', 'as_expected'];
var priorities = ['major','regular','minor','enhancement'];
var Comment = new mongoose.Schema(
{
comment: String,
username: String,
name: String,
dca: {type: Date, default: Date.now}
}
);
var Bug = new mongoose.Schema(
{
id: {type: String},
name: {type: String, required: true},
desc: String,
status: {type: String, default: 'open'},
priority: {type: String, default: 'regular'},
username: { type: String, required: true},
reported_by: {type: String},
company: {type: String, required: true},
comments: [Comment],
dca: {type: Date, default: Date.now},
dua: Date
}
);
Bug.pre('save', function(next) {
if (this.id === undefined) {
this.id = (new Date()).getTime().toString();
}
now = new Date();
this.dua = now;
next();
});
module.exports = mongoose.model('Bug', Bug);
|
/*** AppView ***/
define(function(require, exports, module) {
var View = require('famous/core/View');
var Surface = require('famous/core/Surface');
var Transform = require('famous/core/Transform');
var StateModifier = require('famous/modifiers/StateModifier');
var SlideshowView = require('views/SlideshowView');
function ProjectView() {
View.apply(this, arguments);
}
ProjectView.prototype = Object.create(View.prototype);
ProjectView.prototype.constructor = ProjectView;
ProjectView.DEFAULT_OPTIONS = {};
module.exports = ProjectView;
});
|
"use strict";
var ArrayCollection_1 = require('./ArrayCollection');
exports.ArrayCollection = ArrayCollection_1.ArrayCollection;
var ArrayList_1 = require('./ArrayList');
exports.ArrayList = ArrayList_1.ArrayList;
var SequenceBase_1 = require('./SequenceBase');
exports.SequenceBase = SequenceBase_1.SequenceBase;
var Buckets_1 = require('./Buckets');
exports.Buckets = Buckets_1.Buckets;
var Collection_1 = require('./Collection');
exports.Collection = Collection_1.Collection;
var Dictionary_1 = require('./Dictionary');
exports.Dictionary = Dictionary_1.Dictionary;
exports.Pair = Dictionary_1.Pair;
var Hash_1 = require('./Hash');
exports.HashFunc = Hash_1.HashFunc;
exports.DefaultHashFunc = Hash_1.DefaultHashFunc;
var HashSet_1 = require('./HashSet');
exports.HashSet = HashSet_1.HashSet;
var Iterable_1 = require('./Iterable');
exports.Iterable = Iterable_1.Iterable;
var LinkedList_1 = require('./LinkedList');
exports.LinkedList = LinkedList_1.LinkedList;
var Native_1 = require('./Native');
exports.NativeIndex = Native_1.NativeIndex;
exports.NativeMap = Native_1.NativeMap;
var Sequence_1 = require('./Sequence');
exports.Sequence = Sequence_1.Sequence;
var Stack_1 = require('./Stack');
exports.Stack = Stack_1.Stack;
var Util_1 = require('./Util');
exports.Util = Util_1.Util;
//# sourceMappingURL=index.js.map |
'use strict'
var solc = require('solc/wrapper')
var compileJSON = function () { return '' }
var missingInputs = []
module.exports = function (self) {
self.addEventListener('message', function (e) {
var data = e.data
switch (data.cmd) {
case 'loadVersion':
delete self.Module
// NOTE: workaround some browsers?
self.Module = undefined
compileJSON = null
self.importScripts(data.data)
var compiler = solc(self.Module)
compileJSON = function (input) {
try {
return compiler.compileStandardWrapper(input, function (path) {
missingInputs.push(path)
return { 'error': 'Deferred import' }
})
} catch (exception) {
return JSON.stringify({ error: 'Uncaught JavaScript exception:\n' + exception })
}
}
self.postMessage({
cmd: 'versionLoaded',
data: compiler.version()
})
break
case 'compile':
missingInputs.length = 0
self.postMessage({cmd: 'compiled', job: data.job, data: compileJSON(data.input), missingInputs: missingInputs})
break
}
}, false)
}
|
//Express, Mongo & Environment specific imports
var express = require('express');
var morgan = require('morgan');
var serveStatic = require('serve-static');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var compression = require('compression');
var errorHandler = require('errorhandler');
var mongo = require('./api/config/db');
var env = require('./api/config/env');
// Controllers/Routes import
var BookController = require('./api/controller/BookController');
//MongoDB setup
mongo.createConnection(env.mongoUrl);
//Express setup
var app = express();
//Express middleware
app.use(morgan('short'));
app.use(serveStatic(__dirname + '/app'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(compression());
var environment = process.env.NODE_ENV || 'development';
if ('development' == environment) {
app.use(errorHandler({ dumpExceptions: true, showStack: true }));
var ImportController = require('./api/controller/ImportController');
app.get('/import', ImportController.import);
app.get('/import/reset', ImportController.reset);
}
// Route definitions
app.get('/api/books', BookController.list);
app.get('/api/books/:id', BookController.show);
app.post('api/books', BookController.create);
app.put('/api/books/:id', BookController.update);
app.delete('/api/books/:id', BookController.remove);
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Books app listening at http://%s:%s', host, port);
console.log("Configured MongoDB URL: " + env.mongoUrl);
});
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require("@angular/core");
var ConversationHeaderComponent = (function () {
function ConversationHeaderComponent() {
}
ConversationHeaderComponent.prototype.ngOnInit = function () {
};
__decorate([
core_1.Input(),
__metadata('design:type', Object)
], ConversationHeaderComponent.prototype, "conversationDetailItem", void 0);
ConversationHeaderComponent = __decorate([
core_1.Component({
selector: 'ngm-conversation-header',
styleUrls: ['./conversation-header.component.scss'],
templateUrl: './conversation-header.component.html'
}),
__metadata('design:paramtypes', [])
], ConversationHeaderComponent);
return ConversationHeaderComponent;
}());
exports.ConversationHeaderComponent = ConversationHeaderComponent;
//# sourceMappingURL=conversation-header.component.js.map |
const describe = require("mocha").describe;
const it = require("mocha").it;
const assert = require("chai").assert;
const HttpError = require("./HttpError");
describe("HttpError", function () {
it("should be instance of Error", function () {
const testSubject = new HttpError();
assert.isOk(testSubject instanceof Error);
});
});
|
/**
* jQuery object.
* @external jQuery
* @see {@link http://api.jquery.com/jQuery/}
*/
/**
* The jQuery plugin namespace.
* @external "jQuery.fn"
* @see {@link http://docs.jquery.com/Plugins/Authoring The jQuery Plugin Guide}
*/
/**
* The plugin global configuration object.
* @external "jQuery.vulcanup"
* @property {String} version - The plugin version.
* @property {settings} defaults - The default configuration.
* @property {Object} templates - The default templates.
*/
require('./jup-validation');
const templates = require('./templates');
const constants = require('./constants');
const defaults = require('./defaults');
const methods = require('./methods');
const utils = require('./utils');
const version = '1.0.0-beta';
$(document).on('drop dragover', function (e) {
e.preventDefault();
});
/**
* Invoke on a `<input type="file">` to set it as a file uploader.
*
* By default the configuration is {@link settings} but you can pass an object
* to configure it as you want.
*
* Listen to event changes on the same input, review demo to see how to implement them
* and what parameters they receive:
*
* **`vulcanup-val`** - On validation error. Receives as parameter an object with the error message.
*
* **`vulcanup-upload`** - On file started to being uploaded.
*
* **`vulcanup-progress`** - On upload progress update. Receives as parameter the progress number.
*
* **`vulcanup-error`** - On server error. Receives as parameter an object with details.
*
* **`vulcanup-change`** - On file change. This is triggered when the user uploads
* a file in the server, when it is deleted or when it is changed programmatically.
* Receives as parameter an object with the new file details.
*
* **`vulcanup-delete`** - On file deleted. Receives as parameter the deleted file details.
*
* **`vulcanup-uploaded`** - On file uploaded in the server.
*
* **`vulcanup-complete`** - On upload process completed. This is fired when the
* XHR is finished, regardless of fail or success.
*
* @function external:"jQuery.fn".vulcanup
*
* @param {settings} [settings] - Optional configuration.
*
* @example
* $('input[type=file]').vulcanup({
* url: '/initial/file/url.ext'
* });
*/
jQuery.fn.vulcanup = function (settings) {
'use strict';
const $input = $(this).first();
if (typeof settings === 'string') {
if (methods[settings]) {
if (!$input.data(`vulcanup-config`)) {
throw new Error(`vulcanup element is not instantiated, cannot invoke methods`);
}
const args = Array.prototype.slice.call(arguments, 1);
return methods[settings].apply($input, args);
} else {
throw new Error(`vulcanup method unrecognized "${settings}".`);
}
}
if ($input.data(`vulcanup-config`)) return this;
//
// CONFIGURATION
//
let id = $input.attr('id');
if (!id) {
id = 'vulcanup-'+ (new Date()).getTime();
$input.attr('id', id);
}
if ($input.attr('multiple') !== undefined) {
throw new Error('Input type file cannot be multiple');
}
const conf = $.extend(true, {}, defaults, settings, {
_id: id,
fileupload: {
fileInput: $input
}
});
// File type validation.
if (conf.types[conf.type]) {
conf._type = conf.types[conf.type];
conf.fileupload.acceptFileTypes = conf._type.formats;
} else {
throw new Error('A valid type of file is required');
}
$input.data(`vulcanup-config`, conf);
//
// DOM
//
const $container = $(utils.format(templates.main, conf));
const $validations = $(utils.format(templates.validations, conf));
const $remove = $container.find('.vulcanup__remove');
const $dropzone = $container.find('.vulcanup__dropzone');
const $msg = $container.find('.vulcanup__msg');
$remove.attr('title', utils.format(conf.messages.REMOVE, conf._type));
$input.addClass('vulcanup-input vulcanup-input__hidden');
$input.after($container);
$container.after($validations);
conf.fileupload.dropZone = $container;
conf._$validations = $validations;
conf._$container = $container;
conf._$dropzone = $dropzone;
conf._$msg = $msg;
if (conf.type === 'image') {
$container.addClass('vulcanup_isimage');
}
if (conf.imageContain) {
$container.addClass('vulcanup_isimagecontain');
}
if (!conf.enableReupload) {
$container.addClass('vulcanup_noreupload');
}
if (conf.canRemove) {
$container.addClass('vulcanup_canremove');
}
//
// EVENTS
//
$input.
// On click.
on('click', function (e) {
if (conf._uploading || (conf._url && !conf.enableReupload)) {
e.preventDefault();
return false;
}
}).
// On user error.
on('fileuploadprocessfail', function (e, info) {
const err = info.files[0].error;
methods.setValidation.call($input, err);
}).
// On send.
on('fileuploadsend', function (e, data) {
methods.setUploading.call($input);
}).
// On server progress.
on('fileuploadprogressall', function (e, data) {
const progress = parseInt(data.loaded / data.total * 100, 10);
methods.updateProgress.call($input, progress);
}).
// On server success.
on('fileuploaddone', function (e, data) {
const files = data.files;
const result = data.result;
if (conf.handler) {
const info = conf.handler(result);
if (typeof info !== 'object') {
methods.setError.call($input);
throw new Error('handler should return file object info');
}
if (typeof info.url !== 'string') {
methods.setError.call($input);
throw new Error('handler should return file url property');
}
methods.setUploaded.call($input, {
url: info.url,
file: files[0]
});
}
else if (result && result.files && result.files.length) {
methods.setUploaded.call($input, {
url: result.files[0].url,
file: files[0]
});
}
else {
methods.setError.call($input);
}
}).
// On server error.
on('fileuploadfail', function (e, data) {
methods.setError.call($input);
});
$dropzone.
on('dragenter dragover', e => {
$container.addClass('vulcanup_dragover');
}).
on('dragleave drop', e => {
$container.removeClass('vulcanup_dragover');
});
$container.find('.vulcanup__remove').on('click', function (e) {
e.preventDefault();
$input.trigger(`vulcanup-delete`, { url: conf._url, name: conf._name });
$input.trigger(`vulcanup-change`, { url: null, name: null });
methods.updateProgress.call($input, 0, {silent: true});
methods.setUpload.call($input);
return false;
});
//
// CREATING AND SETTING
//
$input.fileupload(conf.fileupload);
if (conf.url) {
methods.setUploaded.call(this, {
url: conf.url,
name: conf.name,
initial: true
});
} else {
methods.setUpload.call(this);
}
return this;
};
module.exports = jQuery.vulcanup = { version, defaults, templates };
|
const test = require('tape')
const nlp = require('../_lib')
test('match min-max', function(t) {
let doc = nlp('hello1 one hello2').match('#Value{7,9}')
t.equal(doc.out(), '', 'match was too short')
doc = nlp('hello1 one two three four five hello2').match('#Value{3}')
t.equal(doc.out(), 'one two three', 'exactly three')
doc = nlp('hello1 one two three four five hello2').match('#Value{3,3}')
t.equal(doc.out(), 'one two three', 'still exactly three')
doc = nlp('hello1 one two three four five hello2').match('#Value{3,}')
t.equal(doc.out(), 'one two three four five', 'minimum three')
doc = nlp('hello1 one two three four five hello2').match('hello1 .{3}')
t.equal(doc.out(), 'hello1 one two three', 'unspecific greedy exact length')
doc = nlp('hello1 one two').match('hello1 .{3}')
t.equal(doc.out(), '', 'unspecific greedy not long enough')
t.end()
})
|
function ones(rows, columns) {
columns = columns || rows;
if (typeof rows === 'number' && typeof columns === 'number') {
const matrix = [];
for (let i = 0; i < rows; i++) {
matrix.push([]);
for (let j = 0; j < columns; j++) {
matrix[i].push(1);
}
}
return matrix;
}
throw new TypeError('Matrix dimensions should be integers.');
}
module.exports = ones;
|
// http://www.w3.org/2010/05/video/mediaevents.html
var poppy = popcorn( [ vid_elem_ref | 'id_string' ] );
poppy
// pass-through video control methods
.load()
.play()
.pause()
// property setters
.currentTime( time ) // skip forward or backwards `time` seconds
.playbackRate( rate )
.volume( delta )
.mute( [ state ] )
// sugar?
.rewind() // to beginning + stop??
.loop( [ state ] ) // toggle looping
// queuing (maybe unnecessary):
// enqueue method w/ optional args
.queue( 'method', args )
// enqueue arbitrary callback
.queue(function(next){ /* do stuff */ next(); })
// clear the queue
.clearQueue()
// execute arbitrary code @ time
poppy.exec( 1.23, function(){
// exec code
});
// plugin factory sample
popcorn.plugin( 'myPlugin' [, super_plugin ], init_options );
// call plugin (defined above)
poppy.myPlugin( time, options );
// define subtitle plugin
popcorn.plugin( 'subtitle', {
});
poppy
.subtitle( 1.5, {
html: '<p>SUPER AWESOME MEANING</p>',
duration: 5
})
.subtitle({
start: 1.5,
end: 6.5,
html: '<p>SUPER AWESOME MEANING</p>'
})
.subtitle([
{
start: 1.5,
html: '<p>SUPER AWESOME MEANING</p>'
},
{
start: 2.5,
end: 3.5,
html: '<p>OTHER NEAT TEXT</p>'
}
])
.data([
{
subtitle: [
{
start: 1.5,
html: '<p>SUPER AWESOME MEANING</p>'
},
{
start: 2.5,
end: 3.5,
html: '<p>OTHER NEAT TEXT</p>'
}
]
}
]);
// jQuery-dependent plugin, using $.ajax - extend popcorn.data
popcorn.plugin( 'data', popcorn.data, {
_setup: function( options ) {
// called when plugin is first registered (?)
},
_add: function( options ) {
// called when popcorn.data is called
// this == plugin (?)
if ( typeof options === 'string' ) {
$.ajax({
url: options
// stuff
});
} else {
return this.super.data.apply( this, arguments );
}
}
});
poppy.data( '/data.php' ) // data.php returns JSON?
/*
poppy.twitter( dom_elem | 'id_of_dom_elem', options ); // multiple twitters?? FAIL
poppy.twitter( 'load', options );
*/
var widget1 = $(dom_elem).twitter( options ); // ui widget factory initializes twitter widget
poppy.jQuery( 5.9, {
elem: widget1,
method: 'twitter',
args: [ 'search', '@cowboy' ]
})
poppy.jQuery( time, selector, methodname [, args... ] );
poppy.jQuery( 5.9, widget1, 'twitter', 'search', '@cowboy' );
poppy.jQuery( 5.9, '.div', 'css', 'color', 'red' );
poppy.jQuery( 5.9, '#form', 'submit' );
// sugar methods for jQuery
$(selector).popcorn( time, methodname [, args... ] );
$(selector).popcorn( time, fn );
// another idea, using jQuery special events api
$(selector).bind( 'popcorn', { time: 5.9 }, function(e){
$(this).css( 'color', 'red' );
});
// does $.fn[ methodname ].apply( $(selector), args );
|
define(['myweb/jquery'], function ($) {
'use strict';
var error = function (message) {
$('.form-feedback').removeClass('form-success').addClass('form-error').text(message).fadeIn(200);
};
var success = function (message) {
$('.form-feedback').removeClass('form-error').addClass('form-success').text(message).fadeIn(200);
};
var clear = function () {
$('.form-feedback').hide().removeClass('form-success form-error').empty();
};
return {
error: error,
success: success,
clear: clear
};
});
|
const gulp = require('gulp'),
zip = require('gulp-zip');
/**
* Metadata about the plugin.
*
* @var object
*/
const plugin = {
name: 'example-plugin',
directory: '.'
}
gulp.task('distribute', function () {
let paths = [
'vendor/twig/**/*',
'vendor/composer/**/*',
'vendor/autoload.php',
'src/**/*'
]
let src = gulp.src(paths, {
base: './'
})
let archive = src.pipe(zip(`${plugin.name}.zip`))
return archive.pipe(gulp.dest(plugin.directory))
});
|
/*
* This code it's help you to check JS plugin function (e.g. jQuery) exist.
* When function not exist, the code will auto reload JS plugin from your setting.
*
* plugin_name: It's your plugin function name (e.g. jQuery). The type is string.
* reload_url: It's your reload plugin function URL. The type is string.
*
* Copyright 2015, opoepev (Matt, Paul.Lu, Yi-Chun Lu)
* Free to use and abuse under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*/
//Main code
var checkJSPluginExist = function (plugin_name, reload_url, depend_plugin_name) {
//window[plugin_name] || document.write('<script src="' + reload_url + '">\x3C/script>');
if (typeof depend_plugin_name !== 'undefined') {
if (typeof window[depend_plugin_name][plugin_name] !== "function") {
var tag = document.createElement('script');
tag.src = reload_url;
var headerElementTag = document.getElementsByTagName('head')[0];
headerElementTag.appendChild(tag);
return false;
}
} else {
if (typeof window[plugin_name] !== "function") {
var tag = document.createElement('script');
tag.src = reload_url;
var headerElementTag = document.getElementsByTagName('head')[0];
headerElementTag.appendChild(tag);
return false;
}
}
return true;
};
|
const ASSERT = require('assert');
describe('SSL Specs', function () {
const PATH = require('path');
let Acts = require('./../index');
let testcert = PATH.join(__dirname, 'certs', 'test.cert');
let testkey = PATH.join(__dirname, 'certs', 'test.key');
it('boot with testcertificate without chain', function() {
return new Promise((resolve, reject) => {
try {
Acts.createServer(__dirname, {
server: {
address: 'localhost',
port: 8086,
ssl: {
usessl: true,
redirectnonsslrequests: true,
privatekey: testkey,
certificate: testcert,
certificationauthority: []
}
}
});
Acts.start(function () {
Acts.shutdown();
resolve();
});
} catch (e) {
reject(e);
}
});
});
it('boot with testcertificate with chain', function() {
return new Promise((resolve, reject) => {
try {
Acts.createServer(__dirname, {
server: {
address: 'localhost',
port: 8086,
ssl: {
usessl: true,
redirectnonsslrequests: true,
privatekey: testkey,
certificate: testcert,
certificationauthority: [testcert]
}
}
});
Acts.start(function () {
Acts.shutdown();
resolve();
});
} catch (e) {
reject(e);
}
});
});
});
|
const path = require('path');
const inquirer = require('inquirer');
const yargs = require('yargs');
const {
sanitizeArgs,
ui,
invalidGitRepo,
ingredients,
addIngredients,
promiseTimeout
} = require('../common');
const {
cloneRepo,
deleteGitFolder,
establishLocalGitBindings,
addGitRemote,
pushLocalGitToOrigin,
stageChanges
} = require('../tasks/git');
const {
createEnvFile,
checkForExistingFolder,
executeCommand
} = require('../tasks/filesystem');
const {
readAndInitializeProjectRecipe,
bakeProject
} = require('../tasks/project');
const getDefaultProjectName = repoURL => {
let projectName = path.basename(repoURL).toLowerCase();
projectName = projectName.replace(/\.git$/, '');
projectName = projectName.replace(/\.+/g, '-');
projectName = projectName.replace(/-+/g, '-');
return projectName;
};
const getValidProjectName = name => {
return name
.replace(/\W+/g, ' ') // alphanumerics only
.trimRight()
.replace(/ /g, '-')
.toLowerCase();
};
module.exports = {
command: 'prepare',
desc:
'creates a new scaffold from an ezbake project in a specified Git source',
builder: yargs => {
return yargs
.option('n', {
alias: 'projectName',
describe: 'Alphanumeric project name'
})
.option('r', {
alias: 'gitRepoURL',
describe: 'The URL of the source Git repo to ezbake'
})
.option('b', {
alias: 'gitRepoBranch',
describe:
'The branch on the source repo which contains the .ezbake folder'
})
.option('o', {
alias: 'gitOriginURL',
describe:
'The URL of the Git destination repo to push to as a remote origin'
})
.option('s', {
alias: 'simple',
describe:
'Flag to indicate Whether to ask for authorName, authorEmail and projectDescription',
type: 'boolean',
default: false
});
},
handler: async argv => {
// console.log(argv);
let args = sanitizeArgs(argv);
// Sanitize Project Name, if passed in as parameter
if (args['projectName']) {
args['projectName'] = getValidProjectName(args['projectName']);
}
let baseIngredients = ingredients;
const TIMEOUT = 20000;
try {
// Mise en place
baseIngredients = baseIngredients.filter(ingredient => {
if (ingredient.name === 'projectName') {
// Override default project name
if (!args[ingredient.name] && args['gitOriginURL']) {
ingredient.default = getDefaultProjectName(args['gitOriginURL']);
}
}
// Exclude fields for which the values have already been provided with the command
if (args[ingredient.name]) {
console.log(`> ${ingredient.name}: ${args[ingredient.name]}`);
return false;
}
// Exclude some fields in case of simple setup
if (
args['simple'] &&
['authorName', 'authorEmail', 'projectDescription'].includes(
ingredient.name
)
) {
return false;
}
return true;
});
let projectIngredients = await inquirer.prompt(baseIngredients);
projectIngredients = Object.assign(projectIngredients, args);
projectIngredients.projectName = await checkForExistingFolder(
ui,
projectIngredients.projectName
);
// Check if the repo is valid
await cloneRepo(
ui,
projectIngredients.gitRepoURL,
projectIngredients.gitRepoBranch,
projectIngredients.projectName
).catch(invalidGitRepo);
let recipe = readAndInitializeProjectRecipe(
ui,
projectIngredients.projectName,
projectIngredients.gitRepoURL,
projectIngredients.gitRepoBranch
);
// Remove git bindings
await promiseTimeout(
TIMEOUT,
deleteGitFolder(ui, projectIngredients.projectName)
).catch(err => {
throw new Error(`Error: ${err} while deleting cloned Git folder.`);
});
// Ask away!
let ingredients = await inquirer.prompt(recipe.ingredients);
let allIngredients = Object.assign(
{
...projectIngredients,
...ingredients
},
{
projectNameDocker: projectIngredients.projectName.replace(/-/g, '_'),
projectAuthor:
projectIngredients.authorName +
' <' +
projectIngredients.authorEmail +
'>'
}
);
bakeProject(ui, allIngredients, recipe);
// .env file setup
if (recipe.env) {
let envAnswers = await inquirer.prompt(recipe.env);
createEnvFile(ui, projectIngredients.projectName, envAnswers);
}
// Finally, establish a local .git binding
// And optionally add the specified remote
await promiseTimeout(
TIMEOUT,
establishLocalGitBindings(ui, projectIngredients.projectName)
).catch(err => {
throw new Error(`Error: ${err} while establishing Git bindings.`);
});
if (projectIngredients.gitOriginURL) {
await addGitRemote(
ui,
projectIngredients.gitOriginURL,
projectIngredients.projectName
);
}
if (recipe.icing && Array.isArray(recipe.icing)) {
ui.log.write(`. Applying icing...`);
let projectDir = path.join(
process.cwd(),
`./${projectIngredients.projectName}`
);
process.chdir(projectDir);
for (let icing of recipe.icing) {
ui.log.write(` . ${icing.description}`);
if (Array.isArray(icing.cmd)) {
await executeCommand(
addIngredients(icing.cmd, allIngredients),
icing.cmdOptions
);
}
}
ui.log.write(`. Icing applied!`);
}
// Finally, stage and commit the changes.
// And optionally push to a remote repo
await stageChanges(
ui,
'[ezbake] - initial commit',
projectIngredients.projectName
);
if (projectIngredients.gitOriginURL) {
await pushLocalGitToOrigin(
ui,
projectIngredients.gitOriginURL,
projectIngredients.projectName
);
}
ui.log.write(`. Your project is ready!`);
process.exit(0);
} catch (error) {
ui.log.write(error.message);
process.exit(-1);
}
}
};
|
import React from 'react'
import { useSelector } from 'react-redux'
import Container from 'react-bootstrap/Container'
import Row from 'react-bootstrap/Row'
import Col from 'react-bootstrap/Col'
import MoveSelector from '../containers/move-selector'
import Footer from '../containers/footer'
import Player from '../containers/player'
import WelcomeDlg from '../containers/welcome-dlg'
import History from '../features/history'
import { GlobalState } from '../reducers/consts'
const Game = () => {
const showWelcome = useSelector(state => state.globalState === GlobalState.New)
return (
<>
<WelcomeDlg show={showWelcome} />
<Container>
<Row>
<Col>
<Player color='white' />
</Col>
<Col>
<Player color='black' right />
</Col>
</Row>
<Row>
<Col className='px-0'>
<MoveSelector />
</Col>
<Col sm='3' className='pr-0 pl-1'>
<History />
</Col>
</Row>
<Row>
<Col className='px-0'>
<Footer />
</Col>
</Row>
</Container>
</>
)
}
export default Game
|
const fs = require('fs');
const path = require('path');
class Service {
constructor() {
this.getFileRecursevly = this.getFileRecursevly.bind(this);
this.getFiles = this.getFiles.bind(this);
}
getFileRecursevly(folderPath, shortPath = '') {
var files = [];
var folder = fs.readdirSync(path.resolve(__dirname, folderPath));
var x = folder.forEach(file => {
var filePath = path.resolve(folderPath, file);
if (fs.lstatSync(filePath).isDirectory()) {
files.push({
folder: file,
files: this.getFileRecursevly(filePath, file)
})
} else {
files.push({ file: file, folder: shortPath });
}
})
return files;
}
getFiles(path) {
return new Promise((resolve, reject) => {
var files = this.getFileRecursevly(path)
resolve(files)
})
}
}
module.exports = Service; |
import DateParser from '../date-parser.js';
import ParsedInfo from '../../parsed-info';
import moment from 'moment';
Date.now = jest.fn(() => 1527130897000)
test('Parses 12 Jan', () => {
const dateParser = new DateParser();
dateParser.parse('12 Jan', ParsedInfo);
const { value, startIndex, endIndex } = ParsedInfo.dateParser;
expect({ value: value.unix(), startIndex, endIndex })
.toEqual({ value: 1515695400, startIndex: 0, endIndex: 6 });
});
test('Parses 22 May', () => {
const dateParser = new DateParser();
dateParser.parse('22 May', ParsedInfo);
const { value, startIndex, endIndex } = ParsedInfo.dateParser;
expect({ value: value.unix(), startIndex, endIndex })
.toEqual({ value: 1526927400, startIndex: 0, endIndex: 6 });
});
|
exports.LOADING = "LOADING";
exports.ERROR = "ERROR";
exports.SUCCESS = "SUCCESS";
exports.FETCH = "FETCH";
exports.CREATE = "CREATE";
exports.UPDATE = "UPDATE";
exports.DELETE = "DELETE";
exports.SET_EDIT_MODE = "SET_EDIT_MODE";
exports.SET_ADD_MODE = "SET_ADD_MODE";
exports.CLOSE_FORM = "CLOSE_FORM";
exports.SET_PAGE = "SET_PAGE"
|
'use strict';
exports.ContainerBuilder = require('./CqrsContainerBuilder');
exports.EventStream = require('./EventStream');
exports.CommandBus = require('./CommandBus');
exports.EventStore = require('./EventStore');
exports.AbstractAggregate = require('./AbstractAggregate');
exports.AggregateCommandHandler = require('./AggregateCommandHandler');
exports.AbstractSaga = require('./AbstractSaga');
exports.SagaEventHandler = require('./SagaEventHandler');
exports.AbstractProjection = require('./AbstractProjection');
exports.InMemoryMessageBus = require('./infrastructure/InMemoryMessageBus');
exports.InMemoryEventStorage = require('./infrastructure/InMemoryEventStorage');
exports.InMemorySnapshotStorage = require('./infrastructure/InMemorySnapshotStorage');
exports.InMemoryView = require('./infrastructure/InMemoryView');
exports.getMessageHandlerNames = require('./utils/getMessageHandlerNames');
exports.subscribe = require('./subscribe');
|
'use strict';
var _ = require('./underscore-mixins.js');
var fnToNode = new Map();
exports.load = function (nodes, prefix) {
let uuid = require('uuid');
if (prefix != null && prefix.length > 0) {
prefix = prefix + ':';
} else {
prefix = '';
}
_(nodes).forEach(function (fn, name) {
if (_.isFunction(fn)) {
fnToNode.set(fn, {
name: prefix + name,
id: uuid.v4(),
fn: fn,
ingoingLinks: new Map(),
outgoingLinks: new Map(),
counter: 0
});
} else {
exports.load(fn, name);
}
});
};
exports.clone = function (fn, name) {
var node = fnToNode.get(fn);
var newNodeLoader = {};
newNodeLoader[name] = node.fn.bind({});
exports.load(newNodeLoader);
return newNodeLoader[name];
};
exports.debug = function () {
fnToNode.forEach(function (node) {
console.log(
_(Array.from(node.ingoingLinks.keys())).pluck('name'),
node.name,
_(Array.from(node.outgoingLinks.keys())).pluck('name')
);
});
};
var defaultLinkOptions = {
primary: true
};
exports.link = function (fn) {
var node = fnToNode.get(fn);
return {
to: function (toFn, options) {
options = _(options || {}).defaults(defaultLinkOptions);
var toNode = fnToNode.get(toFn);
toNode.ingoingLinks.set(node, options);
node.outgoingLinks.set(toNode, options);
}
};
};
exports.unlink = function (fn) {
var node = fnToNode.get(fn);
return {
from: function (fromFn) {
var fromNode = fnToNode.get(fromFn);
fromNode.ingoingLinks.delete(node);
node.outgoingLinks.delete(fromNode);
}
};
};
exports.remove = function (fn) {
var node = fnToNode.get(fn),
todo = [];
node.ingoingLinks.forEach(function (inOptions, inNode) {
todo.push(function () {
exports.unlink(inNode.fn).from(fn);
});
node.outgoingLinks.forEach(function (outOptions, outNode) {
todo.push(function () {
exports.unlink(fn).from(outNode.fn);
exports.link(inNode.fn).to(outNode.fn, outOptions);
});
});
});
_(todo).invoke('call');
};
exports.replace = function (fn) {
var node = fnToNode.get(fn),
todo = [];
return {
by: function (byFn) {
node.ingoingLinks.forEach(function (inOptions, inNode) {
todo.push(function () {
exports.unlink(inNode.fn).from(node.fn);
exports.link(inNode.fn).to(byFn, inOptions);
});
});
node.outgoingLinks.forEach(function (outOptions, outNode) {
todo.push(function () {
exports.unlink(node.fn).from(outNode.fn);
exports.link(byFn).to(outNode.fn, outOptions);
});
});
_(todo).invoke('call');
}
}
};
exports.before = function (fn) {
var node = fnToNode.get(fn),
todo = [];
return {
insert: function (beforeFn) {
node.ingoingLinks.forEach(function (inOptions, inNode) {
todo.push(function () {
exports.unlink(inNode.fn).from(node.fn);
exports.link(inNode.fn).to(beforeFn, inOptions);
});
});
todo.push(function () {
exports.link(beforeFn).to(node.fn);
});
_(todo).invoke('call');
}
};
};
exports.after = function (fn) {
var node = fnToNode.get(fn),
todo = [];
return {
insert: function (afterFn) {
node.outgoingLinks.forEach(function (outOptions, outNode) {
todo.push(function () {
exports.unlink(node.fn).from(outNode.fn);
exports.link(afterFn).to(outNode.fn, outOptions);
});
});
todo.push(function () {
exports.link(node.fn).to(afterFn);
});
_(todo).invoke('call');
}
};
};
var runEntryNode;
function linksToStream(links) {
let plumber = require('gulp-plumber');
return _(links).chain()
.pluck('fn')
.map(exports.run)
.compact()
.concatVinylStreams()
.value()
.pipe(plumber());
}
exports.run = function (fn) {
var result,
node = fnToNode.get(fn);
runEntryNode = runEntryNode || node;
if (node.lastResult != null) {
return node.lastResult;
}
var primaryStreams = [],
secondaryStreams = [];
node.ingoingLinks.forEach(function (options, node) {
if (options.primary) {
primaryStreams.push(node);
} else {
secondaryStreams.push(node);
}
});
var primaryStream = linksToStream(primaryStreams),
secondaryStream = linksToStream(secondaryStreams);
result = fn(primaryStream, secondaryStream);
if (runEntryNode === node) {
fnToNode.forEach(function (node) {
delete node.lastResult;
});
}
else {
node.lastResult = result;
}
return result;
};
function isNotAlone(node) {
return (node.ingoingLinks.size + node.outgoingLinks.size) > 0;
}
function isSource(node) {
return node.ingoingLinks.size === 0;
}
function isOutput(node) {
return node.outgoingLinks.size === 0;
}
exports.renderGraph = function (renderer, filepath, callback) {
let graphdot = require('./graphdot.js');
var graph = graphdot.digraph('one_gulp_streams_graph');
graph.set('label', 'one-gulp streams graph\n\n');
graph.set('fontname', 'sans-serif');
graph.set('fontsize', '20');
graph.set('labelloc', 't');
graph.set('pad', '0.5,0.5');
graph.set('nodesep', '0.3');
graph.set('splines', 'spline');
graph.set('ranksep', '1');
graph.set('rankdir', 'LR');
var promises = [];
fnToNode.forEach(function (node) {
var nodeOptions = {
label: node.name,
shape: 'rectangle',
fontname: 'sans-serif',
style: 'bold',
margin: '0.2,0.1'
};
if (isSource(node)) {
nodeOptions.shape = 'ellipse';
nodeOptions.color = 'lavender';
nodeOptions.fontcolor = 'lavender';
nodeOptions.margin = '0.1,0.1';
}
if (isOutput(node)) {
nodeOptions.color = 'limegreen';
nodeOptions.fontcolor = 'white';
nodeOptions.style = 'filled';
nodeOptions.margin = '0.25,0.25';
}
if (isNotAlone(node)) {
node.graphNode = graph.addNode(node.id, nodeOptions);
if (isSource(node)) {
var donePromise = new Promise(function (resolve, reject) {
node.fn()
.on('data', function () {
node.counter += 1;
node.graphNode.set('color', 'mediumslateblue');
node.graphNode.set('fontcolor', 'mediumslateblue');
node.graphNode.set('label', node.name + ' (' + node.counter + ')');
})
.on('error', reject)
.on('end', resolve);
});
promises.push(donePromise);
}
}
});
Promise.all(promises).then(function () {
fnToNode.forEach(function (node) {
node.ingoingLinks.forEach(function (options, linkedNode) {
var edgeOptions = {};
if (options.primary) {
edgeOptions.penwidth = '1.5';
} else {
edgeOptions.arrowhead = 'empty';
edgeOptions.style = 'dashed';
}
if (isSource(linkedNode)) {
edgeOptions.color = linkedNode.graphNode.get('color');
}
graph.addEdge(linkedNode.graphNode, node.graphNode, edgeOptions);
});
});
graphdot.renderToSvgFile(graph, renderer, filepath, callback);
});
}; |
import { connect } from 'react-redux';
import Main from './Main';
import * as userActions from '../../state/user/userActions';
const mapStateToProps = (state, ownProps) => {
return {
activeTab: ownProps.location.pathname.split('/')[2]
};
};
const mapDispatchToProps = (dispatch) => {
return {
getUserData: () => dispatch(userActions.authRequest())
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Main);
|
(function(angular) {
'use strict';
angular
.module('jstube.chromeExtensionCleaner.popup')
.directive('jstubeNavbar', jstubeNavbar);
function jstubeNavbar() {
return {
restrict: 'E',
templateUrl: 'nav/_navbar.html',
controller: 'NavbarController',
controllerAs: 'nav'
};
}
} (window.angular)); |
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var $ = __webpack_require__(1);
var React = __webpack_require__(2);
var ReactDOM = __webpack_require__(3);
var Hello_1 = __webpack_require__(4);
var LabelTextbox_1 = __webpack_require__(5);
var WebUser_1 = __webpack_require__(6);
$(function () {
var id = "target";
var container = document.getElementById(id);
var model = new WebUser_1.default("James", null);
function validate() {
return model.validate();
}
var wrapper = React.createElement("div", null, React.createElement(Hello_1.default, {class: "welcome", compiler: "TypeScript", framework: "ReactJS"}), React.createElement(LabelTextbox_1.default, {class: "field-username", type: "text", label: "Username", model: model}), React.createElement("button", {onClick: validate}, "Validate"));
ReactDOM.render(wrapper, container);
});
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
* jQuery JavaScript Library v3.0.0
* https://jquery.com/
*
* Includes Sizzle.js
* https://sizzlejs.com/
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* https://jquery.org/license
*
* Date: 2016-06-09T18:02Z
*/
( function( global, factory ) {
"use strict";
if ( typeof module === "object" && typeof module.exports === "object" ) {
// For CommonJS and CommonJS-like environments where a proper `window`
// is present, execute the factory and get jQuery.
// For environments that do not have a `window` with a `document`
// (such as Node.js), expose a factory as module.exports.
// This accentuates the need for the creation of a real `window`.
// e.g. var jQuery = require("jquery")(window);
// See ticket #14549 for more info.
module.exports = global.document ?
factory( global, true ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
};
} else {
factory( global );
}
// Pass this if window is not defined yet
}( typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1
// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode
// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common
// enough that all such attempts are guarded in a try block.
"use strict";
var arr = [];
var document = window.document;
var getProto = Object.getPrototypeOf;
var slice = arr.slice;
var concat = arr.concat;
var push = arr.push;
var indexOf = arr.indexOf;
var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
var fnToString = hasOwn.toString;
var ObjectFunctionString = fnToString.call( Object );
var support = {};
function DOMEval( code, doc ) {
doc = doc || document;
var script = doc.createElement( "script" );
script.text = code;
doc.head.appendChild( script ).parentNode.removeChild( script );
}
var
version = "3.0.0",
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init( selector, context );
},
// Support: Android <=4.0 only
// Make sure we trim BOM and NBSP
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([a-z])/g,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num != null ?
// Return just the one element from the set
( num < 0 ? this[ num + this.length ] : this[ num ] ) :
// Return all the elements in a clean array
slice.call( this );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
each: function( callback ) {
return jQuery.each( this, callback );
},
map: function( callback ) {
return this.pushStack( jQuery.map( this, function( elem, i ) {
return callback.call( elem, i, elem );
} ) );
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] );
},
end: function() {
return this.prevObject || this.constructor();
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: arr.sort,
splice: arr.splice
};
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[ 0 ] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
// Skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction( target ) ) {
target = {};
}
// Extend jQuery itself if only one argument is passed
if ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( ( options = arguments[ i ] ) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
( copyIsArray = jQuery.isArray( copy ) ) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray( src ) ? src : [];
} else {
clone = src && jQuery.isPlainObject( src ) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend( {
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
// Assume jQuery is ready without the ready module
isReady: true,
error: function( msg ) {
throw new Error( msg );
},
noop: function() {},
isFunction: function( obj ) {
return jQuery.type( obj ) === "function";
},
isArray: Array.isArray,
isWindow: function( obj ) {
return obj != null && obj === obj.window;
},
isNumeric: function( obj ) {
// As of jQuery 3.0, isNumeric is limited to
// strings and numbers (primitives or objects)
// that can be coerced to finite numbers (gh-2662)
var type = jQuery.type( obj );
return ( type === "number" || type === "string" ) &&
// parseFloat NaNs numeric-cast false positives ("")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
!isNaN( obj - parseFloat( obj ) );
},
isPlainObject: function( obj ) {
var proto, Ctor;
// Detect obvious negatives
// Use toString instead of jQuery.type to catch host objects
if ( !obj || toString.call( obj ) !== "[object Object]" ) {
return false;
}
proto = getProto( obj );
// Objects with no prototype (e.g., `Object.create( null )`) are plain
if ( !proto ) {
return true;
}
// Objects with prototype are plain iff they were constructed by a global Object function
Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor;
return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
type: function( obj ) {
if ( obj == null ) {
return obj + "";
}
// Support: Android <=2.3 only (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call( obj ) ] || "object" :
typeof obj;
},
// Evaluates a script in a global context
globalEval: function( code ) {
DOMEval( code );
},
// Convert dashed to camelCase; used by the css and data modules
// Support: IE <=9 - 11, Edge 12 - 13
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
each: function( obj, callback ) {
var length, i = 0;
if ( isArrayLike( obj ) ) {
length = obj.length;
for ( ; i < length; i++ ) {
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
break;
}
}
} else {
for ( i in obj ) {
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
break;
}
}
}
return obj;
},
// Support: Android <=4.0 only
trim: function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArrayLike( Object( arr ) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
return arr == null ? -1 : indexOf.call( arr, elem, i );
},
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
merge: function( first, second ) {
var len = +second.length,
j = 0,
i = first.length;
for ( ; j < len; j++ ) {
first[ i++ ] = second[ j ];
}
first.length = i;
return first;
},
grep: function( elems, callback, invert ) {
var callbackInverse,
matches = [],
i = 0,
length = elems.length,
callbackExpect = !invert;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
callbackInverse = !callback( elems[ i ], i );
if ( callbackInverse !== callbackExpect ) {
matches.push( elems[ i ] );
}
}
return matches;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var length, value,
i = 0,
ret = [];
// Go through the array, translating each of the items to their new values
if ( isArrayLike( elems ) ) {
length = elems.length;
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
}
// Flatten any nested arrays
return concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
now: Date.now,
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
} );
// JSHint would error on this code due to the Symbol not being defined in ES5.
// Defining this global in .jshintrc would create a danger of using the global
// unguarded in another place, it seems safer to just disable JSHint for these
// three lines.
/* jshint ignore: start */
if ( typeof Symbol === "function" ) {
jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ];
}
/* jshint ignore: end */
// Populate the class2type map
jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
function( i, name ) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
} );
function isArrayLike( obj ) {
// Support: real iOS 8.2 only (not reproducible in simulator)
// `in` check used to prevent JIT error (gh-2145)
// hasOwn isn't used here due to false negatives
// regarding Nodelist length in IE
var length = !!obj && "length" in obj && obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
* Sizzle CSS Selector Engine v2.3.0
* https://sizzlejs.com/
*
* Copyright jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2016-01-04
*/
(function( window ) {
var i,
support,
Expr,
getText,
isXML,
tokenize,
compile,
select,
outermostContext,
sortInput,
hasDuplicate,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + 1 * new Date(),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
}
return 0;
},
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf as it's faster than native
// https://jsperf.com/thor-indexof-vs-for/5
indexOf = function( list, elem ) {
var i = 0,
len = list.length;
for ( ; i < len; i++ ) {
if ( list[i] === elem ) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+",
// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +
// Operator (capture 2)
"*([*^$|!~]?=)" + whitespace +
// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
"*\\]",
pseudos = ":(" + identifier + ")(?:\\((" +
// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
// 1. quoted (capture 3; capture 4 or capture 5)
"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
// 2. simple (capture 6)
"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
// 3. anything else (capture 2)
".*" +
")\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rwhitespace = new RegExp( whitespace + "+", "g" ),
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + identifier + ")" ),
"CLASS": new RegExp( "^\\.(" + identifier + ")" ),
"TAG": new RegExp( "^(" + identifier + "|[*])" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rsibling = /[+~]/,
// CSS escapes
// http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox<24
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
high < 0 ?
// BMP codepoint
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
},
// CSS string/identifier serialization
// https://drafts.csswg.org/cssom/#common-serializing-idioms
rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g,
fcssescape = function( ch, asCodePoint ) {
if ( asCodePoint ) {
// U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
if ( ch === "\0" ) {
return "\uFFFD";
}
// Control characters and (dependent upon position) numbers get escaped as code points
return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " ";
}
// Other potentially-special ASCII characters get backslash-escaped
return "\\" + ch;
},
// Used for iframes
// See setDocument()
// Removing the function wrapper causes a "Permission Denied"
// error in IE
unloadHandler = function() {
setDocument();
},
disabledAncestor = addCombinator(
function( elem ) {
return elem.disabled === true;
},
{ dir: "parentNode", next: "legend" }
);
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call( preferredDoc.childNodes )),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
push_native.apply( target, slice.call(els) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( (target[j++] = els[i++]) ) {}
target.length = j - 1;
}
};
}
function Sizzle( selector, context, results, seed ) {
var m, i, elem, nid, match, groups, newSelector,
newContext = context && context.ownerDocument,
// nodeType defaults to 9, since context defaults to document
nodeType = context ? context.nodeType : 9;
results = results || [];
// Return early from calls with invalid selector or context
if ( typeof selector !== "string" || !selector ||
nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
return results;
}
// Try to shortcut find operations (as opposed to filters) in HTML documents
if ( !seed ) {
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
if ( documentIsHTML ) {
// If the selector is sufficiently simple, try using a "get*By*" DOM method
// (excepting DocumentFragment context, where the methods don't exist)
if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) {
// ID selector
if ( (m = match[1]) ) {
// Document context
if ( nodeType === 9 ) {
if ( (elem = context.getElementById( m )) ) {
// Support: IE, Opera, Webkit
// TODO: identify versions
// getElementById can match elements by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
// Element context
} else {
// Support: IE, Opera, Webkit
// TODO: identify versions
// getElementById can match elements by name instead of ID
if ( newContext && (elem = newContext.getElementById( m )) &&
contains( context, elem ) &&
elem.id === m ) {
results.push( elem );
return results;
}
}
// Type selector
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Class selector
} else if ( (m = match[3]) && support.getElementsByClassName &&
context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// Take advantage of querySelectorAll
if ( support.qsa &&
!compilerCache[ selector + " " ] &&
(!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
if ( nodeType !== 1 ) {
newContext = context;
newSelector = selector;
// qSA looks outside Element context, which is not what we want
// Thanks to Andrew Dupont for this workaround technique
// Support: IE <=8
// Exclude object elements
} else if ( context.nodeName.toLowerCase() !== "object" ) {
// Capture the context ID, setting it first if necessary
if ( (nid = context.getAttribute( "id" )) ) {
nid = nid.replace( rcssescape, fcssescape );
} else {
context.setAttribute( "id", (nid = expando) );
}
// Prefix every selector in the list
groups = tokenize( selector );
i = groups.length;
while ( i-- ) {
groups[i] = "#" + nid + " " + toSelector( groups[i] );
}
newSelector = groups.join( "," );
// Expand context for sibling selectors
newContext = rsibling.test( selector ) && testContext( context.parentNode ) ||
context;
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch ( qsaError ) {
} finally {
if ( nid === expando ) {
context.removeAttribute( "id" );
}
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Create key-value caches of limited size
* @returns {function(string, object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key + " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key + " " ] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created element and returns a boolean result
*/
function assert( fn ) {
var el = document.createElement("fieldset");
try {
return !!fn( el );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( el.parentNode ) {
el.parentNode.removeChild( el );
}
// release memory in IE
el = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied
*/
function addHandle( attrs, handler ) {
var arr = attrs.split("|"),
i = arr.length;
while ( i-- ) {
Expr.attrHandle[ arr[i] ] = handler;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
a.sourceIndex - b.sourceIndex;
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for :enabled/:disabled
* @param {Boolean} disabled true for :disabled; false for :enabled
*/
function createDisabledPseudo( disabled ) {
// Known :disabled false positives:
// IE: *[disabled]:not(button, input, select, textarea, optgroup, option, menuitem, fieldset)
// not IE: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable
return function( elem ) {
// Check form elements and option elements for explicit disabling
return "label" in elem && elem.disabled === disabled ||
"form" in elem && elem.disabled === disabled ||
// Check non-disabled form elements for fieldset[disabled] ancestors
"form" in elem && elem.disabled === false && (
// Support: IE6-11+
// Ancestry is covered for us
elem.isDisabled === disabled ||
// Otherwise, assume any non-<option> under fieldset[disabled] is disabled
/* jshint -W018 */
elem.isDisabled !== !disabled &&
("label" in elem || !disabledAncestor( elem )) !== disabled
);
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Checks a node for validity as a Sizzle context
* @param {Element|Object=} context
* @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
*/
function testContext( context ) {
return context && typeof context.getElementsByTagName !== "undefined" && context;
}
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Detects XML nodes
* @param {Element|Object} elem An element or a document
* @returns {Boolean} True iff elem is a non-HTML XML node
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var hasCompare, subWindow,
doc = node ? node.ownerDocument || node : preferredDoc;
// Return early if doc is invalid or already selected
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Update global variables
document = doc;
docElem = document.documentElement;
documentIsHTML = !isXML( document );
// Support: IE 9-11, Edge
// Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
if ( preferredDoc !== document &&
(subWindow = document.defaultView) && subWindow.top !== subWindow ) {
// Support: IE 11, Edge
if ( subWindow.addEventListener ) {
subWindow.addEventListener( "unload", unloadHandler, false );
// Support: IE 9 - 10 only
} else if ( subWindow.attachEvent ) {
subWindow.attachEvent( "onunload", unloadHandler );
}
}
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties
// (excepting IE8 booleans)
support.attributes = assert(function( el ) {
el.className = "i";
return !el.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( el ) {
el.appendChild( document.createComment("") );
return !el.getElementsByTagName("*").length;
});
// Support: IE<9
support.getElementsByClassName = rnative.test( document.getElementsByClassName );
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programmatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( el ) {
docElem.appendChild( el ).id = expando;
return !document.getElementsByName || !document.getElementsByName( expando ).length;
});
// ID find and filter
if ( support.getById ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
var m = context.getElementById( id );
return m ? [ m ] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== "undefined" &&
elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== "undefined" ) {
return context.getElementsByTagName( tag );
// DocumentFragment nodes don't have gEBTN
} else if ( support.qsa ) {
return context.querySelectorAll( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
// By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See https://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = rnative.test( document.querySelectorAll )) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( el ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// https://bugs.jquery.com/ticket/12359
docElem.appendChild( el ).innerHTML = "<a id='" + expando + "'></a>" +
"<select id='" + expando + "-\r\\' msallowcapture=''>" +
"<option selected=''></option></select>";
// Support: IE8, Opera 11-12.16
// Nothing should be selected when empty strings follow ^= or $= or *=
// The test attribute must be unknown in Opera but "safe" for WinRT
// https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
if ( el.querySelectorAll("[msallowcapture^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !el.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+
if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
rbuggyQSA.push("~=");
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !el.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
// Support: Safari 8+, iOS 8+
// https://bugs.webkit.org/show_bug.cgi?id=136851
// In-page `selector#id sibling-combinator selector` fails
if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) {
rbuggyQSA.push(".#.+[+~]");
}
});
assert(function( el ) {
el.innerHTML = "<a href='' disabled='disabled'></a>" +
"<select disabled='disabled'><option/></select>";
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = document.createElement("input");
input.setAttribute( "type", "hidden" );
el.appendChild( input ).setAttribute( "name", "D" );
// Support: IE8
// Enforce case-sensitivity of name attribute
if ( el.querySelectorAll("[name=d]").length ) {
rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( el.querySelectorAll(":enabled").length !== 2 ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Support: IE9-11+
// IE's :disabled selector does not pick up the children of disabled fieldsets
docElem.appendChild( el ).disabled = true;
if ( el.querySelectorAll(":disabled").length !== 2 ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
el.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( el ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( el, "*" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( el, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
/* Contains
---------------------------------------------------------------------- */
hasCompare = rnative.test( docElem.compareDocumentPosition );
// Element contains another
// Purposefully self-exclusive
// As in, an element does not contain itself
contains = hasCompare || rnative.test( docElem.contains ) ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Document order sorting
sortOrder = hasCompare ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
// Sort on method existence if only one input has compareDocumentPosition
var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
if ( compare ) {
return compare;
}
// Calculate position if both inputs belong to the same document
compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
a.compareDocumentPosition( b ) :
// Otherwise we know they are disconnected
1;
// Disconnected nodes
if ( compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
return -1;
}
if ( b === document || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
} :
function( a, b ) {
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Parentless nodes are either documents or disconnected
if ( !aup || !bup ) {
return a === document ? -1 :
b === document ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return document;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
if ( support.matchesSelector && documentIsHTML &&
!compilerCache[ expr + " " ] &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch (e) {}
}
return Sizzle( expr, document, null, [ elem ] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined;
return val !== undefined ?
val :
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null;
};
Sizzle.escape = function( sel ) {
return (sel + "").replace( rcssescape, fcssescape );
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
// Clear input after sorting to release objects
// See https://github.com/jquery/sizzle/pull/225
sortInput = null;
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
while ( (node = elem[i++]) ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (jQuery #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[6] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] ) {
match[2] = match[4] || match[5] || "";
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, uniqueCache, outerCache, node, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType,
diff = false;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ?
node.nodeName.toLowerCase() === name :
node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
// ...in a gzip-friendly way
node = parent;
outerCache = node[ expando ] || (node[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
(outerCache[ node.uniqueID ] = {});
cache = uniqueCache[ type ] || [];
nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
diff = nodeIndex && cache[ 2 ];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
uniqueCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
} else {
// Use previously-cached element index if available
if ( useCache ) {
// ...in a gzip-friendly way
node = elem;
outerCache = node[ expando ] || (node[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
(outerCache[ node.uniqueID ] = {});
cache = uniqueCache[ type ] || [];
nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
diff = nodeIndex;
}
// xml :nth-child(...)
// or :nth-last-child(...) or :nth(-last)?-of-type(...)
if ( diff === false ) {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ?
node.nodeName.toLowerCase() === name :
node.nodeType === 1 ) &&
++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
outerCache = node[ expando ] || (node[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ node.uniqueID ] ||
(outerCache[ node.uniqueID ] = {});
uniqueCache[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
// Don't keep the element (issue #299)
input[0] = null;
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
text = text.replace( runescape, funescape );
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": createDisabledPseudo( false ),
"disabled": createDisabledPseudo( true ),
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
// but not by others (comment: 8; processing instruction: 7; etc.)
// nodeType < 6 works because attributes (2) do not appear as children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeType < 6 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
// Support: IE<8
// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( (tokens = []) );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
});
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
};
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
skip = combinator.next,
key = skip || dir,
checkNonElements = base && key === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var oldCache, uniqueCache, outerCache,
newCache = [ dirruns, doneName ];
// We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
// Support: IE <9 only
// Defend against cloned attroperties (jQuery gh-1709)
uniqueCache = outerCache[ elem.uniqueID ] || (outerCache[ elem.uniqueID ] = {});
if ( skip && skip === elem.nodeName.toLowerCase() ) {
elem = elem[ dir ] || elem;
} else if ( (oldCache = uniqueCache[ key ]) &&
oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
// Assign to newCache so results back-propagate to previous elements
return (newCache[ 2 ] = oldCache[ 2 ]);
} else {
// Reuse newcache so results back-propagate to previous elements
uniqueCache[ key ] = newCache;
// A match means we're done; a fail means we have to keep checking
if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
// Avoid hanging onto element (issue #299)
checkContext = null;
return ret;
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, outermost ) {
var elem, j, matcher,
matchedCount = 0,
i = "0",
unmatched = seed && [],
setMatched = [],
contextBackup = outermostContext,
// We must always have either seed elements or outermost context
elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
len = elems.length;
if ( outermost ) {
outermostContext = context === document || context || outermost;
}
// Add elements passing elementMatchers directly to results
// Support: IE<9, Safari
// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
if ( !context && elem.ownerDocument !== document ) {
setDocument( elem );
xml = !documentIsHTML;
}
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context || document, xml) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// `i` is now the count of elements visited above, and adding it to `matchedCount`
// makes the latter nonnegative.
matchedCount += i;
// Apply set filters to unmatched elements
// NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
// equals `i`), unless we didn't visit _any_ elements in the above loop because we have
// no element matchers and no seed.
// Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
// case, which will result in a "00" `matchedCount` that differs from `i` but is also
// numerically zero.
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !match ) {
match = tokenize( selector );
}
i = match.length;
while ( i-- ) {
cached = matcherFromTokens( match[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
// Save selector and tokenization
cached.selector = selector;
}
return cached;
};
/**
* A low-level selection function that works with Sizzle's compiled
* selector functions
* @param {String|Function} selector A selector or a pre-compiled
* selector function built with Sizzle.compile
* @param {Element} context
* @param {Array} [results]
* @param {Array} [seed] A set of elements to match against
*/
select = Sizzle.select = function( selector, context, results, seed ) {
var i, tokens, token, type, find,
compiled = typeof selector === "function" && selector,
match = !seed && tokenize( (selector = compiled.selector || selector) );
results = results || [];
// Try to minimize operations if there is only one selector in the list and no seed
// (the latter of which guarantees us context)
if ( match.length === 1 ) {
// Reduce context if the leading compound selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && context.nodeType === 9 && documentIsHTML &&
Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
// Precompiled matchers will still verify ancestry, so step up a level
} else if ( compiled ) {
context = context.parentNode;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
// Compile and execute a filtering function if one is not provided
// Provide `match` to avoid retokenization if we modified the selector above
( compiled || compile( selector, match ) )(
seed,
context,
!documentIsHTML,
results,
!context || rsibling.test( selector ) && testContext( context.parentNode ) || context
);
return results;
};
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Support: Chrome 14-35+
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = !!hasDuplicate;
// Initialize against the default document
setDocument();
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( el ) {
// Should return 1, but returns 4 (following)
return el.compareDocumentPosition( document.createElement("fieldset") ) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( el ) {
el.innerHTML = "<a href='#'></a>";
return el.firstChild.getAttribute("href") === "#" ;
}) ) {
addHandle( "type|href|height|width", function( elem, name, isXML ) {
if ( !isXML ) {
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
}
});
}
// Support: IE<9
// Use defaultValue in place of getAttribute("value")
if ( !support.attributes || !assert(function( el ) {
el.innerHTML = "<input/>";
el.firstChild.setAttribute( "value", "" );
return el.firstChild.getAttribute( "value" ) === "";
}) ) {
addHandle( "value", function( elem, name, isXML ) {
if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
return elem.defaultValue;
}
});
}
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
if ( !assert(function( el ) {
return el.getAttribute("disabled") == null;
}) ) {
addHandle( booleans, function( elem, name, isXML ) {
var val;
if ( !isXML ) {
return elem[ name ] === true ? name.toLowerCase() :
(val = elem.getAttributeNode( name )) && val.specified ?
val.value :
null;
}
});
}
return Sizzle;
})( window );
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
// Deprecated
jQuery.expr[ ":" ] = jQuery.expr.pseudos;
jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
jQuery.escapeSelector = Sizzle.escape;
var dir = function( elem, dir, until ) {
var matched = [],
truncate = until !== undefined;
while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) {
if ( elem.nodeType === 1 ) {
if ( truncate && jQuery( elem ).is( until ) ) {
break;
}
matched.push( elem );
}
}
return matched;
};
var siblings = function( n, elem ) {
var matched = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
matched.push( n );
}
}
return matched;
};
var rneedsContext = jQuery.expr.match.needsContext;
var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i );
var risSimple = /^.[^:#\[\.,]*$/;
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
} );
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
} );
}
if ( typeof qualifier === "string" ) {
if ( risSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( indexOf.call( qualifier, elem ) > -1 ) !== not && elem.nodeType === 1;
} );
}
jQuery.filter = function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
} ) );
};
jQuery.fn.extend( {
find: function( selector ) {
var i, ret,
len = this.length,
self = this;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter( function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
} ) );
}
ret = this.pushStack( [] );
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
return len > 1 ? jQuery.uniqueSort( ret ) : ret;
},
filter: function( selector ) {
return this.pushStack( winnow( this, selector || [], false ) );
},
not: function( selector ) {
return this.pushStack( winnow( this, selector || [], true ) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
}
} );
// Initialize a jQuery object
// A central reference to the root jQuery(document)
var rootjQuery,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
// Shortcut simple #id case for speed
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,
init = jQuery.fn.init = function( selector, context, root ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Method init() accepts an alternate rootjQuery
// so migrate can support jQuery.sub (gh-2101)
root = root || rootjQuery;
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector[ 0 ] === "<" &&
selector[ selector.length - 1 ] === ">" &&
selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && ( match[ 1 ] || !context ) ) {
// HANDLE: $(html) -> $(array)
if ( match[ 1 ] ) {
context = context instanceof jQuery ? context[ 0 ] : context;
// Option to run scripts is true for back-compat
// Intentionally let the error be thrown if parseHTML is not present
jQuery.merge( this, jQuery.parseHTML(
match[ 1 ],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[ 2 ] );
if ( elem ) {
// Inject the element directly into the jQuery object
this[ 0 ] = elem;
this.length = 1;
}
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || root ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this[ 0 ] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return root.ready !== undefined ?
root.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}
return jQuery.makeArray( selector, this );
};
// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;
// Initialize central reference
rootjQuery = jQuery( document );
var rparentsprev = /^(?:parents|prev(?:Until|All))/,
// Methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend( {
has: function( target ) {
var targets = jQuery( target, this ),
l = targets.length;
return this.filter( function() {
var i = 0;
for ( ; i < l; i++ ) {
if ( jQuery.contains( this, targets[ i ] ) ) {
return true;
}
}
} );
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
targets = typeof selectors !== "string" && jQuery( selectors );
// Positional selectors never match, since there's no _selection_ context
if ( !rneedsContext.test( selectors ) ) {
for ( ; i < l; i++ ) {
for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && ( targets ?
targets.index( cur ) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector( cur, selectors ) ) ) {
matched.push( cur );
break;
}
}
}
}
return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched );
},
// Determine the position of an element within the set
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
}
// Index in selector
if ( typeof elem === "string" ) {
return indexOf.call( jQuery( elem ), this[ 0 ] );
}
// Locate the position of the desired element
return indexOf.call( this,
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[ 0 ] : elem
);
},
add: function( selector, context ) {
return this.pushStack(
jQuery.uniqueSort(
jQuery.merge( this.get(), jQuery( selector, context ) )
)
);
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter( selector )
);
}
} );
function sibling( cur, dir ) {
while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {}
return cur;
}
jQuery.each( {
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return siblings( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return siblings( elem.firstChild );
},
contents: function( elem ) {
return elem.contentDocument || jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var matched = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
matched = jQuery.filter( selector, matched );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
jQuery.uniqueSort( matched );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
matched.reverse();
}
}
return this.pushStack( matched );
};
} );
var rnotwhite = ( /\S+/g );
// Convert String-formatted options into Object-formatted ones
function createOptions( options ) {
var object = {};
jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
} );
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
createOptions( options ) :
jQuery.extend( {}, options );
var // Flag to know if list is currently firing
firing,
// Last fire value for non-forgettable lists
memory,
// Flag to know if list was already fired
fired,
// Flag to prevent firing
locked,
// Actual callback list
list = [],
// Queue of execution data for repeatable lists
queue = [],
// Index of currently firing callback (modified by add/remove as needed)
firingIndex = -1,
// Fire callbacks
fire = function() {
// Enforce single-firing
locked = options.once;
// Execute callbacks for all pending executions,
// respecting firingIndex overrides and runtime changes
fired = firing = true;
for ( ; queue.length; firingIndex = -1 ) {
memory = queue.shift();
while ( ++firingIndex < list.length ) {
// Run callback and check for early termination
if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false &&
options.stopOnFalse ) {
// Jump to end and forget the data so .add doesn't re-fire
firingIndex = list.length;
memory = false;
}
}
}
// Forget the data if we're done with it
if ( !options.memory ) {
memory = false;
}
firing = false;
// Clean up if we're done firing for good
if ( locked ) {
// Keep an empty list if we have data for future add calls
if ( memory ) {
list = [];
// Otherwise, this object is spent
} else {
list = "";
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// If we have memory from a past run, we should fire after adding
if ( memory && !firing ) {
firingIndex = list.length - 1;
queue.push( memory );
}
( function add( args ) {
jQuery.each( args, function( _, arg ) {
if ( jQuery.isFunction( arg ) ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && jQuery.type( arg ) !== "string" ) {
// Inspect recursively
add( arg );
}
} );
} )( arguments );
if ( memory && !firing ) {
fire();
}
}
return this;
},
// Remove a callback from the list
remove: function() {
jQuery.each( arguments, function( _, arg ) {
var index;
while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( index <= firingIndex ) {
firingIndex--;
}
}
} );
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ?
jQuery.inArray( fn, list ) > -1 :
list.length > 0;
},
// Remove all callbacks from the list
empty: function() {
if ( list ) {
list = [];
}
return this;
},
// Disable .fire and .add
// Abort any current/pending executions
// Clear all callbacks and values
disable: function() {
locked = queue = [];
list = memory = "";
return this;
},
disabled: function() {
return !list;
},
// Disable .fire
// Also disable .add unless we have memory (since it would have no effect)
// Abort any pending executions
lock: function() {
locked = queue = [];
if ( !memory && !firing ) {
list = memory = "";
}
return this;
},
locked: function() {
return !!locked;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( !locked ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
queue.push( args );
if ( !firing ) {
fire();
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
function Identity( v ) {
return v;
}
function Thrower( ex ) {
throw ex;
}
function adoptValue( value, resolve, reject ) {
var method;
try {
// Check for promise aspect first to privilege synchronous behavior
if ( value && jQuery.isFunction( ( method = value.promise ) ) ) {
method.call( value ).done( resolve ).fail( reject );
// Other thenables
} else if ( value && jQuery.isFunction( ( method = value.then ) ) ) {
method.call( value, resolve, reject );
// Other non-thenables
} else {
// Support: Android 4.0 only
// Strict mode functions invoked without .call/.apply get global-object context
resolve.call( undefined, value );
}
// For Promises/A+, convert exceptions into rejections
// Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in
// Deferred#then to conditionally suppress rejection.
} catch ( /*jshint -W002 */ value ) {
// Support: Android 4.0 only
// Strict mode functions invoked without .call/.apply get global-object context
reject.call( undefined, value );
}
}
jQuery.extend( {
Deferred: function( func ) {
var tuples = [
// action, add listener, callbacks,
// ... .then handlers, argument index, [final state]
[ "notify", "progress", jQuery.Callbacks( "memory" ),
jQuery.Callbacks( "memory" ), 2 ],
[ "resolve", "done", jQuery.Callbacks( "once memory" ),
jQuery.Callbacks( "once memory" ), 0, "resolved" ],
[ "reject", "fail", jQuery.Callbacks( "once memory" ),
jQuery.Callbacks( "once memory" ), 1, "rejected" ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
"catch": function( fn ) {
return promise.then( null, fn );
},
// Keep pipe for back-compat
pipe: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred( function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
// Map tuples (progress, done, fail) to arguments (done, fail, progress)
var fn = jQuery.isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ];
// deferred.progress(function() { bind to newDefer or newDefer.notify })
// deferred.done(function() { bind to newDefer or newDefer.resolve })
// deferred.fail(function() { bind to newDefer or newDefer.reject })
deferred[ tuple[ 1 ] ]( function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.progress( newDefer.notify )
.done( newDefer.resolve )
.fail( newDefer.reject );
} else {
newDefer[ tuple[ 0 ] + "With" ](
this,
fn ? [ returned ] : arguments
);
}
} );
} );
fns = null;
} ).promise();
},
then: function( onFulfilled, onRejected, onProgress ) {
var maxDepth = 0;
function resolve( depth, deferred, handler, special ) {
return function() {
var that = this,
args = arguments,
mightThrow = function() {
var returned, then;
// Support: Promises/A+ section 2.3.3.3.3
// https://promisesaplus.com/#point-59
// Ignore double-resolution attempts
if ( depth < maxDepth ) {
return;
}
returned = handler.apply( that, args );
// Support: Promises/A+ section 2.3.1
// https://promisesaplus.com/#point-48
if ( returned === deferred.promise() ) {
throw new TypeError( "Thenable self-resolution" );
}
// Support: Promises/A+ sections 2.3.3.1, 3.5
// https://promisesaplus.com/#point-54
// https://promisesaplus.com/#point-75
// Retrieve `then` only once
then = returned &&
// Support: Promises/A+ section 2.3.4
// https://promisesaplus.com/#point-64
// Only check objects and functions for thenability
( typeof returned === "object" ||
typeof returned === "function" ) &&
returned.then;
// Handle a returned thenable
if ( jQuery.isFunction( then ) ) {
// Special processors (notify) just wait for resolution
if ( special ) {
then.call(
returned,
resolve( maxDepth, deferred, Identity, special ),
resolve( maxDepth, deferred, Thrower, special )
);
// Normal processors (resolve) also hook into progress
} else {
// ...and disregard older resolution values
maxDepth++;
then.call(
returned,
resolve( maxDepth, deferred, Identity, special ),
resolve( maxDepth, deferred, Thrower, special ),
resolve( maxDepth, deferred, Identity,
deferred.notifyWith )
);
}
// Handle all other returned values
} else {
// Only substitute handlers pass on context
// and multiple values (non-spec behavior)
if ( handler !== Identity ) {
that = undefined;
args = [ returned ];
}
// Process the value(s)
// Default process is resolve
( special || deferred.resolveWith )( that, args );
}
},
// Only normal processors (resolve) catch and reject exceptions
process = special ?
mightThrow :
function() {
try {
mightThrow();
} catch ( e ) {
if ( jQuery.Deferred.exceptionHook ) {
jQuery.Deferred.exceptionHook( e,
process.stackTrace );
}
// Support: Promises/A+ section 2.3.3.3.4.1
// https://promisesaplus.com/#point-61
// Ignore post-resolution exceptions
if ( depth + 1 >= maxDepth ) {
// Only substitute handlers pass on context
// and multiple values (non-spec behavior)
if ( handler !== Thrower ) {
that = undefined;
args = [ e ];
}
deferred.rejectWith( that, args );
}
}
};
// Support: Promises/A+ section 2.3.3.3.1
// https://promisesaplus.com/#point-57
// Re-resolve promises immediately to dodge false rejection from
// subsequent errors
if ( depth ) {
process();
} else {
// Call an optional hook to record the stack, in case of exception
// since it's otherwise lost when execution goes async
if ( jQuery.Deferred.getStackHook ) {
process.stackTrace = jQuery.Deferred.getStackHook();
}
window.setTimeout( process );
}
};
}
return jQuery.Deferred( function( newDefer ) {
// progress_handlers.add( ... )
tuples[ 0 ][ 3 ].add(
resolve(
0,
newDefer,
jQuery.isFunction( onProgress ) ?
onProgress :
Identity,
newDefer.notifyWith
)
);
// fulfilled_handlers.add( ... )
tuples[ 1 ][ 3 ].add(
resolve(
0,
newDefer,
jQuery.isFunction( onFulfilled ) ?
onFulfilled :
Identity
)
);
// rejected_handlers.add( ... )
tuples[ 2 ][ 3 ].add(
resolve(
0,
newDefer,
jQuery.isFunction( onRejected ) ?
onRejected :
Thrower
)
);
} ).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 5 ];
// promise.progress = list.add
// promise.done = list.add
// promise.fail = list.add
promise[ tuple[ 1 ] ] = list.add;
// Handle state
if ( stateString ) {
list.add(
function() {
// state = "resolved" (i.e., fulfilled)
// state = "rejected"
state = stateString;
},
// rejected_callbacks.disable
// fulfilled_callbacks.disable
tuples[ 3 - i ][ 2 ].disable,
// progress_callbacks.lock
tuples[ 0 ][ 2 ].lock
);
}
// progress_handlers.fire
// fulfilled_handlers.fire
// rejected_handlers.fire
list.add( tuple[ 3 ].fire );
// deferred.notify = function() { deferred.notifyWith(...) }
// deferred.resolve = function() { deferred.resolveWith(...) }
// deferred.reject = function() { deferred.rejectWith(...) }
deferred[ tuple[ 0 ] ] = function() {
deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments );
return this;
};
// deferred.notifyWith = list.fireWith
// deferred.resolveWith = list.fireWith
// deferred.rejectWith = list.fireWith
deferred[ tuple[ 0 ] + "With" ] = list.fireWith;
} );
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( singleValue ) {
var
// count of uncompleted subordinates
remaining = arguments.length,
// count of unprocessed arguments
i = remaining,
// subordinate fulfillment data
resolveContexts = Array( i ),
resolveValues = slice.call( arguments ),
// the master Deferred
master = jQuery.Deferred(),
// subordinate callback factory
updateFunc = function( i ) {
return function( value ) {
resolveContexts[ i ] = this;
resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
if ( !( --remaining ) ) {
master.resolveWith( resolveContexts, resolveValues );
}
};
};
// Single- and empty arguments are adopted like Promise.resolve
if ( remaining <= 1 ) {
adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject );
// Use .then() to unwrap secondary thenables (cf. gh-3000)
if ( master.state() === "pending" ||
jQuery.isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) {
return master.then();
}
}
// Multiple arguments are aggregated like Promise.all array elements
while ( i-- ) {
adoptValue( resolveValues[ i ], updateFunc( i ), master.reject );
}
return master.promise();
}
} );
// These usually indicate a programmer mistake during development,
// warn about them ASAP rather than swallowing them by default.
var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;
jQuery.Deferred.exceptionHook = function( error, stack ) {
// Support: IE 8 - 9 only
// Console exists when dev tools are open, which can happen at any time
if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) {
window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack );
}
};
// The deferred used on DOM ready
var readyList = jQuery.Deferred();
jQuery.fn.ready = function( fn ) {
readyList.then( fn );
return this;
};
jQuery.extend( {
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
}
} );
jQuery.ready.then = readyList.then;
// The ready event handler and self cleanup method
function completed() {
document.removeEventListener( "DOMContentLoaded", completed );
window.removeEventListener( "load", completed );
jQuery.ready();
}
// Catch cases where $(document).ready() is called
// after the browser event has already occurred.
// Support: IE <=9 - 10 only
// Older IE sometimes signals "interactive" too soon
if ( document.readyState === "complete" ||
( document.readyState !== "loading" && !document.documentElement.doScroll ) ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
window.setTimeout( jQuery.ready );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed );
}
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
len = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
access( elems, fn, i, key[ i ], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < len; i++ ) {
fn(
elems[ i ], key, raw ?
value :
value.call( elems[ i ], i, fn( elems[ i ], key ) )
);
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
len ? fn( elems[ 0 ], key ) : emptyGet;
};
var acceptData = function( owner ) {
// Accepts only:
// - Node
// - Node.ELEMENT_NODE
// - Node.DOCUMENT_NODE
// - Object
// - Any
/* jshint -W018 */
return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
};
function Data() {
this.expando = jQuery.expando + Data.uid++;
}
Data.uid = 1;
Data.prototype = {
cache: function( owner ) {
// Check if the owner object already has a cache
var value = owner[ this.expando ];
// If not, create one
if ( !value ) {
value = {};
// We can accept data for non-element nodes in modern browsers,
// but we should not, see #8335.
// Always return an empty object.
if ( acceptData( owner ) ) {
// If it is a node unlikely to be stringify-ed or looped over
// use plain assignment
if ( owner.nodeType ) {
owner[ this.expando ] = value;
// Otherwise secure it in a non-enumerable property
// configurable must be true to allow the property to be
// deleted when data is removed
} else {
Object.defineProperty( owner, this.expando, {
value: value,
configurable: true
} );
}
}
}
return value;
},
set: function( owner, data, value ) {
var prop,
cache = this.cache( owner );
// Handle: [ owner, key, value ] args
// Always use camelCase key (gh-2257)
if ( typeof data === "string" ) {
cache[ jQuery.camelCase( data ) ] = value;
// Handle: [ owner, { properties } ] args
} else {
// Copy the properties one-by-one to the cache object
for ( prop in data ) {
cache[ jQuery.camelCase( prop ) ] = data[ prop ];
}
}
return cache;
},
get: function( owner, key ) {
return key === undefined ?
this.cache( owner ) :
// Always use camelCase key (gh-2257)
owner[ this.expando ] && owner[ this.expando ][ jQuery.camelCase( key ) ];
},
access: function( owner, key, value ) {
// In cases where either:
//
// 1. No key was specified
// 2. A string key was specified, but no value provided
//
// Take the "read" path and allow the get method to determine
// which value to return, respectively either:
//
// 1. The entire cache object
// 2. The data stored at the key
//
if ( key === undefined ||
( ( key && typeof key === "string" ) && value === undefined ) ) {
return this.get( owner, key );
}
// When the key is not a string, or both a key and value
// are specified, set or extend (existing objects) with either:
//
// 1. An object of properties
// 2. A key and value
//
this.set( owner, key, value );
// Since the "set" path can have two possible entry points
// return the expected data based on which path was taken[*]
return value !== undefined ? value : key;
},
remove: function( owner, key ) {
var i,
cache = owner[ this.expando ];
if ( cache === undefined ) {
return;
}
if ( key !== undefined ) {
// Support array or space separated string of keys
if ( jQuery.isArray( key ) ) {
// If key is an array of keys...
// We always set camelCase keys, so remove that.
key = key.map( jQuery.camelCase );
} else {
key = jQuery.camelCase( key );
// If a key with the spaces exists, use it.
// Otherwise, create an array by matching non-whitespace
key = key in cache ?
[ key ] :
( key.match( rnotwhite ) || [] );
}
i = key.length;
while ( i-- ) {
delete cache[ key[ i ] ];
}
}
// Remove the expando if there's no more data
if ( key === undefined || jQuery.isEmptyObject( cache ) ) {
// Support: Chrome <=35 - 45
// Webkit & Blink performance suffers when deleting properties
// from DOM nodes, so set to undefined instead
// https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted)
if ( owner.nodeType ) {
owner[ this.expando ] = undefined;
} else {
delete owner[ this.expando ];
}
}
},
hasData: function( owner ) {
var cache = owner[ this.expando ];
return cache !== undefined && !jQuery.isEmptyObject( cache );
}
};
var dataPriv = new Data();
var dataUser = new Data();
// Implementation Summary
//
// 1. Enforce API surface and semantic compatibility with 1.9.x branch
// 2. Improve the module's maintainability by reducing the storage
// paths to a single mechanism.
// 3. Use the same single mechanism to support "private" and "user" data.
// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
// 5. Avoid exposing implementation details on user objects (eg. expando properties)
// 6. Provide a clear path for implementation upgrade to WeakMap in 2014
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
rmultiDash = /[A-Z]/g;
function dataAttr( elem, key, data ) {
var name;
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? JSON.parse( data ) :
data;
} catch ( e ) {}
// Make sure we set the data so it isn't changed later
dataUser.set( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
jQuery.extend( {
hasData: function( elem ) {
return dataUser.hasData( elem ) || dataPriv.hasData( elem );
},
data: function( elem, name, data ) {
return dataUser.access( elem, name, data );
},
removeData: function( elem, name ) {
dataUser.remove( elem, name );
},
// TODO: Now that all calls to _data and _removeData have been replaced
// with direct calls to dataPriv methods, these can be deprecated.
_data: function( elem, name, data ) {
return dataPriv.access( elem, name, data );
},
_removeData: function( elem, name ) {
dataPriv.remove( elem, name );
}
} );
jQuery.fn.extend( {
data: function( key, value ) {
var i, name, data,
elem = this[ 0 ],
attrs = elem && elem.attributes;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = dataUser.get( elem );
if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) {
i = attrs.length;
while ( i-- ) {
// Support: IE 11 only
// The attrs elements can be null (#14894)
if ( attrs[ i ] ) {
name = attrs[ i ].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.slice( 5 ) );
dataAttr( elem, name, data[ name ] );
}
}
}
dataPriv.set( elem, "hasDataAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each( function() {
dataUser.set( this, key );
} );
}
return access( this, function( value ) {
var data;
// The calling jQuery object (element matches) is not empty
// (and therefore has an element appears at this[ 0 ]) and the
// `value` parameter was not undefined. An empty jQuery object
// will result in `undefined` for elem = this[ 0 ] which will
// throw an exception if an attempt to read a data cache is made.
if ( elem && value === undefined ) {
// Attempt to get data from the cache
// The key will always be camelCased in Data
data = dataUser.get( elem, key );
if ( data !== undefined ) {
return data;
}
// Attempt to "discover" the data in
// HTML5 custom data-* attrs
data = dataAttr( elem, key );
if ( data !== undefined ) {
return data;
}
// We tried really hard, but the data doesn't exist.
return;
}
// Set the data...
this.each( function() {
// We always store the camelCased key
dataUser.set( this, key, value );
} );
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each( function() {
dataUser.remove( this, key );
} );
}
} );
jQuery.extend( {
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = dataPriv.get( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray( data ) ) {
queue = dataPriv.access( elem, type, jQuery.makeArray( data ) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// Clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// Not public - generate a queueHooks object, or return the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return dataPriv.get( elem, key ) || dataPriv.access( elem, key, {
empty: jQuery.Callbacks( "once memory" ).add( function() {
dataPriv.remove( elem, [ type + "queue", key ] );
} )
} );
}
} );
jQuery.fn.extend( {
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[ 0 ], type );
}
return data === undefined ?
this :
this.each( function() {
var queue = jQuery.queue( this, type, data );
// Ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[ 0 ] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
} );
},
dequeue: function( type ) {
return this.each( function() {
jQuery.dequeue( this, type );
} );
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while ( i-- ) {
tmp = dataPriv.get( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
} );
var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source;
var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" );
var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
var isHiddenWithinTree = function( elem, el ) {
// isHiddenWithinTree might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
// Inline style trumps all
return elem.style.display === "none" ||
elem.style.display === "" &&
// Otherwise, check computed style
// Support: Firefox <=43 - 45
// Disconnected elements can have computed display: none, so first confirm that elem is
// in the document.
jQuery.contains( elem.ownerDocument, elem ) &&
jQuery.css( elem, "display" ) === "none";
};
var swap = function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
};
function adjustCSS( elem, prop, valueParts, tween ) {
var adjusted,
scale = 1,
maxIterations = 20,
currentValue = tween ?
function() { return tween.cur(); } :
function() { return jQuery.css( elem, prop, "" ); },
initial = currentValue(),
unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
initialInUnit = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) &&
rcssNum.exec( jQuery.css( elem, prop ) );
if ( initialInUnit && initialInUnit[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || initialInUnit[ 3 ];
// Make sure we update the tween properties later on
valueParts = valueParts || [];
// Iteratively approximate from a nonzero starting point
initialInUnit = +initial || 1;
do {
// If previous iteration zeroed out, double until we get *something*.
// Use string for doubling so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
initialInUnit = initialInUnit / scale;
jQuery.style( elem, prop, initialInUnit + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// Break the loop if scale is unchanged or perfect, or if we've just had enough.
} while (
scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations
);
}
if ( valueParts ) {
initialInUnit = +initialInUnit || +initial || 0;
// Apply relative offset (+=/-=) if specified
adjusted = valueParts[ 1 ] ?
initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] :
+valueParts[ 2 ];
if ( tween ) {
tween.unit = unit;
tween.start = initialInUnit;
tween.end = adjusted;
}
}
return adjusted;
}
var defaultDisplayMap = {};
function getDefaultDisplay( elem ) {
var temp,
doc = elem.ownerDocument,
nodeName = elem.nodeName,
display = defaultDisplayMap[ nodeName ];
if ( display ) {
return display;
}
temp = doc.body.appendChild( doc.createElement( nodeName ) ),
display = jQuery.css( temp, "display" );
temp.parentNode.removeChild( temp );
if ( display === "none" ) {
display = "block";
}
defaultDisplayMap[ nodeName ] = display;
return display;
}
function showHide( elements, show ) {
var display, elem,
values = [],
index = 0,
length = elements.length;
// Determine new display value for elements that need to change
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
display = elem.style.display;
if ( show ) {
// Since we force visibility upon cascade-hidden elements, an immediate (and slow)
// check is required in this first loop unless we have a nonempty display value (either
// inline or about-to-be-restored)
if ( display === "none" ) {
values[ index ] = dataPriv.get( elem, "display" ) || null;
if ( !values[ index ] ) {
elem.style.display = "";
}
}
if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) {
values[ index ] = getDefaultDisplay( elem );
}
} else {
if ( display !== "none" ) {
values[ index ] = "none";
// Remember what we're overwriting
dataPriv.set( elem, "display", display );
}
}
}
// Set the display of the elements in a second loop to avoid constant reflow
for ( index = 0; index < length; index++ ) {
if ( values[ index ] != null ) {
elements[ index ].style.display = values[ index ];
}
}
return elements;
}
jQuery.fn.extend( {
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
if ( typeof state === "boolean" ) {
return state ? this.show() : this.hide();
}
return this.each( function() {
if ( isHiddenWithinTree( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
} );
}
} );
var rcheckableType = ( /^(?:checkbox|radio)$/i );
var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]+)/i );
var rscriptType = ( /^$|\/(?:java|ecma)script/i );
// We have to close these tags to support XHTML (#13200)
var wrapMap = {
// Support: IE <=9 only
option: [ 1, "<select multiple='multiple'>", "</select>" ],
// XHTML parsers do not magically insert elements in the
// same way that tag soup parsers do. So we cannot shorten
// this by omitting <tbody> or other required elements.
thead: [ 1, "<table>", "</table>" ],
col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
_default: [ 0, "", "" ]
};
// Support: IE <=9 only
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
function getAll( context, tag ) {
// Support: IE <=9 - 11 only
// Use typeof to avoid zero-argument method invocation on host objects (#15151)
var ret = typeof context.getElementsByTagName !== "undefined" ?
context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== "undefined" ?
context.querySelectorAll( tag || "*" ) :
[];
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], ret ) :
ret;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
dataPriv.set(
elems[ i ],
"globalEval",
!refElements || dataPriv.get( refElements[ i ], "globalEval" )
);
}
}
var rhtml = /<|&#?\w+;/;
function buildFragment( elems, context, scripts, selection, ignored ) {
var elem, tmp, tag, wrap, contains, j,
fragment = context.createDocumentFragment(),
nodes = [],
i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || fragment.appendChild( context.createElement( "div" ) );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ];
// Descend through wrappers to the right content
j = wrap[ 0 ];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge( nodes, tmp.childNodes );
// Remember the top-level container
tmp = fragment.firstChild;
// Ensure the created nodes are orphaned (#12392)
tmp.textContent = "";
}
}
}
// Remove wrapper from fragment
fragment.textContent = "";
i = 0;
while ( ( elem = nodes[ i++ ] ) ) {
// Skip elements already in the context collection (trac-4087)
if ( selection && jQuery.inArray( elem, selection ) > -1 ) {
if ( ignored ) {
ignored.push( elem );
}
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( fragment.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( ( elem = tmp[ j++ ] ) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
return fragment;
}
( function() {
var fragment = document.createDocumentFragment(),
div = fragment.appendChild( document.createElement( "div" ) ),
input = document.createElement( "input" );
// Support: Android 4.0 - 4.3 only
// Check state lost if the name is set (#11217)
// Support: Windows Web Apps (WWA)
// `name` and `type` must use .setAttribute for WWA (#14901)
input.setAttribute( "type", "radio" );
input.setAttribute( "checked", "checked" );
input.setAttribute( "name", "t" );
div.appendChild( input );
// Support: Android <=4.1 only
// Older WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE <=11 only
// Make sure textarea (and checkbox) defaultValue is properly cloned
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
} )();
var documentElement = document.documentElement;
var
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
// Support: IE <=9 only
// See #13393 for more info
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
function on( elem, types, selector, data, fn, one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
on( elem, type, selector, data, types[ type ], one );
}
return elem;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return elem;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return elem.each( function() {
jQuery.event.add( this, types, fn, data, selector );
} );
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var handleObjIn, eventHandle, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = dataPriv.get( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Ensure that invalid selectors throw exceptions at attach time
// Evaluate against documentElement in case elem is a non-element node (e.g., document)
if ( selector ) {
jQuery.find.matchesSelector( documentElement, selector );
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !( events = elemData.events ) ) {
events = elemData.events = {};
}
if ( !( eventHandle = elemData.handle ) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ?
jQuery.event.dispatch.apply( elem, arguments ) : undefined;
};
}
// Handle multiple events separated by a space
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[ t ] ) || [];
type = origType = tmp[ 1 ];
namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend( {
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join( "." )
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !( handlers = events[ type ] ) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener if the special events handler returns false
if ( !special.setup ||
special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, origCount, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = dataPriv.hasData( elem ) && dataPriv.get( elem );
if ( !elemData || !( events = elemData.events ) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[ t ] ) || [];
type = origType = tmp[ 1 ];
namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[ 2 ] &&
new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector ||
selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown ||
special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove data and the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
dataPriv.remove( elem, "handle events" );
}
},
dispatch: function( nativeEvent ) {
// Make a writable jQuery.Event from the native event object
var event = jQuery.event.fix( nativeEvent );
var i, j, ret, matched, handleObj, handlerQueue,
args = new Array( arguments.length ),
handlers = ( dataPriv.get( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[ 0 ] = event;
for ( i = 1; i < arguments.length; i++ ) {
args[ i ] = arguments[ i ];
}
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( ( handleObj = matched.handlers[ j++ ] ) &&
!event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or 2) have namespace(s)
// a subset or equal to those in the bound event (both can have no namespace).
if ( !event.rnamespace || event.rnamespace.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle ||
handleObj.handler ).apply( matched.elem, args );
if ( ret !== undefined ) {
if ( ( event.result = ret ) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var i, matches, sel, handleObj,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Support: IE <=9
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
//
// Support: Firefox <=42
// Avoid non-left-click in FF but don't block IE radio events (#3861, gh-2343)
if ( delegateCount && cur.nodeType &&
( event.type !== "click" || isNaN( event.button ) || event.button < 1 ) ) {
for ( ; cur !== this; cur = cur.parentNode || this ) {
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && ( cur.disabled !== true || event.type !== "click" ) ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) > -1 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push( { elem: cur, handlers: matches } );
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push( { elem: this, handlers: handlers.slice( delegateCount ) } );
}
return handlerQueue;
},
addProp: function( name, hook ) {
Object.defineProperty( jQuery.Event.prototype, name, {
enumerable: true,
configurable: true,
get: jQuery.isFunction( hook ) ?
function() {
if ( this.originalEvent ) {
return hook( this.originalEvent );
}
} :
function() {
if ( this.originalEvent ) {
return this.originalEvent[ name ];
}
},
set: function( value ) {
Object.defineProperty( this, name, {
enumerable: true,
configurable: true,
writable: true,
value: value
} );
}
} );
},
fix: function( originalEvent ) {
return originalEvent[ jQuery.expando ] ?
originalEvent :
new jQuery.Event( originalEvent );
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
this.focus();
return false;
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Support: Firefox 20+
// Firefox doesn't alert if the returnValue field is not set.
if ( event.result !== undefined && event.originalEvent ) {
event.originalEvent.returnValue = event.result;
}
}
}
}
};
jQuery.removeEvent = function( elem, type, handle ) {
// This "if" is needed for plain objects
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !( this instanceof jQuery.Event ) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = src.defaultPrevented ||
src.defaultPrevented === undefined &&
// Support: Android <=2.3 only
src.returnValue === false ?
returnTrue :
returnFalse;
// Create target properties
// Support: Safari <=6 - 7 only
// Target should not be a text node (#504, #13143)
this.target = ( src.target && src.target.nodeType === 3 ) ?
src.target.parentNode :
src.target;
this.currentTarget = src.currentTarget;
this.relatedTarget = src.relatedTarget;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
constructor: jQuery.Event,
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
isSimulated: false,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( e && !this.isSimulated ) {
e.preventDefault();
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( e && !this.isSimulated ) {
e.stopPropagation();
}
},
stopImmediatePropagation: function() {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue;
if ( e && !this.isSimulated ) {
e.stopImmediatePropagation();
}
this.stopPropagation();
}
};
// Includes all common event props including KeyEvent and MouseEvent specific props
jQuery.each( {
altKey: true,
bubbles: true,
cancelable: true,
changedTouches: true,
ctrlKey: true,
detail: true,
eventPhase: true,
metaKey: true,
pageX: true,
pageY: true,
shiftKey: true,
view: true,
"char": true,
charCode: true,
key: true,
keyCode: true,
button: true,
buttons: true,
clientX: true,
clientY: true,
offsetX: true,
offsetY: true,
pointerId: true,
pointerType: true,
screenX: true,
screenY: true,
targetTouches: true,
toElement: true,
touches: true,
which: function( event ) {
var button = event.button;
// Add which for key events
if ( event.which == null && rkeyEvent.test( event.type ) ) {
return event.charCode != null ? event.charCode : event.keyCode;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) {
return ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event.which;
}
}, jQuery.event.addProp );
// Create mouseenter/leave events using mouseover/out and event-time checks
// so that event delegation works in jQuery.
// Do the same for pointerenter/pointerleave and pointerover/pointerout
//
// Support: Safari 7 only
// Safari sends mouseenter too often; see:
// https://bugs.chromium.org/p/chromium/issues/detail?id=470258
// for the description of the bug (it existed in older Chrome versions as well).
jQuery.each( {
mouseenter: "mouseover",
mouseleave: "mouseout",
pointerenter: "pointerover",
pointerleave: "pointerout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mouseenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
} );
jQuery.fn.extend( {
on: function( types, selector, data, fn ) {
return on( this, types, selector, data, fn );
},
one: function( types, selector, data, fn ) {
return on( this, types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ?
handleObj.origType + "." + handleObj.namespace :
handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each( function() {
jQuery.event.remove( this, types, fn, selector );
} );
}
} );
var
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,
// Support: IE <=10 - 11, Edge 12 - 13
// In IE/Edge using regex groups here causes severe slowdowns.
// See https://connect.microsoft.com/IE/feedback/details/1736512/
rnoInnerhtml = /<script|<style|<link/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;
function manipulationTarget( elem, content ) {
if ( jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) {
return elem.getElementsByTagName( "tbody" )[ 0 ] || elem;
}
return elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[ 1 ];
} else {
elem.removeAttribute( "type" );
}
return elem;
}
function cloneCopyEvent( src, dest ) {
var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
if ( dest.nodeType !== 1 ) {
return;
}
// 1. Copy private data: events, handlers, etc.
if ( dataPriv.hasData( src ) ) {
pdataOld = dataPriv.access( src );
pdataCur = dataPriv.set( dest, pdataOld );
events = pdataOld.events;
if ( events ) {
delete pdataCur.handle;
pdataCur.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
}
// 2. Copy user data
if ( dataUser.hasData( src ) ) {
udataOld = dataUser.access( src );
udataCur = jQuery.extend( {}, udataOld );
dataUser.set( dest, udataCur );
}
}
// Fix IE bugs, see support tests
function fixInput( src, dest ) {
var nodeName = dest.nodeName.toLowerCase();
// Fails to persist the checked state of a cloned checkbox or radio button.
if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
dest.checked = src.checked;
// Fails to return the selected option to the default selected state when cloning options
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
function domManip( collection, args, callback, ignored ) {
// Flatten any nested arrays
args = concat.apply( [], args );
var fragment, first, scripts, hasScripts, node, doc,
i = 0,
l = collection.length,
iNoClone = l - 1,
value = args[ 0 ],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction ||
( l > 1 && typeof value === "string" &&
!support.checkClone && rchecked.test( value ) ) ) {
return collection.each( function( index ) {
var self = collection.eq( index );
if ( isFunction ) {
args[ 0 ] = value.call( this, index, self.html() );
}
domManip( self, args, callback, ignored );
} );
}
if ( l ) {
fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
// Require either new content or an interest in ignored elements to invoke the callback
if ( first || ignored ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item
// instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
// Support: Android <=4.0 only, PhantomJS 1 only
// push.apply(_, arraylike) throws on ancient WebKit
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( collection[ i ], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!dataPriv.access( node, "globalEval" ) &&
jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Optional AJAX dependency, but won't run scripts if not present
if ( jQuery._evalUrl ) {
jQuery._evalUrl( node.src );
}
} else {
DOMEval( node.textContent.replace( rcleanScript, "" ), doc );
}
}
}
}
}
}
return collection;
}
function remove( elem, selector, keepData ) {
var node,
nodes = selector ? jQuery.filter( selector, elem ) : elem,
i = 0;
for ( ; ( node = nodes[ i ] ) != null; i++ ) {
if ( !keepData && node.nodeType === 1 ) {
jQuery.cleanData( getAll( node ) );
}
if ( node.parentNode ) {
if ( keepData && jQuery.contains( node.ownerDocument, node ) ) {
setGlobalEval( getAll( node, "script" ) );
}
node.parentNode.removeChild( node );
}
}
return elem;
}
jQuery.extend( {
htmlPrefilter: function( html ) {
return html.replace( rxhtmlTag, "<$1></$2>" );
},
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var i, l, srcElements, destElements,
clone = elem.cloneNode( true ),
inPage = jQuery.contains( elem.ownerDocument, elem );
// Fix IE cloning issues
if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&
!jQuery.isXMLDoc( elem ) ) {
// We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
fixInput( srcElements[ i ], destElements[ i ] );
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
cloneCopyEvent( srcElements[ i ], destElements[ i ] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
// Return the cloned set
return clone;
},
cleanData: function( elems ) {
var data, elem, type,
special = jQuery.event.special,
i = 0;
for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) {
if ( acceptData( elem ) ) {
if ( ( data = elem[ dataPriv.expando ] ) ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Support: Chrome <=35 - 45+
// Assign undefined instead of using delete, see Data#remove
elem[ dataPriv.expando ] = undefined;
}
if ( elem[ dataUser.expando ] ) {
// Support: Chrome <=35 - 45+
// Assign undefined instead of using delete, see Data#remove
elem[ dataUser.expando ] = undefined;
}
}
}
}
} );
jQuery.fn.extend( {
detach: function( selector ) {
return remove( this, selector, true );
},
remove: function( selector ) {
return remove( this, selector );
},
text: function( value ) {
return access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().each( function() {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.textContent = value;
}
} );
}, null, value, arguments.length );
},
append: function() {
return domManip( this, arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
} );
},
prepend: function() {
return domManip( this, arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
} );
},
before: function() {
return domManip( this, arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
} );
},
after: function() {
return domManip( this, arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
} );
},
empty: function() {
var elem,
i = 0;
for ( ; ( elem = this[ i ] ) != null; i++ ) {
if ( elem.nodeType === 1 ) {
// Prevent memory leaks
jQuery.cleanData( getAll( elem, false ) );
// Remove any remaining nodes
elem.textContent = "";
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function() {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
} );
},
html: function( value ) {
return access( this, function( value ) {
var elem = this[ 0 ] || {},
i = 0,
l = this.length;
if ( value === undefined && elem.nodeType === 1 ) {
return elem.innerHTML;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
value = jQuery.htmlPrefilter( value );
try {
for ( ; i < l; i++ ) {
elem = this[ i ] || {};
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch ( e ) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var ignored = [];
// Make the changes, replacing each non-ignored context element with the new content
return domManip( this, arguments, function( elem ) {
var parent = this.parentNode;
if ( jQuery.inArray( this, ignored ) < 0 ) {
jQuery.cleanData( getAll( this ) );
if ( parent ) {
parent.replaceChild( elem, this );
}
}
// Force callback invocation
}, ignored );
}
} );
jQuery.each( {
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1,
i = 0;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone( true );
jQuery( insert[ i ] )[ original ]( elems );
// Support: Android <=4.0 only, PhantomJS 1 only
// .get() because push.apply(_, arraylike) throws on ancient WebKit
push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
} );
var rmargin = ( /^margin/ );
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
var getStyles = function( elem ) {
// Support: IE <=11 only, Firefox <=30 (#15098, #14150)
// IE throws on elements created in popups
// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
var view = elem.ownerDocument.defaultView;
if ( !view || !view.opener ) {
view = window;
}
return view.getComputedStyle( elem );
};
( function() {
// Executing both pixelPosition & boxSizingReliable tests require only one layout
// so they're executed at the same time to save the second computation.
function computeStyleTests() {
// This is a singleton, we need to execute it only once
if ( !div ) {
return;
}
div.style.cssText =
"box-sizing:border-box;" +
"position:relative;display:block;" +
"margin:auto;border:1px;padding:1px;" +
"top:1%;width:50%";
div.innerHTML = "";
documentElement.appendChild( container );
var divStyle = window.getComputedStyle( div );
pixelPositionVal = divStyle.top !== "1%";
// Support: Android 4.0 - 4.3 only, Firefox <=3 - 44
reliableMarginLeftVal = divStyle.marginLeft === "2px";
boxSizingReliableVal = divStyle.width === "4px";
// Support: Android 4.0 - 4.3 only
// Some styles come back with percentage values, even though they shouldn't
div.style.marginRight = "50%";
pixelMarginRightVal = divStyle.marginRight === "4px";
documentElement.removeChild( container );
// Nullify the div so it wouldn't be stored in the memory and
// it will also be a sign that checks already performed
div = null;
}
var pixelPositionVal, boxSizingReliableVal, pixelMarginRightVal, reliableMarginLeftVal,
container = document.createElement( "div" ),
div = document.createElement( "div" );
// Finish early in limited (non-browser) environments
if ( !div.style ) {
return;
}
// Support: IE <=9 - 11 only
// Style of cloned element affects source element cloned (#8908)
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" +
"padding:0;margin-top:1px;position:absolute";
container.appendChild( div );
jQuery.extend( support, {
pixelPosition: function() {
computeStyleTests();
return pixelPositionVal;
},
boxSizingReliable: function() {
computeStyleTests();
return boxSizingReliableVal;
},
pixelMarginRight: function() {
computeStyleTests();
return pixelMarginRightVal;
},
reliableMarginLeft: function() {
computeStyleTests();
return reliableMarginLeftVal;
}
} );
} )();
function curCSS( elem, name, computed ) {
var width, minWidth, maxWidth, ret,
style = elem.style;
computed = computed || getStyles( elem );
// Support: IE <=9 only
// getPropertyValue is only needed for .css('filter') (#12537)
if ( computed ) {
ret = computed.getPropertyValue( name ) || computed[ name ];
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Android Browser returns percentage for some values,
// but width seems to be reliably pixels.
// This is against the CSSOM draft spec:
// https://drafts.csswg.org/cssom/#resolved-values
if ( !support.pixelMarginRight() && rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret !== undefined ?
// Support: IE <=9 - 11 only
// IE returns zIndex value as an integer.
ret + "" :
ret;
}
function addGetHookIf( conditionFn, hookFn ) {
// Define the hook, we'll check on the first run if it's really needed.
return {
get: function() {
if ( conditionFn() ) {
// Hook not needed (or it's not possible to use it due
// to missing dependency), remove it.
delete this.get;
return;
}
// Hook needed; redefine it so that the support test is not executed again.
return ( this.get = hookFn ).apply( this, arguments );
}
};
}
var
// Swappable if display is none or starts with table
// except "table", "table-cell", or "table-caption"
// See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: "0",
fontWeight: "400"
},
cssPrefixes = [ "Webkit", "Moz", "ms" ],
emptyStyle = document.createElement( "div" ).style;
// Return a css property mapped to a potentially vendor prefixed property
function vendorPropName( name ) {
// Shortcut for names that are not vendor prefixed
if ( name in emptyStyle ) {
return name;
}
// Check for vendor prefixed names
var capName = name[ 0 ].toUpperCase() + name.slice( 1 ),
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in emptyStyle ) {
return name;
}
}
}
function setPositiveNumber( elem, value, subtract ) {
// Any relative (+/-) values have already been
// normalized at this point
var matches = rcssNum.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// Both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// At this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// At this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// At this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var val,
valueIsBorderBox = true,
styles = getStyles( elem ),
isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// Support: IE <=11 only
// Running getBoundingClientRect on a disconnected node
// in IE throws an error.
if ( elem.getClientRects().length ) {
val = elem.getBoundingClientRect()[ name ];
}
// Some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test( val ) ) {
return val;
}
// Check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox &&
( support.boxSizingReliable() || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// Use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
jQuery.extend( {
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"animationIterationCount": true,
"columnCount": true,
"fillOpacity": true,
"flexGrow": true,
"flexShrink": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"order": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
"float": "cssFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] ||
( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName );
// Gets hook for the prefixed version, then unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// Convert "+=" or "-=" to relative numbers (#7345)
if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) {
value = adjustCSS( elem, name, ret );
// Fixes bug #9237
type = "number";
}
// Make sure that null and NaN values aren't set (#7116)
if ( value == null || value !== value ) {
return;
}
// If a number was passed in, add the unit (except for certain CSS properties)
if ( type === "number" ) {
value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" );
}
// background-* props affect original clone's values
if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !( "set" in hooks ) ||
( value = hooks.set( elem, value, extra ) ) !== undefined ) {
style[ name ] = value;
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks &&
( ret = hooks.get( elem, false, extra ) ) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var val, num, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] ||
( jQuery.cssProps[ origName ] = vendorPropName( origName ) || origName );
// Try prefixed name followed by the unprefixed name
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
// Convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Make numeric if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || isFinite( num ) ? num || 0 : val;
}
return val;
}
} );
jQuery.each( [ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// Certain elements can have dimension info if we invisibly show them
// but it must have a current display style that would benefit
return rdisplayswap.test( jQuery.css( elem, "display" ) ) &&
// Support: Safari 8+
// Table columns in Safari have non-zero offsetWidth & zero
// getBoundingClientRect().width unless display is changed.
// Support: IE <=11 only
// Running getBoundingClientRect on a disconnected node
// in IE throws an error.
( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ?
swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
} ) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var matches,
styles = extra && getStyles( elem ),
subtract = extra && augmentWidthOrHeight(
elem,
name,
extra,
jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
);
// Convert to pixels if value adjustment is needed
if ( subtract && ( matches = rcssNum.exec( value ) ) &&
( matches[ 3 ] || "px" ) !== "px" ) {
elem.style[ name ] = value;
value = jQuery.css( elem, name );
}
return setPositiveNumber( elem, value, subtract );
}
};
} );
jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft,
function( elem, computed ) {
if ( computed ) {
return ( parseFloat( curCSS( elem, "marginLeft" ) ) ||
elem.getBoundingClientRect().left -
swap( elem, { marginLeft: 0 }, function() {
return elem.getBoundingClientRect().left;
} )
) + "px";
}
}
);
// These hooks are used by animate to expand properties
jQuery.each( {
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// Assumes a single number if not a string
parts = typeof value === "string" ? value.split( " " ) : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
} );
jQuery.fn.extend( {
css: function( name, value ) {
return access( this, function( elem, name, value ) {
var styles, len,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
}
} );
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 || jQuery.easing._default;
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;
// Use a property on the element directly when it is not a DOM element,
// or when there is no matching style property that exists.
if ( tween.elem.nodeType !== 1 ||
tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) {
return tween.elem[ tween.prop ];
}
// Passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails.
// Simple values such as "10px" are parsed to Float;
// complex values such as "rotate(1rad)" are returned as-is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// Use step hook for back compat.
// Use cssHook if its there.
// Use .style if available and use plain properties where available.
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.nodeType === 1 &&
( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null ||
jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Support: IE <=9 only
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p * Math.PI ) / 2;
},
_default: "swing"
};
jQuery.fx = Tween.prototype.init;
// Back compat <1.8 extension point
jQuery.fx.step = {};
var
fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rrun = /queueHooks$/;
function raf() {
if ( timerId ) {
window.requestAnimationFrame( raf );
jQuery.fx.tick();
}
}
// Animations created synchronously will run synchronously
function createFxNow() {
window.setTimeout( function() {
fxNow = undefined;
} );
return ( fxNow = jQuery.now() );
}
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
i = 0,
attrs = { height: type };
// If we include width, step value is 1 to do all cssExpand values,
// otherwise step value is 2 to skip over Left and Right
includeWidth = includeWidth ? 1 : 0;
for ( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
function createTween( value, prop, animation ) {
var tween,
collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) {
// We're done with this property
return tween;
}
}
}
function defaultPrefilter( elem, props, opts ) {
/* jshint validthis: true */
var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display,
isBox = "width" in props || "height" in props,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHiddenWithinTree( elem ),
dataShow = dataPriv.get( elem, "fxshow" );
// Queue-skipping animations hijack the fx hooks
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() {
// Ensure the complete handler is called before this completes
anim.always( function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
} );
} );
}
// Detect show/hide animations
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.test( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
// Pretend to be hidden if this is a "show" and
// there is still data from a stopped show/hide
if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
hidden = true;
// Ignore all other no-op show/hide data
} else {
continue;
}
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
}
}
// Bail out if this is a no-op like .hide().hide()
propTween = !jQuery.isEmptyObject( props );
if ( !propTween && jQuery.isEmptyObject( orig ) ) {
return;
}
// Restrict "overflow" and "display" styles during box animations
if ( isBox && elem.nodeType === 1 ) {
// Support: IE <=9 - 11, Edge 12 - 13
// Record all 3 overflow attributes because IE does not infer the shorthand
// from identically-valued overflowX and overflowY
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Identify a display type, preferring old show/hide data over the CSS cascade
restoreDisplay = dataShow && dataShow.display;
if ( restoreDisplay == null ) {
restoreDisplay = dataPriv.get( elem, "display" );
}
display = jQuery.css( elem, "display" );
if ( display === "none" ) {
if ( restoreDisplay ) {
display = restoreDisplay;
} else {
// Get nonempty value(s) by temporarily forcing visibility
showHide( [ elem ], true );
restoreDisplay = elem.style.display || restoreDisplay;
display = jQuery.css( elem, "display" );
showHide( [ elem ] );
}
}
// Animate inline elements as inline-block
if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) {
if ( jQuery.css( elem, "float" ) === "none" ) {
// Restore the original display value at the end of pure show/hide animations
if ( !propTween ) {
anim.done( function() {
style.display = restoreDisplay;
} );
if ( restoreDisplay == null ) {
display = style.display;
restoreDisplay = display === "none" ? "" : display;
}
}
style.display = "inline-block";
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
anim.always( function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
} );
}
// Implement show/hide animations
propTween = false;
for ( prop in orig ) {
// General show/hide setup for this element animation
if ( !propTween ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } );
}
// Store hidden/visible for toggle so `.stop().toggle()` "reverses"
if ( toggle ) {
dataShow.hidden = !hidden;
}
// Show elements before animating them
if ( hidden ) {
showHide( [ elem ], true );
}
/* jshint -W083 */
anim.done( function() {
// The final step of a "hide" animation is actually hiding the element
if ( !hidden ) {
showHide( [ elem ] );
}
dataPriv.remove( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
} );
}
// Per-property setup
propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = propTween.start;
if ( hidden ) {
propTween.end = propTween.start;
propTween.start = 0;
}
}
}
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// Not quite $.extend, this won't overwrite existing keys.
// Reusing 'index' because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = Animation.prefilters.length,
deferred = jQuery.Deferred().always( function() {
// Don't match elem in the :animated selector
delete tick.elem;
} ),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// Support: Android 2.3 only
// Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ] );
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise( {
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, {
specialEasing: {},
easing: jQuery.easing._default
}, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// If we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// Resolve when we played the last frame; otherwise, reject
if ( gotoEnd ) {
deferred.notifyWith( elem, [ animation, 1, 0 ] );
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 = Animation.prefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
if ( jQuery.isFunction( result.stop ) ) {
jQuery._queueHooks( animation.elem, animation.opts.queue ).stop =
jQuery.proxy( result.stop, result );
}
return result;
}
}
jQuery.map( props, createTween, animation );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
} )
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
jQuery.Animation = jQuery.extend( Animation, {
tweeners: {
"*": [ function( prop, value ) {
var tween = this.createTween( prop, value );
adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween );
return tween;
} ]
},
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.match( rnotwhite );
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || [];
Animation.tweeners[ prop ].unshift( callback );
}
},
prefilters: [ defaultPrefilter ],
prefilter: function( callback, prepend ) {
if ( prepend ) {
Animation.prefilters.unshift( callback );
} else {
Animation.prefilters.push( callback );
}
}
} );
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
// Go to the end state if fx are off or if document is hidden
if ( jQuery.fx.off || document.hidden ) {
opt.duration = 0;
} else {
opt.duration = typeof opt.duration === "number" ?
opt.duration : opt.duration in jQuery.fx.speeds ?
jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
}
// Normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.fn.extend( {
fadeTo: function( speed, to, easing, callback ) {
// Show any hidden elements after setting opacity to 0
return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show()
// Animate to the value specified
.end().animate( { opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations, or finishing resolves immediately
if ( empty || dataPriv.get( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each( function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = dataPriv.get( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this &&
( type == null || timers[ index ].queue === type ) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// Start the next in the queue if the last step wasn't forced.
// Timers currently will call their complete callbacks, which
// will dequeue but only if they were gotoEnd.
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
} );
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each( function() {
var index,
data = dataPriv.get( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// Enable finishing flag on private data
data.finish = true;
// Empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.stop ) {
hooks.stop.call( this, true );
}
// Look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// Look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// Turn off finishing flag
delete data.finish;
} );
}
} );
jQuery.each( [ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
} );
// Generate shortcuts for custom animations
jQuery.each( {
slideDown: genFx( "show" ),
slideUp: genFx( "hide" ),
slideToggle: genFx( "toggle" ),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
} );
jQuery.timers = [];
jQuery.fx.tick = function() {
var timer,
i = 0,
timers = jQuery.timers;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
jQuery.timers.push( timer );
if ( timer() ) {
jQuery.fx.start();
} else {
jQuery.timers.pop();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = window.requestAnimationFrame ?
window.requestAnimationFrame( raf ) :
window.setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
if ( window.cancelAnimationFrame ) {
window.cancelAnimationFrame( timerId );
} else {
window.clearInterval( timerId );
}
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Based off of the plugin by Clint Helfers, with permission.
// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/
jQuery.fn.delay = function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = window.setTimeout( next, time );
hooks.stop = function() {
window.clearTimeout( timeout );
};
} );
};
( function() {
var input = document.createElement( "input" ),
select = document.createElement( "select" ),
opt = select.appendChild( document.createElement( "option" ) );
input.type = "checkbox";
// Support: Android <=4.3 only
// Default value for a checkbox should be "on"
support.checkOn = input.value !== "";
// Support: IE <=11 only
// Must access selectedIndex to make default options select
support.optSelected = opt.selected;
// Support: IE <=11 only
// An input loses its value after becoming a radio
input = document.createElement( "input" );
input.value = "t";
input.type = "radio";
support.radioValue = input.value === "t";
} )();
var boolHook,
attrHandle = jQuery.expr.attrHandle;
jQuery.fn.extend( {
attr: function( name, value ) {
return access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each( function() {
jQuery.removeAttr( this, name );
} );
}
} );
jQuery.extend( {
attr: function( elem, name, value ) {
var ret, hooks,
nType = elem.nodeType;
// Don't get/set attributes on text, comment and attribute nodes
if ( nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
// Attribute hooks are determined by the lowercase version
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
hooks = jQuery.attrHooks[ name.toLowerCase() ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : undefined );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
}
if ( hooks && "set" in hooks &&
( ret = hooks.set( elem, value, name ) ) !== undefined ) {
return ret;
}
elem.setAttribute( name, value + "" );
return value;
}
if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
return ret;
}
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ? undefined : ret;
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !support.radioValue && value === "radio" &&
jQuery.nodeName( elem, "input" ) ) {
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
removeAttr: function( elem, value ) {
var name,
i = 0,
attrNames = value && value.match( rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( ( name = attrNames[ i++ ] ) ) {
elem.removeAttribute( name );
}
}
}
} );
// Hooks for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
elem.setAttribute( name, name );
}
return name;
}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = attrHandle[ name ] || jQuery.find.attr;
attrHandle[ name ] = function( elem, name, isXML ) {
var ret, handle,
lowercaseName = name.toLowerCase();
if ( !isXML ) {
// Avoid an infinite loop by temporarily removing this function from the getter
handle = attrHandle[ lowercaseName ];
attrHandle[ lowercaseName ] = ret;
ret = getter( elem, name, isXML ) != null ?
lowercaseName :
null;
attrHandle[ lowercaseName ] = handle;
}
return ret;
};
} );
var rfocusable = /^(?:input|select|textarea|button)$/i,
rclickable = /^(?:a|area)$/i;
jQuery.fn.extend( {
prop: function( name, value ) {
return access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
return this.each( function() {
delete this[ jQuery.propFix[ name ] || name ];
} );
}
} );
jQuery.extend( {
prop: function( elem, name, value ) {
var ret, hooks,
nType = elem.nodeType;
// Don't get/set properties on text, comment and attribute nodes
if ( nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks &&
( ret = hooks.set( elem, value, name ) ) !== undefined ) {
return ret;
}
return ( elem[ name ] = value );
}
if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
return ret;
}
return elem[ name ];
},
propHooks: {
tabIndex: {
get: function( elem ) {
// Support: IE <=9 - 11 only
// elem.tabIndex doesn't always return the
// correct value when it hasn't been explicitly set
// https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr( elem, "tabindex" );
return tabindex ?
parseInt( tabindex, 10 ) :
rfocusable.test( elem.nodeName ) ||
rclickable.test( elem.nodeName ) && elem.href ?
0 :
-1;
}
}
},
propFix: {
"for": "htmlFor",
"class": "className"
}
} );
// Support: IE <=11 only
// Accessing the selectedIndex property
// forces the browser to respect setting selected
// on the option
// The getter ensures a default option is selected
// when in an optgroup
if ( !support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent && parent.parentNode ) {
parent.parentNode.selectedIndex;
}
return null;
},
set: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
}
};
}
jQuery.each( [
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
} );
var rclass = /[\t\r\n\f]/g;
function getClass( elem ) {
return elem.getAttribute && elem.getAttribute( "class" ) || "";
}
jQuery.fn.extend( {
addClass: function( value ) {
var classes, elem, cur, curValue, clazz, j, finalValue,
i = 0;
if ( jQuery.isFunction( value ) ) {
return this.each( function( j ) {
jQuery( this ).addClass( value.call( this, j, getClass( this ) ) );
} );
}
if ( typeof value === "string" && value ) {
classes = value.match( rnotwhite ) || [];
while ( ( elem = this[ i++ ] ) ) {
curValue = getClass( elem );
cur = elem.nodeType === 1 &&
( " " + curValue + " " ).replace( rclass, " " );
if ( cur ) {
j = 0;
while ( ( clazz = classes[ j++ ] ) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
// Only assign if different to avoid unneeded rendering.
finalValue = jQuery.trim( cur );
if ( curValue !== finalValue ) {
elem.setAttribute( "class", finalValue );
}
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, curValue, clazz, j, finalValue,
i = 0;
if ( jQuery.isFunction( value ) ) {
return this.each( function( j ) {
jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) );
} );
}
if ( !arguments.length ) {
return this.attr( "class", "" );
}
if ( typeof value === "string" && value ) {
classes = value.match( rnotwhite ) || [];
while ( ( elem = this[ i++ ] ) ) {
curValue = getClass( elem );
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 &&
( " " + curValue + " " ).replace( rclass, " " );
if ( cur ) {
j = 0;
while ( ( clazz = classes[ j++ ] ) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) > -1 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
// Only assign if different to avoid unneeded rendering.
finalValue = jQuery.trim( cur );
if ( curValue !== finalValue ) {
elem.setAttribute( "class", finalValue );
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value;
if ( typeof stateVal === "boolean" && type === "string" ) {
return stateVal ? this.addClass( value ) : this.removeClass( value );
}
if ( jQuery.isFunction( value ) ) {
return this.each( function( i ) {
jQuery( this ).toggleClass(
value.call( this, i, getClass( this ), stateVal ),
stateVal
);
} );
}
return this.each( function() {
var className, i, self, classNames;
if ( type === "string" ) {
// Toggle individual class names
i = 0;
self = jQuery( this );
classNames = value.match( rnotwhite ) || [];
while ( ( className = classNames[ i++ ] ) ) {
// Check each className given, space separated list
if ( self.hasClass( className ) ) {
self.removeClass( className );
} else {
self.addClass( className );
}
}
// Toggle whole class name
} else if ( value === undefined || type === "boolean" ) {
className = getClass( this );
if ( className ) {
// Store className if set
dataPriv.set( this, "__className__", className );
}
// If the element has a class name or if we're passed `false`,
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
if ( this.setAttribute ) {
this.setAttribute( "class",
className || value === false ?
"" :
dataPriv.get( this, "__className__" ) || ""
);
}
}
} );
},
hasClass: function( selector ) {
var className, elem,
i = 0;
className = " " + selector + " ";
while ( ( elem = this[ i++ ] ) ) {
if ( elem.nodeType === 1 &&
( " " + getClass( elem ) + " " ).replace( rclass, " " )
.indexOf( className ) > -1
) {
return true;
}
}
return false;
}
} );
var rreturn = /\r/g,
rspaces = /[\x20\t\r\n\f]+/g;
jQuery.fn.extend( {
val: function( value ) {
var hooks, ret, isFunction,
elem = this[ 0 ];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] ||
jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks &&
"get" in hooks &&
( ret = hooks.get( elem, "value" ) ) !== undefined
) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// Handle most common string cases
ret.replace( rreturn, "" ) :
// Handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each( function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map( val, function( value ) {
return value == null ? "" : value + "";
} );
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
} );
}
} );
jQuery.extend( {
valHooks: {
option: {
get: function( elem ) {
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
// Support: IE <=10 - 11 only
// option.text throws exceptions (#14686, #14858)
// Strip and collapse whitespace
// https://html.spec.whatwg.org/#strip-and-collapse-whitespace
jQuery.trim( jQuery.text( elem ) ).replace( rspaces, " " );
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one",
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// Support: IE <=9 only
// IE8-9 doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
!option.disabled &&
( !option.parentNode.disabled ||
!jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( option.selected =
jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1
) {
optionSet = true;
}
}
// Force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return values;
}
}
}
} );
// Radios and checkboxes getter/setter
jQuery.each( [ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 );
}
}
};
if ( !support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
return elem.getAttribute( "value" ) === null ? "on" : elem.value;
};
}
} );
// Return jQuery for attributes-only inclusion
var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/;
jQuery.extend( jQuery.event, {
trigger: function( event, data, elem, onlyHandlers ) {
var i, cur, tmp, bubbleType, ontype, handle, special,
eventPath = [ elem || document ],
type = hasOwn.call( event, "type" ) ? event.type : event,
namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf( "." ) > -1 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split( "." );
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf( ":" ) < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join( "." );
event.rnamespace = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === ( elem.ownerDocument || document ) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] &&
dataPriv.get( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && handle.apply && acceptData( cur ) ) {
event.result = handle.apply( cur, data );
if ( event.result === false ) {
event.preventDefault();
}
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( ( !special._default ||
special._default.apply( eventPath.pop(), data ) === false ) &&
acceptData( elem ) ) {
// Call a native DOM method on the target with the same name as the event.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
// Piggyback on a donor event to simulate a different one
// Used only for `focus(in | out)` events
simulate: function( type, elem, event ) {
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true
}
);
jQuery.event.trigger( e, null, elem );
}
} );
jQuery.fn.extend( {
trigger: function( type, data ) {
return this.each( function() {
jQuery.event.trigger( type, data, this );
} );
},
triggerHandler: function( type, data ) {
var elem = this[ 0 ];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
} );
jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup contextmenu" ).split( " " ),
function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
} );
jQuery.fn.extend( {
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
} );
support.focusin = "onfocusin" in window;
// Support: Firefox <=44
// Firefox doesn't have focus(in | out) events
// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787
//
// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1
// focus(in | out) events fire after focus & blur events,
// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order
// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857
if ( !support.focusin ) {
jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler on the document while someone wants focusin/focusout
var handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) );
};
jQuery.event.special[ fix ] = {
setup: function() {
var doc = this.ownerDocument || this,
attaches = dataPriv.access( doc, fix );
if ( !attaches ) {
doc.addEventListener( orig, handler, true );
}
dataPriv.access( doc, fix, ( attaches || 0 ) + 1 );
},
teardown: function() {
var doc = this.ownerDocument || this,
attaches = dataPriv.access( doc, fix ) - 1;
if ( !attaches ) {
doc.removeEventListener( orig, handler, true );
dataPriv.remove( doc, fix );
} else {
dataPriv.access( doc, fix, attaches );
}
}
};
} );
}
var location = window.location;
var nonce = jQuery.now();
var rquery = ( /\?/ );
// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
var xml;
if ( !data || typeof data !== "string" ) {
return null;
}
// Support: IE 9 - 11 only
// IE throws on parseFromString with invalid input.
try {
xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" );
} catch ( e ) {
xml = undefined;
}
if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
};
var
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams(
prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]",
v,
traditional,
add
);
}
} );
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, valueOrFunction ) {
// If value is a function, invoke it and use its return value
var value = jQuery.isFunction( valueOrFunction ) ?
valueOrFunction() :
valueOrFunction;
s[ s.length ] = encodeURIComponent( key ) + "=" +
encodeURIComponent( value == null ? "" : value );
};
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
} );
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" );
};
jQuery.fn.extend( {
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map( function() {
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
} )
.filter( function() {
var type = this.type;
// Use .is( ":disabled" ) so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !rcheckableType.test( type ) );
} )
.map( function( i, elem ) {
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ) {
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
} ) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
} ).get();
}
} );
var
r20 = /%20/g,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat( "*" ),
// Anchor tag for parsing the document origin
originAnchor = document.createElement( "a" );
originAnchor.href = location.href;
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( ( dataType = dataTypes[ i++ ] ) ) {
// Prepend if requested
if ( dataType[ 0 ] === "+" ) {
dataType = dataType.slice( 1 ) || "*";
( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func );
// Otherwise append
} else {
( structure[ dataType ] = structure[ dataType ] || [] ).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if ( typeof dataTypeOrTransport === "string" &&
!seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
} );
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
/* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var ct, type, finalDataType, firstDataType,
contents = s.contents,
dataTypes = s.dataTypes;
// Remove auto dataType and get content-type in the process
while ( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
/* Chain conversions given the request and the original response
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert( s, response, jqXHR, isSuccess ) {
var conv2, current, conv, tmp, prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while ( current ) {
if ( s.responseFields[ current ] ) {
jqXHR[ s.responseFields[ current ] ] = response;
}
// Apply the dataFilter if provided
if ( !prev && isSuccess && s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
prev = current;
current = dataTypes.shift();
if ( current ) {
// There's only work to do if current dataType is non-auto
if ( current === "*" ) {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split( " " );
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.unshift( tmp[ 1 ] );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s.throws ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return {
state: "parsererror",
error: conv ? e : "No conversion from " + prev + " to " + current
};
}
}
}
}
}
}
return { state: "success", data: response };
}
jQuery.extend( {
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: location.href,
type: "GET",
isLocal: rlocalProtocol.test( location.protocol ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /\bxml\b/,
html: /\bhtml/,
json: /\bjson\b/
},
responseFields: {
xml: "responseXML",
text: "responseText",
json: "responseJSON"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": JSON.parse,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var transport,
// URL without anti-cache param
cacheURL,
// Response headers
responseHeadersString,
responseHeaders,
// timeout handle
timeoutTimer,
// Url cleanup var
urlAnchor,
// Request state (becomes false upon send and true upon completion)
completed,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// uncached part of the url
uncached,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context &&
( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery( callbackContext ) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks( "once memory" ),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( completed ) {
if ( !responseHeaders ) {
responseHeaders = {};
while ( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[ 1 ].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return completed ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
if ( completed == null ) {
name = requestHeadersNames[ name.toLowerCase() ] =
requestHeadersNames[ name.toLowerCase() ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( completed == null ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( completed ) {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
} else {
// Lazy-add the new callbacks in a way that preserves old ones
for ( code in map ) {
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR );
// Add protocol if not provided (prefilters might expect it)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || location.href ) + "" )
.replace( rprotocol, location.protocol + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];
// A cross-domain request is in order when the origin doesn't match the current origin.
if ( s.crossDomain == null ) {
urlAnchor = document.createElement( "a" );
// Support: IE <=8 - 11, Edge 12 - 13
// IE throws exception on accessing the href property if url is malformed,
// e.g. http://example.com:80x/
try {
urlAnchor.href = s.url;
// Support: IE <=8 - 11 only
// Anchor's host property isn't correctly set when s.url is relative
urlAnchor.href = urlAnchor.href;
s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !==
urlAnchor.protocol + "//" + urlAnchor.host;
} catch ( e ) {
// If there is an error parsing the URL, assume it is crossDomain,
// it can be rejected by the transport if it is invalid
s.crossDomain = true;
}
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( completed ) {
return jqXHR;
}
// We can fire global events as of now if asked to
// Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
fireGlobals = jQuery.event && s.global;
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
// Remove hash to simplify url manipulation
cacheURL = s.url.replace( rhash, "" );
// More options handling for requests with no content
if ( !s.hasContent ) {
// Remember the hash so we can put it back
uncached = s.url.slice( cacheURL.length );
// If data is available, append data to url
if ( s.data ) {
cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in uncached url if needed
if ( s.cache === false ) {
cacheURL = cacheURL.replace( rts, "" );
uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce++ ) + uncached;
}
// Put hash and anti-cache on the URL that will be requested (gh-1732)
s.url = cacheURL + uncached;
// Change '%20' to '+' if this is encoded form body content (gh-2658)
} else if ( s.data && s.processData &&
( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) {
s.data = s.data.replace( r20, "+" );
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
}
if ( jQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
s.accepts[ s.dataTypes[ 0 ] ] +
( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend &&
( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// Aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
completeDeferred.add( s.complete );
jqXHR.done( s.success );
jqXHR.fail( s.error );
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// If request was aborted inside ajaxSend, stop there
if ( completed ) {
return jqXHR;
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = window.setTimeout( function() {
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
completed = false;
transport.send( requestHeaders, done );
} catch ( e ) {
// Rethrow post-completion exceptions
if ( completed ) {
throw e;
}
// Propagate others as results
done( -1, e );
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Ignore repeat invocations
if ( completed ) {
return;
}
completed = true;
// Clear timeout if it exists
if ( timeoutTimer ) {
window.clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert( s, response, jqXHR, isSuccess );
// If successful, handle type chaining
if ( isSuccess ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader( "Last-Modified" );
if ( modified ) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader( "etag" );
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 || s.type === "HEAD" ) {
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.error;
isSuccess = !error;
}
} else {
// Extract error from statusText and normalize for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
return jqXHR;
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
}
} );
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// Shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
// The url can be an options object (which then must have .url)
return jQuery.ajax( jQuery.extend( {
url: url,
type: method,
dataType: type,
data: data,
success: callback
}, jQuery.isPlainObject( url ) && url ) );
};
} );
jQuery._evalUrl = function( url ) {
return jQuery.ajax( {
url: url,
// Make this explicit, since user can override this through ajaxSetup (#11264)
type: "GET",
dataType: "script",
cache: true,
async: false,
global: false,
"throws": true
} );
};
jQuery.fn.extend( {
wrapAll: function( html ) {
var wrap;
if ( this[ 0 ] ) {
if ( jQuery.isFunction( html ) ) {
html = html.call( this[ 0 ] );
}
// The elements to wrap the target around
wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );
if ( this[ 0 ].parentNode ) {
wrap.insertBefore( this[ 0 ] );
}
wrap.map( function() {
var elem = this;
while ( elem.firstElementChild ) {
elem = elem.firstElementChild;
}
return elem;
} ).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each( function( i ) {
jQuery( this ).wrapInner( html.call( this, i ) );
} );
}
return this.each( function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
} );
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each( function( i ) {
jQuery( this ).wrapAll( isFunction ? html.call( this, i ) : html );
} );
},
unwrap: function( selector ) {
this.parent( selector ).not( "body" ).each( function() {
jQuery( this ).replaceWith( this.childNodes );
} );
return this;
}
} );
jQuery.expr.pseudos.hidden = function( elem ) {
return !jQuery.expr.pseudos.visible( elem );
};
jQuery.expr.pseudos.visible = function( elem ) {
return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};
jQuery.ajaxSettings.xhr = function() {
try {
return new window.XMLHttpRequest();
} catch ( e ) {}
};
var xhrSuccessStatus = {
// File protocol always yields status code 0, assume 200
0: 200,
// Support: IE <=9 only
// #1450: sometimes IE returns 1223 when it should be 204
1223: 204
},
xhrSupported = jQuery.ajaxSettings.xhr();
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
support.ajax = xhrSupported = !!xhrSupported;
jQuery.ajaxTransport( function( options ) {
var callback, errorCallback;
// Cross domain only allowed if supported through XMLHttpRequest
if ( support.cors || xhrSupported && !options.crossDomain ) {
return {
send: function( headers, complete ) {
var i,
xhr = options.xhr();
xhr.open(
options.type,
options.url,
options.async,
options.username,
options.password
);
// Apply custom fields if provided
if ( options.xhrFields ) {
for ( i in options.xhrFields ) {
xhr[ i ] = options.xhrFields[ i ];
}
}
// Override mime type if needed
if ( options.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( options.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Set headers
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
// Callback
callback = function( type ) {
return function() {
if ( callback ) {
callback = errorCallback = xhr.onload =
xhr.onerror = xhr.onabort = xhr.onreadystatechange = null;
if ( type === "abort" ) {
xhr.abort();
} else if ( type === "error" ) {
// Support: IE <=9 only
// On a manual native abort, IE9 throws
// errors on any property access that is not readyState
if ( typeof xhr.status !== "number" ) {
complete( 0, "error" );
} else {
complete(
// File: protocol always yields status 0; see #8605, #14207
xhr.status,
xhr.statusText
);
}
} else {
complete(
xhrSuccessStatus[ xhr.status ] || xhr.status,
xhr.statusText,
// Support: IE <=9 only
// IE9 has no XHR2 but throws on binary (trac-11426)
// For XHR2 non-text, let the caller handle it (gh-2498)
( xhr.responseType || "text" ) !== "text" ||
typeof xhr.responseText !== "string" ?
{ binary: xhr.response } :
{ text: xhr.responseText },
xhr.getAllResponseHeaders()
);
}
}
};
};
// Listen to events
xhr.onload = callback();
errorCallback = xhr.onerror = callback( "error" );
// Support: IE 9 only
// Use onreadystatechange to replace onabort
// to handle uncaught aborts
if ( xhr.onabort !== undefined ) {
xhr.onabort = errorCallback;
} else {
xhr.onreadystatechange = function() {
// Check readyState before timeout as it changes
if ( xhr.readyState === 4 ) {
// Allow onerror to be called first,
// but that will not handle a native abort
// Also, save errorCallback to a variable
// as xhr.onerror cannot be accessed
window.setTimeout( function() {
if ( callback ) {
errorCallback();
}
} );
}
};
}
// Create the abort callback
callback = callback( "abort" );
try {
// Do send the request (this may raise an exception)
xhr.send( options.hasContent && options.data || null );
} catch ( e ) {
// #14683: Only rethrow if this hasn't been notified as an error yet
if ( callback ) {
throw e;
}
}
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
} );
// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432)
jQuery.ajaxPrefilter( function( s ) {
if ( s.crossDomain ) {
s.contents.script = false;
}
} );
// Install script dataType
jQuery.ajaxSetup( {
accepts: {
script: "text/javascript, application/javascript, " +
"application/ecmascript, application/x-ecmascript"
},
contents: {
script: /\b(?:java|ecma)script\b/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
} );
// Handle cache's special case and crossDomain
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
}
} );
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function( s ) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script, callback;
return {
send: function( _, complete ) {
script = jQuery( "<script>" ).prop( {
charset: s.scriptCharset,
src: s.url
} ).on(
"load error",
callback = function( evt ) {
script.remove();
callback = null;
if ( evt ) {
complete( evt.type === "error" ? 404 : 200, evt.type );
}
}
);
// Use native DOM manipulation to avoid our domManip AJAX trickery
document.head.appendChild( script[ 0 ] );
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
} );
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup( {
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
} );
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" &&
( s.contentType || "" )
.indexOf( "application/x-www-form-urlencoded" ) === 0 &&
rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters[ "script json" ] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// Force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always( function() {
// If previous value didn't exist - remove it
if ( overwritten === undefined ) {
jQuery( window ).removeProp( callbackName );
// Otherwise restore preexisting value
} else {
window[ callbackName ] = overwritten;
}
// Save back as free
if ( s[ callbackName ] ) {
// Make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// Save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
} );
// Delegate to script
return "script";
}
} );
// Support: Safari 8 only
// In Safari 8 documents created via document.implementation.createHTMLDocument
// collapse sibling forms: the second one becomes a child of the first one.
// Because of that, this security measure has to be disabled in Safari 8.
// https://bugs.webkit.org/show_bug.cgi?id=137337
support.createHTMLDocument = ( function() {
var body = document.implementation.createHTMLDocument( "" ).body;
body.innerHTML = "<form></form><form></form>";
return body.childNodes.length === 2;
} )();
// Argument "data" should be string of html
// context (optional): If specified, the fragment will be created in this context,
// defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function( data, context, keepScripts ) {
if ( typeof data !== "string" ) {
return [];
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
var base, parsed, scripts;
if ( !context ) {
// Stop scripts or inline event handlers from being executed immediately
// by using document.implementation
if ( support.createHTMLDocument ) {
context = document.implementation.createHTMLDocument( "" );
// Set the base href for the created document
// so any parsed elements with URLs
// are based on the document's URL (gh-2965)
base = context.createElement( "base" );
base.href = document.location.href;
context.head.appendChild( base );
} else {
context = document;
}
}
parsed = rsingleTag.exec( data );
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[ 1 ] ) ];
}
parsed = buildFragment( [ data ], context, scripts );
if ( scripts && scripts.length ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
};
/**
* Load a url into a page
*/
jQuery.fn.load = function( url, params, callback ) {
var selector, type, response,
self = this,
off = url.indexOf( " " );
if ( off > -1 ) {
selector = jQuery.trim( url.slice( off ) );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax( {
url: url,
// If "type" variable is undefined, then "GET" method will be used.
// Make value of this field explicit since
// user can override it through ajaxSetup method
type: type || "GET",
dataType: "html",
data: params
} ).done( function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery( "<div>" ).append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
// If the request succeeds, this function gets "data", "status", "jqXHR"
// but they are ignored because response was set above.
// If it fails, this function gets "jqXHR", "status", "error"
} ).always( callback && function( jqXHR, status ) {
self.each( function() {
callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] );
} );
} );
}
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [
"ajaxStart",
"ajaxStop",
"ajaxComplete",
"ajaxError",
"ajaxSuccess",
"ajaxSend"
], function( i, type ) {
jQuery.fn[ type ] = function( fn ) {
return this.on( type, fn );
};
} );
jQuery.expr.pseudos.animated = function( elem ) {
return jQuery.grep( jQuery.timers, function( fn ) {
return elem === fn.elem;
} ).length;
};
/**
* Gets a window from an element
*/
function getWindow( elem ) {
return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
}
jQuery.offset = {
setOffset: function( elem, options, i ) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css( elem, "position" ),
curElem = jQuery( elem ),
props = {};
// Set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css( elem, "top" );
curCSSLeft = jQuery.css( elem, "left" );
calculatePosition = ( position === "absolute" || position === "fixed" ) &&
( curCSSTop + curCSSLeft ).indexOf( "auto" ) > -1;
// Need to be able to calculate position if either
// top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
// Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
options = options.call( elem, i, jQuery.extend( {}, curOffset ) );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend( {
offset: function( options ) {
// Preserve chaining for setter
if ( arguments.length ) {
return options === undefined ?
this :
this.each( function( i ) {
jQuery.offset.setOffset( this, options, i );
} );
}
var docElem, win, rect, doc,
elem = this[ 0 ];
if ( !elem ) {
return;
}
// Support: IE <=11 only
// Running getBoundingClientRect on a
// disconnected node in IE throws an error
if ( !elem.getClientRects().length ) {
return { top: 0, left: 0 };
}
rect = elem.getBoundingClientRect();
// Make sure element is not hidden (display: none)
if ( rect.width || rect.height ) {
doc = elem.ownerDocument;
win = getWindow( doc );
docElem = doc.documentElement;
return {
top: rect.top + win.pageYOffset - docElem.clientTop,
left: rect.left + win.pageXOffset - docElem.clientLeft
};
}
// Return zeros for disconnected and hidden elements (gh-2310)
return rect;
},
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
elem = this[ 0 ],
parentOffset = { top: 0, left: 0 };
// Fixed elements are offset from window (parentOffset = {top:0, left: 0},
// because it is its only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// Assume getBoundingClientRect is there when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset = {
top: parentOffset.top + jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ),
left: parentOffset.left + jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true )
};
}
// Subtract parent offsets and element margins
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
};
},
// This method will return documentElement in the following cases:
// 1) For the element inside the iframe without offsetParent, this method will return
// documentElement of the parent window
// 2) For the hidden or detached element
// 3) For body or html element, i.e. in case of the html node - it will return itself
//
// but those exceptions were never presented as a real life use-cases
// and might be considered as more preferable results.
//
// This logic, however, is not guaranteed and can change at any point in the future
offsetParent: function() {
return this.map( function() {
var offsetParent = this.offsetParent;
while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || documentElement;
} );
}
} );
// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
var top = "pageYOffset" === prop;
jQuery.fn[ method ] = function( val ) {
return access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? win[ prop ] : elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : win.pageXOffset,
top ? val : win.pageYOffset
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length );
};
} );
// Support: Safari <=7 - 9.1, Chrome <=37 - 49
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// Blink bug: https://bugs.chromium.org/p/chromium/issues/detail?id=589347
// getComputedStyle returns percent when specified for top/left/bottom/right;
// rather than make the css module depend on the offset module, just check for it here
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// If curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
);
} );
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name },
function( defaultExtra, funcName ) {
// Margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// $( window ).outerWidth/Height return w/h including scrollbars (gh-1729)
return funcName.indexOf( "outer" ) === 0 ?
elem[ "inner" + name ] :
elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
// whichever is greatest
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable );
};
} );
} );
jQuery.fn.extend( {
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ?
this.off( selector, "**" ) :
this.off( types, selector || "**", fn );
}
} );
jQuery.parseJSON = JSON.parse;
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
// Note that for maximum portability, libraries that are not jQuery should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. jQuery is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
if ( true ) {
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() {
return jQuery;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
var
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$;
jQuery.noConflict = function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
};
// Expose jQuery and $ identifiers, even in AMD
// (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( !noGlobal ) {
window.jQuery = window.$ = jQuery;
}
return jQuery;
} ) );
/***/ },
/* 2 */
/***/ function(module, exports) {
module.exports = React;
/***/ },
/* 3 */
/***/ function(module, exports) {
module.exports = ReactDOM;
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var React = __webpack_require__(2);
var HelloComponent = (function (_super) {
__extends(HelloComponent, _super);
function HelloComponent() {
_super.apply(this, arguments);
}
HelloComponent.prototype.render = function () {
return React.createElement("div", {className: this.props.class}, this.props.framework);
};
return HelloComponent;
}(React.Component));
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = HelloComponent;
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var React = __webpack_require__(2);
var LabelTextbox = (function (_super) {
__extends(LabelTextbox, _super);
function LabelTextbox() {
_super.apply(this, arguments);
}
LabelTextbox.prototype.update = function (event) {
var model = this.props.model;
var box = this.refs["box"];
model.UserId = box.value;
this.setState({ value: event.target.value });
};
LabelTextbox.prototype.render = function () {
var _this = this;
var classes = 'lb-txt ' + this.props.class;
var model = this.props.model;
return React.createElement("div", {className: classes}, React.createElement("div", {className: "label"}, this.props.label), React.createElement("div", {className: "txt-container"}, React.createElement("input", {ref: "box", className: "txt", type: this.props.type, onChange: function (e) { return _this.update(e); }, value: model.UserId})));
};
return LabelTextbox;
}(React.Component));
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = LabelTextbox;
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var validation_1 = __webpack_require__(7);
var validation_2 = __webpack_require__(7);
var validation_3 = __webpack_require__(7);
var WebUser = (function () {
function WebUser(userId, pwd) {
this.UserId = userId;
this.Pwd = pwd;
}
WebUser.prototype.validate = function () {
return validation_3.validate(this)[0];
};
__decorate([
validation_1.required
], WebUser.prototype, "UserId", void 0);
__decorate([
validation_1.required
], WebUser.prototype, "Pwd", void 0);
WebUser = __decorate([
validation_2.validatable
], WebUser);
return WebUser;
}());
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = WebUser;
/***/ },
/* 7 */
/***/ function(module, exports) {
"use strict";
function validatable(target) {
console.log("Validatable class annotation reached");
}
exports.validatable = validatable;
function init(target) {
if (!target.validators) {
target.validators = [];
}
}
function required(target, prop) {
console.log("Required property annotation reached");
init(target);
target.validators.push(function (modelErrors) {
if (!!this[prop]) {
modelErrors.push(prop.toString().concat(' validation success!'));
return true;
}
else {
modelErrors.push(prop.toString().concat(' cannot be empty!'));
return false;
}
});
}
exports.required = required;
function validate(target) {
var rlt = true;
var modelErrors = [];
if (target.validators != null && target.validators.length > 0) {
for (var _i = 0, _a = target.validators; _i < _a.length; _i++) {
var v = _a[_i];
rlt = v.call(target, modelErrors) && rlt;
}
}
console.log(modelErrors);
return [rlt, modelErrors];
}
exports.validate = validate;
/***/ }
/******/ ]);
//# sourceMappingURL=demo.bundle.js.map |
require('babel-polyfill');
/* eslint-disable */
// Webpack config for creating the production bundle.
var path = require('path');
var webpack = require('webpack');
var CleanPlugin = require('clean-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var strip = require('strip-loader');
var projectRootPath = path.resolve(__dirname, '../');
var assetsPath = path.resolve(projectRootPath, './static/dist');
// https://github.com/halt-hammerzeit/webpack-isomorphic-tools
var WebpackIsomorphicToolsPlugin = require('webpack-isomorphic-tools/plugin');
var webpackIsomorphicToolsPlugin = new WebpackIsomorphicToolsPlugin(require('./webpack-isomorphic-tools'));
module.exports = {
devtool: 'source-map',
context: path.resolve(__dirname, '..'),
entry: {
'main': [
'bootstrap-sass!./src/theme/bootstrap.config.prod.js',
'font-awesome-webpack!./src/theme/font-awesome.config.prod.js',
'./src/client.js'
]
},
output: {
path: assetsPath,
filename: '[name]-[chunkhash].js',
chunkFilename: '[name]-[chunkhash].js',
publicPath: '/dist/'
},
module: {
loaders: [
{ test: /\.jsx?$/, exclude: /node_modules/, loaders: [strip.loader('debug'), 'babel']},
{ test: /\.json$/, loader: 'json-loader' },
{ test: /\.less$/, loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=2&sourceMap!autoprefixer?browsers=last 2 version!less?outputStyle=expanded&sourceMap=true&sourceMapContents=true') },
{ test: /\.scss$/, loader: ExtractTextPlugin.extract('style', 'css?modules&importLoaders=2&sourceMap!autoprefixer?browsers=last 2 version!sass?outputStyle=expanded&sourceMap=true&sourceMapContents=true') },
{ test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff" },
{ test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/font-woff" },
{ test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=application/octet-stream" },
{ test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: "file" },
{ test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: "url?limit=10000&mimetype=image/svg+xml" },
{ test: webpackIsomorphicToolsPlugin.regular_expression('images'), loader: 'url-loader?limit=10240' }
]
},
progress: true,
resolve: {
modulesDirectories: [
'src',
'node_modules'
],
extensions: ['', '.json', '.js', '.jsx']
},
plugins: [
new CleanPlugin([assetsPath], { root: projectRootPath }),
// css files from the extract-text-plugin loader
new ExtractTextPlugin('[name]-[chunkhash].css', {allChunks: true}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
},
__CLIENT__: true,
__SERVER__: false,
__DEVELOPMENT__: false,
__DEVTOOLS__: false
}),
// ignore dev config
new webpack.IgnorePlugin(/\.\/dev/, /\/config$/),
// optimizations
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
webpackIsomorphicToolsPlugin
]
};
|
App.SubPhotoInstance = DS.Model.extend({
width: DS.attr('number'),
height: DS.attr('number'),
url: DS.attr('string'),
type: 'sub_photo_instance'
});
|
finApp.directive('brief', function () {
return {
restrict: 'E',
templateUrl: 'views/directives/brief.html',
controller: 'BriefController',
controllerAs: 'bfc'
};
}); |
describe("grid-columns", function() {
function createSuite(buffered) {
describe(buffered ? "with buffered rendering" : "without buffered rendering", function() {
var defaultColNum = 4,
totalWidth = 1000,
grid, view, colRef, store, column;
function spyOnEvent(object, eventName, fn) {
var obj = {
fn: fn || Ext.emptyFn
},
spy = spyOn(obj, "fn");
object.addListener(eventName, obj.fn);
return spy;
}
function makeGrid(numCols, gridCfg, hiddenFn, lockedFn){
var cols, col, i;
gridCfg = gridCfg || {};
colRef = [];
if (!numCols || typeof numCols === 'number') {
cols = [];
numCols = numCols || defaultColNum;
for (i = 0; i < numCols; ++i) {
col = {
itemId: 'col' + i,
text: 'Col' + i,
dataIndex: 'field' + i
};
if (hiddenFn && hiddenFn(i)) {
col.hidden = true;
}
if (lockedFn && lockedFn(i)) {
col.locked = true;
}
col = new Ext.grid.column.Column(col);
cols.push(col);
}
} else {
cols = numCols;
}
store = new Ext.data.Store({
model: spec.TestModel,
data: [{
field0: 'val1',
field1: 'val2',
field2: 'val3',
field3: 'val4',
field4: 'val5'
}]
});
grid = new Ext.grid.Panel(Ext.apply({
renderTo: Ext.getBody(),
columns: cols,
width: totalWidth,
height: 500,
border: false,
store: store,
bufferedRenderer: buffered,
viewConfig: {
mouseOverOutBuffer: 0
}
}, gridCfg));
view = grid.view;
colRef = grid.getColumnManager().getColumns();
}
function getCell(rowIdx, colIdx) {
return grid.getView().getCellInclusive({
row: rowIdx,
column: colIdx
});
}
function getCellText(rowIdx, colIdx) {
return getCellInner(rowIdx, colIdx).innerHTML;
}
function getCellInner(rowIdx, colIdx) {
var cell = getCell(rowIdx, colIdx);
return Ext.fly(cell).down(grid.getView().innerSelector).dom;
}
function hasCls(el, cls) {
return Ext.fly(el).hasCls(cls);
}
function clickHeader(col) {
// Offset so we're not on the edges to trigger a drag
jasmine.fireMouseEvent(col.titleEl, 'click', 10);
}
function resizeColumn(column, by) {
var colBox = column.el.getBox(),
fromMx = colBox.x + colBox.width - 2,
fromMy = colBox.y + colBox.height / 2,
dragThresh = by > 0 ? Ext.dd.DragDropManager.clickPixelThresh + 1 : -Ext.dd.DragDropManager.clickPixelThresh - 1;
// Mousedown on the header to drag
jasmine.fireMouseEvent(column.el.dom, 'mouseover', fromMx, fromMy);
jasmine.fireMouseEvent(column.el.dom, 'mousemove', fromMx, fromMy);
jasmine.fireMouseEvent(column.el.dom, 'mousedown', fromMx, fromMy);
// The initial move which tiggers the start of the drag
jasmine.fireMouseEvent(column.el.dom, 'mousemove', fromMx + dragThresh, fromMy);
// Move to resize
jasmine.fireMouseEvent(column.el.dom, 'mousemove', fromMx + by + 2, fromMy);
jasmine.fireMouseEvent(column.el.dom, 'mouseup', fromMx + by + 2, fromMy);
}
function setup() {
Ext.define('spec.TestModel', {
extend: 'Ext.data.Model',
fields: ['field0', 'field1', 'field2', 'field3', 'field4']
});
}
function tearDown() {
Ext.destroy(grid, store, column);
grid = view = store = colRef = column = null;
Ext.undefine('spec.TestModel');
Ext.data.Model.schema.clear();
}
beforeEach(setup);
afterEach(tearDown);
// https://sencha.jira.com/browse/EXTJS-19950
describe('force fit columns, shrinking width to where flexes tend to zero', function() {
it('should work', function() {
makeGrid([{
text : 'Col1',
dataIndex : 'foo',
flex : 1
}, {
text : 'Col2',
columns : [{
text : 'Col21',
dataIndex : 'foo2',
width: 140
}, {
text : 'Col22',
dataIndex : 'foo4',
width : 160
}, {
text : 'Col23',
dataIndex : 'foo4',
width : 100
}, {
text : 'Col34',
dataIndex : 'foo4',
width : 85
}]
}, {
text : 'Col3',
dataIndex : 'foo3',
width : 110
}, {
text : 'Col4',
columns : [ {
text : 'Col41',
dataIndex : 'foo2',
flex: 1
}, {
text : 'Col42',
dataIndex : 'foo4',
width : 120
}]
}], {
autoScroll: true,
forceFit: true,
width: 1800
});
expect(function() {
grid.setWidth(700);
}).not.toThrow();
});
});
describe('as containers', function () {
var leafCls = 'x-leaf-column-header',
col;
afterEach(function () {
col = null;
});
describe('group headers', function () {
beforeEach(function () {
makeGrid([{
itemId: 'main1',
columns: [{
itemId: 'child1'
}, {
itemId: 'child2'
}, {
itemId: 'child3'
}]
}]);
col = grid.down('#main1');
});
it('should be stamped as a container', function () {
expect(col.isContainer).toBe(true);
});
it('should not give the titleEl the leaf column class', function () {
expect(col.titleEl.hasCls(leafCls)).toBe(false);
});
});
describe('contains child items', function () {
beforeEach(function () {
makeGrid([{
text: 'Foo',
dataIndex: 'field0',
items: [{
xtype: 'textfield',
itemId: 'foo'
}]
}]);
col = grid.visibleColumnManager.getHeaderByDataIndex('field0');
});
it('should be stamped as a container', function () {
expect(col.isContainer).toBe(true);
});
it('should not give the titleEl the leaf column class', function () {
expect(col.titleEl.hasCls(leafCls)).toBe(false);
});
describe('focusing', function () {
// See EXTJS-15757.
it('should not throw when focusing', function () {
expect(function () {
grid.down('#foo').onFocus();
}).not.toThrow();
});
it('should return the items collection', function () {
var col = grid.visibleColumnManager.getHeaderByDataIndex('field0');
expect(col.getFocusables()).toBe(col.items.items);
});
});
});
});
describe("cell sizing", function() {
it("should size the cells to match fixed header sizes", function() {
makeGrid([{
width: 200
}, {
width: 500
}]);
expect(getCell(0, 0).getWidth()).toBe(200);
expect(getCell(0, 1).getWidth()).toBe(500);
});
it("should size the cells to match flex header sizes", function() {
makeGrid([{
flex: 8
}, {
flex: 2
}]);
expect(getCell(0, 0).getWidth()).toBe(800);
expect(getCell(0, 1).getWidth()).toBe(200);
});
it("should size the cells to match an the text size in the header", function() {
makeGrid([{
width: null,
text: '<div style="width: 25px;"></div>'
}, {
width: null,
text: '<div style="width: 75px;"></div>'
}]);
expect(getCell(0, 0).getWidth()).toBe(colRef[0].titleEl.getWidth() + colRef[0].el.getBorderWidth('lr'));
expect(getCell(0, 1).getWidth()).toBe(colRef[1].titleEl.getWidth() + colRef[1].el.getBorderWidth('lr'));
});
});
describe("initializing", function() {
describe("normal", function() {
it("should accept a column array", function() {
makeGrid([{
text: 'Foo',
dataIndex: 'field0'
}]);
expect(grid.getColumnManager().getHeaderAtIndex(0).text).toBe('Foo');
});
it("should accept a header config", function() {
makeGrid({
margin: 5,
items: [{
text: 'Foo',
dataIndex: 'field0'
}]
});
expect(grid.getColumnManager().getHeaderAtIndex(0).text).toBe('Foo');
expect(grid.headerCt.margin).toBe(5);
});
});
describe("locking", function() {
it("should accept a column array, enabling locking if a column is configured with locked: true", function() {
makeGrid([{
text: 'Foo',
dataIndex: 'field0',
locked: true
}, {
text: 'Bar',
dataIndex: 'field1'
}]);
expect(grid.lockable).toBe(true);
});
it("should accept a header config, enabling locking if any column is configured with locked: true", function() {
makeGrid({
items: [{
text: 'Foo',
dataIndex: 'field0',
locked: true
}, {
text: 'Bar',
dataIndex: 'field1'
}]
});
expect(grid.lockable).toBe(true);
// Top level grid should return columns from both sides
expect(grid.getVisibleColumns().length).toBe(2);
expect(grid.getColumns().length).toBe(2);
});
});
});
describe("column manager", function() {
// Get all columns from the grid ref
function ga() {
return grid.getColumnManager().getColumns();
}
// Get all manager
function gam() {
return grid.getColumnManager();
}
// Get all visible columns from the grid ref
function gv() {
return grid.getVisibleColumnManager().getColumns();
}
// Get visible manager
function gvm() {
return grid.getVisibleColumnManager();
}
it("should provide a getColumnManager method", function(){
makeGrid();
expect(gam().$className).toBe('Ext.grid.ColumnManager');
});
it("should provide a getVisibleColumnManager method", function(){
makeGrid();
expect(gvm().$className).toBe('Ext.grid.ColumnManager');
});
describe("simple grid", function(){
beforeEach(function(){
makeGrid();
});
it("should return all leaf columns", function() {
expect(gv().length).toBe(defaultColNum);
});
it("should have the correct column order", function(){
var cols = gv(),
i = 0,
len = cols.length;
for (; i < len; ++i) {
expect(cols[i]).toBe(colRef[i]);
}
});
it("should update the order when moving columns", function(){
grid.headerCt.move(3, 1);
var cols = gv();
expect(cols[0]).toBe(colRef[0]);
expect(cols[1]).toBe(colRef[3]);
expect(cols[2]).toBe(colRef[1]);
expect(cols[3]).toBe(colRef[2]);
});
it("should update the columns when removing a column", function(){
grid.headerCt.remove(1);
var cols = gv();
expect(cols[0]).toBe(colRef[0]);
expect(cols[1]).toBe(colRef[2]);
expect(cols[2]).toBe(colRef[3]);
});
it("should update the columns when adding a column", function(){
grid.headerCt.add({
text: 'Col4'
});
expect(gv()[4].text).toBe('Col4');
});
describe("functions", function() {
describe("getHeaderIndex", function() {
it("should return the correct index for the header", function() {
expect(gam().getHeaderIndex(colRef[3])).toBe(3);
});
it("should return -1 if the column doesn't exist", function(){
column = new Ext.grid.column.Column();
expect(gam().getHeaderIndex(column)).toBe(-1);
});
});
describe("getHeaderAtIndex", function(){
it("should return the column reference", function(){
expect(gam().getHeaderAtIndex(2)).toBe(colRef[2]);
});
it("should return null if the index is out of bounds", function(){
expect(gam().getHeaderAtIndex(10)).toBeNull();
});
});
describe("getHeaderById", function(){
it("should return the column reference by id", function(){
expect(gam().getHeaderById('col1')).toBe(colRef[1]);
});
it("should return null if the id doesn't exist", function() {
expect(gam().getHeaderById('foo')).toBeNull();
});
});
it("should return the first item", function(){
expect(gam().getFirst()).toBe(colRef[0]);
});
it("should return the last item", function(){
expect(gam().getLast()).toBe(colRef[3]);
});
describe("getNextSibling", function(){
it("should return the next sibling", function(){
expect(gam().getNextSibling(colRef[1])).toBe(colRef[2]);
});
it("should return the null if the next sibling doesn't exist", function(){
expect(gam().getNextSibling(colRef[3])).toBeNull();
});
});
describe("getPreviousSibling", function(){
it("should return the previous sibling", function(){
expect(gam().getPreviousSibling(colRef[2])).toBe(colRef[1]);
});
it("should return the null if the previous sibling doesn't exist", function(){
expect(gam().getPreviousSibling(colRef[0])).toBeNull();
});
});
});
});
describe('getHeaderIndex', function () {
var index, headerCtItems;
beforeEach(function () {
makeGrid([{
text: 'Name',
width: 100,
dataIndex: 'name',
hidden: true
},{
text: 'Email',
width: 100,
dataIndex: 'email'
}, {
text: 'Stock Price',
columns: [{
text: 'Price',
width: 75,
dataIndex: 'price'
}, {
text: 'Phone',
width: 80,
dataIndex: 'phone',
hidden: true
}, {
text: '% Change',
width: 40,
dataIndex: 'pctChange'
}]
}, {
text: 'Foo',
columns: [{
text: 'Foo Price',
width: 75,
dataIndex: 'price',
hidden: true
}, {
text: 'Foo Phone',
width: 80,
dataIndex: 'phone'
}, {
text: 'Foo % Change',
width: 40,
dataIndex: 'pctChange'
}]
}]);
headerCtItems = grid.headerCt.items;
});
afterEach(function () {
index = headerCtItems = null;
});
describe('all columns', function () {
describe('when argument is a column', function () {
it('should return a valid index', function () {
index = gam().getHeaderIndex(headerCtItems.items[0]);
expect(index).not.toBe(-1);
expect(index).toBe(0);
});
it('should return the header regardless of visibility', function () {
var header;
header = headerCtItems.items[0];
index = gam().getHeaderIndex(header);
expect(header.hidden).toBe(true);
expect(index).toBe(0);
});
it('should return the index of the header in its owner stack - rootHeader', function () {
index = gam().getHeaderIndex(headerCtItems.items[3].items.items[0]);
expect(index).toBe(5);
});
it('should return the index of the header in its owner stack - groupHeader', function () {
// Note that this spec is using the same header as the previous spec to demonstrate the difference.
var groupHeader = headerCtItems.items[3];
index = groupHeader.columnManager.getHeaderIndex(groupHeader.items.items[0]);
expect(index).toBe(0);
});
});
describe('when argument is a group header', function () {
it('should return a valid index', function () {
index = gam().getHeaderIndex(headerCtItems.items[2]);
expect(index).not.toBe(-1);
expect(index).toBe(2);
});
it('should return an index of the first leaf of group header', function () {
var colMgrHeader;
// First, get the index from the column mgr. It will retrieve it from the group header's column mgr.
index = gam().getHeaderIndex(headerCtItems.items[2]);
// Next, get a reference to the actual header (top-level col mgr will have a ref to all sub-level headers).
colMgrHeader = gam().getHeaderAtIndex(index);
// Remember, this is the index of the root header's visible col mgr.
expect(index).toBe(2);
expect(colMgrHeader.hidden).toBe(false);
expect(colMgrHeader.dataIndex).toBe('price');
});
it("should be a reference to the first leaf header in the grouped header's columnn manager", function () {
var groupedHeader, colMgrHeader, groupHeaderFirstHeader;
groupedHeader = headerCtItems.items[2];
groupHeaderFirstHeader = groupedHeader.columnManager.getHeaderAtIndex(0);
// First, get the index from the column mgr. It will retrieve it from the group header's column mgr.
index = gam().getHeaderIndex(groupedHeader);
// Next, get a reference to the actual header (top-level col mgr will have a ref to all sub-level headers).
colMgrHeader = gam().getHeaderAtIndex(index);
expect(colMgrHeader).toBe(groupHeaderFirstHeader);
expect(colMgrHeader.hidden).toBe(groupHeaderFirstHeader.hidden);
expect(colMgrHeader.dataIndex).toBe(groupHeaderFirstHeader.dataIndex);
});
it('should return first sub-header regardless of visibility', function () {
var groupedHeader, colMgrHeader, groupHeaderFirstHeader;
groupedHeader = headerCtItems.items[3];
groupHeaderFirstHeader = groupedHeader.columnManager.getHeaderAtIndex(0);
// First, get the index from the column mgr. It will retrieve it from the group header's column mgr.
index = gam().getHeaderIndex(groupedHeader);
// Next, get a reference to the actual header (top-level col mgr will have a ref to all sub-level headers).
colMgrHeader = gam().getHeaderAtIndex(index);
expect(colMgrHeader).toBe(groupHeaderFirstHeader);
expect(colMgrHeader.hidden).toBe(true);
expect(colMgrHeader.text).toBe('Foo Price');
});
});
});
describe('visible only', function () {
describe('when argument is a column', function () {
it('should return the correct index for the header', function() {
expect(gvm().getHeaderIndex(headerCtItems.items[1])).toBe(0);
});
it("should return -1 if the column doesn't exist", function() {
column = new Ext.grid.column.Column();
expect(gvm().getHeaderIndex(column)).toBe(-1);
});
it('should not return a hidden sub-header', function () {
var header;
header = headerCtItems.items[0];
index = gvm().getHeaderIndex(header);
expect(header.hidden).toBe(true);
expect(index).toBe(-1);
});
it('should return a valid index', function () {
index = gvm().getHeaderIndex(headerCtItems.items[1]);
expect(index).not.toBe(-1);
// Will filter out the first hidden column in the stack.
expect(index).toBe(0);
});
it('should return the index of the header in its owner stack - rootHeader', function () {
index = gvm().getHeaderIndex(headerCtItems.items[3].items.items[2]);
expect(index).toBe(4);
});
it('should return the index of the header in its owner stack - groupHeader', function () {
// Note that this spec is using the same header as the previous spec to demonstrate the difference.
var groupHeader = headerCtItems.items[3];
index = groupHeader.visibleColumnManager.getHeaderIndex(groupHeader.items.items[2]);
expect(index).toBe(1);
});
});
describe('when argument is a group header', function () {
it('should return a valid index', function () {
index = gvm().getHeaderIndex(headerCtItems.items[2]);
expect(index).not.toBe(-1);
// Will filter out the second hidden column in the stack.
expect(index).toBe(1);
});
it('should return an index of the first leaf of group header', function () {
var colMgrHeader;
// First, get the index from the column mgr. It will retrieve it from the group header's column mgr.
index = gvm().getHeaderIndex(headerCtItems.items[2]);
// Next, get a reference to the actual header (top-level col mgr will have a ref to all sub-level headers).
colMgrHeader = gvm().getHeaderAtIndex(index);
// Remember, this is the index of the root header's visible col mgr.
expect(index).toBe(1);
expect(colMgrHeader.hidden).toBe(false);
expect(colMgrHeader.dataIndex).toBe('price');
});
it("should be a reference to the first leaf header in the grouped header's columnn manager", function () {
var groupedHeader, colMgrHeader, groupHeaderFirstHeader;
groupedHeader = headerCtItems.items[2];
groupHeaderFirstHeader = headerCtItems.items[2].visibleColumnManager.getHeaderAtIndex(0);
// First, get the index from the column mgr. It will retrieve it from the group header's column mgr.
index = gvm().getHeaderIndex(groupedHeader);
// Next, get a reference to the actual header (top-level col mgr will have a ref to all sub-level headers).
colMgrHeader = gvm().getHeaderAtIndex(index);
expect(colMgrHeader).toBe(groupHeaderFirstHeader);
expect(colMgrHeader.hidden).toBe(groupHeaderFirstHeader.hidden);
expect(colMgrHeader.dataIndex).toBe(groupHeaderFirstHeader.dataIndex);
});
it('should not return a hidden sub-header', function () {
var groupedHeader, colMgrHeader, groupHeaderFirstHeader;
groupedHeader = headerCtItems.items[3];
groupHeaderFirstHeader = groupedHeader.visibleColumnManager.getHeaderAtIndex(0);
// First, get the index from the column mgr. It will retrieve it from the group header's column mgr.
index = gvm().getHeaderIndex(groupedHeader);
// Next, get a reference to the actual header (top-level col mgr will have a ref to all sub-level headers).
colMgrHeader = gvm().getHeaderAtIndex(index);
expect(colMgrHeader).toBe(groupHeaderFirstHeader);
expect(colMgrHeader.hidden).toBe(false);
expect(colMgrHeader.text).toBe('Foo Phone');
});
});
});
});
describe('getHeaderAtIndex', function () {
var header, headerCtItems;
beforeEach(function () {
makeGrid([{
text: 'Name',
width: 100,
dataIndex: 'name',
hidden: true
},{
text: 'Email',
width: 100,
dataIndex: 'email'
}, {
text: 'Stock Price',
columns: [{
text: 'Price',
width: 75,
dataIndex: 'price'
}, {
text: 'Phone',
width: 80,
dataIndex: 'phone',
hidden: true
}, {
text: '% Change',
width: 40,
dataIndex: 'pctChange'
}]
}, {
text: 'Foo',
columns: [{
text: 'Foo Price',
width: 75,
dataIndex: 'price',
hidden: true
}, {
text: 'Foo Phone',
width: 80,
dataIndex: 'phone'
}, {
text: 'Foo % Change',
width: 40,
dataIndex: 'pctChange'
}]
}]);
headerCtItems = grid.headerCt.items;
});
afterEach(function () {
header = headerCtItems = null;
});
describe('all columns', function () {
it('should return a valid header', function () {
header = gam().getHeaderAtIndex(0);
expect(header).not.toBe(null);
expect(header.dataIndex).toBe('name');
});
it('should return the correct header from the index', function() {
expect(gam().getHeaderAtIndex(0).dataIndex).toBe('name');
});
it("should return null if the column doesn't exist", function() {
expect(gam().getHeaderAtIndex(50)).toBe(null);
});
it('should return the header regardless of visibility', function () {
var header2;
header = gam().getHeaderAtIndex(0);
header2 = gam().getHeaderAtIndex(1);
expect(header).not.toBe(null);
expect(header.hidden).toBe(true);
expect(header2).not.toBe(null);
expect(header2.hidden).toBe(false);
});
it('should return the header in its owner stack - rootHeader', function () {
header = gam().getHeaderAtIndex(0);
expect(header.text).toBe('Name');
});
it('should return the index of the header in its owner stack - groupHeader', function () {
// Note that this spec is using the index as the previous spec to demonstrate the difference.
header = headerCtItems.items[3].columnManager.getHeaderAtIndex(0);
expect(header.text).toBe('Foo Price');
});
});
describe('visible only', function () {
it('should return the correct header from the index', function() {
expect(gvm().getHeaderAtIndex(0).dataIndex).toBe('email');
});
it("should return null if the column doesn't exist", function() {
expect(gvm().getHeaderAtIndex(50)).toBe(null);
});
it('should not return a hidden sub-header', function () {
header = gvm().getHeaderAtIndex(2);
expect(header.hidden).toBe(false);
expect(header.dataIndex).toBe('pctChange');
});
it('should return a valid header', function () {
header = gvm().getHeaderAtIndex(0);
expect(header).not.toBe(null);
expect(header.dataIndex).toBe('email');
});
it('should return the header in its owner stack - rootHeader', function () {
header = gvm().getHeaderAtIndex(0);
expect(header.text).toBe('Email');
});
it('should return the index of the header in its owner stack - groupHeader', function () {
// Note that this spec is using the same header as the previous spec to demonstrate the difference.
var groupHeader = headerCtItems.items[3];
header = headerCtItems.items[3].visibleColumnManager.getHeaderAtIndex(0);
expect(header.text).toBe('Foo Phone');
});
});
});
describe('hidden columns', function() {
// Hidden at index 3/6
beforeEach(function(){
makeGrid(8, null, function(i){
return i > 0 && i % 3 === 0;
});
});
it("should return all columns when using getColumnManager", function(){
expect(ga().length).toBe(8);
});
it("should return only visible columns when using getVisibleColumnManager", function(){
expect(gv().length).toBe(6);
});
it("should update the collection when hiding a column", function(){
colRef[0].hide();
expect(gv().length).toBe(5);
});
it("should update the collection when showing a column", function(){
colRef[3].show();
expect(gv().length).toBe(7);
});
describe("getHeaderAtIndex", function(){
it("should return the column reference", function(){
expect(gvm().getHeaderAtIndex(3)).toBe(colRef[4]);
});
it("should return null if the index is out of bounds", function(){
expect(gvm().getHeaderAtIndex(7)).toBeNull();
});
});
describe("getHeaderById", function(){
it("should return the column reference by id", function(){
expect(gvm().getHeaderById('col1')).toBe(colRef[1]);
});
it("should return null if the id doesn't exist", function() {
expect(gvm().getHeaderById('col3')).toBeNull();
});
});
it("should return the first item", function(){
expect(gvm().getFirst()).toBe(colRef[0]);
});
it("should return the last item", function(){
expect(gvm().getLast()).toBe(colRef[7]);
});
describe("getNextSibling", function(){
it("should return the next sibling", function(){
expect(gvm().getNextSibling(colRef[2])).toBe(colRef[4]);
});
it("should return the null if the next sibling doesn't exist", function(){
expect(gvm().getNextSibling(colRef[3])).toBeNull();
});
});
describe("getPreviousSibling", function(){
it("should return the previous sibling", function(){
expect(gvm().getPreviousSibling(colRef[7])).toBe(colRef[5]);
});
it("should return the null if the previous sibling doesn't exist", function(){
expect(gvm().getPreviousSibling(colRef[6])).toBeNull();
});
});
});
describe("locking", function(){
// first 4 locked
beforeEach(function(){
makeGrid(10, null, null, function(i){
return i <= 3;
});
});
describe("global manager", function() {
it("should return both sets of columns", function(){
expect(ga().length).toBe(10);
});
it("should update the collection when adding to the locked side", function(){
grid.lockedGrid.headerCt.add({
text: 'Foo'
});
expect(ga().length).toBe(11);
});
it("should update the collection when adding to the unlocked side", function(){
grid.normalGrid.headerCt.add({
text: 'Foo'
});
expect(ga().length).toBe(11);
});
it("should update the collection when removing from the locked side", function(){
grid.lockedGrid.headerCt.remove(0);
expect(ga().length).toBe(9);
});
it("should update the collection when removing from the unlocked side", function(){
grid.normalGrid.headerCt.remove(0);
expect(ga().length).toBe(9);
});
it("should maintain the same size when locking an item", function(){
grid.lock(colRef[4]);
expect(ga().length).toBe(10);
});
it("should maintain the same size when unlocking an item", function(){
grid.unlock(colRef[0]);
expect(ga().length).toBe(10);
});
});
describe("locked side", function(){
var glm = function(){
return grid.lockedGrid.getColumnManager();
};
it("should only return the columns for this side", function(){
expect(glm().getColumns().length).toBe(4);
});
it("should update the collection when adding an item to this side", function(){
grid.lock(colRef[9]);
expect(glm().getColumns().length).toBe(5);
});
it("should update the collection when removing an item from this side", function(){
grid.unlock(colRef[0]);
expect(glm().getColumns().length).toBe(3);
});
describe("function", function(){
describe("getHeaderIndex", function() {
it("should return the correct index for the header", function() {
expect(glm().getHeaderIndex(colRef[2])).toBe(2);
});
it("should return -1 if the column doesn't exist", function(){
expect(glm().getHeaderIndex(colRef[5])).toBe(-1);
});
});
describe("getHeaderAtIndex", function(){
it("should return the column reference", function(){
expect(glm().getHeaderAtIndex(3)).toBe(colRef[3]);
});
it("should return null if the index is out of bounds", function(){
expect(glm().getHeaderAtIndex(6)).toBeNull();
});
});
describe("getHeaderById", function(){
it("should return the column reference by id", function(){
expect(glm().getHeaderById('col1')).toBe(colRef[1]);
});
it("should return null if the id doesn't exist", function() {
expect(glm().getHeaderById('col5')).toBeNull();
});
});
});
});
describe("unlocked side", function(){
var gum = function(){
return grid.normalGrid.getColumnManager();
};
it("should only return the columns for this side", function(){
expect(gum().getColumns().length).toBe(6);
});
it("should update the collection when adding an item to this side", function(){
grid.unlock(colRef[1]);
expect(gum().getColumns().length).toBe(7);
});
it("should update the collection when removing an item from this side", function(){
grid.lock(colRef[7]);
expect(gum().getColumns().length).toBe(5);
});
describe("function", function(){
var offset = 4;
describe("getHeaderIndex", function() {
it("should return the correct index for the header", function() {
expect(gum().getHeaderIndex(colRef[offset + 2])).toBe(2);
});
it("should return -1 if the column doesn't exist", function(){
expect(gum().getHeaderIndex(colRef[0])).toBe(-1);
});
});
describe("getHeaderAtIndex", function(){
it("should return the column reference", function(){
expect(gum().getHeaderAtIndex(3)).toBe(colRef[3 + offset]);
});
it("should return null if the index is out of bounds", function(){
expect(gum().getHeaderAtIndex(6)).toBeNull();
});
});
describe("getHeaderById", function(){
it("should return the column reference by id", function(){
expect(gum().getHeaderById('col6')).toBe(colRef[6]);
});
it("should return null if the id doesn't exist", function() {
expect(gum().getHeaderById('col2')).toBeNull();
});
});
});
});
});
});
describe("menu", function() {
it("should not allow menu to be shown when menuDisabled: true", function() {
makeGrid([{
dataIndex: 'field0',
width: 200,
filter: 'string',
menuDisabled: true
}], {
plugins: 'gridfilters'
});
// menuDisabled=true, shouldn't have a trigger
expect(colRef[0].triggerEl).toBeNull();
});
it("should not allow menu to be shown when grid is configured with enableColumnHide: false and sortableColumns: false", function() {
makeGrid([{
dataIndex: 'field0',
width: 200
}], {
enableColumnHide: false,
sortableColumns: false
});
expect(colRef[0].triggerEl).toBeNull();
});
it("should allow menu to be shown when requiresMenu: true (from plugin) and grid is configured with enableColumnHide: false and sortableColumns: false", function() {
makeGrid([{
dataIndex: 'field0',
width: 200,
filter: 'string'
}], {
enableColumnHide: false,
sortableColumns: false,
plugins: 'gridfilters'
});
var col = colRef[0],
menu;
col.triggerEl.show();
jasmine.fireMouseEvent(col.triggerEl.dom, 'click');
menu = col.activeMenu;
expect(menu.isVisible()).toBe(true);
expect(col.requiresMenu).toBe(true);
});
});
describe("sorting", function() {
it("should sort by dataIndex when clicking on the header with sortable: true", function() {
makeGrid([{
dataIndex: 'field0',
sortable: true
}]);
clickHeader(colRef[0]);
var sorters = store.getSorters();
expect(sorters.getCount()).toBe(1);
expect(sorters.first().getProperty()).toBe('field0');
expect(sorters.first().getDirection()).toBe('ASC');
});
it("should invert the sort order when clicking on a sorted column", function() {
makeGrid([{
dataIndex: 'field0',
sortable: true
}]);
clickHeader(colRef[0]);
var sorters = store.getSorters();
clickHeader(colRef[0]);
expect(sorters.getCount()).toBe(1);
expect(sorters.first().getProperty()).toBe('field0');
expect(sorters.first().getDirection()).toBe('DESC');
clickHeader(colRef[0]);
expect(sorters.getCount()).toBe(1);
expect(sorters.first().getProperty()).toBe('field0');
expect(sorters.first().getDirection()).toBe('ASC');
});
it("should not sort when configured with sortable false", function() {
makeGrid([{
dataIndex: 'field0',
sortable: false
}]);
clickHeader(colRef[0]);
expect(store.getSorters().getCount()).toBe(0);
});
it("should not sort when the grid is configured with sortableColumns: false", function() {
makeGrid([{
dataIndex: 'field0'
}], {
sortableColumns: false
});
clickHeader(colRef[0]);
expect(store.getSorters().getCount()).toBe(0);
});
});
describe("grouped columns", function() {
var baseCols;
function createGrid(cols, stateful) {
if (grid) {
grid.destroy();
grid = null;
}
makeGrid(cols, {
renderTo: null,
stateful: stateful,
stateId: 'foo'
});
}
function getCol(id) {
return grid.down('#' + id);
}
describe('when stateful', function () {
var col;
beforeEach(function () {
new Ext.state.Provider();
makeGrid([{
itemId: 'main1',
columns: [{
itemId: 'child1'
}, {
itemId: 'child2'
}, {
itemId: 'child3'
}]
}, {
itemId: 'main2',
columns: [{
itemId: 'child4'
}, {
itemId: 'child5'
}, {
itemId: 'child6'
}]
}], {
stateful: true,
stateId: 'foo'
});
});
afterEach(function () {
Ext.state.Manager.getProvider().clear();
col = null;
});
it('should work when toggling visibility on the groups', function () {
// See EXTJS-11661.
col = grid.down('#main2');
col.hide();
// Trigger the bug.
grid.saveState();
col.show();
// Now, select one of the col's children and query its hidden state.
// Really, we can check anything here, b/c if the bug wasn't fixed then
// a TypeError would be thrown in Ext.view.TableLayout#setColumnWidths.
expect(grid.down('#child6').hidden).toBe(false);
});
it('should not show a previously hidden subheader when the visibility of its group header is toggled', function () {
var subheader = grid.down('#child4');
subheader.hide();
col = grid.down('#main2');
col.hide();
col.show();
expect(subheader.hidden).toBe(true);
});
});
describe("column visibility", function() {
var cells;
afterEach(function () {
cells = null;
});
describe("hiding/show during construction", function() {
it("should be able to show a column during construction", function() {
expect(function() {
makeGrid([{
dataIndex: 'field1',
hidden: true,
listeners: {
added: function(c) {
c.show();
}
}
}]);
}).not.toThrow();
expect(grid.getVisibleColumnManager().getColumns()[0]).toBe(colRef[0]);
});
it("should be able to hide a column during construction", function() {
expect(function() {
makeGrid([{
dataIndex: 'field1',
listeners: {
added: function(c) {
c.hide();
}
}
}]);
}).not.toThrow();
expect(grid.getVisibleColumnManager().getColumns().length).toBe(0);
});
});
describe('when groupheader parent is hidden', function () {
describe('hidden at config time', function () {
beforeEach(function () {
makeGrid([{
itemId: 'main1'
}, {
itemId: 'main2',
hidden: true,
columns: [{
itemId: 'child1'
}, {
itemId: 'child2'
}]
}]);
cells = grid.view.body.query('.x-grid-row td');
});
it('should hide child columns at config time if the parent is hidden', function () {
expect(grid.down('#child1').getInherited().hidden).toBe(true);
expect(grid.down('#child2').getInherited().hidden).toBe(true);
// Check the view.
expect(cells.length).toBe(1);
});
it('should not explicitly hide any child columns (they will be hierarchically hidden)', function () {
expect(grid.down('#child1').hidden).toBe(false);
expect(grid.down('#child2').hidden).toBe(false);
// Check the view.
expect(cells.length).toBe(1);
});
});
describe('hidden at run time', function () {
beforeEach(function () {
makeGrid([{
itemId: 'main1'
}, {
itemId: 'main2',
columns: [{
itemId: 'child1'
}, {
itemId: 'child2'
}]
}]);
grid.down('#main2').hide();
cells = grid.view.body.query('.x-grid-row td');
});
it('should hide child columns at runtime if the parent is hidden', function () {
expect(grid.down('#child1').getInherited().hidden).toBe(true);
expect(grid.down('#child2').getInherited().hidden).toBe(true);
// Check the view.
expect(cells.length).toBe(1);
});
it('should not explicitly hide any child columns (they will be hierarchically hidden)', function () {
expect(grid.down('#child1').hidden).toBe(false);
expect(grid.down('#child2').hidden).toBe(false);
// Check the view.
expect(cells.length).toBe(1);
});
});
});
describe('when groupheader parent is shown', function () {
describe('shown at config time', function () {
beforeEach(function () {
makeGrid([{
itemId: 'main1'
}, {
itemId: 'main2',
columns: [{
itemId: 'child1'
}, {
itemId: 'child2'
}]
}]);
cells = grid.view.body.query('.x-grid-row td');
});
it('should not hide child columns at config time if the parent is shown', function () {
expect(grid.down('#child1').getInherited().hidden).not.toBeDefined();
expect(grid.down('#child2').getInherited().hidden).not.toBeDefined();
// Check the view.
expect(cells.length).toBe(3);
});
it('should not explicitly hide any child columns (they will be hierarchically shown)', function () {
expect(grid.down('#child1').hidden).toBe(false);
expect(grid.down('#child2').hidden).toBe(false);
// Check the view.
expect(cells.length).toBe(3);
});
});
describe('shown at run time', function () {
beforeEach(function () {
makeGrid([{
itemId: 'main1'
}, {
itemId: 'main2',
hidden: true,
columns: [{
itemId: 'child1'
}, {
itemId: 'child2'
}]
}]);
grid.down('#main2').show();
cells = grid.view.body.query('.x-grid-row td');
});
it('should show child columns at runtime if the parent is shown', function () {
expect(grid.down('#child1').getInherited().hidden).not.toBeDefined();
expect(grid.down('#child2').getInherited().hidden).not.toBeDefined();
// Check the view.
expect(cells.length).toBe(3);
});
it('should not explicitly hide any child columns (they will be hierarchically shown)', function () {
expect(grid.down('#child1').hidden).toBe(false);
expect(grid.down('#child2').hidden).toBe(false);
// Check the view.
expect(cells.length).toBe(3);
});
});
});
describe("hiding/showing children", function() {
beforeEach(function() {
baseCols = [{
itemId: 'col1',
columns: [{
itemId: 'col11'
}, {
itemId: 'col12'
}, {
itemId: 'col13'
}]
}, {
itemId: 'col2',
columns: [{
itemId: 'col21'
}, {
itemId: 'col22'
}, {
itemId: 'col23'
}]
}];
});
it('should not show a previously hidden subheader when the visibility of its group header is toggled', function () {
var subheader, col;
makeGrid([{
itemId: 'main1'
}, {
itemId: 'main2',
columns: [{
itemId: 'child1'
}, {
itemId: 'child2'
}]
}]);
subheader = grid.down('#child1');
subheader.hide();
col = grid.down('#main2');
col.hide();
col.show();
expect(subheader.hidden).toBe(true);
});
it('should allow any subheader to be reshown when all subheaders are currently hidden', function () {
// There was a bug where a subheader could not be reshown when itself and all of its fellows were curently hidden.
// See EXTJS-18515.
var subheader;
makeGrid([{
itemId: 'main1'
}, {
itemId: 'main2',
columns: [{
itemId: 'child1'
}, {
itemId: 'child2'
}, {
itemId: 'child3'
}]
}]);
grid.down('#child1').hide();
grid.down('#child2').hide();
subheader = grid.down('#child3');
// Toggling would reveal the bug.
subheader.hide();
expect(subheader.hidden).toBe(true);
subheader.show();
expect(subheader.hidden).toBe(false);
});
it('should show the last hidden subheader if all subheaders are currently hidden when the group is reshown', function () {
var groupheader, subheader1, subheader2, subheader3;
makeGrid([{
itemId: 'main1'
}, {
itemId: 'main2',
columns: [{
itemId: 'child1'
}, {
itemId: 'child2'
}, {
itemId: 'child3'
}]
}]);
groupheader = grid.down('#main2');
subheader1 = grid.down('#child1').hide();
subheader3 = grid.down('#child3').hide();
subheader2 = grid.down('#child2')
subheader2.hide();
expect(subheader2.hidden).toBe(true);
groupheader.show();
// The last hidden subheader should now be shown.
expect(subheader2.hidden).toBe(false);
// Let's also demonstrate that the others are still hidden.
expect(subheader1.hidden).toBe(true);
expect(subheader3.hidden).toBe(true);
});
describe("initial configuration", function() {
it("should not hide the parent by default", function() {
createGrid(baseCols);
expect(getCol('col1').hidden).toBe(false);
});
it("should not hide the parent if not all children are hidden", function() {
baseCols[1].columns[2].hidden = baseCols[1].columns[0].hidden = true;
createGrid(baseCols);
expect(getCol('col2').hidden).toBe(false);
});
it("should hide the parent if all children are hidden", function() {
baseCols[1].columns[2].hidden = baseCols[1].columns[1].hidden = baseCols[1].columns[0].hidden = true;
createGrid(baseCols);
expect(getCol('col2').hidden).toBe(true);
});
});
describe("before render", function() {
it("should hide the parent when hiding all children", function() {
createGrid(baseCols);
getCol('col21').hide();
getCol('col22').hide();
getCol('col23').hide();
grid.render(Ext.getBody());
expect(getCol('col2').hidden).toBe(true);
});
it("should show the parent when showing a hidden child", function() {
baseCols[1].columns[2].hidden = baseCols[1].columns[1].hidden = baseCols[1].columns[0].hidden = true;
createGrid(baseCols);
getCol('col22').show();
grid.render(Ext.getBody());
expect(getCol('col2').hidden).toBe(false);
});
});
describe("after render", function() {
it("should hide the parent when hiding all children", function() {
createGrid(baseCols);
grid.render(Ext.getBody());
getCol('col21').hide();
getCol('col22').hide();
getCol('col23').hide();
expect(getCol('col2').hidden).toBe(true);
});
it("should show the parent when showing a hidden child", function() {
baseCols[1].columns[2].hidden = baseCols[1].columns[1].hidden = baseCols[1].columns[0].hidden = true;
createGrid(baseCols);
grid.render(Ext.getBody());
getCol('col22').show();
expect(getCol('col2').hidden).toBe(false);
});
it("should only trigger a single layout when hiding the last leaf in a group", function() {
baseCols[0].columns.splice(1, 2);
createGrid(baseCols);
grid.render(Ext.getBody());
var count = grid.componentLayoutCounter;
getCol('col11').hide();
expect(grid.componentLayoutCounter).toBe(count + 1);
});
it("should only trigger a single refresh when hiding the last leaf in a group", function() {
baseCols[0].columns.splice(1, 2);
createGrid(baseCols);
grid.render(Ext.getBody());
var view = grid.getView(),
count = view.refreshCounter;
getCol('col11').hide();
expect(view.refreshCounter).toBe(count + 1);
});
});
describe('nested stacked columns', function () {
// Test stacked group headers where the only child is the next group header in the hierarchy.
// The last (lowest in the stack) group header will contain multiple child items.
// For example:
//
// +-----------------------------------+
// | col1 |
// |-----------------------------------|
// | col2 |
// other |-----------------------------------| other
// headers | col3 | headers
// |-----------------------------------|
// | col4 |
// |-----------------------------------|
// | Field1 | Field2 | Field3 | Field4 |
// |===================================|
// | view |
// +-----------------------------------+
//
function assertHiddenState(n, hiddenState) {
while (n) {
expect(getCol('col' + n).hidden).toBe(hiddenState);
--n;
}
}
describe('on hide', function () {
beforeEach(function() {
baseCols = [{
itemId: 'col1',
columns: [{
itemId: 'col2',
columns: [{
itemId: 'col3',
columns: [{
itemId: 'col4',
columns: [{
itemId: 'col41'
}, {
itemId: 'col42'
}, {
itemId: 'col43'
}, {
itemId: 'col44'
}]
}]
}]
}]
}, {
itemId: 'col5'
}]
});
it('should hide every group header above the target group header', function () {
createGrid(baseCols);
getCol('col4').hide();
assertHiddenState(4, true);
tearDown();
setup();
createGrid(baseCols);
getCol('col3').hide();
assertHiddenState(3, true);
tearDown();
setup();
createGrid(baseCols);
getCol('col2').hide();
assertHiddenState(2, true);
});
it('should reshow every group header above the target group header when toggled', function () {
createGrid(baseCols);
getCol('col4').hide();
assertHiddenState(4, true);
getCol('col4').show();
assertHiddenState(4, false);
tearDown();
setup();
createGrid(baseCols);
getCol('col3').hide();
assertHiddenState(3, true);
getCol('col3').show();
assertHiddenState(3, false);
tearDown();
setup();
createGrid(baseCols);
getCol('col2').hide();
assertHiddenState(2, true);
getCol('col2').show();
assertHiddenState(2, false);
});
describe('subheaders', function () {
it('should hide all ancestor group headers when hiding all subheaders in lowest group header', function () {
createGrid(baseCols);
getCol('col41').hide();
getCol('col42').hide();
getCol('col43').hide();
getCol('col44').hide();
assertHiddenState(4, true);
});
});
});
describe('on show', function () {
beforeEach(function() {
baseCols = [{
itemId: 'col1',
hidden: true,
columns: [{
itemId: 'col2',
hidden: true,
columns: [{
itemId: 'col3',
hidden: true,
columns: [{
itemId: 'col4',
hidden: true,
columns: [{
itemId: 'col41'
}, {
itemId: 'col42'
}, {
itemId: 'col43'
}, {
itemId: 'col44'
}]
}]
}]
}]
}, {
itemId: 'col5'
}]
});
it('should show every group header above the target group header', function () {
// Here we're showing that a header that is explicitly shown will have every header
// above it shown as well.
createGrid(baseCols);
getCol('col4').show();
assertHiddenState(4, false);
tearDown();
setup();
createGrid(baseCols);
getCol('col3').show();
assertHiddenState(3, false);
tearDown();
setup();
createGrid(baseCols);
getCol('col2').show();
assertHiddenState(2, false);
});
it('should show every group header in the chain no matter which group header is checked', function () {
// Here we're showing that a header that is explicitly shown will have every header
// in the chain shown, no matter which group header was clicked.
//
// Group headers are special in that they are auto-hidden when their subheaders are all
// hidden and auto-shown when the first subheader is reshown. They are the only headers
// that should now be auto-shown or -hidden.
//
// It follows that since group headers are dictated by some automation depending upon the
// state of their child items that all group headers should be shown if anyone in the
// hierarchy is shown since these special group headers only contain one child, which is
// the next group header in the stack.
createGrid(baseCols);
getCol('col4').show();
assertHiddenState(4, false);
tearDown();
setup();
createGrid(baseCols);
getCol('col3').show();
assertHiddenState(4, false);
tearDown();
setup();
createGrid(baseCols);
getCol('col2').show();
assertHiddenState(4, false);
tearDown();
setup();
createGrid(baseCols);
getCol('col1').show();
assertHiddenState(4, false);
});
it('should rehide every group header above the target group header when toggled', function () {
createGrid(baseCols);
getCol('col4').show();
assertHiddenState(4, false);
getCol('col4').hide();
assertHiddenState(4, true);
tearDown();
setup();
createGrid(baseCols);
getCol('col3').show();
assertHiddenState(3, false);
getCol('col3').hide();
assertHiddenState(3, true);
tearDown();
setup();
createGrid(baseCols);
getCol('col2').show();
assertHiddenState(2, false);
getCol('col2').hide();
assertHiddenState(2, true);
});
describe('subheaders', function () {
it('should not show any ancestor group headers when hiding all subheaders in lowest group header', function () {
createGrid(baseCols);
getCol('col41').hide();
getCol('col42').hide();
getCol('col43').hide();
getCol('col44').hide();
assertHiddenState(4, true);
});
it('should show all ancestor group headers when hiding all subheaders in lowest group header and then showing one', function () {
createGrid(baseCols);
getCol('col41').hide();
getCol('col42').hide();
getCol('col43').hide();
getCol('col44').hide();
assertHiddenState(4, true);
getCol('col42').show();
assertHiddenState(4, false);
});
it('should remember which subheader was last checked and restore its state when its group header is rechecked', function () {
var col, subheader, headerCt;
// Let's hide the 3rd menu item.
makeGrid(baseCols);
col = getCol('col4');
subheader = getCol('col43');
headerCt = grid.headerCt;
getCol('col41').hide();
getCol('col42').hide();
getCol('col44').hide();
subheader.hide();
expect(col.hidden).toBe(true);
// Get the menu item.
headerCt.getMenuItemForHeader(headerCt.menu, col).setChecked(true);
expect(subheader.hidden).toBe(false);
// Now let's hide the 2nd menu item.
tearDown();
setup();
makeGrid(baseCols);
col = getCol('col4');
subheader = getCol('col42');
headerCt = grid.headerCt;
getCol('col41').hide();
getCol('col43').hide();
getCol('col44').hide();
subheader.hide();
expect(col.hidden).toBe(true);
// Get the menu item.
headerCt.getMenuItemForHeader(headerCt.menu, col).setChecked(true);
expect(subheader.hidden).toBe(false);
});
it('should only show visible subheaders when all group headers are shown', function () {
var col;
createGrid(baseCols);
col = getCol('col4');
// All subheaders are visible.
col.show();
expect(col.visibleColumnManager.getColumns().length).toBe(4);
// Hide the group header and hide two subheaders.
col.hide();
getCol('col42').hide();
getCol('col43').hide();
// Only two subheaders should now be visible.
col.show();
expect(col.visibleColumnManager.getColumns().length).toBe(2);
});
});
});
});
});
describe("adding/removing children", function() {
beforeEach(function() {
baseCols = [{
itemId: 'col1',
columns: [{
itemId: 'col11'
}, {
itemId: 'col12'
}, {
itemId: 'col13'
}]
}, {
itemId: 'col2',
columns: [{
itemId: 'col21'
}, {
itemId: 'col22'
}, {
itemId: 'col23'
}]
}];
});
describe("before render", function() {
it("should hide the parent if removing the last hidden item", function() {
baseCols[0].columns[0].hidden = baseCols[0].columns[1].hidden = true;
createGrid(baseCols);
getCol('col13').destroy();
grid.render(Ext.getBody());
expect(getCol('col1').hidden).toBe(true);
});
it("should show the parent if adding a visible item and all items are hidden", function() {
baseCols[0].columns[0].hidden = baseCols[0].columns[1].hidden = baseCols[0].columns[2].hidden = true;
createGrid(baseCols);
getCol('col1').add({
itemId: 'col14'
});
grid.render(Ext.getBody());
expect(getCol('col1').hidden).toBe(false);
});
});
describe("after render", function() {
it("should hide the parent if removing the last hidden item", function() {
baseCols[0].columns[0].hidden = baseCols[0].columns[1].hidden = true;
createGrid(baseCols);
grid.render(Ext.getBody());
getCol('col13').destroy();
expect(getCol('col1').hidden).toBe(true);
});
it("should show the parent if adding a visible item and all items are hidden", function() {
baseCols[0].columns[0].hidden = baseCols[0].columns[1].hidden = baseCols[0].columns[2].hidden = true;
createGrid(baseCols);
grid.render(Ext.getBody());
getCol('col1').add({
itemId: 'col14'
});
expect(getCol('col1').hidden).toBe(false);
});
});
});
});
describe("removing columns from group", function() {
beforeEach(function() {
baseCols = [{
itemId: 'col1',
columns: [{
itemId: 'col11'
}, {
itemId: 'col12'
}, {
itemId: 'col13'
}]
}, {
itemId: 'col2',
columns: [{
itemId: 'col21'
}, {
itemId: 'col22'
}, {
itemId: 'col23'
}]
}];
createGrid(baseCols);
});
describe("before render", function() {
it("should destroy the group header when removing all columns", function() {
var headerCt = grid.headerCt,
col2 = getCol('col2');
expect(headerCt.items.indexOf(col2)).toBe(1);
getCol('col21').destroy();
getCol('col22').destroy();
getCol('col23').destroy();
expect(col2.destroyed).toBe(true);
expect(headerCt.items.indexOf(col2)).toBe(-1);
});
});
describe("after render", function() {
it("should destroy the group header when removing all columns", function() {
createGrid(baseCols);
grid.render(Ext.getBody());
var headerCt = grid.headerCt,
col2 = getCol('col2');
expect(headerCt.items.indexOf(col2)).toBe(1);
getCol('col21').destroy();
getCol('col22').destroy();
getCol('col23').destroy();
expect(col2.destroyed).toBe(true);
expect(headerCt.items.indexOf(col2)).toBe(-1);
});
});
});
});
describe("column operations & the view", function() {
describe('', function () {
beforeEach(function() {
makeGrid();
});
it("should update the view when adding a new header", function() {
grid.headerCt.insert(0, {
dataIndex: 'field4'
});
expect(getCellText(0, 0)).toBe('val5');
});
it("should update the view when moving an existing header", function() {
grid.headerCt.insert(0, colRef[1]);
expect(getCellText(0, 0)).toBe('val2');
});
it("should update the view when removing a header", function() {
grid.headerCt.remove(1);
expect(getCellText(0, 1)).toBe('val3');
});
it("should not refresh the view when doing a drag/drop move", function() {
var called = false,
header;
grid.getView().on('refresh', function() {
called = true;
});
// Simulate a DD here
header = colRef[0];
grid.headerCt.move(0, 3);
expect(getCellText(0, 3)).toBe('val1');
expect(called).toBe(false);
});
});
describe('toggling column visibility', function () {
var refreshCounter;
beforeEach(function () {
makeGrid();
refreshCounter = view.refreshCounter;
});
afterEach(function () {
refreshCounter = null;
});
describe('hiding', function () {
it('should update the view', function () {
colRef[0].hide();
expect(view.refreshCounter).toBe(refreshCounter + 1);
});
});
describe('showing', function () {
it('should update the view', function () {
colRef[0].hide();
refreshCounter = view.refreshCounter;
colRef[0].show();
expect(view.refreshCounter).toBe(refreshCounter + 1);
});
});
});
});
describe("locked/normal grid visibility", function() {
function expectVisible(locked, normal) {
expect(grid.lockedGrid.isVisible()).toBe(locked);
expect(grid.normalGrid.isVisible()).toBe(normal);
}
var failCount;
beforeEach(function() {
failCount = Ext.failedLayouts;
});
afterEach(function() {
expect(failCount).toBe(Ext.failedLayouts);
failCount = null;
});
describe("initial", function() {
it("should have both sides visible", function() {
makeGrid([{locked: true}, {}], {
syncTaskDelay: 0
});
expectVisible(true, true);
});
it("should have only the normal side visible if there are no locked columns", function() {
makeGrid([{}, {}], {
enableLocking: true,
syncTaskDelay: 0
});
expectVisible(false, true);
});
it("should have only the locked side visible if there are no normal columns", function() {
makeGrid([{locked: true}, {locked: true}], {
syncTaskDelay: 0
});
expectVisible(true, false);
});
});
describe("dynamic", function() {
beforeEach(function() {
makeGrid([{
locked: true,
itemId: 'col0'
}, {
locked: true,
itemId: 'col1'
}, {
itemId: 'col2'
}, {
itemId: 'col3'
}], {
syncTaskDelay: 0
});
});
describe("normal side", function() {
it("should not hide when removing a column but there are other normal columns", function() {
grid.normalGrid.headerCt.remove('col2');
expectVisible(true, true);
});
it("should hide when removing the last normal column", function() {
grid.normalGrid.headerCt.remove('col2');
grid.normalGrid.headerCt.remove('col3');
expectVisible(true, false);
});
it("should not hide when hiding a column but there are other visible normal columns", function() {
colRef[2].hide();
expectVisible(true, true);
});
it("should hide when hiding the last normal column", function() {
colRef[2].hide();
colRef[3].hide();
expectVisible(true, false);
});
});
describe("locked side", function() {
it("should not hide when removing a column but there are other locked columns", function() {
grid.lockedGrid.headerCt.remove('col0');
expectVisible(true, true);
});
it("should hide when removing the last locked column", function() {
grid.lockedGrid.headerCt.remove('col0');
grid.lockedGrid.headerCt.remove('col1');
expectVisible(false, true);
});
it("should not hide when hiding a column but there are other visible locked columns", function() {
colRef[0].hide();
expectVisible(true, true);
});
it("should hide when hiding the last locked column", function() {
colRef[0].hide();
colRef[1].hide();
expectVisible(false, true);
});
});
});
});
describe("rendering", function() {
beforeEach(function() {
makeGrid();
});
describe("first/last", function() {
it("should stamp x-grid-cell-first on the first column cell", function() {
var cls = grid.getView().firstCls;
expect(hasCls(getCell(0, 0), cls)).toBe(true);
expect(hasCls(getCell(0, 1), cls)).toBe(false);
expect(hasCls(getCell(0, 2), cls)).toBe(false);
expect(hasCls(getCell(0, 3), cls)).toBe(false);
});
it("should stamp x-grid-cell-last on the last column cell", function() {
var cls = grid.getView().lastCls;
expect(hasCls(getCell(0, 0), cls)).toBe(false);
expect(hasCls(getCell(0, 1), cls)).toBe(false);
expect(hasCls(getCell(0, 2), cls)).toBe(false);
expect(hasCls(getCell(0, 3), cls)).toBe(true);
});
it("should update the first class when moving the first column", function() {
grid.headerCt.insert(0, colRef[1]);
var cell = getCell(0, 0),
view = grid.getView(),
cls = view.firstCls;
expect(getCellText(0, 0)).toBe('val2');
expect(hasCls(cell, cls)).toBe(true);
expect(hasCls(getCell(0, 1), cls)).toBe(false);
});
it("should update the last class when moving the last column", function() {
// Suppress console warning about reusing existing id
spyOn(Ext.log, 'warn');
grid.headerCt.add(colRef[1]);
var cell = getCell(0, 3),
view = grid.getView(),
cls = view.lastCls;
expect(getCellText(0, 3)).toBe('val2');
expect(hasCls(cell, cls)).toBe(true);
expect(hasCls(getCell(0, 2), cls)).toBe(false);
});
});
describe("id", function() {
it("should stamp the id of the column in the cell", function() {
expect(hasCls(getCell(0, 0), 'x-grid-cell-col0')).toBe(true);
expect(hasCls(getCell(0, 1), 'x-grid-cell-col1')).toBe(true);
expect(hasCls(getCell(0, 2), 'x-grid-cell-col2')).toBe(true);
expect(hasCls(getCell(0, 3), 'x-grid-cell-col3')).toBe(true);
});
});
});
describe("hiddenHeaders", function() {
it("should lay out the hidden items so cells obtain correct width", function() {
makeGrid([{
width: 100
}, {
flex: 1
}, {
width: 200
}], {
hiddenHeaders: true
});
expect(getCell(0, 0).getWidth()).toBe(100);
expect(getCell(0, 1).getWidth()).toBe(totalWidth - 200 - 100);
expect(getCell(0, 2).getWidth()).toBe(200);
});
it("should lay out grouped column headers", function() {
makeGrid([{
width: 100
}, {
columns: [{
width: 200
}, {
width: 400
}, {
width: 100
}]
}, {
width: 200
}], {
hiddenHeaders: true
});
expect(getCell(0, 0).getWidth()).toBe(100);
expect(getCell(0, 1).getWidth()).toBe(200);
expect(getCell(0, 2).getWidth()).toBe(400);
expect(getCell(0, 3).getWidth()).toBe(100);
expect(getCell(0, 4).getWidth()).toBe(200);
});
});
describe("emptyCellText config", function () {
function expectEmptyText(column, rowIdx, colIdx) {
var cell = getCellInner(rowIdx, colIdx),
el = document.createElement('div');
// We're doing this because ' ' !== ' '. By letting the browser decode the entity, we
// can then do a comparison.
el.innerHTML = column.emptyCellText;
expect(cell.textContent || cell.innerText).toBe(el.textContent || el.innerText);
}
describe("rendering", function() {
beforeEach(function () {
makeGrid([{
width: 100
}, {
emptyCellText: 'derp',
width: 200
}]);
});
it("should use the default html entity for when there is no emptyCellText given", function () {
expectEmptyText(colRef[0], 0, 0);
});
it("should use the value of emptyCellText when configured", function () {
expectEmptyText(colRef[1], 0, 1);
});
});
describe("column update", function() {
describe("full row update", function() {
it("should use the empty text on update", function() {
makeGrid([{
width: 100,
dataIndex: 'field0',
renderer: function(v, meta, rec) {
return v;
}
}]);
// Renderer with >1 arg requires a full row redraw
store.getAt(0).set('field0', '');
expectEmptyText(colRef[0], 0, 0);
});
});
describe("cell update only", function() {
describe("producesHTML: true", function() {
it("should use the empty text on update", function() {
makeGrid([{
width: 100,
producesHTML: true,
dataIndex: 'field0'
}]);
store.getAt(0).set('field0', '');
expectEmptyText(colRef[0], 0, 0);
});
it("should use the empty text on update with a simple renderer", function() {
makeGrid([{
width: 100,
producesHTML: true,
dataIndex: 'field0',
renderer: Ext.identityFn
}]);
store.getAt(0).set('field0', '');
expectEmptyText(colRef[0], 0, 0);
});
});
describe("producesHTML: false", function() {
it("should use the empty text on update", function() {
makeGrid([{
width: 100,
producesHTML: false,
dataIndex: 'field0'
}]);
store.getAt(0).set('field0', '');
expectEmptyText(colRef[0], 0, 0);
});
it("should use the empty text on update with a simple renderer", function() {
makeGrid([{
width: 100,
producesHTML: false,
dataIndex: 'field0',
renderer: Ext.identityFn
}]);
store.getAt(0).set('field0', '');
expectEmptyText(colRef[0], 0, 0);
});
});
});
});
});
describe("non-column items in the header", function() {
it("should show non-columns as children", function() {
makeGrid([{
width: 100,
items: {
xtype: 'textfield',
itemId: 'foo'
}
}]);
expect(grid.down('#foo').isVisible(true)).toBe(true);
});
it("should have the hidden item as visible after showing an initially hidden column", function() {
makeGrid([{
width: 100,
items: {
xtype: 'textfield'
}
}, {
width: 100,
hidden: true,
items: {
xtype: 'textfield',
itemId: 'foo'
}
}]);
var field = grid.down('#foo');
expect(field.isVisible(true)).toBe(false);
field.ownerCt.show();
expect(field.isVisible(true)).toBe(true);
});
});
describe("reconfiguring", function() {
it("should destroy any old columns", function() {
var o = {};
makeGrid(4);
Ext.Array.forEach(colRef, function(col) {
col.on('destroy', function(c) {
o[col.getItemId()] = true;
});
});
grid.reconfigure(null, []);
expect(o).toEqual({
col0: true,
col1: true,
col2: true,
col3: true
});
});
describe("with locking", function() {
it("should resize the locked part to match the grid size", function() {
makeGrid(4, null, null, function(i) {
return i === 0;
});
var borderWidth = grid.lockedGrid.el.getBorderWidth('lr');
// Default column width
expect(grid.lockedGrid.getWidth()).toBe(100 + borderWidth);
grid.reconfigure(null, [{
locked: true,
width: 120
}, {
locked: true,
width: 170
}, {}, {}])
expect(grid.lockedGrid.getWidth()).toBe(120 + 170 + borderWidth);
});
});
});
describe('column header borders', function() {
it('should show header borders by default, and turn them off dynamically', function() {
makeGrid();
expect(colRef[0].el.getBorderWidth('r')).toBe(1);
expect(colRef[1].el.getBorderWidth('r')).toBe(1);
expect(colRef[2].el.getBorderWidth('r')).toBe(1);
grid.setHeaderBorders(false);
expect(colRef[0].el.getBorderWidth('r')).toBe(0);
expect(colRef[1].el.getBorderWidth('r')).toBe(0);
expect(colRef[2].el.getBorderWidth('r')).toBe(0);
});
it('should have no borders if configured false, and should show them dynamically', function() {
makeGrid(null, {
headerBorders: false
});
expect(colRef[0].el.getBorderWidth('r')).toBe(0);
expect(colRef[1].el.getBorderWidth('r')).toBe(0);
expect(colRef[2].el.getBorderWidth('r')).toBe(0);
grid.setHeaderBorders(true);
expect(colRef[0].el.getBorderWidth('r')).toBe(1);
expect(colRef[1].el.getBorderWidth('r')).toBe(1);
expect(colRef[2].el.getBorderWidth('r')).toBe(1);
});
});
describe('column resize', function() {
it('should not fire drag events on headercontainer during resize', function() {
makeGrid();
var colWidth = colRef[0].getWidth(),
dragSpy = spyOnEvent(grid.headerCt.el, 'drag');
resizeColumn(colRef[0], 10);
expect(colRef[0].getWidth()).toBe(colWidth + 10);
expect(dragSpy).not.toHaveBeenCalled();
});
});
});
}
createSuite(false);
createSuite(true);
});
|
import {keccak256, bufferToHex} from "ethereumjs-util"
export default class MerkleTree {
constructor(elements) {
// Filter empty strings and hash elements
this.elements = elements.filter(el => el).map(el => keccak256(el))
// Deduplicate elements
this.elements = this.bufDedup(this.elements)
// Sort elements
this.elements.sort(Buffer.compare)
// Create layers
this.layers = this.getLayers(this.elements)
}
getLayers(elements) {
if (elements.length === 0) {
return [[""]]
}
const layers = []
layers.push(elements)
// Get next layer until we reach the root
while (layers[layers.length - 1].length > 1) {
layers.push(this.getNextLayer(layers[layers.length - 1]))
}
return layers
}
getNextLayer(elements) {
return elements.reduce((layer, el, idx, arr) => {
if (idx % 2 === 0) {
// Hash the current element with its pair element
layer.push(this.combinedHash(el, arr[idx + 1]))
}
return layer
}, [])
}
combinedHash(first, second) {
if (!first) {
return second
}
if (!second) {
return first
}
return keccak256(this.sortAndConcat(first, second))
}
getRoot() {
return this.layers[this.layers.length - 1][0]
}
getHexRoot() {
return bufferToHex(this.getRoot())
}
getProof(el) {
let idx = this.bufIndexOf(el, this.elements)
if (idx === -1) {
throw new Error("Element does not exist in Merkle tree")
}
return this.layers.reduce((proof, layer) => {
const pairElement = this.getPairElement(idx, layer)
if (pairElement) {
proof.push(pairElement)
}
idx = Math.floor(idx / 2)
return proof
}, [])
}
getHexProof(el) {
const proof = this.getProof(el)
return this.bufArrToHexArr(proof)
}
getPairElement(idx, layer) {
const pairIdx = idx % 2 === 0 ? idx + 1 : idx - 1
if (pairIdx < layer.length) {
return layer[pairIdx]
} else {
return null
}
}
bufIndexOf(el, arr) {
let hash
// Convert element to 32 byte hash if it is not one already
if (el.length !== 32 || !Buffer.isBuffer(el)) {
hash = keccak256(el)
} else {
hash = el
}
for (let i = 0; i < arr.length; i++) {
if (hash.equals(arr[i])) {
return i
}
}
return -1
}
bufDedup(elements) {
return elements.filter((el, idx) => {
return this.bufIndexOf(el, elements) === idx
})
}
bufArrToHexArr(arr) {
if (arr.some(el => !Buffer.isBuffer(el))) {
throw new Error("Array is not an array of buffers")
}
return arr.map(el => "0x" + el.toString("hex"))
}
sortAndConcat(...args) {
return Buffer.concat([...args].sort(Buffer.compare))
}
}
|
//
// peas.js
//
// tree data structure in javascript
//
//////////////////////////
var peas = function() {
// "sub" here is used as an object container for
// operations related to sub nodes.
// Each pea node will have a "sub" property
// with an instance of "sub"
var sub = function() {}
// the current node is accesable as "this.pea", from
// methods in the "sub" object
sub.prototype.pea = null
// first and last sub
sub.prototype.first = null
sub.prototype.last = null
// number of sub nodes
sub.prototype.n = 0
// get subnode at index position (0 index)
sub.prototype.at = function( index ) {
var pik,i
if( index > this.pea.sub.n - 1 )
return null
pik = this.pea.sub.first
for( i=0; i<index; i++ )
pik = pik.next
return pik
}
// add spare node at last position
// returns the added node
sub.prototype.add = function( spare ) {
if( this.pea.sub.last ) {
spare.prev = this.pea.sub.last
this.pea.sub.last.next = spare
this.pea.sub.last = spare
} else {
spare.prev = null
this.pea.sub.first = spare
this.pea.sub.last = spare
}
spare.top = this.pea
spare.next = null
this.pea.sub.n++
return spare
}
// insert sub node at index position
// returns the inserted node
sub.prototype.insertAt = function( spare, index ) {
var pik
// validate index given
if( index < 0 )
throw "node insert failed, invalid index"
if( index > this.pea.sub.n )
throw "node insert failed, given index exceeds valid places"
// if insert at last+1, then just add
if( index == this.pea.sub.n ) {
this.pea.add( spare )
return
}
pik = this.pea.sub.at( index )
spare.prev = pik.prev
spare.next = pik
// if not inserting at first
if( pik.prev ) {
pik.prev.next = spare
} else {
// inserting as first
pik.top.sub.first = spare
}
pik.prev = spare
spare.top = this.pea
this.pea.sub.n++
return spare
}
// executes function "action" on each direct
// sub node (not recursive)
sub.prototype.each = function( action ) {
var node = this.pea.sub.first
while( node ) {
action( node )
node = node.next
}
}
///////////////////////////
// constructor function for pea nodes
peas = function( item ) {
this.sub = new sub()
this.sub.pea = this
this.item = item
}
peas.prototype.item = null
// top node
peas.prototype.top = null
// prev
peas.prototype.prev = null
// next
peas.prototype.next = null
// namespace for sub nodes
peas.prototype.sub = {}
// find the root node, of the tree
// of this node
peas.prototype.root = function() {
var node = this
while ( node.top ) node = node.top
}
// executes function func on all the tree
// nodes below (recursively)
peas.prototype.onAllBelow = function( action ) {
var node = this.sub.first
while( node ) {
action( node )
if( node.sub.n > 0 )
nodeMethods.each( action )
node = node.next
}
}
// removes this node from tree, leaving
// other tree nodes in consistent state
peas.prototype.rip = function() {
if( ! this.top ) return this
if( this.next )
this.next.prev = this.prev
if( this.prev )
this.prev.next = this.next
if( this.top.sub.last == this )
this.top.sub.last = this.prev
if( this.top.sub.first == this )
this.top.sub.first = this.next
this.top.sub.n--
this.top = null
this.next = null
this.prev = null
return this
}
// returns an array containing all nodes below this, in the tree
peas.prototype.flat = function() {
var flat = []
var grab = function( node ) {
flat.push( node )
}
root.onAllBelow( grab )
return flat
}
// puts spare node in the tree,
// before of this node.
// returns the inserted node
peas.prototype.putBefore = function( spare ) {
if( ! this.top )
throw "not in a tree"
if ( this.prev )
this.prev.next = spare
if( this.top.sub.first == this )
this.top.sub.first = spare
spare.next = this
spare.prev = this.prev
this.prev = spare
spare.top = this.top
this.top.sub.n++
return spare
}
return peas
}()
|
import formatPhoneNumber, { formatPhoneNumberIntl } from './formatPhoneNumberDefaultMetadata'
describe('formatPhoneNumberDefaultMetadata', () => {
it('should format phone numbers', () => {
formatPhoneNumber('+12133734253', 'NATIONAL').should.equal('(213) 373-4253')
formatPhoneNumber('+12133734253', 'INTERNATIONAL').should.equal('+1 213 373 4253')
formatPhoneNumberIntl('+12133734253').should.equal('+1 213 373 4253')
})
}) |
var final_transcript = '';
var recognizing = false;
//var socket = io.connect('http://collab.di.uniba.it:48922');//"http://collab.di.uniba.it/~iaffaldano:48922"
//socket.emit('client_type', {text: "Speaker"});
if ('webkitSpeechRecognition' in window) {
var recognition = new webkitSpeechRecognition();
recognition.continuous = true;
recognition.interimResults = true;
console.log("MAX ALTERNATIVES = "+ recognition.maxAlternatives);
recognition.onstart = function () {
recognizing = true;
console.log("RECOGNITION STARTED");
};
recognition.onerror = function (event) {
console.log("RECOGNITION ERROR: " + event.error);
recognition.start();
};
recognition.onend = function () {
console.log("RECOGNITION STOPPED");
if(recognizing){
recognition.start();
console.log("RECOGNITION RESTARTED");
}
};
recognition.onresult = function (event) {
var interim_transcript = '';
for (var i = event.resultIndex; i < event.results.length; ++i) {
if (event.results[i].isFinal) {
final_transcript += event.results[i][0].transcript;
console.log("CONFIDENCE (" + event.results[i][0].transcript + ") = " + event.results[i][0].confidence);
//recognition.stop();
//recognition.start();
socket.emit('client_message', {text: event.results[i][0].transcript});
} else {
interim_transcript += event.results[i][0].transcript;
}
}
final_transcript = capitalize(final_transcript);
final_span.innerHTML = linebreak(final_transcript);
interim_span.innerHTML = linebreak(interim_transcript);
};
recognition.onaudiostart= function (event) {
console.log("AUDIO START");
};
recognition.onsoundstart= function (event) {
console.log("SOUND START");
};
recognition.onspeechstart= function (event) {
console.log("SPEECH START");
};
recognition.onspeechend= function (event) {
console.log("SPEECH END");
};
recognition.onsoundend= function (event) {
console.log("SOUND END");
};
recognition.onnomatch= function (event) {
console.log("NO MATCH");
};
}
var two_line = /\n\n/g;
var one_line = /\n/g;
function linebreak(s) {
return s.replace(two_line, '<p></p>').replace(one_line, '<br>');
}
function capitalize(s) {
return s.replace(s.substr(0, 1), function (m) {
return m.toUpperCase();
});
}
function startDictation(event) {
if (recognizing) {
recognition.stop();
recognizing=false;
start_button.innerHTML = "START"
return;
}
final_transcript = '';
recognition.lang = 'it-IT';
recognition.start();
start_button.innerHTML = "STOP"
final_span.innerHTML = '';
interim_span.innerHTML = '';
} |
/* eslint-disable promise/always-return */
import { runAuthenticatedQuery, runQuery } from "schema/v1/test/utils"
describe("UpdateCollectorProfile", () => {
it("updates and returns a collector profile", () => {
/* eslint-disable max-len */
const mutation = `
mutation {
updateCollectorProfile(input: { professional_buyer: true, loyalty_applicant: true, self_reported_purchases: "trust me i buy art", intents: [BUY_ART_AND_DESIGN] }) {
id
name
email
self_reported_purchases
intents
}
}
`
/* eslint-enable max-len */
const context = {
updateCollectorProfileLoader: () =>
Promise.resolve({
id: "3",
name: "Percy",
email: "[email protected]",
self_reported_purchases: "treats",
intents: ["buy art & design"],
}),
}
const expectedProfileData = {
id: "3",
name: "Percy",
email: "[email protected]",
self_reported_purchases: "treats",
intents: ["buy art & design"],
}
expect.assertions(1)
return runAuthenticatedQuery(mutation, context).then(
({ updateCollectorProfile }) => {
expect(updateCollectorProfile).toEqual(expectedProfileData)
}
)
})
it("throws error when data loader is missing", () => {
/* eslint-disable max-len */
const mutation = `
mutation {
updateCollectorProfile(input: { professional_buyer: true, loyalty_applicant: true, self_reported_purchases: "trust me i buy art" }) {
id
name
email
self_reported_purchases
intents
}
}
`
/* eslint-enable max-len */
const errorResponse =
"Missing Update Collector Profile Loader. Check your access token."
expect.assertions(1)
return runQuery(mutation)
.then(() => {
throw new Error("An error was not thrown but was expected.")
})
.catch(error => {
expect(error.message).toEqual(errorResponse)
})
})
})
|
module.exports = require('./src/tracking');
|
/*
Configures webpack to build only assets required
for integration environments.
*/
const webpack = require('webpack');
const merge = require('webpack-merge');
const { source, sourceAll } = require('../lib/path-helpers');
const ciBuildWorkflow = require('./workflow/build.ci');
const { entries } = require(source('fc-config')); // eslint-disable-line
// remove the styleguide dll references
const modify = (config) => {
config.plugins = config.plugins.slice(1);
return config;
};
module.exports = modify(merge(ciBuildWorkflow, {
entry: sourceAll(entries.ci),
plugins: [
new webpack.DefinePlugin({
'process.env.CI_MODE': true
})
]
}));
|
/**
* A null-safe function to repeat the source string the desired amount of times.
* @private
* @param {String} source
* @param {Number} times
* @returns {String}
*/
function _repeat (source, times) {
var result = "";
for (var i = 0; i < times; i++) {
result += source;
}
return result;
}
export default _repeat;
|
(function(d,a){function b(a,b){var g=a.nodeName.toLowerCase();if("area"===g){var g=a.parentNode,i=g.name;if(!a.href||!i||g.nodeName.toLowerCase()!=="map")return!1;g=d("img[usemap=#"+i+"]")[0];return!!g&&e(g)}return(/input|select|textarea|button|object/.test(g)?!a.disabled:"a"==g?a.href||b:b)&&e(a)}function e(a){return!d(a).parents().andSelf().filter(function(){return d.curCSS(this,"visibility")==="hidden"||d.expr.filters.hidden(this)}).length}d.ui=d.ui||{};d.ui.version||(d.extend(d.ui,{version:"1.8.16",
keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91}}),d.fn.extend({propAttr:d.fn.prop||d.fn.attr,_focus:d.fn.focus,focus:function(a,b){return typeof a==="number"?this.each(function(){var e=
this;setTimeout(function(){d(e).focus();b&&b.call(e)},a)}):this._focus.apply(this,arguments)},scrollParent:function(){var a;a=d.browser.msie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(d.curCSS(this,"position",1))&&/(auto|scroll)/.test(d.curCSS(this,"overflow",1)+d.curCSS(this,"overflow-y",1)+d.curCSS(this,"overflow-x",1))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(d.curCSS(this,
"overflow",1)+d.curCSS(this,"overflow-y",1)+d.curCSS(this,"overflow-x",1))}).eq(0);return/fixed/.test(this.css("position"))||!a.length?d(document):a},zIndex:function(b){if(b!==a)return this.css("zIndex",b);if(this.length)for(var b=d(this[0]),e;b.length&&b[0]!==document;){e=b.css("position");if(e==="absolute"||e==="relative"||e==="fixed")if(e=parseInt(b.css("zIndex"),10),!isNaN(e)&&e!==0)return e;b=b.parent()}return 0},disableSelection:function(){return this.bind((d.support.selectstart?"selectstart":
"mousedown")+".ui-disableSelection",function(d){d.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}}),d.each(["Width","Height"],function(b,e){function g(a,b,e,h){d.each(i,function(){b-=parseFloat(d.curCSS(a,"padding"+this,!0))||0;e&&(b-=parseFloat(d.curCSS(a,"border"+this+"Width",!0))||0);h&&(b-=parseFloat(d.curCSS(a,"margin"+this,!0))||0)});return b}var i=e==="Width"?["Left","Right"]:["Top","Bottom"],j=e.toLowerCase(),k={innerWidth:d.fn.innerWidth,innerHeight:d.fn.innerHeight,
outerWidth:d.fn.outerWidth,outerHeight:d.fn.outerHeight};d.fn["inner"+e]=function(i){return i===a?k["inner"+e].call(this):this.each(function(){d(this).css(j,g(this,i)+"px")})};d.fn["outer"+e]=function(a,i){return typeof a!=="number"?k["outer"+e].call(this,a):this.each(function(){d(this).css(j,g(this,a,!0,i)+"px")})}}),d.extend(d.expr[":"],{data:function(a,b,e){return!!d.data(a,e[3])},focusable:function(a){return b(a,!isNaN(d.attr(a,"tabindex")))},tabbable:function(a){var e=d.attr(a,"tabindex"),g=
isNaN(e);return(g||e>=0)&&b(a,!g)}}),d(function(){var a=document.body,b=a.appendChild(b=document.createElement("div"));d.extend(b.style,{minHeight:"100px",height:"auto",padding:0,borderWidth:0});d.support.minHeight=b.offsetHeight===100;d.support.selectstart="onselectstart"in b;a.removeChild(b).style.display="none"}),d.extend(d.ui,{plugin:{add:function(a,b,e){var a=d.ui[a].prototype,i;for(i in e)a.plugins[i]=a.plugins[i]||[],a.plugins[i].push([b,e[i]])},call:function(d,a,b){if((a=d.plugins[a])&&d.element[0].parentNode)for(var i=
0;i<a.length;i++)d.options[a[i][0]]&&a[i][1].apply(d.element,b)}},contains:function(d,a){return document.compareDocumentPosition?d.compareDocumentPosition(a)&16:d!==a&&d.contains(a)},hasScroll:function(a,b){if(d(a).css("overflow")==="hidden")return!1;var e=b&&b==="left"?"scrollLeft":"scrollTop",i=!1;if(a[e]>0)return!0;a[e]=1;i=a[e]>0;a[e]=0;return i},isOverAxis:function(d,a,b){return d>a&&d<a+b},isOver:function(a,b,e,i,j,k){return d.ui.isOverAxis(a,e,j)&&d.ui.isOverAxis(b,i,k)}}))})(jQuery);
(function(d,a){if(d.cleanData){var b=d.cleanData;d.cleanData=function(a){for(var e=0,g;(g=a[e])!=null;e++)try{d(g).triggerHandler("remove")}catch(i){}b(a)}}else{var e=d.fn.remove;d.fn.remove=function(a,b){return this.each(function(){b||(!a||d.filter(a,[this]).length)&&d("*",this).add([this]).each(function(){try{d(this).triggerHandler("remove")}catch(a){}});return e.call(d(this),a,b)})}}d.widget=function(a,b,e){var i=a.split(".")[0],j,a=a.split(".")[1];j=i+"-"+a;if(!e)e=b,b=d.Widget;d.expr[":"][j]=
function(b){return!!d.data(b,a)};d[i]=d[i]||{};d[i][a]=function(d,a){arguments.length&&this._createWidget(d,a)};b=new b;b.options=d.extend(!0,{},b.options);d[i][a].prototype=d.extend(!0,b,{namespace:i,widgetName:a,widgetEventPrefix:d[i][a].prototype.widgetEventPrefix||a,widgetBaseClass:j},e);d.widget.bridge(a,d[i][a])};d.widget.bridge=function(b,e){d.fn[b]=function(g){var i=typeof g==="string",j=Array.prototype.slice.call(arguments,1),k=this,g=!i&&j.length?d.extend.apply(null,[!0,g].concat(j)):g;
if(i&&g.charAt(0)==="_")return k;i?this.each(function(){var i=d.data(this,b),e=i&&d.isFunction(i[g])?i[g].apply(i,j):i;if(e!==i&&e!==a)return k=e,!1}):this.each(function(){var a=d.data(this,b);a?a.option(g||{})._init():d.data(this,b,new e(g,this))});return k}};d.Widget=function(d,a){arguments.length&&this._createWidget(d,a)};d.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:!1},_createWidget:function(a,b){d.data(b,this.widgetName,this);this.element=d(b);this.options=d.extend(!0,
{},this.options,this._getCreateOptions(),a);var e=this;this.element.bind("remove."+this.widgetName,function(){e.destroy()});this._create();this._trigger("create");this._init()},_getCreateOptions:function(){return d.metadata&&d.metadata.get(this.element[0])[this.widgetName]},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName);this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+
"-disabled ui-state-disabled")},widget:function(){return this.element},option:function(b,e){var g=b;if(arguments.length===0)return d.extend({},this.options);if(typeof b==="string"){if(e===a)return this.options[b];g={};g[b]=e}this._setOptions(g);return this},_setOptions:function(a){var b=this;d.each(a,function(d,a){b._setOption(d,a)});return this},_setOption:function(d,a){this.options[d]=a;d==="disabled"&&this.widget()[a?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",
a);return this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_trigger:function(a,b,e){var i=this.options[a],b=d.Event(b);b.type=(a===this.widgetEventPrefix?a:this.widgetEventPrefix+a).toLowerCase();e=e||{};if(b.originalEvent)for(var a=d.event.props.length,j;a;)j=d.event.props[--a],b[j]=b.originalEvent[j];this.element.trigger(b,e);return!(d.isFunction(i)&&i.call(this.element[0],b,e)===!1||b.isDefaultPrevented())}}})(jQuery);
(function(d){var a=!1;d(document).mouseup(function(){a=!1});d.widget("ui.mouse",{options:{cancel:":input,option",distance:1,delay:0},_mouseInit:function(){var a=this;this.element.bind("mousedown."+this.widgetName,function(d){return a._mouseDown(d)}).bind("click."+this.widgetName,function(e){if(!0===d.data(e.target,a.widgetName+".preventClickEvent"))return d.removeData(e.target,a.widgetName+".preventClickEvent"),e.stopImmediatePropagation(),!1});this.started=!1},_mouseDestroy:function(){this.element.unbind("."+
this.widgetName)},_mouseDown:function(b){if(!a){this._mouseStarted&&this._mouseUp(b);this._mouseDownEvent=b;var e=this,f=b.which==1,h=typeof this.options.cancel=="string"&&b.target.nodeName?d(b.target).closest(this.options.cancel).length:!1;if(!f||h||!this._mouseCapture(b))return!0;this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet)this._mouseDelayTimer=setTimeout(function(){e.mouseDelayMet=!0},this.options.delay);if(this._mouseDistanceMet(b)&&this._mouseDelayMet(b)&&(this._mouseStarted=
this._mouseStart(b)!==!1,!this._mouseStarted))return b.preventDefault(),!0;!0===d.data(b.target,this.widgetName+".preventClickEvent")&&d.removeData(b.target,this.widgetName+".preventClickEvent");this._mouseMoveDelegate=function(d){return e._mouseMove(d)};this._mouseUpDelegate=function(d){return e._mouseUp(d)};d(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);b.preventDefault();return a=!0}},_mouseMove:function(a){if(d.browser.msie&&
!(document.documentMode>=9)&&!a.button)return this._mouseUp(a);if(this._mouseStarted)return this._mouseDrag(a),a.preventDefault();if(this._mouseDistanceMet(a)&&this._mouseDelayMet(a))(this._mouseStarted=this._mouseStart(this._mouseDownEvent,a)!==!1)?this._mouseDrag(a):this._mouseUp(a);return!this._mouseStarted},_mouseUp:function(a){d(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted)this._mouseStarted=
!1,a.target==this._mouseDownEvent.target&&d.data(a.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(a);return!1},_mouseDistanceMet:function(d){return Math.max(Math.abs(this._mouseDownEvent.pageX-d.pageX),Math.abs(this._mouseDownEvent.pageY-d.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}})})(jQuery);
(function(d){d.widget("ui.accordion",{options:{active:0,animated:"slide",autoHeight:!0,clearStyle:!1,collapsible:!1,event:"click",fillSpace:!1,header:"> li > :first-child,> :not(li):even",icons:{header:"ui-icon-triangle-1-e",headerSelected:"ui-icon-triangle-1-s"},navigation:!1,navigationFilter:function(){return this.href.toLowerCase()===location.href.toLowerCase()}},_create:function(){var a=this,b=a.options;a.running=0;a.element.addClass("ui-accordion ui-widget ui-helper-reset").children("li").addClass("ui-accordion-li-fix");
a.headers=a.element.find(b.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all").bind("mouseenter.accordion",function(){b.disabled||d(this).addClass("ui-state-hover")}).bind("mouseleave.accordion",function(){b.disabled||d(this).removeClass("ui-state-hover")}).bind("focus.accordion",function(){b.disabled||d(this).addClass("ui-state-focus")}).bind("blur.accordion",function(){b.disabled||d(this).removeClass("ui-state-focus")});a.headers.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom");
if(b.navigation){var e=a.element.find("a").filter(b.navigationFilter).eq(0);if(e.length){var f=e.closest(".ui-accordion-header");a.active=f.length?f:e.closest(".ui-accordion-content").prev()}}a.active=a._findActive(a.active||b.active).addClass("ui-state-default ui-state-active").toggleClass("ui-corner-all").toggleClass("ui-corner-top");a.active.next().addClass("ui-accordion-content-active");a._createIcons();a.resize();a.element.attr("role","tablist");a.headers.attr("role","tab").bind("keydown.accordion",
function(d){return a._keydown(d)}).next().attr("role","tabpanel");a.headers.not(a.active||"").attr({"aria-expanded":"false","aria-selected":"false",tabIndex:-1}).next().hide();a.active.length?a.active.attr({"aria-expanded":"true","aria-selected":"true",tabIndex:0}):a.headers.eq(0).attr("tabIndex",0);d.browser.safari||a.headers.find("a").attr("tabIndex",-1);b.event&&a.headers.bind(b.event.split(" ").join(".accordion ")+".accordion",function(d){a._clickHandler.call(a,d,this);d.preventDefault()})},_createIcons:function(){var a=
this.options;a.icons&&(d("<span></span>").addClass("ui-icon "+a.icons.header).prependTo(this.headers),this.active.children(".ui-icon").toggleClass(a.icons.header).toggleClass(a.icons.headerSelected),this.element.addClass("ui-accordion-icons"))},_destroyIcons:function(){this.headers.children(".ui-icon").remove();this.element.removeClass("ui-accordion-icons")},destroy:function(){var a=this.options;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role");this.headers.unbind(".accordion").removeClass("ui-accordion-header ui-accordion-disabled ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top").removeAttr("role").removeAttr("aria-expanded").removeAttr("aria-selected").removeAttr("tabIndex");
this.headers.find("a").removeAttr("tabIndex");this._destroyIcons();var b=this.headers.next().css("display","").removeAttr("role").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-accordion-disabled ui-state-disabled");(a.autoHeight||a.fillHeight)&&b.css("height","");return d.Widget.prototype.destroy.call(this)},_setOption:function(a,b){d.Widget.prototype._setOption.apply(this,arguments);a=="active"&&this.activate(b);a=="icons"&&(this._destroyIcons(),
b&&this._createIcons());if(a=="disabled")this.headers.add(this.headers.next())[b?"addClass":"removeClass"]("ui-accordion-disabled ui-state-disabled")},_keydown:function(a){if(!this.options.disabled&&!a.altKey&&!a.ctrlKey){var b=d.ui.keyCode,e=this.headers.length,f=this.headers.index(a.target),h=!1;switch(a.keyCode){case b.RIGHT:case b.DOWN:h=this.headers[(f+1)%e];break;case b.LEFT:case b.UP:h=this.headers[(f-1+e)%e];break;case b.SPACE:case b.ENTER:this._clickHandler({target:a.target},a.target),a.preventDefault()}return h?
(d(a.target).attr("tabIndex",-1),d(h).attr("tabIndex",0),h.focus(),!1):!0}},resize:function(){var a=this.options,b;if(a.fillSpace){if(d.browser.msie){var e=this.element.parent().css("overflow");this.element.parent().css("overflow","hidden")}b=this.element.parent().height();d.browser.msie&&this.element.parent().css("overflow",e);this.headers.each(function(){b-=d(this).outerHeight(!0)});this.headers.next().each(function(){d(this).height(Math.max(0,b-d(this).innerHeight()+d(this).height()))}).css("overflow",
"auto")}else a.autoHeight&&(b=0,this.headers.next().each(function(){b=Math.max(b,d(this).height("").height())}).height(b));return this},activate:function(d){this.options.active=d;d=this._findActive(d)[0];this._clickHandler({target:d},d);return this},_findActive:function(a){return a?typeof a==="number"?this.headers.filter(":eq("+a+")"):this.headers.not(this.headers.not(a)):a===!1?d([]):this.headers.filter(":eq(0)")},_clickHandler:function(a,b){var e=this.options;if(!e.disabled)if(a.target){var f=d(a.currentTarget||
b),h=f[0]===this.active[0];e.active=e.collapsible&&h?!1:this.headers.index(f);if(!(this.running||!e.collapsible&&h)){var g=this.active,i=f.next(),j=this.active.next(),k={options:e,newHeader:h&&e.collapsible?d([]):f,oldHeader:this.active,newContent:h&&e.collapsible?d([]):i,oldContent:j},l=this.headers.index(this.active[0])>this.headers.index(f[0]);this.active=h?d([]):f;this._toggle(i,j,k,h,l);g.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").children(".ui-icon").removeClass(e.icons.headerSelected).addClass(e.icons.header);
h||(f.removeClass("ui-state-default ui-corner-all").addClass("ui-state-active ui-corner-top").children(".ui-icon").removeClass(e.icons.header).addClass(e.icons.headerSelected),f.next().addClass("ui-accordion-content-active"))}}else if(e.collapsible){this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").children(".ui-icon").removeClass(e.icons.headerSelected).addClass(e.icons.header);this.active.next().addClass("ui-accordion-content-active");var j=this.active.next(),
k={options:e,newHeader:d([]),oldHeader:e.active,newContent:d([]),oldContent:j},i=this.active=d([]);this._toggle(i,j,k)}},_toggle:function(a,b,e,f,h){var g=this,i=g.options;g.toShow=a;g.toHide=b;g.data=e;var j=function(){return!g?void 0:g._completed.apply(g,arguments)};g._trigger("changestart",null,g.data);g.running=b.size()===0?a.size():b.size();if(i.animated){e={};e=i.collapsible&&f?{toShow:d([]),toHide:b,complete:j,down:h,autoHeight:i.autoHeight||i.fillSpace}:{toShow:a,toHide:b,complete:j,down:h,
autoHeight:i.autoHeight||i.fillSpace};if(!i.proxied)i.proxied=i.animated;if(!i.proxiedDuration)i.proxiedDuration=i.duration;i.animated=d.isFunction(i.proxied)?i.proxied(e):i.proxied;i.duration=d.isFunction(i.proxiedDuration)?i.proxiedDuration(e):i.proxiedDuration;var f=d.ui.accordion.animations,k=i.duration,l=i.animated;l&&!f[l]&&!d.easing[l]&&(l="slide");f[l]||(f[l]=function(d){this.slide(d,{easing:l,duration:k||700})});f[l](e)}else i.collapsible&&f?a.toggle():(b.hide(),a.show()),j(!0);b.prev().attr({"aria-expanded":"false",
"aria-selected":"false",tabIndex:-1}).blur();a.prev().attr({"aria-expanded":"true","aria-selected":"true",tabIndex:0}).focus()},_completed:function(d){this.running=d?0:--this.running;if(!this.running){this.options.clearStyle&&this.toShow.add(this.toHide).css({height:"",overflow:""});this.toHide.removeClass("ui-accordion-content-active");if(this.toHide.length)this.toHide.parent()[0].className=this.toHide.parent()[0].className;this._trigger("change",null,this.data)}}});d.extend(d.ui.accordion,{version:"1.8.16",
animations:{slide:function(a,b){a=d.extend({easing:"swing",duration:300},a,b);if(a.toHide.size())if(a.toShow.size()){var e=a.toShow.css("overflow"),f=0,h={},g={},i,j=a.toShow;i=j[0].style.width;j.width(parseInt(j.parent().width(),10)-parseInt(j.css("paddingLeft"),10)-parseInt(j.css("paddingRight"),10)-(parseInt(j.css("borderLeftWidth"),10)||0)-(parseInt(j.css("borderRightWidth"),10)||0));d.each(["height","paddingTop","paddingBottom"],function(b,i){g[i]="hide";var e=(""+d.css(a.toShow[0],i)).match(/^([\d+-.]+)(.*)$/);
h[i]={value:e[1],unit:e[2]||"px"}});a.toShow.css({height:0,overflow:"hidden"}).show();a.toHide.filter(":hidden").each(a.complete).end().filter(":visible").animate(g,{step:function(d,b){b.prop=="height"&&(f=b.end-b.start===0?0:(b.now-b.start)/(b.end-b.start));a.toShow[0].style[b.prop]=f*h[b.prop].value+h[b.prop].unit},duration:a.duration,easing:a.easing,complete:function(){a.autoHeight||a.toShow.css("height","");a.toShow.css({width:i,overflow:e});a.complete()}})}else a.toHide.animate({height:"hide",
paddingTop:"hide",paddingBottom:"hide"},a);else a.toShow.animate({height:"show",paddingTop:"show",paddingBottom:"show"},a)},bounceslide:function(d){this.slide(d,{easing:d.down?"easeOutBounce":"swing",duration:d.down?1E3:200})}}})})(jQuery);
(function(d){var a=0;d.widget("ui.autocomplete",{options:{appendTo:"body",autoFocus:!1,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null},pending:0,_create:function(){var a=this,e=this.element[0].ownerDocument,f;this.element.addClass("ui-autocomplete-input").attr("autocomplete","off").attr({role:"textbox","aria-autocomplete":"list","aria-haspopup":"true"}).bind("keydown.autocomplete",function(e){if(!a.options.disabled&&!a.element.propAttr("readOnly")){f=
!1;var g=d.ui.keyCode;switch(e.keyCode){case g.PAGE_UP:a._move("previousPage",e);break;case g.PAGE_DOWN:a._move("nextPage",e);break;case g.UP:a._move("previous",e);e.preventDefault();break;case g.DOWN:a._move("next",e);e.preventDefault();break;case g.ENTER:case g.NUMPAD_ENTER:a.menu.active&&(f=!0,e.preventDefault());case g.TAB:if(!a.menu.active)break;a.menu.select(e);break;case g.ESCAPE:a.element.val(a.term);a.close(e);break;default:clearTimeout(a.searching),a.searching=setTimeout(function(){if(a.term!=
a.element.val())a.selectedItem=null,a.search(null,e)},a.options.delay)}}}).bind("keypress.autocomplete",function(d){f&&(f=!1,d.preventDefault())}).bind("focus.autocomplete",function(){if(!a.options.disabled)a.selectedItem=null,a.previous=a.element.val()}).bind("blur.autocomplete",function(d){if(!a.options.disabled)clearTimeout(a.searching),a.closing=setTimeout(function(){a.close(d);a._change(d)},150)});this._initSource();this.response=function(){return a._response.apply(a,arguments)};this.menu=d("<ul></ul>").addClass("ui-autocomplete").appendTo(d(this.options.appendTo||
"body",e)[0]).mousedown(function(e){var f=a.menu.element[0];d(e.target).closest(".ui-menu-item").length||setTimeout(function(){d(document).one("mousedown",function(i){i.target!==a.element[0]&&i.target!==f&&!d.ui.contains(f,i.target)&&a.close()})},1);setTimeout(function(){clearTimeout(a.closing)},13)}).menu({focus:function(d,e){var i=e.item.data("item.autocomplete");!1!==a._trigger("focus",d,{item:i})&&/^key/.test(d.originalEvent.type)&&a.element.val(i.value)},selected:function(d,f){var i=f.item.data("item.autocomplete"),
j=a.previous;if(a.element[0]!==e.activeElement)a.element.focus(),a.previous=j,setTimeout(function(){a.previous=j;a.selectedItem=i},1);!1!==a._trigger("select",d,{item:i})&&a.element.val(i.value);a.term=a.element.val();a.close(d);a.selectedItem=i},blur:function(){a.menu.element.is(":visible")&&a.element.val()!==a.term&&a.element.val(a.term)}}).zIndex(this.element.zIndex()+1).css({top:0,left:0}).hide().data("menu");d.fn.bgiframe&&this.menu.element.bgiframe()},destroy:function(){this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete").removeAttr("role").removeAttr("aria-autocomplete").removeAttr("aria-haspopup");
this.menu.element.remove();d.Widget.prototype.destroy.call(this)},_setOption:function(a,e){d.Widget.prototype._setOption.apply(this,arguments);a==="source"&&this._initSource();a==="appendTo"&&this.menu.element.appendTo(d(e||"body",this.element[0].ownerDocument)[0]);a==="disabled"&&e&&this.xhr&&this.xhr.abort()},_initSource:function(){var b=this,e,f;d.isArray(this.options.source)?(e=this.options.source,this.source=function(a,b){b(d.ui.autocomplete.filter(e,a.term))}):typeof this.options.source==="string"?
(f=this.options.source,this.source=function(e,g){b.xhr&&b.xhr.abort();b.xhr=d.ajax({url:f,data:e,dataType:"json",autocompleteRequest:++a,success:function(d){this.autocompleteRequest===a&&g(d)},error:function(){this.autocompleteRequest===a&&g([])}})}):this.source=this.options.source},search:function(d,a){d=d!=null?d:this.element.val();this.term=this.element.val();if(d.length<this.options.minLength)return this.close(a);clearTimeout(this.closing);return this._trigger("search",a)===!1?void 0:this._search(d)},
_search:function(d){this.pending++;this.element.addClass("ui-autocomplete-loading");this.source({term:d},this.response)},_response:function(d){!this.options.disabled&&d&&d.length?(d=this._normalize(d),this._suggest(d),this._trigger("open")):this.close();this.pending--;this.pending||this.element.removeClass("ui-autocomplete-loading")},close:function(d){clearTimeout(this.closing);this.menu.element.is(":visible")&&(this.menu.element.hide(),this.menu.deactivate(),this._trigger("close",d))},_change:function(d){this.previous!==
this.element.val()&&this._trigger("change",d,{item:this.selectedItem})},_normalize:function(a){return a.length&&a[0].label&&a[0].value?a:d.map(a,function(a){return typeof a==="string"?{label:a,value:a}:d.extend({label:a.label||a.value,value:a.value||a.label},a)})},_suggest:function(a){var e=this.menu.element.empty().zIndex(this.element.zIndex()+1);this._renderMenu(e,a);this.menu.deactivate();this.menu.refresh();e.show();this._resizeMenu();e.position(d.extend({of:this.element},this.options.position));
this.options.autoFocus&&this.menu.next(new d.Event("mouseover"))},_resizeMenu:function(){var d=this.menu.element;d.outerWidth(Math.max(d.width("").outerWidth(),this.element.outerWidth()))},_renderMenu:function(a,e){var f=this;d.each(e,function(d,e){f._renderItem(a,e)})},_renderItem:function(a,e){return d("<li></li>").data("item.autocomplete",e).append(d("<a></a>").text(e.label)).appendTo(a)},_move:function(d,a){if(this.menu.element.is(":visible"))if(this.menu.first()&&/^previous/.test(d)||this.menu.last()&&
/^next/.test(d))this.element.val(this.term),this.menu.deactivate();else this.menu[d](a);else this.search(null,a)},widget:function(){return this.menu.element}});d.extend(d.ui.autocomplete,{escapeRegex:function(d){return d.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")},filter:function(a,e){var f=RegExp(d.ui.autocomplete.escapeRegex(e),"i");return d.grep(a,function(d){return f.test(d.label||d.value||d)})}})})(jQuery);
(function(d){d.widget("ui.menu",{_create:function(){var a=this;this.element.addClass("ui-menu ui-widget ui-widget-content ui-corner-all").attr({role:"listbox","aria-activedescendant":"ui-active-menuitem"}).click(function(b){d(b.target).closest(".ui-menu-item a").length&&(b.preventDefault(),a.select(b))});this.refresh()},refresh:function(){var a=this;this.element.children("li:not(.ui-menu-item):has(a)").addClass("ui-menu-item").attr("role","menuitem").children("a").addClass("ui-corner-all").attr("tabindex",
-1).mouseenter(function(b){a.activate(b,d(this).parent())}).mouseleave(function(){a.deactivate()})},activate:function(d,b){this.deactivate();if(this.hasScroll()){var e=b.offset().top-this.element.offset().top,f=this.element.scrollTop(),h=this.element.height();e<0?this.element.scrollTop(f+e):e>=h&&this.element.scrollTop(f+e-h+b.height())}this.active=b.eq(0).children("a").addClass("ui-state-hover").attr("id","ui-active-menuitem").end();this._trigger("focus",d,{item:b})},deactivate:function(){if(this.active)this.active.children("a").removeClass("ui-state-hover").removeAttr("id"),
this._trigger("blur"),this.active=null},next:function(d){this.move("next",".ui-menu-item:first",d)},previous:function(d){this.move("prev",".ui-menu-item:last",d)},first:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},last:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},move:function(d,b,e){this.active?(d=this.active[d+"All"](".ui-menu-item").eq(0),d.length?this.activate(e,d):this.activate(e,this.element.children(b))):this.activate(e,this.element.children(b))},
nextPage:function(a){if(this.hasScroll())if(!this.active||this.last())this.activate(a,this.element.children(".ui-menu-item:first"));else{var b=this.active.offset().top,e=this.element.height(),f=this.element.children(".ui-menu-item").filter(function(){var a=d(this).offset().top-b-e+d(this).height();return a<10&&a>-10});f.length||(f=this.element.children(".ui-menu-item:last"));this.activate(a,f)}else this.activate(a,this.element.children(".ui-menu-item").filter(!this.active||this.last()?":first":":last"))},
previousPage:function(a){if(this.hasScroll())if(!this.active||this.first())this.activate(a,this.element.children(".ui-menu-item:last"));else{var b=this.active.offset().top,e=this.element.height();result=this.element.children(".ui-menu-item").filter(function(){var a=d(this).offset().top-b+e-d(this).height();return a<10&&a>-10});result.length||(result=this.element.children(".ui-menu-item:first"));this.activate(a,result)}else this.activate(a,this.element.children(".ui-menu-item").filter(!this.active||
this.first()?":last":":first"))},hasScroll:function(){return this.element.height()<this.element[d.fn.prop?"prop":"attr"]("scrollHeight")},select:function(d){this._trigger("selected",d,{item:this.active})}})})(jQuery);
(function(d){var a,b,e,f,h=function(){var a=d(this).find(":ui-button");setTimeout(function(){a.button("refresh")},1)},g=function(a){var b=a.name,e=a.form,f=d([]);b&&(f=e?d(e).find("[name='"+b+"']"):d("[name='"+b+"']",a.ownerDocument).filter(function(){return!this.form}));return f};d.widget("ui.button",{options:{disabled:null,text:!0,label:null,icons:{primary:null,secondary:null}},_create:function(){this.element.closest("form").unbind("reset.button").bind("reset.button",h);if(typeof this.options.disabled!==
"boolean")this.options.disabled=this.element.propAttr("disabled");this._determineButtonType();this.hasTitle=!!this.buttonElement.attr("title");var i=this,j=this.options,k=this.type==="checkbox"||this.type==="radio",l="ui-state-hover"+(!k?" ui-state-active":"");if(j.label===null)j.label=this.buttonElement.html();if(this.element.is(":disabled"))j.disabled=!0;this.buttonElement.addClass("ui-button ui-widget ui-state-default ui-corner-all").attr("role","button").bind("mouseenter.button",function(){j.disabled||
(d(this).addClass("ui-state-hover"),this===a&&d(this).addClass("ui-state-active"))}).bind("mouseleave.button",function(){j.disabled||d(this).removeClass(l)}).bind("click.button",function(d){j.disabled&&(d.preventDefault(),d.stopImmediatePropagation())});this.element.bind("focus.button",function(){i.buttonElement.addClass("ui-state-focus")}).bind("blur.button",function(){i.buttonElement.removeClass("ui-state-focus")});k&&(this.element.bind("change.button",function(){f||i.refresh()}),this.buttonElement.bind("mousedown.button",
function(d){if(!j.disabled)f=!1,b=d.pageX,e=d.pageY}).bind("mouseup.button",function(d){if(!j.disabled&&(b!==d.pageX||e!==d.pageY))f=!0}));this.type==="checkbox"?this.buttonElement.bind("click.button",function(){if(j.disabled||f)return!1;d(this).toggleClass("ui-state-active");i.buttonElement.attr("aria-pressed",i.element[0].checked)}):this.type==="radio"?this.buttonElement.bind("click.button",function(){if(j.disabled||f)return!1;d(this).addClass("ui-state-active");i.buttonElement.attr("aria-pressed",
"true");var a=i.element[0];g(a).not(a).map(function(){return d(this).button("widget")[0]}).removeClass("ui-state-active").attr("aria-pressed","false")}):(this.buttonElement.bind("mousedown.button",function(){if(j.disabled)return!1;d(this).addClass("ui-state-active");a=this;d(document).one("mouseup",function(){a=null})}).bind("mouseup.button",function(){if(j.disabled)return!1;d(this).removeClass("ui-state-active")}).bind("keydown.button",function(a){if(j.disabled)return!1;(a.keyCode==d.ui.keyCode.SPACE||
a.keyCode==d.ui.keyCode.ENTER)&&d(this).addClass("ui-state-active")}).bind("keyup.button",function(){d(this).removeClass("ui-state-active")}),this.buttonElement.is("a")&&this.buttonElement.keyup(function(a){a.keyCode===d.ui.keyCode.SPACE&&d(this).click()}));this._setOption("disabled",j.disabled);this._resetButton()},_determineButtonType:function(){this.type=this.element.is(":checkbox")?"checkbox":this.element.is(":radio")?"radio":this.element.is("input")?"input":"button";if(this.type==="checkbox"||
this.type==="radio"){var d=this.element.parents().filter(":last"),a="label[for='"+this.element.attr("id")+"']";this.buttonElement=d.find(a);if(!this.buttonElement.length&&(d=d.length?d.siblings():this.element.siblings(),this.buttonElement=d.filter(a),!this.buttonElement.length))this.buttonElement=d.find(a);this.element.addClass("ui-helper-hidden-accessible");(d=this.element.is(":checked"))&&this.buttonElement.addClass("ui-state-active");this.buttonElement.attr("aria-pressed",d)}else this.buttonElement=
this.element},widget:function(){return this.buttonElement},destroy:function(){this.element.removeClass("ui-helper-hidden-accessible");this.buttonElement.removeClass("ui-button ui-widget ui-state-default ui-corner-all ui-state-hover ui-state-active ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only").removeAttr("role").removeAttr("aria-pressed").html(this.buttonElement.find(".ui-button-text").html());this.hasTitle||
this.buttonElement.removeAttr("title");d.Widget.prototype.destroy.call(this)},_setOption:function(a,b){d.Widget.prototype._setOption.apply(this,arguments);a==="disabled"?b?this.element.propAttr("disabled",!0):this.element.propAttr("disabled",!1):this._resetButton()},refresh:function(){var a=this.element.is(":disabled");a!==this.options.disabled&&this._setOption("disabled",a);this.type==="radio"?g(this.element[0]).each(function(){d(this).is(":checked")?d(this).button("widget").addClass("ui-state-active").attr("aria-pressed",
"true"):d(this).button("widget").removeClass("ui-state-active").attr("aria-pressed","false")}):this.type==="checkbox"&&(this.element.is(":checked")?this.buttonElement.addClass("ui-state-active").attr("aria-pressed","true"):this.buttonElement.removeClass("ui-state-active").attr("aria-pressed","false"))},_resetButton:function(){if(this.type==="input")this.options.label&&this.element.val(this.options.label);else{var a=this.buttonElement.removeClass("ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only"),
b=d("<span></span>").addClass("ui-button-text").html(this.options.label).appendTo(a.empty()).text(),e=this.options.icons,f=e.primary&&e.secondary,h=[];e.primary||e.secondary?(this.options.text&&h.push("ui-button-text-icon"+(f?"s":e.primary?"-primary":"-secondary")),e.primary&&a.prepend("<span class='ui-button-icon-primary ui-icon "+e.primary+"'></span>"),e.secondary&&a.append("<span class='ui-button-icon-secondary ui-icon "+e.secondary+"'></span>"),this.options.text||(h.push(f?"ui-button-icons-only":
"ui-button-icon-only"),this.hasTitle||a.attr("title",b))):h.push("ui-button-text-only");a.addClass(h.join(" "))}}});d.widget("ui.buttonset",{options:{items:":button, :submit, :reset, :checkbox, :radio, a, :data(button)"},_create:function(){this.element.addClass("ui-buttonset")},_init:function(){this.refresh()},_setOption:function(a,b){a==="disabled"&&this.buttons.button("option",a,b);d.Widget.prototype._setOption.apply(this,arguments)},refresh:function(){var a=this.element.css("direction")==="ltr";
this.buttons=this.element.find(this.options.items).filter(":ui-button").button("refresh").end().not(":ui-button").button().end().map(function(){return d(this).button("widget")[0]}).removeClass("ui-corner-all ui-corner-left ui-corner-right").filter(":first").addClass(a?"ui-corner-left":"ui-corner-right").end().filter(":last").addClass(a?"ui-corner-right":"ui-corner-left").end().end()},destroy:function(){this.element.removeClass("ui-buttonset");this.buttons.map(function(){return d(this).button("widget")[0]}).removeClass("ui-corner-left ui-corner-right").end().button("destroy");
d.Widget.prototype.destroy.call(this)}})})(jQuery);
(function(d,a){function b(){this.debug=!1;this._curInst=null;this._keyEvent=!1;this._disabledInputs=[];this._inDialog=this._datepickerShowing=!1;this._mainDivId="ui-datepicker-div";this._inlineClass="ui-datepicker-inline";this._appendClass="ui-datepicker-append";this._triggerClass="ui-datepicker-trigger";this._dialogClass="ui-datepicker-dialog";this._disableClass="ui-datepicker-disabled";this._unselectableClass="ui-datepicker-unselectable";this._currentClass="ui-datepicker-current-day";this._dayOverClass=
"ui-datepicker-days-cell-over";this.regional=[];this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su",
"Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""};this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:!1,hideIfNoPrevNext:!1,navigationAsDateFormat:!1,gotoCurrent:!1,changeMonth:!1,changeYear:!1,yearRange:"c-10:c+10",showOtherMonths:!1,selectOtherMonths:!1,showWeek:!1,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,
maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:!0,showButtonPanel:!1,autoSize:!1,disabled:!1};d.extend(this._defaults,this.regional[""]);this.dpDiv=e(d('<div id="'+this._mainDivId+'" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))}function e(a){return a.bind("mouseout",function(a){a=
d(a.target).closest("button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a");a.length&&a.removeClass("ui-state-hover ui-datepicker-prev-hover ui-datepicker-next-hover")}).bind("mouseover",function(b){b=d(b.target).closest("button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a");if(!d.datepicker._isDisabledDatepicker(g.inline?a.parent()[0]:g.input[0])&&b.length)b.parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover"),b.addClass("ui-state-hover"),
b.hasClass("ui-datepicker-prev")&&b.addClass("ui-datepicker-prev-hover"),b.hasClass("ui-datepicker-next")&&b.addClass("ui-datepicker-next-hover")})}function f(i,b){d.extend(i,b);for(var e in b)if(b[e]==null||b[e]==a)i[e]=b[e];return i}d.extend(d.ui,{datepicker:{version:"1.8.16"}});var h=(new Date).getTime(),g;d.extend(b.prototype,{markerClassName:"hasDatepicker",maxRows:4,log:function(){this.debug&&console.log.apply("",arguments)},_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(d){f(this._defaults,
d||{});return this},_attachDatepicker:function(a,b){var e=null,f;for(f in this._defaults){var h=a.getAttribute("date:"+f);if(h){e=e||{};try{e[f]=eval(h)}catch(g){e[f]=h}}}f=a.nodeName.toLowerCase();h=f=="div"||f=="span";if(!a.id)this.uuid+=1,a.id="dp"+this.uuid;var p=this._newInst(d(a),h);p.settings=d.extend({},b||{},e||{});f=="input"?this._connectDatepicker(a,p):h&&this._inlineDatepicker(a,p)},_newInst:function(a,b){return{id:a[0].id.replace(/([^A-Za-z0-9_-])/g,"\\\\$1"),input:a,selectedDay:0,selectedMonth:0,
selectedYear:0,drawMonth:0,drawYear:0,inline:b,dpDiv:!b?this.dpDiv:e(d('<div class="'+this._inlineClass+' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))}},_connectDatepicker:function(a,b){var e=d(a);b.append=d([]);b.trigger=d([]);e.hasClass(this.markerClassName)||(this._attachments(e,b),e.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp).bind("setData.datepicker",function(d,a,i){b.settings[a]=i}).bind("getData.datepicker",
function(d,a){return this._get(b,a)}),this._autoSize(b),d.data(a,"datepicker",b),b.settings.disabled&&this._disableDatepicker(a))},_attachments:function(a,b){var e=this._get(b,"appendText"),f=this._get(b,"isRTL");b.append&&b.append.remove();if(e)b.append=d('<span class="'+this._appendClass+'">'+e+"</span>"),a[f?"before":"after"](b.append);a.unbind("focus",this._showDatepicker);b.trigger&&b.trigger.remove();e=this._get(b,"showOn");(e=="focus"||e=="both")&&a.focus(this._showDatepicker);if(e=="button"||
e=="both"){var e=this._get(b,"buttonText"),h=this._get(b,"buttonImage");b.trigger=d(this._get(b,"buttonImageOnly")?d("<img/>").addClass(this._triggerClass).attr({src:h,alt:e,title:e}):d('<button type="button"></button>').addClass(this._triggerClass).html(h==""?e:d("<img/>").attr({src:h,alt:e,title:e})));a[f?"before":"after"](b.trigger);b.trigger.click(function(){d.datepicker._datepickerShowing&&d.datepicker._lastInput==a[0]?d.datepicker._hideDatepicker():d.datepicker._showDatepicker(a[0]);return!1})}},
_autoSize:function(d){if(this._get(d,"autoSize")&&!d.inline){var a=new Date(2009,11,20),b=this._get(d,"dateFormat");if(b.match(/[DM]/)){var e=function(d){for(var a=0,b=0,i=0;i<d.length;i++)if(d[i].length>a)a=d[i].length,b=i;return b};a.setMonth(e(this._get(d,b.match(/MM/)?"monthNames":"monthNamesShort")));a.setDate(e(this._get(d,b.match(/DD/)?"dayNames":"dayNamesShort"))+20-a.getDay())}d.input.attr("size",this._formatDate(d,a).length)}},_inlineDatepicker:function(a,b){var e=d(a);e.hasClass(this.markerClassName)||
(e.addClass(this.markerClassName).append(b.dpDiv).bind("setData.datepicker",function(d,a,i){b.settings[a]=i}).bind("getData.datepicker",function(d,a){return this._get(b,a)}),d.data(a,"datepicker",b),this._setDate(b,this._getDefaultDate(b),!0),this._updateDatepicker(b),this._updateAlternate(b),b.settings.disabled&&this._disableDatepicker(a),b.dpDiv.css("display","block"))},_dialogDatepicker:function(a,b,e,h,g){a=this._dialogInst;if(!a)this.uuid+=1,this._dialogInput=d('<input type="text" id="dp'+this.uuid+
'" style="position: absolute; top: -100px; width: 0px; z-index: -10;"/>'),this._dialogInput.keydown(this._doKeyDown),d("body").append(this._dialogInput),a=this._dialogInst=this._newInst(this._dialogInput,!1),a.settings={},d.data(this._dialogInput[0],"datepicker",a);f(a.settings,h||{});b=b&&b.constructor==Date?this._formatDate(a,b):b;this._dialogInput.val(b);this._pos=g?g.length?g:[g.pageX,g.pageY]:null;if(!this._pos)this._pos=[document.documentElement.clientWidth/2-100+(document.documentElement.scrollLeft||
document.body.scrollLeft),document.documentElement.clientHeight/2-150+(document.documentElement.scrollTop||document.body.scrollTop)];this._dialogInput.css("left",this._pos[0]+20+"px").css("top",this._pos[1]+"px");a.settings.onSelect=e;this._inDialog=!0;this.dpDiv.addClass(this._dialogClass);this._showDatepicker(this._dialogInput[0]);d.blockUI&&d.blockUI(this.dpDiv);d.data(this._dialogInput[0],"datepicker",a);return this},_destroyDatepicker:function(a){var b=d(a),e=d.data(a,"datepicker");if(b.hasClass(this.markerClassName)){var f=
a.nodeName.toLowerCase();d.removeData(a,"datepicker");f=="input"?(e.append.remove(),e.trigger.remove(),b.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp)):(f=="div"||f=="span")&&b.removeClass(this.markerClassName).empty()}},_enableDatepicker:function(a){var b=d(a),e=d.data(a,"datepicker");if(b.hasClass(this.markerClassName)){var f=a.nodeName.toLowerCase();if(f=="input")a.disabled=
!1,e.trigger.filter("button").each(function(){this.disabled=!1}).end().filter("img").css({opacity:"1.0",cursor:""});else if(f=="div"||f=="span")b=b.children("."+this._inlineClass),b.children().removeClass("ui-state-disabled"),b.find("select.ui-datepicker-month, select.ui-datepicker-year").removeAttr("disabled");this._disabledInputs=d.map(this._disabledInputs,function(d){return d==a?null:d})}},_disableDatepicker:function(a){var b=d(a),e=d.data(a,"datepicker");if(b.hasClass(this.markerClassName)){var f=
a.nodeName.toLowerCase();if(f=="input")a.disabled=!0,e.trigger.filter("button").each(function(){this.disabled=!0}).end().filter("img").css({opacity:"0.5",cursor:"default"});else if(f=="div"||f=="span")b=b.children("."+this._inlineClass),b.children().addClass("ui-state-disabled"),b.find("select.ui-datepicker-month, select.ui-datepicker-year").attr("disabled","disabled");this._disabledInputs=d.map(this._disabledInputs,function(d){return d==a?null:d});this._disabledInputs[this._disabledInputs.length]=
a}},_isDisabledDatepicker:function(d){if(!d)return!1;for(var a=0;a<this._disabledInputs.length;a++)if(this._disabledInputs[a]==d)return!0;return!1},_getInst:function(a){try{return d.data(a,"datepicker")}catch(b){throw"Missing instance data for this datepicker";}},_optionDatepicker:function(b,e,h){var g=this._getInst(b);if(arguments.length==2&&typeof e=="string")return e=="defaults"?d.extend({},d.datepicker._defaults):g?e=="all"?d.extend({},g.settings):this._get(g,e):null;var m=e||{};typeof e=="string"&&
(m={},m[e]=h);if(g){this._curInst==g&&this._hideDatepicker();var o=this._getDateDatepicker(b,!0),p=this._getMinMaxDate(g,"min"),n=this._getMinMaxDate(g,"max");f(g.settings,m);if(p!==null&&m.dateFormat!==a&&m.minDate===a)g.settings.minDate=this._formatDate(g,p);if(n!==null&&m.dateFormat!==a&&m.maxDate===a)g.settings.maxDate=this._formatDate(g,n);this._attachments(d(b),g);this._autoSize(g);this._setDate(g,o);this._updateAlternate(g);this._updateDatepicker(g)}},_changeDatepicker:function(d,a,b){this._optionDatepicker(d,
a,b)},_refreshDatepicker:function(d){(d=this._getInst(d))&&this._updateDatepicker(d)},_setDateDatepicker:function(d,a){var b=this._getInst(d);b&&(this._setDate(b,a),this._updateDatepicker(b),this._updateAlternate(b))},_getDateDatepicker:function(d,a){var b=this._getInst(d);b&&!b.inline&&this._setDateFromField(b,a);return b?this._getDate(b):null},_doKeyDown:function(a){var b=d.datepicker._getInst(a.target),e=!0,f=b.dpDiv.is(".ui-datepicker-rtl");b._keyEvent=!0;if(d.datepicker._datepickerShowing)switch(a.keyCode){case 9:d.datepicker._hideDatepicker();
e=!1;break;case 13:return e=d("td."+d.datepicker._dayOverClass+":not(."+d.datepicker._currentClass+")",b.dpDiv),e[0]&&d.datepicker._selectDay(a.target,b.selectedMonth,b.selectedYear,e[0]),(a=d.datepicker._get(b,"onSelect"))?(e=d.datepicker._formatDate(b),a.apply(b.input?b.input[0]:null,[e,b])):d.datepicker._hideDatepicker(),!1;case 27:d.datepicker._hideDatepicker();break;case 33:d.datepicker._adjustDate(a.target,a.ctrlKey?-d.datepicker._get(b,"stepBigMonths"):-d.datepicker._get(b,"stepMonths"),"M");
break;case 34:d.datepicker._adjustDate(a.target,a.ctrlKey?+d.datepicker._get(b,"stepBigMonths"):+d.datepicker._get(b,"stepMonths"),"M");break;case 35:(a.ctrlKey||a.metaKey)&&d.datepicker._clearDate(a.target);e=a.ctrlKey||a.metaKey;break;case 36:(a.ctrlKey||a.metaKey)&&d.datepicker._gotoToday(a.target);e=a.ctrlKey||a.metaKey;break;case 37:if(a.ctrlKey||a.metaKey)d.datepicker._adjustDate(a.target,f?1:-1,"D");e=a.ctrlKey||a.metaKey;a.originalEvent.altKey&&d.datepicker._adjustDate(a.target,a.ctrlKey?
-d.datepicker._get(b,"stepBigMonths"):-d.datepicker._get(b,"stepMonths"),"M");break;case 38:(a.ctrlKey||a.metaKey)&&d.datepicker._adjustDate(a.target,-7,"D");e=a.ctrlKey||a.metaKey;break;case 39:if(a.ctrlKey||a.metaKey)d.datepicker._adjustDate(a.target,f?-1:1,"D");e=a.ctrlKey||a.metaKey;a.originalEvent.altKey&&d.datepicker._adjustDate(a.target,a.ctrlKey?+d.datepicker._get(b,"stepBigMonths"):+d.datepicker._get(b,"stepMonths"),"M");break;case 40:(a.ctrlKey||a.metaKey)&&d.datepicker._adjustDate(a.target,
7,"D");e=a.ctrlKey||a.metaKey;break;default:e=!1}else a.keyCode==36&&a.ctrlKey?d.datepicker._showDatepicker(this):e=!1;e&&(a.preventDefault(),a.stopPropagation())},_doKeyPress:function(b){var e=d.datepicker._getInst(b.target);if(d.datepicker._get(e,"constrainInput")){var e=d.datepicker._possibleChars(d.datepicker._get(e,"dateFormat")),f=String.fromCharCode(b.charCode==a?b.keyCode:b.charCode);return b.ctrlKey||b.metaKey||f<" "||!e||e.indexOf(f)>-1}},_doKeyUp:function(a){a=d.datepicker._getInst(a.target);
if(a.input.val()!=a.lastVal)try{if(d.datepicker.parseDate(d.datepicker._get(a,"dateFormat"),a.input?a.input.val():null,d.datepicker._getFormatConfig(a)))d.datepicker._setDateFromField(a),d.datepicker._updateAlternate(a),d.datepicker._updateDatepicker(a)}catch(b){d.datepicker.log(b)}return!0},_showDatepicker:function(a){a=a.target||a;a.nodeName.toLowerCase()!="input"&&(a=d("input",a.parentNode)[0]);if(!(d.datepicker._isDisabledDatepicker(a)||d.datepicker._lastInput==a)){var b=d.datepicker._getInst(a);
d.datepicker._curInst&&d.datepicker._curInst!=b&&(d.datepicker._datepickerShowing&&d.datepicker._triggerOnClose(d.datepicker._curInst),d.datepicker._curInst.dpDiv.stop(!0,!0));var e=d.datepicker._get(b,"beforeShow"),e=e?e.apply(a,[a,b]):{};if(e!==!1){f(b.settings,e);b.lastVal=null;d.datepicker._lastInput=a;d.datepicker._setDateFromField(b);if(d.datepicker._inDialog)a.value="";if(!d.datepicker._pos)d.datepicker._pos=d.datepicker._findPos(a),d.datepicker._pos[1]+=a.offsetHeight;var h=!1;d(a).parents().each(function(){h|=
d(this).css("position")=="fixed";return!h});h&&d.browser.opera&&(d.datepicker._pos[0]-=document.documentElement.scrollLeft,d.datepicker._pos[1]-=document.documentElement.scrollTop);e={left:d.datepicker._pos[0],top:d.datepicker._pos[1]};d.datepicker._pos=null;b.dpDiv.empty();b.dpDiv.css({position:"absolute",display:"block",top:"-1000px"});d.datepicker._updateDatepicker(b);e=d.datepicker._checkOffset(b,e,h);b.dpDiv.css({position:d.datepicker._inDialog&&d.blockUI?"static":h?"fixed":"absolute",display:"none",
left:e.left+"px",top:e.top+"px"});if(!b.inline){var e=d.datepicker._get(b,"showAnim"),g=d.datepicker._get(b,"duration"),o=function(){var a=b.dpDiv.find("iframe.ui-datepicker-cover");if(a.length){var e=d.datepicker._getBorders(b.dpDiv);a.css({left:-e[0],top:-e[1],width:b.dpDiv.outerWidth(),height:b.dpDiv.outerHeight()})}};b.dpDiv.zIndex(d(a).zIndex()+1);d.datepicker._datepickerShowing=!0;if(d.effects&&d.effects[e])b.dpDiv.show(e,d.datepicker._get(b,"showOptions"),g,o);else b.dpDiv[e||"show"](e?g:null,
o);(!e||!g)&&o();b.input.is(":visible")&&!b.input.is(":disabled")&&b.input.focus();d.datepicker._curInst=b}}}},_updateDatepicker:function(a){this.maxRows=4;var b=d.datepicker._getBorders(a.dpDiv);g=a;a.dpDiv.empty().append(this._generateHTML(a));var e=a.dpDiv.find("iframe.ui-datepicker-cover");e.length&&e.css({left:-b[0],top:-b[1],width:a.dpDiv.outerWidth(),height:a.dpDiv.outerHeight()});a.dpDiv.find("."+this._dayOverClass+" a").mouseover();b=this._getNumberOfMonths(a);e=b[1];a.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width("");
e>1&&a.dpDiv.addClass("ui-datepicker-multi-"+e).css("width",17*e+"em");a.dpDiv[(b[0]!=1||b[1]!=1?"add":"remove")+"Class"]("ui-datepicker-multi");a.dpDiv[(this._get(a,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl");a==d.datepicker._curInst&&d.datepicker._datepickerShowing&&a.input&&a.input.is(":visible")&&!a.input.is(":disabled")&&a.input[0]!=document.activeElement&&a.input.focus();if(a.yearshtml){var f=a.yearshtml;setTimeout(function(){f===a.yearshtml&&a.yearshtml&&a.dpDiv.find("select.ui-datepicker-year:first").replaceWith(a.yearshtml);
f=a.yearshtml=null},0)}},_getBorders:function(a){var d=function(a){return{thin:1,medium:2,thick:3}[a]||a};return[parseFloat(d(a.css("border-left-width"))),parseFloat(d(a.css("border-top-width")))]},_checkOffset:function(a,b,e){var f=a.dpDiv.outerWidth(),h=a.dpDiv.outerHeight(),g=a.input?a.input.outerWidth():0,p=a.input?a.input.outerHeight():0,n=document.documentElement.clientWidth+d(document).scrollLeft(),r=document.documentElement.clientHeight+d(document).scrollTop();b.left-=this._get(a,"isRTL")?
f-g:0;b.left-=e&&b.left==a.input.offset().left?d(document).scrollLeft():0;b.top-=e&&b.top==a.input.offset().top+p?d(document).scrollTop():0;b.left-=Math.min(b.left,b.left+f>n&&n>f?Math.abs(b.left+f-n):0);b.top-=Math.min(b.top,b.top+h>r&&r>h?Math.abs(h+p):0);return b},_findPos:function(a){for(var b=this._get(this._getInst(a),"isRTL");a&&(a.type=="hidden"||a.nodeType!=1||d.expr.filters.hidden(a));)a=a[b?"previousSibling":"nextSibling"];a=d(a).offset();return[a.left,a.top]},_triggerOnClose:function(a){var d=
this._get(a,"onClose");d&&d.apply(a.input?a.input[0]:null,[a.input?a.input.val():"",a])},_hideDatepicker:function(a){var b=this._curInst;if(b&&!(a&&b!=d.data(a,"datepicker"))&&this._datepickerShowing){var a=this._get(b,"showAnim"),e=this._get(b,"duration"),f=function(){d.datepicker._tidyDialog(b);this._curInst=null};if(d.effects&&d.effects[a])b.dpDiv.hide(a,d.datepicker._get(b,"showOptions"),e,f);else b.dpDiv[a=="slideDown"?"slideUp":a=="fadeIn"?"fadeOut":"hide"](a?e:null,f);a||f();d.datepicker._triggerOnClose(b);
this._datepickerShowing=!1;this._lastInput=null;this._inDialog&&(this._dialogInput.css({position:"absolute",left:"0",top:"-100px"}),d.blockUI&&(d.unblockUI(),d("body").append(this.dpDiv)));this._inDialog=!1}},_tidyDialog:function(a){a.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(a){d.datepicker._curInst&&(a=d(a.target),a[0].id!=d.datepicker._mainDivId&&a.parents("#"+d.datepicker._mainDivId).length==0&&!a.hasClass(d.datepicker.markerClassName)&&
!a.hasClass(d.datepicker._triggerClass)&&d.datepicker._datepickerShowing&&(!d.datepicker._inDialog||!d.blockUI)&&d.datepicker._hideDatepicker())},_adjustDate:function(a,b,e){var a=d(a),f=this._getInst(a[0]);this._isDisabledDatepicker(a[0])||(this._adjustInstDate(f,b+(e=="M"?this._get(f,"showCurrentAtPos"):0),e),this._updateDatepicker(f))},_gotoToday:function(a){var a=d(a),b=this._getInst(a[0]);if(this._get(b,"gotoCurrent")&&b.currentDay)b.selectedDay=b.currentDay,b.drawMonth=b.selectedMonth=b.currentMonth,
b.drawYear=b.selectedYear=b.currentYear;else{var e=new Date;b.selectedDay=e.getDate();b.drawMonth=b.selectedMonth=e.getMonth();b.drawYear=b.selectedYear=e.getFullYear()}this._notifyChange(b);this._adjustDate(a)},_selectMonthYear:function(a,b,e){var a=d(a),f=this._getInst(a[0]);f["selected"+(e=="M"?"Month":"Year")]=f["draw"+(e=="M"?"Month":"Year")]=parseInt(b.options[b.selectedIndex].value,10);this._notifyChange(f);this._adjustDate(a)},_selectDay:function(a,b,e,f){var h=d(a);if(!d(f).hasClass(this._unselectableClass)&&
!this._isDisabledDatepicker(h[0]))h=this._getInst(h[0]),h.selectedDay=h.currentDay=d("a",f).html(),h.selectedMonth=h.currentMonth=b,h.selectedYear=h.currentYear=e,this._selectDate(a,this._formatDate(h,h.currentDay,h.currentMonth,h.currentYear))},_clearDate:function(a){a=d(a);this._getInst(a[0]);this._selectDate(a,"")},_selectDate:function(a,b){var e=this._getInst(d(a)[0]),b=b!=null?b:this._formatDate(e);e.input&&e.input.val(b);this._updateAlternate(e);var f=this._get(e,"onSelect");f?f.apply(e.input?
e.input[0]:null,[b,e]):e.input&&e.input.trigger("change");e.inline?this._updateDatepicker(e):(this._hideDatepicker(),this._lastInput=e.input[0],typeof e.input[0]!="object"&&e.input.focus(),this._lastInput=null)},_updateAlternate:function(a){var b=this._get(a,"altField");if(b){var e=this._get(a,"altFormat")||this._get(a,"dateFormat"),f=this._getDate(a),h=this.formatDate(e,f,this._getFormatConfig(a));d(b).each(function(){d(this).val(h)})}},noWeekends:function(a){a=a.getDay();return[a>0&&a<6,""]},iso8601Week:function(a){a=
new Date(a.getTime());a.setDate(a.getDate()+4-(a.getDay()||7));var d=a.getTime();a.setMonth(0);a.setDate(1);return Math.floor(Math.round((d-a)/864E5)/7)+1},parseDate:function(a,b,e){if(a==null||b==null)throw"Invalid arguments";b=typeof b=="object"?b.toString():b+"";if(b=="")return null;for(var f=(e?e.shortYearCutoff:null)||this._defaults.shortYearCutoff,f=typeof f!="string"?f:(new Date).getFullYear()%100+parseInt(f,10),h=(e?e.dayNamesShort:null)||this._defaults.dayNamesShort,g=(e?e.dayNames:null)||
this._defaults.dayNames,p=(e?e.monthNamesShort:null)||this._defaults.monthNamesShort,n=(e?e.monthNames:null)||this._defaults.monthNames,r=e=-1,u=-1,x=-1,q=!1,w=function(d){(d=F+1<a.length&&a.charAt(F+1)==d)&&F++;return d},s=function(a){var d=w(a),a=b.substring(C).match(RegExp("^\\d{1,"+(a=="@"?14:a=="!"?20:a=="y"&&d?4:a=="o"?3:2)+"}"));if(!a)throw"Missing number at position "+C;C+=a[0].length;return parseInt(a[0],10)},v=function(a,e,f){var a=d.map(w(a)?f:e,function(a,d){return[[d,a]]}).sort(function(a,
d){return-(a[1].length-d[1].length)}),i=-1;d.each(a,function(a,d){var e=d[1];if(b.substr(C,e.length).toLowerCase()==e.toLowerCase())return i=d[0],C+=e.length,!1});if(i!=-1)return i+1;else throw"Unknown name at position "+C;},z=function(){if(b.charAt(C)!=a.charAt(F))throw"Unexpected literal at position "+C;C++},C=0,F=0;F<a.length;F++)if(q)a.charAt(F)=="'"&&!w("'")?q=!1:z();else switch(a.charAt(F)){case "d":u=s("d");break;case "D":v("D",h,g);break;case "o":x=s("o");break;case "m":r=s("m");break;case "M":r=
v("M",p,n);break;case "y":e=s("y");break;case "@":var B=new Date(s("@")),e=B.getFullYear(),r=B.getMonth()+1,u=B.getDate();break;case "!":B=new Date((s("!")-this._ticksTo1970)/1E4);e=B.getFullYear();r=B.getMonth()+1;u=B.getDate();break;case "'":w("'")?z():q=!0;break;default:z()}if(C<b.length)throw"Extra/unparsed characters found in date: "+b.substring(C);e==-1?e=(new Date).getFullYear():e<100&&(e+=(new Date).getFullYear()-(new Date).getFullYear()%100+(e<=f?0:-100));if(x>-1){r=1;u=x;do{f=this._getDaysInMonth(e,
r-1);if(u<=f)break;r++;u-=f}while(1)}B=this._daylightSavingAdjust(new Date(e,r-1,u));if(B.getFullYear()!=e||B.getMonth()+1!=r||B.getDate()!=u)throw"Invalid date";return B},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:(718685+Math.floor(492.5)-Math.floor(19.7)+Math.floor(4.925))*864E9,formatDate:function(a,d,b){if(!d)return"";
var e=(b?b.dayNamesShort:null)||this._defaults.dayNamesShort,f=(b?b.dayNames:null)||this._defaults.dayNames,h=(b?b.monthNamesShort:null)||this._defaults.monthNamesShort,b=(b?b.monthNames:null)||this._defaults.monthNames,g=function(d){(d=q+1<a.length&&a.charAt(q+1)==d)&&q++;return d},n=function(a,d,b){d=""+d;if(g(a))for(;d.length<b;)d="0"+d;return d},r=function(a,d,b,e){return g(a)?e[d]:b[d]},u="",x=!1;if(d)for(var q=0;q<a.length;q++)if(x)a.charAt(q)=="'"&&!g("'")?x=!1:u+=a.charAt(q);else switch(a.charAt(q)){case "d":u+=
n("d",d.getDate(),2);break;case "D":u+=r("D",d.getDay(),e,f);break;case "o":u+=n("o",Math.round(((new Date(d.getFullYear(),d.getMonth(),d.getDate())).getTime()-(new Date(d.getFullYear(),0,0)).getTime())/864E5),3);break;case "m":u+=n("m",d.getMonth()+1,2);break;case "M":u+=r("M",d.getMonth(),h,b);break;case "y":u+=g("y")?d.getFullYear():(d.getYear()%100<10?"0":"")+d.getYear()%100;break;case "@":u+=d.getTime();break;case "!":u+=d.getTime()*1E4+this._ticksTo1970;break;case "'":g("'")?u+="'":x=!0;break;
default:u+=a.charAt(q)}return u},_possibleChars:function(a){for(var d="",b=!1,e=function(d){(d=f+1<a.length&&a.charAt(f+1)==d)&&f++;return d},f=0;f<a.length;f++)if(b)a.charAt(f)=="'"&&!e("'")?b=!1:d+=a.charAt(f);else switch(a.charAt(f)){case "d":case "m":case "y":case "@":d+="0123456789";break;case "D":case "M":return null;case "'":e("'")?d+="'":b=!0;break;default:d+=a.charAt(f)}return d},_get:function(d,b){return d.settings[b]!==a?d.settings[b]:this._defaults[b]},_setDateFromField:function(a,d){if(a.input.val()!=
a.lastVal){var b=this._get(a,"dateFormat"),e=a.lastVal=a.input?a.input.val():null,f,h;f=h=this._getDefaultDate(a);var g=this._getFormatConfig(a);try{f=this.parseDate(b,e,g)||h}catch(n){this.log(n),e=d?"":e}a.selectedDay=f.getDate();a.drawMonth=a.selectedMonth=f.getMonth();a.drawYear=a.selectedYear=f.getFullYear();a.currentDay=e?f.getDate():0;a.currentMonth=e?f.getMonth():0;a.currentYear=e?f.getFullYear():0;this._adjustInstDate(a)}},_getDefaultDate:function(a){return this._restrictMinMax(a,this._determineDate(a,
this._get(a,"defaultDate"),new Date))},_determineDate:function(a,b,e){var i;var f=function(a){var d=new Date;d.setDate(d.getDate()+a);return d};if(i=(b=b==null||b===""?e:typeof b=="string"?function(b){try{return d.datepicker.parseDate(d.datepicker._get(a,"dateFormat"),b,d.datepicker._getFormatConfig(a))}catch(e){}for(var f=(b.toLowerCase().match(/^c/)?d.datepicker._getDate(a):null)||new Date,h=f.getFullYear(),g=f.getMonth(),f=f.getDate(),j=/([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g,k=j.exec(b);k;){switch(k[2]||
"d"){case "d":case "D":f+=parseInt(k[1],10);break;case "w":case "W":f+=parseInt(k[1],10)*7;break;case "m":case "M":g+=parseInt(k[1],10);f=Math.min(f,d.datepicker._getDaysInMonth(h,g));break;case "y":case "Y":h+=parseInt(k[1],10),f=Math.min(f,d.datepicker._getDaysInMonth(h,g))}k=j.exec(b)}return new Date(h,g,f)}(b):typeof b=="number"?isNaN(b)?e:f(b):new Date(b.getTime()))&&b.toString()=="Invalid Date"?e:b,b=i)b.setHours(0),b.setMinutes(0),b.setSeconds(0),b.setMilliseconds(0);return this._daylightSavingAdjust(b)},
_daylightSavingAdjust:function(a){if(!a)return null;a.setHours(a.getHours()>12?a.getHours()+2:0);return a},_setDate:function(a,d,b){var e=!d,f=a.selectedMonth,h=a.selectedYear,d=this._restrictMinMax(a,this._determineDate(a,d,new Date));a.selectedDay=a.currentDay=d.getDate();a.drawMonth=a.selectedMonth=a.currentMonth=d.getMonth();a.drawYear=a.selectedYear=a.currentYear=d.getFullYear();(f!=a.selectedMonth||h!=a.selectedYear)&&!b&&this._notifyChange(a);this._adjustInstDate(a);a.input&&a.input.val(e?
"":this._formatDate(a))},_getDate:function(a){return!a.currentYear||a.input&&a.input.val()==""?null:this._daylightSavingAdjust(new Date(a.currentYear,a.currentMonth,a.currentDay))},_generateHTML:function(a){var b=new Date,b=this._daylightSavingAdjust(new Date(b.getFullYear(),b.getMonth(),b.getDate())),e=this._get(a,"isRTL"),f=this._get(a,"showButtonPanel"),g=this._get(a,"hideIfNoPrevNext"),o=this._get(a,"navigationAsDateFormat"),p=this._getNumberOfMonths(a),n=this._get(a,"showCurrentAtPos"),r=this._get(a,
"stepMonths"),u=p[0]!=1||p[1]!=1,x=this._daylightSavingAdjust(!a.currentDay?new Date(9999,9,9):new Date(a.currentYear,a.currentMonth,a.currentDay)),q=this._getMinMaxDate(a,"min"),w=this._getMinMaxDate(a,"max"),n=a.drawMonth-n,s=a.drawYear;n<0&&(n+=12,s--);if(w)for(var v=this._daylightSavingAdjust(new Date(w.getFullYear(),w.getMonth()-p[0]*p[1]+1,w.getDate())),v=q&&v<q?q:v;this._daylightSavingAdjust(new Date(s,n,1))>v;)n--,n<0&&(n=11,s--);a.drawMonth=n;a.drawYear=s;var v=this._get(a,"prevText"),v=
!o?v:this.formatDate(v,this._daylightSavingAdjust(new Date(s,n-r,1)),this._getFormatConfig(a)),v=this._canAdjustMonth(a,-1,s,n)?'<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery_'+h+".datepicker._adjustDate('#"+a.id+"', -"+r+", 'M');\" title=\""+v+'"><span class="ui-icon ui-icon-circle-triangle-'+(e?"e":"w")+'">'+v+"</span></a>":g?"":'<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+v+'"><span class="ui-icon ui-icon-circle-triangle-'+(e?"e":"w")+'">'+v+"</span></a>",
z=this._get(a,"nextText"),z=!o?z:this.formatDate(z,this._daylightSavingAdjust(new Date(s,n+r,1)),this._getFormatConfig(a)),g=this._canAdjustMonth(a,1,s,n)?'<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery_'+h+".datepicker._adjustDate('#"+a.id+"', +"+r+", 'M');\" title=\""+z+'"><span class="ui-icon ui-icon-circle-triangle-'+(e?"w":"e")+'">'+z+"</span></a>":g?"":'<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+z+'"><span class="ui-icon ui-icon-circle-triangle-'+
(e?"w":"e")+'">'+z+"</span></a>",r=this._get(a,"currentText"),z=this._get(a,"gotoCurrent")&&a.currentDay?x:b,r=!o?r:this.formatDate(r,z,this._getFormatConfig(a)),o=!a.inline?'<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery_'+h+'.datepicker._hideDatepicker();">'+this._get(a,"closeText")+"</button>":"",f=f?'<div class="ui-datepicker-buttonpane ui-widget-content">'+(e?o:"")+(this._isInRange(a,z)?'<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery_'+
h+".datepicker._gotoToday('#"+a.id+"');\">"+r+"</button>":"")+(e?"":o)+"</div>":"",o=parseInt(this._get(a,"firstDay"),10),o=isNaN(o)?0:o,r=this._get(a,"showWeek"),z=this._get(a,"dayNames");this._get(a,"dayNamesShort");var C=this._get(a,"dayNamesMin"),F=this._get(a,"monthNames"),B=this._get(a,"monthNamesShort"),N=this._get(a,"beforeShowDay"),K=this._get(a,"showOtherMonths"),T=this._get(a,"selectOtherMonths");this._get(a,"calculateWeek");for(var O=this._getDefaultDate(a),L="",H=0;H<p[0];H++){var P=
"";this.maxRows=4;for(var I=0;I<p[1];I++){var Q=this._daylightSavingAdjust(new Date(s,n,a.selectedDay)),A=" ui-corner-all",D="";if(u){D+='<div class="ui-datepicker-group';if(p[1]>1)switch(I){case 0:D+=" ui-datepicker-group-first";A=" ui-corner-"+(e?"right":"left");break;case p[1]-1:D+=" ui-datepicker-group-last";A=" ui-corner-"+(e?"left":"right");break;default:D+=" ui-datepicker-group-middle",A=""}D+='">'}D+='<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix'+A+'">'+(/all|left/.test(A)&&
H==0?e?g:v:"")+(/all|right/.test(A)&&H==0?e?v:g:"")+this._generateMonthYearHeader(a,n,s,q,w,H>0||I>0,F,B)+'</div><table class="ui-datepicker-calendar"><thead><tr>';for(var E=r?'<th class="ui-datepicker-week-col">'+this._get(a,"weekHeader")+"</th>":"",A=0;A<7;A++){var y=(A+o)%7;E+="<th"+((A+o+6)%7>=5?' class="ui-datepicker-week-end"':"")+'><span title="'+z[y]+'">'+C[y]+"</span></th>"}D+=E+"</tr></thead><tbody>";E=this._getDaysInMonth(s,n);if(s==a.selectedYear&&n==a.selectedMonth)a.selectedDay=Math.min(a.selectedDay,
E);A=(this._getFirstDayOfMonth(s,n)-o+7)%7;E=Math.ceil((A+E)/7);this.maxRows=E=u?this.maxRows>E?this.maxRows:E:E;for(var y=this._daylightSavingAdjust(new Date(s,n,1-A)),R=0;R<E;R++){D+="<tr>";for(var S=!r?"":'<td class="ui-datepicker-week-col">'+this._get(a,"calculateWeek")(y)+"</td>",A=0;A<7;A++){var J=N?N.apply(a.input?a.input[0]:null,[y]):[!0,""],G=y.getMonth()!=n,M=G&&!T||!J[0]||q&&y<q||w&&y>w;S+='<td class="'+((A+o+6)%7>=5?" ui-datepicker-week-end":"")+(G?" ui-datepicker-other-month":"")+(y.getTime()==
Q.getTime()&&n==a.selectedMonth&&a._keyEvent||O.getTime()==y.getTime()&&O.getTime()==Q.getTime()?" "+this._dayOverClass:"")+(M?" "+this._unselectableClass+" ui-state-disabled":"")+(G&&!K?"":" "+J[1]+(y.getTime()==x.getTime()?" "+this._currentClass:"")+(y.getTime()==b.getTime()?" ui-datepicker-today":""))+'"'+((!G||K)&&J[2]?' title="'+J[2]+'"':"")+(M?"":' onclick="DP_jQuery_'+h+".datepicker._selectDay('#"+a.id+"',"+y.getMonth()+","+y.getFullYear()+', this);return false;"')+">"+(G&&!K?" ":M?'<span class="ui-state-default">'+
y.getDate()+"</span>":'<a class="ui-state-default'+(y.getTime()==b.getTime()?" ui-state-highlight":"")+(y.getTime()==x.getTime()?" ui-state-active":"")+(G?" ui-priority-secondary":"")+'" href="#">'+y.getDate()+"</a>")+"</td>";y.setDate(y.getDate()+1);y=this._daylightSavingAdjust(y)}D+=S+"</tr>"}n++;n>11&&(n=0,s++);D+="</tbody></table>"+(u?"</div>"+(p[0]>0&&I==p[1]-1?'<div class="ui-datepicker-row-break"></div>':""):"");P+=D}L+=P}L+=f+(d.browser.msie&&parseInt(d.browser.version,10)<7&&!a.inline?'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>':
"");a._keyEvent=!1;return L},_generateMonthYearHeader:function(a,d,b,e,f,g,p,n){var r=this._get(a,"changeMonth"),u=this._get(a,"changeYear"),x=this._get(a,"showMonthAfterYear"),q='<div class="ui-datepicker-title">',w="";if(g||!r)w+='<span class="ui-datepicker-month">'+p[d]+"</span>";else{var p=e&&e.getFullYear()==b,s=f&&f.getFullYear()==b;w+='<select class="ui-datepicker-month" onchange="DP_jQuery_'+h+".datepicker._selectMonthYear('#"+a.id+"', this, 'M');\" >";for(var v=0;v<12;v++)if((!p||v>=e.getMonth())&&
(!s||v<=f.getMonth()))w+='<option value="'+v+'"'+(v==d?' selected="selected"':"")+">"+n[v]+"</option>";w+="</select>"}x||(q+=w+(g||!r||!u?" ":""));if(!a.yearshtml)if(a.yearshtml="",g||!u)q+='<span class="ui-datepicker-year">'+b+"</span>";else{var n=this._get(a,"yearRange").split(":"),z=(new Date).getFullYear(),p=function(a){a=a.match(/c[+-].*/)?b+parseInt(a.substring(1),10):a.match(/[+-].*/)?z+parseInt(a,10):parseInt(a,10);return isNaN(a)?z:a},d=p(n[0]),n=Math.max(d,p(n[1]||"")),d=e?Math.max(d,
e.getFullYear()):d,n=f?Math.min(n,f.getFullYear()):n;for(a.yearshtml+='<select class="ui-datepicker-year" onchange="DP_jQuery_'+h+".datepicker._selectMonthYear('#"+a.id+"', this, 'Y');\" >";d<=n;d++)a.yearshtml+='<option value="'+d+'"'+(d==b?' selected="selected"':"")+">"+d+"</option>";a.yearshtml+="</select>";q+=a.yearshtml;a.yearshtml=null}q+=this._get(a,"yearSuffix");x&&(q+=(g||!r||!u?" ":"")+w);q+="</div>";return q},_adjustInstDate:function(a,d,b){var e=a.drawYear+(b=="Y"?d:0),f=a.drawMonth+
(b=="M"?d:0),d=Math.min(a.selectedDay,this._getDaysInMonth(e,f))+(b=="D"?d:0),e=this._restrictMinMax(a,this._daylightSavingAdjust(new Date(e,f,d)));a.selectedDay=e.getDate();a.drawMonth=a.selectedMonth=e.getMonth();a.drawYear=a.selectedYear=e.getFullYear();(b=="M"||b=="Y")&&this._notifyChange(a)},_restrictMinMax:function(a,d){var b=this._getMinMaxDate(a,"min"),e=this._getMinMaxDate(a,"max"),b=b&&d<b?b:d;return e&&b>e?e:b},_notifyChange:function(a){var d=this._get(a,"onChangeMonthYear");d&&d.apply(a.input?
a.input[0]:null,[a.selectedYear,a.selectedMonth+1,a])},_getNumberOfMonths:function(a){a=this._get(a,"numberOfMonths");return a==null?[1,1]:typeof a=="number"?[1,a]:a},_getMinMaxDate:function(a,d){return this._determineDate(a,this._get(a,d+"Date"),null)},_getDaysInMonth:function(a,d){return 32-this._daylightSavingAdjust(new Date(a,d,32)).getDate()},_getFirstDayOfMonth:function(a,d){return(new Date(a,d,1)).getDay()},_canAdjustMonth:function(a,d,b,e){var f=this._getNumberOfMonths(a),b=this._daylightSavingAdjust(new Date(b,
e+(d<0?d:f[0]*f[1]),1));d<0&&b.setDate(this._getDaysInMonth(b.getFullYear(),b.getMonth()));return this._isInRange(a,b)},_isInRange:function(a,d){var b=this._getMinMaxDate(a,"min"),e=this._getMinMaxDate(a,"max");return(!b||d.getTime()>=b.getTime())&&(!e||d.getTime()<=e.getTime())},_getFormatConfig:function(a){var d=this._get(a,"shortYearCutoff"),d=typeof d!="string"?d:(new Date).getFullYear()%100+parseInt(d,10);return{shortYearCutoff:d,dayNamesShort:this._get(a,"dayNamesShort"),dayNames:this._get(a,
"dayNames"),monthNamesShort:this._get(a,"monthNamesShort"),monthNames:this._get(a,"monthNames")}},_formatDate:function(a,d,b,e){if(!d)a.currentDay=a.selectedDay,a.currentMonth=a.selectedMonth,a.currentYear=a.selectedYear;d=d?typeof d=="object"?d:this._daylightSavingAdjust(new Date(e,b,d)):this._daylightSavingAdjust(new Date(a.currentYear,a.currentMonth,a.currentDay));return this.formatDate(this._get(a,"dateFormat"),d,this._getFormatConfig(a))}});d.fn.datepicker=function(a){if(!this.length)return this;
if(!d.datepicker.initialized)d(document).mousedown(d.datepicker._checkExternalClick).find("body").append(d.datepicker.dpDiv),d.datepicker.initialized=!0;var b=Array.prototype.slice.call(arguments,1);return typeof a=="string"&&(a=="isDisabled"||a=="getDate"||a=="widget")?d.datepicker["_"+a+"Datepicker"].apply(d.datepicker,[this[0]].concat(b)):a=="option"&&arguments.length==2&&typeof arguments[1]=="string"?d.datepicker["_"+a+"Datepicker"].apply(d.datepicker,[this[0]].concat(b)):this.each(function(){typeof a==
"string"?d.datepicker["_"+a+"Datepicker"].apply(d.datepicker,[this].concat(b)):d.datepicker._attachDatepicker(this,a)})};d.datepicker=new b;d.datepicker.initialized=!1;d.datepicker.uuid=(new Date).getTime();d.datepicker.version="1.8.16";window["DP_jQuery_"+h]=d})(jQuery);
(function(d,a){var b={buttons:!0,height:!0,maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0,width:!0},e={maxHeight:!0,maxWidth:!0,minHeight:!0,minWidth:!0},f=d.attrFn||{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0,click:!0};d.widget("ui.dialog",{options:{autoOpen:!0,buttons:{},closeOnEscape:!0,closeText:"close",dialogClass:"",draggable:!0,hide:null,height:"auto",maxHeight:!1,maxWidth:!1,minHeight:150,minWidth:150,modal:!1,position:{my:"center",at:"center",collision:"fit",using:function(a){var b=
d(this).css(a).offset().top;b<0&&d(this).css("top",a.top-b)}},resizable:!0,show:null,stack:!0,title:"",width:300,zIndex:1E3},_create:function(){this.originalTitle=this.element.attr("title");if(typeof this.originalTitle!=="string")this.originalTitle="";this.options.title=this.options.title||this.originalTitle;var a=this,b=a.options,e=b.title||" ",f=d.ui.dialog.getTitleId(a.element),k=(a.uiDialog=d("<div></div>")).appendTo(document.body).hide().addClass("ui-dialog ui-widget ui-widget-content ui-corner-all "+
b.dialogClass).css({zIndex:b.zIndex}).attr("tabIndex",-1).css("outline",0).keydown(function(e){b.closeOnEscape&&!e.isDefaultPrevented()&&e.keyCode&&e.keyCode===d.ui.keyCode.ESCAPE&&(a.close(e),e.preventDefault())}).attr({role:"dialog","aria-labelledby":f}).mousedown(function(d){a.moveToTop(!1,d)});a.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(k);var l=(a.uiDialogTitlebar=d("<div></div>")).addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(k),
m=d('<a href="#"></a>').addClass("ui-dialog-titlebar-close ui-corner-all").attr("role","button").hover(function(){m.addClass("ui-state-hover")},function(){m.removeClass("ui-state-hover")}).focus(function(){m.addClass("ui-state-focus")}).blur(function(){m.removeClass("ui-state-focus")}).click(function(d){a.close(d);return!1}).appendTo(l);(a.uiDialogTitlebarCloseText=d("<span></span>")).addClass("ui-icon ui-icon-closethick").text(b.closeText).appendTo(m);d("<span></span>").addClass("ui-dialog-title").attr("id",
f).html(e).prependTo(l);if(d.isFunction(b.beforeclose)&&!d.isFunction(b.beforeClose))b.beforeClose=b.beforeclose;l.find("*").add(l).disableSelection();b.draggable&&d.fn.draggable&&a._makeDraggable();b.resizable&&d.fn.resizable&&a._makeResizable();a._createButtons(b.buttons);a._isOpen=!1;d.fn.bgiframe&&k.bgiframe()},_init:function(){this.options.autoOpen&&this.open()},destroy:function(){this.overlay&&this.overlay.destroy();this.uiDialog.hide();this.element.unbind(".dialog").removeData("dialog").removeClass("ui-dialog-content ui-widget-content").hide().appendTo("body");
this.uiDialog.remove();this.originalTitle&&this.element.attr("title",this.originalTitle);return this},widget:function(){return this.uiDialog},close:function(a){var b=this,e,f;if(!1!==b._trigger("beforeClose",a)){b.overlay&&b.overlay.destroy();b.uiDialog.unbind("keypress.ui-dialog");b._isOpen=!1;b.options.hide?b.uiDialog.hide(b.options.hide,function(){b._trigger("close",a)}):(b.uiDialog.hide(),b._trigger("close",a));d.ui.dialog.overlay.resize();if(b.options.modal)e=0,d(".ui-dialog").each(function(){this!==
b.uiDialog[0]&&(f=d(this).css("z-index"),isNaN(f)||(e=Math.max(e,f)))}),d.ui.dialog.maxZ=e;return b}},isOpen:function(){return this._isOpen},moveToTop:function(a,b){var e=this.options;if(e.modal&&!a||!e.stack&&!e.modal)return this._trigger("focus",b);if(e.zIndex>d.ui.dialog.maxZ)d.ui.dialog.maxZ=e.zIndex;if(this.overlay)d.ui.dialog.maxZ+=1,this.overlay.$el.css("z-index",d.ui.dialog.overlay.maxZ=d.ui.dialog.maxZ);e={scrollTop:this.element.scrollTop(),scrollLeft:this.element.scrollLeft()};d.ui.dialog.maxZ+=
1;this.uiDialog.css("z-index",d.ui.dialog.maxZ);this.element.attr(e);this._trigger("focus",b);return this},open:function(){if(!this._isOpen){var a=this.options,b=this.uiDialog;this.overlay=a.modal?new d.ui.dialog.overlay(this):null;this._size();this._position(a.position);b.show(a.show);this.moveToTop(!0);a.modal&&b.bind("keypress.ui-dialog",function(a){if(a.keyCode===d.ui.keyCode.TAB){var b=d(":tabbable",this),e=b.filter(":first"),b=b.filter(":last");if(a.target===b[0]&&!a.shiftKey)return e.focus(1),
!1;else if(a.target===e[0]&&a.shiftKey)return b.focus(1),!1}});d(this.element.find(":tabbable").get().concat(b.find(".ui-dialog-buttonpane :tabbable").get().concat(b.get()))).eq(0).focus();this._isOpen=!0;this._trigger("open");return this}},_createButtons:function(a){var b=this,e=!1,j=d("<div></div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"),k=d("<div></div>").addClass("ui-dialog-buttonset").appendTo(j);b.uiDialog.find(".ui-dialog-buttonpane").remove();typeof a==="object"&&
a!==null&&d.each(a,function(){return!(e=!0)});e&&(d.each(a,function(a,e){var e=d.isFunction(e)?{click:e,text:a}:e,h=d('<button type="button"></button>').click(function(){e.click.apply(b.element[0],arguments)}).appendTo(k);d.each(e,function(a,d){if(a!=="click")if(a in f)h[a](d);else h.attr(a,d)});d.fn.button&&h.button()}),j.appendTo(b.uiDialog))},_makeDraggable:function(){function a(d){return{position:d.position,offset:d.offset}}var b=this,e=b.options,f=d(document),k;b.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",
handle:".ui-dialog-titlebar",containment:"document",start:function(f,m){k=e.height==="auto"?"auto":d(this).height();d(this).height(d(this).height()).addClass("ui-dialog-dragging");b._trigger("dragStart",f,a(m))},drag:function(d,e){b._trigger("drag",d,a(e))},stop:function(l,m){e.position=[m.position.left-f.scrollLeft(),m.position.top-f.scrollTop()];d(this).removeClass("ui-dialog-dragging").height(k);b._trigger("dragStop",l,a(m));d.ui.dialog.overlay.resize()}})},_makeResizable:function(b){function e(a){return{originalPosition:a.originalPosition,
originalSize:a.originalSize,position:a.position,size:a.size}}var b=b===a?this.options.resizable:b,f=this,j=f.options,k=f.uiDialog.css("position"),b=typeof b==="string"?b:"n,e,s,w,se,sw,ne,nw";f.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:f.element,maxWidth:j.maxWidth,maxHeight:j.maxHeight,minWidth:j.minWidth,minHeight:f._minHeight(),handles:b,start:function(a,b){d(this).addClass("ui-dialog-resizing");f._trigger("resizeStart",a,e(b))},resize:function(a,d){f._trigger("resize",
a,e(d))},stop:function(a,b){d(this).removeClass("ui-dialog-resizing");j.height=d(this).height();j.width=d(this).width();f._trigger("resizeStop",a,e(b));d.ui.dialog.overlay.resize()}}).css("position",k).find(".ui-resizable-se").addClass("ui-icon ui-icon-grip-diagonal-se")},_minHeight:function(){var a=this.options;return a.height==="auto"?a.minHeight:Math.min(a.minHeight,a.height)},_position:function(a){var b=[],e=[0,0],f;if(a){if(typeof a==="string"||typeof a==="object"&&"0"in a)b=a.split?a.split(" "):
[a[0],a[1]],b.length===1&&(b[1]=b[0]),d.each(["left","top"],function(a,d){+b[a]===b[a]&&(e[a]=b[a],b[a]=d)}),a={my:b.join(" "),at:b.join(" "),offset:e.join(" ")};a=d.extend({},d.ui.dialog.prototype.options.position,a)}else a=d.ui.dialog.prototype.options.position;(f=this.uiDialog.is(":visible"))||this.uiDialog.show();this.uiDialog.css({top:0,left:0}).position(d.extend({of:window},a));f||this.uiDialog.hide()},_setOptions:function(a){var f=this,i={},j=!1;d.each(a,function(a,d){f._setOption(a,d);a in
b&&(j=!0);a in e&&(i[a]=d)});j&&this._size();this.uiDialog.is(":data(resizable)")&&this.uiDialog.resizable("option",i)},_setOption:function(a,b){var e=this.uiDialog;switch(a){case "beforeclose":a="beforeClose";break;case "buttons":this._createButtons(b);break;case "closeText":this.uiDialogTitlebarCloseText.text(""+b);break;case "dialogClass":e.removeClass(this.options.dialogClass).addClass("ui-dialog ui-widget ui-widget-content ui-corner-all "+b);break;case "disabled":b?e.addClass("ui-dialog-disabled"):
e.removeClass("ui-dialog-disabled");break;case "draggable":var f=e.is(":data(draggable)");f&&!b&&e.draggable("destroy");!f&&b&&this._makeDraggable();break;case "position":this._position(b);break;case "resizable":(f=e.is(":data(resizable)"))&&!b&&e.resizable("destroy");f&&typeof b==="string"&&e.resizable("option","handles",b);!f&&b!==!1&&this._makeResizable(b);break;case "title":d(".ui-dialog-title",this.uiDialogTitlebar).html(""+(b||" "))}d.Widget.prototype._setOption.apply(this,arguments)},
_size:function(){var a=this.options,b,e,f=this.uiDialog.is(":visible");this.element.show().css({width:"auto",minHeight:0,height:0});if(a.minWidth>a.width)a.width=a.minWidth;b=this.uiDialog.css({height:"auto",width:a.width}).height();e=Math.max(0,a.minHeight-b);a.height==="auto"?d.support.minHeight?this.element.css({minHeight:e,height:"auto"}):(this.uiDialog.show(),a=this.element.css("height","auto").height(),f||this.uiDialog.hide(),this.element.height(Math.max(a,e))):this.element.height(Math.max(a.height-
b,0));this.uiDialog.is(":data(resizable)")&&this.uiDialog.resizable("option","minHeight",this._minHeight())}});d.extend(d.ui.dialog,{version:"1.8.16",uuid:0,maxZ:0,getTitleId:function(a){a=a.attr("id");if(!a)this.uuid+=1,a=this.uuid;return"ui-dialog-title-"+a},overlay:function(a){this.$el=d.ui.dialog.overlay.create(a)}});d.extend(d.ui.dialog.overlay,{instances:[],oldInstances:[],maxZ:0,events:d.map("focus,mousedown,mouseup,keydown,keypress,click".split(","),function(a){return a+".dialog-overlay"}).join(" "),
create:function(a){this.instances.length===0&&(setTimeout(function(){d.ui.dialog.overlay.instances.length&&d(document).bind(d.ui.dialog.overlay.events,function(a){if(d(a.target).zIndex()<d.ui.dialog.overlay.maxZ)return!1})},1),d(document).bind("keydown.dialog-overlay",function(b){a.options.closeOnEscape&&!b.isDefaultPrevented()&&b.keyCode&&b.keyCode===d.ui.keyCode.ESCAPE&&(a.close(b),b.preventDefault())}),d(window).bind("resize.dialog-overlay",d.ui.dialog.overlay.resize));var b=(this.oldInstances.pop()||
d("<div></div>").addClass("ui-widget-overlay")).appendTo(document.body).css({width:this.width(),height:this.height()});d.fn.bgiframe&&b.bgiframe();this.instances.push(b);return b},destroy:function(a){var b=d.inArray(a,this.instances);b!=-1&&this.oldInstances.push(this.instances.splice(b,1)[0]);this.instances.length===0&&d([document,window]).unbind(".dialog-overlay");a.remove();var e=0;d.each(this.instances,function(){e=Math.max(e,this.css("z-index"))});this.maxZ=e},height:function(){var a,b;return d.browser.msie&&
d.browser.version<7?(a=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight),b=Math.max(document.documentElement.offsetHeight,document.body.offsetHeight),a<b?d(window).height()+"px":a+"px"):d(document).height()+"px"},width:function(){var a,b;return d.browser.msie?(a=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth),b=Math.max(document.documentElement.offsetWidth,document.body.offsetWidth),a<b?d(window).width()+"px":a+"px"):d(document).width()+"px"},resize:function(){var a=
d([]);d.each(d.ui.dialog.overlay.instances,function(){a=a.add(this)});a.css({width:0,height:0}).css({width:d.ui.dialog.overlay.width(),height:d.ui.dialog.overlay.height()})}});d.extend(d.ui.dialog.overlay.prototype,{destroy:function(){d.ui.dialog.overlay.destroy(this.$el)}})})(jQuery);
(function(d){d.widget("ui.draggable",d.ui.mouse,{widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1},_create:function(){if(this.options.helper=="original"&&!/^(?:r|a|f)/.test(this.element.css("position")))this.element[0].style.position=
"relative";this.options.addClasses&&this.element.addClass("ui-draggable");this.options.disabled&&this.element.addClass("ui-draggable-disabled");this._mouseInit()},destroy:function(){if(this.element.data("draggable"))return this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._mouseDestroy(),this},_mouseCapture:function(a){var b=this.options;if(this.helper||b.disabled||d(a.target).is(".ui-resizable-handle"))return!1;
this.handle=this._getHandle(a);if(!this.handle)return!1;b.iframeFix&&d(b.iframeFix===!0?"iframe":b.iframeFix).each(function(){d('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1E3}).css(d(this).offset()).appendTo("body")});return!0},_mouseStart:function(a){var b=this.options;this.helper=this._createHelper(a);this._cacheHelperProportions();if(d.ui.ddmanager)d.ui.ddmanager.current=
this;this._cacheMargins();this.cssPosition=this.helper.css("position");this.scrollParent=this.helper.scrollParent();this.offset=this.positionAbs=this.element.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};d.extend(this.offset,{click:{left:a.pageX-this.offset.left,top:a.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this.position=this._generatePosition(a);this.originalPageX=a.pageX;
this.originalPageY=a.pageY;b.cursorAt&&this._adjustOffsetFromHelper(b.cursorAt);b.containment&&this._setContainment();if(this._trigger("start",a)===!1)return this._clear(),!1;this._cacheHelperProportions();d.ui.ddmanager&&!b.dropBehaviour&&d.ui.ddmanager.prepareOffsets(this,a);this.helper.addClass("ui-draggable-dragging");this._mouseDrag(a,!0);d.ui.ddmanager&&d.ui.ddmanager.dragStart(this,a);return!0},_mouseDrag:function(a,b){this.position=this._generatePosition(a);this.positionAbs=this._convertPositionTo("absolute");
if(!b){var e=this._uiHash();if(this._trigger("drag",a,e)===!1)return this._mouseUp({}),!1;this.position=e.position}if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=this.position.left+"px";if(!this.options.axis||this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";d.ui.ddmanager&&d.ui.ddmanager.drag(this,a);return!1},_mouseStop:function(a){var b=!1;d.ui.ddmanager&&!this.options.dropBehaviour&&(b=d.ui.ddmanager.drop(this,a));if(this.dropped)b=this.dropped,this.dropped=
!1;if((!this.element[0]||!this.element[0].parentNode)&&this.options.helper=="original")return!1;if(this.options.revert=="invalid"&&!b||this.options.revert=="valid"&&b||this.options.revert===!0||d.isFunction(this.options.revert)&&this.options.revert.call(this.element,b)){var e=this;d(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){e._trigger("stop",a)!==!1&&e._clear()})}else this._trigger("stop",a)!==!1&&this._clear();return!1},_mouseUp:function(a){this.options.iframeFix===
!0&&d("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)});d.ui.ddmanager&&d.ui.ddmanager.dragStop(this,a);return d.ui.mouse.prototype._mouseUp.call(this,a)},cancel:function(){this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear();return this},_getHandle:function(a){var b=!this.options.handle||!d(this.options.handle,this.element).length?!0:!1;d(this.options.handle,this.element).find("*").andSelf().each(function(){this==a.target&&(b=!0)});return b},_createHelper:function(a){var b=
this.options,a=d.isFunction(b.helper)?d(b.helper.apply(this.element[0],[a])):b.helper=="clone"?this.element.clone().removeAttr("id"):this.element;a.parents("body").length||a.appendTo(b.appendTo=="parent"?this.element[0].parentNode:b.appendTo);a[0]!=this.element[0]&&!/(fixed|absolute)/.test(a.css("position"))&&a.css("position","absolute");return a},_adjustOffsetFromHelper:function(a){typeof a=="string"&&(a=a.split(" "));d.isArray(a)&&(a={left:+a[0],top:+a[1]||0});if("left"in a)this.offset.click.left=
a.left+this.margins.left;if("right"in a)this.offset.click.left=this.helperProportions.width-a.right+this.margins.left;if("top"in a)this.offset.click.top=a.top+this.margins.top;if("bottom"in a)this.offset.click.top=this.helperProportions.height-a.bottom+this.margins.top},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var a=this.offsetParent.offset();this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],this.offsetParent[0])&&(a.left+=
this.scrollParent.scrollLeft(),a.top+=this.scrollParent.scrollTop());if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&d.browser.msie)a={top:0,left:0};return{top:a.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:a.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var a=this.element.position();return{top:a.top-(parseInt(this.helper.css("top"),
10)||0)+this.scrollParent.scrollTop(),left:a.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},
_setContainment:function(){var a=this.options;if(a.containment=="parent")a.containment=this.helper[0].parentNode;if(a.containment=="document"||a.containment=="window")this.containment=[a.containment=="document"?0:d(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,a.containment=="document"?0:d(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,(a.containment=="document"?0:d(window).scrollLeft())+d(a.containment=="document"?document:window).width()-this.helperProportions.width-
this.margins.left,(a.containment=="document"?0:d(window).scrollTop())+(d(a.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(a.containment)&&a.containment.constructor!=Array){var a=d(a.containment),b=a[0];if(b){a.offset();var e=d(b).css("overflow")!="hidden";this.containment=[(parseInt(d(b).css("borderLeftWidth"),10)||0)+(parseInt(d(b).css("paddingLeft"),10)||0),(parseInt(d(b).css("borderTopWidth"),
10)||0)+(parseInt(d(b).css("paddingTop"),10)||0),(e?Math.max(b.scrollWidth,b.offsetWidth):b.offsetWidth)-(parseInt(d(b).css("borderLeftWidth"),10)||0)-(parseInt(d(b).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(e?Math.max(b.scrollHeight,b.offsetHeight):b.offsetHeight)-(parseInt(d(b).css("borderTopWidth"),10)||0)-(parseInt(d(b).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom];this.relative_container=a}}else if(a.containment.constructor==
Array)this.containment=a.containment},_convertPositionTo:function(a,b){if(!b)b=this.position;var e=a=="absolute"?1:-1,f=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,h=/(html|body)/i.test(f[0].tagName);return{top:b.top+this.offset.relative.top*e+this.offset.parent.top*e-(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():
h?0:f.scrollTop())*e),left:b.left+this.offset.relative.left*e+this.offset.parent.left*e-(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():h?0:f.scrollLeft())*e)}},_generatePosition:function(a){var b=this.options,e=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,f=/(html|body)/i.test(e[0].tagName),h=a.pageX,g=a.pageY;
if(this.originalPosition){var i;if(this.containment)this.relative_container?(i=this.relative_container.offset(),i=[this.containment[0]+i.left,this.containment[1]+i.top,this.containment[2]+i.left,this.containment[3]+i.top]):i=this.containment,a.pageX-this.offset.click.left<i[0]&&(h=i[0]+this.offset.click.left),a.pageY-this.offset.click.top<i[1]&&(g=i[1]+this.offset.click.top),a.pageX-this.offset.click.left>i[2]&&(h=i[2]+this.offset.click.left),a.pageY-this.offset.click.top>i[3]&&(g=i[3]+this.offset.click.top);
b.grid&&(g=b.grid[1]?this.originalPageY+Math.round((g-this.originalPageY)/b.grid[1])*b.grid[1]:this.originalPageY,g=i?!(g-this.offset.click.top<i[1]||g-this.offset.click.top>i[3])?g:!(g-this.offset.click.top<i[1])?g-b.grid[1]:g+b.grid[1]:g,h=b.grid[0]?this.originalPageX+Math.round((h-this.originalPageX)/b.grid[0])*b.grid[0]:this.originalPageX,h=i?!(h-this.offset.click.left<i[0]||h-this.offset.click.left>i[2])?h:!(h-this.offset.click.left<i[0])?h-b.grid[0]:h+b.grid[0]:h)}return{top:g-this.offset.click.top-
this.offset.relative.top-this.offset.parent.top+(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollTop():f?0:e.scrollTop()),left:h-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(d.browser.safari&&d.browser.version<526&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():f?0:e.scrollLeft())}},_clear:function(){this.helper.removeClass("ui-draggable-dragging");this.helper[0]!=
this.element[0]&&!this.cancelHelperRemoval&&this.helper.remove();this.helper=null;this.cancelHelperRemoval=!1},_trigger:function(a,b,e){e=e||this._uiHash();d.ui.plugin.call(this,a,[b,e]);if(a=="drag")this.positionAbs=this._convertPositionTo("absolute");return d.Widget.prototype._trigger.call(this,a,b,e)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}});d.extend(d.ui.draggable,{version:"1.8.16"});d.ui.plugin.add("draggable",
"connectToSortable",{start:function(a,b){var e=d(this).data("draggable"),f=e.options,h=d.extend({},b,{item:e.element});e.sortables=[];d(f.connectToSortable).each(function(){var b=d.data(this,"sortable");b&&!b.options.disabled&&(e.sortables.push({instance:b,shouldRevert:b.options.revert}),b.refreshPositions(),b._trigger("activate",a,h))})},stop:function(a,b){var e=d(this).data("draggable"),f=d.extend({},b,{item:e.element});d.each(e.sortables,function(){if(this.instance.isOver){this.instance.isOver=
0;e.cancelHelperRemoval=!0;this.instance.cancelHelperRemoval=!1;if(this.shouldRevert)this.instance.options.revert=!0;this.instance._mouseStop(a);this.instance.options.helper=this.instance.options._helper;e.options.helper=="original"&&this.instance.currentItem.css({top:"auto",left:"auto"})}else this.instance.cancelHelperRemoval=!1,this.instance._trigger("deactivate",a,f)})},drag:function(a,b){var e=d(this).data("draggable"),f=this;d.each(e.sortables,function(){this.instance.positionAbs=e.positionAbs;
this.instance.helperProportions=e.helperProportions;this.instance.offset.click=e.offset.click;if(this.instance._intersectsWith(this.instance.containerCache)){if(!this.instance.isOver)this.instance.isOver=1,this.instance.currentItem=d(f).clone().removeAttr("id").appendTo(this.instance.element).data("sortable-item",!0),this.instance.options._helper=this.instance.options.helper,this.instance.options.helper=function(){return b.helper[0]},a.target=this.instance.currentItem[0],this.instance._mouseCapture(a,
!0),this.instance._mouseStart(a,!0,!0),this.instance.offset.click.top=e.offset.click.top,this.instance.offset.click.left=e.offset.click.left,this.instance.offset.parent.left-=e.offset.parent.left-this.instance.offset.parent.left,this.instance.offset.parent.top-=e.offset.parent.top-this.instance.offset.parent.top,e._trigger("toSortable",a),e.dropped=this.instance.element,e.currentItem=e.element,this.instance.fromOutside=e;this.instance.currentItem&&this.instance._mouseDrag(a)}else if(this.instance.isOver)this.instance.isOver=
0,this.instance.cancelHelperRemoval=!0,this.instance.options.revert=!1,this.instance._trigger("out",a,this.instance._uiHash(this.instance)),this.instance._mouseStop(a,!0),this.instance.options.helper=this.instance.options._helper,this.instance.currentItem.remove(),this.instance.placeholder&&this.instance.placeholder.remove(),e._trigger("fromSortable",a),e.dropped=!1})}});d.ui.plugin.add("draggable","cursor",{start:function(){var a=d("body"),b=d(this).data("draggable").options;if(a.css("cursor"))b._cursor=
a.css("cursor");a.css("cursor",b.cursor)},stop:function(){var a=d(this).data("draggable").options;a._cursor&&d("body").css("cursor",a._cursor)}});d.ui.plugin.add("draggable","opacity",{start:function(a,b){var e=d(b.helper),f=d(this).data("draggable").options;if(e.css("opacity"))f._opacity=e.css("opacity");e.css("opacity",f.opacity)},stop:function(a,b){var e=d(this).data("draggable").options;e._opacity&&d(b.helper).css("opacity",e._opacity)}});d.ui.plugin.add("draggable","scroll",{start:function(){var a=
d(this).data("draggable");if(a.scrollParent[0]!=document&&a.scrollParent[0].tagName!="HTML")a.overflowOffset=a.scrollParent.offset()},drag:function(a){var b=d(this).data("draggable"),e=b.options,f=!1;if(b.scrollParent[0]!=document&&b.scrollParent[0].tagName!="HTML"){if(!e.axis||e.axis!="x")if(b.overflowOffset.top+b.scrollParent[0].offsetHeight-a.pageY<e.scrollSensitivity)b.scrollParent[0].scrollTop=f=b.scrollParent[0].scrollTop+e.scrollSpeed;else if(a.pageY-b.overflowOffset.top<e.scrollSensitivity)b.scrollParent[0].scrollTop=
f=b.scrollParent[0].scrollTop-e.scrollSpeed;if(!e.axis||e.axis!="y")if(b.overflowOffset.left+b.scrollParent[0].offsetWidth-a.pageX<e.scrollSensitivity)b.scrollParent[0].scrollLeft=f=b.scrollParent[0].scrollLeft+e.scrollSpeed;else if(a.pageX-b.overflowOffset.left<e.scrollSensitivity)b.scrollParent[0].scrollLeft=f=b.scrollParent[0].scrollLeft-e.scrollSpeed}else{if(!e.axis||e.axis!="x")a.pageY-d(document).scrollTop()<e.scrollSensitivity?f=d(document).scrollTop(d(document).scrollTop()-e.scrollSpeed):
d(window).height()-(a.pageY-d(document).scrollTop())<e.scrollSensitivity&&(f=d(document).scrollTop(d(document).scrollTop()+e.scrollSpeed));if(!e.axis||e.axis!="y")a.pageX-d(document).scrollLeft()<e.scrollSensitivity?f=d(document).scrollLeft(d(document).scrollLeft()-e.scrollSpeed):d(window).width()-(a.pageX-d(document).scrollLeft())<e.scrollSensitivity&&(f=d(document).scrollLeft(d(document).scrollLeft()+e.scrollSpeed))}f!==!1&&d.ui.ddmanager&&!e.dropBehaviour&&d.ui.ddmanager.prepareOffsets(b,a)}});
d.ui.plugin.add("draggable","snap",{start:function(){var a=d(this).data("draggable"),b=a.options;a.snapElements=[];d(b.snap.constructor!=String?b.snap.items||":data(draggable)":b.snap).each(function(){var b=d(this),f=b.offset();this!=a.element[0]&&a.snapElements.push({item:this,width:b.outerWidth(),height:b.outerHeight(),top:f.top,left:f.left})})},drag:function(a,b){for(var e=d(this).data("draggable"),f=e.options,h=f.snapTolerance,g=b.offset.left,i=g+e.helperProportions.width,j=b.offset.top,k=j+e.helperProportions.height,
l=e.snapElements.length-1;l>=0;l--){var m=e.snapElements[l].left,o=m+e.snapElements[l].width,p=e.snapElements[l].top,n=p+e.snapElements[l].height;if(m-h<g&&g<o+h&&p-h<j&&j<n+h||m-h<g&&g<o+h&&p-h<k&&k<n+h||m-h<i&&i<o+h&&p-h<j&&j<n+h||m-h<i&&i<o+h&&p-h<k&&k<n+h){if(f.snapMode!="inner"){var r=Math.abs(p-k)<=h,u=Math.abs(n-j)<=h,x=Math.abs(m-i)<=h,q=Math.abs(o-g)<=h;if(r)b.position.top=e._convertPositionTo("relative",{top:p-e.helperProportions.height,left:0}).top-e.margins.top;if(u)b.position.top=e._convertPositionTo("relative",
{top:n,left:0}).top-e.margins.top;if(x)b.position.left=e._convertPositionTo("relative",{top:0,left:m-e.helperProportions.width}).left-e.margins.left;if(q)b.position.left=e._convertPositionTo("relative",{top:0,left:o}).left-e.margins.left}var w=r||u||x||q;if(f.snapMode!="outer"){r=Math.abs(p-j)<=h;u=Math.abs(n-k)<=h;x=Math.abs(m-g)<=h;q=Math.abs(o-i)<=h;if(r)b.position.top=e._convertPositionTo("relative",{top:p,left:0}).top-e.margins.top;if(u)b.position.top=e._convertPositionTo("relative",{top:n-e.helperProportions.height,
left:0}).top-e.margins.top;if(x)b.position.left=e._convertPositionTo("relative",{top:0,left:m}).left-e.margins.left;if(q)b.position.left=e._convertPositionTo("relative",{top:0,left:o-e.helperProportions.width}).left-e.margins.left}!e.snapElements[l].snapping&&(r||u||x||q||w)&&e.options.snap.snap&&e.options.snap.snap.call(e.element,a,d.extend(e._uiHash(),{snapItem:e.snapElements[l].item}));e.snapElements[l].snapping=r||u||x||q||w}else e.snapElements[l].snapping&&e.options.snap.release&&e.options.snap.release.call(e.element,
a,d.extend(e._uiHash(),{snapItem:e.snapElements[l].item})),e.snapElements[l].snapping=!1}}});d.ui.plugin.add("draggable","stack",{start:function(){var a=d(this).data("draggable").options,a=d.makeArray(d(a.stack)).sort(function(a,b){return(parseInt(d(a).css("zIndex"),10)||0)-(parseInt(d(b).css("zIndex"),10)||0)});if(a.length){var b=parseInt(a[0].style.zIndex)||0;d(a).each(function(a){this.style.zIndex=b+a});this[0].style.zIndex=b+a.length}}});d.ui.plugin.add("draggable","zIndex",{start:function(a,
b){var e=d(b.helper),f=d(this).data("draggable").options;if(e.css("zIndex"))f._zIndex=e.css("zIndex");e.css("zIndex",f.zIndex)},stop:function(a,b){var e=d(this).data("draggable").options;e._zIndex&&d(b.helper).css("zIndex",e._zIndex)}})})(jQuery);
(function(d){d.widget("ui.droppable",{widgetEventPrefix:"drop",options:{accept:"*",activeClass:!1,addClasses:!0,greedy:!1,hoverClass:!1,scope:"default",tolerance:"intersect"},_create:function(){var a=this.options,b=a.accept;this.isover=0;this.isout=1;this.accept=d.isFunction(b)?b:function(a){return a.is(b)};this.proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight};d.ui.ddmanager.droppables[a.scope]=d.ui.ddmanager.droppables[a.scope]||[];d.ui.ddmanager.droppables[a.scope].push(this);
a.addClasses&&this.element.addClass("ui-droppable")},destroy:function(){for(var a=d.ui.ddmanager.droppables[this.options.scope],b=0;b<a.length;b++)a[b]==this&&a.splice(b,1);this.element.removeClass("ui-droppable ui-droppable-disabled").removeData("droppable").unbind(".droppable");return this},_setOption:function(a,b){if(a=="accept")this.accept=d.isFunction(b)?b:function(a){return a.is(b)};d.Widget.prototype._setOption.apply(this,arguments)},_activate:function(a){var b=d.ui.ddmanager.current;this.options.activeClass&&
this.element.addClass(this.options.activeClass);b&&this._trigger("activate",a,this.ui(b))},_deactivate:function(a){var b=d.ui.ddmanager.current;this.options.activeClass&&this.element.removeClass(this.options.activeClass);b&&this._trigger("deactivate",a,this.ui(b))},_over:function(a){var b=d.ui.ddmanager.current;if(b&&(b.currentItem||b.element)[0]!=this.element[0])if(this.accept.call(this.element[0],b.currentItem||b.element))this.options.hoverClass&&this.element.addClass(this.options.hoverClass),this._trigger("over",
a,this.ui(b))},_out:function(a){var b=d.ui.ddmanager.current;if(b&&(b.currentItem||b.element)[0]!=this.element[0])if(this.accept.call(this.element[0],b.currentItem||b.element))this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("out",a,this.ui(b))},_drop:function(a,b){var e=b||d.ui.ddmanager.current;if(!e||(e.currentItem||e.element)[0]==this.element[0])return!1;var f=!1;this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function(){var a=d.data(this,
"droppable");if(a.options.greedy&&!a.options.disabled&&a.options.scope==e.options.scope&&a.accept.call(a.element[0],e.currentItem||e.element)&&d.ui.intersect(e,d.extend(a,{offset:a.element.offset()}),a.options.tolerance))return f=!0,!1});return f?!1:this.accept.call(this.element[0],e.currentItem||e.element)?(this.options.activeClass&&this.element.removeClass(this.options.activeClass),this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("drop",a,this.ui(e)),this.element):
!1},ui:function(a){return{draggable:a.currentItem||a.element,helper:a.helper,position:a.position,offset:a.positionAbs}}});d.extend(d.ui.droppable,{version:"1.8.16"});d.ui.intersect=function(a,b,e){if(!b.offset)return!1;var f=(a.positionAbs||a.position.absolute).left,h=f+a.helperProportions.width,g=(a.positionAbs||a.position.absolute).top,i=g+a.helperProportions.height,j=b.offset.left,k=j+b.proportions.width,l=b.offset.top,m=l+b.proportions.height;switch(e){case "fit":return j<=f&&h<=k&&l<=g&&i<=m;
case "intersect":return j<f+a.helperProportions.width/2&&h-a.helperProportions.width/2<k&&l<g+a.helperProportions.height/2&&i-a.helperProportions.height/2<m;case "pointer":return d.ui.isOver((a.positionAbs||a.position.absolute).top+(a.clickOffset||a.offset.click).top,(a.positionAbs||a.position.absolute).left+(a.clickOffset||a.offset.click).left,l,j,b.proportions.height,b.proportions.width);case "touch":return(g>=l&&g<=m||i>=l&&i<=m||g<l&&i>m)&&(f>=j&&f<=k||h>=j&&h<=k||f<j&&h>k);default:return!1}};
d.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(a,b){var e=d.ui.ddmanager.droppables[a.options.scope]||[],f=b?b.type:null,h=(a.currentItem||a.element).find(":data(droppable)").andSelf(),g=0;a:for(;g<e.length;g++)if(!(e[g].options.disabled||a&&!e[g].accept.call(e[g].element[0],a.currentItem||a.element))){for(var i=0;i<h.length;i++)if(h[i]==e[g].element[0]){e[g].proportions.height=0;continue a}e[g].visible=e[g].element.css("display")!="none";if(e[g].visible)f=="mousedown"&&
e[g]._activate.call(e[g],b),e[g].offset=e[g].element.offset(),e[g].proportions={width:e[g].element[0].offsetWidth,height:e[g].element[0].offsetHeight}}},drop:function(a,b){var e=!1;d.each(d.ui.ddmanager.droppables[a.options.scope]||[],function(){if(this.options&&(!this.options.disabled&&this.visible&&d.ui.intersect(a,this,this.options.tolerance)&&(e=e||this._drop.call(this,b)),!this.options.disabled&&this.visible&&this.accept.call(this.element[0],a.currentItem||a.element)))this.isout=1,this.isover=
0,this._deactivate.call(this,b)});return e},dragStart:function(a,b){a.element.parents(":not(body,html)").bind("scroll.droppable",function(){a.options.refreshPositions||d.ui.ddmanager.prepareOffsets(a,b)})},drag:function(a,b){a.options.refreshPositions&&d.ui.ddmanager.prepareOffsets(a,b);d.each(d.ui.ddmanager.droppables[a.options.scope]||[],function(){if(!this.options.disabled&&!this.greedyChild&&this.visible){var e=d.ui.intersect(a,this,this.options.tolerance);if(e=!e&&this.isover==1?"isout":e&&this.isover==
0?"isover":null){var f;if(this.options.greedy){var h=this.element.parents(":data(droppable):eq(0)");if(h.length)f=d.data(h[0],"droppable"),f.greedyChild=e=="isover"?1:0}if(f&&e=="isover")f.isover=0,f.isout=1,f._out.call(f,b);this[e]=1;this[e=="isout"?"isover":"isout"]=0;this[e=="isover"?"_over":"_out"].call(this,b);if(f&&e=="isout")f.isout=0,f.isover=1,f._over.call(f,b)}}})},dragStop:function(a,b){a.element.parents(":not(body,html)").unbind("scroll.droppable");a.options.refreshPositions||d.ui.ddmanager.prepareOffsets(a,
b)}}})(jQuery);
(function(d){d.widget("ui.panel",{options:{event:"click",collapsible:!0,collapseType:"default",collapsed:!1,accordion:!1,collapseSpeed:"fast",draggable:!1,trueVerticalText:!0,vHeight:"220px",stackable:!0,width:"auto",controls:!1,cookie:null,widgetClass:"ui-helper-reset ui-widget ui-panel",headerClass:"ui-helper-reset ui-widget-header ui-panel-header ui-corner-top",contentClass:"ui-helper-reset ui-widget-content ui-panel-content ui-corner-bottom",contentTextClass:"ui-panel-content-text",rightboxClass:"ui-panel-rightbox",
controlsClass:"ui-panel-controls",titleClass:"ui-panel-title",titleTextClass:"ui-panel-title-text",iconClass:"ui-icon",hoverClass:"ui-state-hover",collapsePnlClass:"ui-panel-clps-pnl",headerIconClpsd:"ui-icon-triangle-1-e",headerIcon:"ui-icon-triangle-1-s",slideRIconClpsd:"ui-icon-arrowthickstop-1-w",slideRIcon:"ui-icon-arrowthickstop-1-e",slideLIconClpsd:"ui-icon-arrowthickstop-1-e",slideLIcon:"ui-icon-arrowthickstop-1-w"},_init:function(){this._panelize()},_panelize:function(){if(this.element.is("div")){var a=
this,b=this.options;this.panelBox=this.element;b.width=="auto"?b.width=this.panelBox.css("width"):this.panelBox.css("width",b.width);this.panelBox.attr("role","panel");b.id=this.panelBox.attr("id");this.headerBox=this.element.children(":first");this.contentBox=this.element.children().eq(1);b.content=this.contentBox.html();this.contentBox.wrapInner("<div/>");this.contentTextBox=this.contentBox.children(":first").addClass(b.contentTextClass);this.headerBox.wrapInner("<div><span/></div>");this.titleBox=
this.headerBox.children(":first");this.titleTextBox=this.titleBox.children(":first");this.titleText=this.titleTextBox.html();this.headerBox.prepend("<span/>");this.rightBox=this.headerBox.children(":first").addClass(b.rightboxClass);b.controls!=!1?(this.rightBox.append("<span/>"),this.controlsBox=this.rightBox.children(":first").addClass(b.controlsClass).html(b.controls)):this.controlsBox=null;this.panelBox.addClass(b.widgetClass);this.headerBox.addClass(b.headerClass);this.titleBox.addClass(b.titleClass);
this.titleTextBox.addClass(b.titleTextClass);this.contentBox.addClass(b.contentClass);if(b.collapsible){switch(b.collapseType){case "slide-right":var e=0;b.controls&&(e=1);this.rightBox.append("<span><span/></span>");this.collapsePanel=this.rightBox.children().eq(e).addClass(b.collapsePnlClass);this.collapseButton=this.collapsePanel.children(":first").addClass(b.slideRIcon);this.iconBtnClpsd=b.slideRIconClpsd;this.iconBtn=b.slideRIcon;this.ctrlBox=this.controlsBox;break;case "slide-left":this.headerBox.prepend("<span><span/></span>");
this.collapsePanel=this.headerBox.children(":first").addClass(b.collapsePnlClass);this.collapseButton=this.collapsePanel.children(":first").addClass(b.slideLIcon);this.iconBtnClpsd=b.slideLIconClpsd;this.iconBtn=b.slideLIcon;this.ctrlBox=this.rightBox;break;default:this.headerBox.prepend("<span><span/></span>"),this.collapseButton=this.headerBox.children(":first").addClass(b.headerIcon),this.iconBtnClpsd=b.headerIconClpsd,this.iconBtn=b.headerIcon,this.ctrlBox=this.controlsBox}this._buttonHover(this.collapseButton);
this.collapseButton.addClass(b.iconClass);b.event&&(this.collapseButton.bind(b.event+".panel",function(d){return a._clickHandler.call(a,d,this)}),this.titleTextBox.bind(b.event+".panel",function(d){return a._clickHandler.call(a,d,this)}));if(b.accordion)b.collapsed=!0,b.trueVerticalText=!1;if(b.cookie)b.collapsed=a._cookie()==0?!1:!0;this.panelBox.data("collapsed",b.collapsed);if(b.stackable&&d.inArray(b.collapseType,["slide-right","slide-left"])>-1){this.panelDock=this.panelBox.siblings("div[role=panelDock]:first");
this.panelFrame=this.panelBox.siblings("div[role=panelFrame]:first");if(this.panelDock.length==0)this.panelDock=this.panelBox.parent(0).prepend("<div>").children(":first"),this.panelFrame=this.panelDock.after("<div>").next(":first"),this.panelDock.attr("role","panelDock").css("float",b.collapseType=="slide-left"?"left":"right"),this.panelFrame.attr("role","panelFrame").css({"float":b.collapseType=="slide-left"?"left":"right",overflow:"hidden"});b.collapsed?this.panelDock.append(this.panelBox):this.panelFrame.append(this.panelBox)}b.collapsed&&
a.toggle(0,!0)}else this.titleTextBox.css("cursor","default");!b.accordion&&b.draggable&&d.fn.draggable&&this._makeDraggable();this.panelBox.show()}},_cookie:function(){var a=this.cookie||(this.cookie=this.options.cookie.name||"ui-panel-"+this.options.id);return d.cookie.apply(null,[a].concat(d.makeArray(arguments)))},_makeDraggable:function(){this.panelBox.draggable({containment:"document",handle:".ui-panel-header",cancel:".ui-panel-content",cursor:"move"});this.contentBox.css("position","absolute")},
_clickHandler:function(){var a=this.options;if(a.disabled)return!1;this.toggle(a.collapseSpeed);return!1},toggle:function(a,b){var e=this.options,f=this.panelBox,h=this.contentBox,g=this.headerBox,i=this.titleTextBox,j=this.titleText,k=this.ctrlBox,l=this.panelDock,m="";jQuery.support.leadingWhitespace||(m="-ie");h.css("display")=="none"?this._trigger("unfold"):this._trigger("fold");k&&k.toggle(0);e.collapseType=="default"?a==0?(k&&k.hide(),h.hide()):h.slideToggle(a):(a==0?(e.collapsed=!1,k&&k.hide(),
h.hide()):h.toggle(),e.collapsed==!1?(e.trueVerticalText?(g.toggleClass("ui-panel-vtitle").css("height",e.vHeight),m==""&&(h="height:"+(parseInt(e.vHeight)-50)+"px;width:100%;position:absolute;bottom:0;left:0;",i.empty().append('<div style="'+h+'z-index:3;"></div><object style="'+h+'z-index:2;" type="image/svg+xml" data="data:image/svg+xml;charset=utf-8,<svg xmlns=\'http://www.w3.org/2000/svg\'><text x=\'-'+(parseInt(e.vHeight)-60)+"px' y='16px' style='font-weight:"+i.css("font-weight")+";font-family:"+
i.css("font-family").replace(/"/g,"")+";font-size:"+i.css("font-size")+";fill:"+i.css("color")+";' transform='rotate(-90)' text-rendering='optimizeSpeed'>"+j+'</text></svg>"></object>').css("height",e.vHeight)),i.toggleClass("ui-panel-vtext"+m)):(g.attr("align","center"),i.html(i.text().replace(/(.)/g,"$1<BR>"))),f.animate({width:"2.4em"},a),e.stackable&&(b?l.append(f):l.prepend(f))):(e.stackable&&this.panelFrame.append(f),e.trueVerticalText?(g.toggleClass("ui-panel-vtitle").css("height","auto"),
i.empty().append(j),i.toggleClass("ui-panel-vtext"+m)):(g.attr("align","left"),i.html(i.text().replace(/<BR>/g," "))),f.animate({width:e.width},a)));if((a!=0||e.trueVerticalText)&&e.cookie==null||!b&&e.cookie!=null)e.collapsed=!e.collapsed;this.panelBox.data("collapsed",e.collapsed);b||(e.cookie&&this._cookie(Number(e.collapsed),e.cookie),e.accordion&&d("."+e.accordion+"[role='panel'][id!='"+e.id+"']:not(:data(collapsed))").panel("toggle",a,!0));this.collapseButton.toggleClass(this.iconBtnClpsd).toggleClass(this.iconBtn);
g.toggleClass("ui-corner-all")},content:function(a){this.contentTextBox.html(a)},destroy:function(){var a=this.options;this.headerBox.html(this.titleText).removeAttr("align").removeAttr("style").removeClass("ui-panel-vtitle ui-corner-all "+a.headerClass);this.contentBox.removeClass(a.contentClass).removeAttr("style").html(a.content);this.panelBox.removeAttr("role").removeAttr("style").removeData("collapsed").unbind(".panel").removeClass(a.widgetClass);a.stackable&&d.inArray(a.collapseType,["slide-right",
"slide-left"])>-1&&(this.panelDock.before(this.panelBox),this.panelDock.children("div[role=panel]").length==0&&this.panelFrame.children("div[role=panel]").length==0&&(this.panelDock.remove(),this.panelFrame.remove()));a.cookie&&this._cookie(null,a.cookie);return this},_buttonHover:function(a){var b=this.options;a.bind({mouseover:function(){d(this).addClass(b.hoverClass)},mouseout:function(){d(this).removeClass(b.hoverClass)}})}});d.extend(d.ui.panel,{version:"0.6"})})(jQuery);
(function(d){d.ui=d.ui||{};var a=/left|center|right/,b=/top|center|bottom/,e=d.fn.position,f=d.fn.offset;d.fn.position=function(f){if(!f||!f.of)return e.apply(this,arguments);var f=d.extend({},f),g=d(f.of),i=g[0],j=(f.collision||"flip").split(" "),k=f.offset?f.offset.split(" "):[0,0],l,m,o;i.nodeType===9?(l=g.width(),m=g.height(),o={top:0,left:0}):i.setTimeout?(l=g.width(),m=g.height(),o={top:g.scrollTop(),left:g.scrollLeft()}):i.preventDefault?(f.at="left top",l=m=0,o={top:f.of.pageY,left:f.of.pageX}):
(l=g.outerWidth(),m=g.outerHeight(),o=g.offset());d.each(["my","at"],function(){var d=(f[this]||"").split(" ");d.length===1&&(d=a.test(d[0])?d.concat(["center"]):b.test(d[0])?["center"].concat(d):["center","center"]);d[0]=a.test(d[0])?d[0]:"center";d[1]=b.test(d[1])?d[1]:"center";f[this]=d});j.length===1&&(j[1]=j[0]);k[0]=parseInt(k[0],10)||0;k.length===1&&(k[1]=k[0]);k[1]=parseInt(k[1],10)||0;f.at[0]==="right"?o.left+=l:f.at[0]==="center"&&(o.left+=l/2);f.at[1]==="bottom"?o.top+=m:f.at[1]==="center"&&
(o.top+=m/2);o.left+=k[0];o.top+=k[1];return this.each(function(){var a=d(this),b=a.outerWidth(),e=a.outerHeight(),g=parseInt(d.curCSS(this,"marginLeft",!0))||0,i=parseInt(d.curCSS(this,"marginTop",!0))||0,q=b+g+(parseInt(d.curCSS(this,"marginRight",!0))||0),w=e+i+(parseInt(d.curCSS(this,"marginBottom",!0))||0),s=d.extend({},o),v;f.my[0]==="right"?s.left-=b:f.my[0]==="center"&&(s.left-=b/2);f.my[1]==="bottom"?s.top-=e:f.my[1]==="center"&&(s.top-=e/2);s.left=Math.round(s.left);s.top=Math.round(s.top);
v={left:s.left-g,top:s.top-i};d.each(["left","top"],function(a,g){if(d.ui.position[j[a]])d.ui.position[j[a]][g](s,{targetWidth:l,targetHeight:m,elemWidth:b,elemHeight:e,collisionPosition:v,collisionWidth:q,collisionHeight:w,offset:k,my:f.my,at:f.at})});d.fn.bgiframe&&a.bgiframe();a.offset(d.extend(s,{using:f.using}))})};d.ui.position={fit:{left:function(a,b){var e=d(window),e=b.collisionPosition.left+b.collisionWidth-e.width()-e.scrollLeft();a.left=e>0?a.left-e:Math.max(a.left-b.collisionPosition.left,
a.left)},top:function(a,b){var e=d(window),e=b.collisionPosition.top+b.collisionHeight-e.height()-e.scrollTop();a.top=e>0?a.top-e:Math.max(a.top-b.collisionPosition.top,a.top)}},flip:{left:function(a,b){if(b.at[0]!=="center"){var e=d(window),e=b.collisionPosition.left+b.collisionWidth-e.width()-e.scrollLeft(),f=b.my[0]==="left"?-b.elemWidth:b.my[0]==="right"?b.elemWidth:0,k=b.at[0]==="left"?b.targetWidth:-b.targetWidth,l=-2*b.offset[0];a.left+=b.collisionPosition.left<0?f+k+l:e>0?f+k+l:0}},top:function(a,
b){if(b.at[1]!=="center"){var e=d(window),e=b.collisionPosition.top+b.collisionHeight-e.height()-e.scrollTop(),f=b.my[1]==="top"?-b.elemHeight:b.my[1]==="bottom"?b.elemHeight:0,k=b.at[1]==="top"?b.targetHeight:-b.targetHeight,l=-2*b.offset[1];a.top+=b.collisionPosition.top<0?f+k+l:e>0?f+k+l:0}}}};if(!d.offset.setOffset)d.offset.setOffset=function(a,b){if(/static/.test(d.curCSS(a,"position")))a.style.position="relative";var e=d(a),f=e.offset(),k=parseInt(d.curCSS(a,"top",!0),10)||0,l=parseInt(d.curCSS(a,
"left",!0),10)||0,f={top:b.top-f.top+k,left:b.left-f.left+l};"using"in b?b.using.call(a,f):e.css(f)},d.fn.offset=function(a){var b=this[0];return!b||!b.ownerDocument?null:a?this.each(function(){d.offset.setOffset(this,a)}):f.call(this)}})(jQuery);
(function(d,a){d.widget("ui.progressbar",{options:{value:0,max:100},min:0,_create:function(){this.element.addClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").attr({role:"progressbar","aria-valuemin":this.min,"aria-valuemax":this.options.max,"aria-valuenow":this._value()});this.valueDiv=d("<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>").appendTo(this.element);this.oldValue=this._value();this._refreshValue()},destroy:function(){this.element.removeClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow");
this.valueDiv.remove();d.Widget.prototype.destroy.apply(this,arguments)},value:function(d){if(d===a)return this._value();this._setOption("value",d);return this},_setOption:function(a,e){if(a==="value")this.options.value=e,this._refreshValue(),this._value()===this.options.max&&this._trigger("complete");d.Widget.prototype._setOption.apply(this,arguments)},_value:function(){var a=this.options.value;typeof a!=="number"&&(a=0);return Math.min(this.options.max,Math.max(this.min,a))},_percentage:function(){return 100*
this._value()/this.options.max},_refreshValue:function(){var a=this.value(),d=this._percentage();if(this.oldValue!==a)this.oldValue=a,this._trigger("change");this.valueDiv.toggle(a>this.min).toggleClass("ui-corner-right",a===this.options.max).width(d.toFixed(0)+"%");this.element.attr("aria-valuenow",a)}});d.extend(d.ui.progressbar,{version:"1.8.16"})})(jQuery);
(function(d){d.widget("ui.resizable",d.ui.mouse,{widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:1E3},_create:function(){var a=this,b=this.options;this.element.addClass("ui-resizable");d.extend(this,{_aspectRatio:!!b.aspectRatio,aspectRatio:b.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],
_helper:b.helper||b.ghost||b.animate?b.helper||"ui-resizable-helper":null});if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i))/relative/.test(this.element.css("position"))&&d.browser.opera&&this.element.css({position:"relative",top:"auto",left:"auto"}),this.element.wrap(d('<div class="ui-wrapper" style="overflow: hidden;"></div>').css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),
this.element=this.element.parent().data("resizable",this.element.data("resizable")),this.elementIsWrapper=!0,this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")}),this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0}),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize",
"none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css({margin:this.originalElement.css("margin")}),this._proportionallyResize();this.handles=b.handles||(!d(".ui-resizable-handle",this.element).length?"e,s,se":{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"});if(this.handles.constructor==String){if(this.handles==
"all")this.handles="n,e,s,w,se,sw,ne,nw";var h=this.handles.split(",");this.handles={};for(var g=0;g<h.length;g++){var i=d.trim(h[g]),j=d('<div class="ui-resizable-handle ui-resizable-'+i+'"></div>');/sw|se|ne|nw/.test(i)&&j.css({zIndex:++b.zIndex});"se"==i&&j.addClass("ui-icon ui-icon-gripsmall-diagonal-se");this.handles[i]=".ui-resizable-"+i;this.element.append(j)}}this._renderAxis=function(a){var a=a||this.element,b;for(b in this.handles){this.handles[b].constructor==String&&(this.handles[b]=d(this.handles[b],
this.element).show());if(this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)){var e=d(this.handles[b],this.element),f=0,f=/sw|ne|nw|se|n|s/.test(b)?e.outerHeight():e.outerWidth(),e=["padding",/ne|nw|n/.test(b)?"Top":/se|sw|s/.test(b)?"Bottom":/^e$/.test(b)?"Right":"Left"].join("");a.css(e,f);this._proportionallyResize()}d(this.handles[b])}};this._renderAxis(this.element);this._handles=d(".ui-resizable-handle",this.element).disableSelection();this._handles.mouseover(function(){if(!a.resizing){if(this.className)var d=
this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i);a.axis=d&&d[1]?d[1]:"se"}});b.autoHide&&(this._handles.hide(),d(this.element).addClass("ui-resizable-autohide").hover(function(){b.disabled||(d(this).removeClass("ui-resizable-autohide"),a._handles.show())},function(){!b.disabled&&!a.resizing&&(d(this).addClass("ui-resizable-autohide"),a._handles.hide())}));this._mouseInit()},destroy:function(){this._mouseDestroy();var a=function(a){d(a).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};
if(this.elementIsWrapper){a(this.element);var b=this.element;b.after(this.originalElement.css({position:b.css("position"),width:b.outerWidth(),height:b.outerHeight(),top:b.css("top"),left:b.css("left")})).remove()}this.originalElement.css("resize",this.originalResizeStyle);a(this.originalElement);return this},_mouseCapture:function(a){var b=!1,h;for(h in this.handles)d(this.handles[h])[0]==a.target&&(b=!0);return!this.options.disabled&&b},_mouseStart:function(b){var f=this.options,h=this.element.position(),
g=this.element;this.resizing=!0;this.documentScroll={top:d(document).scrollTop(),left:d(document).scrollLeft()};(g.is(".ui-draggable")||/absolute/.test(g.css("position")))&&g.css({position:"absolute",top:h.top,left:h.left});d.browser.opera&&/relative/.test(g.css("position"))&&g.css({position:"relative",top:"auto",left:"auto"});this._renderProxy();var h=a(this.helper.css("left")),i=a(this.helper.css("top"));f.containment&&(h+=d(f.containment).scrollLeft()||0,i+=d(f.containment).scrollTop()||0);this.offset=
this.helper.offset();this.position={left:h,top:i};this.size=this._helper?{width:g.outerWidth(),height:g.outerHeight()}:{width:g.width(),height:g.height()};this.originalSize=this._helper?{width:g.outerWidth(),height:g.outerHeight()}:{width:g.width(),height:g.height()};this.originalPosition={left:h,top:i};this.sizeDiff={width:g.outerWidth()-g.width(),height:g.outerHeight()-g.height()};this.originalMousePosition={left:b.pageX,top:b.pageY};this.aspectRatio=typeof f.aspectRatio=="number"?f.aspectRatio:
this.originalSize.width/this.originalSize.height||1;f=d(".ui-resizable-"+this.axis).css("cursor");d("body").css("cursor",f=="auto"?this.axis+"-resize":f);g.addClass("ui-resizable-resizing");this._propagate("start",b);return!0},_mouseDrag:function(a){var d=this.helper,b=this.originalMousePosition,g=this._change[this.axis];if(!g)return!1;b=g.apply(this,[a,a.pageX-b.left||0,a.pageY-b.top||0]);this._updateVirtualBoundaries(a.shiftKey);if(this._aspectRatio||a.shiftKey)b=this._updateRatio(b,a);b=this._respectSize(b,
a);this._propagate("resize",a);d.css({top:this.position.top+"px",left:this.position.left+"px",width:this.size.width+"px",height:this.size.height+"px"});!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize();this._updateCache(b);this._trigger("resize",a,this.ui());return!1},_mouseStop:function(a){this.resizing=!1;var b=this.options;if(this._helper){var h=this._proportionallyResizeElements,g=h.length&&/textarea/i.test(h[0].nodeName),h=g&&d.ui.hasScroll(h[0],"left")?0:
this.sizeDiff.height,g=g?0:this.sizeDiff.width,g={width:this.helper.width()-g,height:this.helper.height()-h},h=parseInt(this.element.css("left"),10)+(this.position.left-this.originalPosition.left)||null,i=parseInt(this.element.css("top"),10)+(this.position.top-this.originalPosition.top)||null;b.animate||this.element.css(d.extend(g,{top:i,left:h}));this.helper.height(this.size.height);this.helper.width(this.size.width);this._helper&&!b.animate&&this._proportionallyResize()}d("body").css("cursor","auto");
this.element.removeClass("ui-resizable-resizing");this._propagate("stop",a);this._helper&&this.helper.remove();return!1},_updateVirtualBoundaries:function(a){var d=this.options,h,g,i,d={minWidth:b(d.minWidth)?d.minWidth:0,maxWidth:b(d.maxWidth)?d.maxWidth:Infinity,minHeight:b(d.minHeight)?d.minHeight:0,maxHeight:b(d.maxHeight)?d.maxHeight:Infinity};if(this._aspectRatio||a){a=d.minHeight*this.aspectRatio;g=d.minWidth/this.aspectRatio;h=d.maxHeight*this.aspectRatio;i=d.maxWidth/this.aspectRatio;if(a>
d.minWidth)d.minWidth=a;if(g>d.minHeight)d.minHeight=g;if(h<d.maxWidth)d.maxWidth=h;if(i<d.maxHeight)d.maxHeight=i}this._vBoundaries=d},_updateCache:function(a){this.offset=this.helper.offset();if(b(a.left))this.position.left=a.left;if(b(a.top))this.position.top=a.top;if(b(a.height))this.size.height=a.height;if(b(a.width))this.size.width=a.width},_updateRatio:function(a){var d=this.position,h=this.size,g=this.axis;if(b(a.height))a.width=a.height*this.aspectRatio;else if(b(a.width))a.height=a.width/
this.aspectRatio;if(g=="sw")a.left=d.left+(h.width-a.width),a.top=null;if(g=="nw")a.top=d.top+(h.height-a.height),a.left=d.left+(h.width-a.width);return a},_respectSize:function(a){var d=this._vBoundaries,h=this.axis,g=b(a.width)&&d.maxWidth&&d.maxWidth<a.width,i=b(a.height)&&d.maxHeight&&d.maxHeight<a.height,j=b(a.width)&&d.minWidth&&d.minWidth>a.width,k=b(a.height)&&d.minHeight&&d.minHeight>a.height;if(j)a.width=d.minWidth;if(k)a.height=d.minHeight;if(g)a.width=d.maxWidth;if(i)a.height=d.maxHeight;
var l=this.originalPosition.left+this.originalSize.width,m=this.position.top+this.size.height,o=/sw|nw|w/.test(h),h=/nw|ne|n/.test(h);if(j&&o)a.left=l-d.minWidth;if(g&&o)a.left=l-d.maxWidth;if(k&&h)a.top=m-d.minHeight;if(i&&h)a.top=m-d.maxHeight;if((d=!a.width&&!a.height)&&!a.left&&a.top)a.top=null;else if(d&&!a.top&&a.left)a.left=null;return a},_proportionallyResize:function(){if(this._proportionallyResizeElements.length)for(var a=this.helper||this.element,b=0;b<this._proportionallyResizeElements.length;b++){var h=
this._proportionallyResizeElements[b];if(!this.borderDif){var g=[h.css("borderTopWidth"),h.css("borderRightWidth"),h.css("borderBottomWidth"),h.css("borderLeftWidth")],i=[h.css("paddingTop"),h.css("paddingRight"),h.css("paddingBottom"),h.css("paddingLeft")];this.borderDif=d.map(g,function(a,d){var b=parseInt(a,10)||0,e=parseInt(i[d],10)||0;return b+e})}if(!d.browser.msie||!d(a).is(":hidden")&&!d(a).parents(":hidden").length)h.css({height:a.height()-this.borderDif[0]-this.borderDif[2]||0,width:a.width()-
this.borderDif[1]-this.borderDif[3]||0})}},_renderProxy:function(){var a=this.options;this.elementOffset=this.element.offset();if(this._helper){this.helper=this.helper||d('<div style="overflow:hidden;"></div>');var b=d.browser.msie&&d.browser.version<7,h=b?1:0,b=b?2:-1;this.helper.addClass(this._helper).css({width:this.element.outerWidth()+b,height:this.element.outerHeight()+b,position:"absolute",left:this.elementOffset.left-h+"px",top:this.elementOffset.top-h+"px",zIndex:++a.zIndex});this.helper.appendTo("body").disableSelection()}else this.helper=
this.element},_change:{e:function(a,d){return{width:this.originalSize.width+d}},w:function(a,d){return{left:this.originalPosition.left+d,width:this.originalSize.width-d}},n:function(a,d,b){return{top:this.originalPosition.top+b,height:this.originalSize.height-b}},s:function(a,d,b){return{height:this.originalSize.height+b}},se:function(a,b,h){return d.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[a,b,h]))},sw:function(a,b,h){return d.extend(this._change.s.apply(this,arguments),
this._change.w.apply(this,[a,b,h]))},ne:function(a,b,h){return d.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[a,b,h]))},nw:function(a,b,h){return d.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[a,b,h]))}},_propagate:function(a,b){d.ui.plugin.call(this,a,[b,this.ui()]);a!="resize"&&this._trigger(a,b,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,
originalSize:this.originalSize,originalPosition:this.originalPosition}}});d.extend(d.ui.resizable,{version:"1.8.16"});d.ui.plugin.add("resizable","alsoResize",{start:function(){var a=d(this).data("resizable").options,b=function(a){d(a).each(function(){var a=d(this);a.data("resizable-alsoresize",{width:parseInt(a.width(),10),height:parseInt(a.height(),10),left:parseInt(a.css("left"),10),top:parseInt(a.css("top"),10),position:a.css("position")})})};typeof a.alsoResize=="object"&&!a.alsoResize.parentNode?
a.alsoResize.length?(a.alsoResize=a.alsoResize[0],b(a.alsoResize)):d.each(a.alsoResize,function(a){b(a)}):b(a.alsoResize)},resize:function(a,b){var h=d(this).data("resizable"),g=h.options,i=h.originalSize,j=h.originalPosition,k={height:h.size.height-i.height||0,width:h.size.width-i.width||0,top:h.position.top-j.top||0,left:h.position.left-j.left||0},l=function(a,e){d(a).each(function(){var a=d(this),g=d(this).data("resizable-alsoresize"),i={},m=e&&e.length?e:a.parents(b.originalElement[0]).length?
["width","height"]:["width","height","top","left"];d.each(m,function(a,d){var b=(g[d]||0)+(k[d]||0);b&&b>=0&&(i[d]=b||null)});if(d.browser.opera&&/relative/.test(a.css("position")))h._revertToRelativePosition=!0,a.css({position:"absolute",top:"auto",left:"auto"});a.css(i)})};typeof g.alsoResize=="object"&&!g.alsoResize.nodeType?d.each(g.alsoResize,function(a,d){l(a,d)}):l(g.alsoResize)},stop:function(){var a=d(this).data("resizable"),b=a.options,h=function(a){d(a).each(function(){var a=d(this);a.css({position:a.data("resizable-alsoresize").position})})};
if(a._revertToRelativePosition)a._revertToRelativePosition=!1,typeof b.alsoResize=="object"&&!b.alsoResize.nodeType?d.each(b.alsoResize,function(a){h(a)}):h(b.alsoResize);d(this).removeData("resizable-alsoresize")}});d.ui.plugin.add("resizable","animate",{stop:function(a){var b=d(this).data("resizable"),h=b.options,g=b._proportionallyResizeElements,i=g.length&&/textarea/i.test(g[0].nodeName),j=i&&d.ui.hasScroll(g[0],"left")?0:b.sizeDiff.height,i={width:b.size.width-(i?0:b.sizeDiff.width),height:b.size.height-
j},j=parseInt(b.element.css("left"),10)+(b.position.left-b.originalPosition.left)||null,k=parseInt(b.element.css("top"),10)+(b.position.top-b.originalPosition.top)||null;b.element.animate(d.extend(i,k&&j?{top:k,left:j}:{}),{duration:h.animateDuration,easing:h.animateEasing,step:function(){var h={width:parseInt(b.element.css("width"),10),height:parseInt(b.element.css("height"),10),top:parseInt(b.element.css("top"),10),left:parseInt(b.element.css("left"),10)};g&&g.length&&d(g[0]).css({width:h.width,
height:h.height});b._updateCache(h);b._propagate("resize",a)}})}});d.ui.plugin.add("resizable","containment",{start:function(){var b=d(this).data("resizable"),f=b.element,h=b.options.containment;if(f=h instanceof d?h.get(0):/parent/.test(h)?f.parent().get(0):h)if(b.containerElement=d(f),/document/.test(h)||h==document)b.containerOffset={left:0,top:0},b.containerPosition={left:0,top:0},b.parentData={element:d(document),left:0,top:0,width:d(document).width(),height:d(document).height()||document.body.parentNode.scrollHeight};
else{var g=d(f),i=[];d(["Top","Right","Left","Bottom"]).each(function(d,b){i[d]=a(g.css("padding"+b))});b.containerOffset=g.offset();b.containerPosition=g.position();b.containerSize={height:g.innerHeight()-i[3],width:g.innerWidth()-i[1]};var h=b.containerOffset,j=b.containerSize.height,k=b.containerSize.width,k=d.ui.hasScroll(f,"left")?f.scrollWidth:k,j=d.ui.hasScroll(f)?f.scrollHeight:j;b.parentData={element:f,left:h.left,top:h.top,width:k,height:j}}},resize:function(a){var b=d(this).data("resizable"),
h=b.options,g=b.containerOffset,i=b.position,a=b._aspectRatio||a.shiftKey,j={top:0,left:0},k=b.containerElement;k[0]!=document&&/static/.test(k.css("position"))&&(j=g);if(i.left<(b._helper?g.left:0)){b.size.width+=b._helper?b.position.left-g.left:b.position.left-j.left;if(a)b.size.height=b.size.width/h.aspectRatio;b.position.left=h.helper?g.left:0}if(i.top<(b._helper?g.top:0)){b.size.height+=b._helper?b.position.top-g.top:b.position.top;if(a)b.size.width=b.size.height*h.aspectRatio;b.position.top=
b._helper?g.top:0}b.offset.left=b.parentData.left+b.position.left;b.offset.top=b.parentData.top+b.position.top;h=Math.abs((b._helper?b.offset.left-j.left:b.offset.left-j.left)+b.sizeDiff.width);g=Math.abs((b._helper?b.offset.top-j.top:b.offset.top-g.top)+b.sizeDiff.height);i=b.containerElement.get(0)==b.element.parent().get(0);j=/relative|absolute/.test(b.containerElement.css("position"));i&&j&&(h-=b.parentData.left);if(h+b.size.width>=b.parentData.width&&(b.size.width=b.parentData.width-h,a))b.size.height=
b.size.width/b.aspectRatio;if(g+b.size.height>=b.parentData.height&&(b.size.height=b.parentData.height-g,a))b.size.width=b.size.height*b.aspectRatio},stop:function(){var a=d(this).data("resizable"),b=a.options,h=a.containerOffset,g=a.containerPosition,i=a.containerElement,j=d(a.helper),k=j.offset(),l=j.outerWidth()-a.sizeDiff.width,j=j.outerHeight()-a.sizeDiff.height;a._helper&&!b.animate&&/relative/.test(i.css("position"))&&d(this).css({left:k.left-g.left-h.left,width:l,height:j});a._helper&&!b.animate&&
/static/.test(i.css("position"))&&d(this).css({left:k.left-g.left-h.left,width:l,height:j})}});d.ui.plugin.add("resizable","ghost",{start:function(){var a=d(this).data("resizable"),b=a.options,h=a.size;a.ghost=a.originalElement.clone();a.ghost.css({opacity:0.25,display:"block",position:"relative",height:h.height,width:h.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass(typeof b.ghost=="string"?b.ghost:"");a.ghost.appendTo(a.helper)},resize:function(){var a=d(this).data("resizable");
a.ghost&&a.ghost.css({position:"relative",height:a.size.height,width:a.size.width})},stop:function(){var a=d(this).data("resizable");a.ghost&&a.helper&&a.helper.get(0).removeChild(a.ghost.get(0))}});d.ui.plugin.add("resizable","grid",{resize:function(){var a=d(this).data("resizable"),b=a.options,h=a.size,g=a.originalSize,i=a.originalPosition,j=a.axis;b.grid=typeof b.grid=="number"?[b.grid,b.grid]:b.grid;var k=Math.round((h.width-g.width)/(b.grid[0]||1))*(b.grid[0]||1),b=Math.round((h.height-g.height)/
(b.grid[1]||1))*(b.grid[1]||1);/^(se|s|e)$/.test(j)?(a.size.width=g.width+k,a.size.height=g.height+b):/^(ne)$/.test(j)?(a.size.width=g.width+k,a.size.height=g.height+b,a.position.top=i.top-b):(/^(sw)$/.test(j)?(a.size.width=g.width+k,a.size.height=g.height+b):(a.size.width=g.width+k,a.size.height=g.height+b,a.position.top=i.top-b),a.position.left=i.left-k)}});var a=function(a){return parseInt(a,10)||0},b=function(a){return!isNaN(parseInt(a,10))}})(jQuery);
(function(d){d.widget("ui.selectable",d.ui.mouse,{options:{appendTo:"body",autoRefresh:!0,distance:0,filter:"*",tolerance:"touch"},_create:function(){var a=this;this.element.addClass("ui-selectable");this.dragged=!1;var b;this.refresh=function(){b=d(a.options.filter,a.element[0]);b.each(function(){var a=d(this),b=a.offset();d.data(this,"selectable-item",{element:this,$element:a,left:b.left,top:b.top,right:b.left+a.outerWidth(),bottom:b.top+a.outerHeight(),startselected:!1,selected:a.hasClass("ui-selected"),
selecting:a.hasClass("ui-selecting"),unselecting:a.hasClass("ui-unselecting")})})};this.refresh();this.selectees=b.addClass("ui-selectee");this._mouseInit();this.helper=d("<div class='ui-selectable-helper'></div>")},destroy:function(){this.selectees.removeClass("ui-selectee").removeData("selectable-item");this.element.removeClass("ui-selectable ui-selectable-disabled").removeData("selectable").unbind(".selectable");this._mouseDestroy();return this},_mouseStart:function(a){var b=this;this.opos=[a.pageX,
a.pageY];if(!this.options.disabled){var e=this.options;this.selectees=d(e.filter,this.element[0]);this._trigger("start",a);d(e.appendTo).append(this.helper);this.helper.css({left:a.clientX,top:a.clientY,width:0,height:0});e.autoRefresh&&this.refresh();this.selectees.filter(".ui-selected").each(function(){var e=d.data(this,"selectable-item");e.startselected=!0;if(!a.metaKey)e.$element.removeClass("ui-selected"),e.selected=!1,e.$element.addClass("ui-unselecting"),e.unselecting=!0,b._trigger("unselecting",
a,{unselecting:e.element})});d(a.target).parents().andSelf().each(function(){var e=d.data(this,"selectable-item");if(e){var h=!a.metaKey||!e.$element.hasClass("ui-selected");e.$element.removeClass(h?"ui-unselecting":"ui-selected").addClass(h?"ui-selecting":"ui-unselecting");e.unselecting=!h;e.selecting=h;(e.selected=h)?b._trigger("selecting",a,{selecting:e.element}):b._trigger("unselecting",a,{unselecting:e.element});return!1}})}},_mouseDrag:function(a){var b=this;this.dragged=!0;if(!this.options.disabled){var e=
this.options,f=this.opos[0],h=this.opos[1],g=a.pageX,i=a.pageY;if(f>g)var j=g,g=f,f=j;h>i&&(j=i,i=h,h=j);this.helper.css({left:f,top:h,width:g-f,height:i-h});this.selectees.each(function(){var j=d.data(this,"selectable-item");if(j&&j.element!=b.element[0]){var l=!1;e.tolerance=="touch"?l=!(j.left>g||j.right<f||j.top>i||j.bottom<h):e.tolerance=="fit"&&(l=j.left>f&&j.right<g&&j.top>h&&j.bottom<i);if(l){if(j.selected)j.$element.removeClass("ui-selected"),j.selected=!1;if(j.unselecting)j.$element.removeClass("ui-unselecting"),
j.unselecting=!1;if(!j.selecting)j.$element.addClass("ui-selecting"),j.selecting=!0,b._trigger("selecting",a,{selecting:j.element})}else{if(j.selecting)if(a.metaKey&&j.startselected)j.$element.removeClass("ui-selecting"),j.selecting=!1,j.$element.addClass("ui-selected"),j.selected=!0;else{j.$element.removeClass("ui-selecting");j.selecting=!1;if(j.startselected)j.$element.addClass("ui-unselecting"),j.unselecting=!0;b._trigger("unselecting",a,{unselecting:j.element})}if(j.selected&&!a.metaKey&&!j.startselected)j.$element.removeClass("ui-selected"),
j.selected=!1,j.$element.addClass("ui-unselecting"),j.unselecting=!0,b._trigger("unselecting",a,{unselecting:j.element})}}});return!1}},_mouseStop:function(a){var b=this;this.dragged=!1;d(".ui-unselecting",this.element[0]).each(function(){var e=d.data(this,"selectable-item");e.$element.removeClass("ui-unselecting");e.unselecting=!1;e.startselected=!1;b._trigger("unselected",a,{unselected:e.element})});d(".ui-selecting",this.element[0]).each(function(){var e=d.data(this,"selectable-item");e.$element.removeClass("ui-selecting").addClass("ui-selected");
e.selecting=!1;e.selected=!0;e.startselected=!0;b._trigger("selected",a,{selected:e.element})});this._trigger("stop",a);this.helper.remove();return!1}});d.extend(d.ui.selectable,{version:"1.8.16"})})(jQuery);
(function(d){d.widget("ui.selectmenu",{getter:"value",version:"1.8",eventPrefix:"selectmenu",options:{transferClasses:!0,typeAhead:"sequential",style:"dropdown",positionOptions:{my:"left top",at:"left bottom",offset:null},width:null,menuWidth:null,handleWidth:26,maxHeight:null,icons:null,format:null,bgImage:function(){},wrapperElement:"<div />"},_create:function(){var a=this,b=this.options,e=this.element.attr("id")||"ui-selectmenu-"+Math.random().toString(16).slice(2,10);this.ids=[e+"-button",e+"-menu"];
this._safemouseup=!0;this.newelement=d("<a />",{"class":this.widgetBaseClass+" ui-widget ui-state-default ui-corner-all",id:this.ids[0],role:"button",href:"#",tabindex:this.element.attr("disabled")?1:0,"aria-haspopup":!0,"aria-owns":this.ids[1]});this.newelementWrap=d(b.wrapperElement).append(this.newelement).insertAfter(this.element);var f=this.element.attr("tabindex");f&&this.newelement.attr("tabindex",f);this.newelement.data("selectelement",this.element);this.selectmenuIcon=d('<span class="'+this.widgetBaseClass+
'-icon ui-icon"></span>').prependTo(this.newelement);this.newelement.prepend('<span class="'+a.widgetBaseClass+'-status" />');d('label[for="'+e+'"]').attr("for",this.ids[0]).bind("click.selectmenu",function(){a.newelement[0].focus();return!1});this.newelement.bind("mousedown.selectmenu",function(d){a._toggle(d,!0);if(b.style=="popup")a._safemouseup=!1,setTimeout(function(){a._safemouseup=!0},300);return!1}).bind("click.selectmenu",function(){return!1}).bind("keydown.selectmenu",function(b){var e=
!1;switch(b.keyCode){case d.ui.keyCode.ENTER:e=!0;break;case d.ui.keyCode.SPACE:a._toggle(b);break;case d.ui.keyCode.UP:b.altKey?a.open(b):a._moveSelection(-1);break;case d.ui.keyCode.DOWN:b.altKey?a.open(b):a._moveSelection(1);break;case d.ui.keyCode.LEFT:a._moveSelection(-1);break;case d.ui.keyCode.RIGHT:a._moveSelection(1);break;case d.ui.keyCode.TAB:e=!0;break;default:e=!0}return e}).bind("keypress.selectmenu",function(b){a._typeAhead(b.which,"mouseup");return!0}).bind("mouseover.selectmenu focus.selectmenu",
function(){b.disabled||d(this).addClass(a.widgetBaseClass+"-focus ui-state-hover")}).bind("mouseout.selectmenu blur.selectmenu",function(){b.disabled||d(this).removeClass(a.widgetBaseClass+"-focus ui-state-hover")});d(document).bind("mousedown.selectmenu",function(b){a.close(b)});this.element.bind("click.selectmenu",function(){a._refreshValue()}).bind("focus.selectmenu",function(){a.newelement&&a.newelement[0].focus()});if(!b.width)b.width=this.element.outerWidth();this.newelement.width(b.width);
this.element.hide();this.list=d("<ul />",{"class":"ui-widget ui-widget-content","aria-hidden":!0,role:"listbox","aria-labelledby":this.ids[0],id:this.ids[1]});this.listWrap=d(b.wrapperElement).addClass(a.widgetBaseClass+"-menu").append(this.list).appendTo("body");this.list.bind("keydown.selectmenu",function(b){var e=!1;switch(b.keyCode){case d.ui.keyCode.UP:b.altKey?a.close(b,!0):a._moveFocus(-1);break;case d.ui.keyCode.DOWN:b.altKey?a.close(b,!0):a._moveFocus(1);break;case d.ui.keyCode.LEFT:a._moveFocus(-1);
break;case d.ui.keyCode.RIGHT:a._moveFocus(1);break;case d.ui.keyCode.HOME:a._moveFocus(":first");break;case d.ui.keyCode.PAGE_UP:a._scrollPage("up");break;case d.ui.keyCode.PAGE_DOWN:a._scrollPage("down");break;case d.ui.keyCode.END:a._moveFocus(":last");break;case d.ui.keyCode.ENTER:case d.ui.keyCode.SPACE:a.close(b,!0);d(b.target).parents("li:eq(0)").trigger("mouseup");break;case d.ui.keyCode.TAB:e=!0;a.close(b,!0);d(b.target).parents("li:eq(0)").trigger("mouseup");break;case d.ui.keyCode.ESCAPE:a.close(b,
!0);break;default:e=!0}return e}).bind("keypress.selectmenu",function(b){a._typeAhead(b.which,"focus");return!0}).bind("mousedown.selectmenu mouseup.selectmenu",function(){return!1})},_init:function(){var a=this,b=this.options,e=[];this.element.find("option").each(function(){var f=d(this);e.push({value:f.attr("value"),text:a._formatText(f.text()),selected:f.attr("selected"),disabled:f.attr("disabled"),classes:f.attr("class"),typeahead:f.attr("typeahead"),parentOptGroup:f.parent("optgroup"),bgImage:b.bgImage.call(f)})});
var f=a.options.style=="popup"?" ui-state-active":"";this.list.html("");if(e.length)for(var h=0;h<e.length;h++){var g={role:"presentation"};e[h].disabled&&(g["class"]=this.namespace+"-state-disabled");var i={html:e[h].text,href:"#",tabindex:-1,role:"option","aria-selected":!1};if(e[h].disabled)i["aria-disabled"]=e[h].disabled;if(e[h].typeahead)i.typeahead=e[h].typeahead;i=d("<a/>",i);g=d("<li/>",g).append(i).data("index",h).addClass(e[h].classes).data("optionClasses",e[h].classes||"").bind("mouseup.selectmenu",
function(b){if(a._safemouseup&&!a._disabled(b.currentTarget)&&!a._disabled(d(b.currentTarget).parents("ul>li."+a.widgetBaseClass+"-group "))){var e=d(this).data("index")!=a._selectedIndex();a.index(d(this).data("index"));a.select(b);e&&a.change(b);a.close(b,!0)}return!1}).bind("click.selectmenu",function(){return!1}).bind("mouseover.selectmenu focus.selectmenu",function(b){!d(b.currentTarget).hasClass(a.namespace+"-state-disabled")&&!d(b.currentTarget).parent("ul").parent("li").hasClass(a.namespace+
"-state-disabled")&&(a._selectedOptionLi().addClass(f),a._focusedOptionLi().removeClass(a.widgetBaseClass+"-item-focus ui-state-hover"),d(this).removeClass("ui-state-active").addClass(a.widgetBaseClass+"-item-focus ui-state-hover"))}).bind("mouseout.selectmenu blur.selectmenu",function(){d(this).is(a._selectedOptionLi().selector)&&d(this).addClass(f);d(this).removeClass(a.widgetBaseClass+"-item-focus ui-state-hover")});e[h].parentOptGroup.length?(i=a.widgetBaseClass+"-group-"+this.element.find("optgroup").index(e[h].parentOptGroup),
this.list.find("li."+i).length?this.list.find("li."+i+":last ul").append(g):d(' <li role="presentation" class="'+a.widgetBaseClass+"-group "+i+(e[h].parentOptGroup.attr("disabled")?" "+this.namespace+'-state-disabled" aria-disabled="true"':'"')+'><span class="'+a.widgetBaseClass+'-group-label">'+e[h].parentOptGroup.attr("label")+"</span><ul></ul></li> ").appendTo(this.list).find("ul").append(g)):g.appendTo(this.list);if(b.icons)for(var j in b.icons)g.is(b.icons[j].find)&&(g.data("optionClasses",e[h].classes+
" "+a.widgetBaseClass+"-hasIcon").addClass(a.widgetBaseClass+"-hasIcon"),i=b.icons[j].icon||"",g.find("a:eq(0)").prepend('<span class="'+a.widgetBaseClass+"-item-icon ui-icon "+i+'"></span>'),e[h].bgImage&&g.find("span").css("background-image",e[h].bgImage))}else d('<li role="presentation"><a href="#" tabindex="-1" role="option"></a></li>').appendTo(this.list);h=b.style=="dropdown";this.newelement.toggleClass(a.widgetBaseClass+"-dropdown",h).toggleClass(a.widgetBaseClass+"-popup",!h);this.list.toggleClass(a.widgetBaseClass+
"-menu-dropdown ui-corner-bottom",h).toggleClass(a.widgetBaseClass+"-menu-popup ui-corner-all",!h).find("li:first").toggleClass("ui-corner-top",!h).end().find("li:last").addClass("ui-corner-bottom");this.selectmenuIcon.toggleClass("ui-icon-triangle-1-s",h).toggleClass("ui-icon-triangle-2-n-s",!h);b.transferClasses&&(h=this.element.attr("class")||"",this.newelement.add(this.list).addClass(h));b.style=="dropdown"?this.list.width(b.menuWidth?b.menuWidth:b.width):this.list.width(b.menuWidth?b.menuWidth:
b.width-b.handleWidth);this.list.css("height","auto");h=this.listWrap.height();b.maxHeight&&b.maxHeight<h?this.list.height(b.maxHeight):(j=d(window).height()/3,j<h&&this.list.height(j));this._optionLis=this.list.find("li:not(."+a.widgetBaseClass+"-group)");this.element.attr("disabled")?this.disable():this.enable();this.index(this._selectedIndex());window.setTimeout(function(){a._refreshPosition()},200)},destroy:function(){this.element.removeData(this.widgetName).removeClass(this.widgetBaseClass+"-disabled "+
this.namespace+"-state-disabled").removeAttr("aria-disabled").unbind(".selectmenu");d(document).unbind(".selectmenu");d("label[for="+this.newelement.attr("id")+"]").attr("for",this.element.attr("id")).unbind(".selectmenu");this.newelementWrap.remove();this.listWrap.remove();this.element.show();d.Widget.prototype.destroy.apply(this,arguments)},_typeAhead:function(a,b){var e=this,f=!1,h=String.fromCharCode(a).toUpperCase();c=h.toLowerCase();if(e.options.typeAhead=="sequential"){window.clearTimeout("ui.selectmenu-"+
e.selectmenuId);var g=typeof e._prevChar=="undefined"?"":e._prevChar.join(""),i=function(a,h,g){f=!0;d(a).trigger(b);typeof e._prevChar=="undefined"?e._prevChar=[g]:e._prevChar[e._prevChar.length]=g};this.list.find("li a").each(function(a){if(!f){var b=d(this).attr("typeahead")||d(this).text();b.indexOf(g+h)===0?i(this,a,h):b.indexOf(g+c)===0&&i(this,a,c)}});window.setTimeout(function(){e._prevChar=void 0},1E3,e)}else{if(!e._prevChar)e._prevChar=["",0];f=!1;this.list.find("li a").each(function(a){if(!f){var g=
d(this).text();if(g.indexOf(h)===0||g.indexOf(c)===0)e._prevChar[0]==h?e._prevChar[1]<a&&(f=!0,d(this).trigger(b),e._prevChar[1]=a):(f=!0,d(this).trigger(b),e._prevChar[1]=a)}});this._prevChar[0]=h}},_uiHash:function(){var a=this.index();return{index:a,option:d("option",this.element).get(a),value:this.element[0].value}},open:function(a){var b=this.options;this.newelement.attr("aria-disabled")!="true"&&(this._closeOthers(a),this.newelement.addClass("ui-state-active"),this.listWrap.appendTo(b.appendTo),
this.list.attr("aria-hidden",!1),b.style=="dropdown"&&this.newelement.removeClass("ui-corner-all").addClass("ui-corner-top"),this.listWrap.addClass(this.widgetBaseClass+"-open"),d.browser.msie&&d.browser.version.substr(0,1)==7&&this._refreshPosition(),b=this.list.attr("aria-hidden",!1).find("li:not(."+this.widgetBaseClass+"-group):eq("+this._selectedIndex()+"):visible a"),b.length&&b[0].focus(),this._refreshPosition(),this._trigger("open",a,this._uiHash()))},close:function(a,b){this.newelement.is(".ui-state-active")&&
(this.newelement.removeClass("ui-state-active"),this.listWrap.removeClass(this.widgetBaseClass+"-open"),this.list.attr("aria-hidden",!0),this.options.style=="dropdown"&&this.newelement.removeClass("ui-corner-top").addClass("ui-corner-all"),b&&this.newelement.focus(),this._trigger("close",a,this._uiHash()))},change:function(a){this.element.trigger("change");this._trigger("change",a,this._uiHash())},select:function(a){if(this._disabled(a.currentTarget))return!1;this._trigger("select",a,this._uiHash())},
_closeOthers:function(a){d("."+this.widgetBaseClass+".ui-state-active").not(this.newelement).each(function(){d(this).data("selectelement").selectmenu("close",a)});d("."+this.widgetBaseClass+".ui-state-hover").trigger("mouseout")},_toggle:function(a,b){this.list.is("."+this.widgetBaseClass+"-open")?this.close(a,b):this.open(a)},_formatText:function(a){return this.options.format?this.options.format(a):a},_selectedIndex:function(){return this.element[0].selectedIndex},_selectedOptionLi:function(){return this._optionLis.eq(this._selectedIndex())},
_focusedOptionLi:function(){return this.list.find("."+this.widgetBaseClass+"-item-focus")},_moveSelection:function(a,b){if(!this.options.disabled){var d=parseInt(this._selectedOptionLi().data("index")||0,10)+a;d<0&&(d=0);d>this._optionLis.size()-1&&(d=this._optionLis.size()-1);if(d===b)return!1;if(this._optionLis.eq(d).hasClass(this.namespace+"-state-disabled"))a>0?++a:--a,this._moveSelection(a,d);else return this._optionLis.eq(d).trigger("mouseup")}},_moveFocus:function(a,b){var d=isNaN(a)?parseInt(this._optionLis.filter(a).data("index"),
10):parseInt(this._focusedOptionLi().data("index")||0,10)+a;d<0&&(d=0);d>this._optionLis.size()-1&&(d=this._optionLis.size()-1);if(d===b)return!1;var f=this.widgetBaseClass+"-item-"+Math.round(Math.random()*1E3);this._focusedOptionLi().find("a:eq(0)").attr("id","");this._optionLis.eq(d).hasClass(this.namespace+"-state-disabled")?(a>0?++a:--a,this._moveFocus(a,d)):this._optionLis.eq(d).find("a:eq(0)").attr("id",f).focus();this.list.attr("aria-activedescendant",f)},_scrollPage:function(a){var b=Math.floor(this.list.outerHeight()/
this.list.find("li:first").outerHeight());this._moveFocus(a=="up"?-b:b)},_setOption:function(a,b){this.options[a]=b;a=="disabled"&&(this.close(),this.element.add(this.newelement).add(this.list)[b?"addClass":"removeClass"](this.widgetBaseClass+"-disabled "+this.namespace+"-state-disabled").attr("aria-disabled",b))},disable:function(a,b){typeof a=="undefined"?this._setOption("disabled",!0):b=="optgroup"?this._disableOptgroup(a):this._disableOption(a)},enable:function(a,b){typeof a=="undefined"?this._setOption("disabled",
!1):b=="optgroup"?this._enableOptgroup(a):this._enableOption(a)},_disabled:function(a){return d(a).hasClass(this.namespace+"-state-disabled")},_disableOption:function(a){var b=this._optionLis.eq(a);b&&(b.addClass(this.namespace+"-state-disabled").find("a").attr("aria-disabled",!0),this.element.find("option").eq(a).attr("disabled","disabled"))},_enableOption:function(a){var b=this._optionLis.eq(a);b&&(b.removeClass(this.namespace+"-state-disabled").find("a").attr("aria-disabled",!1),this.element.find("option").eq(a).removeAttr("disabled"))},
_disableOptgroup:function(a){var b=this.list.find("li."+this.widgetBaseClass+"-group-"+a);b&&(b.addClass(this.namespace+"-state-disabled").attr("aria-disabled",!0),this.element.find("optgroup").eq(a).attr("disabled","disabled"))},_enableOptgroup:function(a){var b=this.list.find("li."+this.widgetBaseClass+"-group-"+a);b&&(b.removeClass(this.namespace+"-state-disabled").attr("aria-disabled",!1),this.element.find("optgroup").eq(a).removeAttr("disabled"))},index:function(a){if(arguments.length)if(this._disabled(d(this._optionLis[a])))return!1;
else this.element[0].selectedIndex=a,this._refreshValue();else return this._selectedIndex()},value:function(a){if(arguments.length)this.element[0].value=a,this._refreshValue();else return this.element[0].value},_refreshValue:function(){var a=this.options.style=="popup"?" ui-state-active":"",b=this.widgetBaseClass+"-item-"+Math.round(Math.random()*1E3);this.list.find("."+this.widgetBaseClass+"-item-selected").removeClass(this.widgetBaseClass+"-item-selected"+a).find("a").attr("aria-selected","false").attr("id",
"");this._selectedOptionLi().addClass(this.widgetBaseClass+"-item-selected"+a).find("a").attr("aria-selected","true").attr("id",b);var a=this.newelement.data("optionClasses")?this.newelement.data("optionClasses"):"",d=this._selectedOptionLi().data("optionClasses")?this._selectedOptionLi().data("optionClasses"):"";this.newelement.removeClass(a).data("optionClasses",d).addClass(d).find("."+this.widgetBaseClass+"-status").html(this._selectedOptionLi().find("a:eq(0)").html());this.list.attr("aria-activedescendant",
b)},_refreshPosition:function(){var a=this.options;if(a.style=="popup"&&!a.positionOptions.offset)var b=this._selectedOptionLi(),b="0 -"+(b.outerHeight()+b.offset().top-this.list.offset().top);var d=this.element.zIndex();d&&this.listWrap.css("zIndex",d);this.listWrap.position({of:a.positionOptions.of||this.newelement,my:a.positionOptions.my,at:a.positionOptions.at,offset:a.positionOptions.offset||b,collision:a.positionOptions.collision||"flip"})}})})(jQuery);
(function(d){d.widget("ui.slider",d.ui.mouse,{widgetEventPrefix:"slide",options:{animate:!1,distance:0,max:100,min:0,orientation:"horizontal",range:!1,step:1,value:0,values:null},_create:function(){var a=this,b=this.options,e=this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),f=b.values&&b.values.length||1,h=[];this._mouseSliding=this._keySliding=!1;this._animateOff=!0;this._handleIndex=null;this._detectOrientation();this._mouseInit();this.element.addClass("ui-slider ui-slider-"+
this.orientation+" ui-widget ui-widget-content ui-corner-all"+(b.disabled?" ui-slider-disabled ui-disabled":""));this.range=d([]);if(b.range){if(b.range===!0){if(!b.values)b.values=[this._valueMin(),this._valueMin()];if(b.values.length&&b.values.length!==2)b.values=[b.values[0],b.values[0]]}this.range=d("<div></div>").appendTo(this.element).addClass("ui-slider-range ui-widget-header"+(b.range==="min"||b.range==="max"?" ui-slider-range-"+b.range:""))}for(var g=e.length;g<f;g+=1)h.push("<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>");
this.handles=e.add(d(h.join("")).appendTo(a.element));this.handle=this.handles.eq(0);this.handles.add(this.range).filter("a").click(function(a){a.preventDefault()}).hover(function(){b.disabled||d(this).addClass("ui-state-hover")},function(){d(this).removeClass("ui-state-hover")}).focus(function(){b.disabled?d(this).blur():(d(".ui-slider .ui-state-focus").removeClass("ui-state-focus"),d(this).addClass("ui-state-focus"))}).blur(function(){d(this).removeClass("ui-state-focus")});this.handles.each(function(a){d(this).data("index.ui-slider-handle",
a)});this.handles.keydown(function(b){var e=!0,f=d(this).data("index.ui-slider-handle"),h,g,o;if(!a.options.disabled){switch(b.keyCode){case d.ui.keyCode.HOME:case d.ui.keyCode.END:case d.ui.keyCode.PAGE_UP:case d.ui.keyCode.PAGE_DOWN:case d.ui.keyCode.UP:case d.ui.keyCode.RIGHT:case d.ui.keyCode.DOWN:case d.ui.keyCode.LEFT:if(e=!1,!a._keySliding&&(a._keySliding=!0,d(this).addClass("ui-state-active"),h=a._start(b,f),h===!1))return}o=a.options.step;h=a.options.values&&a.options.values.length?g=a.values(f):
g=a.value();switch(b.keyCode){case d.ui.keyCode.HOME:g=a._valueMin();break;case d.ui.keyCode.END:g=a._valueMax();break;case d.ui.keyCode.PAGE_UP:g=a._trimAlignValue(h+(a._valueMax()-a._valueMin())/5);break;case d.ui.keyCode.PAGE_DOWN:g=a._trimAlignValue(h-(a._valueMax()-a._valueMin())/5);break;case d.ui.keyCode.UP:case d.ui.keyCode.RIGHT:if(h===a._valueMax())return;g=a._trimAlignValue(h+o);break;case d.ui.keyCode.DOWN:case d.ui.keyCode.LEFT:if(h===a._valueMin())return;g=a._trimAlignValue(h-o)}a._slide(b,
f,g);return e}}).keyup(function(b){var e=d(this).data("index.ui-slider-handle");if(a._keySliding)a._keySliding=!1,a._stop(b,e),a._change(b,e),d(this).removeClass("ui-state-active")});this._refreshValue();this._animateOff=!1},destroy:function(){this.handles.remove();this.range.remove();this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-slider-disabled ui-widget ui-widget-content ui-corner-all").removeData("slider").unbind(".slider");this._mouseDestroy();return this},_mouseCapture:function(a){var b=
this.options,e,f,h,g,i;if(b.disabled)return!1;this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()};this.elementOffset=this.element.offset();e=this._normValueFromMouse({x:a.pageX,y:a.pageY});f=this._valueMax()-this._valueMin()+1;g=this;this.handles.each(function(a){var b=Math.abs(e-g.values(a));f>b&&(f=b,h=d(this),i=a)});b.range===!0&&this.values(1)===b.min&&(i+=1,h=d(this.handles[i]));if(this._start(a,i)===!1)return!1;this._mouseSliding=!0;g._handleIndex=i;h.addClass("ui-state-active").focus();
b=h.offset();this._clickOffset=!d(a.target).parents().andSelf().is(".ui-slider-handle")?{left:0,top:0}:{left:a.pageX-b.left-h.width()/2,top:a.pageY-b.top-h.height()/2-(parseInt(h.css("borderTopWidth"),10)||0)-(parseInt(h.css("borderBottomWidth"),10)||0)+(parseInt(h.css("marginTop"),10)||0)};this.handles.hasClass("ui-state-hover")||this._slide(a,i,e);return this._animateOff=!0},_mouseStart:function(){return!0},_mouseDrag:function(a){var b=this._normValueFromMouse({x:a.pageX,y:a.pageY});this._slide(a,
this._handleIndex,b);return!1},_mouseStop:function(a){this.handles.removeClass("ui-state-active");this._mouseSliding=!1;this._stop(a,this._handleIndex);this._change(a,this._handleIndex);this._clickOffset=this._handleIndex=null;return this._animateOff=!1},_detectOrientation:function(){this.orientation=this.options.orientation==="vertical"?"vertical":"horizontal"},_normValueFromMouse:function(a){var b;this.orientation==="horizontal"?(b=this.elementSize.width,a=a.x-this.elementOffset.left-(this._clickOffset?
this._clickOffset.left:0)):(b=this.elementSize.height,a=a.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0));b=a/b;b>1&&(b=1);b<0&&(b=0);this.orientation==="vertical"&&(b=1-b);a=this._valueMax()-this._valueMin();return this._trimAlignValue(this._valueMin()+b*a)},_start:function(a,b){var d={handle:this.handles[b],value:this.value()};if(this.options.values&&this.options.values.length)d.value=this.values(b),d.values=this.values();return this._trigger("start",a,d)},_slide:function(a,
b,d){var f;if(this.options.values&&this.options.values.length){f=this.values(b?0:1);if(this.options.values.length===2&&this.options.range===!0&&(b===0&&d>f||b===1&&d<f))d=f;d!==this.values(b)&&(f=this.values(),f[b]=d,a=this._trigger("slide",a,{handle:this.handles[b],value:d,values:f}),this.values(b?0:1),a!==!1&&this.values(b,d,!0))}else d!==this.value()&&(a=this._trigger("slide",a,{handle:this.handles[b],value:d}),a!==!1&&this.value(d))},_stop:function(a,b){var d={handle:this.handles[b],value:this.value()};
if(this.options.values&&this.options.values.length)d.value=this.values(b),d.values=this.values();this._trigger("stop",a,d)},_change:function(a,b){if(!this._keySliding&&!this._mouseSliding){var d={handle:this.handles[b],value:this.value()};if(this.options.values&&this.options.values.length)d.value=this.values(b),d.values=this.values();this._trigger("change",a,d)}},value:function(a){if(arguments.length)this.options.value=this._trimAlignValue(a),this._refreshValue(),this._change(null,0);else return this._value()},
values:function(a,b){var e,f,h;if(arguments.length>1)this.options.values[a]=this._trimAlignValue(b),this._refreshValue(),this._change(null,a);else if(arguments.length)if(d.isArray(arguments[0])){e=this.options.values;f=arguments[0];for(h=0;h<e.length;h+=1)e[h]=this._trimAlignValue(f[h]),this._change(null,h);this._refreshValue()}else return this.options.values&&this.options.values.length?this._values(a):this.value();else return this._values()},_setOption:function(a,b){var e,f=0;if(d.isArray(this.options.values))f=
this.options.values.length;d.Widget.prototype._setOption.apply(this,arguments);switch(a){case "disabled":b?(this.handles.filter(".ui-state-focus").blur(),this.handles.removeClass("ui-state-hover"),this.handles.propAttr("disabled",!0),this.element.addClass("ui-disabled")):(this.handles.propAttr("disabled",!1),this.element.removeClass("ui-disabled"));break;case "orientation":this._detectOrientation();this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation);
this._refreshValue();break;case "value":this._animateOff=!0;this._refreshValue();this._change(null,0);this._animateOff=!1;break;case "values":this._animateOff=!0;this._refreshValue();for(e=0;e<f;e+=1)this._change(null,e);this._animateOff=!1}},_value:function(){var a=this.options.value;return a=this._trimAlignValue(a)},_values:function(a){var b,d;if(arguments.length)b=this.options.values[a],b=this._trimAlignValue(b);else{b=this.options.values.slice();for(d=0;d<b.length;d+=1)b[d]=this._trimAlignValue(b[d])}return b},
_trimAlignValue:function(a){if(a<=this._valueMin())return this._valueMin();if(a>=this._valueMax())return this._valueMax();var b=this.options.step>0?this.options.step:1,d=(a-this._valueMin())%b;a-=d;Math.abs(d)*2>=b&&(a+=d>0?b:-b);return parseFloat(a.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max},_refreshValue:function(){var a=this.options.range,b=this.options,e=this,f=!this._animateOff?b.animate:!1,h,g={},i,j,k,l;if(this.options.values&&this.options.values.length)this.handles.each(function(a){h=
(e.values(a)-e._valueMin())/(e._valueMax()-e._valueMin())*100;g[e.orientation==="horizontal"?"left":"bottom"]=h+"%";d(this).stop(1,1)[f?"animate":"css"](g,b.animate);if(e.options.range===!0)if(e.orientation==="horizontal"){if(a===0)e.range.stop(1,1)[f?"animate":"css"]({left:h+"%"},b.animate);if(a===1)e.range[f?"animate":"css"]({width:h-i+"%"},{queue:!1,duration:b.animate})}else{if(a===0)e.range.stop(1,1)[f?"animate":"css"]({bottom:h+"%"},b.animate);if(a===1)e.range[f?"animate":"css"]({height:h-i+
"%"},{queue:!1,duration:b.animate})}i=h});else{j=this.value();k=this._valueMin();l=this._valueMax();h=l!==k?(j-k)/(l-k)*100:0;g[e.orientation==="horizontal"?"left":"bottom"]=h+"%";this.handle.stop(1,1)[f?"animate":"css"](g,b.animate);if(a==="min"&&this.orientation==="horizontal")this.range.stop(1,1)[f?"animate":"css"]({width:h+"%"},b.animate);if(a==="max"&&this.orientation==="horizontal")this.range[f?"animate":"css"]({width:100-h+"%"},{queue:!1,duration:b.animate});if(a==="min"&&this.orientation===
"vertical")this.range.stop(1,1)[f?"animate":"css"]({height:h+"%"},b.animate);if(a==="max"&&this.orientation==="vertical")this.range[f?"animate":"css"]({height:100-h+"%"},{queue:!1,duration:b.animate})}}});d.extend(d.ui.slider,{version:"1.8.16"})})(jQuery);
(function(d){d.widget("ui.sortable",d.ui.mouse,{widgetEventPrefix:"sort",options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1E3},_create:function(){var a=this.options;this.containerCache={};this.element.addClass("ui-sortable");this.refresh();
this.floating=this.items.length?a.axis==="x"||/left|right/.test(this.items[0].item.css("float"))||/inline|table-cell/.test(this.items[0].item.css("display")):!1;this.offset=this.element.offset();this._mouseInit()},destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled").removeData("sortable").unbind(".sortable");this._mouseDestroy();for(var a=this.items.length-1;a>=0;a--)this.items[a].item.removeData("sortable-item");return this},_setOption:function(a,b){a==="disabled"?(this.options[a]=
b,this.widget()[b?"addClass":"removeClass"]("ui-sortable-disabled")):d.Widget.prototype._setOption.apply(this,arguments)},_mouseCapture:function(a,b){if(this.reverting)return!1;if(this.options.disabled||this.options.type=="static")return!1;this._refreshItems(a);var e=null,f=this;d(a.target).parents().each(function(){if(d.data(this,"sortable-item")==f)return e=d(this),!1});d.data(a.target,"sortable-item")==f&&(e=d(a.target));if(!e)return!1;if(this.options.handle&&!b){var h=!1;d(this.options.handle,
e).find("*").andSelf().each(function(){this==a.target&&(h=!0)});if(!h)return!1}this.currentItem=e;this._removeCurrentsFromItems();return!0},_mouseStart:function(a,b,e){b=this.options;this.currentContainer=this;this.refreshPositions();this.helper=this._createHelper(a);this._cacheHelperProportions();this._cacheMargins();this.scrollParent=this.helper.scrollParent();this.offset=this.currentItem.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};this.helper.css("position",
"absolute");this.cssPosition=this.helper.css("position");d.extend(this.offset,{click:{left:a.pageX-this.offset.left,top:a.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this._generatePosition(a);this.originalPageX=a.pageX;this.originalPageY=a.pageY;b.cursorAt&&this._adjustOffsetFromHelper(b.cursorAt);this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]};this.helper[0]!=this.currentItem[0]&&this.currentItem.hide();
this._createPlaceholder();b.containment&&this._setContainment();if(b.cursor){if(d("body").css("cursor"))this._storedCursor=d("body").css("cursor");d("body").css("cursor",b.cursor)}if(b.opacity){if(this.helper.css("opacity"))this._storedOpacity=this.helper.css("opacity");this.helper.css("opacity",b.opacity)}if(b.zIndex){if(this.helper.css("zIndex"))this._storedZIndex=this.helper.css("zIndex");this.helper.css("zIndex",b.zIndex)}if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML")this.overflowOffset=
this.scrollParent.offset();this._trigger("start",a,this._uiHash());this._preserveHelperProportions||this._cacheHelperProportions();if(!e)for(e=this.containers.length-1;e>=0;e--)this.containers[e]._trigger("activate",a,this._uiHash(this));if(d.ui.ddmanager)d.ui.ddmanager.current=this;d.ui.ddmanager&&!b.dropBehaviour&&d.ui.ddmanager.prepareOffsets(this,a);this.dragging=!0;this.helper.addClass("ui-sortable-helper");this._mouseDrag(a);return!0},_mouseDrag:function(a){this.position=this._generatePosition(a);
this.positionAbs=this._convertPositionTo("absolute");if(!this.lastPositionAbs)this.lastPositionAbs=this.positionAbs;if(this.options.scroll){var b=this.options,e=!1;if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"){if(this.overflowOffset.top+this.scrollParent[0].offsetHeight-a.pageY<b.scrollSensitivity)this.scrollParent[0].scrollTop=e=this.scrollParent[0].scrollTop+b.scrollSpeed;else if(a.pageY-this.overflowOffset.top<b.scrollSensitivity)this.scrollParent[0].scrollTop=e=this.scrollParent[0].scrollTop-
b.scrollSpeed;if(this.overflowOffset.left+this.scrollParent[0].offsetWidth-a.pageX<b.scrollSensitivity)this.scrollParent[0].scrollLeft=e=this.scrollParent[0].scrollLeft+b.scrollSpeed;else if(a.pageX-this.overflowOffset.left<b.scrollSensitivity)this.scrollParent[0].scrollLeft=e=this.scrollParent[0].scrollLeft-b.scrollSpeed}else a.pageY-d(document).scrollTop()<b.scrollSensitivity?e=d(document).scrollTop(d(document).scrollTop()-b.scrollSpeed):d(window).height()-(a.pageY-d(document).scrollTop())<b.scrollSensitivity&&
(e=d(document).scrollTop(d(document).scrollTop()+b.scrollSpeed)),a.pageX-d(document).scrollLeft()<b.scrollSensitivity?e=d(document).scrollLeft(d(document).scrollLeft()-b.scrollSpeed):d(window).width()-(a.pageX-d(document).scrollLeft())<b.scrollSensitivity&&(e=d(document).scrollLeft(d(document).scrollLeft()+b.scrollSpeed));e!==!1&&d.ui.ddmanager&&!b.dropBehaviour&&d.ui.ddmanager.prepareOffsets(this,a)}this.positionAbs=this._convertPositionTo("absolute");if(!this.options.axis||this.options.axis!="y")this.helper[0].style.left=
this.position.left+"px";if(!this.options.axis||this.options.axis!="x")this.helper[0].style.top=this.position.top+"px";for(b=this.items.length-1;b>=0;b--){var e=this.items[b],f=e.item[0],h=this._intersectsWithPointer(e);if(h&&f!=this.currentItem[0]&&this.placeholder[h==1?"next":"prev"]()[0]!=f&&!d.ui.contains(this.placeholder[0],f)&&(this.options.type=="semi-dynamic"?!d.ui.contains(this.element[0],f):1)){this.direction=h==1?"down":"up";if(this.options.tolerance=="pointer"||this._intersectsWithSides(e))this._rearrange(a,
e);else break;this._trigger("change",a,this._uiHash());break}}this._contactContainers(a);d.ui.ddmanager&&d.ui.ddmanager.drag(this,a);this._trigger("sort",a,this._uiHash());this.lastPositionAbs=this.positionAbs;return!1},_mouseStop:function(a,b){if(a){d.ui.ddmanager&&!this.options.dropBehaviour&&d.ui.ddmanager.drop(this,a);if(this.options.revert){var e=this,f=e.placeholder.offset();e.reverting=!0;d(this.helper).animate({left:f.left-this.offset.parent.left-e.margins.left+(this.offsetParent[0]==document.body?
0:this.offsetParent[0].scrollLeft),top:f.top-this.offset.parent.top-e.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){e._clear(a)})}else this._clear(a,b);return!1}},cancel:function(){if(this.dragging){this._mouseUp({target:null});this.options.helper=="original"?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var a=this.containers.length-1;a>=0;a--)if(this.containers[a]._trigger("deactivate",
null,this._uiHash(this)),this.containers[a].containerCache.over)this.containers[a]._trigger("out",null,this._uiHash(this)),this.containers[a].containerCache.over=0}this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.options.helper!="original"&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),d.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?d(this.domPosition.prev).after(this.currentItem):
d(this.domPosition.parent).prepend(this.currentItem));return this},serialize:function(a){var b=this._getItemsAsjQuery(a&&a.connected),e=[],a=a||{};d(b).each(function(){var b=(d(a.item||this).attr(a.attribute||"id")||"").match(a.expression||/(.+)[-=_](.+)/);b&&e.push((a.key||b[1]+"[]")+"="+(a.key&&a.expression?b[1]:b[2]))});!e.length&&a.key&&e.push(a.key+"=");return e.join("&")},toArray:function(a){var b=this._getItemsAsjQuery(a&&a.connected),e=[],a=a||{};b.each(function(){e.push(d(a.item||this).attr(a.attribute||
"id")||"")});return e},_intersectsWith:function(a){var b=this.positionAbs.left,d=b+this.helperProportions.width,f=this.positionAbs.top,h=f+this.helperProportions.height,g=a.left,i=g+a.width,j=a.top,k=j+a.height,l=this.offset.click.top,m=this.offset.click.left;return this.options.tolerance=="pointer"||this.options.forcePointerForContainers||this.options.tolerance!="pointer"&&this.helperProportions[this.floating?"width":"height"]>a[this.floating?"width":"height"]?f+l>j&&f+l<k&&b+m>g&&b+m<i:g<b+this.helperProportions.width/
2&&d-this.helperProportions.width/2<i&&j<f+this.helperProportions.height/2&&h-this.helperProportions.height/2<k},_intersectsWithPointer:function(a){var b=d.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,a.top,a.height),a=d.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,a.left,a.width),b=b&&a,a=this._getDragVerticalDirection(),e=this._getDragHorizontalDirection();return!b?!1:this.floating?e&&e=="right"||a=="down"?2:1:a&&(a=="down"?2:1)},_intersectsWithSides:function(a){var b=
d.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,a.top+a.height/2,a.height),a=d.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,a.left+a.width/2,a.width),e=this._getDragVerticalDirection(),f=this._getDragHorizontalDirection();return this.floating&&f?f=="right"&&a||f=="left"&&!a:e&&(e=="down"&&b||e=="up"&&!b)},_getDragVerticalDirection:function(){var a=this.positionAbs.top-this.lastPositionAbs.top;return a!=0&&(a>0?"down":"up")},_getDragHorizontalDirection:function(){var a=this.positionAbs.left-
this.lastPositionAbs.left;return a!=0&&(a>0?"right":"left")},refresh:function(a){this._refreshItems(a);this.refreshPositions();return this},_connectWith:function(){var a=this.options;return a.connectWith.constructor==String?[a.connectWith]:a.connectWith},_getItemsAsjQuery:function(a){var b=[],e=[],f=this._connectWith();if(f&&a)for(a=f.length-1;a>=0;a--)for(var h=d(f[a]),g=h.length-1;g>=0;g--){var i=d.data(h[g],"sortable");i&&i!=this&&!i.options.disabled&&e.push([d.isFunction(i.options.items)?i.options.items.call(i.element):
d(i.options.items,i.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),i])}e.push([d.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):d(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);for(a=e.length-1;a>=0;a--)e[a][0].each(function(){b.push(this)});return d(b)},_removeCurrentsFromItems:function(){for(var a=this.currentItem.find(":data(sortable-item)"),b=0;b<this.items.length;b++)for(var d=
0;d<a.length;d++)a[d]==this.items[b].item[0]&&this.items.splice(b,1)},_refreshItems:function(a){this.items=[];this.containers=[this];var b=this.items,e=[[d.isFunction(this.options.items)?this.options.items.call(this.element[0],a,{item:this.currentItem}):d(this.options.items,this.element),this]],f=this._connectWith();if(f)for(var h=f.length-1;h>=0;h--)for(var g=d(f[h]),i=g.length-1;i>=0;i--){var j=d.data(g[i],"sortable");j&&j!=this&&!j.options.disabled&&(e.push([d.isFunction(j.options.items)?j.options.items.call(j.element[0],
a,{item:this.currentItem}):d(j.options.items,j.element),j]),this.containers.push(j))}for(h=e.length-1;h>=0;h--){a=e[h][1];f=e[h][0];i=0;for(g=f.length;i<g;i++)j=d(f[i]),j.data("sortable-item",a),b.push({item:j,instance:a,width:0,height:0,left:0,top:0})}},refreshPositions:function(a){if(this.offsetParent&&this.helper)this.offset.parent=this._getParentOffset();for(var b=this.items.length-1;b>=0;b--){var e=this.items[b];if(!(e.instance!=this.currentContainer&&this.currentContainer&&e.item[0]!=this.currentItem[0])){var f=
this.options.toleranceElement?d(this.options.toleranceElement,e.item):e.item;if(!a)e.width=f.outerWidth(),e.height=f.outerHeight();f=f.offset();e.left=f.left;e.top=f.top}}if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(b=this.containers.length-1;b>=0;b--)f=this.containers[b].element.offset(),this.containers[b].containerCache.left=f.left,this.containers[b].containerCache.top=f.top,this.containers[b].containerCache.width=this.containers[b].element.outerWidth(),
this.containers[b].containerCache.height=this.containers[b].element.outerHeight();return this},_createPlaceholder:function(a){var b=a||this,e=b.options;if(!e.placeholder||e.placeholder.constructor==String){var f=e.placeholder;e.placeholder={element:function(){var a=d(document.createElement(b.currentItem[0].nodeName)).addClass(f||b.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];if(!f)a.style.visibility="hidden";return a},update:function(a,d){if(!f||e.forcePlaceholderSize)d.height()||
d.height(b.currentItem.innerHeight()-parseInt(b.currentItem.css("paddingTop")||0,10)-parseInt(b.currentItem.css("paddingBottom")||0,10)),d.width()||d.width(b.currentItem.innerWidth()-parseInt(b.currentItem.css("paddingLeft")||0,10)-parseInt(b.currentItem.css("paddingRight")||0,10))}}}b.placeholder=d(e.placeholder.element.call(b.element,b.currentItem));b.currentItem.after(b.placeholder);e.placeholder.update(b,b.placeholder)},_contactContainers:function(a){for(var b=null,e=null,f=this.containers.length-
1;f>=0;f--)if(!d.ui.contains(this.currentItem[0],this.containers[f].element[0]))if(this._intersectsWith(this.containers[f].containerCache)){if(!b||!d.ui.contains(this.containers[f].element[0],b.element[0]))b=this.containers[f],e=f}else if(this.containers[f].containerCache.over)this.containers[f]._trigger("out",a,this._uiHash(this)),this.containers[f].containerCache.over=0;if(b)if(this.containers.length===1)this.containers[e]._trigger("over",a,this._uiHash(this)),this.containers[e].containerCache.over=
1;else if(this.currentContainer!=this.containers[e]){for(var b=1E4,f=null,h=this.positionAbs[this.containers[e].floating?"left":"top"],g=this.items.length-1;g>=0;g--)if(d.ui.contains(this.containers[e].element[0],this.items[g].item[0])){var i=this.items[g][this.containers[e].floating?"left":"top"];Math.abs(i-h)<b&&(b=Math.abs(i-h),f=this.items[g])}if(f||this.options.dropOnEmpty)this.currentContainer=this.containers[e],f?this._rearrange(a,f,null,!0):this._rearrange(a,null,this.containers[e].element,
!0),this._trigger("change",a,this._uiHash()),this.containers[e]._trigger("change",a,this._uiHash(this)),this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[e]._trigger("over",a,this._uiHash(this)),this.containers[e].containerCache.over=1}},_createHelper:function(a){var b=this.options,a=d.isFunction(b.helper)?d(b.helper.apply(this.element[0],[a,this.currentItem])):b.helper=="clone"?this.currentItem.clone():this.currentItem;a.parents("body").length||d(b.appendTo!=
"parent"?b.appendTo:this.currentItem[0].parentNode)[0].appendChild(a[0]);if(a[0]==this.currentItem[0])this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")};(a[0].style.width==""||b.forceHelperSize)&&a.width(this.currentItem.width());(a[0].style.height==""||b.forceHelperSize)&&a.height(this.currentItem.height());return a},_adjustOffsetFromHelper:function(a){typeof a==
"string"&&(a=a.split(" "));d.isArray(a)&&(a={left:+a[0],top:+a[1]||0});if("left"in a)this.offset.click.left=a.left+this.margins.left;if("right"in a)this.offset.click.left=this.helperProportions.width-a.right+this.margins.left;if("top"in a)this.offset.click.top=a.top+this.margins.top;if("bottom"in a)this.offset.click.top=this.helperProportions.height-a.bottom+this.margins.top},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var a=this.offsetParent.offset();this.cssPosition==
"absolute"&&this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],this.offsetParent[0])&&(a.left+=this.scrollParent.scrollLeft(),a.top+=this.scrollParent.scrollTop());if(this.offsetParent[0]==document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&d.browser.msie)a={top:0,left:0};return{top:a.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:a.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition==
"relative"){var a=this.currentItem.position();return{top:a.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:a.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},
_setContainment:function(){var a=this.options;if(a.containment=="parent")a.containment=this.helper[0].parentNode;if(a.containment=="document"||a.containment=="window")this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,d(a.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(d(a.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-
this.margins.top];if(!/^(document|window|parent)$/.test(a.containment)){var b=d(a.containment)[0],a=d(a.containment).offset(),e=d(b).css("overflow")!="hidden";this.containment=[a.left+(parseInt(d(b).css("borderLeftWidth"),10)||0)+(parseInt(d(b).css("paddingLeft"),10)||0)-this.margins.left,a.top+(parseInt(d(b).css("borderTopWidth"),10)||0)+(parseInt(d(b).css("paddingTop"),10)||0)-this.margins.top,a.left+(e?Math.max(b.scrollWidth,b.offsetWidth):b.offsetWidth)-(parseInt(d(b).css("borderLeftWidth"),10)||
0)-(parseInt(d(b).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,a.top+(e?Math.max(b.scrollHeight,b.offsetHeight):b.offsetHeight)-(parseInt(d(b).css("borderTopWidth"),10)||0)-(parseInt(d(b).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(a,b){if(!b)b=this.position;var e=a=="absolute"?1:-1,f=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],this.offsetParent[0]))?
this.offsetParent:this.scrollParent,h=/(html|body)/i.test(f[0].tagName);return{top:b.top+this.offset.relative.top*e+this.offset.parent.top*e-(d.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():h?0:f.scrollTop())*e),left:b.left+this.offset.relative.left*e+this.offset.parent.left*e-(d.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():h?0:f.scrollLeft())*e)}},_generatePosition:function(a){var b=
this.options,e=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&d.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,f=/(html|body)/i.test(e[0].tagName);if(this.cssPosition=="relative"&&!(this.scrollParent[0]!=document&&this.scrollParent[0]!=this.offsetParent[0]))this.offset.relative=this._getRelativeOffset();var h=a.pageX,g=a.pageY;this.originalPosition&&(this.containment&&(a.pageX-this.offset.click.left<this.containment[0]&&(h=this.containment[0]+
this.offset.click.left),a.pageY-this.offset.click.top<this.containment[1]&&(g=this.containment[1]+this.offset.click.top),a.pageX-this.offset.click.left>this.containment[2]&&(h=this.containment[2]+this.offset.click.left),a.pageY-this.offset.click.top>this.containment[3]&&(g=this.containment[3]+this.offset.click.top)),b.grid&&(g=this.originalPageY+Math.round((g-this.originalPageY)/b.grid[1])*b.grid[1],g=this.containment?!(g-this.offset.click.top<this.containment[1]||g-this.offset.click.top>this.containment[3])?
g:!(g-this.offset.click.top<this.containment[1])?g-b.grid[1]:g+b.grid[1]:g,h=this.originalPageX+Math.round((h-this.originalPageX)/b.grid[0])*b.grid[0],h=this.containment?!(h-this.offset.click.left<this.containment[0]||h-this.offset.click.left>this.containment[2])?h:!(h-this.offset.click.left<this.containment[0])?h-b.grid[0]:h+b.grid[0]:h));return{top:g-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(d.browser.safari&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollTop():
f?0:e.scrollTop()),left:h-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(d.browser.safari&&this.cssPosition=="fixed"?0:this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():f?0:e.scrollLeft())}},_rearrange:function(a,b,d,f){d?d[0].appendChild(this.placeholder[0]):b.item[0].parentNode.insertBefore(this.placeholder[0],this.direction=="down"?b.item[0]:b.item[0].nextSibling);this.counter=this.counter?++this.counter:1;var h=this,g=this.counter;window.setTimeout(function(){g==
h.counter&&h.refreshPositions(!f)},0)},_clear:function(a,b){this.reverting=!1;var e=[];!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem);this._noFinalSort=null;if(this.helper[0]==this.currentItem[0]){for(var f in this._storedCSS)if(this._storedCSS[f]=="auto"||this._storedCSS[f]=="static")this._storedCSS[f]="";this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();this.fromOutside&&!b&&e.push(function(a){this._trigger("receive",
a,this._uiHash(this.fromOutside))});(this.fromOutside||this.domPosition.prev!=this.currentItem.prev().not(".ui-sortable-helper")[0]||this.domPosition.parent!=this.currentItem.parent()[0])&&!b&&e.push(function(a){this._trigger("update",a,this._uiHash())});if(!d.ui.contains(this.element[0],this.currentItem[0])){b||e.push(function(a){this._trigger("remove",a,this._uiHash())});for(f=this.containers.length-1;f>=0;f--)d.ui.contains(this.containers[f].element[0],this.currentItem[0])&&!b&&(e.push(function(a){return function(b){a._trigger("receive",
b,this._uiHash(this))}}.call(this,this.containers[f])),e.push(function(a){return function(b){a._trigger("update",b,this._uiHash(this))}}.call(this,this.containers[f])))}for(f=this.containers.length-1;f>=0;f--)if(b||e.push(function(a){return function(b){a._trigger("deactivate",b,this._uiHash(this))}}.call(this,this.containers[f])),this.containers[f].containerCache.over)e.push(function(a){return function(b){a._trigger("out",b,this._uiHash(this))}}.call(this,this.containers[f])),this.containers[f].containerCache.over=
0;this._storedCursor&&d("body").css("cursor",this._storedCursor);this._storedOpacity&&this.helper.css("opacity",this._storedOpacity);this._storedZIndex&&this.helper.css("zIndex",this._storedZIndex=="auto"?"":this._storedZIndex);this.dragging=!1;if(this.cancelHelperRemoval){if(!b){this._trigger("beforeStop",a,this._uiHash());for(f=0;f<e.length;f++)e[f].call(this,a);this._trigger("stop",a,this._uiHash())}return!1}b||this._trigger("beforeStop",a,this._uiHash());this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
this.helper[0]!=this.currentItem[0]&&this.helper.remove();this.helper=null;if(!b){for(f=0;f<e.length;f++)e[f].call(this,a);this._trigger("stop",a,this._uiHash())}this.fromOutside=!1;return!0},_trigger:function(){d.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(a){var b=a||this;return{helper:b.helper,placeholder:b.placeholder||d([]),position:b.position,originalPosition:b.originalPosition,offset:b.positionAbs,item:b.currentItem,sender:a?a.element:null}}});d.extend(d.ui.sortable,
{version:"1.8.16"})})(jQuery);
(function(d,a){var b=0,e=0;d.widget("ui.tabs",{options:{add:null,ajaxOptions:null,cache:!1,cookie:null,collapsible:!1,disable:null,disabled:[],enable:null,event:"click",fx:null,idPrefix:"ui-tabs-",load:null,panelTemplate:"<div></div>",remove:null,select:null,show:null,spinner:"<em>Loading…</em>",tabTemplate:"<li><a href='#{href}'><span>#{label}</span></a></li>"},_create:function(){this._tabify(!0)},_setOption:function(a,b){a=="selected"?this.options.collapsible&&b==this.options.selected||this.select(b):
(this.options[a]=b,this._tabify())},_tabId:function(a){return a.title&&a.title.replace(/\s/g,"_").replace(/[^\w\u00c0-\uFFFF-]/g,"")||this.options.idPrefix+ ++b},_sanitizeSelector:function(a){return a.replace(/:/g,"\\:")},_cookie:function(){var a=this.cookie||(this.cookie=this.options.cookie.name||"ui-tabs-"+ ++e);return d.cookie.apply(null,[a].concat(d.makeArray(arguments)))},_ui:function(a,b){return{tab:a,panel:b,index:this.anchors.index(a)}},_cleanup:function(){this.lis.filter(".ui-state-processing").removeClass("ui-state-processing").find("span:data(label.tabs)").each(function(){var a=
d(this);a.html(a.data("label.tabs")).removeData("label.tabs")})},_tabify:function(b){function e(a,b){a.css("display","");!d.support.opacity&&b.opacity&&a[0].style.removeAttribute("filter")}var g=this,i=this.options,j=/^#.+/;this.list=this.element.find("ol,ul").eq(0);this.lis=d(" > li:has(a[href])",this.list);this.anchors=this.lis.map(function(){return d("a",this)[0]});this.panels=d([]);this.anchors.each(function(a,b){var e=d(b).attr("href"),f=e.split("#")[0],h;if(f&&(f===location.toString().split("#")[0]||
(h=d("base")[0])&&f===h.href))e=b.hash,b.href=e;j.test(e)?g.panels=g.panels.add(g.element.find(g._sanitizeSelector(e))):e&&e!=="#"?(d.data(b,"href.tabs",e),d.data(b,"load.tabs",e.replace(/#.*$/,"")),e=g._tabId(b),b.href="#"+e,f=g.element.find("#"+e),f.length||(f=d(i.panelTemplate).attr("id",e).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").insertAfter(g.panels[a-1]||g.list),f.data("destroy.tabs",!0)),g.panels=g.panels.add(f)):i.disabled.push(a)});if(b){this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all");
this.list.addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.lis.addClass("ui-state-default ui-corner-top");this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom");if(i.selected===a){location.hash&&this.anchors.each(function(a,b){if(b.hash==location.hash)return i.selected=a,!1});if(typeof i.selected!=="number"&&i.cookie)i.selected=parseInt(g._cookie(),10);if(typeof i.selected!=="number"&&this.lis.filter(".ui-tabs-selected").length)i.selected=
this.lis.index(this.lis.filter(".ui-tabs-selected"));i.selected=i.selected||(this.lis.length?0:-1)}else if(i.selected===null)i.selected=-1;i.selected=i.selected>=0&&this.anchors[i.selected]||i.selected<0?i.selected:0;i.disabled=d.unique(i.disabled.concat(d.map(this.lis.filter(".ui-state-disabled"),function(a){return g.lis.index(a)}))).sort();d.inArray(i.selected,i.disabled)!=-1&&i.disabled.splice(d.inArray(i.selected,i.disabled),1);this.panels.addClass("ui-tabs-hide");this.lis.removeClass("ui-tabs-selected ui-state-active");
i.selected>=0&&this.anchors.length&&(g.element.find(g._sanitizeSelector(g.anchors[i.selected].hash)).removeClass("ui-tabs-hide"),this.lis.eq(i.selected).addClass("ui-tabs-selected ui-state-active"),g.element.queue("tabs",function(){g._trigger("show",null,g._ui(g.anchors[i.selected],g.element.find(g._sanitizeSelector(g.anchors[i.selected].hash))[0]))}),this.load(i.selected));d(window).bind("unload",function(){g.lis.add(g.anchors).unbind(".tabs");g.lis=g.anchors=g.panels=null})}else i.selected=this.lis.index(this.lis.filter(".ui-tabs-selected"));
this.element[i.collapsible?"addClass":"removeClass"]("ui-tabs-collapsible");i.cookie&&this._cookie(i.selected,i.cookie);for(var b=0,k;k=this.lis[b];b++)d(k)[d.inArray(b,i.disabled)!=-1&&!d(k).hasClass("ui-tabs-selected")?"addClass":"removeClass"]("ui-state-disabled");i.cache===!1&&this.anchors.removeData("cache.tabs");this.lis.add(this.anchors).unbind(".tabs");if(i.event!=="mouseover"){var l=function(a,b){b.is(":not(.ui-state-disabled)")&&b.addClass("ui-state-"+a)};this.lis.bind("mouseover.tabs",
function(){l("hover",d(this))});this.lis.bind("mouseout.tabs",function(){d(this).removeClass("ui-state-hover")});this.anchors.bind("focus.tabs",function(){l("focus",d(this).closest("li"))});this.anchors.bind("blur.tabs",function(){d(this).closest("li").removeClass("ui-state-focus")})}var m,o;if(i.fx)d.isArray(i.fx)?(m=i.fx[0],o=i.fx[1]):m=o=i.fx;var p=o?function(a,b){d(a).closest("li").addClass("ui-tabs-selected ui-state-active");b.hide().removeClass("ui-tabs-hide").animate(o,o.duration||"normal",
function(){e(b,o);g._trigger("show",null,g._ui(a,b[0]))})}:function(a,b){d(a).closest("li").addClass("ui-tabs-selected ui-state-active");b.removeClass("ui-tabs-hide");g._trigger("show",null,g._ui(a,b[0]))},n=m?function(a,b){b.animate(m,m.duration||"normal",function(){g.lis.removeClass("ui-tabs-selected ui-state-active");b.addClass("ui-tabs-hide");e(b,m);g.element.dequeue("tabs")})}:function(a,b){g.lis.removeClass("ui-tabs-selected ui-state-active");b.addClass("ui-tabs-hide");g.element.dequeue("tabs")};
this.anchors.bind(i.event+".tabs",function(){var a=this,b=d(a).closest("li"),e=g.panels.filter(":not(.ui-tabs-hide)"),f=g.element.find(g._sanitizeSelector(a.hash));if(b.hasClass("ui-tabs-selected")&&!i.collapsible||b.hasClass("ui-state-disabled")||b.hasClass("ui-state-processing")||g.panels.filter(":animated").length||g._trigger("select",null,g._ui(this,f[0]))===!1)return this.blur(),!1;i.selected=g.anchors.index(this);g.abort();if(i.collapsible)if(b.hasClass("ui-tabs-selected"))return i.selected=
-1,i.cookie&&g._cookie(i.selected,i.cookie),g.element.queue("tabs",function(){n(a,e)}).dequeue("tabs"),this.blur(),!1;else if(!e.length)return i.cookie&&g._cookie(i.selected,i.cookie),g.element.queue("tabs",function(){p(a,f)}),g.load(g.anchors.index(this)),this.blur(),!1;i.cookie&&g._cookie(i.selected,i.cookie);if(f.length)e.length&&g.element.queue("tabs",function(){n(a,e)}),g.element.queue("tabs",function(){p(a,f)}),g.load(g.anchors.index(this));else throw"jQuery UI Tabs: Mismatching fragment identifier.";
d.browser.msie&&this.blur()});this.anchors.bind("click.tabs",function(){return!1})},_getIndex:function(a){typeof a=="string"&&(a=this.anchors.index(this.anchors.filter("[href$="+a+"]")));return a},destroy:function(){var a=this.options;this.abort();this.element.unbind(".tabs").removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible").removeData("tabs");this.list.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.anchors.each(function(){var a=
d.data(this,"href.tabs");if(a)this.href=a;var b=d(this).unbind(".tabs");d.each(["href","load","cache"],function(a,d){b.removeData(d+".tabs")})});this.lis.unbind(".tabs").add(this.panels).each(function(){d.data(this,"destroy.tabs")?d(this).remove():d(this).removeClass("ui-state-default ui-corner-top ui-tabs-selected ui-state-active ui-state-hover ui-state-focus ui-state-disabled ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide")});a.cookie&&this._cookie(null,a.cookie);return this},add:function(b,
e,g){if(g===a)g=this.anchors.length;var i=this,j=this.options,e=d(j.tabTemplate.replace(/#\{href\}/g,b).replace(/#\{label\}/g,e)),b=!b.indexOf("#")?b.replace("#",""):this._tabId(d("a",e)[0]);e.addClass("ui-state-default ui-corner-top").data("destroy.tabs",!0);var k=i.element.find("#"+b);k.length||(k=d(j.panelTemplate).attr("id",b).data("destroy.tabs",!0));k.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide");g>=this.lis.length?(e.appendTo(this.list),k.appendTo(this.list[0].parentNode)):
(e.insertBefore(this.lis[g]),k.insertBefore(this.panels[g]));j.disabled=d.map(j.disabled,function(a){return a>=g?++a:a});this._tabify();if(this.anchors.length==1)j.selected=0,e.addClass("ui-tabs-selected ui-state-active"),k.removeClass("ui-tabs-hide"),this.element.queue("tabs",function(){i._trigger("show",null,i._ui(i.anchors[0],i.panels[0]))}),this.load(0);this._trigger("add",null,this._ui(this.anchors[g],this.panels[g]));return this},remove:function(a){var a=this._getIndex(a),b=this.options,e=this.lis.eq(a).remove(),
i=this.panels.eq(a).remove();e.hasClass("ui-tabs-selected")&&this.anchors.length>1&&this.select(a+(a+1<this.anchors.length?1:-1));b.disabled=d.map(d.grep(b.disabled,function(b){return b!=a}),function(b){return b>=a?--b:b});this._tabify();this._trigger("remove",null,this._ui(e.find("a")[0],i[0]));return this},enable:function(a){var a=this._getIndex(a),b=this.options;if(d.inArray(a,b.disabled)!=-1)return this.lis.eq(a).removeClass("ui-state-disabled"),b.disabled=d.grep(b.disabled,function(b){return b!=
a}),this._trigger("enable",null,this._ui(this.anchors[a],this.panels[a])),this},disable:function(a){var a=this._getIndex(a),b=this.options;a!=b.selected&&(this.lis.eq(a).addClass("ui-state-disabled"),b.disabled.push(a),b.disabled.sort(),this._trigger("disable",null,this._ui(this.anchors[a],this.panels[a])));return this},select:function(a){a=this._getIndex(a);if(a==-1)if(this.options.collapsible&&this.options.selected!=-1)a=this.options.selected;else return this;this.anchors.eq(a).trigger(this.options.event+
".tabs");return this},load:function(a){var a=this._getIndex(a),b=this,e=this.options,i=this.anchors.eq(a)[0],j=d.data(i,"load.tabs");this.abort();if(!j||this.element.queue("tabs").length!==0&&d.data(i,"cache.tabs"))this.element.dequeue("tabs");else{this.lis.eq(a).addClass("ui-state-processing");if(e.spinner){var k=d("span",i);k.data("label.tabs",k.html()).html(e.spinner)}this.xhr=d.ajax(d.extend({},e.ajaxOptions,{url:j,success:function(j,m){b.element.find(b._sanitizeSelector(i.hash)).html(j);b._cleanup();
e.cache&&d.data(i,"cache.tabs",!0);b._trigger("load",null,b._ui(b.anchors[a],b.panels[a]));try{e.ajaxOptions.success(j,m)}catch(o){}},error:function(d,j){b._cleanup();b._trigger("load",null,b._ui(b.anchors[a],b.panels[a]));try{e.ajaxOptions.error(d,j,a,i)}catch(o){}}}));b.element.dequeue("tabs");return this}},abort:function(){this.element.queue([]);this.panels.stop(!1,!0);this.element.queue("tabs",this.element.queue("tabs").splice(-2,2));this.xhr&&(this.xhr.abort(),delete this.xhr);this._cleanup();
return this},url:function(a,b){this.anchors.eq(a).removeData("cache.tabs").data("load.tabs",b);return this},length:function(){return this.anchors.length}});d.extend(d.ui.tabs,{version:"1.8.16"});d.extend(d.ui.tabs.prototype,{rotation:null,rotate:function(a,b){var d=this,e=this.options,j=d._rotate||(d._rotate=function(b){clearTimeout(d.rotation);d.rotation=setTimeout(function(){var a=e.selected;d.select(++a<d.anchors.length?a:0)},a);b&&b.stopPropagation()}),k=d._unrotate||(d._unrotate=!b?function(a){a.clientX&&
d.rotate(null)}:function(){t=e.selected;j()});a?(this.element.bind("tabsshow",j),this.anchors.bind(e.event+".tabs",k),j()):(clearTimeout(d.rotation),this.element.unbind("tabsshow",j),this.anchors.unbind(e.event+".tabs",k),delete this._rotate,delete this._unrotate);return this}})})(jQuery);
jQuery.effects||function(d,a){function b(a){var b;return a&&a.constructor==Array&&a.length==3?a:(b=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(a))?[parseInt(b[1],10),parseInt(b[2],10),parseInt(b[3],10)]:(b=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(a))?[parseFloat(b[1])*2.55,parseFloat(b[2])*2.55,parseFloat(b[3])*2.55]:(b=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(a))?[parseInt(b[1],16),parseInt(b[2],
16),parseInt(b[3],16)]:(b=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(a))?[parseInt(b[1]+b[1],16),parseInt(b[2]+b[2],16),parseInt(b[3]+b[3],16)]:/rgba\(0, 0, 0, 0\)/.exec(a)?j.transparent:j[d.trim(a).toLowerCase()]}function e(){var a=document.defaultView?document.defaultView.getComputedStyle(this,null):this.currentStyle,b={},d,e;if(a&&a.length&&a[0]&&a[a[0]])for(var f=a.length;f--;)d=a[f],typeof a[d]=="string"&&(e=d.replace(/\-(\w)/g,function(a,b){return b.toUpperCase()}),b[e]=a[d]);else for(d in a)typeof a[d]===
"string"&&(b[d]=a[d]);return b}function f(a){var b,e;for(b in a)e=a[b],(e==null||d.isFunction(e)||b in l||/scrollbar/.test(b)||!/color/i.test(b)&&isNaN(parseFloat(e)))&&delete a[b];return a}function h(a,b){var d={_:0},e;for(e in b)a[e]!=b[e]&&(d[e]=b[e]);return d}function g(a,b,e,f){if(typeof a=="object")f=b,e=null,b=a,a=b.effect;d.isFunction(b)&&(f=b,e=null,b={});if(typeof b=="number"||d.fx.speeds[b])f=e,e=b,b={};d.isFunction(e)&&(f=e,e=null);b=b||{};e=e||b.duration;e=d.fx.off?0:typeof e=="number"?
e:e in d.fx.speeds?d.fx.speeds[e]:d.fx.speeds._default;f=f||b.complete;return[a,b,e,f]}function i(a){return!a||typeof a==="number"||d.fx.speeds[a]?!0:typeof a==="string"&&!d.effects[a]?!0:!1}d.effects={};d.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","borderColor","color","outlineColor"],function(a,e){d.fx.step[e]=function(a){if(!a.colorInit){var f;f=a.elem;var g=e,h;do{h=d.curCSS(f,g);if(h!=""&&h!="transparent"||d.nodeName(f,"body"))break;g="backgroundColor"}while(f=
f.parentNode);f=b(h);a.start=f;a.end=b(a.end);a.colorInit=!0}a.elem.style[e]="rgb("+Math.max(Math.min(parseInt(a.pos*(a.end[0]-a.start[0])+a.start[0],10),255),0)+","+Math.max(Math.min(parseInt(a.pos*(a.end[1]-a.start[1])+a.start[1],10),255),0)+","+Math.max(Math.min(parseInt(a.pos*(a.end[2]-a.start[2])+a.start[2],10),255),0)+")"}});var j={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],
darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],
maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]},k=["add","remove","toggle"],l={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};d.effects.animateClass=function(a,b,g,i){d.isFunction(g)&&(i=g,g=null);return this.queue(function(){var j=d(this),l=j.attr("style")||
" ",x=f(e.call(this)),q,w=j.attr("class");d.each(k,function(b,d){if(a[d])j[d+"Class"](a[d])});q=f(e.call(this));j.attr("class",w);j.animate(h(x,q),{queue:!1,duration:b,easing:g,complete:function(){d.each(k,function(b,d){if(a[d])j[d+"Class"](a[d])});typeof j.attr("style")=="object"?(j.attr("style").cssText="",j.attr("style").cssText=l):j.attr("style",l);i&&i.apply(this,arguments);d.dequeue(this)}})})};d.fn.extend({_addClass:d.fn.addClass,addClass:function(a,b,e,f){return b?d.effects.animateClass.apply(this,
[{add:a},b,e,f]):this._addClass(a)},_removeClass:d.fn.removeClass,removeClass:function(a,b,e,f){return b?d.effects.animateClass.apply(this,[{remove:a},b,e,f]):this._removeClass(a)},_toggleClass:d.fn.toggleClass,toggleClass:function(b,e,f,g,h){return typeof e=="boolean"||e===a?f?d.effects.animateClass.apply(this,[e?{add:b}:{remove:b},f,g,h]):this._toggleClass(b,e):d.effects.animateClass.apply(this,[{toggle:b},e,f,g])},switchClass:function(a,b,e,f,g){return d.effects.animateClass.apply(this,[{add:b,
remove:a},e,f,g])}});d.extend(d.effects,{version:"1.8.16",save:function(a,b){for(var d=0;d<b.length;d++)b[d]!==null&&a.data("ec.storage."+b[d],a[0].style[b[d]])},restore:function(a,b){for(var d=0;d<b.length;d++)b[d]!==null&&a.css(b[d],a.data("ec.storage."+b[d]))},setMode:function(a,b){b=="toggle"&&(b=a.is(":hidden")?"show":"hide");return b},getBaseline:function(a,b){var d,e;switch(a[0]){case "top":d=0;break;case "middle":d=0.5;break;case "bottom":d=1;break;default:d=a[0]/b.height}switch(a[1]){case "left":e=
0;break;case "center":e=0.5;break;case "right":e=1;break;default:e=a[1]/b.width}return{x:e,y:d}},createWrapper:function(a){if(a.parent().is(".ui-effects-wrapper"))return a.parent();var b={width:a.outerWidth(!0),height:a.outerHeight(!0),"float":a.css("float")},e=d("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),f=document.activeElement;a.wrap(e);(a[0]===f||d.contains(a[0],f))&&d(f).focus();e=a.parent();a.css("position")==
"static"?(e.css({position:"relative"}),a.css({position:"relative"})):(d.extend(b,{position:a.css("position"),zIndex:a.css("z-index")}),d.each(["top","left","bottom","right"],function(d,e){b[e]=a.css(e);isNaN(parseInt(b[e],10))&&(b[e]="auto")}),a.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"}));return e.css(b).show()},removeWrapper:function(a){var b,e=document.activeElement;return a.parent().is(".ui-effects-wrapper")?(b=a.parent().replaceWith(a),(a[0]===e||d.contains(a[0],e))&&d(e).focus(),
b):a},setTransition:function(a,b,e,f){f=f||{};d.each(b,function(b,d){unit=a.cssUnit(d);unit[0]>0&&(f[d]=unit[0]*e+unit[1])});return f}});d.fn.extend({effect:function(a,b,e,f){var h=g.apply(this,arguments),i={options:h[1],duration:h[2],callback:h[3]},h=i.options.mode,j=d.effects[a];return d.fx.off||!j?h?this[h](i.duration,i.callback):this.each(function(){i.callback&&i.callback.call(this)}):j.call(this,i)},_show:d.fn.show,show:function(a){if(i(a))return this._show.apply(this,arguments);else{var b=g.apply(this,
arguments);b[1].mode="show";return this.effect.apply(this,b)}},_hide:d.fn.hide,hide:function(a){if(i(a))return this._hide.apply(this,arguments);else{var b=g.apply(this,arguments);b[1].mode="hide";return this.effect.apply(this,b)}},__toggle:d.fn.toggle,toggle:function(a){if(i(a)||typeof a==="boolean"||d.isFunction(a))return this.__toggle.apply(this,arguments);else{var b=g.apply(this,arguments);b[1].mode="toggle";return this.effect.apply(this,b)}},cssUnit:function(a){var b=this.css(a),e=[];d.each(["em",
"px","%","pt"],function(a,d){b.indexOf(d)>0&&(e=[parseFloat(b),d])});return e}});d.easing.jswing=d.easing.swing;d.extend(d.easing,{def:"easeOutQuad",swing:function(a,b,e,f,g){return d.easing[d.easing.def](a,b,e,f,g)},easeInQuad:function(a,b,d,e,f){return e*(b/=f)*b+d},easeOutQuad:function(a,b,d,e,f){return-e*(b/=f)*(b-2)+d},easeInOutQuad:function(a,b,d,e,f){return(b/=f/2)<1?e/2*b*b+d:-e/2*(--b*(b-2)-1)+d},easeInCubic:function(a,b,d,e,f){return e*(b/=f)*b*b+d},easeOutCubic:function(a,b,d,e,f){return e*
((b=b/f-1)*b*b+1)+d},easeInOutCubic:function(a,b,d,e,f){return(b/=f/2)<1?e/2*b*b*b+d:e/2*((b-=2)*b*b+2)+d},easeInQuart:function(a,b,d,e,f){return e*(b/=f)*b*b*b+d},easeOutQuart:function(a,b,d,e,f){return-e*((b=b/f-1)*b*b*b-1)+d},easeInOutQuart:function(a,b,d,e,f){return(b/=f/2)<1?e/2*b*b*b*b+d:-e/2*((b-=2)*b*b*b-2)+d},easeInQuint:function(a,b,d,e,f){return e*(b/=f)*b*b*b*b+d},easeOutQuint:function(a,b,d,e,f){return e*((b=b/f-1)*b*b*b*b+1)+d},easeInOutQuint:function(a,b,d,e,f){return(b/=f/2)<1?e/2*
b*b*b*b*b+d:e/2*((b-=2)*b*b*b*b+2)+d},easeInSine:function(a,b,d,e,f){return-e*Math.cos(b/f*(Math.PI/2))+e+d},easeOutSine:function(a,b,d,e,f){return e*Math.sin(b/f*(Math.PI/2))+d},easeInOutSine:function(a,b,d,e,f){return-e/2*(Math.cos(Math.PI*b/f)-1)+d},easeInExpo:function(a,b,d,e,f){return b==0?d:e*Math.pow(2,10*(b/f-1))+d},easeOutExpo:function(a,b,d,e,f){return b==f?d+e:e*(-Math.pow(2,-10*b/f)+1)+d},easeInOutExpo:function(a,b,d,e,f){return b==0?d:b==f?d+e:(b/=f/2)<1?e/2*Math.pow(2,10*(b-1))+d:e/
2*(-Math.pow(2,-10*--b)+2)+d},easeInCirc:function(a,b,d,e,f){return-e*(Math.sqrt(1-(b/=f)*b)-1)+d},easeOutCirc:function(a,b,d,e,f){return e*Math.sqrt(1-(b=b/f-1)*b)+d},easeInOutCirc:function(a,b,d,e,f){return(b/=f/2)<1?-e/2*(Math.sqrt(1-b*b)-1)+d:e/2*(Math.sqrt(1-(b-=2)*b)+1)+d},easeInElastic:function(a,b,d,e,f){var a=1.70158,g=0,h=e;if(b==0)return d;if((b/=f)==1)return d+e;g||(g=f*0.3);h<Math.abs(e)?(h=e,a=g/4):a=g/(2*Math.PI)*Math.asin(e/h);return-(h*Math.pow(2,10*(b-=1))*Math.sin((b*f-a)*2*Math.PI/
g))+d},easeOutElastic:function(a,b,d,e,f){var a=1.70158,g=0,h=e;if(b==0)return d;if((b/=f)==1)return d+e;g||(g=f*0.3);h<Math.abs(e)?(h=e,a=g/4):a=g/(2*Math.PI)*Math.asin(e/h);return h*Math.pow(2,-10*b)*Math.sin((b*f-a)*2*Math.PI/g)+e+d},easeInOutElastic:function(a,b,d,e,f){var a=1.70158,g=0,h=e;if(b==0)return d;if((b/=f/2)==2)return d+e;g||(g=f*0.3*1.5);h<Math.abs(e)?(h=e,a=g/4):a=g/(2*Math.PI)*Math.asin(e/h);return b<1?-0.5*h*Math.pow(2,10*(b-=1))*Math.sin((b*f-a)*2*Math.PI/g)+d:h*Math.pow(2,-10*
(b-=1))*Math.sin((b*f-a)*2*Math.PI/g)*0.5+e+d},easeInBack:function(b,d,e,f,g,h){h==a&&(h=1.70158);return f*(d/=g)*d*((h+1)*d-h)+e},easeOutBack:function(b,d,e,f,g,h){h==a&&(h=1.70158);return f*((d=d/g-1)*d*((h+1)*d+h)+1)+e},easeInOutBack:function(b,d,e,f,h,g){g==a&&(g=1.70158);return(d/=h/2)<1?f/2*d*d*(((g*=1.525)+1)*d-g)+e:f/2*((d-=2)*d*(((g*=1.525)+1)*d+g)+2)+e},easeInBounce:function(a,b,e,f,g){return f-d.easing.easeOutBounce(a,g-b,0,f,g)+e},easeOutBounce:function(a,b,d,e,f){return(b/=f)<1/2.75?
e*7.5625*b*b+d:b<2/2.75?e*(7.5625*(b-=1.5/2.75)*b+0.75)+d:b<2.5/2.75?e*(7.5625*(b-=2.25/2.75)*b+0.9375)+d:e*(7.5625*(b-=2.625/2.75)*b+0.984375)+d},easeInOutBounce:function(a,b,e,f,g){return b<g/2?d.easing.easeInBounce(a,b*2,0,f,g)*0.5+e:d.easing.easeOutBounce(a,b*2-g,0,f,g)*0.5+f*0.5+e}})}(jQuery);
(function(d){d.effects.blind=function(a){return this.queue(function(){var b=d(this),e=["position","top","bottom","left","right"],f=d.effects.setMode(b,a.options.mode||"hide"),h=a.options.direction||"vertical";d.effects.save(b,e);b.show();var g=d.effects.createWrapper(b).css({overflow:"hidden"}),i=h=="vertical"?"height":"width",h=h=="vertical"?g.height():g.width();f=="show"&&g.css(i,0);var j={};j[i]=f=="show"?h:0;g.animate(j,a.duration,a.options.easing,function(){f=="hide"&&b.hide();d.effects.restore(b,
e);d.effects.removeWrapper(b);a.callback&&a.callback.apply(b[0],arguments);b.dequeue()})})}})(jQuery);
(function(d){d.effects.bounce=function(a){return this.queue(function(){var b=d(this),e=["position","top","bottom","left","right"],f=d.effects.setMode(b,a.options.mode||"effect"),h=a.options.direction||"up",g=a.options.distance||20,i=a.options.times||5,j=a.duration||250;/show|hide/.test(f)&&e.push("opacity");d.effects.save(b,e);b.show();d.effects.createWrapper(b);var k=h=="up"||h=="down"?"top":"left",h=h=="up"||h=="left"?"pos":"neg",g=a.options.distance||(k=="top"?b.outerHeight({margin:!0})/3:b.outerWidth({margin:!0})/
3);f=="show"&&b.css("opacity",0).css(k,h=="pos"?-g:g);f=="hide"&&(g/=i*2);f!="hide"&&i--;if(f=="show"){var l={opacity:1};l[k]=(h=="pos"?"+=":"-=")+g;b.animate(l,j/2,a.options.easing);g/=2;i--}for(l=0;l<i;l++){var m={},o={};m[k]=(h=="pos"?"-=":"+=")+g;o[k]=(h=="pos"?"+=":"-=")+g;b.animate(m,j/2,a.options.easing).animate(o,j/2,a.options.easing);g=f=="hide"?g*2:g/2}f=="hide"?(l={opacity:0},l[k]=(h=="pos"?"-=":"+=")+g,b.animate(l,j/2,a.options.easing,function(){b.hide();d.effects.restore(b,e);d.effects.removeWrapper(b);
a.callback&&a.callback.apply(this,arguments)})):(m={},o={},m[k]=(h=="pos"?"-=":"+=")+g,o[k]=(h=="pos"?"+=":"-=")+g,b.animate(m,j/2,a.options.easing).animate(o,j/2,a.options.easing,function(){d.effects.restore(b,e);d.effects.removeWrapper(b);a.callback&&a.callback.apply(this,arguments)}));b.queue("fx",function(){b.dequeue()});b.dequeue()})}})(jQuery);
(function(d){d.effects.clip=function(a){return this.queue(function(){var b=d(this),e=["position","top","bottom","left","right","height","width"],f=d.effects.setMode(b,a.options.mode||"hide"),h=a.options.direction||"vertical";d.effects.save(b,e);b.show();var g=d.effects.createWrapper(b).css({overflow:"hidden"}),g=b[0].tagName=="IMG"?g:b,i={size:h=="vertical"?"height":"width",position:h=="vertical"?"top":"left"},h=h=="vertical"?g.height():g.width();f=="show"&&(g.css(i.size,0),g.css(i.position,h/2));
var j={};j[i.size]=f=="show"?h:0;j[i.position]=f=="show"?0:h/2;g.animate(j,{queue:!1,duration:a.duration,easing:a.options.easing,complete:function(){f=="hide"&&b.hide();d.effects.restore(b,e);d.effects.removeWrapper(b);a.callback&&a.callback.apply(b[0],arguments);b.dequeue()}})})}})(jQuery);
(function(d){d.effects.drop=function(a){return this.queue(function(){var b=d(this),e=["position","top","bottom","left","right","opacity"],f=d.effects.setMode(b,a.options.mode||"hide"),h=a.options.direction||"left";d.effects.save(b,e);b.show();d.effects.createWrapper(b);var g=h=="up"||h=="down"?"top":"left",h=h=="up"||h=="left"?"pos":"neg",i=a.options.distance||(g=="top"?b.outerHeight({margin:!0})/2:b.outerWidth({margin:!0})/2);f=="show"&&b.css("opacity",0).css(g,h=="pos"?-i:i);var j={opacity:f=="show"?
1:0};j[g]=(f=="show"?h=="pos"?"+=":"-=":h=="pos"?"-=":"+=")+i;b.animate(j,{queue:!1,duration:a.duration,easing:a.options.easing,complete:function(){f=="hide"&&b.hide();d.effects.restore(b,e);d.effects.removeWrapper(b);a.callback&&a.callback.apply(this,arguments);b.dequeue()}})})}})(jQuery);
(function(d){d.effects.explode=function(a){return this.queue(function(){var b=a.options.pieces?Math.round(Math.sqrt(a.options.pieces)):3,e=a.options.pieces?Math.round(Math.sqrt(a.options.pieces)):3;a.options.mode=a.options.mode=="toggle"?d(this).is(":visible")?"hide":"show":a.options.mode;var f=d(this).show().css("visibility","hidden"),h=f.offset();h.top-=parseInt(f.css("marginTop"),10)||0;h.left-=parseInt(f.css("marginLeft"),10)||0;for(var g=f.outerWidth(!0),i=f.outerHeight(!0),j=0;j<b;j++)for(var k=
0;k<e;k++)f.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-k*(g/e),top:-j*(i/b)}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:g/e,height:i/b,left:h.left+k*(g/e)+(a.options.mode=="show"?(k-Math.floor(e/2))*(g/e):0),top:h.top+j*(i/b)+(a.options.mode=="show"?(j-Math.floor(b/2))*(i/b):0),opacity:a.options.mode=="show"?0:1}).animate({left:h.left+k*(g/e)+(a.options.mode=="show"?0:(k-Math.floor(e/2))*(g/e)),top:h.top+
j*(i/b)+(a.options.mode=="show"?0:(j-Math.floor(b/2))*(i/b)),opacity:a.options.mode=="show"?1:0},a.duration||500);setTimeout(function(){a.options.mode=="show"?f.css({visibility:"visible"}):f.css({visibility:"visible"}).hide();a.callback&&a.callback.apply(f[0]);f.dequeue();d("div.ui-effects-explode").remove()},a.duration||500)})}})(jQuery);
(function(d){d.effects.fade=function(a){return this.queue(function(){var b=d(this),e=d.effects.setMode(b,a.options.mode||"hide");b.animate({opacity:e},{queue:!1,duration:a.duration,easing:a.options.easing,complete:function(){a.callback&&a.callback.apply(this,arguments);b.dequeue()}})})}})(jQuery);
(function(d){d.effects.fold=function(a){return this.queue(function(){var b=d(this),e=["position","top","bottom","left","right"],f=d.effects.setMode(b,a.options.mode||"hide"),h=a.options.size||15,g=!!a.options.horizFirst,i=a.duration?a.duration/2:d.fx.speeds._default/2;d.effects.save(b,e);b.show();var j=d.effects.createWrapper(b).css({overflow:"hidden"}),k=f=="show"!=g,l=k?["width","height"]:["height","width"],k=k?[j.width(),j.height()]:[j.height(),j.width()],m=/([0-9]+)%/.exec(h);m&&(h=parseInt(m[1],
10)/100*k[f=="hide"?0:1]);f=="show"&&j.css(g?{height:0,width:h}:{height:h,width:0});g={};m={};g[l[0]]=f=="show"?k[0]:h;m[l[1]]=f=="show"?k[1]:0;j.animate(g,i,a.options.easing).animate(m,i,a.options.easing,function(){f=="hide"&&b.hide();d.effects.restore(b,e);d.effects.removeWrapper(b);a.callback&&a.callback.apply(b[0],arguments);b.dequeue()})})}})(jQuery);
(function(d){d.effects.highlight=function(a){return this.queue(function(){var b=d(this),e=["backgroundImage","backgroundColor","opacity"],f=d.effects.setMode(b,a.options.mode||"show"),h={backgroundColor:b.css("backgroundColor")};if(f=="hide")h.opacity=0;d.effects.save(b,e);b.show().css({backgroundImage:"none",backgroundColor:a.options.color||"#ffff99"}).animate(h,{queue:!1,duration:a.duration,easing:a.options.easing,complete:function(){f=="hide"&&b.hide();d.effects.restore(b,e);f=="show"&&!d.support.opacity&&
this.style.removeAttribute("filter");a.callback&&a.callback.apply(this,arguments);b.dequeue()}})})}})(jQuery);
(function(d){d.effects.pulsate=function(a){return this.queue(function(){var b=d(this),e=d.effects.setMode(b,a.options.mode||"show");times=(a.options.times||5)*2-1;duration=a.duration?a.duration/2:d.fx.speeds._default/2;isVisible=b.is(":visible");animateTo=0;isVisible||(b.css("opacity",0).show(),animateTo=1);(e=="hide"&&isVisible||e=="show"&&!isVisible)&×--;for(e=0;e<times;e++)b.animate({opacity:animateTo},duration,a.options.easing),animateTo=(animateTo+1)%2;b.animate({opacity:animateTo},duration,
a.options.easing,function(){animateTo==0&&b.hide();a.callback&&a.callback.apply(this,arguments)});b.queue("fx",function(){b.dequeue()}).dequeue()})}})(jQuery);
(function(d){d.effects.puff=function(a){return this.queue(function(){var b=d(this),e=d.effects.setMode(b,a.options.mode||"hide"),f=parseInt(a.options.percent,10)||150,h=f/100,g={height:b.height(),width:b.width()};d.extend(a.options,{fade:!0,mode:e,percent:e=="hide"?f:100,from:e=="hide"?g:{height:g.height*h,width:g.width*h}});b.effect("scale",a.options,a.duration,a.callback);b.dequeue()})};d.effects.scale=function(a){return this.queue(function(){var b=d(this),e=d.extend(!0,{},a.options),f=d.effects.setMode(b,
a.options.mode||"effect"),h=parseInt(a.options.percent,10)||(parseInt(a.options.percent,10)==0?0:f=="hide"?0:100),g=a.options.direction||"both",i=a.options.origin;if(f!="effect")e.origin=i||["middle","center"],e.restore=!0;i={height:b.height(),width:b.width()};b.from=a.options.from||(f=="show"?{height:0,width:0}:i);h={y:g!="horizontal"?h/100:1,x:g!="vertical"?h/100:1};b.to={height:i.height*h.y,width:i.width*h.x};if(a.options.fade){if(f=="show")b.from.opacity=0,b.to.opacity=1;if(f=="hide")b.from.opacity=
1,b.to.opacity=0}e.from=b.from;e.to=b.to;e.mode=f;b.effect("size",e,a.duration,a.callback);b.dequeue()})};d.effects.size=function(a){return this.queue(function(){var b=d(this),e=["position","top","bottom","left","right","width","height","overflow","opacity"],f=["position","top","bottom","left","right","overflow","opacity"],h=["width","height","overflow"],g=["fontSize"],i=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"],j=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"],
k=d.effects.setMode(b,a.options.mode||"effect"),l=a.options.restore||!1,m=a.options.scale||"both",o=a.options.origin,p={height:b.height(),width:b.width()};b.from=a.options.from||p;b.to=a.options.to||p;if(o)o=d.effects.getBaseline(o,p),b.from.top=(p.height-b.from.height)*o.y,b.from.left=(p.width-b.from.width)*o.x,b.to.top=(p.height-b.to.height)*o.y,b.to.left=(p.width-b.to.width)*o.x;var n={from:{y:b.from.height/p.height,x:b.from.width/p.width},to:{y:b.to.height/p.height,x:b.to.width/p.width}};if(m==
"box"||m=="both"){if(n.from.y!=n.to.y)e=e.concat(i),b.from=d.effects.setTransition(b,i,n.from.y,b.from),b.to=d.effects.setTransition(b,i,n.to.y,b.to);if(n.from.x!=n.to.x)e=e.concat(j),b.from=d.effects.setTransition(b,j,n.from.x,b.from),b.to=d.effects.setTransition(b,j,n.to.x,b.to)}if((m=="content"||m=="both")&&n.from.y!=n.to.y)e=e.concat(g),b.from=d.effects.setTransition(b,g,n.from.y,b.from),b.to=d.effects.setTransition(b,g,n.to.y,b.to);d.effects.save(b,l?e:f);b.show();d.effects.createWrapper(b);
b.css("overflow","hidden").css(b.from);if(m=="content"||m=="both")i=i.concat(["marginTop","marginBottom"]).concat(g),j=j.concat(["marginLeft","marginRight"]),h=e.concat(i).concat(j),b.find("*[width]").each(function(){child=d(this);l&&d.effects.save(child,h);var b={height:child.height(),width:child.width()};child.from={height:b.height*n.from.y,width:b.width*n.from.x};child.to={height:b.height*n.to.y,width:b.width*n.to.x};if(n.from.y!=n.to.y)child.from=d.effects.setTransition(child,i,n.from.y,child.from),
child.to=d.effects.setTransition(child,i,n.to.y,child.to);if(n.from.x!=n.to.x)child.from=d.effects.setTransition(child,j,n.from.x,child.from),child.to=d.effects.setTransition(child,j,n.to.x,child.to);child.css(child.from);child.animate(child.to,a.duration,a.options.easing,function(){l&&d.effects.restore(child,h)})});b.animate(b.to,{queue:!1,duration:a.duration,easing:a.options.easing,complete:function(){b.to.opacity===0&&b.css("opacity",b.from.opacity);k=="hide"&&b.hide();d.effects.restore(b,l?e:
f);d.effects.removeWrapper(b);a.callback&&a.callback.apply(this,arguments);b.dequeue()}})})}})(jQuery);
(function(d){d.effects.shake=function(a){return this.queue(function(){var b=d(this),e=["position","top","bottom","left","right"];d.effects.setMode(b,a.options.mode||"effect");var f=a.options.direction||"left",h=a.options.distance||20,g=a.options.times||3,i=a.duration||a.options.duration||140;d.effects.save(b,e);b.show();d.effects.createWrapper(b);var j=f=="up"||f=="down"?"top":"left",k=f=="up"||f=="left"?"pos":"neg",f={},l={},m={};f[j]=(k=="pos"?"-=":"+=")+h;l[j]=(k=="pos"?"+=":"-=")+h*2;m[j]=(k==
"pos"?"-=":"+=")+h*2;b.animate(f,i,a.options.easing);for(h=1;h<g;h++)b.animate(l,i,a.options.easing).animate(m,i,a.options.easing);b.animate(l,i,a.options.easing).animate(f,i/2,a.options.easing,function(){d.effects.restore(b,e);d.effects.removeWrapper(b);a.callback&&a.callback.apply(this,arguments)});b.queue("fx",function(){b.dequeue()});b.dequeue()})}})(jQuery);
(function(d){d.effects.slide=function(a){return this.queue(function(){var b=d(this),e=["position","top","bottom","left","right"],f=d.effects.setMode(b,a.options.mode||"show"),h=a.options.direction||"left";d.effects.save(b,e);b.show();d.effects.createWrapper(b).css({overflow:"hidden"});var g=h=="up"||h=="down"?"top":"left",h=h=="up"||h=="left"?"pos":"neg",i=a.options.distance||(g=="top"?b.outerHeight({margin:!0}):b.outerWidth({margin:!0}));f=="show"&&b.css(g,h=="pos"?isNaN(i)?"-"+i:-i:i);var j={};
j[g]=(f=="show"?h=="pos"?"+=":"-=":h=="pos"?"-=":"+=")+i;b.animate(j,{queue:!1,duration:a.duration,easing:a.options.easing,complete:function(){f=="hide"&&b.hide();d.effects.restore(b,e);d.effects.removeWrapper(b);a.callback&&a.callback.apply(this,arguments);b.dequeue()}})})}})(jQuery);
(function(d){d.effects.transfer=function(a){return this.queue(function(){var b=d(this),e=d(a.options.to),f=e.offset(),e={top:f.top,left:f.left,height:e.innerHeight(),width:e.innerWidth()},f=b.offset(),h=d('<div class="ui-effects-transfer"></div>').appendTo(document.body).addClass(a.options.className).css({top:f.top,left:f.left,height:b.innerHeight(),width:b.innerWidth(),position:"absolute"}).animate(e,a.duration,a.options.easing,function(){h.remove();a.callback&&a.callback.apply(b[0],arguments);b.dequeue()})})}})(jQuery);
|
/*
* jQuery Cryptography Plug-in
* version: 1.0.0 (24 Sep 2008)
* copyright 2008 Scott Thompson http://www.itsyndicate.ca - [email protected]
* http://www.opensource.org/licenses/mit-license.php
*
* A set of functions to do some basic cryptography encoding/decoding
* I compiled from some javascripts I found into a jQuery plug-in.
* Thanks go out to the original authors.
*
* Changelog: 1.1.0
* - rewrote plugin to use only one item in the namespace
*
* --- Base64 Encoding and Decoding code was written by
*
* Base64 code from Tyler Akins -- http://rumkin.com
* and is placed in the public domain
*
*
* --- MD5 and SHA1 Functions based upon Paul Johnston's javascript libraries.
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*
* xTea Encrypt and Decrypt
* copyright 2000-2005 Chris Veness
* http://www.movable-type.co.uk
*
*
* Examples:
*
var md5 = $().crypt({method:"md5",source:$("#phrase").val()});
var sha1 = $().crypt({method:"sha1",source:$("#phrase").val()});
var b64 = $().crypt({method:"b64enc",source:$("#phrase").val()});
var b64dec = $().crypt({method:"b64dec",source:b64});
var xtea = $().crypt({method:"xteaenc",source:$("#phrase").val(),keyPass:$("#passPhrase").val()});
var xteadec = $().crypt({method:"xteadec",source:xtea,keyPass:$("#passPhrase").val()});
var xteab64 = $().crypt({method:"xteab64enc",source:$("#phrase").val(),keyPass:$("#passPhrase").val()});
var xteab64dec = $().crypt({method:"xteab64dec",source:xteab64,keyPass:$("#passPhrase").val()});
You can also pass source this way.
var md5 = $("#idOfSource").crypt({method:"md5"});
*
*/
(function(s){s.fn.crypt=function(m){function t(g){var i="",j,k,f,c,l,a,b=0;do j=g.source.charCodeAt(b++),k=g.source.charCodeAt(b++),f=g.source.charCodeAt(b++),c=j>>2,j=(j&3)<<4|k>>4,l=(k&15)<<2|f>>6,a=f&63,isNaN(k)?l=a=64:isNaN(f)&&(a=64),i+=g.b64Str.charAt(c)+g.b64Str.charAt(j)+g.b64Str.charAt(l)+g.b64Str.charAt(a);while(b<g.source.length);return i}function u(g){var i="",j,k,f,c,l,a=0;g.source=g.source.replace(/[^A-Za-z0-9!_-]/g,"");do j=g.b64Str.indexOf(g.source.charAt(a++)),k=g.b64Str.indexOf(g.source.charAt(a++)),
c=g.b64Str.indexOf(g.source.charAt(a++)),l=g.b64Str.indexOf(g.source.charAt(a++)),j=j<<2|k>>4,k=(k&15)<<4|c>>2,f=(c&3)<<6|l,i+=String.fromCharCode(j),64!=c&&(i+=String.fromCharCode(k)),64!=l&&(i+=String.fromCharCode(f));while(a<g.source.length);return i}function x(g){function i(c,f,a,b,d,e){c=o(o(f,c),o(b,e));return o(c<<d|c>>>32-d,a)}function j(c,f,a,b,d,e,h){return i(f&a|~f&b,c,f,d,e,h)}function k(c,f,a,b,d,e,h){return i(f&b|a&~b,c,f,d,e,h)}function f(c,f,a,b,d,e,h){return i(a^(f|~b),c,f,d,e,h)}
return function(c){for(var f=g.hexcase?"0123456789ABCDEF":"0123456789abcdef",a="",b=0;b<4*c.length;b++)a+=f.charAt(c[b>>2]>>8*(b%4)+4&15)+f.charAt(c[b>>2]>>8*(b%4)&15);return a}(function(c,g){c[g>>5]|=128<<g%32;c[(g+64>>>9<<4)+14]=g;for(var a=1732584193,b=-271733879,d=-1732584194,e=271733878,h=0;h<c.length;h+=16)var m=a,p=b,q=d,n=e,a=j(a,b,d,e,c[h+0],7,-680876936),e=j(e,a,b,d,c[h+1],12,-389564586),d=j(d,e,a,b,c[h+2],17,606105819),b=j(b,d,e,a,c[h+3],22,-1044525330),a=j(a,b,d,e,c[h+4],7,-176418897),
e=j(e,a,b,d,c[h+5],12,1200080426),d=j(d,e,a,b,c[h+6],17,-1473231341),b=j(b,d,e,a,c[h+7],22,-45705983),a=j(a,b,d,e,c[h+8],7,1770035416),e=j(e,a,b,d,c[h+9],12,-1958414417),d=j(d,e,a,b,c[h+10],17,-42063),b=j(b,d,e,a,c[h+11],22,-1990404162),a=j(a,b,d,e,c[h+12],7,1804603682),e=j(e,a,b,d,c[h+13],12,-40341101),d=j(d,e,a,b,c[h+14],17,-1502002290),b=j(b,d,e,a,c[h+15],22,1236535329),a=k(a,b,d,e,c[h+1],5,-165796510),e=k(e,a,b,d,c[h+6],9,-1069501632),d=k(d,e,a,b,c[h+11],14,643717713),b=k(b,d,e,a,c[h+0],20,-373897302),
a=k(a,b,d,e,c[h+5],5,-701558691),e=k(e,a,b,d,c[h+10],9,38016083),d=k(d,e,a,b,c[h+15],14,-660478335),b=k(b,d,e,a,c[h+4],20,-405537848),a=k(a,b,d,e,c[h+9],5,568446438),e=k(e,a,b,d,c[h+14],9,-1019803690),d=k(d,e,a,b,c[h+3],14,-187363961),b=k(b,d,e,a,c[h+8],20,1163531501),a=k(a,b,d,e,c[h+13],5,-1444681467),e=k(e,a,b,d,c[h+2],9,-51403784),d=k(d,e,a,b,c[h+7],14,1735328473),b=k(b,d,e,a,c[h+12],20,-1926607734),a=i(b^d^e,a,b,c[h+5],4,-378558),e=i(a^b^d,e,a,c[h+8],11,-2022574463),d=i(e^a^b,d,e,c[h+11],16,1839030562),
b=i(d^e^a,b,d,c[h+14],23,-35309556),a=i(b^d^e,a,b,c[h+1],4,-1530992060),e=i(a^b^d,e,a,c[h+4],11,1272893353),d=i(e^a^b,d,e,c[h+7],16,-155497632),b=i(d^e^a,b,d,c[h+10],23,-1094730640),a=i(b^d^e,a,b,c[h+13],4,681279174),e=i(a^b^d,e,a,c[h+0],11,-358537222),d=i(e^a^b,d,e,c[h+3],16,-722521979),b=i(d^e^a,b,d,c[h+6],23,76029189),a=i(b^d^e,a,b,c[h+9],4,-640364487),e=i(a^b^d,e,a,c[h+12],11,-421815835),d=i(e^a^b,d,e,c[h+15],16,530742520),b=i(d^e^a,b,d,c[h+2],23,-995338651),a=f(a,b,d,e,c[h+0],6,-198630844),e=
f(e,a,b,d,c[h+7],10,1126891415),d=f(d,e,a,b,c[h+14],15,-1416354905),b=f(b,d,e,a,c[h+5],21,-57434055),a=f(a,b,d,e,c[h+12],6,1700485571),e=f(e,a,b,d,c[h+3],10,-1894986606),d=f(d,e,a,b,c[h+10],15,-1051523),b=f(b,d,e,a,c[h+1],21,-2054922799),a=f(a,b,d,e,c[h+8],6,1873313359),e=f(e,a,b,d,c[h+15],10,-30611744),d=f(d,e,a,b,c[h+6],15,-1560198380),b=f(b,d,e,a,c[h+13],21,1309151649),a=f(a,b,d,e,c[h+4],6,-145523070),e=f(e,a,b,d,c[h+11],10,-1120210379),d=f(d,e,a,b,c[h+2],15,718787259),b=f(b,d,e,a,c[h+9],21,-343485551),
a=o(a,m),b=o(b,p),d=o(d,q),e=o(e,n);return[a,b,d,e]}(function(c){for(var f=[],a=(1<<g.chrsz)-1,b=0;b<c.length*g.chrsz;b+=g.chrsz)f[b>>5]|=(c.charCodeAt(b/g.chrsz)&a)<<b%32;return f}(g.source),g.source.length*g.chrsz))}function o(g,i){var j=(g&65535)+(i&65535);return(g>>16)+(i>>16)+(j>>16)<<16|j&65535}function y(g){return function(i){for(var j=g.hexcase?"0123456789ABCDEF":"0123456789abcdef",k="",f=0;f<4*i.length;f++)k+=j.charAt(i[f>>2]>>8*(3-f%4)+4&15)+j.charAt(i[f>>2]>>8*(3-f%4)&15);return k}(function(g,
j){g[j>>5]|=128<<24-j%32;g[(j+64>>9<<4)+15]=j;for(var k=Array(80),f=1732584193,c=-271733879,l=-1732584194,a=271733878,b=-1009589776,d=0;d<g.length;d+=16){for(var e=f,h=c,m=l,p=a,q=b,n=0;80>n;n++){k[n]=16>n?g[d+n]:(k[n-3]^k[n-8]^k[n-14]^k[n-16])<<1|(k[n-3]^k[n-8]^k[n-14]^k[n-16])>>>31;var r=f<<5|f>>>27,s;s=20>n?c&l|~c&a:40>n?c^l^a:60>n?c&l|c&a|l&a:c^l^a;r=o(o(r,s),o(o(b,k[n]),20>n?1518500249:40>n?1859775393:60>n?-1894007588:-899497514));b=a;a=l;l=c<<30|c>>>2;c=f;f=r}f=o(f,e);c=o(c,h);l=o(l,m);a=o(a,
p);b=o(b,q)}return[f,c,l,a,b]}(function(i){for(var j=[],k=(1<<g.chrsz)-1,f=0;f<i.length*g.chrsz;f+=g.chrsz)j[f>>5]|=(i.charCodeAt(f/g.chrsz)&k)<<32-g.chrsz-f%32;return j}(g.source),g.source.length*g.chrsz))}function v(g){var i=Array(2),j=Array(4),k="",f;g.source=escape(g.source);for(f=0;4>f;f++)j[f]=q(g.strKey.slice(4*f,4*(f+1)));for(f=0;f<g.source.length;f+=8){i[0]=q(g.source.slice(f,f+4));i[1]=q(g.source.slice(f+4,f+8));for(var c=i,l=c[0],a=c[1],b=0;84941944608!=b;)l+=(a<<4^a>>>5)+a^b+j[b&3],b+=
2654435769,a+=(l<<4^l>>>5)+l^b+j[b>>>11&3];c[0]=l;c[1]=a;k+=r(i[0])+r(i[1])}return z(k)}function w(g){var i=Array(2),j=Array(4),k="",f;for(f=0;4>f;f++)j[f]=q(g.strKey.slice(4*f,4*(f+1)));ciphertext=A(g.source);for(f=0;f<ciphertext.length;f+=8){i[0]=q(ciphertext.slice(f,f+4));i[1]=q(ciphertext.slice(f+4,f+8));for(var g=i,c=g[0],l=g[1],a=84941944608;0!=a;)l-=(c<<4^c>>>5)+c^a+j[a>>>11&3],a-=2654435769,c-=(l<<4^l>>>5)+l^a+j[a&3];g[0]=c;g[1]=l;k+=r(i[0])+r(i[1])}k=k.replace(/\0+$/,"");return unescape(k)}
function q(g){for(var i=0,j=0;4>j;j++)i|=g.charCodeAt(j)<<8*j;return isNaN(i)?0:i}function r(g){return String.fromCharCode(g&255,g>>8&255,g>>16&255,g>>24&255)}function z(g){return g.replace(/[\0\t\n\v\f\r\xa0'"!]/g,function(g){return"!"+g.charCodeAt(0)+"!"})}function A(g){return g.replace(/!\d\d?\d?!/g,function(g){return String.fromCharCode(g.slice(1,-1))})}m=s.extend({b64Str:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!-_",strKey:"123",method:"md5",source:"",chrsz:8,hexcase:0},
m);if(!m.source){var p=s(this);if(p.html())m.source=p.html();else if(p.val())m.source=p.val();else return alert("Please provide source text"),!1}if("md5"==m.method)return x(m);if("sha1"==m.method)return y(m);if("b64enc"==m.method)return t(m);if("b64dec"==m.method)return u(m);if("xteaenc"==m.method)return v(m);if("xteadec"==m.method)return w(m);if("xteab64enc"==m.method)return p=v(m),m.method="b64enc",m.source=p,t(m);if("xteab64dec"==m.method)return p=u(m),m.method="xteadec",m.source=p,w(m)}})(jQuery);
|
/* eslint-disable func-names */
const {
sampleUrls,
shortSampleUrls,
E2E_WAIT_TIME: WAIT_TIME,
E2E_PRESENT_WAIT_TIME: PRESENT_WAIT_TIME
} = require('../e2e_helper');
module.exports = {
after(browser) {
browser.end();
},
'Go to top page': browser => {
browser.page.index().navigate().waitForElementVisible('body', PRESENT_WAIT_TIME);
},
'Add musics': browser => {
browser.page
.index()
.log('add musics')
.setValue('@trackUrlField', sampleUrls.join(','))
.submitForm('@trackSubmitButton')
.waitForElementPresent('a.playlist-content:nth-child(5)', PRESENT_WAIT_TIME)
.assert.elementPresent('@playButton')
.assert.hasPlaylistLength(5)
.api.pause(WAIT_TIME);
},
'Play music': browser => {
browser.page
.index()
.moveToElement('@playerBlock', 10, 10)
.click('@playButton')
.waitForElementPresent('@pauseButton', PRESENT_WAIT_TIME)
.assert.elementPresent('@pauseButton')
.assert.hasPlaylistLength(5)
.assert.currentTrackNumEquals(1)
.assert.currentTitleEquals(1)
.api.pause(WAIT_TIME);
},
'Play next music': browser => {
browser.page
.index()
.click('@nextButton')
.waitForElementNotPresent('a.playlist-content:nth-child(5)', PRESENT_WAIT_TIME) // dequeue
.assert.elementPresent('@pauseButton')
.assert.hasPlaylistLength(4)
.assert.currentTrackNumEquals(1)
.assert.currentTitleEquals(1)
.api.pause(WAIT_TIME);
},
'Has play prev music button?': browser => {
browser.page.index().assert.cssClassPresent('@prevButton', 'deactivate');
},
'Stop music': browser => {
browser.page
.index()
.click('@pauseButton')
.waitForElementPresent('@playButton', PRESENT_WAIT_TIME)
.assert.elementPresent('@playButton')
.assert.hasPlaylistLength(4)
.assert.currentTrackNumEquals(1)
.assert.title('jukebox')
.api.pause(WAIT_TIME);
},
'Play specified music': browser => {
browser.page
.index()
.click('a.playlist-content:nth-child(3)')
.waitForElementPresent('@pauseButton', PRESENT_WAIT_TIME)
.assert.elementPresent('@pauseButton')
.assert.hasPlaylistLength(4)
.assert.currentTrackNumEquals(3)
.assert.currentTitleEquals(3)
.api.pause(WAIT_TIME);
},
'Delete current music': browser => {
browser.page
.index()
.click('a.playlist-content:nth-child(3) i[title=Delete]')
.waitForElementPresent('@playButton', PRESENT_WAIT_TIME)
.assert.elementPresent('@playButton')
.assert.hasPlaylistLength(3)
.assert.currentTrackNumEquals(3)
.assert.title('jukebox')
.api.pause(WAIT_TIME);
},
'Add short music': browser => {
browser.page
.index()
.setValue('@trackUrlField', shortSampleUrls[0])
.submitForm('@trackSubmitButton')
.waitForElementPresent('a.playlist-content:nth-child(4)', PRESENT_WAIT_TIME)
.assert.hasPlaylistLength(4);
},
'Play short music': browser => {
browser.page
.index()
.click('a.playlist-content:nth-child(4)')
.waitForElementPresent('@pauseButton', PRESENT_WAIT_TIME);
},
'Wait till end': browser => {
browser.page
.index()
.waitForElementNotPresent(
'.playlist-content:nth-child(4) .thumbnail-wrapper i',
PRESENT_WAIT_TIME
)
.assert.elementPresent('@playButton')
.assert.hasPlaylistLength(3);
},
'Clear playlist': browser => {
browser.page
.index()
.click('@openClearModalButton')
.waitForElementPresent('@clearModal', PRESENT_WAIT_TIME)
.click('@clearButton')
.waitForElementNotPresent('a.playlist-content', PRESENT_WAIT_TIME)
.assert.hasPlaylistLength(0)
.api.pause(WAIT_TIME);
}
};
|
/*!
* Bootstrap v3.3.7 (http://getbootstrap.com)
* Copyright 2011-2016 Twitter, Inc.
* Licensed under the MIT license
*/
if (typeof jQuery === 'undefined') {
throw new Error('Bootstrap\'s JavaScript requires jQuery')
}
+function ($) {
'use strict';
var version = $.fn.jquery.split(' ')[0].split('.')
if ((version[0] < 2 && version[1] < 9) || (version[0] == 1 && version[1] == 9 && version[2] < 1) || (version[0] > 3)) {
throw new Error('Bootstrap\'s JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4')
}
}(jQuery);
/* ========================================================================
* Bootstrap: transition.js v3.3.7
* http://getbootstrap.com/javascript/#transitions
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
WebkitTransition : 'webkitTransitionEnd',
MozTransition : 'transitionend',
OTransition : 'oTransitionEnd otransitionend',
transition : 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return { end: transEndEventNames[name] }
}
}
return false // explicit for ie8 ( ._.)
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function (duration) {
var called = false
var $el = this
$(this).one('bsTransitionEnd', function () { called = true })
var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
setTimeout(callback, duration)
return this
}
$(function () {
$.support.transition = transitionEnd()
if (!$.support.transition) return
$.event.special.bsTransitionEnd = {
bindType: $.support.transition.end,
delegateType: $.support.transition.end,
handle: function (e) {
if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments)
}
}
})
}(jQuery);
/* ========================================================================
* Bootstrap: alert.js v3.3.7
* http://getbootstrap.com/javascript/#alerts
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// ALERT CLASS DEFINITION
// ======================
var dismiss = '[data-dismiss="alert"]'
var Alert = function (el) {
$(el).on('click', dismiss, this.close)
}
Alert.VERSION = '3.3.7'
Alert.TRANSITION_DURATION = 150
Alert.prototype.close = function (e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector === '#' ? [] : selector)
if (e) e.preventDefault()
if (!$parent.length) {
$parent = $this.closest('.alert')
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented()) return
$parent.removeClass('in')
function removeElement() {
// detach from parent, fire event then clean up data
$parent.detach().trigger('closed.bs.alert').remove()
}
$.support.transition && $parent.hasClass('fade') ?
$parent
.one('bsTransitionEnd', removeElement)
.emulateTransitionEnd(Alert.TRANSITION_DURATION) :
removeElement()
}
// ALERT PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.alert')
if (!data) $this.data('bs.alert', (data = new Alert(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.alert
$.fn.alert = Plugin
$.fn.alert.Constructor = Alert
// ALERT NO CONFLICT
// =================
$.fn.alert.noConflict = function () {
$.fn.alert = old
return this
}
// ALERT DATA-API
// ==============
$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
}(jQuery);
/* ========================================================================
* Bootstrap: button.js v3.3.7
* http://getbootstrap.com/javascript/#buttons
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// BUTTON PUBLIC CLASS DEFINITION
// ==============================
var Button = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Button.DEFAULTS, options)
this.isLoading = false
}
Button.VERSION = '3.3.7'
Button.DEFAULTS = {
loadingText: 'loading...'
}
Button.prototype.setState = function (state) {
var d = 'disabled'
var $el = this.$element
var val = $el.is('input') ? 'val' : 'html'
var data = $el.data()
state += 'Text'
if (data.resetText == null) $el.data('resetText', $el[val]())
// push to event loop to allow forms to submit
setTimeout($.proxy(function () {
$el[val](data[state] == null ? this.options[state] : data[state])
if (state == 'loadingText') {
this.isLoading = true
$el.addClass(d).attr(d, d).prop(d, true)
} else if (this.isLoading) {
this.isLoading = false
$el.removeClass(d).removeAttr(d).prop(d, false)
}
}, this), 0)
}
Button.prototype.toggle = function () {
var changed = true
var $parent = this.$element.closest('[data-toggle="buttons"]')
if ($parent.length) {
var $input = this.$element.find('input')
if ($input.prop('type') == 'radio') {
if ($input.prop('checked')) changed = false
$parent.find('.active').removeClass('active')
this.$element.addClass('active')
} else if ($input.prop('type') == 'checkbox') {
if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false
this.$element.toggleClass('active')
}
$input.prop('checked', this.$element.hasClass('active'))
if (changed) $input.trigger('change')
} else {
this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
this.$element.toggleClass('active')
}
}
// BUTTON PLUGIN DEFINITION
// ========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.button')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.button', (data = new Button(this, options)))
if (option == 'toggle') data.toggle()
else if (option) data.setState(option)
})
}
var old = $.fn.button
$.fn.button = Plugin
$.fn.button.Constructor = Button
// BUTTON NO CONFLICT
// ==================
$.fn.button.noConflict = function () {
$.fn.button = old
return this
}
// BUTTON DATA-API
// ===============
$(document)
.on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) {
var $btn = $(e.target).closest('.btn')
Plugin.call($btn, 'toggle')
if (!($(e.target).is('input[type="radio"], input[type="checkbox"]'))) {
// Prevent double click on radios, and the double selections (so cancellation) on checkboxes
e.preventDefault()
// The target component still receive the focus
if ($btn.is('input,button')) $btn.trigger('focus')
else $btn.find('input:visible,button:visible').first().trigger('focus')
}
})
.on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) {
$(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type))
})
}(jQuery);
/* ========================================================================
* Bootstrap: carousel.js v3.3.7
* http://getbootstrap.com/javascript/#carousel
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// CAROUSEL CLASS DEFINITION
// =========================
var Carousel = function (element, options) {
this.$element = $(element)
this.$indicators = this.$element.find('.carousel-indicators')
this.options = options
this.paused = null
this.sliding = null
this.interval = null
this.$active = null
this.$items = null
this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this))
this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element
.on('mouseenter.bs.carousel', $.proxy(this.pause, this))
.on('mouseleave.bs.carousel', $.proxy(this.cycle, this))
}
Carousel.VERSION = '3.3.7'
Carousel.TRANSITION_DURATION = 600
Carousel.DEFAULTS = {
interval: 5000,
pause: 'hover',
wrap: true,
keyboard: true
}
Carousel.prototype.keydown = function (e) {
if (/input|textarea/i.test(e.target.tagName)) return
switch (e.which) {
case 37: this.prev(); break
case 39: this.next(); break
default: return
}
e.preventDefault()
}
Carousel.prototype.cycle = function (e) {
e || (this.paused = false)
this.interval && clearInterval(this.interval)
this.options.interval
&& !this.paused
&& (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
return this
}
Carousel.prototype.getItemIndex = function (item) {
this.$items = item.parent().children('.item')
return this.$items.index(item || this.$active)
}
Carousel.prototype.getItemForDirection = function (direction, active) {
var activeIndex = this.getItemIndex(active)
var willWrap = (direction == 'prev' && activeIndex === 0)
|| (direction == 'next' && activeIndex == (this.$items.length - 1))
if (willWrap && !this.options.wrap) return active
var delta = direction == 'prev' ? -1 : 1
var itemIndex = (activeIndex + delta) % this.$items.length
return this.$items.eq(itemIndex)
}
Carousel.prototype.to = function (pos) {
var that = this
var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active'))
if (pos > (this.$items.length - 1) || pos < 0) return
if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid"
if (activeIndex == pos) return this.pause().cycle()
return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos))
}
Carousel.prototype.pause = function (e) {
e || (this.paused = true)
if (this.$element.find('.next, .prev').length && $.support.transition) {
this.$element.trigger($.support.transition.end)
this.cycle(true)
}
this.interval = clearInterval(this.interval)
return this
}
Carousel.prototype.next = function () {
if (this.sliding) return
return this.slide('next')
}
Carousel.prototype.prev = function () {
if (this.sliding) return
return this.slide('prev')
}
Carousel.prototype.slide = function (type, next) {
var $active = this.$element.find('.item.active')
var $next = next || this.getItemForDirection(type, $active)
var isCycling = this.interval
var direction = type == 'next' ? 'left' : 'right'
var that = this
if ($next.hasClass('active')) return (this.sliding = false)
var relatedTarget = $next[0]
var slideEvent = $.Event('slide.bs.carousel', {
relatedTarget: relatedTarget,
direction: direction
})
this.$element.trigger(slideEvent)
if (slideEvent.isDefaultPrevented()) return
this.sliding = true
isCycling && this.pause()
if (this.$indicators.length) {
this.$indicators.find('.active').removeClass('active')
var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)])
$nextIndicator && $nextIndicator.addClass('active')
}
var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid"
if ($.support.transition && this.$element.hasClass('slide')) {
$next.addClass(type)
$next[0].offsetWidth // force reflow
$active.addClass(direction)
$next.addClass(direction)
$active
.one('bsTransitionEnd', function () {
$next.removeClass([type, direction].join(' ')).addClass('active')
$active.removeClass(['active', direction].join(' '))
that.sliding = false
setTimeout(function () {
that.$element.trigger(slidEvent)
}, 0)
})
.emulateTransitionEnd(Carousel.TRANSITION_DURATION)
} else {
$active.removeClass('active')
$next.addClass('active')
this.sliding = false
this.$element.trigger(slidEvent)
}
isCycling && this.cycle()
return this
}
// CAROUSEL PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.carousel')
var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option)
var action = typeof option == 'string' ? option : options.slide
if (!data) $this.data('bs.carousel', (data = new Carousel(this, options)))
if (typeof option == 'number') data.to(option)
else if (action) data[action]()
else if (options.interval) data.pause().cycle()
})
}
var old = $.fn.carousel
$.fn.carousel = Plugin
$.fn.carousel.Constructor = Carousel
// CAROUSEL NO CONFLICT
// ====================
$.fn.carousel.noConflict = function () {
$.fn.carousel = old
return this
}
// CAROUSEL DATA-API
// =================
var clickHandler = function (e) {
var href
var $this = $(this)
var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7
if (!$target.hasClass('carousel')) return
var options = $.extend({}, $target.data(), $this.data())
var slideIndex = $this.attr('data-slide-to')
if (slideIndex) options.interval = false
Plugin.call($target, options)
if (slideIndex) {
$target.data('bs.carousel').to(slideIndex)
}
e.preventDefault()
}
$(document)
.on('click.bs.carousel.data-api', '[data-slide]', clickHandler)
.on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler)
$(window).on('load', function () {
$('[data-ride="carousel"]').each(function () {
var $carousel = $(this)
Plugin.call($carousel, $carousel.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: collapse.js v3.3.7
* http://getbootstrap.com/javascript/#collapse
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
/* jshint latedef: false */
+function ($) {
'use strict';
// COLLAPSE PUBLIC CLASS DEFINITION
// ================================
var Collapse = function (element, options) {
this.$element = $(element)
this.options = $.extend({}, Collapse.DEFAULTS, options)
this.$trigger = $('[data-toggle="collapse"][href="#' + element.id + '"],' +
'[data-toggle="collapse"][data-target="#' + element.id + '"]')
this.transitioning = null
if (this.options.parent) {
this.$parent = this.getParent()
} else {
this.addAriaAndCollapsedClass(this.$element, this.$trigger)
}
if (this.options.toggle) this.toggle()
}
Collapse.VERSION = '3.3.7'
Collapse.TRANSITION_DURATION = 350
Collapse.DEFAULTS = {
toggle: true
}
Collapse.prototype.dimension = function () {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
Collapse.prototype.show = function () {
if (this.transitioning || this.$element.hasClass('in')) return
var activesData
var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing')
if (actives && actives.length) {
activesData = actives.data('bs.collapse')
if (activesData && activesData.transitioning) return
}
var startEvent = $.Event('show.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
if (actives && actives.length) {
Plugin.call(actives, 'hide')
activesData || actives.data('bs.collapse', null)
}
var dimension = this.dimension()
this.$element
.removeClass('collapse')
.addClass('collapsing')[dimension](0)
.attr('aria-expanded', true)
this.$trigger
.removeClass('collapsed')
.attr('aria-expanded', true)
this.transitioning = 1
var complete = function () {
this.$element
.removeClass('collapsing')
.addClass('collapse in')[dimension]('')
this.transitioning = 0
this.$element
.trigger('shown.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
var scrollSize = $.camelCase(['scroll', dimension].join('-'))
this.$element
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize])
}
Collapse.prototype.hide = function () {
if (this.transitioning || !this.$element.hasClass('in')) return
var startEvent = $.Event('hide.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
var dimension = this.dimension()
this.$element[dimension](this.$element[dimension]())[0].offsetHeight
this.$element
.addClass('collapsing')
.removeClass('collapse in')
.attr('aria-expanded', false)
this.$trigger
.addClass('collapsed')
.attr('aria-expanded', false)
this.transitioning = 1
var complete = function () {
this.transitioning = 0
this.$element
.removeClass('collapsing')
.addClass('collapse')
.trigger('hidden.bs.collapse')
}
if (!$.support.transition) return complete.call(this)
this.$element
[dimension](0)
.one('bsTransitionEnd', $.proxy(complete, this))
.emulateTransitionEnd(Collapse.TRANSITION_DURATION)
}
Collapse.prototype.toggle = function () {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
Collapse.prototype.getParent = function () {
return $(this.options.parent)
.find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]')
.each($.proxy(function (i, element) {
var $element = $(element)
this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element)
}, this))
.end()
}
Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) {
var isOpen = $element.hasClass('in')
$element.attr('aria-expanded', isOpen)
$trigger
.toggleClass('collapsed', !isOpen)
.attr('aria-expanded', isOpen)
}
function getTargetFromTrigger($trigger) {
var href
var target = $trigger.attr('data-target')
|| (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7
return $(target)
}
// COLLAPSE PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.collapse')
var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data && options.toggle && /show|hide/.test(option)) options.toggle = false
if (!data) $this.data('bs.collapse', (data = new Collapse(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.collapse
$.fn.collapse = Plugin
$.fn.collapse.Constructor = Collapse
// COLLAPSE NO CONFLICT
// ====================
$.fn.collapse.noConflict = function () {
$.fn.collapse = old
return this
}
// COLLAPSE DATA-API
// =================
$(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) {
var $this = $(this)
if (!$this.attr('data-target')) e.preventDefault()
var $target = getTargetFromTrigger($this)
var data = $target.data('bs.collapse')
var option = data ? 'toggle' : $this.data()
Plugin.call($target, option)
})
}(jQuery);
/* ========================================================================
* Bootstrap: dropdown.js v3.3.7
* http://getbootstrap.com/javascript/#dropdowns
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// DROPDOWN CLASS DEFINITION
// =========================
var backdrop = '.dropdown-backdrop'
var toggle = '[data-toggle="dropdown"]'
var Dropdown = function (element) {
$(element).on('click.bs.dropdown', this.toggle)
}
Dropdown.VERSION = '3.3.7'
function getParent($this) {
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = selector && $(selector)
return $parent && $parent.length ? $parent : $this.parent()
}
function clearMenus(e) {
if (e && e.which === 3) return
$(backdrop).remove()
$(toggle).each(function () {
var $this = $(this)
var $parent = getParent($this)
var relatedTarget = { relatedTarget: this }
if (!$parent.hasClass('open')) return
if (e && e.type == 'click' && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return
$parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this.attr('aria-expanded', 'false')
$parent.removeClass('open').trigger($.Event('hidden.bs.dropdown', relatedTarget))
})
}
Dropdown.prototype.toggle = function (e) {
var $this = $(this)
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
clearMenus()
if (!isActive) {
if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) {
// if mobile we use a backdrop because click events don't delegate
$(document.createElement('div'))
.addClass('dropdown-backdrop')
.insertAfter($(this))
.on('click', clearMenus)
}
var relatedTarget = { relatedTarget: this }
$parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget))
if (e.isDefaultPrevented()) return
$this
.trigger('focus')
.attr('aria-expanded', 'true')
$parent
.toggleClass('open')
.trigger($.Event('shown.bs.dropdown', relatedTarget))
}
return false
}
Dropdown.prototype.keydown = function (e) {
if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return
var $this = $(this)
e.preventDefault()
e.stopPropagation()
if ($this.is('.disabled, :disabled')) return
var $parent = getParent($this)
var isActive = $parent.hasClass('open')
if (!isActive && e.which != 27 || isActive && e.which == 27) {
if (e.which == 27) $parent.find(toggle).trigger('focus')
return $this.trigger('click')
}
var desc = ' li:not(.disabled):visible a'
var $items = $parent.find('.dropdown-menu' + desc)
if (!$items.length) return
var index = $items.index(e.target)
if (e.which == 38 && index > 0) index-- // up
if (e.which == 40 && index < $items.length - 1) index++ // down
if (!~index) index = 0
$items.eq(index).trigger('focus')
}
// DROPDOWN PLUGIN DEFINITION
// ==========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.dropdown')
if (!data) $this.data('bs.dropdown', (data = new Dropdown(this)))
if (typeof option == 'string') data[option].call($this)
})
}
var old = $.fn.dropdown
$.fn.dropdown = Plugin
$.fn.dropdown.Constructor = Dropdown
// DROPDOWN NO CONFLICT
// ====================
$.fn.dropdown.noConflict = function () {
$.fn.dropdown = old
return this
}
// APPLY TO STANDARD DROPDOWN ELEMENTS
// ===================================
$(document)
.on('click.bs.dropdown.data-api', clearMenus)
.on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() })
.on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle)
.on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown)
.on('keydown.bs.dropdown.data-api', '.dropdown-menu', Dropdown.prototype.keydown)
}(jQuery);
/* ========================================================================
* Bootstrap: modal.js v3.3.7
* http://getbootstrap.com/javascript/#modals
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// MODAL CLASS DEFINITION
// ======================
var Modal = function (element, options) {
this.options = options
this.$body = $(document.body)
this.$element = $(element)
this.$dialog = this.$element.find('.modal-dialog')
this.$backdrop = null
this.isShown = null
this.originalBodyPad = null
this.scrollbarWidth = 0
this.ignoreBackdropClick = false
if (this.options.remote) {
this.$element
.find('.modal-content')
.load(this.options.remote, $.proxy(function () {
this.$element.trigger('loaded.bs.modal')
}, this))
}
}
Modal.VERSION = '3.3.7'
Modal.TRANSITION_DURATION = 300
Modal.BACKDROP_TRANSITION_DURATION = 150
Modal.DEFAULTS = {
backdrop: true,
keyboard: true,
show: true
}
Modal.prototype.toggle = function (_relatedTarget) {
return this.isShown ? this.hide() : this.show(_relatedTarget)
}
Modal.prototype.show = function (_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.checkScrollbar()
this.setScrollbar()
this.$body.addClass('modal-open')
this.escape()
this.resize()
this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
this.$dialog.on('mousedown.dismiss.bs.modal', function () {
that.$element.one('mouseup.dismiss.bs.modal', function (e) {
if ($(e.target).is(that.$element)) that.ignoreBackdropClick = true
})
})
this.backdrop(function () {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(that.$body) // don't move modals dom position
}
that.$element
.show()
.scrollTop(0)
that.adjustDialog()
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element.addClass('in')
that.enforceFocus()
var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
transition ?
that.$dialog // wait for modal to slide in
.one('bsTransitionEnd', function () {
that.$element.trigger('focus').trigger(e)
})
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
that.$element.trigger('focus').trigger(e)
})
}
Modal.prototype.hide = function (e) {
if (e) e.preventDefault()
e = $.Event('hide.bs.modal')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.escape()
this.resize()
$(document).off('focusin.bs.modal')
this.$element
.removeClass('in')
.off('click.dismiss.bs.modal')
.off('mouseup.dismiss.bs.modal')
this.$dialog.off('mousedown.dismiss.bs.modal')
$.support.transition && this.$element.hasClass('fade') ?
this.$element
.one('bsTransitionEnd', $.proxy(this.hideModal, this))
.emulateTransitionEnd(Modal.TRANSITION_DURATION) :
this.hideModal()
}
Modal.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (document !== e.target &&
this.$element[0] !== e.target &&
!this.$element.has(e.target).length) {
this.$element.trigger('focus')
}
}, this))
}
Modal.prototype.escape = function () {
if (this.isShown && this.options.keyboard) {
this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) {
e.which == 27 && this.hide()
}, this))
} else if (!this.isShown) {
this.$element.off('keydown.dismiss.bs.modal')
}
}
Modal.prototype.resize = function () {
if (this.isShown) {
$(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this))
} else {
$(window).off('resize.bs.modal')
}
}
Modal.prototype.hideModal = function () {
var that = this
this.$element.hide()
this.backdrop(function () {
that.$body.removeClass('modal-open')
that.resetAdjustments()
that.resetScrollbar()
that.$element.trigger('hidden.bs.modal')
})
}
Modal.prototype.removeBackdrop = function () {
this.$backdrop && this.$backdrop.remove()
this.$backdrop = null
}
Modal.prototype.backdrop = function (callback) {
var that = this
var animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $(document.createElement('div'))
.addClass('modal-backdrop ' + animate)
.appendTo(this.$body)
this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) {
if (this.ignoreBackdropClick) {
this.ignoreBackdropClick = false
return
}
if (e.target !== e.currentTarget) return
this.options.backdrop == 'static'
? this.$element[0].focus()
: this.hide()
}, this))
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
if (!callback) return
doAnimate ?
this.$backdrop
.one('bsTransitionEnd', callback)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
var callbackRemove = function () {
that.removeBackdrop()
callback && callback()
}
$.support.transition && this.$element.hasClass('fade') ?
this.$backdrop
.one('bsTransitionEnd', callbackRemove)
.emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) :
callbackRemove()
} else if (callback) {
callback()
}
}
// these following methods are used to handle overflowing modals
Modal.prototype.handleUpdate = function () {
this.adjustDialog()
}
Modal.prototype.adjustDialog = function () {
var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight
this.$element.css({
paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '',
paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : ''
})
}
Modal.prototype.resetAdjustments = function () {
this.$element.css({
paddingLeft: '',
paddingRight: ''
})
}
Modal.prototype.checkScrollbar = function () {
var fullWindowWidth = window.innerWidth
if (!fullWindowWidth) { // workaround for missing window.innerWidth in IE8
var documentElementRect = document.documentElement.getBoundingClientRect()
fullWindowWidth = documentElementRect.right - Math.abs(documentElementRect.left)
}
this.bodyIsOverflowing = document.body.clientWidth < fullWindowWidth
this.scrollbarWidth = this.measureScrollbar()
}
Modal.prototype.setScrollbar = function () {
var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10)
this.originalBodyPad = document.body.style.paddingRight || ''
if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth)
}
Modal.prototype.resetScrollbar = function () {
this.$body.css('padding-right', this.originalBodyPad)
}
Modal.prototype.measureScrollbar = function () { // thx walsh
var scrollDiv = document.createElement('div')
scrollDiv.className = 'modal-scrollbar-measure'
this.$body.append(scrollDiv)
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth
this.$body[0].removeChild(scrollDiv)
return scrollbarWidth
}
// MODAL PLUGIN DEFINITION
// =======================
function Plugin(option, _relatedTarget) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.modal')
var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option](_relatedTarget)
else if (options.show) data.show(_relatedTarget)
})
}
var old = $.fn.modal
$.fn.modal = Plugin
$.fn.modal.Constructor = Modal
// MODAL NO CONFLICT
// =================
$.fn.modal.noConflict = function () {
$.fn.modal = old
return this
}
// MODAL DATA-API
// ==============
$(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this)
var href = $this.attr('href')
var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7
var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
if ($this.is('a')) e.preventDefault()
$target.one('show.bs.modal', function (showEvent) {
if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown
$target.one('hidden.bs.modal', function () {
$this.is(':visible') && $this.trigger('focus')
})
})
Plugin.call($target, option, this)
})
}(jQuery);
/* ========================================================================
* Bootstrap: tooltip.js v3.3.7
* http://getbootstrap.com/javascript/#tooltip
* Inspired by the original jQuery.tipsy by Jason Frame
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TOOLTIP PUBLIC CLASS DEFINITION
// ===============================
var Tooltip = function (element, options) {
this.type = null
this.options = null
this.enabled = null
this.timeout = null
this.hoverState = null
this.$element = null
this.inState = null
this.init('tooltip', element, options)
}
Tooltip.VERSION = '3.3.7'
Tooltip.TRANSITION_DURATION = 150
Tooltip.DEFAULTS = {
animation: true,
placement: 'top',
selector: false,
template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
trigger: 'hover focus',
title: '',
delay: 0,
html: false,
container: false,
viewport: {
selector: 'body',
padding: 0
}
}
Tooltip.prototype.init = function (type, element, options) {
this.enabled = true
this.type = type
this.$element = $(element)
this.options = this.getOptions(options)
this.$viewport = this.options.viewport && $($.isFunction(this.options.viewport) ? this.options.viewport.call(this, this.$element) : (this.options.viewport.selector || this.options.viewport))
this.inState = { click: false, hover: false, focus: false }
if (this.$element[0] instanceof document.constructor && !this.options.selector) {
throw new Error('`selector` option must be specified when initializing ' + this.type + ' on the window.document object!')
}
var triggers = this.options.trigger.split(' ')
for (var i = triggers.length; i--;) {
var trigger = triggers[i]
if (trigger == 'click') {
this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
} else if (trigger != 'manual') {
var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin'
var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'
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()
}
Tooltip.prototype.getDefaults = function () {
return Tooltip.DEFAULTS
}
Tooltip.prototype.getOptions = function (options) {
options = $.extend({}, this.getDefaults(), this.$element.data(), options)
if (options.delay && typeof options.delay == 'number') {
options.delay = {
show: options.delay,
hide: options.delay
}
}
return options
}
Tooltip.prototype.getDelegateOptions = function () {
var options = {}
var defaults = this.getDefaults()
this._options && $.each(this._options, function (key, value) {
if (defaults[key] != value) options[key] = value
})
return options
}
Tooltip.prototype.enter = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
if (obj instanceof $.Event) {
self.inState[obj.type == 'focusin' ? 'focus' : 'hover'] = true
}
if (self.tip().hasClass('in') || self.hoverState == 'in') {
self.hoverState = 'in'
return
}
clearTimeout(self.timeout)
self.hoverState = 'in'
if (!self.options.delay || !self.options.delay.show) return self.show()
self.timeout = setTimeout(function () {
if (self.hoverState == 'in') self.show()
}, self.options.delay.show)
}
Tooltip.prototype.isInStateTrue = function () {
for (var key in this.inState) {
if (this.inState[key]) return true
}
return false
}
Tooltip.prototype.leave = function (obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(obj.currentTarget, this.getDelegateOptions())
$(obj.currentTarget).data('bs.' + this.type, self)
}
if (obj instanceof $.Event) {
self.inState[obj.type == 'focusout' ? 'focus' : 'hover'] = false
}
if (self.isInStateTrue()) return
clearTimeout(self.timeout)
self.hoverState = 'out'
if (!self.options.delay || !self.options.delay.hide) return self.hide()
self.timeout = setTimeout(function () {
if (self.hoverState == 'out') self.hide()
}, self.options.delay.hide)
}
Tooltip.prototype.show = function () {
var e = $.Event('show.bs.' + this.type)
if (this.hasContent() && this.enabled) {
this.$element.trigger(e)
var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0])
if (e.isDefaultPrevented() || !inDom) return
var that = this
var $tip = this.tip()
var tipId = this.getUID(this.type)
this.setContent()
$tip.attr('id', tipId)
this.$element.attr('aria-describedby', tipId)
if (this.options.animation) $tip.addClass('fade')
var placement = typeof this.options.placement == 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement
var autoToken = /\s?auto?\s?/i
var autoPlace = autoToken.test(placement)
if (autoPlace) placement = placement.replace(autoToken, '') || 'top'
$tip
.detach()
.css({ top: 0, left: 0, display: 'block' })
.addClass(placement)
.data('bs.' + this.type, this)
this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
this.$element.trigger('inserted.bs.' + this.type)
var pos = this.getPosition()
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (autoPlace) {
var orgPlacement = placement
var viewportDim = this.getPosition(this.$viewport)
placement = placement == 'bottom' && pos.bottom + actualHeight > viewportDim.bottom ? 'top' :
placement == 'top' && pos.top - actualHeight < viewportDim.top ? 'bottom' :
placement == 'right' && pos.right + actualWidth > viewportDim.width ? 'left' :
placement == 'left' && pos.left - actualWidth < viewportDim.left ? 'right' :
placement
$tip
.removeClass(orgPlacement)
.addClass(placement)
}
var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
this.applyPlacement(calculatedOffset, placement)
var complete = function () {
var prevHoverState = that.hoverState
that.$element.trigger('shown.bs.' + that.type)
that.hoverState = null
if (prevHoverState == 'out') that.leave(that)
}
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
}
}
Tooltip.prototype.applyPlacement = function (offset, placement) {
var $tip = this.tip()
var width = $tip[0].offsetWidth
var height = $tip[0].offsetHeight
// manually read margins because getBoundingClientRect includes difference
var marginTop = parseInt($tip.css('margin-top'), 10)
var marginLeft = parseInt($tip.css('margin-left'), 10)
// we must check for NaN for ie 8/9
if (isNaN(marginTop)) marginTop = 0
if (isNaN(marginLeft)) marginLeft = 0
offset.top += marginTop
offset.left += marginLeft
// $.fn.offset doesn't round pixel values
// so we use setOffset directly with our own function B-0
$.offset.setOffset($tip[0], $.extend({
using: function (props) {
$tip.css({
top: Math.round(props.top),
left: Math.round(props.left)
})
}
}, offset), 0)
$tip.addClass('in')
// check to see if placing tip in new offset caused the tip to resize itself
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (placement == 'top' && actualHeight != height) {
offset.top = offset.top + height - actualHeight
}
var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)
if (delta.left) offset.left += delta.left
else offset.top += delta.top
var isVertical = /top|bottom/.test(placement)
var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight
var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight'
$tip.offset(offset)
this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical)
}
Tooltip.prototype.replaceArrow = function (delta, dimension, isVertical) {
this.arrow()
.css(isVertical ? 'left' : 'top', 50 * (1 - delta / dimension) + '%')
.css(isVertical ? 'top' : 'left', '')
}
Tooltip.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
$tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
$tip.removeClass('fade in top bottom left right')
}
Tooltip.prototype.hide = function (callback) {
var that = this
var $tip = $(this.$tip)
var e = $.Event('hide.bs.' + this.type)
function complete() {
if (that.hoverState != 'in') $tip.detach()
if (that.$element) { // TODO: Check whether guarding this code with this `if` is really necessary.
that.$element
.removeAttr('aria-describedby')
.trigger('hidden.bs.' + that.type)
}
callback && callback()
}
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$tip.removeClass('in')
$.support.transition && $tip.hasClass('fade') ?
$tip
.one('bsTransitionEnd', complete)
.emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :
complete()
this.hoverState = null
return this
}
Tooltip.prototype.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') || '').attr('title', '')
}
}
Tooltip.prototype.hasContent = function () {
return this.getTitle()
}
Tooltip.prototype.getPosition = function ($element) {
$element = $element || this.$element
var el = $element[0]
var isBody = el.tagName == 'BODY'
var elRect = el.getBoundingClientRect()
if (elRect.width == null) {
// width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093
elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top })
}
var isSvg = window.SVGElement && el instanceof window.SVGElement
// Avoid using $.offset() on SVGs since it gives incorrect results in jQuery 3.
// See https://github.com/twbs/bootstrap/issues/20280
var elOffset = isBody ? { top: 0, left: 0 } : (isSvg ? null : $element.offset())
var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() }
var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null
return $.extend({}, elRect, scroll, outerDims, elOffset)
}
Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {
return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :
placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :
/* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width }
}
Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) {
var delta = { top: 0, left: 0 }
if (!this.$viewport) return delta
var viewportPadding = this.options.viewport && this.options.viewport.padding || 0
var viewportDimensions = this.getPosition(this.$viewport)
if (/right|left/.test(placement)) {
var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll
var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight
if (topEdgeOffset < viewportDimensions.top) { // top overflow
delta.top = viewportDimensions.top - topEdgeOffset
} else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow
delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset
}
} else {
var leftEdgeOffset = pos.left - viewportPadding
var rightEdgeOffset = pos.left + viewportPadding + actualWidth
if (leftEdgeOffset < viewportDimensions.left) { // left overflow
delta.left = viewportDimensions.left - leftEdgeOffset
} else if (rightEdgeOffset > viewportDimensions.right) { // right overflow
delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset
}
}
return delta
}
Tooltip.prototype.getTitle = function () {
var title
var $e = this.$element
var o = this.options
title = $e.attr('data-original-title')
|| (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
return title
}
Tooltip.prototype.getUID = function (prefix) {
do prefix += ~~(Math.random() * 1000000)
while (document.getElementById(prefix))
return prefix
}
Tooltip.prototype.tip = function () {
if (!this.$tip) {
this.$tip = $(this.options.template)
if (this.$tip.length != 1) {
throw new Error(this.type + ' `template` option must consist of exactly 1 top-level element!')
}
}
return this.$tip
}
Tooltip.prototype.arrow = function () {
return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow'))
}
Tooltip.prototype.enable = function () {
this.enabled = true
}
Tooltip.prototype.disable = function () {
this.enabled = false
}
Tooltip.prototype.toggleEnabled = function () {
this.enabled = !this.enabled
}
Tooltip.prototype.toggle = function (e) {
var self = this
if (e) {
self = $(e.currentTarget).data('bs.' + this.type)
if (!self) {
self = new this.constructor(e.currentTarget, this.getDelegateOptions())
$(e.currentTarget).data('bs.' + this.type, self)
}
}
if (e) {
self.inState.click = !self.inState.click
if (self.isInStateTrue()) self.enter(self)
else self.leave(self)
} else {
self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
}
}
Tooltip.prototype.destroy = function () {
var that = this
clearTimeout(this.timeout)
this.hide(function () {
that.$element.off('.' + that.type).removeData('bs.' + that.type)
if (that.$tip) {
that.$tip.detach()
}
that.$tip = null
that.$arrow = null
that.$viewport = null
that.$element = null
})
}
// TOOLTIP PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tooltip')
var options = typeof option == 'object' && option
if (!data && /destroy|hide/.test(option)) return
if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tooltip
$.fn.tooltip = Plugin
$.fn.tooltip.Constructor = Tooltip
// TOOLTIP NO CONFLICT
// ===================
$.fn.tooltip.noConflict = function () {
$.fn.tooltip = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: popover.js v3.3.7
* http://getbootstrap.com/javascript/#popovers
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// POPOVER PUBLIC CLASS DEFINITION
// ===============================
var Popover = function (element, options) {
this.init('popover', element, options)
}
if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js')
Popover.VERSION = '3.3.7'
Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, {
placement: 'right',
trigger: 'click',
content: '',
template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
})
// NOTE: POPOVER EXTENDS tooltip.js
// ================================
Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype)
Popover.prototype.constructor = Popover
Popover.prototype.getDefaults = function () {
return Popover.DEFAULTS
}
Popover.prototype.setContent = function () {
var $tip = this.tip()
var title = this.getTitle()
var content = this.getContent()
$tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
$tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events
this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text'
](content)
$tip.removeClass('fade top bottom left right in')
// IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do
// this manually by checking the contents.
if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide()
}
Popover.prototype.hasContent = function () {
return this.getTitle() || this.getContent()
}
Popover.prototype.getContent = function () {
var $e = this.$element
var o = this.options
return $e.attr('data-content')
|| (typeof o.content == 'function' ?
o.content.call($e[0]) :
o.content)
}
Popover.prototype.arrow = function () {
return (this.$arrow = this.$arrow || this.tip().find('.arrow'))
}
// POPOVER PLUGIN DEFINITION
// =========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.popover')
var options = typeof option == 'object' && option
if (!data && /destroy|hide/.test(option)) return
if (!data) $this.data('bs.popover', (data = new Popover(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.popover
$.fn.popover = Plugin
$.fn.popover.Constructor = Popover
// POPOVER NO CONFLICT
// ===================
$.fn.popover.noConflict = function () {
$.fn.popover = old
return this
}
}(jQuery);
/* ========================================================================
* Bootstrap: scrollspy.js v3.3.7
* http://getbootstrap.com/javascript/#scrollspy
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// SCROLLSPY CLASS DEFINITION
// ==========================
function ScrollSpy(element, options) {
this.$body = $(document.body)
this.$scrollElement = $(element).is(document.body) ? $(window) : $(element)
this.options = $.extend({}, ScrollSpy.DEFAULTS, options)
this.selector = (this.options.target || '') + ' .nav li > a'
this.offsets = []
this.targets = []
this.activeTarget = null
this.scrollHeight = 0
this.$scrollElement.on('scroll.bs.scrollspy', $.proxy(this.process, this))
this.refresh()
this.process()
}
ScrollSpy.VERSION = '3.3.7'
ScrollSpy.DEFAULTS = {
offset: 10
}
ScrollSpy.prototype.getScrollHeight = function () {
return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight)
}
ScrollSpy.prototype.refresh = function () {
var that = this
var offsetMethod = 'offset'
var offsetBase = 0
this.offsets = []
this.targets = []
this.scrollHeight = this.getScrollHeight()
if (!$.isWindow(this.$scrollElement[0])) {
offsetMethod = 'position'
offsetBase = this.$scrollElement.scrollTop()
}
this.$body
.find(this.selector)
.map(function () {
var $el = $(this)
var href = $el.data('target') || $el.attr('href')
var $href = /^#./.test(href) && $(href)
return ($href
&& $href.length
&& $href.is(':visible')
&& [[$href[offsetMethod]().top + offsetBase, href]]) || null
})
.sort(function (a, b) { return a[0] - b[0] })
.each(function () {
that.offsets.push(this[0])
that.targets.push(this[1])
})
}
ScrollSpy.prototype.process = function () {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
var scrollHeight = this.getScrollHeight()
var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height()
var offsets = this.offsets
var targets = this.targets
var activeTarget = this.activeTarget
var i
if (this.scrollHeight != scrollHeight) {
this.refresh()
}
if (scrollTop >= maxScroll) {
return activeTarget != (i = targets[targets.length - 1]) && this.activate(i)
}
if (activeTarget && scrollTop < offsets[0]) {
this.activeTarget = null
return this.clear()
}
for (i = offsets.length; i--;) {
activeTarget != targets[i]
&& scrollTop >= offsets[i]
&& (offsets[i + 1] === undefined || scrollTop < offsets[i + 1])
&& this.activate(targets[i])
}
}
ScrollSpy.prototype.activate = function (target) {
this.activeTarget = target
this.clear()
var selector = this.selector +
'[data-target="' + target + '"],' +
this.selector + '[href="' + target + '"]'
var active = $(selector)
.parents('li')
.addClass('active')
if (active.parent('.dropdown-menu').length) {
active = active
.closest('li.dropdown')
.addClass('active')
}
active.trigger('activate.bs.scrollspy')
}
ScrollSpy.prototype.clear = function () {
$(this.selector)
.parentsUntil(this.options.target, '.active')
.removeClass('active')
}
// SCROLLSPY PLUGIN DEFINITION
// ===========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.scrollspy')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.scrollspy
$.fn.scrollspy = Plugin
$.fn.scrollspy.Constructor = ScrollSpy
// SCROLLSPY NO CONFLICT
// =====================
$.fn.scrollspy.noConflict = function () {
$.fn.scrollspy = old
return this
}
// SCROLLSPY DATA-API
// ==================
$(window).on('load.bs.scrollspy.data-api', function () {
$('[data-spy="scroll"]').each(function () {
var $spy = $(this)
Plugin.call($spy, $spy.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: tab.js v3.3.7
* http://getbootstrap.com/javascript/#tabs
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// TAB CLASS DEFINITION
// ====================
var Tab = function (element) {
// jscs:disable requireDollarBeforejQueryAssignment
this.element = $(element)
// jscs:enable requireDollarBeforejQueryAssignment
}
Tab.VERSION = '3.3.7'
Tab.TRANSITION_DURATION = 150
Tab.prototype.show = function () {
var $this = this.element
var $ul = $this.closest('ul:not(.dropdown-menu)')
var selector = $this.data('target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
if ($this.parent('li').hasClass('active')) return
var $previous = $ul.find('.active:last a')
var hideEvent = $.Event('hide.bs.tab', {
relatedTarget: $this[0]
})
var showEvent = $.Event('show.bs.tab', {
relatedTarget: $previous[0]
})
$previous.trigger(hideEvent)
$this.trigger(showEvent)
if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return
var $target = $(selector)
this.activate($this.closest('li'), $ul)
this.activate($target, $target.parent(), function () {
$previous.trigger({
type: 'hidden.bs.tab',
relatedTarget: $this[0]
})
$this.trigger({
type: 'shown.bs.tab',
relatedTarget: $previous[0]
})
})
}
Tab.prototype.activate = function (element, container, callback) {
var $active = container.find('> .active')
var transition = callback
&& $.support.transition
&& ($active.length && $active.hasClass('fade') || !!container.find('> .fade').length)
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
.end()
.find('[data-toggle="tab"]')
.attr('aria-expanded', false)
element
.addClass('active')
.find('[data-toggle="tab"]')
.attr('aria-expanded', true)
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if (element.parent('.dropdown-menu').length) {
element
.closest('li.dropdown')
.addClass('active')
.end()
.find('[data-toggle="tab"]')
.attr('aria-expanded', true)
}
callback && callback()
}
$active.length && transition ?
$active
.one('bsTransitionEnd', next)
.emulateTransitionEnd(Tab.TRANSITION_DURATION) :
next()
$active.removeClass('in')
}
// TAB PLUGIN DEFINITION
// =====================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.tab')
if (!data) $this.data('bs.tab', (data = new Tab(this)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.tab
$.fn.tab = Plugin
$.fn.tab.Constructor = Tab
// TAB NO CONFLICT
// ===============
$.fn.tab.noConflict = function () {
$.fn.tab = old
return this
}
// TAB DATA-API
// ============
var clickHandler = function (e) {
e.preventDefault()
Plugin.call($(this), 'show')
}
$(document)
.on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler)
.on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler)
}(jQuery);
/* ========================================================================
* Bootstrap: affix.js v3.3.7
* http://getbootstrap.com/javascript/#affix
* ========================================================================
* Copyright 2011-2016 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// AFFIX CLASS DEFINITION
// ======================
var Affix = function (element, options) {
this.options = $.extend({}, Affix.DEFAULTS, options)
this.$target = $(this.options.target)
.on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
.on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this))
this.$element = $(element)
this.affixed = null
this.unpin = null
this.pinnedOffset = null
this.checkPosition()
}
Affix.VERSION = '3.3.7'
Affix.RESET = 'affix affix-top affix-bottom'
Affix.DEFAULTS = {
offset: 0,
target: window
}
Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) {
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
var targetHeight = this.$target.height()
if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false
if (this.affixed == 'bottom') {
if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom'
return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom'
}
var initializing = this.affixed == null
var colliderTop = initializing ? scrollTop : position.top
var colliderHeight = initializing ? targetHeight : height
if (offsetTop != null && scrollTop <= offsetTop) return 'top'
if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom'
return false
}
Affix.prototype.getPinnedOffset = function () {
if (this.pinnedOffset) return this.pinnedOffset
this.$element.removeClass(Affix.RESET).addClass('affix')
var scrollTop = this.$target.scrollTop()
var position = this.$element.offset()
return (this.pinnedOffset = position.top - scrollTop)
}
Affix.prototype.checkPositionWithEventLoop = function () {
setTimeout($.proxy(this.checkPosition, this), 1)
}
Affix.prototype.checkPosition = function () {
if (!this.$element.is(':visible')) return
var height = this.$element.height()
var offset = this.options.offset
var offsetTop = offset.top
var offsetBottom = offset.bottom
var scrollHeight = Math.max($(document).height(), $(document.body).height())
if (typeof offset != 'object') offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element)
if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)
var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom)
if (this.affixed != affix) {
if (this.unpin != null) this.$element.css('top', '')
var affixType = 'affix' + (affix ? '-' + affix : '')
var e = $.Event(affixType + '.bs.affix')
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
this.affixed = affix
this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null
this.$element
.removeClass(Affix.RESET)
.addClass(affixType)
.trigger(affixType.replace('affix', 'affixed') + '.bs.affix')
}
if (affix == 'bottom') {
this.$element.offset({
top: scrollHeight - height - offsetBottom
})
}
}
// AFFIX PLUGIN DEFINITION
// =======================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.affix')
var options = typeof option == 'object' && option
if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.affix
$.fn.affix = Plugin
$.fn.affix.Constructor = Affix
// AFFIX NO CONFLICT
// =================
$.fn.affix.noConflict = function () {
$.fn.affix = old
return this
}
// AFFIX DATA-API
// ==============
$(window).on('load', function () {
$('[data-spy="affix"]').each(function () {
var $spy = $(this)
var data = $spy.data()
data.offset = data.offset || {}
if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom
if (data.offsetTop != null) data.offset.top = data.offsetTop
Plugin.call($spy, data)
})
})
}(jQuery);
$(function () {
$('.button-checkbox').each(function () {
// Settings
var $widget = $(this),
$button = $widget.find('button'),
$checkbox = $widget.find('input:checkbox'),
color = $button.data('color'),
settings = {
on: {
icon: 'glyphicon glyphicon-check'
},
off: {
icon: 'fa fa-square-o'
}
};
// Event Handlers
$button.on('click', function () {
$checkbox.prop('checked', !$checkbox.is(':checked'));
$checkbox.triggerHandler('change');
updateDisplay();
});
$checkbox.on('change', function () {
updateDisplay();
});
// Actions
function updateDisplay() {
var isChecked = $checkbox.is(':checked');
// Set the button's state
$button.data('state', (isChecked) ? "on" : "off");
// Set the button's icon
$button.find('.state-icon')
.removeClass()
.addClass('state-icon ' + settings[$button.data('state')].icon);
// Update the button's color
if (isChecked) {
$button
.removeClass('btn-default')
.addClass('btn-' + color + ' active');
}
else {
$button
.removeClass('btn-' + color + ' active')
.addClass('btn-default');
}
}
// Initialization
function init() {
updateDisplay();
// Inject the icon if applicable
if ($button.find('.state-icon').length == 0) {
$button.prepend('<i class="state-icon ' + settings[$button.data('state')].icon + '"></i> ');
}
}
init();
});
});
|
#! /usr/bin/env node
import minimist from 'minimist'
import Avifors from './Avifors'
import YamlModelBuilder from './model/YamlModelBuilder'
import Configuration from './Configuration'
import {helpMessage} from './help'
import YamlHelper from './tools/YamlHelper'
const avifors = new Avifors()
const corePlugins = ['./model/plugin', './template/plugin', './commands/plugin']
corePlugins.forEach(plugin => require(plugin).default(avifors))
const argv = minimist(process.argv.slice(2))
const userCommand = argv._[0]
if (userCommand === undefined || userCommand === 'help') {
console.log(helpMessage)
} else {
const yamlHelper = new YamlHelper()
const config = new Configuration(argv.config, yamlHelper)
avifors.loadPlugins(config.plugins)
const modelBuilder = new YamlModelBuilder(avifors, yamlHelper)
const model = modelBuilder.build(config.modelFiles)
avifors.setModel(model)
avifors.getCommand(userCommand)({
avifors: avifors,
model: model,
argv: argv
})
}
|
import express from 'express'
import cors from 'cors'
import bodyParser from 'body-parser'
import helmet from 'helmet'
import httpStatus from 'http-status'
import path from 'path'
import routes from './routes'
import logger from './helpers/logger.js'
const app = express()
// Pug
app.set('view engine', 'pug')
app.set('views', path.join(__dirname, 'views'))
// Helmet helps you secure your Express apps by setting various HTTP headers.
app.use(helmet())
// Enable CORS
app.use(cors())
// To use with Nginx
// app.enable('trust proxy')
// Parse incoming request bodies in a middleware before your handlers, available under the req.body property.
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
// API Routes
app.use('/', routes)
// Catch 404
app.get('*', (req, res) => {
res.status(404).send({ message: 'Not found' })
})
// Error log
app.use((err, req, res, next) => {
logger.log(err.level || 'error', err.message)
next(err)
})
// Error handler
app.use((err, req, res, next) => {
res.status(err.status || 500).send({
status: err.status || 500,
message: err.status ? err.message : httpStatus[500],
})
})
export default app
|
import Lab from 'lab';
import server from '../../server';
import data from '../data';
const expect = Lab.assertions.expect;
export const lab = Lab.script();
lab.experiment('ProfileCtrl', function() {
lab.before(done => {
data.sync().then(done, done);
});
lab.test('[getAuthenticated] returns the current profile', function(done) {
const options = {
method: 'GET',
url: '/profile',
headers: {
'Authorization': `Bearer ${data.fp.token.value}`
}
};
server.inject(options, function(response) {
const result = response.result;
expect(response.statusCode).to.equal(200);
expect(result.email).to.equal(data.fp.account.profile.email);
done();
});
});
lab.test('[getAuthenticated] returns 401 without a token', function(done) {
const options = {
method: 'GET',
url: '/profile'
};
server.inject(options, function(response) {
expect(response.statusCode).to.equal(401);
done();
});
});
lab.test('[get] returns the correct profile by id', function(done) {
const options = {
method: 'GET',
url: `/profile/${data.tp.account.profile.id}`,
headers: {
'Authorization': `Bearer ${data.fp.token.value}`
}
};
server.inject(options, function(response) {
const result = response.result;
expect(response.statusCode).to.equal(200);
expect(result.id).to.equal(data.tp.account.profile.id);
done();
});
});
lab.test('[get] returns the correct profile by email', function(done) {
const options = {
method: 'GET',
url: `/profile/${encodeURIComponent(data.tp.account.profile.email)}`,
headers: {
'Authorization': `Bearer ${data.fp.token.value}`
}
};
server.inject(options, function(response) {
const result = response.result;
expect(response.statusCode).to.equal(200);
expect(result.email).to.equal(data.tp.account.profile.email);
done();
});
});
lab.test('[get] returns 404 if not found by id', function(done) {
const options = {
method: 'GET',
url: `/profile/123-456`,
headers: {
'Authorization': `Bearer ${data.fp.token.value}`
}
};
server.inject(options, function(response) {
expect(response.statusCode).to.equal(404);
done();
});
});
lab.test('[get] returns 404 if not found by email', function(done) {
const options = {
method: 'GET',
url: `/profile/${encodeURIComponent('[email protected]')}`,
headers: {
'Authorization': `Bearer ${data.fp.token.value}`
}
};
server.inject(options, function(response) {
expect(response.statusCode).to.equal(404);
done();
});
});
lab.test('[update] returns the profile with a new first name (by id)', function(done) {
const options = {
method: 'PUT',
url: `/profile/${data.tp.account.profile.id}`,
headers: {
'Authorization': `Bearer ${data.tp.token.value}`
},
payload: {
firstName: 'Gargantua'
}
};
server.inject(options, function(response) {
const result = response.result;
expect(response.statusCode).to.equal(200);
expect(result.name.first).to.equal('Gargantua');
done();
});
});
lab.test('[update] returns the profile with a new last name (by email)', function(done) {
const options = {
method: 'PUT',
url: `/profile/${data.tp.account.profile.email}`,
headers: {
'Authorization': `Bearer ${data.tp.token.value}`
},
payload: {
lastName: 'Batman'
}
};
server.inject(options, function(response) {
const result = response.result;
expect(response.statusCode).to.equal(200);
expect(result.name.last).to.equal('Batman');
done();
});
});
lab.test('[update] returns 401 if trying to update someone else\'s profile', function(done) {
const options = {
method: 'PUT',
url: `/profile/${data.tp.account.profile.email}`,
headers: {
'Authorization': `Bearer ${data.fp.token.value}`
},
payload: {
lastName: 'Batman'
}
};
server.inject(options, function(response) {
expect(response.statusCode).to.equal(401);
done();
});
});
});
|
const fs = require('fs')
const path = require('path')
const LRU = require('lru-cache')
const express = require('express')
const favicon = require('serve-favicon')
const compression = require('compression')
const resolve = file => path.resolve(__dirname, file)
const { createBundleRenderer } = require('vue-server-renderer')
const isProd = process.env.NODE_ENV === 'production'
const useMicroCache = process.env.MICRO_CACHE !== 'false'
const serverInfo =
`express/${require('express/package.json').version} ` +
`vue-server-renderer/${require('vue-server-renderer/package.json').version}`
const app = express()
const template = fs.readFileSync(resolve('./src/index.html'), 'utf-8');
function createRenderer (bundle, options) {
// https://github.com/vuejs/vue/blob/dev/packages/vue-server-renderer/README.md#why-use-bundlerenderer
return createBundleRenderer(bundle, Object.assign(options, {
template,
// for component caching
cache: LRU({
max: 1000,
maxAge: 1000 * 60 * 15
}),
// this is only needed when vue-server-renderer is npm-linked
basedir: resolve('./dist'),
// recommended for performance
runInNewContext: false
}))
}
let renderer
let readyPromise
if (isProd) {
// In production: create server renderer using built server bundle.
// The server bundle is generated by vue-ssr-webpack-plugin.
const bundle = require('./dist/vue-ssr-server-bundle.json')
// The client manifests are optional, but it allows the renderer
// to automatically infer preload/prefetch links and directly add <script>
// tags for any async chunks used during render, avoiding waterfall requests.
const clientManifest = require('./dist/vue-ssr-client-manifest.json')
renderer = createRenderer(bundle, {
clientManifest
})
} else {
// In development: setup the dev server with watch and hot-reload,
// and create a new renderer on bundle / index template update.
readyPromise = require('./build/setup-dev-server')(app, (bundle, options) => {
renderer = createRenderer(bundle, options)
})
}
const serve = (path, cache) => express.static(resolve(path), {
maxAge: cache && isProd ? 1000 * 60 * 60 * 24 * 30 : 0
})
app.use(compression({ threshold: 0 }))
//app.use(favicon('./public/logo-48.png'))
app.use('/dist', serve('./dist', true))
app.use('/public', serve('./public', true))
app.use('/manifest.json', serve('./manifest.json', true))
app.use('/service-worker.js', serve('./dist/service-worker.js'))
// 1-second microcache.
// https://www.nginx.com/blog/benefits-of-microcaching-nginx/
const microCache = LRU({
max: 100,
maxAge: 1000
})
// since this app has no user-specific content, every page is micro-cacheable.
// if your app involves user-specific content, you need to implement custom
// logic to determine whether a request is cacheable based on its url and
// headers.
const isCacheable = req => useMicroCache
function render (req, res) {
const s = Date.now()
res.setHeader("Content-Type", "text/html")
res.setHeader("Server", serverInfo)
const handleError = err => {
if (err.url) {
res.redirect(err.url)
} else if(err.code === 404) {
res.status(404).end('404 | Page Not Found')
} else {
// Render Error Page or Redirect
res.status(500).end('500 | Internal Server Error')
console.error(`error during render : ${req.url}`)
console.error(err.stack)
}
}
const cacheable = isCacheable(req)
if (cacheable) {
const hit = microCache.get(req.url)
if (hit) {
if (!isProd) {
console.log(`cache hit!`)
}
return res.end(hit)
}
}
const context = {
title: '交易虎_手机游戏交易平台_手游交易_帐号交易_游戏币交易_装备交易_道具交易_jiaoyihu', // default title
url: req.url
}
renderer.renderToString(context, (err, html) => {
debugger;
if (err) {
return handleError(err)
}
res.end(html)
if (cacheable) {
microCache.set(req.url, html)
}
if (!isProd) {
console.log(`whole request: ${Date.now() - s}ms`)
}
})
}
app.get('*', isProd ? render : (req, res) => {
readyPromise.then(() => render(req, res))
})
const port = process.env.PORT || 80;
app.listen(port, () => {
console.log(`server started at localhost:${port}`)
})
|
$(function(){
$("#addCompanyForm").validate({
rules: {
name : {
required : true
},
email: {
required: true,
email: true
},
url : {
required : true,
url : true
}
},
messages: {
name : {
required : "Please enter your company name"
},
url : {
required : "Please enter your company website",
url : "Please enter a valid url"
},
email: {
required: "Enter your Company email address",
email: "Please enter a valid email address",
}
}
});
$('#addCompanyDialog').on('hide.bs.modal', function (e) {
refresh();
});
$('#addCompanyDialog').on('shown.bs.modal', function (e) {
$('#name').focus();
$('#id').val('');
var id = $(e.relatedTarget).attr('id');
var isEdit = $(e.relatedTarget).hasClass('fa-edit');
console.log(isEdit);
if(isEdit){
$('#id').val(id);
$.getJSON('/account/companies/' + id, function(data){
if(data.result){
$('#name').val(data.result.name);
$('#email').val(data.result.email);
$('#url').val(data.result.url);
}
});
}
var validator = $( "#addCompanyForm" ).validate();
validator.resetForm();
});
$('#confirm-delete').on('show.bs.modal', function(e) {
var id = $(e.relatedTarget).attr('id');
$(this).find('.btn-ok').on('click', function(){
$.ajax({
url: '/account/companies/' + id,
type: 'delete',
dataType: 'json',
success: function(data) {
$('#message ').html('<div class="error" style="text-align:center;padding:5px;">' + data.message + '</div>')
$('#confirm-delete').modal('hide');
if(data.result)
getCompanies();
}
});
});
});
$("#addCompanyForm").submit(function(e) {
e.preventDefault();
if($( "#addCompanyForm" ).valid()){
var actionurl = '/account/companies';
var type = 'post';
console.log($('#id').val() != '');
if($('#id').val() != ''){
type = 'put';
actionurl = '/account/companies/' + $('#id').val();
}
//var actionurl = e.currentTarget.action;
$.ajax({
url: actionurl,
type: type,
dataType: 'json',
data: $("#addCompanyForm").serialize(),
success: function(data) {
$('#message ').html('<div class="error" style="text-align:center;padding:5px;">' + data.message + '</div>')
$('#addCompanyDialog').modal('hide');
if(data.result)
getCompanies();
}
});
}
});
var getCompanies= function(){
$('#companylist').html('<div class="loader"><i class="fa fa-spinner fa-pulse"></i></div>');
$.get('/account/companies/list', function(data){
$('#companylist').html(data);
$('#message ').html('');
});
};
$('#refresh').on('click', function () {
$('#message ').html('');
getCompanies();
});
var refresh = function () {
$('#id').val('');
$('#name').val('');
$('#url').val('');
$('#email').val('');
};
getCompanies();
}); |
module.exports = {
entry: {
'public/js/bundle.js': ['./index.js'],
},
output: {
filename: '[name]',
},
devtool: 'eval',
module: {
loaders: [
{
test: /.js$/,
exclude: /node_modules/,
loaders: ['babel'],
}
]
}
}
|
import { expect } from 'chai'
import {List, Map} from 'immutable'
import categories from '../src/reducer.js'
describe("Category Test", () => {
it("should add a category", () => {
let initialState = Map({
user: 'Skye'
})
let expectedState = Map({
user: 'Skye',
categories: Map({
'Love': 0
})
})
let result = categories(initialState, {type:'ADD_CATEGORY', value:'Love'})
expect(result).to.eql(expectedState)
})
it("adding a category does not modify previous state", () => {
let initialState = Map({
user: 'Skye',
categories: Map({
'Love': 90
})
})
let expectedState = Map({
user: 'Skye',
categories: Map({
'Love': 90,
'Communication': 0
})
})
let result = categories(initialState, {type:'ADD_CATEGORY', value:'Communication'})
expect(result).to.eql(expectedState)
expect(initialState).to.eql(Map({
user: 'Skye',
categories: Map({
'Love': 90
})
}))
})
it("should rate a category", () => {
let initialState = Map({
user: 'Skye',
categories: Map({
'Love': 0
})
})
let expectedState = Map({
user: 'Skye',
categories: Map({
'Love': 90
})
})
let result = categories(initialState, { type:'RATE_CATEGORY', name:'Love', value:90 })
expect(result).to.eql(Map({
user: 'Skye',
categories: Map({
'Love': 90
})
}))
})
it("should stop adding categories", () => {
let initialState = Map({
user: 'Skye',
categories: Map({
'Love': 90,
'Communication': 80,
'Fun' : 100
})
})
let expectedState = Map({
user: 'Skye',
categories: Map({
'Love': 90,
'Communication': 80,
'Fun' : 100
}),
categories_finished: true
})
let result = categories(initialState, {type:'FINISH_CATEGORIES', value: true})
expect(result).to.eql(expectedState)
})
})
|
/**
* DevExtreme (core/component_registrator.js)
* Version: 16.2.5
* Build date: Mon Feb 27 2017
*
* Copyright (c) 2012 - 2017 Developer Express Inc. ALL RIGHTS RESERVED
* EULA: https://www.devexpress.com/Support/EULAs/DevExtreme.xml
*/
"use strict";
var $ = require("jquery"),
errors = require("./errors"),
MemorizedCallbacks = require("./memorized_callbacks"),
publicComponentUtils = require("./utils/public_component");
var callbacks = new MemorizedCallbacks;
var registerComponent = function(name, namespace, componentClass) {
if (!componentClass) {
componentClass = namespace
} else {
namespace[name] = componentClass
}
publicComponentUtils.name(componentClass, name);
callbacks.fire(name, componentClass)
};
registerComponent.callbacks = callbacks;
var registerJQueryComponent = function(name, componentClass) {
$.fn[name] = function(options) {
var result, isMemberInvoke = "string" === typeof options;
if (isMemberInvoke) {
var memberName = options,
memberArgs = $.makeArray(arguments).slice(1);
this.each(function() {
var instance = componentClass.getInstance(this);
if (!instance) {
throw errors.Error("E0009", name)
}
var member = instance[memberName],
memberValue = member.apply(instance, memberArgs);
if (void 0 === result) {
result = memberValue
}
})
} else {
this.each(function() {
var instance = componentClass.getInstance(this);
if (instance) {
instance.option(options)
} else {
new componentClass(this, options)
}
});
result = this
}
return result
}
};
callbacks.add(registerJQueryComponent);
module.exports = registerComponent;
|
$(document).ready(function(){hopscotch.startTour({id:"my-intro",steps:[{target:"logo-tour",title:"Logo Here",content:"You can find here status of user who's currently online.",placement:"bottom",yOffset:10},{target:"display-title-tour",title:"Display Text",content:"Click on the button and make sidebar navigation small.",placement:"top",zindex:999},{target:"page-title-tour",title:"User settings",content:"You can edit you profile info here.",placement:"bottom",zindex:999},{target:"thankyou-tour",title:"Thank you !",content:"Here you can change theme skins and other features.",placement:"top",zindex:999}],showPrevButton:!0})}); |
'use strict';
angular.module('mgcrea.ngStrap.dropdown', ['mgcrea.ngStrap.tooltip'])
.provider('$dropdown', function() {
var defaults = this.defaults = {
animation: 'am-fade',
prefixClass: 'dropdown',
prefixEvent: 'dropdown',
placement: 'bottom-left',
template: 'dropdown/dropdown.tpl.html',
trigger: 'click',
container: false,
keyboard: true,
html: false,
delay: 0
};
this.$get = function($window, $rootScope, $tooltip, $timeout) {
var bodyEl = angular.element($window.document.body);
var matchesSelector = Element.prototype.matchesSelector || Element.prototype.webkitMatchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector;
function DropdownFactory(element, config) {
var $dropdown = {};
// Common vars
var options = angular.extend({}, defaults, config);
var scope = $dropdown.$scope = options.scope && options.scope.$new() || $rootScope.$new();
$dropdown = $tooltip(element, options);
var parentEl = element.parent();
// Protected methods
$dropdown.$onKeyDown = function(evt) {
if (!/(38|40)/.test(evt.keyCode)) return;
evt.preventDefault();
evt.stopPropagation();
// Retrieve focused index
var items = angular.element($dropdown.$element[0].querySelectorAll('li:not(.divider) a'));
if(!items.length) return;
var index;
angular.forEach(items, function(el, i) {
if(matchesSelector && matchesSelector.call(el, ':focus')) index = i;
});
// Navigate with keyboard
if(evt.keyCode === 38 && index > 0) index--;
else if(evt.keyCode === 40 && index < items.length - 1) index++;
else if(angular.isUndefined(index)) index = 0;
items.eq(index)[0].focus();
};
// Overrides
var show = $dropdown.show;
$dropdown.show = function() {
show();
// use timeout to hookup the events to prevent
// event bubbling from being processed imediately.
$timeout(function() {
options.keyboard && $dropdown.$element.on('keydown', $dropdown.$onKeyDown);
bodyEl.on('click', onBodyClick);
}, 0, false);
parentEl.hasClass('dropdown') && parentEl.addClass('open');
};
var hide = $dropdown.hide;
$dropdown.hide = function() {
if(!$dropdown.$isShown) return;
options.keyboard && $dropdown.$element.off('keydown', $dropdown.$onKeyDown);
bodyEl.off('click', onBodyClick);
parentEl.hasClass('dropdown') && parentEl.removeClass('open');
hide();
};
var destroy = $dropdown.destroy;
$dropdown.destroy = function() {
bodyEl.off('click', onBodyClick);
destroy();
};
// Private functions
function onBodyClick(evt) {
if(evt.target === element[0]) return;
return evt.target !== element[0] && $dropdown.hide();
}
return $dropdown;
}
return DropdownFactory;
};
})
.directive('bsDropdown', function($window, $sce, $dropdown) {
return {
restrict: 'EAC',
scope: true,
link: function postLink(scope, element, attr, transclusion) {
// Directive options
var options = {scope: scope};
angular.forEach(['placement', 'container', 'delay', 'trigger', 'keyboard', 'html', 'animation', 'template', 'id'], function(key) {
if(angular.isDefined(attr[key])) options[key] = attr[key];
});
// use string regex match boolean attr falsy values, leave truthy values be
var falseValueRegExp = /^(false|0|)$/i;
angular.forEach(['html', 'container'], function(key) {
if(angular.isDefined(attr[key]) && falseValueRegExp.test(attr[key]))
options[key] = false;
});
// Support scope as an object
attr.bsDropdown && scope.$watch(attr.bsDropdown, function(newValue, oldValue) {
scope.content = newValue;
}, true);
// Visibility binding support
attr.bsShow && scope.$watch(attr.bsShow, function(newValue, oldValue) {
if(!dropdown || !angular.isDefined(newValue)) return;
if(angular.isString(newValue)) newValue = !!newValue.match(/true|,?(dropdown),?/i);
newValue === true ? dropdown.show() : dropdown.hide();
});
// Initialize dropdown
var dropdown = $dropdown(element, options);
// Garbage collection
scope.$on('$destroy', function() {
if (dropdown) dropdown.destroy();
options = null;
dropdown = null;
});
}
};
});
|
/*
*
* hocNotification
*
*/
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { compose, setPropTypes } from 'recompose';
import { createStructuredSelector } from 'reselect';
import { selectNotifications } from 'features/common_ui/selectors';
const mapStateToProps = createStructuredSelector({
notifications: selectNotifications(),
});
const sliderPropsType = setPropTypes({
notifications: PropTypes.oneOfType([PropTypes.array, PropTypes.object]).isRequired,
});
const hocNotification = compose(connect(mapStateToProps), sliderPropsType);
export default hocNotification;
|
// This contains the module definition factory function, application state,
// events, and the router.
this.jda = {
// break up logical components of code into modules.
module: function()
{
// Internal module cache.
var modules = {};
// Create a new module reference scaffold or load an existing module.
return function(name)
{
// If this module has already been created, return it
if (modules[name]) return modules[name];
// Create a module and save it under this name
return modules[name] = { Views: {} };
};
}(),
// Keep active application instances namespaced under an app object.
app: _.extend({
apiLocation : sessionStorage.getItem("apiUrl"),
currentView : 'list',
resultsPerPage : 100,
init : function(){
// make item collection
this.currentFilter=null;
var Browser = jda.module("browser");
this.resultsView = new Browser.Items.Collections.Views.Results();
this.eventMap = new Browser.Views.EventMap();
this.initCollectionsDrawer();
this.startRouter();
var _this=this;
},
initCollectionsDrawer:function(){
//load my collections drawer
var Browser = jda.module("browser");
this.myCollectionsDrawer = new Browser.Items.Collections.Views.MyCollectionsDrawer();
this.myCollectionsDrawer.getCollectionList();
},
startRouter: function()
{
var _this = this;
// Defining the application router, you can attach sub routers here.
var Router = Backbone.Router.extend({
routes: {
"" : 'search',
":query" : 'search'
},
search : function( query ){
_this.parseURLHash(query);
}
});
this.router = new Router();
Backbone.history.start();
},
queryStringToHash: function (query) {
var query_obj = {};
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
pair[0] = decodeURIComponent(pair[0]);
pair[1] = decodeURIComponent(pair[1]);
// If first entry with this name
if (typeof query_obj[pair[0]] === "undefined") {
query_obj[pair[0]] = pair[1];
// If second entry with this name
} else if (typeof query_obj[pair[0]] === "string") {
var arr = [ query_obj[pair[0]], pair[1] ];
query_obj[pair[0]] = arr;
// If third or later entry with this name
} else {
query_obj[pair[0]].push(pair[1]);
}
}
//parse time slider properties
query_obj.times = {};
if (query_obj.min_date !== null){
query_obj.times.start = query_obj.min_date;
}
if (query_obj.max_date !== null){
query_obj.times.end = query_obj.max_date;
}
return query_obj;
},
parseURLHash : function (query){
var _this=this;
var Browser = jda.module("browser");
//Update Search Object
if (!_.isUndefined(query)){
this.searchObject = this.queryStringToHash(query);
} else {
this.searchObject = {page:1};
}
console.log("searchObject",this.searchObject);
//Update interface
this.updateSearchUI(this.searchObject);
//Load filter if nec, carry out search
if(sessionStorage.getItem('filterType')=='none'||!_.isUndefined(this.filterModel)) {
if (!_.isUndefined(this.searchObject.view_type)) this.switchViewTo(this.searchObject.view_type,true) ;
else this.search(this.searchObject);
}
else{
$('.tab-content').find('.btn-group').hide();
$('#jda-related-tags').hide();
$('#event-button').hide();
if(sessionStorage.getItem('filterType')=='user'){
this.filterType ="user";
this.filterModel = new Browser.Users.Model({id:sessionStorage.getItem('filterId')});
this.filterModel.fetch({
success : function(model, response){
_this.resultsView.userFilter = new Browser.Users.Views.UserPage({model:model});
if (!_.isUndefined(_this.searchObject.view_type)) _this.switchViewTo(_this.searchObject.view_type,true) ;
else _this.search(_this.searchObject);
},
error : function(model, response){
console.log('Failed to fetch the user object.');
}
});
}
else if(sessionStorage.getItem('filterType')=='collection'){
this.filterType ="collection";
this.filterModel = new Browser.Items.Model({id:sessionStorage.getItem('filterId')});
this.filterModel.fetch({
success : function(model, response){
_this.resultsView.collectionFilter = new Browser.Items.Views.CollectionPage({model:model});
if (!_.isUndefined(_this.searchObject.view_type)) _this.switchViewTo(_this.searchObject.view_type,true) ;
else _this.search(_this.searchObject);
},
error : function(model, response){
console.log('Failed to fetch the user object.');
}
});
}
}
},
sort : function(){
this.searchObject.sort = $('#zeega-sort').val();
this.updateURLHash(this.searchObject);
this.search(this.searchObject);
},
parseSearchUI : function(){
var facets = VisualSearch.searchQuery.models;
var obj={};
var tagQuery = "";
var textQuery = "";
_.each( VisualSearch.searchBox.facetViews, function( facet ){
if( facet.model.get('category') != 'tag' && facet.model.get('category') != 'text')
{
facet.model.set({'value': null });
facet.remove();
}
});
_.each(facets, function(facet){
switch ( facet.get('category') )
{
case 'text':
textQuery = (textQuery.length > 0) ? textQuery + " AND " + facet.get('value') : facet.get('value');
textQuery=textQuery.replace(/^#/, '');
break;
case 'tag':
tagQuery = (tagQuery.length > 0) ? tagQuery + " AND " + facet.get('value') : tagQuery + facet.get('value');
tagQuery=tagQuery.replace(/^#/, '');
break;
}
});
obj.q = textQuery;
obj.tags = tagQuery;
obj.view_type = this.currentView;
obj.media_type = $('#zeega-content-type').val();
// remove retweets
if ($("#noRTChk").is(":checked")) {
obj.nq = "RT";
}
obj.sort = $('#zeega-sort').val();
obj.times = this.searchObject.times;
this.searchObject=obj;
this.updateURLHash(obj);
this.search(obj);
},
updateSearchUI : function(obj){
VisualSearch.searchBox.disableFacets();
VisualSearch.searchBox.value('');
VisualSearch.searchBox.flags.allSelected = false;
var tags, text;
if (!_.isUndefined(obj.q)&&obj.q.length>0){
text = obj.q.split(" AND ");
for( var j=0; j<text.length; j++ ){
VisualSearch.searchBox.addFacet('text', text[j], 0);
}
}
//check for tags
if (!_.isUndefined(obj.tags)&&obj.tags.length>0){
tags = obj.tags.split(" AND ");
for(var i=0;i<tags.length;i++)
{
VisualSearch.searchBox.addFacet('tag', tags[i], 0);
}
}
if (!_.isUndefined(obj.media_type)) $('#zeega-content-type').val(obj.media_type);
else $('#zeega-content-type').val("");
if (!_.isUndefined(obj.sort)) $('#zeega-sort').val(obj.sort);
else $('#zeega-sort').val("relevant");
$('#select-wrap-text').text( $('#zeega-content-type option[value=\''+$('#zeega-content-type').val()+'\']').text() );
},
updateURLHash : function(obj){
var hash = '';
if( !_.isUndefined(this.viewType)) hash += 'view_type=' + this.viewType + '&';
if( !_.isUndefined(obj.q) && obj.q.length > 0) hash += 'q=' + obj.q + '&';
if( !_.isUndefined(obj.nq)) hash += 'nq=' + obj.nq + '&';
if( !_.isUndefined(obj.tags) && obj.tags.length > 0) hash += 'tags=' + obj.tags + '&';
if( !_.isUndefined(obj.media_type) )hash += 'media_type='+ obj.media_type + '&';
if( !_.isUndefined(obj.media_after) )hash += 'media_after='+ obj.media_after + '&';
if( !_.isUndefined(obj.media_before) )hash += 'media_before='+ obj.media_before + '&';
if( !_.isUndefined(obj.sort) ) hash += 'sort='+ obj.sort + '&';
if( !_.isUndefined(obj.mapBounds) ) hash += 'map_bounds='+ encodeURIComponent(obj.mapBounds) + '&';
if( !_.isUndefined(obj.times)&& !_.isNull(obj.times) )
{
if( !_.isUndefined(obj.times.start) ) hash += 'min_date='+ obj.times.start + '&';
if( !_.isUndefined(obj.times.end) ) hash += 'max_date='+ obj.times.end + '&';
}
jda.app.router.navigate(hash,{trigger:false});
},
search : function(obj){
if(!_.isUndefined(this.filterType)){
if(this.filterType=="user"){
obj.user= sessionStorage.getItem('filterId');
}
else if(this.filterType=="collection"){
obj.itemId = sessionStorage.getItem('filterId');
}
}
this.resultsView.search( obj,true );
if (this.currentView == 'event') this.eventMap.load();
},
switchViewTo : function( view , refresh ){
var _this=this;
if( view != this.currentView&&(view=="event"||this.currentView=="event"))refresh = true;
this.currentView = view;
$('.tab-pane').removeClass('active');
$('#zeega-'+view+'-view').addClass('active');
switch( this.currentView )
{
case 'list':
this.showListView(refresh);
break;
case 'event':
this.showEventView(refresh);
break;
case 'thumb':
this.showThumbnailView(refresh);
break;
default:
console.log('view type not recognized');
}
},
showListView : function(refresh){
$('#zeega-view-buttons .btn').removeClass('active');
$('#list-button').addClass('active');
$('#jda-right').show();
$('#event-time-slider').hide();
$('#zeega-results-count').removeClass('zeega-results-count-event');
$('#zeega-results-count').css('left', 0);
$('#zeega-results-count').css('z-index', 0);
$('#zeega-results-count-text-with-date').hide();
if(this.resultsView.updated)
{
this.resultsView.render();
}
this.viewType='list';
if(refresh){
this.searchObject.times=null;
this.search(this.searchObject);
}
this.updateURLHash(this.searchObject);
},
showThumbnailView : function(refresh){
$('#zeega-view-buttons .btn').removeClass('active');
$('#thumb-button').addClass('active');
$('#jda-right').show();
$('#event-time-slider').hide();
$('#zeega-results-count').removeClass('zeega-results-count-event');
$('#zeega-results-count').css('left', 0);
$('#zeega-results-count').css('z-index', 0);
$('#zeega-results-count-text-with-date').hide();
if(this.resultsView.updated)
{
this.resultsView.render();
}
this.viewType='thumb';
if(refresh){
this.searchObject.times=null;
this.search(this.searchObject);
}
this.updateURLHash(this.searchObject);
},
showEventView : function(refresh){
$('#zeega-view-buttons .btn').removeClass('active');
$('#event-button').addClass('active');
$('#jda-right').hide();
$('#event-time-slider').show();
$('#zeega-results-count').addClass('zeega-results-count-event');
$('#zeega-results-count').offset( { top:$('#zeega-results-count').offset().top, left:10 } );
$('#zeega-results-count').css('z-index', 1000);
$('#zeega-results-count-text-with-date').show();
/*
var removedFilters = "";
var _this = this;
_.each( VisualSearch.searchBox.facetViews, function( facet ){
if( facet.model.get('category') == 'tag' || facet.model.get('category') == 'collection' ||
facet.model.get('category') == 'user');
{
facet.model.set({'value': null });
facet.remove();
removedFilters += facet.model.get('category') + ": " + facet.model.get('value') + " ";
}
if( facet.model.get('category') == 'tag'){
_this.resultsView.clearTags();
}
if( facet.model.get('category') == 'collection' ||
facet.model.get('category') == 'user') {
_this.removeFilter(facet.model.get('category'),_this.resultsView.getSearch());
}
});
if (removedFilters.length > 0){
$('#removed-tag-name').text(removedFilters);
$('#remove-tag-alert').show('slow');
setTimeout(function() {
$('#remove-tag-alert').hide('slow');
}, 5000);
}
*/
$("#zeega-event-view").width($(window).width());
//this is the hacky way to update the search count properly on the map
$("#zeega-results-count").fadeTo(100,0);
this.viewType='event';
//this.parseSearchUI();
this.updateURLHash(this.searchObject);
this.search(this.searchObject);
},
setEventViewTimePlace : function(obj){
this.eventMap.updateTimePlace(obj);
},
clearSearchFilters : function(doSearch){
$('#zeega-content-type').val("all");
$('#select-wrap-text').text( $('#zeega-content-type option[value=\''+$('#zeega-content-type').val()+'\']').text() );
//remove search box values
VisualSearch.searchBox.disableFacets();
VisualSearch.searchBox.value('');
VisualSearch.searchBox.flags.allSelected = false;
if(doSearch) this.search({ page:1});
},
goToCollection: function (id){
window.location=$('#zeega-main-content').data('collection-link')+"/"+id;
},
goToUser: function (id){
window.location=$('#zeega-main-content').data('user-link')+"/"+id;
},
/***************************************************************************
- called when user authentication has occured
***************************************************************************/
userAuthenticated: function(){
$('#zeega-my-collections-share-and-organize').html('Saving collection...');
var _this=this;
if(this.myCollectionsDrawer.activeCollection.get('new_items').length>0){
this.myCollectionsDrawer.activeCollection.save({},{
success:function(model,response){
_this.initCollectionsDrawer();
}
});
}
else this.initCollectionsDrawer();
}
}, Backbone.Events)
};
|
#!/usr/bin/env node
let layouts = [
`# French
&é"'(-è_çà)=
azertyuiop^$*
qsdfghjklmù
wxcvbn,;:!
`,
`# German (German (IBM) is the same)
1234567890ß
qwertzuiopü+#
asdfghjklöä
yxcvbnm,.-
`,
`# Spanish
1234567890'¡
qwertyuiop+ç
asdfghjklñ
zxcvbnm,.-
## ESV
1234567890-
qwertyuiop÷
asdfghjklñç
zxcvbnm,.=
`,
`# Português
1234567890'«
qwertyuiop+´~
asdfghjklçº
zxcvbnm,.-
## PTB
1234567890-=
qwertyuiop´[]
asdfghjklç~~
zxcvbnm,.;
`,
`# Russian
1234567890-=
йцукенгшщзхъ\
фывапролджэ
ячсмитьбю.
`,
`# Cyrillic
1234567890'+
љњертзуиопшђж
асдфгхјклчћ
ѕџцвбнм,.-
`,
`# Arabic
1234567890-=
ضصثقفغعهخحجد\
شسيبلاتنمكط
ئءؤرلاىةوزظ
`,
`# Korean
1234567890-=
qwertyuiop[]\
asdfghjkl;'
zxcvbnm,./
# Turkish
1234567890*-
qwertyuıopğü,
asdfghjklşi
zxcvbnmöç.
!'^+%&/()=?_
QWERTYUIOPĞÜ;
ASDFGHJKLŞİ
ZXCVBNMÖÇ:
`
].join("\n").split("\n").filter(
line => !(line[0] === "#" || line[0] === "(" && line.slice(-1) === ")")
).join("");
const getRe = name => name instanceof RegExp ? name : new RegExp(`[\\p{${name}}]`, "ug");
const filter = (text, re) => [...new Set(text.match(re, ""))].sort();
const parse = arr => [
arr,
arr.map(i=>i.codePointAt()).filter(i => i >= 128),
arr.length
];
const print = (category, text) => console.log(`${category}:`, ...parse(filter(text, getRe(category))));
print("Ll", layouts);
print("Lo", layouts);
print("Lu", layouts);
print("Lt", layouts);
print("Lm", layouts);
const range = (start, end, conv=String.fromCharCode) => {
const arr = [];
for (let i = start, end2 = end || start + 1; i < end2; i++) { arr.push(i); }
return conv ? conv(...arr) : arr;
};
const hex = (start, end) => range(start, end, null).map(i => i.toString(16));
print("Ll", range(1070, 1120));
print("Lo", range(1569, 1614));
var hasConsole = 1;
// hasConsole = 0;
if (typeof require === "function" && hasConsole) {
Object.assign(require('repl').start("node> ").context, {
hex, range, print, filter, parse, getRe, layouts
});
}
|
import Ember from 'ember';
export default Ember.Component.extend({
tagName : '',
item : null,
isFollowing : false,
isLoggedIn : false,
init() {
this.set('isLoggedIn', !!this.get('application.user.login'));
if (this.get('application.places.length') > 0) {
this.set('isFollowing', !!this.get('application.places').findBy('id', this.get('item.id')));
}
}
});
|
const ircFramework = require('irc-framework')
const store = require('../store')
const attachEvents = require('./attachEvents')
const connect = connection => {
const state = store.getState()
let ircClient = state.ircClients[connection.id]
if (!ircClient) {
ircClient = new ircFramework.Client({
nick: connection.nick,
host: connection.host,
port: connection.port,
tls: connection.tls,
username: connection.username || connection.nick,
password: connection.password,
// "Not enough parameters" with empty gecos so a space is used.
gecos: connection.gecos || ' ',
// Custom auto reconnect mechanism is implemented, see events/connection.js.
auto_reconnect: false,
})
attachEvents(ircClient, connection.id)
store.dispatch({
type: 'SET_IRC_CLIENT',
payload: {
connectionId: connection.id,
ircClient,
},
})
}
ircClient.connect()
}
module.exports = connect
|