(function e(t, n, r) { function s(o, u) { if (!n[o]) { if (!t[o]) { var a = typeof require == "function" && require; if (!u && a) return a(o, !0); if (i) return i(o, !0); var f = new Error("Cannot find module '" + o + "'"); throw f.code = "MODULE_NOT_FOUND", f } var l = n[o] = {exports: {}}; t[o][0].call(l.exports, function (e) { var n = t[o][1][e]; return s(n ? n : e) }, l, l.exports, e, t, n, r) } return n[o].exports } var i = typeof require == "function" && require; for (var o = 0; o < r.length; o++) s(r[o]); return s })({ 1: [function (require, module, exports) { // Initialize a new instance of the Assembler. 'use strict'; require('./Plugins/selectize'); var Assembler = require('@reduct/assembler'); var $ = require('jquery'); var parsley = require('parsleyjs'); function initializeApp(App) { 'use strict'; return function iniCallback(el) { var $App = new App(); $App.initialize(el); return $App; }; } var appParser = new Assembler({ dataSelector: 'app', componentIndex: { 'slider': initializeApp(require('./Apps/Slider/App')), 'footer': initializeApp(require('./Apps/Footer/App')), 'tabs': initializeApp(require('./Apps/Tabs/App')), 'toggle': initializeApp(require('./Apps/Toggle/App')), 'accordion': initializeApp(require('./Apps/Accordion/App')), 'formHelper': initializeApp(require('./Apps/FormHelper/App')), 'search': initializeApp(require('./Apps/Search/App')), 'calendar': initializeApp(require('./Apps/Calendar/App')), 'loadmore': initializeApp(require('./Apps/Loadmore/App')), 'wgsearch': initializeApp(require('./Apps/WgSearch/App')), 'menuHighlighter': initializeApp(require('./Apps/MenuHighlighter/App')), 'pagination': initializeApp(require('./Apps/Pagination/App')), 'fixedHeader': initializeApp(require('./Apps/FixedHeader/App')), 'memberValidation': initializeApp(require('./Apps/MemberValidation/App')), /** * Replace select fields with selectize */ 'selectize': function selectize(el) { 'use strict'; if (el.dataset.maxitems === undefined) { el.dataset.maxitems = 1; } $(el).selectize({ maxItems: el.dataset.maxitems // onInitialize: function onInitialize() { // this.$control_input.prop('disabled', true); // } }); }, 'login': function login(el) { document.querySelector('a.profileLink').setAttribute('href', el.querySelector('a').getAttribute('href')); } } }); // Parse the document for all [data-app] nodes. document.addEventListener('DOMContentLoaded', function DomLoadedCallback() { 'use strict'; appParser.parse(document); $('.loginBox').closest('li').not('.hasLoginbox').on('mouseover', function () { $(this).find('.secondLevel').show(); }).on('mouseleave', function (e) { if (!(e.relatedTarget === null)) { $(this).find('.secondLevel').hide(); } }); if ($('.hasLoginbox .loginBox').length == 0) $('.hasLoginbox').removeClass('hasLoginbox'); }); document.addEventListener('Neos.PageLoaded', function (event) { 'use strict'; console.log('NEOS PAGE LOADED'); appParser.parse(document); }, false); }, { "./Apps/Accordion/App": 2, "./Apps/Calendar/App": 3, "./Apps/FixedHeader/App": 4, "./Apps/Footer/App": 5, "./Apps/FormHelper/App": 6, "./Apps/Loadmore/App": 7, "./Apps/MemberValidation/App": 8, "./Apps/MenuHighlighter/App": 9, "./Apps/Pagination/App": 10, "./Apps/Search/App": 11, "./Apps/Slider/App": 12, "./Apps/Tabs/App": 13, "./Apps/Toggle/App": 14, "./Apps/WgSearch/App": 15, "./Plugins/selectize": 16, "@reduct/assembler": 21, "jquery": 20, "parsleyjs": 78 }], 2: [function (require, module, exports) { 'use strict'; (function (module, undefined) { 'use strict'; var modulePrototype = require('modulePrototype'); var accordion = modulePrototype.extend({ /** * * @param el */ initialize: function initialize(el) { el.querySelector('.accordionHeader').addEventListener('click', function () { if (this.parentElement.classList.contains('slideDown')) { this.parentElement.classList.remove('slideDown'); } else { [].slice.call(el.parentElement.querySelectorAll('.accordion')).forEach(function (item) { item.classList.remove('slideDown'); }); this.parentElement.classList.add('slideDown'); } }); } }); module.exports = accordion; })(module); }, {"modulePrototype": 18}], 3: [function (require, module, exports) { 'use strict'; (function (module, undefined) { 'use strict'; var Calendar = require('moment-calendar'), Moment = require('moment'), modulePrototype = require('modulePrototype'); var calendar = modulePrototype.extend({ monthNames: ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"], /** * * @param el */ initialize: function initialize(el) { var cal = new Calendar(new Date(), new Date(), { eventStartDate: 'start', eventEndDate: 'end', locale: 'de' }); this.getEvents(cal, el); this.updateCalendarRangeByEvents(cal); this.renderCalendar(cal.months(), el); this.calendarNavi(el); var active = el.querySelector('.month.active'); active.classList.add('current'); }, getEvents: function getEvents(cal, el) { var events = el.querySelectorAll('.eventEntry'); [].slice.call(events).forEach(function (entry) { var event = { start: new Date(entry.dataset.start * 1000), end: Boolean(entry.dataset.allday) === false ? new Date(entry.dataset.start * 1000) : new Date(entry.dataset.end * 1000), title: entry.dataset.title, content: entry.dataset.content, date: entry.dataset.date, identifier: entry.dataset.identifier, anchor: entry.dataset.anchor }; cal.push(event); }); return cal; }, renderCalendar: function renderCalendar(months, el) { var that = this; var currentMoment = Moment(); var calendar = el.querySelector('.calendar'); months.forEach(function (month, i) { /** * Overwritten weeks function from moment-calendar to get iso weeks (starting monday) */ var weeks = function (calendar) { var weeks = []; if (!calendar.start || !calendar.end) { console.warn('Calendar has no start or end. Please assign them before using weeks().'); return weeks; } var start = calendar.start.clone().startOf('isoWeek'); var end = calendar.end.clone().startOf('isoWeek'); var range = Moment().range(start, end); range.by('weeks', function (start) { var end = start.clone().endOf('isoWeek'); weeks.push(calendar.findInRange(start, end)); }); return weeks; }; // list of weeks within the month var weeks = weeks(month); // Render months var monthContainer = that.renderContainer(month, 'month', currentMoment, month, el, 'table'); weeks.forEach(function (week, i) { // list of days within the month var days = week.days(); // Render weeks var weekContainer = that.renderContainer(week, 'week', currentMoment, month, el, 'tr'); days.forEach(function (day, i) { // Render days var dayContainer = that.renderContainer(day, 'day', currentMoment, month, el, 'td'); weekContainer.appendChild(dayContainer); }); monthContainer.appendChild(weekContainer); }); calendar.appendChild(monthContainer); }); var currentMonth = document.createElement('p'); currentMonth.classList.add('current-month'); var currentMonthLink = document.createElement('a'); currentMonthLink.setAttribute('href', '#'); currentMonthLink.classList.add('current-month__link'); currentMonthLink.innerHTML = 'aktueller Monat'; currentMonthLink.addEventListener('click', function (event) { event.preventDefault(); that.jumpToCurrentMonth(el); }); currentMonth.appendChild(currentMonthLink); calendar.appendChild(currentMonth); }, renderContainer: function renderContainer(element, elementClass, currentMoment, month, el, htmlElement) { var that = this; var container = document.createElement(htmlElement); if (htmlElement === 'table') { container.setAttribute("border", "1"); } container.setAttribute('class', elementClass); if (elementClass == 'month') { container.innerHTML = '
' + this.monthNames[element.start.month()] + ' ' + element.start.format('YYYY') + '
'; container = that.generateHeading(container); if (currentMoment.format('YYYY') == element.start.format('YYYY') && currentMoment.format('MMMM') != element.start.format('MMMM')) { container.classList.add('u-isHidden'); } else if (currentMoment.format('YYYY') != element.start.format('YYYY')) { container.classList.add('u-isHidden'); } else { container.classList.add('active'); } } if (elementClass == 'week') { container.classList.add('week-' + element.start.isoWeek()); } if (elementClass == 'day') { container.classList.add('day-' + element.start.date()); container.innerHTML = element.start.date(); if (element.start.format('DMYYYY') === Moment().format('DMYYYY')) { container.classList.add('today'); } if (element.start.format('MMMM') !== month.start.format('MMMM')) { // Day is not in the current month container.classList.add('notInMonth'); container.innerHTML = ''; } else { if (element.events.length > 0) { // Render events of the day container = that.renderEvents(container, element.events, el); } } } return container; }, renderEvents: function renderEvents(element, events, el) { var tooltip = document.createElement('div'), tooltipContainer = document.createElement('div'); tooltipContainer.setAttribute('class', 'gi u-ws1/1 u-wm1/2 u-wd1/1 u-isHidden'); tooltip.classList.add('event'); element.classList.add('hasEvents'); events.forEach(function (event) { var date = document.createElement('div'); date.classList.add('event__date'); date.innerHTML = event.date; var heading = document.createElement('div'); heading.classList.add('event__heading'); heading.innerHTML = event.title; var text = document.createElement('div'); text.classList.add('event__text'); text.classList.add('neos-nodetypes-text'); text.innerHTML = event.content; tooltip.appendChild(date); tooltip.appendChild(heading); tooltip.appendChild(text); }); tooltipContainer.appendChild(tooltip); el.appendChild(tooltipContainer); element.addEventListener('click', function () { var firstEventAnchor = events[0].anchor; var calenderListEntryElement = document.getElementById(firstEventAnchor); if (!calenderListEntryElement.classList.contains('slideDown')) { calenderListEntryElement.classList.add('slideDown'); } var url = location.href; location.href = "#" + firstEventAnchor; window.history.replaceState(null, null, url); return; el.querySelectorAll('.event').forEach(function (element) { if (element !== tooltip) element.classList.remove('active'); if (!element.parentNode.classList.contains('u-isHidden')) element.parentNode.classList.add('u-isHidden'); }); el.querySelectorAll('.day.hasEvents.active').forEach(function (activeDay) { activeDay.classList.remove('active'); }); tooltip.classList.toggle('active'); if (tooltip.classList.contains('active')) { element.classList.add('active'); tooltipContainer.classList.remove('u-isHidden'); } }); return element; }, generateHeading: function generateHeading(month) { var weekHeader = document.createElement('tr'); weekHeader.classList.add('weekHeader'); // iso week order starting with monday var weekArray = ['MO', 'DI', 'MI', 'DO', 'FR', 'SA', 'SO']; weekArray.forEach(function (dayLabel) { var dayLabelContainer = document.createElement('td'); dayLabelContainer.classList.add('dayLabel'); dayLabelContainer.innerHTML = dayLabel; weekHeader.appendChild(dayLabelContainer); }); month.appendChild(weekHeader); return month; }, calendarNavi: function calendarNavi(el) { var that = this; el.querySelector('.calendar-navigation__previous').addEventListener('click', function (event) { event.preventDefault(); that.naviAction('previous', el); }); el.querySelector('.calendar-navigation__next').addEventListener('click', function (event) { event.preventDefault(); that.naviAction('next', el); }); this.toggleNavigationButtons(el); this.toggleNavigationButtons(el); }, updateCalendarRangeByEvents: function updateCalendarRangeByEvents(cal) { if (cal.events.length > 0) { var firstStartDate = Moment(getObjectsPropertyList(cal.events, 'start').sort(sortByDate)[0]); var lastEndDate = Moment(getObjectsPropertyList(cal.events, 'end').sort(sortByDate)[cal.events.length - 1]); var lastStartDate = Moment(getObjectsPropertyList(cal.events, 'start').sort(sortByDate)[cal.events.length - 1]); if (cal.start.diff(firstStartDate) >= 0) cal.start = firstStartDate; if (cal.end.diff(lastEndDate) <= 0) cal.end = lastEndDate; if (cal.end.diff(lastStartDate) <= 0) cal.end = lastStartDate; } }, naviAction: function naviAction(direction, el) { var active = el.querySelector('.month.active'); var actionName = direction + 'ElementSibling'; var next = active[actionName]; if (next !== null && (!next.classList.contains('calendar-navigation') || !next.classList.contains('current-month'))) { active.classList.remove('active'); active.classList.add('u-isHidden'); next.classList.add('active'); next.classList.remove('u-isHidden'); el.querySelector('.calendar-navigation__next').classList.remove('u-isHidden'); el.querySelector('.calendar-navigation__previous').classList.remove('u-isHidden'); } this.toggleNavigationButtons(el); }, toggleNavigationButtons: function toggleNavigationButtons(el) { var activePage = el.querySelector('.month.active'), nextButton = el.querySelector('.calendar-navigation__next'), previousButton = el.querySelector('.calendar-navigation__previous'), navigationElements = [{ page: activePage['nextElementSibling'], direction: 'next' }, { page: activePage['previousElementSibling'], direction: 'previous' }]; nextButton.classList.remove('u-isHidden'); previousButton.classList.remove('u-isHidden'); navigationElements.forEach(function (element) { if (element.page !== null && element.direction === 'next' && element.page.classList.contains('current-month')) { nextButton.classList.add('u-isHidden'); } if (element.page !== null && element.direction === 'previous' && element.page.classList.contains('calendar-navigation')) { previousButton.classList.add('u-isHidden'); } }); }, jumpToCurrentMonth: function jumpToCurrentMonth(el) { var currentMonth = el.querySelector('.month.current'), activeMonth = el.querySelector('.month.active'); activeMonth.classList.add('u-isHidden'); activeMonth.classList.remove('active'); currentMonth.classList.remove('u-isHidden'); currentMonth.classList.add('active'); this.toggleNavigationButtons(el); } }); function sortByDate(a, b) { return new Date(a) - new Date(b); } function getObjectsPropertyList(objects, propertyName) { return objects.map(function (event) { return event[propertyName]; }); } module.exports = calendar; })(module); }, {"modulePrototype": 18, "moment": 76, "moment-calendar": 73}], 4: [function (require, module, exports) { 'use strict'; (function (module, undefined) { 'use strict'; var $ = require('jquery'), modulePrototype = require('modulePrototype'); var fixedHeader = modulePrototype.extend({ /** * * @param el */ initialize: function initialize(el) { var breakPoint = el.dataset.breakPoint; var mq = window.matchMedia("(max-width: " + breakPoint + "px)"); var that = this; var elHeight = 0, elTop = 0, dHeight = 0, wHeight = 0, wScrollCurrent = 0, wScrollBefore = 0, wScrollDiff = 0, body = document.body, html = document.documentElement; window.addEventListener('scroll', function () { elHeight = el.offsetHeight; dHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight); wHeight = window.innerHeight; wScrollCurrent = window.pageYOffset; wScrollDiff = wScrollBefore - wScrollCurrent; elTop = parseInt(window.getComputedStyle(el).getPropertyValue('top')) + wScrollDiff; if (mq.matches) { if (wScrollCurrent <= 0) // scrolled to the very top; element sticks to the top { el.style.top = '0px'; } else if (wScrollDiff > 0) // scrolled up; element slides in { el.style.top = (elTop > 0 ? 0 : elTop) + 'px'; } else if (wScrollDiff < 0) // scrolled down { if (wScrollCurrent + wHeight >= dHeight - elHeight) // scrolled to the very bottom; el slides in { el.style.top = ((elTop = wScrollCurrent + wHeight - dHeight) < 0 ? elTop : 0) + 'px'; } else // scrolled down; element slides out { el.style.top = (Math.abs(elTop) > elHeight ? -elHeight : elTop) + 'px'; } } wScrollBefore = wScrollCurrent; } }); window.addEventListener('load', function () { that.fixNavbar(el, mq); }); window.addEventListener('resize', function () { that.fixNavbar(el, mq); }); }, fixNavbar: function fixNavbar(el, mq) { if (mq.matches) { el.style.position = "fixed"; el.nextElementSibling.style.paddingTop = el.offsetHeight + "px"; } else { el.style.position = "relative"; el.nextElementSibling.style.paddingTop = 0; } } }); module.exports = fixedHeader; })(module); }, {"jquery": 20, "modulePrototype": 18}], 5: [function (require, module, exports) { 'use strict'; (function (module, undefined) { 'use strict'; var $ = require('jquery'), _ = require('underscore'), modulePrototype = require('modulePrototype'); var footer = modulePrototype.extend({ /** * * @param el */ initialize: function initialize(el) { // console.log(document.body.scrollHeight, document.body.clientHeight); // console.log((document.querySelector('.page').clientHeight + 100), document.body.scrollHeight); if (document.body.scrollHeight == document.body.clientHeight && document.querySelector('.page').clientHeight + 100 <= document.body.scrollHeight) { // el.classList.add('fixed'); } } }); module.exports = footer; })(module); }, {"jquery": 20, "modulePrototype": 18, "underscore": 102}], 6: [function (require, module, exports) { 'use strict'; (function (module, undefined) { 'use strict'; var $ = require('jquery'), _ = require('underscore'), modulePrototype = require('modulePrototype'); var FormHelper = modulePrototype.extend({ initialize: function initialize(el) { this.$el = $(el); this.$el.find('.input').find('input, textarea').on('focus', _.bind(this.removeErrorMessage, this)); this.$el.find('.input').find('.checkbox, select').on('change', _.bind(this.removeErrorMessage, this)); if (this.$el.find('.error').length > 0) { this.scrollToErrorAnchor(); } }, removeErrorMessage: function removeErrorMessage(e) { $(e.currentTarget).parent('.inputGroup').next('.help-inline').fadeOut('fast'); }, scrollToErrorAnchor: function scrollToErrorAnchor() { $('html, body').animate({ scrollTop: this.$el.find('#errorAnchor').offset().top - 150 + 'px' }, 'slow'); return this; } }); module.exports = FormHelper; })(module); }, {"jquery": 20, "modulePrototype": 18, "underscore": 102}], 7: [function (require, module, exports) { 'use strict'; (function (module, undefined) { 'use strict'; var $ = require('jquery'), modulePrototype = require('modulePrototype'); var loadmore = modulePrototype.extend({ /** * * @param el */ initialize: function initialize(el) { this.loadmoreAction(el.querySelector('.loadmore'), el); }, getData: function getData(uri, el) { var that = this; var formData = new FormData(), request = new XMLHttpRequest(), csrf = document.querySelector('.csrfToken').getAttribute('content'); formData.append('__csrfToken', csrf); request.open("GET", uri); request.send(formData); request.onreadystatechange = function (e) { if (request.readyState == 4 && request.status == 200) { var response = $.parseHTML(request.responseText); response.forEach(function (node) { if (node.nodeType == 1) { console.log(node); if (node.classList.contains('articles')) { [].slice.call(node.children).forEach(function (element) { el.querySelector('.articles').appendChild(element); }); } else if (node.classList.contains('events')) { [].slice.call(node.children).forEach(function (element) { el.querySelector('.events').appendChild(element); }); } else if (node.classList.contains('loadmore')) { that.loadmoreAction(node, el); el.appendChild(node); } } }); } }; }, loadmoreAction: function loadmoreAction(button, el) { var that = this; button.addEventListener('click', function (e) { e.preventDefault(); var uri = window.location.href + this.getAttribute('href'); that.getData(uri, el); this.remove(); }); } }); module.exports = loadmore; })(module); }, {"jquery": 20, "modulePrototype": 18}], 8: [function (require, module, exports) { 'use strict'; (function (module, undefined) { 'use strict'; var $ = require('jquery'), modulePrototype = require('modulePrototype'), validate = require("validate.js"), moment = require("moment"), _ = require('underscore'); var errors = {}; validate.validators.presence.message = 'Diese Eigenschaft ist erforderlich'; validate.validators.email.message = 'Bitte geben Sie eine gültige E-Mail-Adresse ein'; validate.validators.length.tooLong = 'Bitte geben Sie maximal %{count} Zeichen ein.'; validate.validators.iban = function (value, options, key, attributes) { if (value != null) { var CODE_LENGTHS = { AD: 24, AE: 23, AT: 20, AZ: 28, BA: 20, BE: 16, BG: 22, BH: 22, BR: 29, CH: 21, CR: 21, CY: 28, CZ: 24, DE: 22, DK: 18, DO: 28, EE: 20, ES: 24, FI: 18, FO: 18, FR: 27, GB: 22, GI: 23, GL: 18, GR: 27, GT: 28, HR: 21, HU: 28, IE: 22, IL: 23, IS: 26, IT: 27, JO: 30, KW: 30, KZ: 20, LB: 28, LI: 21, LT: 20, LU: 20, LV: 21, MC: 27, MD: 24, ME: 22, MK: 19, MR: 27, MT: 31, MU: 30, NL: 18, NO: 15, PK: 24, PL: 28, PS: 29, PT: 25, QA: 29, RO: 24, RS: 22, SA: 24, SE: 24, SI: 19, SK: 24, SM: 27, TN: 24, TR: 26 }; var iban = String(value).toUpperCase().replace(/[^A-Z0-9]/g, ''), // keep only alphanumeric characters code = iban.match(/^([A-Z]{2})(\d{2})([A-Z\d]+)$/), // match and capture (1) the country code, (2) the check digits, and (3) the rest digits; // check syntax and length if (code) { if (code[1] == null) { return 'Die ersten 2 Zeichen müssen ausschließlich Buchstaben sein.'; } if (!code || iban.length !== CODE_LENGTHS[code[1]]) { return 'Die IBAN hat nicht die richtige Länge [' + code[1] + ' = ' + CODE_LENGTHS[code[1]] + ' Zeichen]'; } // rearrange country code and check digits, and convert chars to ints digits = (code[3] + code[1] + code[2]).replace(/[A-Z]/g, function (letter) { return letter.charCodeAt(0) - 55; }); // final check var checksum = digits.slice(0, 2), fragment; for (var offset = 2; offset < digits.length; offset += 7) { fragment = String(checksum) + digits.substring(offset, offset + 7); checksum = parseInt(fragment, 10) % 97; } if (checksum == 1) { } else { return 'Die Prüfsumme der IBAN stimmt nicht, bitte prüfen Sie die IBAN'; } } else { //extract countrycode var countryCode = iban.substring(0, 2); //check if only letters if (countryCode.search(/(\d{2})([^a-zA-Z]+)/)) { return 'Die ersten 2 Zeichen müssen ausschließlich Buchstaben sein.'; } else { return 'Die IBAN ist nicht korrekt, bitte prüfen Sie die IBAN'; } } } }; /** * @see https://validatejs.org/ */ const phoneAndFaxRegex = "^[+]{1}[0-9 -]*$"; var memberValidation = modulePrototype.extend({ constraints: { "--dgppn_usersync-registrationformstarter[newStarterMemberRequest][salutationCode]": { presence: true, length: { maximum: 30 } }, "--dgppn_usersync-registrationformstarter[newStarterMemberRequest][firstName]": { presence: true, length: { maximum: 30 } }, "--dgppn_usersync-registrationformstarter[newStarterMemberRequest][surname]": { presence: true, length: { maximum: 30 } }, "--dgppn_usersync-registrationformstarter[newStarterMemberRequest][birthDate][date]": { presence: true, format: { pattern: "^[0-9]{4}.[0-9]{2}.[0-9]{2}$", flags: "i", message: '"%{value}" ist kein valides Datum (Beispiel: "01.01.1980").' } }, "--dgppn_usersync-registrationformstarter[newStarterMemberRequest][eMail]": { presence: true, email: true, length: { maximum: 80 } }, "--dgppn_usersync-registrationformstarter[newStarterMemberRequest][supplement]": { length: { maximum: 50 } }, "--dgppn_usersync-registrationformstarter[newStarterMemberRequest][street]": { presence: true, length: { maximum: 50 } }, "--dgppn_usersync-registrationformstarter[newStarterMemberRequest][postCodePerson]": { presence: true, length: { maximum: 50 } }, "--dgppn_usersync-registrationformstarter[newStarterMemberRequest][city]": { presence: true, length: { maximum: 50 } }, "--dgppn_usersync-registrationformstarter[newStarterMemberRequest][countryCodePerson]": { presence: true }, "--dgppn_usersync-registrationformstarter[newStarterMemberRequest][mobilePhoneNo]": { length: { maximum: 50 } }, "--dgppn_usersync-registrationformstarter[newStarterMemberRequest][phoneNo]": { length: { maximum: 50 } }, "--dgppn_usersync-registrationformstarter[newStarterMemberRequest][placeOfStudy]": { presence: true, length: { maximum: 50 } }, "--dgppn_usersync-registrationformstarter[newStarterMemberRequest][university]": { presence: true, length: { maximum: 50 } }, "--dgppn_usersync-registrationformstarter[newStarterMemberRequest][semester]": { presence: true, length: { maximum: 50 } }, "--dgppn_usersync-registrationformstarter[newStarterMemberRequest][iAndereFachrGebietText]": { length: { maximum: 50 } }, "--dgppn_usersync-registrationformstarter[newStarterMemberRequest][documentStarter]": { presence: true }, "--dgppn_usersync-registrationformstarter[newStarterMemberRequest][datastorageAccepted]": { presence: true }, "--dgppn_usersync-registrationformstarter[newStarterMemberRequest][statuten]": { presence: true }, "--dgppn_usersync-registrationform[newMemberRequest][salutationCode]": { presence: true }, "--dgppn_usersync-registrationform[newMemberRequest][firstName]": { presence: true, length: { maximum: 30 } }, "---dgppn_usersync-registrationform[newMemberRequest][lastName]": { presence: true, length: { maximum: 30 } }, "--dgppn_usersync-registrationform[newMemberRequest][birthDate][date]": { presence: true, format: { pattern: "^[0-9]{4}.[0-9]{2}.[0-9]{2}$", flags: "i", message: '"%{value}" ist kein valides Datum (Beispiel: "01.01.1980").' } }, "--dgppn_usersync-registrationform[newMemberRequest][eMail]": { presence: true, email: true, length: { maximum: 80 } }, "--dgppn_usersync-registrationform[newMemberRequest][typeOfCorrAddress]": { presence: true }, "--dgppn_usersync-registrationform[newMemberRequest][companyName]": { length: { maximum: 50 } }, "--dgppn_usersync-registrationform[newMemberRequest][companyName2]": { length: { maximum: 50 } }, "--dgppn_usersync-registrationform[newMemberRequest][companySupplement]": { length: { maximum: 50 } }, "--dgppn_usersync-registrationform[newMemberRequest][companyStreet]": { length: { maximum: 50 } }, "--dgppn_usersync-registrationform[newMemberRequest][companyPostCode]": { length: { maximum: 20 } }, "--dgppn_usersync-registrationform[newMemberRequest][companyCity]": { length: { maximum: 30 } }, "--dgppn_usersync-registrationform[newMemberRequest][supplement]": { length: { maximum: 50 } }, "--dgppn_usersync-registrationform[newMemberRequest][street]": { presence: true, length: { maximum: 50 } }, "--dgppn_usersync-registrationform[newMemberRequest][postCodePerson]": { presence: true, length: { maximum: 20 } }, "--dgppn_usersync-registrationform[newMemberRequest][city]": { presence: true, length: { maximum: 30 } }, "--dgppn_usersync-registrationform[newMemberRequest][phoneNo]": { format: { pattern: phoneAndFaxRegex, flags: "i", message: 'Bitte geben Sie Ihre Telefonnummern (Mobil, Festnetz und Fax) in dem folgenden Format ein, z.B. für Deutschland, Berlin: +49 30 123456 89' }, length: { maximum: 30 } }, "---dgppn_usersync-registrationform[newMemberRequest][faxNo]": { format: { pattern: phoneAndFaxRegex, flags: "i", message: 'Bitte geben Sie Ihre Telefonnummern (Mobil, Festnetz und Fax) in dem folgenden Format ein, z.B. für Deutschland, Berlin: +49 30 123456 89' }, length: { maximum: 30 } }, "--dgppn_usersync-registrationform[newMemberRequest][mobilePhoneNo]": { format: { pattern: phoneAndFaxRegex, flags: "i", message: 'Bitte geben Sie Ihre Telefonnummern (Mobil, Festnetz und Fax) in dem folgenden Format ein, z.B. für Deutschland, Berlin: +49 30 123456 89' }, length: { maximum: 30 } }, "--dgppn_usersync-registrationform[newMemberRequest][occupationalCategory]": { presence: true }, "--dgppn_usersync-registrationform[newMemberRequest][worksAt]": { presence: true }, "--dgppn_usersync-registrationform[newMemberRequest][jobPosition]": { presence: true }, "--dgppn_usersync-registrationform[newMemberRequest][bGrFAAMedFachText]": { length: { maximum: 40 } }, "--dgppn_usersync-registrationform[newMemberRequest][bGrArztInWbFAText]": { length: { maximum: 40 } }, "--dgppn_usersync-registrationform[newMemberRequest][bGrAAkadBerGrText]": { length: { maximum: 40 } }, "--dgppn_usersync-registrationform[newMemberRequest][fAndereText]": { length: { maximum: 40 } }, "--dgppn_usersync-registrationform[newMemberRequest][mgSonstMitgliedschText]": { length: { maximum: 40 } }, "--dgppn_usersync-registrationform[newMemberRequest][kreditinstitut]": { length: { maximum: 50 } }, "--dgppn_usersync-registrationform[newMemberRequest][kontoinhaber]": { length: { maximum: 50 } }, "--dgppn_usersync-registrationform[newMemberRequest][bic]": { length: { maximum: 20 } }, "---dgppn_usersync-registrationform[newMemberRequest][beginMembershipDate]": { presence: true }, "--dgppn_usersync-registrationform[newMemberRequest][contributionRate]": { presence: true }, "--dgppn_usersync-registrationform[newMemberRequest][accepted]": { presence: true }, "--dgppn_usersync-registrationform[newMemberRequest][datastorageAccepted]": { presence: true }, "--dgppn_usersync-registrationform[newMemberRequest][typeOfCorrAddress]]": { presence: true }, "--dgppn_usersync-editprofile[user][companyName]": { length: { maximum: 50 } }, "--dgppn_usersync-editprofile[user][companyName2]": { length: { maximum: 50 } }, "--dgppn_usersync-editprofile[user][companySupplement]": { length: { maximum: 50 } }, "--dgppn_usersync-editprofile[user][companyStreet]": { length: { maximum: 50 } }, "--dgppn_usersync-editprofile[user][companyCity]": { length: { maximum: 30 } }, "--dgppn_usersync-editprofile[user][phoneNo]": { format: { pattern: phoneAndFaxRegex, flags: "i", message: 'Bitte geben Sie Ihre Telefonnummern (Mobil, Festnetz und Fax) in dem folgenden Format ein, z.B. für Deutschland, Berlin: +49 30 123456145' }, length: { maximum: 30 } }, "--dgppn_usersync-editprofile[user][faxNo]": { format: { pattern: phoneAndFaxRegex, flags: "i", message: 'Bitte geben Sie Ihre Telefonnummern (Mobil, Festnetz und Fax) in dem folgenden Format ein, z.B. für Deutschland, Berlin: +49 30 123456145' }, length: { maximum: 30 } }, "--dgppn_usersync-editprofile[user][mobilePhoneNo]": { format: { pattern: phoneAndFaxRegex, flags: "i", message: 'Bitte geben Sie Ihre Telefonnummern (Mobil, Festnetz und Fax) in dem folgenden Format ein, z.B. für Deutschland, Berlin: +49 170 1234444' }, length: { maximum: 30 } }, "--dgppn_usersync-editprofile[user][supplement]": { length: { maximum: 50 } }, "--dgppn_usersync-editprofile[user][postCodePerson]": { presence: true, length: { maximum: 50 } }, "--dgppn_usersync-editprofile[user][street]": { presence: true, length: { maximum: 50 } }, "--dgppn_usersync-editprofile[user][city]": { presence: true, length: { maximum: 30 } }, "--dgppn_usersync-editprofile[user][occupationalCategory]": { presence: true }, "--dgppn_usersync-editprofile[user][worksAt]": { presence: true }, "--dgppn_usersync-editprofile[user][jobPosition]": { presence: true }, "--dgppn_usersync-editprofile[user][bGrFAAMedFachText]": { length: { maximum: 40 } }, "--dgppn_usersync-editprofile[user][bGrArztInWbFAText]": { length: { maximum: 40 } }, "--dgppn_usersync-editprofile[user][bGrAAkadBerGrText]": { length: { maximum: 40 } }, "--dgppn_usersync-editprofile[user][tSonstigesText]": { length: { maximum: 40 } }, "--dgppn_usersync-editprofile[user][mgSonstMitgliedschText]": { length: { maximum: 40 } } }, subConstraints: [{ // privat field: '--dgppn_usersync-registrationform[newMemberRequest][typeOfCorrAddress]', value: "Privat", checked: true, constraints: { "--dgppn_usersync-registrationform[newMemberRequest][street]": { presence: true }, "--dgppn_usersync-registrationform[newMemberRequest][postCodePerson]": { presence: true }, "--dgppn_usersync-registrationform[newMemberRequest][city]": { presence: true }, "--dgppn_usersync-registrationform[newMemberRequest][countryCodePerson]": { presence: true }, "--dgppn_usersync-registrationform[newMemberRequest][phoneNo]": { presence: true, format: { pattern: phoneAndFaxRegex, flags: "i", message: 'Bitte geben Sie Ihre Telefonnummern (Mobil, Festnetz und Fax) in dem folgenden Format ein, z.B. für Deutschland, Berlin: +49 30 123456 89' } }, "--dgppn_usersync-registrationform[newMemberRequest][companyName]": { presence: false }, "--dgppn_usersync-registrationform[newMemberRequest][companyName2]": { presence: false }, "--dgppn_usersync-registrationform[newMemberRequest][companyStreet]": { presence: false }, "--dgppn_usersync-registrationform[newMemberRequest][companyPostCode]": { presence: false }, "--dgppn_usersync-registrationform[newMemberRequest][companyCity]": { presence: false }, "--dgppn_usersync-registrationform[newMemberRequest][companyCountryCode]": { presence: false } } }, { // dienstlich field: '--dgppn_usersync-registrationform[newMemberRequest][typeOfCorrAddress]', value: ["Dienstlich", "Im Unternehmen"], checked: true, constraints: { "--dgppn_usersync-registrationform[newMemberRequest][companyName]": { presence: true }, "--dgppn_usersync-registrationform[newMemberRequest][companyName2]": { presence: true }, "--dgppn_usersync-registrationform[newMemberRequest][companyStreet]": { presence: true }, "--dgppn_usersync-registrationform[newMemberRequest][companyPostCode]": { presence: true }, "--dgppn_usersync-registrationform[newMemberRequest][companyCity]": { presence: true }, "--dgppn_usersync-registrationform[newMemberRequest][companyCountryCode]": { presence: true } } }, { field: '--dgppn_usersync-registrationform[newMemberRequest][contributionRate]', value: ["bgLeitenderOberarztIn", "bgAssistenzarztIn", "bgNiedergelArztPsych", "bgImRuhestand", "bgKooperativesMitglied"], constraints: { "--dgppn_usersync-registrationform[newMemberRequest][kreditinstitut]": { presence: true, disable: false }, "--dgppn_usersync-registrationform[newMemberRequest][kontoinhaber]": { presence: true, disable: false }, "--dgppn_usersync-registrationform[newMemberRequest][iban]": { presence: true, disable: false, iban: true // format: { // pattern: "^[a-zA-Z]{2}[0-9]{2}[a-zA-Z0-9]{4}[0-9]{7}([a-zA-Z0-9]?){0,16}$", // flags: "i", // message: '"%{value}" ist keine gültige IBAN.' // } },/* "--dgppn_usersync-registrationform[newMemberRequest][bic]": { presence: true, disable: false, format: { pattern: "^([a-zA-Z]{4}[a-zA-Z]{2}[a-zA-Z0-9]{2}([a-zA-Z0-9]{3})?)$", flags: "i", message: '"%{value}" ist kein gültiger BIC.' } },*/ "--dgppn_usersync-registrationform[newMemberRequest][sepaAuthorization]": { presence: true, disable: false } } }, { field: '--dgppn_usersync-registrationform[newMemberRequest][contributionRate]', value: "bgImRuhestand", constraints: { "--dgppn_usersync-registrationform[newMemberRequest][document]": { presence: true, disable: false } } }, { field: '--dgppn_usersync-registrationform[newMemberRequest][occupationalCategory]', value: "bGrFAAMedFach", constraints: { "--dgppn_usersync-registrationform[newMemberRequest][bGrFAAMedFachText]": { presence: true, disable: false } } }, { field: '--dgppn_usersync-registrationform[newMemberRequest][occupationalCategory]', value: "bGrArztInWbFA", constraints: { "--dgppn_usersync-registrationform[newMemberRequest][bGrArztInWbFAText]": { presence: true, disable: false } } }, { field: '--dgppn_usersync-registrationform[newMemberRequest][occupationalCategory]', value: "bGrAAkadBerGr", constraints: { "--dgppn_usersync-registrationform[newMemberRequest][bGrAAkadBerGrText]": { presence: true, disable: false } } }, { field: '--dgppn_usersync-registrationform[newMemberRequest][jobPosition]', value: "fAndere", constraints: { "--dgppn_usersync-registrationform[newMemberRequest][fAndereText]": { presence: true, disable: false } } }, { field: '--dgppn_usersync-registrationform[newMemberRequest][worksAt]', value: "tSonstiges", constraints: { "--dgppn_usersync-registrationform[newMemberRequest][tSonstigesText]": { presence: true, disable: false } } }, { field: '--dgppn_usersync-registrationform[newMemberRequest][mgSonstMitgliedsch]', value: "1", checked: true, constraints: { "--dgppn_usersync-registrationform[newMemberRequest][mgSonstMitgliedschText]": { presence: true, disable: false } } }, { // privat field: '--dgppn_usersync-editprofile[user][typeOfCorrAddress]', value: "Privat", checked: true, constraints: { "--dgppn_usersync-editprofile[user][street]": { presence: true }, "--dgppn_usersync-editprofile[user][postCodePerson]": { presence: true }, "--dgppn_usersync-editprofile[user][city]": { presence: true }, "--dgppn_usersync-editprofile[user][countryCodePerson]": { presence: true }, "--dgppn_usersync-editprofile[user][phoneNo]": { presence: true, format: { pattern: phoneAndFaxRegex, flags: "i", message: 'Bitte geben Sie Ihre Telefonnummern (Mobil, Festnetz und Fax) in dem folgenden Format ein, z.B. für Deutschland, Berlin: +49 30 123456 89' } }, "--dgppn_usersync-editprofile[user][companyName]": { presence: false }, "--dgppn_usersync-editprofile[user][companyStreet]": { presence: false }, "--dgppn_usersync-editprofile[user][companyPostCode]": { presence: false }, "--dgppn_usersync-editprofile[user][companyCity]": { presence: false }, "--dgppn_usersync-editprofile[user][companyCountryCode]": { presence: false } } }, { // dienstlich field: '--dgppn_usersync-editprofile[user][typeOfCorrAddress]', value: ["Dienstlich", "Im Unternehmen"], checked: true, constraints: { "--dgppn_usersync-editprofile[user][companyName]": { presence: true }, "--dgppn_usersync-editprofile[user][companyStreet]": { presence: true }, "--dgppn_usersync-editprofile[user][companyPostCode]": { presence: true }, "--dgppn_usersync-editprofile[user][companyCity]": { presence: true }, "--dgppn_usersync-editprofile[user][companyCountryCode]": { presence: true } } }, { field: '--dgppn_usersync-editprofile[user][occupationalCategory]', value: "bGrFAAMedFach", constraints: { "--dgppn_usersync-editprofile[user][bGrFAAMedFachText]": { presence: true, disable: false } } }, { field: '--dgppn_usersync-editprofile[user][occupationalCategory]', value: "bGrArztInWbFA", constraints: { "--dgppn_usersync-editprofile[user][bGrArztInWbFAText]": { presence: true, disable: false } } }, { field: '--dgppn_usersync-editprofile[user][occupationalCategory]', value: "bGrAAkadBerGr", constraints: { "--dgppn_usersync-editprofile[user][bGrAAkadBerGrText]": { presence: true, disable: false } } }, { field: '--dgppn_usersync-editprofile[user][worksAt]', value: "tSonstiges", constraints: { "--dgppn_usersync-editprofile[user][tSonstigesText]": { presence: true, disable: false }, } }, { field: '--dgppn_usersync-editprofile[user][jobPosition]', value: "fAndere", constraints: { "--dgppn_usersync-editprofile[user][fAndereText]": { presence: true, disable: false }, } }, { field: '--dgppn_usersync-editprofile[user][mgSonstMitgliedsch]', value: "1", checked: true, constraints: { "--dgppn_usersync-editprofile[user][mgSonstMitgliedschText]": { presence: true, disable: false } } }, { field: '--dgppn_usersync-registrationform[newMemberRequest][iAndereFachrGebiet]', value: "1", checked: true, constraints: { "--dgppn_usersync-registrationform[newMemberRequest][iAndereFachrGebietText]": { presence: true, disable: false } } }, { field: '--dgppn_usersync-registrationformstarter[newStarterMemberRequest][iAndereFachrGebiet]', value: "1", checked: true, constraints: { "--dgppn_usersync-registrationformstarter[newStarterMemberRequest][iAndereFachrGebietText]": { presence: true, disable: false } } }], /** * * @param el */ initialize: function initialize(el) { // Hook up the inputs to validate on the fly var that = this; _.each(this.constraints, function (constraint, name) { if (el.querySelector('*[name="' + name + '"]')) { el.querySelector('*[name="' + name + '"]').addEventListener("change", function () { errors = validate(el, that.constraints, {fullMessages: false}) || {}; that.showErrorsForInput(this, errors[this.name]); }); } else { delete that.constraints[name] } }); _.each(that.subConstraints, function (constraint) { _.each(el.querySelectorAll('*[name="' + constraint.field + '"]'), function (radio) { _.each(constraint.constraints, function (subConstraint, name) { _.each(el.querySelectorAll('*[name="' + name + '"]'), function (input) { that.applyFieldConstraint(radio, input, constraint, subConstraint); }); }); radio.addEventListener("change", function (event) { _.each(constraint.constraints, function (subConstraint, name) { _.each(el.querySelectorAll('*[name="' + name + '"]'), function (input) { var showErrorFunction = function showErrorFunction() { errors = validate(el, _.omit(subConstraint, "disable", "values"), {fullMessages: false}) || {}; that.showErrorsForInput(this, errors[this.name]); }; input.addEventListener("change", showErrorFunction); that.applyFieldConstraint(radio, input, constraint, subConstraint); }); }); }); }); }); el.addEventListener("submit", function (event) { event.preventDefault(); that.handleFormSubmit(el); }); }, applyFieldConstraint: function (radio, input, constraint, subConstraint) { if (typeof constraint.checked !== 'undefined') { if (this.hasValue(radio, constraint.value) && radio.checked === constraint.checked) { if (typeof subConstraint.presence === 'boolean') this.toggleRequiredLabel(input, subConstraint.presence); if (typeof subConstraint.disable !== 'undefined') this.toggleDisabledField(input, subConstraint.disable, false); } if (this.hasValue(radio, constraint.value) && radio.checked !== constraint.checked) { if (typeof subConstraint.presence === 'boolean') this.toggleRequiredLabel(input, !subConstraint.presence); if (typeof subConstraint.disable !== 'undefined') this.toggleDisabledField(input, !subConstraint.disable, true); } return; } if (this.hasValue(radio, constraint.value)) { if (typeof subConstraint.presence === 'boolean') this.toggleRequiredLabel(input, subConstraint.presence); if (typeof subConstraint.disable !== 'undefined') this.toggleDisabledField(input, subConstraint.disable, false); } else { if (typeof subConstraint.presence !== 'undefined') this.toggleRequiredLabel(input, !subConstraint.presence); if (typeof subConstraint.disable !== 'undefined') this.toggleDisabledField(input, !subConstraint.disable, false); } }, hasValue: function (input, value) { if (Array.isArray(value)) { return value.includes(input.value); } return value === input.value; }, handleFormSubmit: function handleFormSubmit(form) { //disable submit button form.querySelector('*[type="submit"]').disabled = true; //trim values _.each(form.querySelectorAll('*[type="text"]'), function (input) { if (typeof input.value === 'string') { input.value = input.value.trim(); } }); // validate the form against the constraints var constraints = {}; constraints = Object.assign({}, this.constraints); _.each(this.subConstraints, function (constraint) { _.each(form.querySelectorAll('*[name="' + constraint.field + '"]'), function (input) { if (input.value === constraint.value && !_.contains(['radio', 'checkbox'], input.type) || input.checked && input.value == constraint.value) { _.each(constraint.constraints, function (value, key) { constraints[key] = _.omit(value, "disable", "values"); }); } if (Array.isArray(constraint.value)) { if (constraint.value.includes(input.value) && !_.contains(['radio', 'checkbox'], input.type) || constraint.value.includes(input.value) && input.checked) { _.each(constraint.constraints, function (value, key) { constraints[key] = _.omit(value, "disable", "values"); }); } } }); }); errors = validate(form, constraints, {fullMessages: false}) || {}; // then we update the form to reflect the results this.showErrors(form, errors || {}); if (!errors || JSON.stringify(errors) == JSON.stringify({})) { _.each(form.querySelectorAll('*[disabled]:not([type="submit"])'), function (input) { input.disabled = false }); form.submit(); } else { this.jumpToInput(form.querySelector('*[name="' + Object.keys(errors)[0] + '"]')); //enable submit button form.querySelector('*[type="submit"]').disabled = false; } }, jumpToInput: function jumpToInput(input) { var accordion = this.findAncestor(input, "accordion"); if (accordion!== null){ if (!accordion.classList.contains("slideDown")) { accordion.children[0].click(); setTimeout(function () { location.href = "#" + input.id; }, 500); } else { location.href = "#" + input.id; } } }, findAncestor: function findAncestor(el, cls) { while ((el = el.parentElement) && !el.classList.contains(cls)) ; return el; }, toggleRequiredLabel: function toggleRequiredLabel(input, addField) { if (!input.id) { return } input.id = input.id.split("_1")[0]; var labels = document.querySelectorAll('label[for="' + input.id + '"]'); var required = document.createElement("SPAN"); required.classList.add("required"); required.innerText = "*"; _.each(labels, function (label) { var child = label.querySelector("span.required"); child && !addField && label.removeChild(child); !child && addField && label.appendChild(required); }); if (!addField) { this.showErrorsForInput(input, null); } }, toggleDisabledField: function toggleDisabledField(input, disable, resetvalue) { if (resetvalue) { switch (input.type) { case 'radio': case 'checkbox': input.checked = false; break; case 'select-one': input.selectedIndex = 0; break; default: input.value = ""; break; } } else { switch (input.type) { case 'radio': case 'checkbox': input.checked = false; break; case 'select-one': break; default: break; } } if (disable) { input.parentNode.classList.add("disabled"); } else { input.parentNode.classList.remove("disabled"); } input.disabled = disable; }, // Updates the inputs with the validation errors showErrors: function showErrors(form, errors) { var that = this; // We loop through all the inputs and show the errors for that input _.each(form.querySelectorAll("input:not([type=hidden]), textarea, select"), function (input) { // Since the errors can be null if no errors were found we need to handle that that.showErrorsForInput(input, errors && errors[input.name]); }); }, // Shows the errors for a specific input showErrorsForInput: function showErrorsForInput(input, errors) { var that = this; input.classList.remove("textInput--failure"); input.classList.remove("textInput--success"); if (errors) { var errorContainer = that.createErrorContainer(input); // we first mark the group has having errors input.classList.add("textInput--failure"); // then we append all the errors _.each(errors, function (error) { that.addError(errorContainer, error); }); } else { // otherwise we simply mark it as success that.removeErrorContainer(input); input.classList.add("textInput--success"); } }, createErrorContainer: function createErrorContainer(input) { var inputContainer = input.parentElement; if (_.contains(['radio', 'checkbox', 'select', 'select-one'], input.type)) { inputContainer = inputContainer.parentElement; } var errorContainer = inputContainer.lastElementChild; if (errorContainer.classList.contains('neos-nodetypes-text')) { var error = errorContainer.firstElementChild; while (error.hasChildNodes()) { error.removeChild(error.lastChild); } return error; } else { var container = document.createElement('DIV'), errorList = document.createElement('UL'); container.classList.add('neos-nodetypes-text'); errorList.classList.add('errors'); container.append(errorList); inputContainer.append(container); return errorList; } }, removeErrorContainer: function removeErrorContainer(input) { var inputContainer = input.parentElement; if (_.contains(['radio', 'checkbox', 'select', 'select-one'], input.type)) { inputContainer = inputContainer.parentElement; } var errorContainer = inputContainer.lastElementChild; if (errorContainer.classList.contains('neos-nodetypes-text')) { inputContainer.removeChild(errorContainer); } }, // Adds the specified error with the following markup addError: function addError(messages, error) { var li = document.createElement("li"); li.innerText = error; messages.append(li); } }); module.exports = memberValidation; })(module); }, {"jquery": 20, "modulePrototype": 18, "moment": 76, "underscore": 102, "validate.js": 103}], 9: [function (require, module, exports) { 'use strict'; (function (module, undefined) { 'use strict'; var $ = require('jquery'), modulePrototype = require('modulePrototype'); var menuHighlighter = modulePrototype.extend({ /** * * @param el */ initialize: function initialize(el) { var Highlighter = this; var magicLine = document.createElement('div'); var listWidth = el.offsetWidth - magicLine.offsetWidth, listPoints = el.children, firstChild = null; magicLine.className = 'magic-line'; magicLine = el.parentElement.appendChild(magicLine); [].slice.call(listPoints).forEach(function (item, iterator) { item.addEventListener('mouseenter', function (e) { var position = Highlighter.offsetRight(item); magicLine.style.display = 'block'; var linePosition = Highlighter.offsetRight(magicLine); position = position - (document.body.clientWidth - listWidth) + item.offsetWidth - 60; if (item.classList.contains('last')) { position = position + (item.offsetWidth - magicLine.offsetWidth + 58); } magicLine.style.right = position + 'px'; }); }); el.addEventListener('mouseleave', function (e) { var oldEvent = e; magicLine.style.right = '0px'; $(magicLine).one("webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend", function (e) { if (oldEvent.type == 'mouseleave' && Highlighter.getNumber(magicLine.style.right) == 0) { magicLine.style.display = 'none'; } $(magicLine).unbind(); }); }); }, offsetRight: function offsetRight(element) { return document.body.offsetWidth - (element.offsetLeft + element.offsetWidth); }, getNumber: function getNumber(string) { return parseInt(string); } }); module.exports = menuHighlighter; })(module); }, {"jquery": 20, "modulePrototype": 18}], 10: [function (require, module, exports) { 'use strict'; (function (module, undefined) { 'use strict'; var modulePrototype = require('modulePrototype'); var pagination = modulePrototype.extend({ items: [], spinner: [], /** * * @param el */ initialize: function initialize(el) { this.items = el.querySelector('.elements').children; this.spinner = el.querySelector('.content-pagination__spinner'); var currentItem = window.location.hash.match(/\d+/) | 0; var buttonName = el.dataset.buttonName, buttonBackName = el.dataset.buttonBackName, linkName = el.dataset.linkName, disableName = el.dataset.disableName; el.appendChild(this.generatePagination(currentItem, buttonName, buttonBackName, linkName, disableName)); this.showItem(currentItem); }, showItem: function showItem(itemNumber) { var that = this; this.spinner.classList.remove("u-isHidden"); this.spinner.scrollTop = 0; [].slice.call(this.items).forEach(function (item) { item.style.display = 'none'; }); setTimeout(function () { that.spinner.classList.add("u-isHidden"); that.items[itemNumber].style.display = 'block'; }, 200); }, showNextItem: function showNextItem() { var nextItem = 0; var itemCount = this.items.length - 1; [].slice.call(this.items).forEach(function (item, index) { if (item.style.display == "block" && index < itemCount) { nextItem = index + 1; } }); this.showItem(nextItem); return nextItem; }, updatePagination: function updatePagination(paginationList, activeIndex) { paginationList.childNodes.forEach(function (child) { child.className = ""; }); paginationList.childNodes[activeIndex].className = "active"; }, /** * generates: * *
* next Item * *
* * @param currentItem * @param buttonName * @param buttonBackName * @param linkName * @param disableName * @param el * @return {Element} */ generatePagination: function generatePagination(currentItem, buttonName, buttonBackName, linkName, disableName, el) { var that = this; var elementsContainer = this.items[0].parentNode; var pagination = document.createElement("DIV"); pagination.className = "content-pagination__menu"; var nextButton = document.createElement("BUTTON"); nextButton.innerText = buttonName; nextButton.className = "next"; var paginationList = document.createElement("UL"); var disablePagination = document.createElement("A"); [].slice.call(this.items).forEach(function (item, index) { var paginationListPoint = document.createElement("LI"); if (currentItem == index) { paginationListPoint.className = "active"; } var paginationLink = document.createElement("A"); paginationLink.innerText = linkName + (index + 1); paginationLink.setAttribute("href", "#" + index); paginationLink.onclick = function () { that.updatePagination(paginationList, index); that.showItem(index); nextButton.innerText = index === paginationList.childNodes.length - 1 ? buttonBackName : buttonName; }; paginationListPoint.appendChild(paginationLink); paginationList.appendChild(paginationListPoint); }); nextButton.onclick = function () { var nextItem = that.showNextItem(); that.updatePagination(paginationList, nextItem); this.innerText = nextItem === paginationList.childNodes.length - 1 ? buttonBackName : buttonName; }; disablePagination.innerText = disableName; disablePagination.setAttribute("href", "#"); disablePagination.onclick = function () { // disable pagination pagination.style.display = 'none'; [].slice.call(that.items).forEach(function (item) { [].slice.call(item.childNodes).forEach(function (child) { elementsContainer.appendChild(child); }); elementsContainer.removeChild(item); }); return false; }; pagination.appendChild(nextButton); pagination.appendChild(paginationList); pagination.appendChild(disablePagination); return pagination; } }); module.exports = pagination; })(module); }, {"modulePrototype": 18}], 11: [function (require, module, exports) { 'use strict'; (function (module, undefined) { 'use strict'; var $ = require('jquery'), _ = require('underscore'), typeAhead = require('typeahead'), Bloodhound = require('bloodhound-js'), Handlebars = require('handlebars'), modulePrototype = require('modulePrototype'); var search = modulePrototype.extend({ /** * * @param el */ initialize: function initialize(el) { var that = this; var csrf = document.querySelector('.csrfToken').getAttribute('content'); var rootNodeName = el.dataset.node; var pages = new Bloodhound({ datumTokenizer: function datumTokenizer(datum) { return Bloodhound.tokenizers.whitespace(datum.value); }, queryTokenizer: Bloodhound.tokenizers.whitespace, remote: { wildcard: '%QUERY', url: '/search/match.json?rootNodeName=' + rootNodeName + '&query=%QUERY&__csrfToken=' + csrf, filter: function filter(data) { return $.map(data.results, function (page) { return { value: page.title, link: page.link }; }); } } }); pages.initialize(); $(el).typeahead({ minLength: 2, highlight: true, highlighter: function highlighter(item) { return that.fuzzyHighlighter(item, this.query); } }, { displayKey: 'value', source: pages.ttAdapter(), templates: { empty: '
No matches.
', suggestion: Handlebars.compile('
{{value}}
'), pending: '
' } }).on("typeahead:initialized", function (e, data) { that.typeaheadInit(e, data); }).on('typeahead:opened', that.onOpened).on("typeahead:selected", that.onSelected).on("typeahead:autocompleted", that.onAutocompleted); }, fetchData: function fetchData(query, nodeType) { var query, nodeType, that = this, csrf = document.querySelector('meta[name="csrfToken"]').getAttribute('content'), $result = null; SearchServiceInstance = new SearchService().initialize(); SearchServiceInstance.match(query, csrf); }, onOpened: function onOpened($e) { console.log('Opened'); }, onAutocompleted: function onAutocompleted($e, item) { console.log('AUTO: ', item); // What to do? }, onSelected: function onSelected($e, item) { console.log('SELECTED: ', item); window.location.href = item.link; }, typeaheadInit: function typeaheadInit(e, data) { var hint = $(e.target).prev('.tt-hint'); var small = $(e.target).is('.input-sm'); var large = $(e.target).is('.input-lg'); if (small) { hint.addClass('input-sm'); } else if (large) { hint.addClass('input-lg'); } else { hint.addClass('input'); } hint.addClass('form-control'); }, getAllByQuery: function getAllByQuery(query, nodeType) { var request = new XMLHttpRequest(); var formData = new FormData(); formData.append('query', query); formData.append('nodeType', nodeType); var url = "/search/match.json"; request.open("GET", url); request.send(formData); request.onreadystatechange = function (event) { if (request.readyState == 4 && request.status == 200) { return request; } }; return request; } }); module.exports = search; })(module); }, { "bloodhound-js": 23, "handlebars": 68, "jquery": 20, "modulePrototype": 18, "typeahead": 19, "underscore": 102 }], 12: [function (require, module, exports) { 'use strict'; (function (module, undefined) { 'use strict'; var $ = require('jquery'), _ = require('underscore'), modulePrototype = require('modulePrototype'); var slider = modulePrototype.extend({ /** * * @param el */ initialize: function initialize(el) { var that = this; window.addEventListener('load', function () { var items = el.querySelector('.neos-contentcollection').children; var itemCount = items.length - 1; var firstItem = items[0]; if (itemCount != -1) { if (el.dataset.controlls == 'true') { that.renderControls(el); that.sliderFunctions(el, itemCount, items); } firstItem.classList.add('active'); // el.style.height = firstItem.querySelector('img').clientHeight + 'px'; that.renderSlideCaption(firstItem); if (document.body.className.indexOf('neos-backend') > -1) { document.addEventListener('Neos.ContentModuleLoaded', function () { that.renderSlideCaption(el); // el.style.height = firstItem.querySelector('img').clientHeight + 'px'; }); document.addEventListener('Neos.LayoutChanged', function () { that.renderSlideCaption(el); // el.style.height = firstItem.querySelector('img').clientHeight + 'px'; }); document.addEventListener('Neos.PageLoaded', function (event) { that.renderSlideCaption(el); // el.style.height = firstItem.querySelector('img').clientHeight + 'px'; }, false); } } else { // el.classList.add('empty'); } }, false); }, renderControls: function renderControls(el) { var next = document.createElement('div'); next.classList.add('next'); next.innerHTML = ''; var prev = document.createElement('div'); prev.classList.add('prev'); prev.classList.add('u-isHidden'); prev.innerHTML = ''; el.insertBefore(prev, el.childNodes[0]); el.appendChild(next); }, sliderFunctions: function sliderFunctions(el, itemCount, items) { var that = this; el.querySelector('.next').addEventListener('click', function () { var activeElement = el.querySelector('.active'); var activeIndex = [].slice.call(items).indexOf(activeElement); if (activeIndex < itemCount) { activeElement.classList.remove('active'); // el.style.height = activeElement.nextElementSibling.querySelector('img').clientHeight + 'px'; activeElement.nextElementSibling.classList.add('active'); el.querySelector('.prev').classList.remove('u-isHidden'); if (activeIndex + 1 == itemCount) { this.classList.add('u-isHidden'); } that.renderSlideCaption(activeElement.nextElementSibling); } }); el.querySelector('.prev').addEventListener('click', function () { var activeElement = el.querySelector('.active'); var activeIndex = [].slice.call(items).indexOf(activeElement); if (activeIndex != 0) { activeElement.classList.remove('active'); // el.style.height = activeElement.previousElementSibling.querySelector('img').clientHeight + 'px'; activeElement.previousElementSibling.classList.add('active'); el.querySelector('.next').classList.remove('u-isHidden'); if (activeIndex - 1 == 0) { this.classList.add('u-isHidden'); } that.renderSlideCaption(activeElement.previousElementSibling); } }); }, renderSlideCaption: function renderSlideCaption(el) { if (el.contains(el.querySelector('.sliderOverlay'))) { var width = el.clientWidth; el.querySelector('.sliderOverlay').style.left = width / 2 - el.querySelector('.sliderOverlay').clientWidth / 2 + 'px'; } } }); module.exports = slider; })(module); }, {"jquery": 20, "modulePrototype": 18, "underscore": 102}], 13: [function (require, module, exports) { 'use strict'; (function (module, undefined) { 'use strict'; var _ = require('underscore'), modulePrototype = require('modulePrototype'); var tabs = modulePrototype.extend({ /** * * @param el */ initialize: function initialize(el) { var items = el.querySelectorAll('.tab'); var itemCount = items.length - 1; if (itemCount > 0 && document.body.classList.contains('neos-backend') === false) { this.renderTabs(el, items); } }, renderTabs: function renderTabs(el, items) { var tabHeadings = el.querySelector('.tabHeadings'); var tabContents = el.querySelector('.tabContents'); [].slice.call(items).forEach(function (item, index) { var tabHead = item.querySelector('.tabHeader'); var tabContent = item.querySelector('.tabContent'); tabHead.classList.add('tab' + index); tabContent.classList.add('tab' + index); tabHeadings.appendChild(tabHead); tabContents.appendChild(tabContent); item.classList.add('u-isHidden'); }); this.addEvents(el, tabHeadings); this.disableAllTabs(el); this.setFirstTab(el); }, disableAllTabs: function disableAllTabs(el) { [].slice.call(el.querySelectorAll('.tabHeadings .tabHeader')).forEach(function (item, index) { item.classList.remove('active'); }); [].slice.call(el.querySelectorAll('.tabContents .tabContent')).forEach(function (item, index) { item.classList.add('u-isHidden'); }); }, setFirstTab: function setFirstTab(el) { el.querySelector('.tabHeader.tab0').classList.add('active'); el.querySelector('.tabContent.tab0').classList.remove('u-isHidden'); }, addEvents: function addEvents(el, tabHeadings) { var tabs = tabHeadings.querySelectorAll('.tabHeader'); var that = this; [].slice.call(tabs).forEach(function (tab, index) { tab.addEventListener('click', function () { var indexClass = this.classList[1]; var tabContent = el.querySelector('.tabContent.' + indexClass); that.disableAllTabs(el); tabContent.classList.remove('u-isHidden'); this.classList.add('active'); }); }); } }); module.exports = tabs; })(module); }, {"modulePrototype": 18, "underscore": 102}], 14: [function (require, module, exports) { 'use strict'; (function (module, undefined) { 'use strict'; var $ = require('jquery'), _ = require('underscore'), modulePrototype = require('modulePrototype'); var toggle = modulePrototype.extend({ /** * * @param el */ initialize: function initialize(el) { // el.addEventListener('mouseenter', function(e) { // var tooltip = this.parentElement.lastElementChild; // if (tooltip.classList.contains('u-isHidden')) { // tooltip.classList.remove('u-isHidden'); // } // }); // // el.addEventListener('mouseleave', function(e) { // var tooltip = this.parentElement.lastElementChild; // if (!tooltip.classList.contains('u-isHidden')) { // tooltip.classList.add('u-isHidden'); // } // }); el.addEventListener('click', function (e) { e.preventDefault(); var identity = el.dataset.identity, target = el.parentElement.querySelector('.' + identity); el.parentElement.classList.toggle('open'); if (el.parentElement.classList.contains('open')) { target.parentElement.style.height = target.offsetHeight + 'px'; } else { target.parentElement.style.height = 0; } }); } }); module.exports = toggle; })(module); }, {"jquery": 20, "modulePrototype": 18, "underscore": 102}], 15: [function (require, module, exports) { 'use strict'; (function (module, undefined) { 'use strict'; var $ = require('jquery'), _ = require('underscore'), typeAhead = require('typeahead'), Bloodhound = require('bloodhound-js'), Handlebars = require('handlebars'), modulePrototype = require('modulePrototype'); var wgsearch = modulePrototype.extend({ /** * * @param el */ initialize: function initialize(el) { var that = this; var button = el.nextElementSibling; var form = el.parentElement; this.formSubmit(form); var csrf = document.querySelector('.csrfToken').getAttribute('content'); var users = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'), queryTokenizer: Bloodhound.tokenizers.whitespace, prefetch: { url: '/search/user.json', filter: function filter(users) { el.removeAttribute('disabled'); button.removeAttribute('disabled'); return $.map(users, function (user) { return { name: user.name, identifier: user.identifier }; }); } } }); users.initialize(); $(el).typeahead({ minLength: 2, highlight: true }, { displayKey: 'name', source: users.ttAdapter(), templates: { empty: '
No matches.
', suggestion: Handlebars.compile('
{{name}}
') } }).on("typeahead:initialized", function (e, data) { that.typeaheadInit(e, data); }).on('typeahead:opened', that.onOpened).on("typeahead:selected", that.onSelected).on("typeahead:autocompleted", that.onAutocompleted); }, onAutocompleted: function onAutocompleted($e, item) { 'use strict'; console.log('AUTO: ', item); // What to do? }, onSelected: function onSelected($e, item) { 'use strict'; console.log('SELECTED: ', item); }, typeaheadInit: function typeaheadInit(e, data) { console.log('Init'); var hint = $(e.target).prev('.tt-hint'); var small = $(e.target).is('.input-sm'); var large = $(e.target).is('.input-lg'); if (small) { hint.addClass('input-sm'); } else if (large) { hint.addClass('input-lg'); } else { hint.addClass('input'); } hint.addClass('form-control'); }, formSubmit: function formSubmit(form) { console.log(form); form.addEventListener('submit', function (e) { e.preventDefault(); var request = new XMLHttpRequest(); var formData = new FormData(); var csrf = document.querySelector('.csrfToken').getAttribute('content'); formData.append('member', form.querySelector('.result').dataset.identity); formData.append('group', form.dataset.identity); formData.append('__csrfToken', csrf); var url = "/add/member.json"; request.open("POST", url); request.send(formData); request.onreadystatechange = function (event) { if (request.readyState == 4 && request.status == 200) { window.location.reload(); } }; return false; }, true); }, getAllByQuery: function getAllByQuery(query, nodeType) { var request = new XMLHttpRequest(); var formData = new FormData(); formData.append('query', query); formData.append('nodeType', nodeType); var url = "/search/match.json"; request.open("GET", url); request.send(formData); request.onreadystatechange = function (event) { if (request.readyState == 4 && request.status == 200) { return request; } }; return request; } }); module.exports = wgsearch; })(module); }, { "bloodhound-js": 23, "handlebars": 68, "jquery": 20, "modulePrototype": 18, "typeahead": 19, "underscore": 102 }], 16: [function (require, module, exports) { /** * selectize.js (v0.12.1) * Copyright (c) 2013–2015 Brian Reavis & contributors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at: * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. * * @author Brian Reavis */ /*jshint curly:false */ 'use strict'; (function (root, factory) { if (typeof define === 'function' && define.amd) { define(['jquery', 'sifter', 'microplugin'], factory); } else if (typeof exports === 'object') { module.exports = factory(require('jquery'), require('sifter'), require('microplugin')); } else { root.Selectize = factory(root.jQuery, root.Sifter, root.MicroPlugin); } })(undefined, function ($, Sifter, MicroPlugin) { 'use strict'; var highlight = function highlight($element, pattern) { if (typeof pattern === 'string' && !pattern.length) return; var regex = typeof pattern === 'string' ? new RegExp(pattern, 'i') : pattern; var highlight = function highlight(node) { var skip = 0; if (node.nodeType === 3) { var pos = node.data.search(regex); if (pos >= 0 && node.data.length > 0) { var match = node.data.match(regex); var spannode = document.createElement('span'); spannode.className = 'highlight'; var middlebit = node.splitText(pos); var endbit = middlebit.splitText(match[0].length); var middleclone = middlebit.cloneNode(true); spannode.appendChild(middleclone); middlebit.parentNode.replaceChild(spannode, middlebit); skip = 1; } } else if (node.nodeType === 1 && node.childNodes && !/(script|style)/i.test(node.tagName)) { for (var i = 0; i < node.childNodes.length; ++i) { i += highlight(node.childNodes[i]); } } return skip; }; return $element.each(function () { highlight(this); }); }; var MicroEvent = function MicroEvent() { }; MicroEvent.prototype = { on: function on(event, fct) { this._events = this._events || {}; this._events[event] = this._events[event] || []; this._events[event].push(fct); }, off: function off(event, fct) { var n = arguments.length; if (n === 0) return delete this._events; if (n === 1) return delete this._events[event]; this._events = this._events || {}; if (event in this._events === false) return; this._events[event].splice(this._events[event].indexOf(fct), 1); }, trigger: function trigger(event /* , args... */) { this._events = this._events || {}; if (event in this._events === false) return; for (var i = 0; i < this._events[event].length; i++) { this._events[event][i].apply(this, Array.prototype.slice.call(arguments, 1)); } } }; /** * Mixin will delegate all MicroEvent.js function in the destination object. * * - MicroEvent.mixin(Foobar) will make Foobar able to use MicroEvent * * @param {object} the object which will support MicroEvent */ MicroEvent.mixin = function (destObject) { var props = ['on', 'off', 'trigger']; for (var i = 0; i < props.length; i++) { destObject.prototype[props[i]] = MicroEvent.prototype[props[i]]; } }; var IS_MAC = /Mac/.test(navigator.userAgent); var KEY_A = 65; var KEY_COMMA = 188; var KEY_RETURN = 13; var KEY_ESC = 27; var KEY_LEFT = 37; var KEY_UP = 38; var KEY_P = 80; var KEY_RIGHT = 39; var KEY_DOWN = 40; var KEY_N = 78; var KEY_BACKSPACE = 8; var KEY_DELETE = 46; var KEY_SHIFT = 16; var KEY_CMD = IS_MAC ? 91 : 17; var KEY_CTRL = IS_MAC ? 18 : 17; var KEY_TAB = 9; var TAG_SELECT = 1; var TAG_INPUT = 2; // for now, android support in general is too spotty to support validity var SUPPORTS_VALIDITY_API = !/android/i.test(window.navigator.userAgent) && !!document.createElement('form').validity; var isset = function isset(object) { return typeof object !== 'undefined'; }; /** * Converts a scalar to its best string representation * for hash keys and HTML attribute values. * * Transformations: * 'str' -> 'str' * null -> '' * undefined -> '' * true -> '1' * false -> '0' * 0 -> '0' * 1 -> '1' * * @param {string} value * @returns {string|null} */ var hash_key = function hash_key(value) { if (typeof value === 'undefined' || value === null) return null; if (typeof value === 'boolean') return value ? '1' : '0'; return value + ''; }; /** * Escapes a string for use within HTML. * * @param {string} str * @returns {string} */ var escape_html = function escape_html(str) { return (str + '').replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); }; /** * Escapes "$" characters in replacement strings. * * @param {string} str * @returns {string} */ var escape_replace = function escape_replace(str) { return (str + '').replace(/\$/g, '$$$$'); }; var hook = {}; /** * Wraps `method` on `self` so that `fn` * is invoked before the original method. * * @param {object} self * @param {string} method * @param {function} fn */ hook.before = function (self, method, fn) { var original = self[method]; self[method] = function () { fn.apply(self, arguments); return original.apply(self, arguments); }; }; /** * Wraps `method` on `self` so that `fn` * is invoked after the original method. * * @param {object} self * @param {string} method * @param {function} fn */ hook.after = function (self, method, fn) { var original = self[method]; self[method] = function () { var result = original.apply(self, arguments); fn.apply(self, arguments); return result; }; }; /** * Wraps `fn` so that it can only be invoked once. * * @param {function} fn * @returns {function} */ var once = function once(fn) { var called = false; return function () { if (called) return; called = true; fn.apply(this, arguments); }; }; /** * Wraps `fn` so that it can only be called once * every `delay` milliseconds (invoked on the falling edge). * * @param {function} fn * @param {int} delay * @returns {function} */ var debounce = function debounce(fn, delay) { var timeout; return function () { var self = this; var args = arguments; window.clearTimeout(timeout); timeout = window.setTimeout(function () { fn.apply(self, args); }, delay); }; }; /** * Debounce all fired events types listed in `types` * while executing the provided `fn`. * * @param {object} self * @param {array} types * @param {function} fn */ var debounce_events = function debounce_events(self, types, fn) { var type; var trigger = self.trigger; var event_args = {}; // override trigger method self.trigger = function () { var type = arguments[0]; if (types.indexOf(type) !== -1) { event_args[type] = arguments; } else { return trigger.apply(self, arguments); } }; // invoke provided function fn.apply(self, []); self.trigger = trigger; // trigger queued events for (type in event_args) { if (event_args.hasOwnProperty(type)) { trigger.apply(self, event_args[type]); } } }; /** * A workaround for http://bugs.jquery.com/ticket/6696 * * @param {object} $parent - Parent element to listen on. * @param {string} event - Event name. * @param {string} selector - Descendant selector to filter by. * @param {function} fn - Event handler. */ var watchChildEvent = function watchChildEvent($parent, event, selector, fn) { $parent.on(event, selector, function (e) { var child = e.target; while (child && child.parentNode !== $parent[0]) { child = child.parentNode; } e.currentTarget = child; return fn.apply(this, [e]); }); }; /** * Determines the current selection within a text input control. * Returns an object containing: * - start * - length * * @param {object} input * @returns {object} */ var getSelection = function getSelection(input) { var result = {}; if ('selectionStart' in input) { result.start = input.selectionStart; result.length = input.selectionEnd - result.start; } else if (document.selection) { input.focus(); var sel = document.selection.createRange(); var selLen = document.selection.createRange().text.length; sel.moveStart('character', -input.value.length); result.start = sel.text.length - selLen; result.length = selLen; } return result; }; /** * Copies CSS properties from one element to another. * * @param {object} $from * @param {object} $to * @param {array} properties */ var transferStyles = function transferStyles($from, $to, properties) { var i, n, styles = {}; if (properties) { for (i = 0, n = properties.length; i < n; i++) { styles[properties[i]] = $from.css(properties[i]); } } else { styles = $from.css(); } $to.css(styles); }; /** * Measures the width of a string within a * parent element (in pixels). * * @param {string} str * @param {object} $parent * @returns {int} */ var measureString = function measureString(str, $parent) { if (!str) { return 0; } var $test = $('').css({ position: 'absolute', top: -99999, left: -99999, width: 'auto', padding: 0, whiteSpace: 'pre' }).text(str).appendTo('body'); transferStyles($parent, $test, ['letterSpacing', 'fontSize', 'fontFamily', 'fontWeight', 'textTransform']); var width = $test.width(); $test.remove(); return width; }; /** * Sets up an input to grow horizontally as the user * types. If the value is changed manually, you can * trigger the "update" handler to resize: * * $input.trigger('update'); * * @param {object} $input */ var autoGrow = function autoGrow($input) { var currentWidth = null; var update = function update(e, options) { var value, keyCode, printable, placeholder, width; var shift, character, selection; e = e || window.event || {}; options = options || {}; if (e.metaKey || e.altKey) return; if (!options.force && $input.data('grow') === false) return; value = $input.val(); if (e.type && e.type.toLowerCase() === 'keydown') { keyCode = e.keyCode; printable = keyCode >= 97 && keyCode <= 122 || // a-z keyCode >= 65 && keyCode <= 90 || // A-Z keyCode >= 48 && keyCode <= 57 || // 0-9 keyCode === 32 // space ; if (keyCode === KEY_DELETE || keyCode === KEY_BACKSPACE) { selection = getSelection($input[0]); if (selection.length) { value = value.substring(0, selection.start) + value.substring(selection.start + selection.length); } else if (keyCode === KEY_BACKSPACE && selection.start) { value = value.substring(0, selection.start - 1) + value.substring(selection.start + 1); } else if (keyCode === KEY_DELETE && typeof selection.start !== 'undefined') { value = value.substring(0, selection.start) + value.substring(selection.start + 1); } } else if (printable) { shift = e.shiftKey; character = String.fromCharCode(e.keyCode); if (shift) character = character.toUpperCase(); else character = character.toLowerCase(); value += character; } } placeholder = $input.attr('placeholder'); if (!value && placeholder) { value = placeholder; } width = measureString(value, $input) + 4; if (width !== currentWidth) { currentWidth = width; $input.width(width); $input.triggerHandler('resize'); } }; $input.on('keydown keyup update blur', update); update(); }; var Selectize = function Selectize($input, settings) { var key, i, n, dir, input, self = this; input = $input[0]; input.selectize = self; // detect rtl environment var computedStyle = window.getComputedStyle && window.getComputedStyle(input, null); dir = computedStyle ? computedStyle.getPropertyValue('direction') : input.currentStyle && input.currentStyle.direction; dir = dir || $input.parents('[dir]:first').attr('dir') || ''; // setup default state $.extend(self, { order: 0, settings: settings, $input: $input, tabIndex: $input.attr('tabindex') || '', tagType: input.tagName.toLowerCase() === 'select' ? TAG_SELECT : TAG_INPUT, rtl: /rtl/i.test(dir), eventNS: '.selectize' + ++Selectize.count, highlightedValue: null, isOpen: false, isDisabled: false, isRequired: $input.is('[required]'), isInvalid: false, isLocked: false, isFocused: false, isInputHidden: false, isSetup: false, isShiftDown: false, isCmdDown: false, isCtrlDown: false, ignoreFocus: false, ignoreBlur: false, ignoreHover: false, hasOptions: false, currentResults: null, lastValue: '', caretPos: 0, loading: 0, loadedSearches: {}, $activeOption: null, $activeItems: [], optgroups: {}, options: {}, userOptions: {}, items: [], renderCache: {}, onSearchChange: settings.loadThrottle === null ? self.onSearchChange : debounce(self.onSearchChange, settings.loadThrottle) }); // search system self.sifter = new Sifter(this.options, {diacritics: settings.diacritics}); // build options table if (self.settings.options) { for (i = 0, n = self.settings.options.length; i < n; i++) { self.registerOption(self.settings.options[i]); } delete self.settings.options; } // build optgroup table if (self.settings.optgroups) { for (i = 0, n = self.settings.optgroups.length; i < n; i++) { self.registerOptionGroup(self.settings.optgroups[i]); } delete self.settings.optgroups; } // option-dependent defaults self.settings.mode = self.settings.mode || (self.settings.maxItems === 1 ? 'single' : 'multi'); if (typeof self.settings.hideSelected !== 'boolean') { self.settings.hideSelected = self.settings.mode === 'multi'; } self.initializePlugins(self.settings.plugins); self.setupCallbacks(); self.setupTemplates(); self.setup(); }; // mixins // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - MicroEvent.mixin(Selectize); MicroPlugin.mixin(Selectize); // methods // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - $.extend(Selectize.prototype, { /** * Creates all elements and sets up event bindings. */ setup: function setup() { var self = this; var settings = self.settings; var eventNS = self.eventNS; var $window = $(window); var $document = $(document); var $input = self.$input; var $wrapper; var $control; var $control_input; var $dropdown; var $dropdown_content; var $dropdown_parent; var inputMode; var timeout_blur; var timeout_focus; var classes; var classes_plugins; inputMode = self.settings.mode; classes = $input.attr('class') || ''; $wrapper = $('
').addClass(settings.wrapperClass).addClass(classes).addClass(inputMode); $control = $('
').addClass(settings.inputClass).addClass('items').appendTo($wrapper); $control_input = $('').appendTo($control).attr('tabindex', $input.is(':disabled') ? '-1' : self.tabIndex); $dropdown_parent = $(settings.dropdownParent || $wrapper); $dropdown = $('
').addClass(settings.dropdownClass).addClass(inputMode).hide().appendTo($dropdown_parent); $dropdown_content = $('
').addClass(settings.dropdownContentClass).appendTo($dropdown); if (self.settings.copyClassesToDropdown) { $dropdown.addClass(classes); } $wrapper.css({ width: $input[0].style.width }); if (self.plugins.names.length) { classes_plugins = 'plugin-' + self.plugins.names.join(' plugin-'); $wrapper.addClass(classes_plugins); $dropdown.addClass(classes_plugins); } if ((settings.maxItems === null || settings.maxItems > 1) && self.tagType === TAG_SELECT) { $input.attr('multiple', 'multiple'); } if (self.settings.placeholder) { $control_input.attr('placeholder', settings.placeholder); } // if splitOn was not passed in, construct it from the delimiter to allow pasting universally if (!self.settings.splitOn && self.settings.delimiter) { var delimiterEscaped = self.settings.delimiter.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); self.settings.splitOn = new RegExp('\\s*' + delimiterEscaped + '+\\s*'); } if ($input.attr('autocorrect')) { $control_input.attr('autocorrect', $input.attr('autocorrect')); } if ($input.attr('autocapitalize')) { $control_input.attr('autocapitalize', $input.attr('autocapitalize')); } self.$wrapper = $wrapper; self.$control = $control; self.$control_input = $control_input; self.$dropdown = $dropdown; self.$dropdown_content = $dropdown_content; $dropdown.on('mouseenter', '[data-selectable]', function () { return self.onOptionHover.apply(self, arguments); }); $dropdown.on('mousedown click', '[data-selectable]', function () { return self.onOptionSelect.apply(self, arguments); }); watchChildEvent($control, 'mousedown', '*:not(input)', function () { return self.onItemSelect.apply(self, arguments); }); autoGrow($control_input); $control.on({ mousedown: function mousedown() { return self.onMouseDown.apply(self, arguments); }, click: function click() { return self.onClick.apply(self, arguments); } }); $control_input.on({ mousedown: function mousedown(e) { e.stopPropagation(); }, keydown: function keydown() { return self.onKeyDown.apply(self, arguments); }, keyup: function keyup() { return self.onKeyUp.apply(self, arguments); }, keypress: function keypress() { return self.onKeyPress.apply(self, arguments); }, resize: function resize() { self.positionDropdown.apply(self, []); }, blur: function blur() { return self.onBlur.apply(self, arguments); }, focus: function focus() { self.ignoreBlur = false; return self.onFocus.apply(self, arguments); }, paste: function paste() { return self.onPaste.apply(self, arguments); } }); $document.on('keydown' + eventNS, function (e) { self.isCmdDown = e[IS_MAC ? 'metaKey' : 'ctrlKey']; self.isCtrlDown = e[IS_MAC ? 'altKey' : 'ctrlKey']; self.isShiftDown = e.shiftKey; }); $document.on('keyup' + eventNS, function (e) { if (e.keyCode === KEY_CTRL) self.isCtrlDown = false; if (e.keyCode === KEY_SHIFT) self.isShiftDown = false; if (e.keyCode === KEY_CMD) self.isCmdDown = false; }); $document.on('mousedown' + eventNS, function (e) { if (self.isFocused) { // prevent events on the dropdown scrollbar from causing the control to blur if (e.target === self.$dropdown[0] || e.target.parentNode === self.$dropdown[0]) { return false; } // blur on click outside if (!self.$control.has(e.target).length && e.target !== self.$control[0]) { self.blur(e.target); } } }); $window.on(['scroll' + eventNS, 'resize' + eventNS].join(' '), function () { if (self.isOpen) { self.positionDropdown.apply(self, arguments); } }); $window.on('mousemove' + eventNS, function () { self.ignoreHover = false; }); // store original children and tab index so that they can be // restored when the destroy() method is called. this.revertSettings = { $children: $input.children().detach(), tabindex: $input.attr('tabindex') }; $input.attr('tabindex', -1).hide().after(self.$wrapper); if ($.isArray(settings.items)) { self.setValue(settings.items); delete settings.items; } // feature detect for the validation API if (SUPPORTS_VALIDITY_API) { $input.on('invalid' + eventNS, function (e) { e.preventDefault(); self.isInvalid = true; self.refreshState(); }); } self.updateOriginalInput(); self.refreshItems(); self.refreshState(); self.updatePlaceholder(); self.isSetup = true; if ($input.is(':disabled')) { self.disable(); } self.on('change', this.onChange); $input.data('selectize', self); $input.addClass('selectized'); self.trigger('initialize'); // preload options if (settings.preload === true) { self.onSearchChange(''); } }, /** * Sets up default rendering functions. */ setupTemplates: function setupTemplates() { var self = this; var field_label = self.settings.labelField; var field_optgroup = self.settings.optgroupLabelField; var templates = { 'optgroup': function optgroup(data) { return '
' + data.html + '
'; }, 'optgroup_header': function optgroup_header(data, escape) { return '
' + escape(data[field_optgroup]) + '
'; }, 'option': function option(data, escape) { return '
' + escape(data[field_label]) + '
'; }, 'item': function item(data, escape) { return '
' + escape(data[field_label]) + '
'; }, 'option_create': function option_create(data, escape) { return '
Add ' + escape(data.input) + '
'; } }; self.settings.render = $.extend({}, templates, self.settings.render); }, /** * Maps fired events to callbacks provided * in the settings used when creating the control. */ setupCallbacks: function setupCallbacks() { var key, fn, callbacks = { 'initialize': 'onInitialize', 'change': 'onChange', 'item_add': 'onItemAdd', 'item_remove': 'onItemRemove', 'clear': 'onClear', 'option_add': 'onOptionAdd', 'option_remove': 'onOptionRemove', 'option_clear': 'onOptionClear', 'optgroup_add': 'onOptionGroupAdd', 'optgroup_remove': 'onOptionGroupRemove', 'optgroup_clear': 'onOptionGroupClear', 'dropdown_open': 'onDropdownOpen', 'dropdown_close': 'onDropdownClose', 'type': 'onType', 'load': 'onLoad', 'focus': 'onFocus', 'blur': 'onBlur' }; for (key in callbacks) { if (callbacks.hasOwnProperty(key)) { fn = this.settings[callbacks[key]]; if (fn) this.on(key, fn); } } }, /** * Triggered when the main control element * has a click event. * * @param {object} e * @return {boolean} */ onClick: function onClick(e) { var self = this; // necessary for mobile webkit devices (manual focus triggering // is ignored unless invoked within a click event) if (!self.isFocused) { self.focus(); e.preventDefault(); } }, /** * Triggered when the main control element * has a mouse down event. * * @param {object} e * @return {boolean} */ onMouseDown: function onMouseDown(e) { var self = this; var defaultPrevented = e.isDefaultPrevented(); var $target = $(e.target); if (self.isFocused) { // retain focus by preventing native handling. if the // event target is the input it should not be modified. // otherwise, text selection within the input won't work. if (e.target !== self.$control_input[0]) { if (self.settings.mode === 'single') { // toggle dropdown self.isOpen ? self.close() : self.open(); } else if (!defaultPrevented) { self.setActiveItem(null); } return false; } } else { // give control focus if (!defaultPrevented) { window.setTimeout(function () { self.focus(); }, 0); } } }, /** * Triggered when the value of the control has been changed. * This should propagate the event to the original DOM * input / select element. */ onChange: function onChange() { this.$input.trigger('change'); }, /** * Triggered on paste. * * @param {object} e * @returns {boolean} */ onPaste: function onPaste(e) { var self = this; if (self.isFull() || self.isInputHidden || self.isLocked) { e.preventDefault(); } else { // If a regex or string is included, this will split the pasted // input and create Items for each separate value if (self.settings.splitOn) { setTimeout(function () { var splitInput = $.trim(self.$control_input.val() || '').split(self.settings.splitOn); for (var i = 0, n = splitInput.length; i < n; i++) { self.createItem(splitInput[i]); } }, 0); } } }, /** * Triggered on keypress. * * @param {object} e * @returns {boolean} */ onKeyPress: function onKeyPress(e) { if (this.isLocked) return e && e.preventDefault(); var character = String.fromCharCode(e.keyCode || e.which); if (this.settings.create && this.settings.mode === 'multi' && character === this.settings.delimiter) { this.createItem(); e.preventDefault(); return false; } }, /** * Triggered on keydown. * * @param {object} e * @returns {boolean} */ onKeyDown: function onKeyDown(e) { var isInput = e.target === this.$control_input[0]; var self = this; if (self.isLocked) { if (e.keyCode !== KEY_TAB) { e.preventDefault(); } return; } switch (e.keyCode) { case KEY_A: if (self.isCmdDown) { self.selectAll(); return; } break; case KEY_ESC: if (self.isOpen) { e.preventDefault(); e.stopPropagation(); self.close(); } return; case KEY_N: if (!e.ctrlKey || e.altKey) break; case KEY_DOWN: if (!self.isOpen && self.hasOptions) { self.open(); } else if (self.$activeOption) { self.ignoreHover = true; var $next = self.getAdjacentOption(self.$activeOption, 1); if ($next.length) self.setActiveOption($next, true, true); } e.preventDefault(); return; case KEY_P: if (!e.ctrlKey || e.altKey) break; case KEY_UP: if (self.$activeOption) { self.ignoreHover = true; var $prev = self.getAdjacentOption(self.$activeOption, -1); if ($prev.length) self.setActiveOption($prev, true, true); } e.preventDefault(); return; case KEY_RETURN: if (self.isOpen && self.$activeOption) { self.onOptionSelect({currentTarget: self.$activeOption}); e.preventDefault(); } return; case KEY_LEFT: self.advanceSelection(-1, e); return; case KEY_RIGHT: self.advanceSelection(1, e); return; case KEY_TAB: if (self.settings.selectOnTab && self.isOpen && self.$activeOption) { self.onOptionSelect({currentTarget: self.$activeOption}); // Default behaviour is to jump to the next field, we only want this // if the current field doesn't accept any more entries if (!self.isFull()) { e.preventDefault(); } } if (self.settings.create && self.createItem()) { e.preventDefault(); } return; case KEY_BACKSPACE: case KEY_DELETE: self.deleteSelection(e); return; } if ((self.isFull() || self.isInputHidden) && !(IS_MAC ? e.metaKey : e.ctrlKey)) { e.preventDefault(); return; } }, /** * Triggered on keyup. * * @param {object} e * @returns {boolean} */ onKeyUp: function onKeyUp(e) { var self = this; if (self.isLocked) return e && e.preventDefault(); var value = self.$control_input.val() || ''; if (self.lastValue !== value) { self.lastValue = value; self.onSearchChange(value); self.refreshOptions(); self.trigger('type', value); } }, /** * Invokes the user-provide option provider / loader. * * Note: this function is debounced in the Selectize * constructor (by `settings.loadDelay` milliseconds) * * @param {string} value */ onSearchChange: function onSearchChange(value) { var self = this; var fn = self.settings.load; if (!fn) return; if (self.loadedSearches.hasOwnProperty(value)) return; self.loadedSearches[value] = true; self.load(function (callback) { fn.apply(self, [value, callback]); }); }, /** * Triggered on focus. * * @param {object} e (optional) * @returns {boolean} */ onFocus: function onFocus(e) { var self = this; var wasFocused = self.isFocused; if (self.isDisabled) { self.blur(); e && e.preventDefault(); return false; } if (self.ignoreFocus) return; self.isFocused = true; if (self.settings.preload === 'focus') self.onSearchChange(''); if (!wasFocused) self.trigger('focus'); if (!self.$activeItems.length) { self.showInput(); self.setActiveItem(null); self.refreshOptions(!!self.settings.openOnFocus); } self.refreshState(); }, /** * Triggered on blur. * * @param {object} e * @param {Element} dest */ onBlur: function onBlur(e, dest) { var self = this; if (!self.isFocused) return; self.isFocused = false; if (self.ignoreFocus) { return; } else if (!self.ignoreBlur && document.activeElement === self.$dropdown_content[0]) { // necessary to prevent IE closing the dropdown when the scrollbar is clicked self.ignoreBlur = true; self.onFocus(e); return; } var deactivate = function deactivate() { self.close(); self.setTextboxValue(''); self.setActiveItem(null); self.setActiveOption(null); self.setCaret(self.items.length); self.refreshState(); // IE11 bug: element still marked as active (dest || document.body).focus(); self.ignoreFocus = false; self.trigger('blur'); }; self.ignoreFocus = true; if (self.settings.create && self.settings.createOnBlur) { self.createItem(null, false, deactivate); } else { deactivate(); } }, /** * Triggered when the user rolls over * an option in the autocomplete dropdown menu. * * @param {object} e * @returns {boolean} */ onOptionHover: function onOptionHover(e) { if (this.ignoreHover) return; this.setActiveOption(e.currentTarget, false); }, /** * Triggered when the user clicks on an option * in the autocomplete dropdown menu. * * @param {object} e * @returns {boolean} */ onOptionSelect: function onOptionSelect(e) { var value, $target, $option, self = this; if (e.preventDefault) { e.preventDefault(); e.stopPropagation(); } $target = $(e.currentTarget); if ($target.hasClass('create')) { self.createItem(null, function () { if (self.settings.closeAfterSelect) { self.close(); } }); } else { value = $target.attr('data-value'); if (typeof value !== 'undefined') { self.lastQuery = null; self.setTextboxValue(''); self.addItem(value); if (self.settings.closeAfterSelect) { self.close(); } else if (!self.settings.hideSelected && e.type && /mouse/.test(e.type)) { self.setActiveOption(self.getOption(value)); } } } }, /** * Triggered when the user clicks on an item * that has been selected. * * @param {object} e * @returns {boolean} */ onItemSelect: function onItemSelect(e) { var self = this; if (self.isLocked) return; if (self.settings.mode === 'multi') { e.preventDefault(); self.setActiveItem(e.currentTarget, e); } }, /** * Invokes the provided method that provides * results to a callback---which are then added * as options to the control. * * @param {function} fn */ load: function load(fn) { var self = this; var $wrapper = self.$wrapper.addClass(self.settings.loadingClass); self.loading++; fn.apply(self, [function (results) { self.loading = Math.max(self.loading - 1, 0); if (results && results.length) { self.addOption(results); self.refreshOptions(self.isFocused && !self.isInputHidden); } if (!self.loading) { $wrapper.removeClass(self.settings.loadingClass); } self.trigger('load', results); }]); }, /** * Sets the input field of the control to the specified value. * * @param {string} value */ setTextboxValue: function setTextboxValue(value) { var $input = this.$control_input; var changed = $input.val() !== value; if (changed) { $input.val(value).triggerHandler('update'); this.lastValue = value; } }, /** * Returns the value of the control. If multiple items * can be selected (e.g. or * element to reflect the current state. */ updateOriginalInput: function updateOriginalInput(opts) { var i, n, options, label, self = this; opts = opts || {}; if (self.tagType === TAG_SELECT) { options = []; for (i = 0, n = self.items.length; i < n; i++) { label = self.options[self.items[i]][self.settings.labelField] || ''; options.push(''); } if (!options.length && !this.$input.attr('multiple')) { options.push(''); } self.$input.html(options.join('')); } else { self.$input.val(self.getValue()); self.$input.attr('value', self.$input.val()); } if (self.isSetup) { if (!opts.silent) { self.trigger('change', self.$input.val()); } } }, /** * Shows/hide the input placeholder depending * on if there items in the list already. */ updatePlaceholder: function updatePlaceholder() { if (!this.settings.placeholder) return; var $input = this.$control_input; if (this.items.length) { $input.removeAttr('placeholder'); } else { $input.attr('placeholder', this.settings.placeholder); } $input.triggerHandler('update', {force: true}); }, /** * Shows the autocomplete dropdown containing * the available options. */ open: function open() { var self = this; if (self.isLocked || self.isOpen || self.settings.mode === 'multi' && self.isFull()) return; self.focus(); self.isOpen = true; self.refreshState(); self.$dropdown.css({visibility: 'hidden', display: 'block'}); self.positionDropdown(); self.$dropdown.css({visibility: 'visible'}); self.trigger('dropdown_open', self.$dropdown); }, /** * Closes the autocomplete dropdown menu. */ close: function close() { var self = this; var trigger = self.isOpen; if (self.settings.mode === 'single' && self.items.length) { self.hideInput(); } self.isOpen = false; self.$dropdown.hide(); self.setActiveOption(null); self.refreshState(); if (trigger) self.trigger('dropdown_close', self.$dropdown); }, /** * Calculates and applies the appropriate * position of the dropdown. */ positionDropdown: function positionDropdown() { var $control = this.$control; var offset = this.settings.dropdownParent === 'body' ? $control.offset() : $control.position(); offset.top += $control.outerHeight(true); this.$dropdown.css({ width: $control.outerWidth(), top: offset.top, left: offset.left }); }, /** * Resets / clears all selected items * from the control. * * @param {boolean} silent */ clear: function clear(silent) { var self = this; if (!self.items.length) return; self.$control.children(':not(input)').remove(); self.items = []; self.lastQuery = null; self.setCaret(0); self.setActiveItem(null); self.updatePlaceholder(); self.updateOriginalInput({silent: silent}); self.refreshState(); self.showInput(); self.trigger('clear'); }, /** * A helper method for inserting an element * at the current caret position. * * @param {object} $el */ insertAtCaret: function insertAtCaret($el) { var caret = Math.min(this.caretPos, this.items.length); if (caret === 0) { this.$control.prepend($el); } else { $(this.$control[0].childNodes[caret]).before($el); } this.setCaret(caret + 1); }, /** * Removes the current selected item(s). * * @param {object} e (optional) * @returns {boolean} */ deleteSelection: function deleteSelection(e) { var i, n, direction, selection, values, caret, option_select, $option_select, $tail; var self = this; direction = e && e.keyCode === KEY_BACKSPACE ? -1 : 1; selection = getSelection(self.$control_input[0]); if (self.$activeOption && !self.settings.hideSelected) { option_select = self.getAdjacentOption(self.$activeOption, -1).attr('data-value'); } // determine items that will be removed values = []; if (self.$activeItems.length) { $tail = self.$control.children('.active:' + (direction > 0 ? 'last' : 'first')); caret = self.$control.children(':not(input)').index($tail); if (direction > 0) { caret++; } for (i = 0, n = self.$activeItems.length; i < n; i++) { values.push($(self.$activeItems[i]).attr('data-value')); } if (e) { e.preventDefault(); e.stopPropagation(); } } else if ((self.isFocused || self.settings.mode === 'single') && self.items.length) { if (direction < 0 && selection.start === 0 && selection.length === 0) { values.push(self.items[self.caretPos - 1]); } else if (direction > 0 && selection.start === self.$control_input.val().length) { values.push(self.items[self.caretPos]); } } // allow the callback to abort if (!values.length || typeof self.settings.onDelete === 'function' && self.settings.onDelete.apply(self, [values]) === false) { return false; } // perform removal if (typeof caret !== 'undefined') { self.setCaret(caret); } while (values.length) { self.removeItem(values.pop()); } self.showInput(); self.positionDropdown(); self.refreshOptions(true); // select previous option if (option_select) { $option_select = self.getOption(option_select); if ($option_select.length) { self.setActiveOption($option_select); } } return true; }, /** * Selects the previous / next item (depending * on the `direction` argument). * * > 0 - right * < 0 - left * * @param {int} direction * @param {object} e (optional) */ advanceSelection: function advanceSelection(direction, e) { var tail, selection, idx, valueLength, cursorAtEdge, $tail; var self = this; if (direction === 0) return; if (self.rtl) direction *= -1; tail = direction > 0 ? 'last' : 'first'; selection = getSelection(self.$control_input[0]); if (self.isFocused && !self.isInputHidden) { valueLength = self.$control_input.val().length; cursorAtEdge = direction < 0 ? selection.start === 0 && selection.length === 0 : selection.start === valueLength; if (cursorAtEdge && !valueLength) { self.advanceCaret(direction, e); } } else { $tail = self.$control.children('.active:' + tail); if ($tail.length) { idx = self.$control.children(':not(input)').index($tail); self.setActiveItem(null); self.setCaret(direction > 0 ? idx + 1 : idx); } } }, /** * Moves the caret left / right. * * @param {int} direction * @param {object} e (optional) */ advanceCaret: function advanceCaret(direction, e) { var self = this, fn, $adj; if (direction === 0) return; fn = direction > 0 ? 'next' : 'prev'; if (self.isShiftDown) { $adj = self.$control_input[fn](); if ($adj.length) { self.hideInput(); self.setActiveItem($adj); e && e.preventDefault(); } } else { self.setCaret(self.caretPos + direction); } }, /** * Moves the caret to the specified index. * * @param {int} i */ setCaret: function setCaret(i) { var self = this; if (self.settings.mode === 'single') { i = self.items.length; } else { i = Math.max(0, Math.min(self.items.length, i)); } if (!self.isPending) { // the input must be moved by leaving it in place and moving the // siblings, due to the fact that focus cannot be restored once lost // on mobile webkit devices var j, n, fn, $children, $child; $children = self.$control.children(':not(input)'); for (j = 0, n = $children.length; j < n; j++) { $child = $($children[j]).detach(); if (j < i) { self.$control_input.before($child); } else { self.$control.append($child); } } } self.caretPos = i; }, /** * Disables user input on the control. Used while * items are being asynchronously created. */ lock: function lock() { this.close(); this.isLocked = true; this.refreshState(); }, /** * Re-enables user input on the control. */ unlock: function unlock() { this.isLocked = false; this.refreshState(); }, /** * Disables user input on the control completely. * While disabled, it cannot receive focus. */ disable: function disable() { var self = this; self.$input.prop('disabled', true); self.$control_input.prop('disabled', true).prop('tabindex', -1); self.isDisabled = true; self.lock(); }, /** * Enables the control so that it can respond * to focus and user input. */ enable: function enable() { var self = this; self.$input.prop('disabled', false); self.$control_input.prop('disabled', false).prop('tabindex', self.tabIndex); self.isDisabled = false; self.unlock(); }, /** * Completely destroys the control and * unbinds all event listeners so that it can * be garbage collected. */ destroy: function destroy() { var self = this; var eventNS = self.eventNS; var revertSettings = self.revertSettings; self.trigger('destroy'); self.off(); self.$wrapper.remove(); self.$dropdown.remove(); self.$input.html('').append(revertSettings.$children).removeAttr('tabindex').removeClass('selectized').attr({tabindex: revertSettings.tabindex}).show(); self.$control_input.removeData('grow'); self.$input.removeData('selectize'); $(window).off(eventNS); $(document).off(eventNS); $(document.body).off(eventNS); delete self.$input[0].selectize; }, /** * A helper method for rendering "item" and * "option" templates, given the data. * * @param {string} templateName * @param {object} data * @returns {string} */ render: function render(templateName, data) { var value, id, label; var html = ''; var cache = false; var self = this; var regex_tag = /^[\t \r\n]*<([a-z][a-z0-9\-_]*(?:\:[a-z][a-z0-9\-_]*)?)/i; if (templateName === 'option' || templateName === 'item') { value = hash_key(data[self.settings.valueField]); cache = !!value; } // pull markup from cache if it exists if (cache) { if (!isset(self.renderCache[templateName])) { self.renderCache[templateName] = {}; } if (self.renderCache[templateName].hasOwnProperty(value)) { return self.renderCache[templateName][value]; } } // render markup html = self.settings.render[templateName].apply(this, [data, escape_html]); // add mandatory attributes if (templateName === 'option' || templateName === 'option_create') { html = html.replace(regex_tag, '<$1 data-selectable'); } if (templateName === 'optgroup') { id = data[self.settings.optgroupValueField] || ''; html = html.replace(regex_tag, '<$1 data-group="' + escape_replace(escape_html(id)) + '"'); } if (templateName === 'option' || templateName === 'item') { html = html.replace(regex_tag, '<$1 data-value="' + escape_replace(escape_html(value || '')) + '"'); } // update cache if (cache) { self.renderCache[templateName][value] = html; } return html; }, /** * Clears the render cache for a template. If * no template is given, clears all render * caches. * * @param {string} templateName */ clearCache: function clearCache(templateName) { var self = this; if (typeof templateName === 'undefined') { self.renderCache = {}; } else { delete self.renderCache[templateName]; } }, /** * Determines whether or not to display the * create item prompt, given a user input. * * @param {string} input * @return {boolean} */ canCreate: function canCreate(input) { var self = this; if (!self.settings.create) return false; var filter = self.settings.createFilter; return input.length && (typeof filter !== 'function' || filter.apply(self, [input])) && (typeof filter !== 'string' || new RegExp(filter).test(input)) && (!(filter instanceof RegExp) || filter.test(input)); } }); Selectize.count = 0; Selectize.defaults = { options: [], optgroups: [], plugins: [], delimiter: ',', splitOn: null, // regexp or string for splitting up values from a paste command persist: true, diacritics: true, create: false, createOnBlur: false, createFilter: null, highlight: true, openOnFocus: true, maxOptions: 1000, maxItems: null, hideSelected: null, addPrecedence: false, selectOnTab: false, preload: false, allowEmptyOption: false, closeAfterSelect: false, scrollDuration: 60, loadThrottle: 300, loadingClass: 'loading', dataAttr: 'data-data', optgroupField: 'optgroup', valueField: 'value', labelField: 'text', optgroupLabelField: 'label', optgroupValueField: 'value', lockOptgroupOrder: false, sortField: '$order', searchField: ['text'], searchConjunction: 'and', mode: null, wrapperClass: 'selectize-control', inputClass: 'selectize-input', dropdownClass: 'selectize-dropdown', dropdownContentClass: 'selectize-dropdown-content', dropdownParent: null, copyClassesToDropdown: true, /* load : null, // function(query, callback) { ... } score : null, // function(search) { ... } onInitialize : null, // function() { ... } onChange : null, // function(value) { ... } onItemAdd : null, // function(value, $item) { ... } onItemRemove : null, // function(value) { ... } onClear : null, // function() { ... } onOptionAdd : null, // function(value, data) { ... } onOptionRemove : null, // function(value) { ... } onOptionClear : null, // function() { ... } onOptionGroupAdd : null, // function(id, data) { ... } onOptionGroupRemove : null, // function(id) { ... } onOptionGroupClear : null, // function() { ... } onDropdownOpen : null, // function($dropdown) { ... } onDropdownClose : null, // function($dropdown) { ... } onType : null, // function(str) { ... } onDelete : null, // function(values) { ... } */ render: { /* item: null, optgroup: null, optgroup_header: null, option: null, option_create: null */ } }; $.fn.selectize = function (settings_user) { var defaults = $.fn.selectize.defaults; var settings = $.extend({}, defaults, settings_user); var attr_data = settings.dataAttr; var field_label = settings.labelField; var field_value = settings.valueField; var field_optgroup = settings.optgroupField; var field_optgroup_label = settings.optgroupLabelField; var field_optgroup_value = settings.optgroupValueField; /** * Initializes selectize from a element. * * @param {object} $input * @param {object} settings_element */ var init_textbox = function init_textbox($input, settings_element) { var i, n, values, option; var data_raw = $input.attr(attr_data); if (!data_raw) { var value = $.trim($input.val() || ''); if (!settings.allowEmptyOption && !value.length) return; values = value.split(settings.delimiter); for (i = 0, n = values.length; i < n; i++) { option = {}; option[field_label] = values[i]; option[field_value] = values[i]; settings_element.options.push(option); } settings_element.items = values; } else { settings_element.options = JSON.parse(data_raw); for (i = 0, n = settings_element.options.length; i < n; i++) { settings_element.items.push(settings_element.options[i][field_value]); } } }; /** * Initializes selectize from a " + ""; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if (div.querySelectorAll("[msallowcapture^='']").length) { rbuggyQSA.push("[*^$]=" + whitespace + "*(?:''|\"\")"); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if (!div.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 (!div.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 (!div.querySelectorAll(":checked").length) { rbuggyQSA.push(":checked"); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibing-combinator selector` fails if (!div.querySelectorAll("a#" + expando + "+*").length) { rbuggyQSA.push(".#.+[+~]"); } }); assert(function (div) { // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = document.createElement("input"); input.setAttribute("type", "hidden"); div.appendChild(input).setAttribute("name", "D"); // Support: IE8 // Enforce case-sensitivity of name attribute if (div.querySelectorAll("[name=d]").length) { rbuggyQSA.push("name" + whitespace + "*[*^$|!~]?="); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if (!div.querySelectorAll(":enabled").length) { rbuggyQSA.push(":enabled", ":disabled"); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ((support.matchesSelector = rnative.test((matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector)))) { assert(function (div) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call(div, "div"); // This should fail with an exception // Gecko does not error, returns false instead matches.call(div, "[s!='']:x"); rbuggyMatches.push("!=", pseudos); }); } rbuggyQSA = rbuggyQSA.length && new RegExp(rbuggyQSA.join("|")); rbuggyMatches = rbuggyMatches.length && new RegExp(rbuggyMatches.join("|")); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test(docElem.compareDocumentPosition); // Element contains another // Purposefully 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.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": function (elem) { return elem.disabled === false; }, "disabled": function (elem) { return elem.disabled === true; }, "checked": function (elem) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function (elem) { // Accessing this property makes selected-by-default // options in Safari work properly if (elem.parentNode) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function (elem) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for (elem = elem.firstChild; elem; elem = elem.nextSibling) { if (elem.nodeType < 6) { return false; } } return true; }, "parent": function (elem) { return !Expr.pseudos["empty"](elem); }, // Element/input types "header": function (elem) { return rheader.test(elem.nodeName); }, "input": function (elem) { return rinputs.test(elem.nodeName); }, "button": function (elem) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function (elem) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ((attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text"); }, // Position-in-collection "first": createPositionalPseudo(function () { return [0]; }), "last": createPositionalPseudo(function (matchIndexes, length) { return [length - 1]; }), "eq": createPositionalPseudo(function (matchIndexes, length, argument) { return [argument < 0 ? argument + length : argument]; }), "even": createPositionalPseudo(function (matchIndexes, length) { var i = 0; for (; i < length; i += 2) { matchIndexes.push(i); } return matchIndexes; }), "odd": createPositionalPseudo(function (matchIndexes, length) { var i = 1; for (; i < length; i += 2) { matchIndexes.push(i); } return matchIndexes; }), "lt": createPositionalPseudo(function (matchIndexes, length, argument) { var i = argument < 0 ? argument + length : argument; for (; --i >= 0;) { matchIndexes.push(i); } return matchIndexes; }), "gt": createPositionalPseudo(function (matchIndexes, length, argument) { var i = argument < 0 ? argument + length : argument; for (; ++i < length;) { matchIndexes.push(i); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for (i in {radio: true, checkbox: true, file: true, password: true, image: true}) { Expr.pseudos[i] = createInputPseudo(i); } for (i in {submit: true, reset: true}) { Expr.pseudos[i] = createButtonPseudo(i); } // Easy API for creating new setFilters function setFilters() { } setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function (selector, parseOnly) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[selector + " "]; if (cached) { return parseOnly ? 0 : cached.slice(0); } soFar = selector; groups = []; preFilters = Expr.preFilter; while (soFar) { // Comma and first run if (!matched || (match = rcomma.exec(soFar))) { if (match) { // Don't consume trailing commas as valid soFar = soFar.slice(match[0].length) || soFar; } groups.push((tokens = [])); } matched = false; // Combinators if ((match = rcombinators.exec(soFar))) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace(rtrim, " ") }); soFar = soFar.slice(matched.length); } // Filters for (type in Expr.filter) { if ((match = matchExpr[type].exec(soFar)) && (!preFilters[type] || (match = preFilters[type](match)))) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice(matched.length); } } if (!matched) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) : // Cache the tokens tokenCache(selector, groups).slice(0); }; function toSelector(tokens) { var i = 0, len = tokens.length, selector = ""; for (; i < len; i++) { selector += tokens[i].value; } return selector; } function addCombinator(matcher, combinator, base) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function (elem, context, xml) { while ((elem = elem[dir])) { if (elem.nodeType === 1 || checkNonElements) { return matcher(elem, context, xml); } } } : // Check against all ancestor/preceding elements function (elem, context, xml) { var oldCache, 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 ((oldCache = uniqueCache[dir]) && oldCache[0] === dirruns && oldCache[1] === doneName) { // Assign to newCache so results back-propagate to previous elements return (newCache[2] = oldCache[2]); } else { // Reuse newcache so results back-propagate to previous elements uniqueCache[dir] = newCache; // A match means we're done; a fail means we have to keep checking if ((newCache[2] = matcher(elem, context, xml))) { return true; } } } } } }; } function elementMatcher(matchers) { return matchers.length > 1 ? function (elem, context, xml) { var i = matchers.length; while (i--) { if (!matchers[i](elem, context, xml)) { return false; } } return true; } : matchers[0]; } function multipleContexts(selector, contexts, results) { var i = 0, len = contexts.length; for (; i < len; i++) { Sizzle(selector, contexts[i], results); } return results; } function condense(unmatched, map, filter, context, xml) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for (; i < len; i++) { if ((elem = unmatched[i])) { if (!filter || filter(elem, context, xml)) { newUnmatched.push(elem); if (mapped) { map.push(i); } } } } return newUnmatched; } function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector) { if (postFilter && !postFilter[expando]) { postFilter = setMatcher(postFilter); } if (postFinder && !postFinder[expando]) { postFinder = setMatcher(postFinder, postSelector); } return markFunction(function (seed, results, context, xml) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts(selector || "*", context.nodeType ? [context] : context, []), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && (seed || !selector) ? condense(elems, preMap, preFilter, context, xml) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || (seed ? preFilter : preexisting || postFilter) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if (matcher) { matcher(matcherIn, matcherOut, context, xml); } // Apply postFilter if (postFilter) { temp = condense(matcherOut, postMap); postFilter(temp, [], context, xml); // Un-match failing elements by moving them back to matcherIn i = temp.length; while (i--) { if ((elem = temp[i])) { matcherOut[postMap[i]] = !(matcherIn[postMap[i]] = elem); } } } if (seed) { if (postFinder || preFilter) { if (postFinder) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while (i--) { if ((elem = matcherOut[i])) { // Restore matcherIn since elem is not yet a final match temp.push((matcherIn[i] = elem)); } } postFinder(null, (matcherOut = []), temp, xml); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while (i--) { if ((elem = matcherOut[i]) && (temp = postFinder ? indexOf(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: ) 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 (div1) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition(document.createElement("div")) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if (!assert(function (div) { div.innerHTML = ""; return div.firstChild.getAttribute("href") === "#"; })) { addHandle("type|href|height|width", function (elem, name, isXML) { if (!isXML) { return elem.getAttribute(name, name.toLowerCase() === "type" ? 1 : 2); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if (!support.attributes || !assert(function (div) { div.innerHTML = ""; div.firstChild.setAttribute("value", ""); return div.firstChild.getAttribute("value") === ""; })) { addHandle("value", function (elem, name, isXML) { if (!isXML && elem.nodeName.toLowerCase() === "input") { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if (!assert(function (div) { return div.getAttribute("disabled") == null; })) { addHandle(booleans, function (elem, name, isXML) { var val; if (!isXML) { return elem[name] === true ? name.toLowerCase() : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; } }); } return Sizzle; })(window); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; 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 = (/^<([\w-]+)\s*\/?>(?:<\/\1>|)$/); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow(elements, qualifier, not) { if (jQuery.isFunction(qualifier)) { return jQuery.grep(elements, function (elem, i) { /* jshint -W018 */ return !!qualifier.call(elem, i, elem) !== not; }); } if (qualifier.nodeType) { return jQuery.grep(elements, function (elem) { return (elem === qualifier) !== not; }); } if (typeof qualifier === "string") { if (risSimple.test(qualifier)) { return jQuery.filter(qualifier, elements, not); } qualifier = jQuery.filter(qualifier, elements); } return jQuery.grep(elements, function (elem) { return (indexOf.call(qualifier, elem) > -1) !== not; }); } jQuery.filter = function (expr, elems, not) { var elem = elems[0]; if (not) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector(elem, expr) ? [elem] : [] : jQuery.find.matches(expr, jQuery.grep(elems, function (elem) { return elem.nodeType === 1; })); }; jQuery.fn.extend({ find: function (selector) { var i, len = this.length, ret = [], self = this; if (typeof selector !== "string") { return this.pushStack(jQuery(selector).filter(function () { for (i = 0; i < len; i++) { if (jQuery.contains(self[i], this)) { return true; } } })); } for (i = 0; i < len; i++) { jQuery.find(selector, self[i], ret); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack(len > 1 ? jQuery.unique(ret) : ret); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, filter: function (selector) { return this.pushStack(winnow(this, selector || [], false)); }, not: function (selector) { return this.pushStack(winnow(this, selector || [], true)); }, is: function (selector) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test(selector) ? jQuery(selector) : selector || [], false ).length; } }); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // A simple way to check for HTML strings // Prioritize #id over to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, init = jQuery.fn.init = function (selector, context, 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]); // Support: Blackberry 4.6 // gEBID returns nodes no longer in the document (#6963) if (elem && elem.parentNode) { // Inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if (!context || context.jquery) { return (context || 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.context = 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); } if (selector.selector !== undefined) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray(selector, this); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery(document); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // Methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ has: function (target) { var targets = jQuery(target, this), l = targets.length; return this.filter(function () { var i = 0; for (; i < l; i++) { if (jQuery.contains(this, targets[i])) { return true; } } }); }, closest: function (selectors, context) { var cur, i = 0, l = this.length, matched = [], pos = rneedsContext.test(selectors) || typeof selectors !== "string" ? jQuery(selectors, context || this.context) : 0; for (; i < l; i++) { for (cur = this[i]; cur && cur !== context; cur = cur.parentNode) { // Always skip document fragments if (cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors))) { matched.push(cur); break; } } } return this.pushStack(matched.length > 1 ? jQuery.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) { 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; }; jQuery.extend({ Deferred: function (func) { var tuples = [ // action, add listener, listener list, final state ["resolve", "done", jQuery.Callbacks("once memory"), "resolved"], ["reject", "fail", jQuery.Callbacks("once memory"), "rejected"], ["notify", "progress", jQuery.Callbacks("memory")] ], state = "pending", promise = { state: function () { return state; }, always: function () { deferred.done(arguments).fail(arguments); return this; }, then: function ( /* fnDone, fnFail, fnProgress */) { var fns = arguments; return jQuery.Deferred(function (newDefer) { jQuery.each(tuples, function (i, tuple) { var fn = jQuery.isFunction(fns[i]) && fns[i]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[tuple[1]](function () { var returned = fn && fn.apply(this, arguments); if (returned && jQuery.isFunction(returned.promise)) { returned.promise() .progress(newDefer.notify) .done(newDefer.resolve) .fail(newDefer.reject); } else { newDefer[tuple[0] + "With"]( this === promise ? newDefer.promise() : this, fn ? [returned] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function (obj) { return obj != null ? jQuery.extend(obj, promise) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each(tuples, function (i, tuple) { var list = tuple[2], stateString = tuple[3]; // promise[ done | fail | progress ] = list.add promise[tuple[1]] = list.add; // Handle state if (stateString) { list.add(function () { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[i ^ 1][2].disable, tuples[2][2].lock); } // deferred[ resolve | reject | notify ] deferred[tuple[0]] = function () { deferred[tuple[0] + "With"](this === deferred ? promise : this, arguments); return this; }; deferred[tuple[0] + "With"] = list.fireWith; }); // Make the deferred a promise promise.promise(deferred); // Call given func if any if (func) { func.call(deferred, deferred); } // All done! return deferred; }, // Deferred helper when: function (subordinate /* , ..., subordinateN */) { var i = 0, resolveValues = slice.call(arguments), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || (subordinate && jQuery.isFunction(subordinate.promise)) ? length : 0, // the master Deferred. // If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function (i, contexts, values) { return function (value) { contexts[i] = this; values[i] = arguments.length > 1 ? slice.call(arguments) : value; if (values === progressValues) { deferred.notifyWith(contexts, values); } else if (!(--remaining)) { deferred.resolveWith(contexts, values); } }; }, progressValues, progressContexts, resolveContexts; // Add listeners to Deferred subordinates; treat others as resolved if (length > 1) { progressValues = new Array(length); progressContexts = new Array(length); resolveContexts = new Array(length); for (; i < length; i++) { if (resolveValues[i] && jQuery.isFunction(resolveValues[i].promise)) { resolveValues[i].promise() .progress(updateFunc(i, progressContexts, progressValues)) .done(updateFunc(i, resolveContexts, resolveValues)) .fail(deferred.reject); } else { --remaining; } } } // If we're not waiting on anything, resolve the master if (!remaining) { deferred.resolveWith(resolveContexts, resolveValues); } return deferred.promise(); } }); // The deferred used on DOM ready var readyList; jQuery.fn.ready = function (fn) { // Add the callback jQuery.ready.promise().done(fn); return this; }; jQuery.extend({ // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function (hold) { if (hold) { jQuery.readyWait++; } else { jQuery.ready(true); } }, // Handle when the DOM is ready ready: function (wait) { // Abort if there are pending holds or we're already ready if (wait === true ? --jQuery.readyWait : jQuery.isReady) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if (wait !== true && --jQuery.readyWait > 0) { return; } // If there are functions bound, to execute readyList.resolveWith(document, [jQuery]); // Trigger any bound ready events if (jQuery.fn.triggerHandler) { jQuery(document).triggerHandler("ready"); jQuery(document).off("ready"); } } }); /** * The ready event handler and self cleanup method */ function completed() { document.removeEventListener("DOMContentLoaded", completed); window.removeEventListener("load", completed); jQuery.ready(); } jQuery.ready.promise = function (obj) { if (!readyList) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called // after the browser event has already occurred. // Support: IE9-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); } } return readyList.promise(obj); }; // Kick off the DOM ready check even if the user does not jQuery.ready.promise(); // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = 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 = { register: function (owner, initial) { var value = initial || {}; // 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, non-writable property // configurability must be true to allow the property to be // deleted with the delete operator } else { Object.defineProperty(owner, this.expando, { value: value, writable: true, configurable: true }); } return owner[this.expando]; }, cache: function (owner) { // 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)) { return {}; } // 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 if (typeof data === "string") { cache[data] = value; // Handle: [ owner, { properties } ] args } else { // Copy the properties one-by-one to the cache object for (prop in data) { cache[prop] = data[prop]; } } return cache; }, get: function (owner, key) { return key === undefined ? this.cache(owner) : owner[this.expando] && owner[this.expando][key]; }, access: function (owner, key, value) { var stored; // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if (key === undefined || ((key && typeof key === "string") && value === undefined)) { stored = this.get(owner, key); return stored !== undefined ? stored : this.get(owner, jQuery.camelCase(key)); } // When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set(owner, key, value); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function (owner, key) { var i, name, camel, cache = owner[this.expando]; if (cache === undefined) { return; } if (key === undefined) { this.register(owner); } else { // Support array or space separated string of keys if (jQuery.isArray(key)) { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = key.concat(key.map(jQuery.camelCase)); } else { camel = jQuery.camelCase(key); // Try the string as a key before any manipulation if (key in cache) { name = [key, camel]; } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = camel; name = name in cache ? [name] : (name.match(rnotwhite) || []); } } i = name.length; while (i--) { delete cache[name[i]]; } } // 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://code.google.com/p/chromium/issues/detail?id=378607 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) ? jQuery.parseJSON(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: IE11+ // The attrs elements can be null (#14894) if (attrs[i]) { name = attrs[i].name; if (name.indexOf("data-") === 0) { name = jQuery.camelCase(name.slice(5)); dataAttr(elem, name, data[name]); } } } 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, camelKey; // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if (elem && value === undefined) { // Attempt to get data from the cache // with the key as-is data = dataUser.get(elem, key) || // Try to find dashed key if it exists (gh-2779) // This is for 2.2.x only dataUser.get(elem, key.replace(rmultiDash, "-$&").toLowerCase()); if (data !== undefined) { return data; } camelKey = jQuery.camelCase(key); // Attempt to get data from the cache // with the key camelized data = dataUser.get(elem, camelKey); if (data !== undefined) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr(elem, camelKey, undefined); if (data !== undefined) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... camelKey = jQuery.camelCase(key); this.each(function () { // First, attempt to store a copy or reference of any // data that might've been store with a camelCased key. var data = dataUser.get(this, camelKey); // For HTML5 data-* attribute interop, we have to // store property names with dashes in a camelCase form. // This might not apply to all properties...* dataUser.set(this, camelKey, value); // *... In the case of properties that might _actually_ // have dashes, we need to also store a copy of that // unchanged property. if (key.indexOf("-") > -1 && data !== undefined) { 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 isHidden = function (elem, el) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css(elem, "display") === "none" || !jQuery.contains(elem.ownerDocument, elem); }; 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 rcheckableType = (/^(?:checkbox|radio)$/i); var rtagName = (/<([\w:-]+)/); var rscriptType = (/^$|\/(?:java|ecma)script/i); // We have to close these tags to support XHTML (#13200) var wrapMap = { // Support: IE9 option: [1, ""], // XHTML parsers do not magically insert elements in the // same way that tag soup parsers do. So we cannot shorten // this by omitting or other required elements. thead: [1, "", "
"], col: [2, "", "
"], tr: [2, "", "
"], td: [3, "", "
"], _default: [0, "", ""] }; // Support: IE9 wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; function getAll(context, tag) { // Support: IE9-11+ // 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.1, PhantomJS<2 // 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.1, PhantomJS<2 // 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, Safari<=5.1 // 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: Safari<=5.1, Android<4.2 // Older WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode(true).cloneNode(true).lastChild.checked; // Support: IE<=11+ // Make sure textarea (and checkbox) defaultValue is properly cloned div.innerHTML = ""; support.noCloneChecked = !!div.cloneNode(true).lastChild.defaultValue; })(); var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, rtypenamespace = /^([^.]*)(?:\.(.+)|)/; function returnTrue() { return true; } function returnFalse() { return false; } // Support: IE9 // 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; } // 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 (event) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix(event); var i, j, ret, matched, handleObj, handlerQueue = [], args = slice.call(arguments), handlers = (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; 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 (at least): Chrome, IE9 // Find delegate handlers // Black-hole SVG 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; }, // Includes some event props shared by KeyEvent and MouseEvent props: ("altKey bubbles cancelable ctrlKey currentTarget detail eventPhase " + "metaKey relatedTarget shiftKey target timeStamp view which").split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function (event, original) { // Add which for key events if (event.which == null) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: ("button buttons clientX clientY offsetX offsetY pageX pageY " + "screenX screenY toElement").split(" "), filter: function (event, original) { var eventDoc, doc, body, button = original.button; // Calculate pageX/Y if missing and clientX/Y available if (event.pageX == null && original.clientX != null) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = original.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if (!event.which && button !== undefined) { event.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0))); } return event; } }, fix: function (event) { if (event[jQuery.expando]) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[type]; if (!fixHook) { this.fixHooks[type] = fixHook = rmouseEvent.test(type) ? this.mouseHooks : rkeyEvent.test(type) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat(fixHook.props) : this.props; event = new jQuery.Event(originalEvent); i = copy.length; while (i--) { prop = copy[i]; event[prop] = originalEvent[prop]; } // Support: Cordova 2.5 (WebKit) (#13255) // All events should have a target; Cordova deviceready doesn't if (!event.target) { event.target = document; } // Support: Safari 6.0+, Chrome<28 // Target should not be a text node (#504, #13143) if (event.target.nodeType === 3) { event.target = event.target.parentNode; } return fixHook.filter ? fixHook.filter(event, originalEvent) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function () { if (this !== safeActiveElement() && this.focus) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function () { if (this === safeActiveElement() && this.blur) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function () { if (this.type === "checkbox" && this.click && jQuery.nodeName(this, "input")) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function (event) { return jQuery.nodeName(event.target, "a"); } }, beforeunload: { postDispatch: function (event) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if (event.result !== undefined && event.originalEvent) { event.originalEvent.returnValue = event.result; } } } } }; 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<4.0 src.returnValue === false ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if (props) { jQuery.extend(this, props); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[jQuery.expando] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { 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(); } }; // 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://code.google.com/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)(([\w:-]+)[^>]*)\/>/gi, // Support: IE 10-11, Edge 10240+ // In IE/Edge using regex groups here causes severe slowdowns. // See https://connect.microsoft.com/IE/feedback/details/1736512/ rnoInnerhtml = /\s*$/g; // Manipulating tables requires a tbody function manipulationTarget(elem, content) { return jQuery.nodeName(elem, "table") && jQuery.nodeName(content.nodeType !== 11 ? content : content.firstChild, "tr") ? elem.getElementsByTagName("tbody")[0] || elem.appendChild(elem.ownerDocument.createElement("tbody")) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript(elem) { elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; return elem; } function restoreScript(elem) { var match = rscriptTypeMasked.exec(elem.type); if (match) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } 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.1, PhantomJS<2 // 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 { jQuery.globalEval(node.textContent.replace(rcleanScript, "")); } } } } } } 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>"); }, 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: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll(clone); srcElements = getAll(elem); for (i = 0, l = srcElements.length; i < l; i++) { fixInput(srcElements[i], destElements[i]); } } // Copy the events from the original to the clone if (dataAndEvents) { if (deepDataAndEvents) { srcElements = srcElements || getAll(elem); destElements = destElements || getAll(clone); for (i = 0, l = srcElements.length; i < l; i++) { cloneCopyEvent(srcElements[i], destElements[i]); } } else { cloneCopyEvent(elem, clone); } } // Preserve script evaluation history destElements = getAll(clone, "script"); if (destElements.length > 0) { setGlobalEval(destElements, !inPage && getAll(elem, "script")); } // Return the cloned set return clone; }, 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({ // Keep domManip exposed until 3.0 (gh-2225) domManip: domManip, 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: QtWebKit // .get() because push.apply(_, arraylike) throws push.apply(ret, elems.get()); } return this.pushStack(ret); }; }); var iframe, elemdisplay = { // Support: Firefox // We have to pre-define these values for FF (#10227) HTML: "block", BODY: "block" }; /** * Retrieve the actual display of a element * @param {String} name nodeName of the element * @param {Object} doc Document object */ // Called only from within defaultDisplay function actualDisplay(name, doc) { var elem = jQuery(doc.createElement(name)).appendTo(doc.body), display = jQuery.css(elem[0], "display"); // We don't have any data stored on the element, // so use "detach" method as fast way to get rid of the element elem.detach(); return display; } /** * Try to determine the default display value of an element * @param {String} nodeName */ function defaultDisplay(nodeName) { var doc = document, display = elemdisplay[nodeName]; if (!display) { display = actualDisplay(nodeName, doc); // If the simple way fails, read from inside an iframe if (display === "none" || !display) { // Use the already-created iframe if possible iframe = (iframe || jQuery("