// This is done by ansarada. (function () { function CustomEvent ( event, params ) { params = params || { bubbles: false, cancelable: false, detail: undefined }; var evt = document.createEvent( 'CustomEvent' ); evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail ); return evt; }; CustomEvent.prototype = window.Event.prototype; window.CustomEvent = CustomEvent; })();;/** * Ansarada * Adapted from http://freqdec.github.io/datePicker/ * MIT/GPL2 license * * Changes: * Added support for CSS name spaces * Added support for not creating the action button * Added support to display * Added support to disable year forward and back buttons * Removed IE6 to IE8 support * Removed clicking on day moves to next week * Fixed IE 10 keyboard support * Todo: * Remove old mark up * remove table **/ var datePicker = (function datePicker() { 'use strict'; var debug = false, isOpera = Object.prototype.toString.call(window.opera) === '[object Opera]', describedBy = '', languageInfo = parseUILanguage(), nbsp = String.fromCharCode(160), datePickers = {}, weeksInYearCache = {}, bespokeTitles = {}, uniqueId = 0, finalOpacity = 100, transitionEnd = '', buttonTabIndex = true, mouseWheel = true, deriveLocale = false, localeImport = false, nodrag = false, langFileFolder = false, returnLocaleDate = false, kbEvent = false, dateParseFallback = true, cellFormat = '%d %F %Y', titleFormat = '%F %d, %Y', statusFormat = '', formatParts = isOpera ? ['%j'] : ['%j', ' %F %Y'], dPartsRegExp = /%([d|j])/, mPartsRegExp = /%([M|F|m|n])/, yPartsRegExp = /%[y|Y]/, noSelectionRegExp = /-unused|out-of-range|day-disabled|not-selectable/, formatTestRegExp = /%([d|j|M|F|m|n|Y|y])/, formatSplitRegExp = /%([d|D|l|j|N|w|S|W|M|F|m|n|t|Y|y])/, rangeRegExp = /^((\d\d\d\d)(0[1-9]|1[012])(0[1-9]|[12][0-9]|3[01]))$/, wcDateRegExp = /^(((\d\d\d\d)|(\*\*\*\*))((0[1-9]|1[012])|(\*\*))(0[1-9]|[12][0-9]|3[01]))$/, wsCharClass = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029'; // https://gist.github.com/padolsey/527683 (function() { var scriptFiles = document.getElementsByTagName('script'), json = parseJSON(String(scriptFiles[scriptFiles.length - 1].innerHTML).replace(/[\n\r\s\t]+/g, ' ').replace(/^\s+/, '').replace(/\s+$/, '')); if(typeof json === 'object' && !('err' in json)) { affectJSON(json); }; if(deriveLocale && typeof(fdLocale) != 'object') { var head = document.getElementsByTagName('head')[0] || document.documentElement, loc = langFileFolder ? langFileFolder : scriptFiles[scriptFiles.length - 1].src.substr(0, scriptFiles[scriptFiles.length - 1].src.lastIndexOf('/')) + '/lang/', script, i; for(i = 0; i < languageInfo.length; i++) { script = document.createElement('script'); script.type = 'text/javascript'; script.src = loc + languageInfo[i] + '.js'; script.charSet = 'utf-8'; }; script = null; } else { returnLocaleDate = true; }; })(); function removeChildNodes(elem) { while(elem.firstChild) { elem.removeChild(elem.firstChild); }; }; function addClass(e, c) { if(new RegExp('(^|[' + wsCharClass + '])' + c + '([' + wsCharClass + ']|$)').test(e.className)) { return; }; e.className += ( e.className ? ' ' : '' ) + c; }; function removeClass(e, c) { e.className = !c ? '' : e.className.replace(new RegExp('(^|[' + wsCharClass + '])' + c + '([' + wsCharClass + ']|$)'), ' ').replace(new RegExp('/^[' + wsCharClass + '][' + wsCharClass + ']*/'), '').replace(new RegExp('/[' + wsCharClass + '][' + wsCharClass + ']*$/'), ''); }; // Attempts to parse the current language from the HTML element. Defaults to 'en' if none given function parseUILanguage() { var languageTag = document.getElementsByTagName('html')[0].getAttribute('lang') || document.getElementsByTagName('html')[0].getAttribute('xml:lang'); languageTag = !languageTag ? 'en' : languageTag.toLowerCase(); return languageTag.search(/^([a-z]{2,3})-([a-z]{2})$/) != -1 ? [languageTag.match(/^([a-z]{2,3})-([a-z]{2})$/)[1], languageTag] : [languageTag]; }; // Cross browser split from http://blog.stevenlevithan.com/archives/cross-browser-split var cbSplit = function(str, separator, limit) { // if `separator` is not a regex, use the native `split` if(Object.prototype.toString.call(separator) !== '[object RegExp]') { return cbSplit._nativeSplit.call(str, separator, limit); }; var output = [], lastLastIndex = 0, flags = '', separator = RegExp(separator.source, 'g'), separator2, match, lastIndex, lastLength; str = str + ''; if(!cbSplit._compliantExecNpcg) { separator2 = RegExp('^' + separator.source + '$(?!\\s)', flags); }; /* behavior for `limit`: if it's... - `undefined`: no limit. - `NaN` or zero: return an empty array. - a positive number: use `Math.floor(limit)`. - a negative number: no limit. - other: type-convert, then use the above rules. */ if(limit === undefined || +limit < 0) { limit = Infinity; } else { limit = Math.floor(+limit); if(!limit) { return []; }; }; while(match = separator.exec(str)) { lastIndex = match.index + match[0].length; // `separator.lastIndex` is not reliable cross-browser if (lastIndex > lastLastIndex) { output.push(str.slice(lastLastIndex, match.index)); // fix browsers whose `exec` methods don't consistently return `undefined` for nonparticipating capturing groups if(!cbSplit._compliantExecNpcg && match.length > 1) { match[0].replace(separator2, function () { for (var i = 1; i < arguments.length - 2; i++) { if(arguments[i] === undefined) { match[i] = undefined; }; }; }); }; if(match.length > 1 && match.index < str.length) { Array.prototype.push.apply(output, match.slice(1)); }; lastLength = match[0].length; lastLastIndex = lastIndex; if(output.length >= limit) { break; }; }; if(separator.lastIndex === match.index) { // avoid an infinite loop separator.lastIndex++; }; }; if(lastLastIndex === str.length) { if (lastLength || !separator.test('')) { output.push(''); }; } else { output.push(str.slice(lastLastIndex)); }; return output.length > limit ? output.slice(0, limit) : output; }; // NPCG: nonparticipating capturing group cbSplit._compliantExecNpcg = /()??/.exec('')[1] === undefined; cbSplit._nativeSplit = String.prototype.split; // Affects the JSON passed to the script function affectJSON(json) { if(!(typeof json === 'object')) { return; }; var key, switchObj = { 'debug':function(value) { debug = !!value; return true; }, 'lang':function(value) { if(typeof value === 'string' && value.search(/^[a-z]{2,3}(-([a-z]{2}))?$/i) != -1) { languageInfo = [value.toLowerCase()]; returnLocaleDate = true; deriveLocale = true; }; return true; }, 'nodrag':function(value) { nodrag = !!value; return true; }, 'buttontabindex':function(value) { buttonTabIndex = !!value; return true; }, 'derivelocale':function(value) { deriveLocale = !!value; return true; }, 'mousewheel':function(value) { mouseWheel = !!value; return true; }, 'cellformat':function(value) { if(typeof value === 'string') { parseCellFormat(value); }; return true; }, 'titleformat':function(value) { if(typeof value === 'string') { titleFormat = value; }; return true; }, 'statusformat':function(value) { if(typeof value === 'string') { statusFormat = value; }; return true; }, 'describedby':function(value) { if(typeof value === 'string') { describedBy = value; }; return true; }, 'finalopacity':function(value) { if(typeof value === 'number' && (+value > 20 && +value <= 100)) { finalOpacity = parseInt(value, 10); }; return true; }, 'bespoketitles':function(value) { if(typeof value === 'object') { bespokeTitles = {}; for(var dt in value) { if(value.hasOwnProperty(dt) && String(dt).match(wcDateRegExp) != -1) { bespokeTitles[dt] = String(value[dt]); }; }; }; return true; }, 'dateparsefallback':function(value) { dateParseFallback = !!value; return true; }, 'languagefilelocation':function(value) { langFileFolder = value; return true; }, '_default':function() { if(debug) { throw 'Unknown key located within JSON data: ' + key; }; return true; } }; for(key in json) { if(!json.hasOwnProperty(key)) { continue; }; (switchObj.hasOwnProperty(String(key).toLowerCase()) && switchObj[String(key).toLowerCase()] || switchObj._default)(json[key]); }; }; // Parses the JSON passed either between the script tags or by using the // setGlobalOptions method function parseJSON(str) { if(!(typeof str === 'string') || str == '') { return {}; }; try { // Does a JSON (native or not) Object exist if(typeof JSON === 'object' && JSON.parse) { return window.JSON.parse(str); // Genious code taken from: http://kentbrewster.com/badges/ } else if(/debug|lang|nodrag|buttontabindex|derivelocale|mousewheel|cellformat|titleformat|statusformat|describedby|finalopacity|bespoketitles|dateparsefallback/.test(str.toLowerCase())) { var f = Function(['var document,top,self,window,parent,Number,Date,Object,Function,', 'Array,String,Math,RegExp,Image,ActiveXObject;', 'return (' , str.replace(/<\!--.+-->/gim,'').replace(/\bfunction\b/g,'function-') , ');'].join('')); return f(); }; } catch (e) { }; if(debug) { throw 'Could not parse the JSON object'; }; return {'err':1}; }; // Parses the cell format to use whenever the datepicker has keyboard focus function parseCellFormat(value) { if(isOpera) { // Don't use hidden text for opera due to the default // 'blue' browser focus outline stretching outside of the viewport // and degrading visual accessibility. Harsh & hackish though... formatParts = ['%j']; cellFormat = '%j %F %Y'; return; }; // If no day part stipulated then use presets if(value.match(/%([d|j])/) == -1) { return; }; // Basic split on the %j or %d modifiers formatParts = cbSplit(value, /%([d|j])/); cellFormat = value; }; function pad(value, length) { length = Math.min(4, length || 2); return '0000'.substr(0,length - Math.min(String(value).length, length)) + value; }; // Very, very basic event functions function addEvent(obj, type, fn) { if(obj.addEventListener) { obj.addEventListener(type, fn, true); } else if(obj.attachEvent) { obj.attachEvent('on'+type, fn); }; }; function removeEvent(obj, type, fn) { try { if(obj.removeEventListener) { obj.removeEventListener(type, fn, true); } else if(obj.detachEvent) { obj.detachEvent('on'+type, fn); }; } catch(err) {}; }; function stopEvent(e) { e = e || document.parentWindow.event; if(e.stopPropagation) { e.stopPropagation(); e.preventDefault(); }; return false; }; function setARIARole(element, role) { if(element && element.tagName) { element.setAttribute('role', role); }; }; function setARIAProperty(element, property, value) { if(element && element.tagName) { element.setAttribute('aria-' + property, value); }; }; // Sets a tabindex attribute on an element, bends over for IE. function setTabIndex(e, i) { e.setAttribute('tabindex', i); e.tabIndex = i; }; function dateToYYYYMMDD(dt) { return dt instanceof Date && !isNaN(dt) ? dt.getFullYear() + pad(dt.getMonth() + 1) + '' + pad(dt.getDate()) : dt; }; // The datePicker object itself function datePicker(options) { this.dateSet = null; this.timerSet = false; this.visible = false; this.fadeTimer = null; this.timer = null; this.yearInc = 0; this.monthInc = 0; this.dayInc = 0; this.mx = 0; this.my = 0; this.x = 0; this.y = 0; this.created = false; this.disabled = false; this.opacity = 0; this.opacityTo = 100; this.finalOpacity = 100; this.inUpdate = false; this.kbEventsAdded = false; this.fullCreate = false; this.selectedTD = null; this.cursorTD = null; this.cursorDate = options.cursorDate ? options.cursorDate : '', this.date = options.cursorDate ? new Date(+options.cursorDate.substr(0,4), +options.cursorDate.substr(4,2) - 1, +options.cursorDate.substr(6,2),5,0,0) : new Date(); this.defaults = {}; this.dynDisabledDates = {}; this.dateList = []; this.bespokeClass = options.bespokeClass; this.firstDayOfWeek = localeImport.firstDayOfWeek; this.interval = new Date(); this.clickActivated = false; this.showCursor = false; this.noFocus = true; this.kbEvent = false; this.delayedUpdate = false; this.showActionButton = true; this.bespokeTitles = {}; this.bespokeTabIndex = options.bespokeTabIndex; this.customCssClassName = options.customCssClassName; this.noYearForwardBack = options.noYearForwardBack; this.actionElement = options.actionElement; for(var thing in options) { if(!options.hasOwnProperty(thing) || String(thing).search(/^(callbacks|formElements|enabledDates|disabledDates)$/) != -1) { continue; }; this[thing] = options[thing]; }; for(var i = 0, prop; prop = ['callbacks', 'formElements'][i]; i++) { this[prop] = {}; if(prop in options) { for(thing in options[prop]) { if(options[prop].hasOwnProperty(thing)) { this[prop][thing] = options[prop][thing]; }; }; }; }; // Adjust time to stop daylight savings madness on windows this.date.setHours(5); // Called from an associated form elements onchange event this.changeHandler = function() { // In a perfect world this shouldn't ever happen if(o.disabled) { return; }; o.setDateFromInput(); o.callback('dateset', o.createCbArgObj()); }; // Creates the object passed to the callback functions this.createCbArgObj = function() { return this.dateSet ? { 'id' :this.id, 'date' :this.dateSet, 'dd' :pad(this.date.getDate()), 'mm' :pad(this.date.getMonth() + 1), 'yyyy' :this.date.getFullYear() } : { 'id' :this.id, 'date' :null, 'dd' :null, 'mm' :null, 'yyyy' :null }; }; // Attempts to grab the window scroll offsets this.getScrollOffsets = function() { if(typeof(window.pageYOffset) == 'number') { //Netscape compliant return [window.pageXOffset, window.pageYOffset]; } else if(document.body && (document.body.scrollLeft || document.body.scrollTop)) { //DOM compliant return [document.body.scrollLeft, document.body.scrollTop]; } else if(document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) { //IE6 standards compliant mode return [document.documentElement.scrollLeft, document.documentElement.scrollTop]; }; return [0,0]; }; // Calculates the current list of disabled & enabled dates for a specific year/month this.getDateExceptions = function(y, m) { m = pad(m); var obj = {}, lower = o.firstDateShown, upper = o.lastDateShown, rLength = o.dateList.length, rNumber, workingDt, workingY, workingM, dtLower, dtUpper, i, dt, dt1, dt2, rngLower, rngUpper, cDate; if(!upper || !lower) { lower = o.firstDateShown = y + pad(m) + '01'; upper = o.lastDateShown = y + pad(m) + pad(daysInMonth(m, y)); }; dtLower = Number(lower.substr(0,6)); dtUpper = Number(upper.substr(0,6)); workingDt = String(dtLower); while(+workingDt <= dtUpper) { workingY = workingDt.substr(0,4); workingM = workingDt.substr(4,2); for(rNumber = 0; rNumber < rLength; rNumber++) { dt1 = String(o.dateList[rNumber].rLow).replace(/^(\*\*\*\*)/, workingY).replace(/^(\d\d\d\d)(\*\*)/, '$1'+workingM); dt2 = String(o.dateList[rNumber].rHigh).replace(/^(\*\*\*\*)/, workingY).replace(/^(\d\d\d\d)(\*\*)/, '$1'+workingM); // Single date if(dt2 == 1) { if(+dt1 >= +o.firstDateShown && +dt1 <= +o.lastDateShown) { obj[dt1] = o.dateList[rNumber].type; }; continue; }; // Date Range if(dt1 <= dt2 && workingDt >= dt1.substr(0,6) && workingDt <= dt2.substr(0,6) ) { rngLower = Math.max(dt1, Math.max(String(workingDt) + '01', this.firstDateShown)); rngUpper = Math.min(dt2, Math.min(String(workingDt) + '31', this.lastDateShown)); for(i = rngLower; i <= rngUpper; i++) { obj[i] = o.dateList[rNumber].type; }; }; }; // Let the Date Object take care of month overflowss workingDt = new Date(workingY, +workingM, 2); workingDt = workingDt.getFullYear()+''+pad(workingDt.getMonth()+1); }; return obj; }; // Repositions the datepicker beside the button - to the bottom by // preference but to the top if there is not enough room to display the // entire U.I. at the bottom (it really should be updated to favour // bottom positioning if not enough room to display the entire U.I. at // the top in that scenario though) this.reposition = function() { if(!o.created || o.staticPos) { return; }; o.div.style.visibility = 'hidden'; o.div.style.left = o.div.style.top = '0px'; o.div.style.display = 'block'; var osh = o.div.offsetHeight, osw = o.div.offsetWidth, elem = (o.showActionButton) ? document.getElementById(getCssClassNameSpace(o)+ '-but-' + o.id) : document.getElementById(o.id), pos = o.truePosition(elem), trueBody = (document.compatMode && document.compatMode!='BackCompat') ? document.documentElement : document.body, sOffsets = o.getScrollOffsets(), scrollTop = sOffsets[1], scrollLeft = sOffsets[0], tSpace = parseInt(pos[1] - 2) - parseInt(scrollTop), bSpace = parseInt(trueBody.clientHeight + scrollTop) - parseInt(pos[1] + elem.offsetHeight + 2), placeAtBottom = 0, inputControlOuterHeight = $('#' + o.id).outerHeight(); o.div.style.visibility = 'visible'; if($(o.div).parents('.ace-dialog-content').length) { var toplocation = $('#' + o.id)[0].getBoundingClientRect().top + $('#' + o.id).outerHeight() + $(o.div).outerHeight(); placeAtBottom = (toplocation < $(window).height()) && (toplocation < $(o.div).parents('.ace-dialog-content').outerHeight()); } else { placeAtBottom = (bSpace > tSpace); } if(placeAtBottom) { removeClass(o.div, getCssClassNameSpace(o) + '-pos-top'); addClass(o.div, getCssClassNameSpace(o) + '-pos-bottom'); $(o.div).css('top', inputControlOuterHeight + 'px'); $(o.div).css('bottom', ''); } else { removeClass(o.div, getCssClassNameSpace(o) + '-pos-bottom') addClass(o.div, getCssClassNameSpace(o) + '-pos-top') $(o.div).css('bottom', inputControlOuterHeight + 'px'); $(o.div).css('top', ''); } }; this.removeCursorHighlight = function() { var td = document.getElementById(getCssClassNameSpace(o) + '-hover-' + o.id); if(td) { removeClass(td, getCssClassNameSpace(o) + '-hover'); }; }; this.addCursorHighlight = function() { var td = document.getElementById(getCssClassNameSpace(o) + '-hover' + o.id); if(td) { addClass(td, getCssClassNameSpace(o) + '-hover'); }; }; // Resets the tabindex of the previously focused cell this.removeOldFocus = function() { var td = document.getElementById(getCssClassNameSpace(o) + '-hover-' + o.id); if(td) { try { setTabIndex(td, -1); removeClass(td, getCssClassNameSpace(o) + '-hover'); td.id = ''; td.onblur = null; td.onfocus = null; } catch(err) {}; }; }; // Sets the tabindex & focus on the currently highlighted cell this.setNewFocus = function() { var td = document.getElementById(getCssClassNameSpace(o) + '-hover-' + o.id); if(td) { try { setTabIndex(td, 0); if(this.showCursor) { addClass(td, getCssClassNameSpace(o) + '-hover'); }; // If opened with the keyboard then add focus & blur events to the cell if(!this.clickActivated) { td.onblur = o.onblur; td.onfocus = o.onfocus; }; // If opened with the keyboard (and not in opera) then add a screen-reader friendly date format if(!isOpera && !this.clickActivated) { o.addAccessibleDate(); }; // Try to programmatically set focus on the cell if(!this.noFocus && !this.clickActivated) { setTimeout(function() { try { td.focus(); } catch(err) {}; }, 0); }; } catch(err) { }; }; }; // Adds a screen-reader friendly date to the current cell whenever // the datepicker has been opened with the keyboard this.addAccessibleDate = function() { var td = document.getElementById(getCssClassNameSpace(o) + '-hover-' + o.id); if(td && !(td.getElementsByTagName('span').length)) { var ymd = td.className.match(/cd-([\d]{4})([\d]{2})([\d]{2})/), noS = td.className.search(noSelectionRegExp) != -1, spn = document.createElement('span'), spnC; spn.className = getCssClassNameSpace(o) + '-screen-reader'; removeChildNodes(td); if(noS) { spnC = spn.cloneNode(false); spnC.appendChild(document.createTextNode(getTitleTranslation(13))); td.appendChild(spnC); }; for(var pt = 0, part; part = formatParts[pt]; pt++) { if(part == '%j' || part == '%d') { td.appendChild(document.createTextNode(printFormattedDate(new Date(ymd[1], +ymd[2]-1, ymd[3], 5, 0, 0), part, true))); } else { spnC = spn.cloneNode(false); spnC.appendChild(document.createTextNode(printFormattedDate(new Date(ymd[1], +ymd[2]-1, ymd[3], 5, 0, 0), part, true))); td.appendChild(spnC); }; }; }; }; // Sets the current cursor to a specific date this.setCursorDate = function(yyyymmdd) { if(String(yyyymmdd).search(/^([0-9]{8})$/) != -1) { this.date = new Date(+yyyymmdd.substr(0,4), +yyyymmdd.substr(4,2) - 1, +yyyymmdd.substr(6,2), 5, 0, 0); this.cursorDate = yyyymmdd; if(this.staticPos) { this.updateTable(); }; }; }; // Updates the table used to display the datepicker this.updateTable = function(noCallback) { if(!o || o.inUpdate || !o.created) { return; }; // We are currently updating (used to stop public methods from firing) o.inUpdate = true; // Remove the focus from the currently highlighted cell o.removeOldFocus(); o.div.dir = localeImport.rtl ? 'rtl' : 'ltr'; // If the update timer initiated if(o.timerSet && !o.delayedUpdate) { // Are we incrementing/decrementing the month if(o.monthInc) { var n = o.date.getDate(), d = new Date(o.date); d.setDate(2); d.setMonth(d.getMonth() + o.monthInc * 1); // Don't go over the days in the month d.setDate(Math.min(n, daysInMonth(d.getMonth(),d.getFullYear()))); o.date = new Date(d); } else { o.date.setDate(Math.min(o.date.getDate()+o.dayInc, daysInMonth(o.date.getMonth()+o.monthInc,o.date.getFullYear()+o.yearInc))); o.date.setMonth(o.date.getMonth() + o.monthInc); o.date.setFullYear(o.date.getFullYear() + o.yearInc); }; }; // Make sure the internal date is within range o.outOfRange(); // Disable/enable the today button if(!o.noToday) { o.disableTodayButton(); }; // Disable/enable the month & year buttons o.showHideButtons(o.date); var cd = o.date.getDate(), cm = o.date.getMonth(), cy = o.date.getFullYear(), cursorDate = (String(cy) + pad(cm+1) + pad(cd)), tmpDate = new Date(cy, cm, 1, 5, 0, 0); tmpDate.setHours(5); var dt, dts, cName, row, td, i, currentDate, cellAdded, col, currentStub, abbr, bespokeRenderClass, spnC, dateSetD, selectable, weekDay, // Weekday of the fist of the month weekDayC = (tmpDate.getDay() + 6) % 7, // The column index this weekday will occupy firstColIndex = (((weekDayC - o.firstDayOfWeek) + 7 ) % 7) - 1, // The number of days in the current month dpm = daysInMonth(cm, cy), // Today as a Date Object today = new Date(), // Today as a YYYYMMDD String today = today.getFullYear() + pad(today.getMonth()+1) + pad(today.getDate()), // A Sring date stub in a YYYYMM format for the current date stub = String(tmpDate.getFullYear()) + pad(tmpDate.getMonth()+1), // cellAdded = [4,4,4,4,4,4], // The first day of the previous month as a Date Object lm = new Date(cy, cm-1, 1, 5, 0, 0), // The first day of the next month as a Date Object nm = new Date(cy, cm+1, 1, 5, 0, 0), // The number of days in the previous month daySub = daysInMonth(lm.getMonth(), lm.getFullYear()), // YYYYMM String date stub for the next month stubN = String(nm.getFullYear()) + pad(nm.getMonth()+1), // YYYYMM String date stub for the previous month stubP = String(lm.getFullYear()) + pad(lm.getMonth()+1), weekDayN = (nm.getDay() + 6) % 7, weekDayP = (lm.getDay() + 6) % 7, // A SPAN node to clone when adding dates to individual cells spn = document.createElement('span'); // Give the '-screen-reader' class to the span in order to hide them in the UI // but keep them accessible to screen-readers spn.className = getCssClassNameSpace(o) + '-screen-reader'; // The first & last dates shown on the datepicker UI - could be a date from the previous & next month respectively o.firstDateShown = !o.constrainSelection && o.fillGrid && (0 - firstColIndex < 1) ? String(stubP) + (daySub + (0 - firstColIndex)) : stub + '01'; o.lastDateShown = !o.constrainSelection && o.fillGrid ? stubN + pad(41 - firstColIndex - dpm) : stub + String(dpm); // Store a reference to the current YYYYMM String representation of the current month o.currentYYYYMM = stub; bespokeRenderClass = o.callback('redraw', {id:o.id, dd:pad(cd), mm:pad(cm+1), yyyy:cy, firstDateDisplayed:o.firstDateShown, lastDateDisplayed:o.lastDateShown}) || {}; // An Object of dates that have been explicitly disabled (1) or enabled (0) dts = o.getDateExceptions(cy, cm+1); // Double check current date within limits etc o.checkSelectedDate(); // dateSetD = (o.dateSet != null) ? o.dateSet.getFullYear() + pad(o.dateSet.getMonth()+1) + pad(o.dateSet.getDate()) : false; // If we have selected a date then set its ARIA selected property // to false. We then set the ARIA selected property to true on the // newly selected cell after redrawing the table if(this.selectedTD != null) { setARIAProperty(this.selectedTD, 'selected', false); this.selectedTD = null; }; // Redraw all of the table cells representing the date parts of the UI for(var curr = 0; curr < 42; curr++) { // Current row row = Math.floor(curr / 7); // Current TD node td = o.tds[curr]; // Clone our SPAN node spnC = spn.cloneNode(false); // Remove any previous contents from the cell removeChildNodes(td); // If the current cell contains a date if((curr > firstColIndex && curr <= (firstColIndex + dpm)) || o.fillGrid) { currentStub = stub; weekDay = weekDayC; dt = curr - firstColIndex; cName = []; selectable = true; // Are we drawing last month if(dt < 1) { dt = daySub + dt; currentStub = stubP; weekDay = weekDayP; selectable = !o.constrainSelection; cName.push('month-out'); // Are we drawing next month } else if(dt > dpm) { dt -= dpm; currentStub = stubN; weekDay = weekDayN; selectable = !o.constrainSelection; cName.push('month-out'); }; // Calcuate this cells weekday weekDay = (weekDay + dt + 6) % 7; // Push a classname representing the weekday e.g. 'day-3' cName.push('day-' + weekDay + ' cell-' + curr); // A YYYYMMDD String representation of this cells date currentDate = currentStub + String(dt < 10 ? '0' : '') + dt; // If this cells date is out of range if(o.rangeLow && +currentDate < +o.rangeLow || o.rangeHigh && +currentDate > +o.rangeHigh) { // Add a classname to style the cell and stop selection td.className = 'out-of-range'; // Reset this TD nodes title attribute td.title = ''; // Append the cells date as a text node to the TD td.appendChild(document.createTextNode(dt)); // Jaysus, what the feck does this line do again... if(o.showWeeks) { cellAdded[row] = Math.min(cellAdded[row], 2); }; // This cells date is within the lower & upper ranges (or no ranges have been defined) } else { // If it's a date from last or next month and the 'constrainSelection' option // is false then give the cell a CD-YYYYMMDD class if(selectable) { td.title = titleFormat ? printFormattedDate(new Date(+String(currentStub).substr(0,4), +String(currentStub).substr(4, 2) - 1, +dt, 5, 0, 0), titleFormat, true) : ''; cName.push('cd-' + currentDate + ' yyyymmdd-' + currentDate + ' yyyymm-' + currentStub + ' mmdd-' + currentStub.substr(4,2) + pad(dt)); // Otherwise give a 'not-selectable' class (which shouldn't be styled in any way, it's for internal use) } else { td.title = titleFormat ? getTitleTranslation(13) + ' ' + printFormattedDate(new Date(+String(currentStub).substr(0,4), +String(currentStub).substr(4, 2) - 1, +dt, 5, 0, 0), titleFormat, true) : ''; cName.push('yyyymmdd-' + currentDate + ' yyyymm-' + currentStub + ' mmdd-' + currentStub.substr(4,2) + pad(dt) + ' not-selectable'); }; // Add a classname if the current cells date is today if(currentDate == today) { cName.push(getCssClassNameSpace(o) + '-today'); }; // If this cell represents the currently selected date if(dateSetD == currentDate) { // Add a classname (for styling purposes) cName.push(getCssClassNameSpace(o) + '-selected-date'); // Set the ARIA selected property to true setARIAProperty(td, 'selected', 'true'); // And cache a reference to the current cell this.selectedTD = td; }; // If the current cell has been explicitly disabled if(((currentDate in dts) && dts[currentDate] == 1) // or || // ... the current weekday has been disabled (o.disabledDays[weekDay] && // ... and the current date has not been explicitly enabled !((currentDate in dts) && dts[currentDate] == 0) ) ) { // Add a classname to style the cell and stop selection cName.push('day-disabled'); // Update the current cells title to say 'Disabled date: ...' (or whatever the translation says) if(titleFormat && selectable) { td.title = getTitleTranslation(13) + ' ' + td.title; }; }; // Has the redraw callback given us a bespoke classname to add to this cell if(currentDate in bespokeRenderClass) { cName.push(bespokeRenderClass[currentDate]); }; // Do we need to highlight this cells weekday representation if(o.highlightDays[weekDay]) { cName.push(getCssClassNameSpace(o) + '-highlight'); }; // Is the current onscreen cursor set to this cells date if(cursorDate == currentDate) { td.id = getCssClassNameSpace(o) + '-hover-' + o.id; }; // Add the date to the TD cell as a text node. Note: If the datepicker has been given keyboard // events, this textnode is replaced by a more screen-reader friendly date during the focus event td.appendChild(document.createTextNode(dt)); // Add the classnames to the TD node td.className = cName.join(' '); // If the UI displays week numbers then update the celladded if(o.showWeeks) { cellAdded[row] = Math.min(cName[0] == 'month-out' ? 3 : 1, cellAdded[row]); }; }; // The current TD node is empty i.e. represents no date in the UI } else { // Add a classname to style the cell td.className = getCssClassNameSpace(o) + '-unused'; // Add a non-breaking space to unused TD node (for IEs benefit mostly) td.appendChild(document.createTextNode(nbsp)); // Reset the TD nodes title attribute td.title = ''; }; // Do we update the week number for this row if(o.showWeeks && curr - (row * 7) == 6) { removeChildNodes(o.wkThs[row]); o.wkThs[row].appendChild(document.createTextNode(cellAdded[row] == 4 && !o.fillGrid ? nbsp : getWeekNumber(cy, cm, curr - firstColIndex - 6))); o.wkThs[row].className = getCssClassNameSpace(o) + '-week-header' + (['','',' out-of-range',' month-out',''][cellAdded[row]]); }; }; // Update the UI title bar displaying the year & month var span = o.titleBar.getElementsByTagName('span'); removeChildNodes(span[0]); removeChildNodes(span[1]); span[0].appendChild(document.createTextNode(getMonthTranslation(cm, false) + nbsp)); span[1].appendChild(document.createTextNode(cy)); // If we are in an animation if(o.timerSet) { // Speed the timer up a little bit to make the pause between updates quicker o.timerInc = 50 + Math.round(((o.timerInc - 50) / 1.8)); // Recall this function in a timeout o.timer = window.setTimeout(o.updateTable, o.timerInc); }; // We are not currently updating the UI o.inUpdate = o.delayedUpdate = false; // Focus on the correct TD node o.setNewFocus(); }; // Removes all scaffold from the DOM & events from memory this.destroy = function() { // Remove the button if it exists if(document.getElementById(getCssClassNameSpace(o) + '-but-' + this.id)) { document.getElementById(getCssClassNameSpace(o) + '-but-' + this.id).parentNode.removeChild(document.getElementById(getCssClassNameSpace(o) +'-but-' + this.id)); }; if(!this.created) { return; }; // Event cleanup for Internet Explorers benefit removeEvent(this.table, 'mousedown', o.onmousedown); removeEvent(this.table, 'mouseover', o.onmouseover); removeEvent(this.table, 'mouseout', o.onmouseout); removeEvent(document, 'mousedown', o.onmousedown); removeEvent(document, 'mouseup', o.clearTimer); if (window.addEventListener && !window.devicePixelRatio) { try { window.removeEventListener('DOMMouseScroll', this.onmousewheel, false); } catch(err) {}; } else { removeEvent(document, 'mousewheel', this.onmousewheel); removeEvent(window, 'mousewheel', this.onmousewheel); }; o.removeOnFocusEvents(); clearTimeout(o.fadeTimer); clearTimeout(o.timer); if(this.div && this.div.parentNode) { this.div.parentNode.removeChild(this.div); }; o = null; }; this.resizeInlineDiv = function() { o.div.style.width = o.table.offsetWidth + 'px'; o.div.style.height = o.table.offsetHeight + 'px'; }; this.reset = function() { var elemID, elem; for(elemID in o.formElements) { elem = document.getElementById(elemID); if(elem) { if(elem.tagName.toLowerCase() == 'select') { elem.selectedIndex = o.defaultVals[elemID]; } else { elem.value = o.defaultVals[elemID]; }; }; }; o.changeHandler(); }; // Creates the DOM scaffold this.create = function() { if(document.getElementById(getCssClassNameSpace(o) + '-' + this.id)) { return; }; var tr, row, col, tableHead, tableBody, tableFoot; this.noFocus = true; function createTH(details) { var th = document.createElement('th'); if(details.thClassName) { th.className = details.thClassName; }; if(details.colspan) { th.setAttribute('colspan', details.colspan); }; th.unselectable = 'on'; return th; }; function createThAndButton(tr, obj) { for(var i = 0, details; details = obj[i]; i++) { var th = createTH(details); tr.appendChild(th); var but = document.createElement('span'); but.className = details.className; but.id = o.id + details.id; but.appendChild(document.createTextNode(details.text || o.nbsp)); but.title = details.title || ''; but.unselectable = 'on'; th.appendChild(but); }; }; this.div = document.createElement('div'); this.div.id = getCssClassNameSpace(o) + '-' + this.id; this.div.className = getCssClassNameSpace(o) + ' ' + getCssClassNameSpace(o) + '-hidden' + this.bespokeClass; // Attempt to hide the div from screen readers during content creation this.div.style.visibility = 'hidden'; // Set the ARIA describedby property if the required block available if(this.describedBy && document.getElementById(this.describedBy)) { setARIAProperty(this.div, 'describedby', this.describedBy); }; // Set the ARIA labelled property if the required label available if(this.labelledBy) { setARIAProperty(this.div, 'labelledby', this.labelledBy.id); }; this.idiv = document.createElement('div'); this.table = document.createElement('table'); this.table.className = getCssClassNameSpace(o) + '-table'; this.table.id = getCssClassNameSpace(o) + '-table-' + o.id; this.table.onmouseover = this.onmouseover; this.table.onmouseout = this.onmouseout; this.table.onclick = this.onclick; if(this.finalOpacity < 100) { this.idiv.style.opacity = Math.min(Math.max(parseInt(this.finalOpacity, 10) / 100, .2), 1); }; if(this.staticPos) { this.table.onmousedown = this.onmousedown; }; this.div.appendChild(this.idiv); this.idiv.appendChild(this.table); var dragEnabledCN = !this.dragDisabled ? ' drag-enabled' : ''; if(!this.staticPos) { this.div.style.visibility = 'hidden'; this.div.className += dragEnabledCN; if(this.actionElement !== null) { this.actionElement.appendChild(this.div); } else { document.getElementsByTagName('body')[0].appendChild(this.div); } // Aria 'hidden' property for non active popup datepickers setARIAProperty(this.div, 'hidden', 'true'); } else { var elem = document.getElementById(this.positioned ? this.positioned : this.id); if(!elem) { this.div = null; if(debug) { throw this.positioned ? 'Could not locate a datePickers associated parent element with an id:' + this.positioned : 'Could not locate a datePickers associated input with an id:' + this.id; }; return; }; this.div.className += ' static-datepicker'; if(this.positioned) { elem.appendChild(this.div); } else { elem.parentNode.insertBefore(this.div, elem.nextSibling); }; if(this.hideInput) { for(var elemID in this.formElements) { elem = document.getElementById(elemID); if(elem) { elem.className += ' ' + getCssClassNameSpace(this) + '-hidden-input'; }; }; }; setTimeout(this.resizeInlineDiv, 300); }; // ARIA Application role setARIARole(this.div, 'application'); //setARIARole(this.table, 'grid'); if(this.statusFormat) { tableFoot = document.createElement('tfoot'); this.table.appendChild(tableFoot); tr = document.createElement('tr'); tr.className = getCssClassNameSpace(o) + '-tfoot'; tableFoot.appendChild(tr); this.statusBar = createTH({thClassName:getCssClassNameSpace(o) + '-statusbar' + dragEnabledCN, colspan:this.showWeeks ? 8 : 7}); tr.appendChild(this.statusBar); this.updateStatus(); }; tableHead = document.createElement('thead'); tableHead.className = getCssClassNameSpace(o) + '-thead'; this.table.appendChild(tableHead); tr = document.createElement('tr'); setARIARole(tr, 'presentation'); tableHead.appendChild(tr); //Title Bar this.titleBar = createTH( { thClassName:getCssClassNameSpace(o) +'-title' + dragEnabledCN + ' ' + getCssClassNameSpace(o) + '-header-content', colspan:this.showWeeks ? 6 : 5 } ); this.monthBackButton = createTH( { thClassName: getCssClassNameSpace(o) + '-prev-but ' + getCssClassNameSpace(o) + '-prev-month' + ' ' + getCssClassNameSpace(o) + '-header-content', title:getTitleTranslation(0) } ); this.monthNextButton = createTH( { thClassName: getCssClassNameSpace(o) + '-next-but ' + getCssClassNameSpace(o) + '-next-month' + ' ' + getCssClassNameSpace(o) + '-header-content', text:'\u203A', title:getTitleTranslation(1) } ); tr.appendChild(this.monthBackButton); tr.appendChild(this.titleBar); tr.appendChild(this.monthNextButton); tr = null; var span = document.createElement('span'); span.appendChild(document.createTextNode(nbsp)); span.className = getCssClassNameSpace(o) + '-month-display' + dragEnabledCN; this.titleBar.appendChild(span); span = document.createElement('span'); span.appendChild(document.createTextNode(nbsp)); span.className = getCssClassNameSpace(o) + '-year-display' + dragEnabledCN; this.titleBar.appendChild(span); var hyperlink = document.createElement('span'); hyperlink.className = getCssClassNameSpace(o) + '-prev-month-tigger ' + getCssClassNameSpace(o) + '-header-button'; hyperlink.id = this.id + '-prev-month-but'; this.butPrevMonth = hyperlink; this.monthBackTigger = hyperlink; this.monthBackButton.appendChild(hyperlink); span = document.createElement('span'); span.appendChild(document.createTextNode(nbsp)); span.className = 'ace-icon ace-icon-control-arrowleft'; span.id = this.id + '-prev-month-but-inter'; this.monthBackTigger.appendChild(span); hyperlink = document.createElement('span'); hyperlink.className = getCssClassNameSpace(o) + '-next-month-tigger ' + getCssClassNameSpace(o) + '-header-button'; hyperlink.id = this.id + '-next-month-but'; this.butNextMonth = hyperlink; this.monthNextTigger = hyperlink; this.monthNextButton.appendChild(hyperlink); span = document.createElement('span'); span.appendChild(document.createTextNode(nbsp)); span.className = 'ace-icon ace-icon-control-arrowright'; span.id = this.id + '-next-month-but-inter'; this.monthNextTigger.appendChild(span); span = null; tr = document.createElement('tr'); setARIARole(tr, 'presentation'); tableHead.appendChild(tr); tableBody = document.createElement('tbody'); this.table.appendChild(tableBody); var colspanTotal = this.showWeeks ? 8 : 7, colOffset = this.showWeeks ? 0 : -1, but, abbr, formElemId, formElem; for(var rows = 0; rows < 7; rows++) { row = document.createElement('tr'); if(rows != 0) { // ARIA Grid role setARIARole(row, 'row'); tableBody.appendChild(row); } else { tableHead.appendChild(row); }; for(var cols = 0; cols < colspanTotal; cols++) { if(rows === 0 || (this.showWeeks && cols === 0)) { col = document.createElement('th'); } else { col = document.createElement('td'); setARIAProperty(col, 'describedby', this.id + '-col-' + cols + (this.showWeeks ? ' ' + this.id + '-row-' + rows : '')); setARIAProperty(col, 'selected', 'false'); }; row.appendChild(col); if((this.showWeeks && cols > 0 && rows > 0) || (!this.showWeeks && rows > 0)) { //setARIARole(col, 'gridcell'); } else { if(rows === 0 && cols > colOffset) { col.className = getCssClassNameSpace(o) + '-day-header'; col.scope = 'col'; //setARIARole(col, 'columnheader'); col.id = this.id + '-col-' + cols; } else { col.className = getCssClassNameSpace(o) +'-week-header'; col.scope = 'row'; //setARIARole(col, 'rowheader'); col.id = this.id + '-row-' + rows; }; }; }; }; col = row = null; this.ths = this.table.getElementsByTagName('thead')[0].getElementsByTagName('tr')[2].getElementsByTagName('th'); for (var y = 0; y < colspanTotal; y++) { if(y == 0 && this.showWeeks) { this.ths[y].appendChild(document.createTextNode(getTitleTranslation(6))); this.ths[y].title = getTitleTranslation(8); continue; }; if(y > (this.showWeeks ? 0 : -1)) { but = document.createElement('span'); but.className = getCssClassNameSpace(o) + '-day-header'; this.ths[y].appendChild(but); }; }; but = null; this.trs = this.table.getElementsByTagName('tbody')[0].getElementsByTagName('tr'); this.tds = this.table.getElementsByTagName('tbody')[0].getElementsByTagName('td'); if(this.noToday && this.butToday != null) { this.butToday.style.display = 'none'; }; if(this.showWeeks) { this.wkThs = this.table.getElementsByTagName('tbody')[0].getElementsByTagName('th'); this.div.className += ' weeks-displayed'; }; tableBody = tableHead = tr = createThAndButton = createTH = null; this.updateTableHeaders(); this.created = true; this.updateTable(); if(this.staticPos) { this.visible = true; this.opacity = 100; this.div.style.visibility = 'visible'; this.div.style.display = 'block'; this.noFocus = true; this.fade(); } else { this.reposition(); this.div.style.visibility = 'visible'; this.fade(); this.noFocus = true; }; this.callback('domcreate', { 'id':this.id }); }; this.transEnd = function() { o.div.style.display = 'none'; o.div.style.visibility = 'hidden'; setARIAProperty(o.div, 'hidden', 'true'); }; this.fade = function() { window.clearTimeout(o.fadeTimer); o.fadeTimer = null; o.setOpacity(o.opacityTo); if(o.opacityTo == 0) { o.div.style.visibility = 'hidden'; setARIAProperty(o.div, 'hidden', 'true'); o.visible = false; } else { o.div.style.visibility = 'visible'; removeClass(o.div, getCssClassNameSpace(o) + '-hidden'); setARIAProperty(o.div, 'hidden', 'false'); o.visible = true; }; }; this.trackDrag = function(e) { e = e || window.event; var diffx = (e.pageX?e.pageX:e.clientX?e.clientX:e.x) - o.mx; var diffy = (e.pageY?e.pageY:e.clientY?e.clientY:e.Y) - o.my; o.div.style.left = Math.round(o.x + diffx) > 0 ? Math.round(o.x + diffx) + 'px' : '0px'; o.div.style.top = Math.round(o.y + diffy) > 0 ? Math.round(o.y + diffy) + 'px' : '0px'; }; this.stopDrag = function(e) { var b = document.getElementsByTagName('body')[0]; removeClass(b, getCssClassNameSpace(o) + '-drag-active'); removeEvent(document,'mousemove',o.trackDrag, false); removeEvent(document,'mouseup',o.stopDrag, false); o.div.style.zIndex = 9999; }; this.onmousedown = function(e) { e = e || document.parentWindow.event; var el = e.target != null ? e.target : e.srcElement, origEl = el, hideDP = true, reg = new RegExp('^' + getCssClassNameSpace(o) + '-(but-)?' + o.id + '$'); o.mouseDownElem = null; // Are we within the wrapper div or the button while(el) { if(el.id && el.id.length && el.id.search(reg) != -1) { hideDP = false; break; }; try { el = el.parentNode; } catch(err) { break; }; }; // If not, then ... if(hideDP) { hideAll(); return true; }; if((o.div.className + origEl.className).search(getCssClassNameSpace(o) + '-disabled') != -1) { return true; }; // We check the mousedown events on the buttons if(origEl.id.search(new RegExp('^' + o.id + '(-prev-year-but|-prev-month-but|-next-month-but|-next-year-but|-prev-month-but-inter|-next-month-but-inter)$')) != -1) { o.mouseDownElem = origEl; addEvent(document, 'mouseup', o.clearTimer); addEvent(origEl, 'mouseout', o.clearTimer); var incs = { '-prev-year-but':[0,-1,0], '-prev-month-but':[0,0,-1], '-next-year-but':[0,1,0], '-next-month-but':[0,0,1] }, check = origEl.id.replace(o.id, '').replace('-inter',''), dateYYYYMM = Number(o.date.getFullYear() + pad(o.date.getMonth()+1)); o.timerInc = 800; o.timerSet = true; o.dayInc = incs[check][0]; o.yearInc = incs[check][1]; o.monthInc = incs[check][2]; o.accellerator = 1; if(!(o.currentYYYYMM == dateYYYYMM)) { if((o.currentYYYYMM < dateYYYYMM && (o.yearInc == -1 || o.monthInc == -1)) || (o.currentYYYYMM > dateYYYYMM && (o.yearInc == 1 || o.monthInc == 1))) { o.delayedUpdate = false; o.timerInc = 1200; } else { o.delayedUpdate = true; }; }; o.updateTable(); return stopEvent(e); } else if(el.className.search('drag-enabled') != -1) { o.mx = e.pageX ? e.pageX : e.clientX ? e.clientX : e.x; o.my = e.pageY ? e.pageY : e.clientY ? e.clientY : e.Y; o.x = parseInt(o.div.style.left, 10); o.y = parseInt(o.div.style.top, 10); addEvent(document,'mousemove',o.trackDrag, false); addEvent(document,'mouseup',o.stopDrag, false); addClass(document.getElementsByTagName('body')[0], getCssClassNameSpace(o) + '-drag-active'); o.div.style.zIndex = 10000; return stopEvent(e); }; return true; }; this.onclick = function(e) { if((o.opacity != o.opacityTo) || o.disabled) { return stopEvent(e); }; e = e || document.parentWindow.event; var el = e.target != null ? e.target : e.srcElement; while(el.parentNode) { // Are we within a valid i.e. clickable TD node if(el.tagName && el.tagName.toLowerCase() == 'td') { if(el.className.search(/cd-([0-9]{8})/) == -1 || el.className.search(noSelectionRegExp) != -1) { return stopEvent(e); }; var cellDate = el.className.match(/cd-([0-9]{8})/)[1]; o.date = new Date(cellDate.substr(0,4),cellDate.substr(4,2)-1,cellDate.substr(6,2), 5, 0, 0); o.dateSet = new Date(o.date); o.noFocus = true; o.callback('dateset', { 'id':o.id, 'date':o.dateSet, 'dd':o.dateSet.getDate(), 'mm':o.dateSet.getMonth() + 1, 'yyyy':o.dateSet.getFullYear() }); o.returnFormattedDate(); o.hide(); o.stopTimer(); break; } else if(el.id && el.id == o.id + '-today-but') { o.date = new Date(); o.updateTable(); o.stopTimer(); break; } try { el = el.parentNode; } catch(err) { break; }; }; return stopEvent(e); }; this.show = function(autoFocus) { if(this.staticPos) { return; }; var elem, elemID; for(elemID in this.formElements) { elem = document.getElementById(this.id); if(!elem || (elem && elem.disabled)) { return; }; }; this.noFocus = true; // If the datepicker doesn't exist in the dom if(!this.created || !document.getElementById(getCssClassNameSpace(o) + '-' + this.id)) { this.created = false; this.fullCreate = false; this.create(); this.fullCreate = true; } else { this.setDateFromInput(); this.reposition(); }; this.noFocus = !!!autoFocus; if(this.noFocus) { this.clickActivated = true; this.showCursor = false; addEvent(document, 'mousedown', this.onmousedown); if(mouseWheel) { if (window.addEventListener && !window.devicePixelRatio) { window.addEventListener('DOMMouseScroll', this.onmousewheel, false); } else { addEvent(document, 'mousewheel', this.onmousewheel); addEvent(window, 'mousewheel', this.onmousewheel); }; }; } else { this.clickActivated = false; this.showCursor = true; }; this.opacityTo = 100; this.div.style.display = 'block'; this.setNewFocus(); this.fade(); var butt = document.getElementById(getCssClassNameSpace(this) + '-but-' + this.id); if(butt) { addClass(butt, getCssClassNameSpace(o) + '-button-active'); }; }; this.hide = function() { if(!this.visible || !this.created || !document.getElementById(getCssClassNameSpace(o) + '-' + this.id)) { return; }; this.kbEvent = false; removeClass(o.div, getCssClassNameSpace(o) + '-focus'); this.stopTimer(); this.removeOnFocusEvents(); this.clickActivated = false; this.noFocus = true; this.showCursor = false; this.setNewFocus(); if(this.staticPos) { return; }; if(this.statusBar) { this.updateStatus(getTitleTranslation(9)); }; var butt = document.getElementById(getCssClassNameSpace(o) + '-but-' + this.id); if(butt) { removeClass(butt, getCssClassNameSpace(o) + '-button-active'); }; removeEvent(document, 'mousedown', this.onmousedown); if(mouseWheel) { if (window.addEventListener && !window.devicePixelRatio) { try { window.removeEventListener('DOMMouseScroll', this.onmousewheel, false); } catch(err) {}; } else { removeEvent(document, 'mousewheel', this.onmousewheel); removeEvent(window, 'mousewheel', this.onmousewheel); }; }; this.opacityTo = 0; this.fade(); this.callback('hideControl', this.createCbArgObj()); }; this.onblur = function(e) { o.removeCursorHighlight(); o.hide(); }; // The current cursor cell gains focus this.onfocus = function(e) { o.noFocus = false; addClass(o.div, getCssClassNameSpace(o) + '-focus'); if(o.statusBar) { o.updateStatus(printFormattedDate(o.date, o.statusFormat, true)); }; o.showCursor = true; o.addCursorHighlight(); o.addOnFocusEvents(); }; this.onmousewheel = function(e) { e = e || document.parentWindow.event; var delta = 0; if (e.wheelDelta) { delta = e.wheelDelta/120; if (isOpera && window.opera.version() < 9.2) { delta = -delta; }; } else if(e.detail) { delta = -e.detail/3; }; var n = o.date.getDate(), d = new Date(o.date), inc = delta > 0 ? 1 : -1; d.setDate(2); d.setMonth(d.getMonth() + inc * 1); d.setDate(Math.min(n, daysInMonth(d.getMonth(),d.getFullYear()))); if(o.outOfRange(d)) { return stopEvent(e); }; o.date = new Date(d); o.updateTable(); if(o.statusBar) { o.updateStatus(printFormattedDate(o.date, o.statusFormat, true)); }; return stopEvent(e); }; this.onkeydown = function (e) { o.stopTimer(); if(!o.visible) { return false; }; e = e || document.parentWindow.event; var kc = e.keyCode ? e.keyCode : e.charCode; if(kc == 13) { // RETURN/ENTER: close & select the date var td = document.getElementById(getCssClassNameSpace(o) + '-hover-' + o.id); if(!td || td.className.search(/cd-([0-9]{8})/) == -1 || td.className.search(/out-of-range|day-disabled/) != -1) { return stopEvent(e); }; o.dateSet = new Date(o.date); o.callback('dateset', o.createCbArgObj()); o.returnFormattedDate(); o.hide(); return stopEvent(e); } else if(kc == 27) { // ESC: close, no date selection, refocus on popup button if(!o.staticPos) { o.hide(); var butt = document.getElementById(getCssClassNameSpace(o) + '-but-' + o.id); if(butt) { setTimeout(function(){try{butt.focus()}catch(err){}},0); }; return stopEvent(e); }; return true; } else if(kc == 32 || kc == 0) { // SPACE: goto todays date o.date = new Date(); o.updateTable(); return stopEvent(e); } else if(kc == 9) { // TAB: pass focus - non popup datepickers only if(!o.staticPos) { return stopEvent(e); }; return true; }; // A number key has been pressed so change the first day of the week if((kc > 49 && kc < 56) || (kc > 97 && kc < 104)) { if(kc > 96) { kc -= (96-48); }; kc -= 49; o.firstDayOfWeek = (o.firstDayOfWeek + kc) % 7; o.updateTableHeaders(); return stopEvent(e); }; // If outside any other tested keycodes then let the keystroke pass if(kc < 33 || kc > 40) { return true; }; var d = new Date(o.date), cursorYYYYMM = o.date.getFullYear() + pad(o.date.getMonth()+1), tmp; // HOME: Set date to first day of current month if(kc == 36) { d.setDate(1); // END: Set date to last day of current month } else if(kc == 35) { d.setDate(daysInMonth(d.getMonth(),d.getFullYear())); // PAGE UP & DOWN } else if ( kc == 33 || kc == 34) { var inc = (kc == 34) ? 1 : -1; // CTRL + PAGE UP/DOWN: Moves to the same date in the previous/next year if(e.ctrlKey) { d.setFullYear(d.getFullYear() + inc * 1); // PAGE UP/DOWN: Moves to the same date in the previous/next month } else { var n = o.date.getDate(); d.setDate(2); d.setMonth(d.getMonth() + inc * 1); d.setDate(Math.min(n, daysInMonth(d.getMonth(),d.getFullYear()))); }; // LEFT ARROW } else if ( kc == 37 ) { d = new Date(o.date.getFullYear(), o.date.getMonth(), o.date.getDate() - 1, 5, 0, 0); // RIGHT ARROW } else if ( kc == 39 || kc == 34) { d = new Date(o.date.getFullYear(), o.date.getMonth(), o.date.getDate() + 1, 5, 0, 0); // UP ARROW } else if ( kc == 38 ) { d = new Date(o.date.getFullYear(), o.date.getMonth(), o.date.getDate() - 7, 5, 0, 0); // DOWN ARROW } else if ( kc == 40 ) { d = new Date(o.date.getFullYear(), o.date.getMonth(), o.date.getDate() + 7, 5, 0, 0); }; // If the new date is out of range then disallow action if(o.outOfRange(d)) { return stopEvent(e); }; // Otherwise set the new cursor date o.date = d; // Update the status bar if needs be if(o.statusBar) { o.updateStatus(o.getBespokeTitle(o.date.getFullYear(),o.date.getMonth() + 1,o.date.getDate()) || printFormattedDate(o.date, o.statusFormat, true)); }; // YYYYMMDD format String of the current cursor date var t = String(o.date.getFullYear()) + pad(o.date.getMonth()+1) + pad(o.date.getDate()); // If we need to redraw the UI completely if(e.ctrlKey || (kc == 33 || kc == 34) || t < o.firstDateShown || t > o.lastDateShown) { o.updateTable(); // Just highlight current cell } else { // Do we need to disable the today button for this date if(!o.noToday) { o.disableTodayButton(); }; // Remove focus from the previous cell o.removeOldFocus(); // Show/hide the month & year buttons o.showHideButtons(o.date); // Locate this TD for(var i = 0, td; td = o.tds[i]; i++) { if(td.className.search('cd-' + t) == -1) { continue; }; td.id = getCssClassNameSpace(o) + '-hover-' + o.id; o.setNewFocus(); break; }; }; return stopEvent(e); }; this.onmouseout = function(e) { e = e || document.parentWindow.event; var p = e.toElement || e.relatedTarget; while(p && p != this) { try { p = p.parentNode; } catch(e) { p = this; }; }; if(p == this) { return false; }; if(o.clickActivated || (o.staticPos && !o.kbEventsAdded)) { o.showCursor = false; o.removeCursorHighlight(); }; if(o.currentTR) { o.currentTR.className = ''; o.currentTR = null; }; if(o.statusBar) { o.updateStatus(o.dateSet ? o.getBespokeTitle(o.dateSet.getFullYear(),o.dateSet.getMonth() + 1,o.dateSet.getDate()) || printFormattedDate(o.dateSet, o.statusFormat, true) : getTitleTranslation(9)); }; }; this.onmouseover = function(e) { e = e || document.parentWindow.event; var el = e.target != null ? e.target : e.srcElement; while(el.nodeType != 1) { el = el.parentNode; }; if(!el || ! el.tagName) { return; }; o.noFocus = true; var statusText = getTitleTranslation(9); if(o.clickActivated || (o.staticPos && !o.kbEventsAdded)) { o.showCursor = false; }; switch (el.tagName.toLowerCase()) { case 'td': if(el.className.search(/unused|out-of-range/) != -1) { statusText = getTitleTranslation(9); } if(el.className.search(/cd-([0-9]{8})/) != -1) { o.showCursor = true; o.stopTimer(); var cellDate = el.className.match(/cd-([0-9]{8})/)[1]; o.removeOldFocus(); el.id = getCssClassNameSpace(o) + '-hover-' + o.id; o.setNewFocus(); o.date = new Date(+cellDate.substr(0,4),+cellDate.substr(4,2)-1,+cellDate.substr(6,2), 5, 0, 0); if(!o.noToday) { o.disableTodayButton(); }; statusText = o.getBespokeTitle(+cellDate.substr(0,4),+cellDate.substr(4,2),+cellDate.substr(6,2)) || printFormattedDate(o.date, o.statusFormat, true); }; break; case 'th': if(!o.statusBar) { break; }; if(el.className.search(/drag-enabled/) != -1) { statusText = getTitleTranslation(10); } else if(el.className.search(/week-header/) != -1) { var txt = el.firstChild ? el.firstChild.nodeValue : ''; statusText = txt.search(/^(\d+)$/) != -1 ? getTitleTranslation(7, [txt, txt < 3 && o.date.getMonth() == 11 ? getWeeksInYear(o.date.getFullYear()) + 1 : getWeeksInYear(o.date.getFullYear())]) : getTitleTranslation(9); }; break; case 'span': if(!o.statusBar) { break; }; if(el.className.search(/day-([0-6])/) != -1) { var day = el.className.match(/day-([0-6])/)[1]; statusText = getTitleTranslation(11, [getDayTranslation(day, false)]); } else if(el.className.search(/(drag-enabled|today-but|prev-(year|month)|next-(year|month))/) != -1 && el.className.search(/disabled/) == -1) { statusText = getTitleTranslation({'drag-enabled':10,'prev-year':2,'prev-month':0,'next-year':3,'next-month':1,'today-but':12}[el.className.match(/(drag-enabled|today-but|prev-(year|month)|next-(year|month))/)[0]]); }; break; default: statusText = ''; }; while(el.parentNode) { el = el.parentNode; if(el.nodeType == 1 && el.tagName.toLowerCase() == 'tr') { if(o.currentTR) { if(el == o.currentTR) { break; }; o.currentTR.className = ''; }; el.className = 'dp-row-highlight'; o.currentTR = el; break; }; }; if(o.statusBar && statusText) { o.updateStatus(statusText); }; if(!o.showCursor) { o.removeCursorHighlight(); }; }; this.clearTimer = function() { o.stopTimer(); o.timerInc = 800; o.yearInc = 0; o.monthInc = 0; o.dayInc = 0; removeEvent(document, 'mouseup', o.clearTimer); if(o.mouseDownElem != null) { removeEvent(o.mouseDownElem, 'mouseout', o.clearTimer); }; o.mouseDownElem = null; }; var o = this; this.setDateFromInput(); if(this.staticPos) { this.create(); } else { this.createButton(); }; (function() { var elemID, elem, elemCnt = 0; for(elemID in o.formElements) { elem = document.getElementById(elemID); if(elem && elem.tagName && elem.tagName.search(/select|input/i) != -1) { addEvent(elem, 'change', o.changeHandler); if(elemCnt == 0 && elem.form) { addEvent(elem.form, 'reset', o.reset); }; elemCnt++; }; if(!elem || elem.disabled == true) { o.disableDatePicker(); }; }; })(); // We have fully created the datepicker... this.fullCreate = true; }; datePicker.prototype.addButtonEvents = function(but) { function buttonEvent (e) { e = e || window.event; var inpId = this.id.replace(getCssClassNameSpace(o) + '-but-',''), dpVisible = isVisible(inpId), autoFocus = false, kbEvent = datePickers[inpId].kbEvent; if(kbEvent) { datePickers[inpId].kbEvent = false; return; }; if(e.type == 'keydown') { var kc = e.keyCode != null ? e.keyCode : e.charCode; if(kc != 13) return true; datePickers[inpId].kbEvent = true; if(dpVisible) { removeClass(this, getCssClassNameSpace(o) + '-button-active'); hideAll(); return stopEvent(e); }; autoFocus = true; } else { datePickers[inpId].kbEvent = false; }; if(!dpVisible) { addClass(this, getCssClassNameSpace(o) + '-button-active'); hideAll(inpId); showDatePicker(inpId, autoFocus); } else { removeClass(this, getCssClassNameSpace(o) + '-button-active'); hideAll(); }; return stopEvent(e); }; but.onclick = buttonEvent; but.onkeydown = buttonEvent; if(!buttonTabIndex) { setTabIndex(but, -1); } else { setTabIndex(but, this.bespokeTabIndex); }; }; datePicker.prototype.createButton = function() { if(this.staticPos || document.getElementById(getCssClassNameSpace(this) + '-but-' + this.id) || !this.actionButton ) { return; }; var inp = document.getElementById(this.id), span = document.createElement('span'), but = document.createElement('a'); but.href = '#' + this.id; but.className = getCssClassNameSpace(o) + '-control'; but.title = getTitleTranslation(5); but.id = getCssClassNameSpace(o) + '-but-' + this.id; span.appendChild(document.createTextNode(nbsp)); but.appendChild(span); span = document.createElement('span'); span.className = getCssClassNameSpace(o) + '-screen-reader'; span.appendChild(document.createTextNode(but.title)); but.appendChild(span); // Set the ARIA role to be 'button' setARIARole(but, 'button'); // Set a 'haspopup' ARIA property setARIAProperty(but, 'haspopup', true); if(this.positioned && document.getElementById(this.positioned)) { document.getElementById(this.positioned).appendChild(but); } else { inp.parentNode.insertBefore(but, inp.nextSibling); }; this.addButtonEvents(but); but = null; this.callback('dombuttoncreate', {id:this.id}); }; datePicker.prototype.setBespokeTitles = function(titles) { this.bespokeTitles = {}; this.addBespokeTitles(titles); }; datePicker.prototype.addBespokeTitles = function(titles) { for(var dt in titles) { if(titles.hasOwnProperty(dt)) { this.bespokeTitles[dt] = titles[dt]; }; }; }; datePicker.prototype.getBespokeTitle = function(y,m,d) { var dt, dtFull, yyyymmdd = y + String(pad(m)) + pad(d); // Try the datepickers bespoke titles for(dt in this.bespokeTitles) { if(this.bespokeTitles.hasOwnProperty(dt)) { dtFull = String(dt).replace(/^(\*\*\*\*)/, y).replace(/^(\d\d\d\d)(\*\*)/, '$1'+ pad(m)); if(dtFull == yyyymmdd) { return this.bespokeTitles[dt]; }; }; }; // Try the generic bespoke titles for(dt in bespokeTitles) { if(bespokeTitles.hasOwnProperty(dt)) { dtFull = String(dt).replace(/^(\*\*\*\*)/, y).replace(/^(\d\d\d\d)(\*\*)/, '$1'+ pad(m)); if(dtFull == yyyymmdd) { return bespokeTitles[dt]; }; }; }; return false; }; datePicker.prototype.returnSelectedDate = function() { return this.dateSet; }; datePicker.prototype.setRangeLow = function(range) { if(String(range).search(rangeRegExp) == -1) { if(debug) { throw 'Invalid value passed to setRangeLow method: ' + range; }; return false; }; this.rangeLow = range; if(!this.inUpdate) { this.setDateFromInput(); }; }; datePicker.prototype.setRangeHigh = function(range) { if(String(range).search(rangeRegExp) == -1) { if(debug) { throw 'Invalid value passed to setRangeHigh method: ' + range; }; return false; }; this.rangeHigh = range; if(!this.inUpdate) { this.setDateFromInput(); }; }; datePicker.prototype.setDisabledDays = function(dayArray) { if(!dayArray.length || dayArray.join('').search(/^([0|1]{7})$/) == -1) { if(debug) { throw 'Invalid values located when attempting to call setDisabledDays'; }; return false; }; this.disabledDays = dayArray; if(!this.inUpdate) { this.setDateFromInput(); }; }; datePicker.prototype.setDisabledDates = function(dateObj) { this.filterDateList(dateObj, true); }; datePicker.prototype.setEnabledDates = function(dateObj) { this.filterDateList(dateObj, false); }; datePicker.prototype.addDisabledDates = function(dateObj) { this.addDatesToList(dateObj, true); }; datePicker.prototype.addEnabledDates = function(dateObj) { this.addDatesToList(dateObj, false); }; datePicker.prototype.filterDateList = function(dateObj, type) { var tmpDates = []; for(var i = 0; i < this.dateList.length; i++) { if(this.dateList[i].type != type) { tmpDates.push(this.dateList[i]); }; }; this.dateList = tmpDates.concat(); this.addDatesToList(dateObj, type); }; datePicker.prototype.addDatesToList = function(dateObj, areDisabled) { var startD; for(startD in dateObj) { if(String(startD).search(wcDateRegExp) != -1 && (dateObj[startD] == 1 || String(dateObj[startD]).search(wcDateRegExp) != -1)) { if(dateObj[startD] != 1 && Number(String(startD).replace(/^\*\*\*\*/, 2010).replace(/^(\d\d\d\d)(\*\*)/, '$1'+'22')) > Number(String(dateObj[startD]).replace(/^\*\*\*\*/, 2010).replace(/^(\d\d\d\d)(\*\*)/, '$1'+'22'))) { continue; }; this.dateList.push({ type:!!(areDisabled), rLow:startD, rHigh:dateObj[startD] }); }; }; if(!this.inUpdate) { this.setDateFromInput(); }; }; datePicker.prototype.setSelectedDate = function(yyyymmdd) { if(String(yyyymmdd).search(wcDateRegExp) == -1) { return false; }; var match = yyyymmdd.match(rangeRegExp), dt = new Date(+match[2],+match[3]-1,+match[4], 5, 0, 0); if(!dt || isNaN(dt) || !this.canDateBeSelected(dt)) { return false; }; this.dateSet = new Date(dt); this.date = new Date(dt); if(!this.inUpdate) { this.updateTable(); }; this.callback('dateset', this.createCbArgObj()); this.returnFormattedDate(); }; datePicker.prototype.checkSelectedDate = function() { if(this.dateSet && !this.canDateBeSelected(this.dateSet)) { this.dateSet = null; }; if(!this.inUpdate) { this.updateTable(); }; }; datePicker.prototype.addOnFocusEvents = function() { if(this.kbEventsAdded || this.noFocus) { return; }; addEvent(document, 'keydown', this.onkeydown); addEvent(document, 'mousedown', this.onmousedown); this.noFocus = false; this.kbEventsAdded = true; }; datePicker.prototype.removeOnFocusEvents = function() { if(!this.kbEventsAdded) { return; }; removeEvent(document, 'keypress', this.onkeydown); removeEvent(document, 'keydown', this.onkeydown); removeEvent(document, 'mousedown', this.onmousedown); this.kbEventsAdded = false; }; datePicker.prototype.stopTimer = function() { this.timerSet = false; window.clearTimeout(this.timer); }; datePicker.prototype.setOpacity = function(op) { this.div.style.opacity = op/100; this.opacity = op; }; datePicker.prototype.truePosition = function(element) { var pos = this.cumulativeOffset(element); if(isOpera) { return pos; }; var iebody = (document.compatMode && document.compatMode != 'BackCompat')? document.documentElement : document.body, dsocleft = document.all ? iebody.scrollLeft : window.pageXOffset, dsoctop = document.all ? iebody.scrollTop : window.pageYOffset, posReal = this.realOffset(element); return [pos[0] - posReal[0] + dsocleft, pos[1] - posReal[1] + dsoctop]; }; datePicker.prototype.realOffset = function(element) { var t = 0, l = 0; do { t += element.scrollTop || 0; l += element.scrollLeft || 0; element = element.parentNode; } while(element); return [l, t]; }; datePicker.prototype.cumulativeOffset = function(element) { var t = 0, l = 0; do { t += element.offsetTop || 0; l += element.offsetLeft || 0; element = element.offsetParent; } while(element); return [l, t]; }; datePicker.prototype.outOfRange = function(tmpDate) { if(!this.rangeLow && !this.rangeHigh) { return false; }; var level = false; if(!tmpDate) { level = true; tmpDate = this.date; }; var d = pad(tmpDate.getDate()), m = pad(tmpDate.getMonth() + 1), y = tmpDate.getFullYear(), dt = String(y)+String(m)+String(d); if(this.rangeLow && +dt < +this.rangeLow) { if(!level) { return true; }; this.date = new Date(this.rangeLow.substr(0,4), this.rangeLow.substr(4,2)-1, this.rangeLow.substr(6,2), 5, 0, 0); return false; }; if(this.rangeHigh && +dt > +this.rangeHigh) { if(!level) { return true; }; this.date = new Date(this.rangeHigh.substr(0,4), this.rangeHigh.substr(4,2)-1, this.rangeHigh.substr(6,2), 5, 0, 0); }; return false; }; datePicker.prototype.canDateBeSelected = function(tmpDate) { if(!tmpDate || isNaN(tmpDate)) { return false; }; var d = pad(tmpDate.getDate()), m = pad(tmpDate.getMonth() + 1), y = tmpDate.getFullYear(), dt = y + '' + m + '' + d, dd = this.getDateExceptions(y, m), wd = tmpDate.getDay() == 0 ? 7 : tmpDate.getDay(); // If date out of range if((this.rangeLow && +dt < +this.rangeLow) || (this.rangeHigh && +dt > +this.rangeHigh) || // or the date has been explicitly disabled ((dt in dd) && dd[dt] == 1) || // or the date lies on a disabled weekday and it hasn't been explicitly enabled (this.disabledDays[wd-1] && (!(dt in dd) || ((dt in dd) && dd[dt] == 1)))) { return false; }; return true; }; datePicker.prototype.updateStatus = function(msg) { removeChildNodes(this.statusBar); // All this arseing about just for sups in the footer... nice typography and all that... if(msg && this.statusFormat.search(/%S/) != -1 && msg.search(/([0-9]{1,2})(st|nd|rd|th)/) != -1) { msg = cbSplit(msg.replace(/([0-9]{1,2})(st|nd|rd|th)/, '$1$2'), /|<\/sup>/); var dc = document.createDocumentFragment(); for(var i = 0, nd; nd = msg[i]; i++) { if(/^(st|nd|rd|th)$/.test(nd)) { var sup = document.createElement('sup'); sup.appendChild(document.createTextNode(nd)); dc.appendChild(sup); } else { dc.appendChild(document.createTextNode(nd)); }; }; this.statusBar.appendChild(dc); } else { this.statusBar.appendChild(document.createTextNode(msg ? msg : getTitleTranslation(9))); }; }; /* Still needs work... */ datePicker.prototype.setDateFromInput = function() { var origDateSet = this.dateSet, m = false, but = this.staticPos ? false : document.getElementById(getCssClassNameSpace(this) + '-but-' + this.id), e = localeImport.imported ? [].concat(localeDefaults.fullMonths).concat(localeDefaults.monthAbbrs) : [], l = localeImport.imported ? [].concat(localeImport.fullMonths).concat(localeImport.monthAbbrs) : [], eosRegExp = /(3[01]|[12][0-9]|0?[1-9])(st|nd|rd|th)/i, elemCnt = 0, dt = false, allFormats, i, elemID, elem, elemFmt, d, y, elemVal, dp, mp, yp; // Reset the internal dateSet variable this.dateSet = null; // Try and get a year, month and day from the form element values for(elemID in this.formElements) { elem = document.getElementById(elemID); if(!elem) { return false; }; elemCnt++; elemVal = String(elem.value); if(!elemVal) { continue; }; elemFmt = this.formElements[elemID]; allFormats = [elemFmt]; dt = false; dp = elemFmt.search(dPartsRegExp) != -1; mp = elemFmt.search(mPartsRegExp) != -1; yp = elemFmt.search(yPartsRegExp) != -1; // Try to assign some default date formats to throw at // the (simple) regExp parser for single date parts. if(!(dp && mp && yp)) { if(yp && !(mp || dp)) { allFormats = allFormats.concat([ '%Y', '%y' ]); } else if(mp && !(yp || dp)) { allFormats = allFormats.concat([ '%M', '%F', '%m', '%n' ]); } else if(dp && !(yp || mp)) { allFormats = allFormats.concat([ '%d%', '%j' ]); }; }; for(i = 0; i < allFormats.length; i++) { dt = parseDateString(elemVal, allFormats[i]); if(dt) { if(!d && dp && dt.d) { d = dt.d; }; if(m === false && mp && dt.m) { m = dt.m; }; if(!y && yp && dt.y) { y = dt.y; }; }; if(((dp && d) || !dp) && ((mp && !m === false) || !mp) && ((yp && y) || !yp)) { break; }; }; }; // Last ditch attempt at date parsing for single inputs that // represent the day, month and year parts of the date format. // I'm - thankfully - passing this responsibility off to the browser. // Date parsing in js sucks but the browsers' in-built Date.parse method // will inevitably be better than anything I would hazard to write. // Date.parse is implementation dependant though so don't expect // consistency, rhyme or reason. if(dateParseFallback && (!d || m === false || !y) && dp && mp && yp && elemCnt == 1 && elemVal) { // If locale imported then replace month names with English // counterparts if necessary if(localeImport.imported) { for(i = 0; i < l.length; i++) { elemVal = elemVal.replace(new RegExp(l[i], 'i'), e[i]); }; }; // Remove English ordinal suffix if(elemVal.search(eosRegExp) != -1) { elemVal = elemVal.replace(eosRegExp, elemVal.match(eosRegExp)[1]); }; // Older browsers have problems with dashes so we replace with // slashes which appear to be supported by all and then try to use // the in-built Date Object to parse a valid date dt = new Date(elemVal.replace(new RegExp('\-', 'g'), '/')); if(dt && !isNaN(dt)) { d = dt.getDate(); m = dt.getMonth() + 1; y = dt.getFullYear(); }; }; dt = false; if(d && !(m === false) && y) { if(+d > daysInMonth(+m - 1, +y)) { d = daysInMonth(+m - 1, +y); dt = false; } else { dt = new Date(+y, +m - 1, +d, 5, 0, 0); }; }; if(but) { removeClass(but, getCssClassNameSpace(o) + '-dateval'); }; if(!dt || isNaN(dt)) { var newDate = new Date(y || new Date().getFullYear(), !(m === false) ? m - 1 : new Date().getMonth(), 1, 5, 0, 0); this.date = this.cursorDate ? new Date(+this.cursorDate.substr(0,4), +this.cursorDate.substr(4,2) - 1, +this.cursorDate.substr(6,2), 5, 0, 0) : new Date(newDate.getFullYear(), newDate.getMonth(), Math.min(+d || new Date().getDate(), daysInMonth(newDate.getMonth(), newDate.getFullYear())), 5, 0, 0); this.outOfRange(); if(this.fullCreate) { this.updateTable(); }; return; }; dt.setHours(5); this.date = new Date(dt); this.outOfRange(); if(dt.getTime() == this.date.getTime() && this.canDateBeSelected(this.date)) { this.dateSet = new Date(this.date); if(but) { addClass(but, getCssClassNameSpace(o) + '-dateval'); }; this.returnFormattedDate(true); }; if(this.fullCreate) { this.updateTable(); }; }; datePicker.prototype.setSelectIndex = function(elem, indx) { for(var opt = elem.options.length-1; opt >= 0; opt--) { if(elem.options[opt].value == indx) { elem.selectedIndex = opt; return; }; }; }; datePicker.prototype.returnFormattedDate = function(noFocus) { var but = this.staticPos ? false : document.getElementById(getCssClassNameSpace(this) + '-but-' + this.id); if(!this.dateSet) { if(but) { removeClass(but, getCssClassNameSpace(o) + '-dateval'); }; return; }; var d = pad(this.dateSet.getDate()), m = pad(this.dateSet.getMonth() + 1), y = this.dateSet.getFullYear(), el = false, elemID, elem, elemFmt, fmtDate; noFocus = !!noFocus; for(elemID in this.formElements) { elem = document.getElementById(elemID); if(!elem) { return; }; if(!el) { el = elem; }; elemFmt = this.formElements[elemID]; fmtDate = printFormattedDate(this.dateSet, elemFmt, returnLocaleDate); if(elem.tagName.toLowerCase() == 'input') { elem.value = fmtDate; } else { this.setSelectIndex(elem, fmtDate); }; }; if(this.staticPos) { this.noFocus = true; this.updateTable(); this.noFocus = false; } else if(but) { addClass(but, getCssClassNameSpace(o) + '-dateval'); }; if(this.fullCreate) { if(el.type && el.type != 'hidden' && !noFocus) { try{ el.focus(); } catch(err) {}; }; }; if(!noFocus) { this.callback('datereturned', this.createCbArgObj()); }; }; datePicker.prototype.disableDatePicker = function() { if(this.disabled) { return; }; if(this.staticPos) { this.removeOnFocusEvents(); this.removeOldFocus(); this.noFocus = true; addClass(this.div, getCssClassNameSpace(this) + '-disabled'); this.table.onmouseover = this.table.onclick = this.table.onmouseout = this.table.onmousedown = null; removeEvent(document, 'mousedown', this.onmousedown); removeEvent(document, 'mouseup', this.clearTimer); } else { if(this.visible) { this.hide(); }; var but = document.getElementById(getCssClassNameSpace(this) + '-but-' + this.id); if(but) { addClass(but, getCssClassNameSpace(o) + '-control-disabled'); // Set a 'disabled' ARIA state setARIAProperty(but, 'disabled', true); but.onkeydown = but.onclick = function() { return false; }; setTabIndex(but, -1); but.title = ''; } }; clearTimeout(this.timer); this.disabled = true; }; datePicker.prototype.enableDatePicker = function() { if(!this.disabled) { return; }; if(this.staticPos) { this.removeOldFocus(); if(this.dateSet != null) { this.date = this.dateSet; }; this.noFocus = true; this.updateTable(); removeClass(this.div, getCssClassNameSpace(o) + '-disabled'); this.disabled = false; this.table.onmouseover = this.onmouseover; this.table.onmouseout = this.onmouseout; this.table.onclick = this.onclick; this.table.onmousedown = this.onmousedown; } else { var but = document.getElementById(getCssClassNameSpace(o) + '-but-' + this.id); if(but) { removeClass(but, getCssClassNameSpace(o) + '-control-disabled'); // Reset the 'disabled' ARIA state setARIAProperty(but, 'disabled', false); this.addButtonEvents(but); but.title = getTitleTranslation(5); }; }; this.disabled = false; }; datePicker.prototype.disableTodayButton = function() { var today = new Date(); removeClass(this.butToday, getCssClassNameSpace(this) + '-disabled'); if(this.outOfRange(today) || (this.date.getDate() == today.getDate() && this.date.getMonth() == today.getMonth() && this.date.getFullYear() == today.getFullYear()) ) { addClass(this.butToday, getCssClassNameSpace(this) + '-disabled'); }; }; datePicker.prototype.updateTableHeaders = function() { var colspanTotal = this.showWeeks ? 8 : 7, colOffset = this.showWeeks ? 1 : 0, d, but; for(var col = colOffset; col < colspanTotal; col++ ) { d = (this.firstDayOfWeek + (col - colOffset)) % 7; this.ths[col].title = getDayTranslation(d, false); if(col > colOffset) { but = this.ths[col].getElementsByTagName('span')[0]; removeChildNodes(but); but.appendChild(document.createTextNode(getDayTranslation(d, true))); but.title = this.ths[col].title; but = null; } else { removeChildNodes(this.ths[col]); this.ths[col].appendChild(document.createTextNode(getDayTranslation(d, true))); }; removeClass(this.ths[col], getCssClassNameSpace(this) + '-highlight'); if(this.highlightDays[d]) { addClass(this.ths[col], getCssClassNameSpace(this) + '-highlight'); }; }; if(this.created) { this.updateTable(); }; }; datePicker.prototype.callback = function(type, args) { if(!type || !(type in this.callbacks)) { return false; }; var ret = false, func; for(func = 0; func < this.callbacks[type].length; func++) { ret = this.callbacks[type][func](args || this.id); }; return ret; }; datePicker.prototype.showHideButtons = function(tmpDate) { if(!this.butPrevYear) { return; }; var tdm = tmpDate.getMonth(), tdy = tmpDate.getFullYear(); if(this.outOfRange(new Date((tdy - 1), tdm, daysInMonth(+tdm, tdy-1), 5, 0, 0))) { addClass(this.butPrevYear, getCssClassNameSpace(this) + '-disabled'); if(this.yearInc == -1) { this.stopTimer(); }; } else { removeClass(this.butPrevYear, getCssClassNameSpace(this) + '-disabled'); }; if(this.outOfRange(new Date(tdy, (+tdm - 1), daysInMonth(+tdm-1, tdy), 5, 0, 0))) { addClass(this.butPrevMonth, getCssClassNameSpace(this) + '-disabled'); if(this.monthInc == -1) { this.stopTimer(); }; } else { removeClass(this.butPrevMonth, getCssClassNameSpace(this) + '-disabled'); }; if(this.outOfRange(new Date((tdy + 1), +tdm, 1, 5, 0, 0))) { addClass(this.butNextYear, getCssClassNameSpace(this) + '-disabled'); if(this.yearInc == 1) { this.stopTimer(); }; } else { removeClass(this.butNextYear, getCssClassNameSpace(this) + '-disabled'); }; if(this.outOfRange(new Date(tdy, +tdm + 1, 1, 5, 0, 0))) { addClass(this.butNextMonth, getCssClassNameSpace(this) + '-disabled'); if(this.monthInc == 1) { this.stopTimer(); }; } else { removeClass(this.butNextMonth, getCssClassNameSpace(this) + '-disabled'); }; }; var localeDefaults = { fullMonths:['January','February','March','April','May','June','July','August','September','October','November','December'], monthAbbrs:['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'], fullDays: ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'], dayAbbrs: ['M','T','W','T','F','S','S'], titles: ['Previous month','Next month','Previous year','Next year', 'Today', 'Show Calendar', 'wk', 'Week [[%0%]] of [[%1%]]', 'Week', 'Select a date', 'Click \u0026 Drag to move', 'Display \u201C[[%0%]]\u201D first', 'Go to Today\u2019s date', 'Disabled date :'], rtl: false, firstDayOfWeek:0, imported: false }; var joinNodeLists = function() { if(!arguments.length) { return []; }; var nodeList = []; for (var i = 0; i < arguments.length; i++) { for (var j = 0, item; item = arguments[i][j]; j++) { nodeList[nodeList.length] = item; }; }; return nodeList; }; var cleanUp = function() { var dp, fe; for(dp in datePickers) { for(fe in datePickers[dp].formElements) { if(!document.getElementById(fe)) { datePickers[dp].destroy(); datePickers[dp] = null; delete datePickers[dp]; break; }; }; }; }; var hideAll = function(exception) { var dp; for(dp in datePickers) { if(!datePickers[dp].created || (exception && exception == datePickers[dp].id)) { continue; }; datePickers[dp].hide(); }; }; var hideDatePicker = function(inpID) { if(inpID in datePickers) { if(!datePickers[inpID].created || datePickers[inpID].staticPos) { return; }; datePickers[inpID].hide(); }; }; var showDatePicker = function(inpID, autoFocus) { if(!(inpID in datePickers)) { return false; }; datePickers[inpID].clickActivated = !!!autoFocus; datePickers[inpID].show(autoFocus); return true; }; var getCssClassNameSpace = function(options){ if(options.customCssClassName != null){ return options.customCssClassName; } else { return 'date-picker'; } }; var destroy = function(e) { e = e || window.event; // Don't remove datepickers if it's a pagehide/pagecache event (webkit et al) if(e.persisted) { return; }; var dp; for(dp in datePickers) { datePickers[dp].destroy(); datePickers[dp] = null; delete datePickers[dp]; }; datePickers = null; removeEvent(window, 'unload', datePicker.destroy); }; var destroySingleDatePicker = function(id) { if(id && (id in datePickers)) { datePickers[id].destroy(); datePickers[id] = null; delete datePickers[id]; }; }; var getTitleTranslation = function(num, replacements) { replacements = replacements || []; if(localeImport.titles.length > num) { var txt = localeImport.titles[num]; if(replacements && replacements.length) { for(var i = 0; i < replacements.length; i++) { txt = txt.replace('[[%' + i + '%]]', replacements[i]); }; }; return txt.replace(/[[%(\d)%]]/g,''); }; return ''; }; var getDayTranslation = function(day, abbreviation) { var titles = localeImport[abbreviation ? 'dayAbbrs' : 'fullDays']; return titles.length && titles.length > day ? titles[day] : ''; }; var getMonthTranslation = function(month, abbreviation) { var titles = localeImport[abbreviation ? 'monthAbbrs' : 'fullMonths']; return titles.length && titles.length > month ? titles[month] : ''; }; var daysInMonth = function(nMonth, nYear) { nMonth = (nMonth + 12) % 12; return (((0 == (nYear%4)) && ((0 != (nYear%100)) || (0 == (nYear%400)))) && nMonth == 1) ? 29: [31,28,31,30,31,30,31,31,30,31,30,31][nMonth]; }; var getWeeksInYear = function(Y) { if(Y in weeksInYearCache) { return weeksInYearCache[Y]; }; var X1 = new Date(Y, 0, 4), X2 = new Date(Y, 11, 28); X1.setDate(X1.getDate() - (6 + X1.getDay()) % 7); X2.setDate(X2.getDate() + (7 - X2.getDay()) % 7); weeksInYearCache[Y] = Math.round((X2 - X1) / 604800000); return weeksInYearCache[Y]; }; var getWeekNumber = function(y,m,d) { var d = new Date(y, m, d, 0, 0, 0), DoW = d.getDay(), ms; d.setDate(d.getDate() - (DoW + 6) % 7 + 3); ms = d.valueOf(); d.setMonth(0); d.setDate(4); return Math.round((ms - d.valueOf()) / (7 * 864e5)) + 1; }; var printFormattedDate = function(date, fmt, useImportedLocale) { if(!date || isNaN(date)) { return fmt; }; var d = date.getDate(), D = date.getDay(), m = date.getMonth(), y = date.getFullYear(), locale = useImportedLocale ? localeImport : localeDefaults, fmtParts = String(fmt).split(formatSplitRegExp), fmtParts = cbSplit(fmt, formatSplitRegExp), fmtNewParts = [], flags = { 'd':pad(d), 'D':locale.dayAbbrs[D == 0 ? 6 : D - 1], 'l':locale.fullDays[D == 0 ? 6 : D - 1], 'j':d, 'N':D == 0 ? 7 : D, 'w':D, 'W':getWeekNumber(y,m,d), 'M':locale.monthAbbrs[m], 'F':locale.fullMonths[m], 'm':pad(m + 1), 'n':m + 1, 't':daysInMonth(m, y), 'y':String(y).substr(2,2), 'Y':y, 'S':['th', 'st', 'nd', 'rd'][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10] }, len = fmtParts.length, currFlag, f; for(f = 0; f < len; f++) { currFlag = fmtParts[f]; fmtNewParts.push(currFlag in flags ? flags[currFlag] : currFlag); }; return fmtNewParts.join(''); }; var parseDateString = function(str, fmt) { var d = false, m = false, y = false, dp = fmt.search(dPartsRegExp) != -1 ? 1 : 0, mp = fmt.search(mPartsRegExp) != -1 ? 1 : 0, yp = fmt.search(yPartsRegExp) != -1 ? 1 : 0, now = new Date(), parts = cbSplit(fmt, formatSplitRegExp), str = '' + str, len = parts.length, pt, part, l; loopLabel: for(pt = 0; pt < len; pt++) { part = parts[pt]; if(part === '') { continue loopLabel; }; if(str.length == 0) { break; }; switch(part) { // Dividers - be easy on them all i.e. accept them all when parsing... case '/': case '.': case ' ': case '-': case ',': case ':': str = str.substr(1); break; // DAY case 'd': // Day of the month, 2 digits with leading zeros (01 - 31) or without leading zeros (1 - 31) if(str.search(/^(3[01]|[12][0-9]|0[1-9])/) != -1 || str.search(/^(3[01]|[12][0-9]|[1-9])/) != -1) { if(str.search(/^(3[01]|[12][0-9]|[1-9])/) != -1) { d = +str.match(/^(3[01]|[12][0-9]|[1-9])/)[0]; str = str.substr(str.match(/^(3[01]|[12][0-9]|[1-9])/)[0].length); }else { d = str.substr(0,2); str = str.substr(2); } break; } else { return false; }; case 'D': // A textual representation of a day, three letters (Mon - Sun) case 'l': // A full textual representation of the day of the week (Monday - Sunday) // Accept English & imported locales and both modifiers l = localeDefaults.fullDays.concat(localeDefaults.dayAbbrs); if(localeImport.imported) { l = l.concat(localeImport.fullDays).concat(localeImport.dayAbbrs); }; for(var i = 0; i < l.length; i++) { if(new RegExp('^' + l[i], 'i').test(str)) { str = str.substr(l[i].length); continue loopLabel; }; }; break; case 'N': // ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0) 1 (for Monday) through 7 (for Sunday) case 'w': // Numeric representation of the day of the week 0 (for Sunday) through 6 (for Saturday) if(str.search(part == 'N' ? /^([1-7])/ : /^([0-6])/) != -1) { str = str.substr(1); }; break; case 'S': // English ordinal suffix for the day of the month, 2 characters: st, nd, rd or th if(str.search(/^(st|nd|rd|th)/i) != -1) { str = str.substr(2); }; break; // WEEK case 'W': // ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0): 1 - 53 if(str.search(/^([1-9]|[1234[0-9]|5[0-3])/) != -1) { str = str.substr(str.match(/^([1-9]|[1234[0-9]|5[0-3])/)[0].length); }; break; // MONTH case 'M': // A short textual representation of a month, three letters case 'F': // A full textual representation of a month, such as January or March // Accept English & imported locales and both modifiers l = localeDefaults.fullMonths.concat(localeDefaults.monthAbbrs); if(localeImport.imported) { l = l.concat(localeImport.fullMonths).concat(localeImport.monthAbbrs); }; for(var i = 0; i < l.length; i++) { if(str.search(new RegExp('^' + l[i],'i')) != -1) { str = str.substr(l[i].length); m = ((i + 12) % 12) + 1; continue loopLabel; }; }; return false; case 'm': // Numeric representation of a month, with leading zeros or without leading zero l = /^(1[012]|0[1-9])/; var noZeroMonth = /^(1[012]|[1-9])/; if(str.search(l) != -1 || str.search(noZeroMonth) != -1) { if(str.search(noZeroMonth) != -1){ m = +str.match(noZeroMonth)[0]; str = str.substr(str.match(noZeroMonth)[0].length); } else { m = +str.substr(0, 2); str = str.substr(2); } break; } else { return false; }; case 't': // Number of days in the given month: 28 through 31 if(str.search(/2[89]|3[01]/) != -1) { str = str.substr(2); break; } else { return false; }; // YEAR case 'Y': // A full numeric representation of a year, 4 digits if(str.search(/^(\d{4})/) != -1) { y = str.substr(0,4); str = str.substr(4); break; } else { return false; }; case 'y': // A two digit representation of a year if(str.search(/^(0[0-9]|[1-9][0-9])/) != -1) { y = str.substr(0,2); y = +y < 50 ? '20' + String(y) : '19' + String(y); str = str.substr(2); break; } else { return false; }; default: str = str.substr(part.length); }; }; if((dp && d === false) || (mp && m === false) || (yp && y === false)) { return false; }; if(dp && mp && yp && +d > daysInMonth(+m - 1, +y)) { return false; }; return { 'd':dp ? +d : false, 'm':mp ? +m : false, 'y':yp ? +y : false }; }; var findLabelForElement = function(element) { var label; if(element.parentNode && element.parentNode.tagName.toLowerCase() == 'label') { label = element.parentNode; } else { var labelList = document.getElementsByTagName('label'); // loop through label array attempting to match each 'for' attribute to the id of the current element for(var lbl = 0; lbl < labelList.length; lbl++) { // Internet Explorer requires the htmlFor test if((labelList[lbl]['htmlFor'] && labelList[lbl]['htmlFor'] == element.id) || (labelList[lbl].getAttribute('for') == element.id)) { label = labelList[lbl]; break; }; }; }; if(label && !label.id && element.id) { label.id = element.id + '_label'; }; return label; }; var updateLanguage = function() { if(typeof(window.fdLocale) == 'object' ) { localeImport = { titles : fdLocale.titles, fullMonths : fdLocale.fullMonths, monthAbbrs : fdLocale.monthAbbrs, fullDays : fdLocale.fullDays, dayAbbrs : fdLocale.dayAbbrs, firstDayOfWeek : ('firstDayOfWeek' in fdLocale) ? fdLocale.firstDayOfWeek : 0, rtl : ('rtl' in fdLocale) ? !!(fdLocale.rtl) : false, imported : true }; } else if(!localeImport) { localeImport = localeDefaults; }; }; var loadLanguage = function() { updateLanguage(); var dp; for(dp in datePickers) { if(!datePickers[dp].created) { continue; }; datePickers[dp].updateTable(); }; }; var checkElem = function(elem) { return !(!elem || !elem.tagName || !((elem.tagName.toLowerCase() == 'input' && (elem.type == 'text' || elem.type == 'hidden' || elem.type == 'date')) || elem.tagName.toLowerCase() == 'select')); }; var addDatePicker = function(options) { updateLanguage(); if(!options.formElements) { if(debug) { throw 'No form elements stipulated within initialisation parameters'; }; return; }; options.id = (options.id && (options.id in options.formElements)) ? options.id : ''; options.enabledDates = false; options.disabledDates = false; var partsFound = {d:0,m:0,y:0}, defaultVals = {}, cursorDate = false, myMin = 0, myMax = 0, fmt, opts, dtPartStr, elemID, elem, dt, i; for(elemID in options.formElements) { elem = document.getElementById(elemID); if(!checkElem(elem)) { if(debug) { throw 'Element ' + elemID + ' is of the wrong type or does not exist within the DOM'; }; return false; }; if(!(options.formElements[elemID].match(formatTestRegExp))) { if(debug) { throw 'Element ' + elemID + ' has a date format that does not contain either a day (d|j), month (m|F|n) or year (y|Y) part: ' + options.formElements[elemID]; }; return false; }; if(!options.id) { options.id = elemID; }; defaultVals[elemID] = elem.tagName == 'select' ? elem.selectedIndex || 0 : elem.defaultValue; fmt = { 'value':options.formElements[elemID] }; fmt.d = fmt.value.search(dPartsRegExp) != -1; fmt.m = fmt.value.search(mPartsRegExp) != -1; fmt.y = fmt.value.search(yPartsRegExp) != -1; if(fmt.d) { partsFound.d++; }; if(fmt.m) { partsFound.m++; }; if(fmt.y) { partsFound.y++; }; if(elem.tagName.toLowerCase() == 'select') { // If we have a selectList, then try to parse the higher and lower limits var selOptions = elem.options; // Check the yyyymmdd if(fmt.d && fmt.m && fmt.y) { cursorDate = false; // Dynamically calculate the available 'enabled' dates options.enabledDates = {}; options.disabledDates = {}; for(i = 0; i < selOptions.length; i++) { dt = parseDateString(selOptions[i].value, fmt.value); if(dt && dt.y && !(dt.m === false) && dt.d) { dtPartStr = dt.y + '' + pad(dt.m) + pad(dt.d); if(!cursorDate) { cursorDate = dtPartStr; }; options.enabledDates[dtPartStr] = 1; if(!myMin || +dtPartStr < +myMin) { myMin = dtPartStr; }; if(!myMax || +dtPartStr > +myMax) { myMax = dtPartStr; }; }; }; // Automatically set cursor to first available date (if no bespoke cursorDate was set); if(!options.cursorDate && cursorDate) { options.cursorDate = cursorDate; }; options.disabledDates[myMin] = myMax; } else if(fmt.m && fmt.y) { for(i = 0; i < selOptions.length; i++) { dt = parseDateString(selOptions[i].value, fmt.value); if(dt.y && !(dt.m === false)) { dtPartStr = dt.y + '' + pad(dt.m); if(!myMin || +dtPartStr < +myMin) { myMin = dtPartStr; }; if(!myMax || +dtPartStr > +myMax) { myMax = dtPartStr; }; }; }; // Round the min & max values to be used as rangeLow & rangeHigh myMin += '' + '01'; myMax += '' + daysInMonth(+myMax.substr(4,2) - 1, +myMax.substr(0,4)); } else if(fmt.y) { for(i = 0; i < selOptions.length; i++) { dt = parseDateString(selOptions[i].value, fmt.value); if(dt.y) { if(!myMin || +dt.y < +myMin) { myMin = dt.y; }; if(!myMax || +dt.y > +myMax) { myMax = dt.y; }; }; }; // Round the min & max values to be used as rangeLow & rangeHigh myMin += '' + '0101'; myMax += '' + '1231'; }; }; }; if(!(partsFound.d == 1 && partsFound.m == 1 && partsFound.y == 1)) { if(debug) { throw 'Could not find all of the required date parts within the date format for element: ' + elem.id; }; return false; }; options.rangeLow = dateToYYYYMMDD(options.rangeLow || false); options.rangeHigh = dateToYYYYMMDD(options.rangeHigh || false); options.cursorDate = dateToYYYYMMDD(options.cursorDate || false); if(myMin && (!options.rangeLow || (+options.rangeLow < +myMin))) { options.rangeLow = myMin; }; if(myMax && (!options.rangeHigh || (+options.rangeHigh > +myMax))) { options.rangeHigh = myMax; }; opts = { formElements:options.formElements, // default values defaultVals:defaultVals, // Form element id id:options.id, // Non popup datepicker required staticPos:!!(options.staticPos || options.nopopup), // Position static datepicker or popup datepicker's button positioned:options.positioned && document.getElementById(options.positioned) ? options.positioned : '', // Ranges stipulated in YYYYMMDD format rangeLow:options.rangeLow && String(options.rangeLow).search(rangeRegExp) != -1 ? options.rangeLow : '', rangeHigh:options.rangeHigh && String(options.rangeHigh).search(rangeRegExp) != -1 ? options.rangeHigh : '', // Status bar format statusFormat:options.statusFormat || statusFormat, // No fade in/out effect noFadeEffect:!!(options.staticPos) ? true : !!(options.noFadeEffect), // No drag functionality dragDisabled:nodrag || !!(options.staticPos) ? true : !!(options.dragDisabled), // Bespoke tabindex for this datePicker (or its activation button) bespokeTabIndex:options.bespokeTabindex && typeof options.bespokeTabindex == 'number' ? parseInt(options.bespokeTabindex, 10) : 0, // Bespoke titles bespokeTitles:options.bespokeTitles || (bespokeTitles || {}), // Final opacity finalOpacity:options.finalOpacity && typeof options.finalOpacity == 'number' && (options.finalOpacity > 20 && options.finalOpacity <= 100) ? parseInt(+options.finalOpacity, 10) : (!!(options.staticPos) ? 100 : finalOpacity), // Do we hide the form elements on datepicker creation hideInput:!!(options.hideInput), // Do we hide the 'today' button noToday:!!(options.noTodayButton), // Do we show week numbers showWeeks:!!(options.showWeeks), // Do we fill the entire grid with dates fillGrid:!!(options.fillGrid), // Do we constrain selection of dates outside the current month constrainSelection:'constrainSelection' in options ? !!(options.constrainSelection) : true, // The date to set the initial cursor to cursorDate:options.cursorDate && String(options.cursorDate).search(rangeRegExp) != -1 ? options.cursorDate : '', // Locate label to set the ARIA labelled-by property labelledBy:findLabelForElement(elem), // Have we been passed a describedBy to set the ARIA decribed-by property... describedBy:(options.describedBy && document.getElementById(options.describedBy)) ? options.describedBy : describedBy && document.getElementById(describedBy) ? describedBy : '', // Callback functions callbacks:options.callbackFunctions ? options.callbackFunctions : {}, // Days of the week to highlight (normally the weekend) highlightDays:options.highlightDays && options.highlightDays.length && options.highlightDays.length == 7 ? options.highlightDays : [0,0,0,0,0,1,1], // Days of the week to disable disabledDays:options.disabledDays && options.disabledDays.length && options.disabledDays.length == 7 ? options.disabledDays : [0,0,0,0,0,0,0], // A bespoke class to give the datepicker bespokeClass:options.bespokeClass ? ' ' + options.bespokeClass : '', // Show Action Button showActionButton: !!(options.showActionButton), //Custom CSS Class Name customCssClassName: options.customCssClassName, //No year forward and back noYearForwardBack: !!(options.noYearForwardBack), //Action element to use actionElement: options.actionElement }; datePickers[options.id] = new datePicker(opts); if('disabledDates' in options && !(options.disabledDates === false)) { datePickers[options.id].setDisabledDates(options.disabledDates) }; if('enabledDates' in options && !(options.enabledDates === false)) { datePickers[options.id].setEnabledDates(options.enabledDates) }; datePickers[options.id].callback('create', datePickers[options.id].createCbArgObj()); }; // Used by the button to dictate whether to open or close the datePicker var isVisible = function(id) { return (!id || !(id in datePickers)) ? false : datePickers[id].visible; }; var updateStatic = function() { var dp; for(dp in datePickers) { if(datePickers.hasOwnProperty(dp)) { datePickers[dp].changeHandler(); }; }; }; addEvent(window, 'unload', destroy); addEvent(window, 'load', function() { setTimeout(updateStatic, 0); }); return { // General event functions... addEvent: function(obj, type, fn) { return addEvent(obj, type, fn); }, removeEvent: function(obj, type, fn) { return removeEvent(obj, type, fn); }, stopEvent: function(e) { return stopEvent(e); }, // Show a single popup datepicker show: function(inpID, autoFocus) { return showDatePicker(inpID, autoFocus); }, // Hide a popup datepicker hide: function(inpID) { return hideDatePicker(inpID); }, // Create a new datepicker createDatePicker: function(options) { addDatePicker(options); }, // Destroy a datepicker (remove events and DOM nodes) destroyDatePicker: function(inpID) { destroySingleDatePicker(inpID); }, // Check datePicker form elements exist, if not, destroy the datepicker cleanUp: function() { cleanUp(); }, // Pretty print a date object according to the format passed in printFormattedDate: function(dt, fmt, useImportedLocale) { return printFormattedDate(dt, fmt, useImportedLocale); }, // Update the internal date using the form element value setDateFromInput: function(inpID) { if(!inpID || !(inpID in datePickers)) return false; datePickers[inpID].setDateFromInput(); }, // Set low and high date ranges setRangeLow: function(inpID, yyyymmdd) { if(!inpID || !(inpID in datePickers)) { return false; }; datePickers[inpID].setRangeLow(dateToYYYYMMDD(yyyymmdd)); }, setRangeHigh: function(inpID, yyyymmdd) { if(!inpID || !(inpID in datePickers)) { return false; }; datePickers[inpID].setRangeHigh(dateToYYYYMMDD(yyyymmdd)); }, // Set bespoke titles for a datepicker instance setBespokeTitles: function(inpID, titles) {if(!inpID || !(inpID in datePickers)) { return false; }; datePickers[inpID].setBespokeTitles(titles); }, // Add bespoke titles for a datepicker instance addBespokeTitles: function(inpID, titles) {if(!inpID || !(inpID in datePickers)) { return false; }; datePickers[inpID].addBespokeTitles(titles); }, // Attempt to parse a valid date from a date string using the passed in format parseDateString: function(str, format) { return parseDateString(str, format); }, // Change global configuration parameters setGlobalOptions: function(json) { affectJSON(json); }, // Forces the datepickers 'selected' date setSelectedDate: function(inpID, yyyymmdd) { if(!inpID || !(inpID in datePickers)) { return false; }; datePickers[inpID].setSelectedDate(dateToYYYYMMDD(yyyymmdd)); }, // Is the date valid for selection i.e. not outside ranges etc dateValidForSelection: function(inpID, dt) { if(!inpID || !(inpID in datePickers)) return false; return datePickers[inpID].canDateBeSelected(dt); }, // Add disabled and enabled dates addDisabledDates: function(inpID, dts) { if(!inpID || !(inpID in datePickers)) return false; datePickers[inpID].addDisabledDates(dts); }, setDisabledDates: function(inpID, dts) { if(!inpID || !(inpID in datePickers)) return false; datePickers[inpID].setDisabledDates(dts); }, addEnabledDates: function(inpID, dts) { if(!inpID || !(inpID in datePickers)) return false; datePickers[inpID].addEnabledDates(dts); }, setEnabledDates: function(inpID, dts) { if(!inpID || !(inpID in datePickers)) return false; datePickers[inpID].setEnabledDates(dts); }, // Disable and enable the datepicker disable: function(inpID) { if(!inpID || !(inpID in datePickers)) return false; datePickers[inpID].disableDatePicker(); }, enable: function(inpID) { if(!inpID || !(inpID in datePickers)) return false; datePickers[inpID].enableDatePicker(); }, // Set the cursor date setCursorDate: function(inpID, yyyymmdd) { if(!inpID || !(inpID in datePickers)) return false; datePickers[inpID].setCursorDate(dateToYYYYMMDD(yyyymmdd)); }, // Whats the currently selected date getSelectedDate: function(inpID) { return (!inpID || !(inpID in datePickers)) ? false : datePickers[inpID].returnSelectedDate(); }, // Attempt to update the language (causes a redraw of all datepickers on the page) loadLanguage: function() { loadLanguage(); }, // Set the debug level i.e. throw errors or fail silently setDebug: function(dbg) { debug = !!(dbg); }, // Converts Date Object to a YYYYMMDD formatted String dateToYYYYMMDDStr: function(dt) { return dateToYYYYMMDD(dt); } }; })(); ;(function(window, document, exportName, undefined) { 'use strict'; var VENDOR_PREFIXES = ['', 'webkit', 'moz', 'MS', 'ms', 'o']; var TEST_ELEMENT = document.createElement('div'); var TYPE_FUNCTION = 'function'; var round = Math.round; var abs = Math.abs; var now = Date.now; /** * set a timeout with a given scope * @param {Function} fn * @param {Number} timeout * @param {Object} context * @returns {number} */ function setTimeoutContext(fn, timeout, context) { return setTimeout(bindFn(fn, context), timeout); } /** * if the argument is an array, we want to execute the fn on each entry * if it aint an array we don't want to do a thing. * this is used by all the methods that accept a single and array argument. * @param {*|Array} arg * @param {String} fn * @param {Object} [context] * @returns {Boolean} */ function invokeArrayArg(arg, fn, context) { if (Array.isArray(arg)) { each(arg, context[fn], context); return true; } return false; } /** * walk objects and arrays * @param {Object} obj * @param {Function} iterator * @param {Object} context */ function each(obj, iterator, context) { var i; if (!obj) { return; } if (obj.forEach) { obj.forEach(iterator, context); } else if (obj.length !== undefined) { i = 0; while (i < obj.length) { iterator.call(context, obj[i], i, obj); i++; } } else { for (i in obj) { obj.hasOwnProperty(i) && iterator.call(context, obj[i], i, obj); } } } /** * extend object. * means that properties in dest will be overwritten by the ones in src. * @param {Object} dest * @param {Object} src * @param {Boolean} [merge] * @returns {Object} dest */ function extend(dest, src, merge) { var keys = Object.keys(src); var i = 0; while (i < keys.length) { if (!merge || (merge && dest[keys[i]] === undefined)) { dest[keys[i]] = src[keys[i]]; } i++; } return dest; } /** * merge the values from src in the dest. * means that properties that exist in dest will not be overwritten by src * @param {Object} dest * @param {Object} src * @returns {Object} dest */ function merge(dest, src) { return extend(dest, src, true); } /** * simple class inheritance * @param {Function} child * @param {Function} base * @param {Object} [properties] */ function inherit(child, base, properties) { var baseP = base.prototype, childP; childP = child.prototype = Object.create(baseP); childP.constructor = child; childP._super = baseP; if (properties) { extend(childP, properties); } } /** * simple function bind * @param {Function} fn * @param {Object} context * @returns {Function} */ function bindFn(fn, context) { return function boundFn() { return fn.apply(context, arguments); }; } /** * let a boolean value also be a function that must return a boolean * this first item in args will be used as the context * @param {Boolean|Function} val * @param {Array} [args] * @returns {Boolean} */ function boolOrFn(val, args) { if (typeof val == TYPE_FUNCTION) { return val.apply(args ? args[0] || undefined : undefined, args); } return val; } /** * use the val2 when val1 is undefined * @param {*} val1 * @param {*} val2 * @returns {*} */ function ifUndefined(val1, val2) { return (val1 === undefined) ? val2 : val1; } /** * addEventListener with multiple events at once * @param {EventTarget} target * @param {String} types * @param {Function} handler */ function addEventListeners(target, types, handler) { each(splitStr(types), function(type) { target.addEventListener(type, handler, false); }); } /** * removeEventListener with multiple events at once * @param {EventTarget} target * @param {String} types * @param {Function} handler */ function removeEventListeners(target, types, handler) { each(splitStr(types), function(type) { target.removeEventListener(type, handler, false); }); } /** * find if a node is in the given parent * @method hasParent * @param {HTMLElement} node * @param {HTMLElement} parent * @return {Boolean} found */ function hasParent(node, parent) { while (node) { if (node == parent) { return true; } node = node.parentNode; } return false; } /** * small indexOf wrapper * @param {String} str * @param {String} find * @returns {Boolean} found */ function inStr(str, find) { return str.indexOf(find) > -1; } /** * split string on whitespace * @param {String} str * @returns {Array} words */ function splitStr(str) { return str.trim().split(/\s+/g); } /** * find if a array contains the object using indexOf or a simple polyFill * @param {Array} src * @param {String} find * @param {String} [findByKey] * @return {Boolean|Number} false when not found, or the index */ function inArray(src, find, findByKey) { if (src.indexOf && !findByKey) { return src.indexOf(find); } else { var i = 0; while (i < src.length) { if ((findByKey && src[i][findByKey] == find) || (!findByKey && src[i] === find)) { return i; } i++; } return -1; } } /** * convert array-like objects to real arrays * @param {Object} obj * @returns {Array} */ function toArray(obj) { return Array.prototype.slice.call(obj, 0); } /** * unique array with objects based on a key (like 'id') or just by the array's value * @param {Array} src [{id:1},{id:2},{id:1}] * @param {String} [key] * @param {Boolean} [sort=False] * @returns {Array} [{id:1},{id:2}] */ function uniqueArray(src, key, sort) { var results = []; var values = []; var i = 0; while (i < src.length) { var val = key ? src[i][key] : src[i]; if (inArray(values, val) < 0) { results.push(src[i]); } values[i] = val; i++; } if (sort) { if (!key) { results = results.sort(); } else { results = results.sort(function sortUniqueArray(a, b) { return a[key] > b[key]; }); } } return results; } /** * get the prefixed property * @param {Object} obj * @param {String} property * @returns {String|Undefined} prefixed */ function prefixed(obj, property) { var prefix, prop; var camelProp = property[0].toUpperCase() + property.slice(1); var i = 0; while (i < VENDOR_PREFIXES.length) { prefix = VENDOR_PREFIXES[i]; prop = (prefix) ? prefix + camelProp : property; if (prop in obj) { return prop; } i++; } return undefined; } /** * get a unique id * @returns {number} uniqueId */ var _uniqueId = 1; function uniqueId() { return _uniqueId++; } /** * get the window object of an element * @param {HTMLElement} element * @returns {DocumentView|Window} */ function getWindowForElement(element) { var doc = element.ownerDocument; return (doc.defaultView || doc.parentWindow); } var MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android/i; var SUPPORT_TOUCH = ('ontouchstart' in window); var SUPPORT_POINTER_EVENTS = prefixed(window, 'PointerEvent') !== undefined; var SUPPORT_ONLY_TOUCH = SUPPORT_TOUCH && MOBILE_REGEX.test(navigator.userAgent); var INPUT_TYPE_TOUCH = 'touch'; var INPUT_TYPE_PEN = 'pen'; var INPUT_TYPE_MOUSE = 'mouse'; var INPUT_TYPE_KINECT = 'kinect'; var COMPUTE_INTERVAL = 25; var INPUT_START = 1; var INPUT_MOVE = 2; var INPUT_END = 4; var INPUT_CANCEL = 8; var DIRECTION_NONE = 1; var DIRECTION_LEFT = 2; var DIRECTION_RIGHT = 4; var DIRECTION_UP = 8; var DIRECTION_DOWN = 16; var DIRECTION_HORIZONTAL = DIRECTION_LEFT | DIRECTION_RIGHT; var DIRECTION_VERTICAL = DIRECTION_UP | DIRECTION_DOWN; var DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL; var PROPS_XY = ['x', 'y']; var PROPS_CLIENT_XY = ['clientX', 'clientY']; /** * create new input type manager * @param {Manager} manager * @param {Function} callback * @returns {Input} * @constructor */ function Input(manager, callback) { var self = this; this.manager = manager; this.callback = callback; this.element = manager.element; this.target = manager.options.inputTarget; // smaller wrapper around the handler, for the scope and the enabled state of the manager, // so when disabled the input events are completely bypassed. this.domHandler = function(ev) { if (boolOrFn(manager.options.enable, [manager])) { self.handler(ev); } }; this.init(); } Input.prototype = { /** * should handle the inputEvent data and trigger the callback * @virtual */ handler: function() { }, /** * bind the events */ init: function() { this.evEl && addEventListeners(this.element, this.evEl, this.domHandler); this.evTarget && addEventListeners(this.target, this.evTarget, this.domHandler); this.evWin && addEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler); }, /** * unbind the events */ destroy: function() { this.evEl && removeEventListeners(this.element, this.evEl, this.domHandler); this.evTarget && removeEventListeners(this.target, this.evTarget, this.domHandler); this.evWin && removeEventListeners(getWindowForElement(this.element), this.evWin, this.domHandler); } }; /** * create new input type manager * called by the Manager constructor * @param {Hammer} manager * @returns {Input} */ function createInputInstance(manager) { var Type; var inputClass = manager.options.inputClass; if (inputClass) { Type = inputClass; } else if (SUPPORT_POINTER_EVENTS) { Type = PointerEventInput; } else if (SUPPORT_ONLY_TOUCH) { Type = TouchInput; } else if (!SUPPORT_TOUCH) { Type = MouseInput; } else { Type = TouchMouseInput; } return new (Type)(manager, inputHandler); } /** * handle input events * @param {Manager} manager * @param {String} eventType * @param {Object} input */ function inputHandler(manager, eventType, input) { var pointersLen = input.pointers.length; var changedPointersLen = input.changedPointers.length; var isFirst = (eventType & INPUT_START && (pointersLen - changedPointersLen === 0)); var isFinal = (eventType & (INPUT_END | INPUT_CANCEL) && (pointersLen - changedPointersLen === 0)); input.isFirst = !!isFirst; input.isFinal = !!isFinal; if (isFirst) { manager.session = {}; } // source event is the normalized value of the domEvents // like 'touchstart, mouseup, pointerdown' input.eventType = eventType; // compute scale, rotation etc computeInputData(manager, input); // emit secret event manager.emit('hammer.input', input); manager.recognize(input); manager.session.prevInput = input; } /** * extend the data with some usable properties like scale, rotate, velocity etc * @param {Object} manager * @param {Object} input */ function computeInputData(manager, input) { var session = manager.session; var pointers = input.pointers; var pointersLength = pointers.length; // store the first input to calculate the distance and direction if (!session.firstInput) { session.firstInput = simpleCloneInputData(input); } // to compute scale and rotation we need to store the multiple touches if (pointersLength > 1 && !session.firstMultiple) { session.firstMultiple = simpleCloneInputData(input); } else if (pointersLength === 1) { session.firstMultiple = false; } var firstInput = session.firstInput; var firstMultiple = session.firstMultiple; var offsetCenter = firstMultiple ? firstMultiple.center : firstInput.center; var center = input.center = getCenter(pointers); input.timeStamp = now(); input.deltaTime = input.timeStamp - firstInput.timeStamp; input.angle = getAngle(offsetCenter, center); input.distance = getDistance(offsetCenter, center); computeDeltaXY(session, input); input.offsetDirection = getDirection(input.deltaX, input.deltaY); input.scale = firstMultiple ? getScale(firstMultiple.pointers, pointers) : 1; input.rotation = firstMultiple ? getRotation(firstMultiple.pointers, pointers) : 0; computeIntervalInputData(session, input); // find the correct target var target = manager.element; if (hasParent(input.srcEvent.target, target)) { target = input.srcEvent.target; } input.target = target; } function computeDeltaXY(session, input) { var center = input.center; var offset = session.offsetDelta || {}; var prevDelta = session.prevDelta || {}; var prevInput = session.prevInput || {}; if (input.eventType === INPUT_START || prevInput.eventType === INPUT_END) { prevDelta = session.prevDelta = { x: prevInput.deltaX || 0, y: prevInput.deltaY || 0 }; offset = session.offsetDelta = { x: center.x, y: center.y }; } input.deltaX = prevDelta.x + (center.x - offset.x); input.deltaY = prevDelta.y + (center.y - offset.y); } /** * velocity is calculated every x ms * @param {Object} session * @param {Object} input */ function computeIntervalInputData(session, input) { var last = session.lastInterval || input, deltaTime = input.timeStamp - last.timeStamp, velocity, velocityX, velocityY, direction; if (input.eventType != INPUT_CANCEL && (deltaTime > COMPUTE_INTERVAL || last.velocity === undefined)) { var deltaX = last.deltaX - input.deltaX; var deltaY = last.deltaY - input.deltaY; var v = getVelocity(deltaTime, deltaX, deltaY); velocityX = v.x; velocityY = v.y; velocity = (abs(v.x) > abs(v.y)) ? v.x : v.y; direction = getDirection(deltaX, deltaY); session.lastInterval = input; } else { // use latest velocity info if it doesn't overtake a minimum period velocity = last.velocity; velocityX = last.velocityX; velocityY = last.velocityY; direction = last.direction; } input.velocity = velocity; input.velocityX = velocityX; input.velocityY = velocityY; input.direction = direction; } /** * create a simple clone from the input used for storage of firstInput and firstMultiple * @param {Object} input * @returns {Object} clonedInputData */ function simpleCloneInputData(input) { // make a simple copy of the pointers because we will get a reference if we don't // we only need clientXY for the calculations var pointers = []; var i = 0; while (i < input.pointers.length) { pointers[i] = { clientX: round(input.pointers[i].clientX), clientY: round(input.pointers[i].clientY) }; i++; } return { timeStamp: now(), pointers: pointers, center: getCenter(pointers), deltaX: input.deltaX, deltaY: input.deltaY }; } /** * get the center of all the pointers * @param {Array} pointers * @return {Object} center contains `x` and `y` properties */ function getCenter(pointers) { var pointersLength = pointers.length; // no need to loop when only one touch if (pointersLength === 1) { return { x: round(pointers[0].clientX), y: round(pointers[0].clientY) }; } var x = 0, y = 0, i = 0; while (i < pointersLength) { x += pointers[i].clientX; y += pointers[i].clientY; i++; } return { x: round(x / pointersLength), y: round(y / pointersLength) }; } /** * calculate the velocity between two points. unit is in px per ms. * @param {Number} deltaTime * @param {Number} x * @param {Number} y * @return {Object} velocity `x` and `y` */ function getVelocity(deltaTime, x, y) { return { x: x / deltaTime || 0, y: y / deltaTime || 0 }; } /** * get the direction between two points * @param {Number} x * @param {Number} y * @return {Number} direction */ function getDirection(x, y) { if (x === y) { return DIRECTION_NONE; } if (abs(x) >= abs(y)) { return x > 0 ? DIRECTION_LEFT : DIRECTION_RIGHT; } return y > 0 ? DIRECTION_UP : DIRECTION_DOWN; } /** * calculate the absolute distance between two points * @param {Object} p1 {x, y} * @param {Object} p2 {x, y} * @param {Array} [props] containing x and y keys * @return {Number} distance */ function getDistance(p1, p2, props) { if (!props) { props = PROPS_XY; } var x = p2[props[0]] - p1[props[0]], y = p2[props[1]] - p1[props[1]]; return Math.sqrt((x * x) + (y * y)); } /** * calculate the angle between two coordinates * @param {Object} p1 * @param {Object} p2 * @param {Array} [props] containing x and y keys * @return {Number} angle */ function getAngle(p1, p2, props) { if (!props) { props = PROPS_XY; } var x = p2[props[0]] - p1[props[0]], y = p2[props[1]] - p1[props[1]]; return Math.atan2(y, x) * 180 / Math.PI; } /** * calculate the rotation degrees between two pointersets * @param {Array} start array of pointers * @param {Array} end array of pointers * @return {Number} rotation */ function getRotation(start, end) { return getAngle(end[1], end[0], PROPS_CLIENT_XY) - getAngle(start[1], start[0], PROPS_CLIENT_XY); } /** * calculate the scale factor between two pointersets * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out * @param {Array} start array of pointers * @param {Array} end array of pointers * @return {Number} scale */ function getScale(start, end) { return getDistance(end[0], end[1], PROPS_CLIENT_XY) / getDistance(start[0], start[1], PROPS_CLIENT_XY); } var MOUSE_INPUT_MAP = { mousedown: INPUT_START, mousemove: INPUT_MOVE, mouseup: INPUT_END }; var MOUSE_ELEMENT_EVENTS = 'mousedown'; var MOUSE_WINDOW_EVENTS = 'mousemove mouseup'; /** * Mouse events input * @constructor * @extends Input */ function MouseInput() { this.evEl = MOUSE_ELEMENT_EVENTS; this.evWin = MOUSE_WINDOW_EVENTS; this.allow = true; // used by Input.TouchMouse to disable mouse events this.pressed = false; // mousedown state Input.apply(this, arguments); } inherit(MouseInput, Input, { /** * handle mouse events * @param {Object} ev */ handler: function MEhandler(ev) { var eventType = MOUSE_INPUT_MAP[ev.type]; // on start we want to have the left mouse button down if (eventType & INPUT_START && ev.button === 0) { this.pressed = true; } if (eventType & INPUT_MOVE && ev.which !== 1) { eventType = INPUT_END; } // mouse must be down, and mouse events are allowed (see the TouchMouse input) if (!this.pressed || !this.allow) { return; } if (eventType & INPUT_END) { this.pressed = false; } this.callback(this.manager, eventType, { pointers: [ev], changedPointers: [ev], pointerType: INPUT_TYPE_MOUSE, srcEvent: ev }); } }); var POINTER_INPUT_MAP = { pointerdown: INPUT_START, pointermove: INPUT_MOVE, pointerup: INPUT_END, pointercancel: INPUT_CANCEL, pointerout: INPUT_CANCEL }; // in IE10 the pointer types is defined as an enum var IE10_POINTER_TYPE_ENUM = { 2: INPUT_TYPE_TOUCH, 3: INPUT_TYPE_PEN, 4: INPUT_TYPE_MOUSE, 5: INPUT_TYPE_KINECT // see https://twitter.com/jacobrossi/status/480596438489890816 }; var POINTER_ELEMENT_EVENTS = 'pointerdown'; var POINTER_WINDOW_EVENTS = 'pointermove pointerup pointercancel'; // IE10 has prefixed support, and case-sensitive if (window.MSPointerEvent) { POINTER_ELEMENT_EVENTS = 'MSPointerDown'; POINTER_WINDOW_EVENTS = 'MSPointerMove MSPointerUp MSPointerCancel'; } /** * Pointer events input * @constructor * @extends Input */ function PointerEventInput() { this.evEl = POINTER_ELEMENT_EVENTS; this.evWin = POINTER_WINDOW_EVENTS; Input.apply(this, arguments); this.store = (this.manager.session.pointerEvents = []); } inherit(PointerEventInput, Input, { /** * handle mouse events * @param {Object} ev */ handler: function PEhandler(ev) { var store = this.store; var removePointer = false; var eventTypeNormalized = ev.type.toLowerCase().replace('ms', ''); var eventType = POINTER_INPUT_MAP[eventTypeNormalized]; var pointerType = IE10_POINTER_TYPE_ENUM[ev.pointerType] || ev.pointerType; var isTouch = (pointerType == INPUT_TYPE_TOUCH); // start and mouse must be down if (eventType & INPUT_START && (ev.button === 0 || isTouch)) { store.push(ev); } else if (eventType & (INPUT_END | INPUT_CANCEL)) { removePointer = true; } // get index of the event in the store // it not found, so the pointer hasn't been down (so it's probably a hover) var storeIndex = inArray(store, ev.pointerId, 'pointerId'); if (storeIndex < 0) { return; } // update the event in the store store[storeIndex] = ev; this.callback(this.manager, eventType, { pointers: store, changedPointers: [ev], pointerType: pointerType, srcEvent: ev }); if (removePointer) { // remove from the store store.splice(storeIndex, 1); } } }); var TOUCH_INPUT_MAP = { touchstart: INPUT_START, touchmove: INPUT_MOVE, touchend: INPUT_END, touchcancel: INPUT_CANCEL }; var TOUCH_TARGET_EVENTS = 'touchstart touchmove touchend touchcancel'; /** * Touch events input * @constructor * @extends Input */ function TouchInput() { this.evTarget = TOUCH_TARGET_EVENTS; this.targetIds = {}; Input.apply(this, arguments); } inherit(TouchInput, Input, { /** * handle touch events * @param {Object} ev */ handler: function TEhandler(ev) { var type = TOUCH_INPUT_MAP[ev.type]; var touches = getTouches.call(this, ev, type); if (!touches) { return; } this.callback(this.manager, type, { pointers: touches[0], changedPointers: touches[1], pointerType: INPUT_TYPE_TOUCH, srcEvent: ev }); } }); /** * @this {TouchInput} * @param {Object} ev * @param {Number} type flag * @returns {undefined|Array} [all, changed] */ function getTouches(ev, type) { var allTouches = toArray(ev.touches); var targetIds = this.targetIds; // when there is only one touch, the process can be simplified if (type & (INPUT_START | INPUT_MOVE) && allTouches.length === 1) { targetIds[allTouches[0].identifier] = true; return [allTouches, allTouches]; } var i, targetTouches = toArray(ev.targetTouches), changedTouches = toArray(ev.changedTouches), changedTargetTouches = []; // collect touches if (type === INPUT_START) { i = 0; while (i < targetTouches.length) { targetIds[targetTouches[i].identifier] = true; i++; } } // filter changed touches to only contain touches that exist in the collected target ids i = 0; while (i < changedTouches.length) { if (targetIds[changedTouches[i].identifier]) { changedTargetTouches.push(changedTouches[i]); } // cleanup removed touches if (type & (INPUT_END | INPUT_CANCEL)) { delete targetIds[changedTouches[i].identifier]; } i++; } if (!changedTargetTouches.length) { return; } return [ // merge targetTouches with changedTargetTouches so it contains ALL touches, including 'end' and 'cancel' uniqueArray(targetTouches.concat(changedTargetTouches), 'identifier', true), changedTargetTouches ]; } /** * Combined touch and mouse input * * Touch has a higher priority then mouse, and while touching no mouse events are allowed. * This because touch devices also emit mouse events while doing a touch. * * @constructor * @extends Input */ function TouchMouseInput() { Input.apply(this, arguments); var handler = bindFn(this.handler, this); this.touch = new TouchInput(this.manager, handler); this.mouse = new MouseInput(this.manager, handler); } inherit(TouchMouseInput, Input, { /** * handle mouse and touch events * @param {Hammer} manager * @param {String} inputEvent * @param {Object} inputData */ handler: function TMEhandler(manager, inputEvent, inputData) { var isTouch = (inputData.pointerType == INPUT_TYPE_TOUCH), isMouse = (inputData.pointerType == INPUT_TYPE_MOUSE); // when we're in a touch event, so block all upcoming mouse events // most mobile browser also emit mouseevents, right after touchstart if (isTouch) { this.mouse.allow = false; } else if (isMouse && !this.mouse.allow) { return; } // reset the allowMouse when we're done if (inputEvent & (INPUT_END | INPUT_CANCEL)) { this.mouse.allow = true; } this.callback(manager, inputEvent, inputData); }, /** * remove the event listeners */ destroy: function destroy() { this.touch.destroy(); this.mouse.destroy(); } }); var PREFIXED_TOUCH_ACTION = prefixed(TEST_ELEMENT.style, 'touchAction'); var NATIVE_TOUCH_ACTION = PREFIXED_TOUCH_ACTION !== undefined; // magical touchAction value var TOUCH_ACTION_COMPUTE = 'compute'; var TOUCH_ACTION_AUTO = 'auto'; var TOUCH_ACTION_MANIPULATION = 'manipulation'; // not implemented var TOUCH_ACTION_NONE = 'none'; var TOUCH_ACTION_PAN_X = 'pan-x'; var TOUCH_ACTION_PAN_Y = 'pan-y'; /** * Touch Action * sets the touchAction property or uses the js alternative * @param {Manager} manager * @param {String} value * @constructor */ function TouchAction(manager, value) { this.manager = manager; this.set(value); } TouchAction.prototype = { /** * set the touchAction value on the element or enable the polyfill * @param {String} value */ set: function(value) { // find out the touch-action by the event handlers if (value == TOUCH_ACTION_COMPUTE) { value = this.compute(); } if (NATIVE_TOUCH_ACTION) { this.manager.element.style[PREFIXED_TOUCH_ACTION] = value; } this.actions = value.toLowerCase().trim(); }, /** * just re-set the touchAction value */ update: function() { this.set(this.manager.options.touchAction); }, /** * compute the value for the touchAction property based on the recognizer's settings * @returns {String} value */ compute: function() { var actions = []; each(this.manager.recognizers, function(recognizer) { if (boolOrFn(recognizer.options.enable, [recognizer])) { actions = actions.concat(recognizer.getTouchAction()); } }); return cleanTouchActions(actions.join(' ')); }, /** * this method is called on each input cycle and provides the preventing of the browser behavior * @param {Object} input */ preventDefaults: function(input) { // not needed with native support for the touchAction property if (NATIVE_TOUCH_ACTION) { return; } var srcEvent = input.srcEvent; var direction = input.offsetDirection; // if the touch action did prevented once this session if (this.manager.session.prevented) { srcEvent.preventDefault(); return; } var actions = this.actions; var hasNone = inStr(actions, TOUCH_ACTION_NONE); var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y); var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X); if (hasNone || (hasPanY && direction & DIRECTION_HORIZONTAL) || (hasPanX && direction & DIRECTION_VERTICAL)) { return this.preventSrc(srcEvent); } }, /** * call preventDefault to prevent the browser's default behavior (scrolling in most cases) * @param {Object} srcEvent */ preventSrc: function(srcEvent) { this.manager.session.prevented = true; srcEvent.preventDefault(); } }; /** * when the touchActions are collected they are not a valid value, so we need to clean things up. * * @param {String} actions * @returns {*} */ function cleanTouchActions(actions) { // none if (inStr(actions, TOUCH_ACTION_NONE)) { return TOUCH_ACTION_NONE; } var hasPanX = inStr(actions, TOUCH_ACTION_PAN_X); var hasPanY = inStr(actions, TOUCH_ACTION_PAN_Y); // pan-x and pan-y can be combined if (hasPanX && hasPanY) { return TOUCH_ACTION_PAN_X + ' ' + TOUCH_ACTION_PAN_Y; } // pan-x OR pan-y if (hasPanX || hasPanY) { return hasPanX ? TOUCH_ACTION_PAN_X : TOUCH_ACTION_PAN_Y; } // manipulation if (inStr(actions, TOUCH_ACTION_MANIPULATION)) { return TOUCH_ACTION_MANIPULATION; } return TOUCH_ACTION_AUTO; } /** * Recognizer flow explained; * * All recognizers have the initial state of POSSIBLE when a input session starts. * The definition of a input session is from the first input until the last input, with all it's movement in it. * * Example session for mouse-input: mousedown -> mousemove -> mouseup * * On each recognizing cycle (see Manager.recognize) the .recognize() method is executed * which determines with state it should be. * * If the recognizer has the state FAILED, CANCELLED or RECOGNIZED (equals ENDED), it is reset to * POSSIBLE to give it another change on the next cycle. * * Possible * | * +-----+---------------+ * | | * +-----+-----+ | * | | | * Failed Cancelled | * +-------+------+ * | | * Recognized Began * | * Changed * | * Ended/Recognized */ var STATE_POSSIBLE = 1; var STATE_BEGAN = 2; var STATE_CHANGED = 4; var STATE_ENDED = 8; var STATE_RECOGNIZED = STATE_ENDED; var STATE_CANCELLED = 16; var STATE_FAILED = 32; /** * Recognizer * Every recognizer needs to extend from this class. * @constructor * @param {Object} options */ function Recognizer(options) { this.id = uniqueId(); this.manager = null; this.options = merge(options || {}, this.defaults); // default is enable true this.options.enable = ifUndefined(this.options.enable, true); this.state = STATE_POSSIBLE; this.simultaneous = {}; this.requireFail = []; } Recognizer.prototype = { /** * @virtual * @type {Object} */ defaults: {}, /** * set options * @param {Object} options * @return {Recognizer} */ set: function(options) { extend(this.options, options); // also update the touchAction, in case something changed about the directions/enabled state this.manager && this.manager.touchAction.update(); return this; }, /** * recognize simultaneous with an other recognizer. * @param {Recognizer} otherRecognizer * @returns {Recognizer} this */ recognizeWith: function(otherRecognizer) { if (invokeArrayArg(otherRecognizer, 'recognizeWith', this)) { return this; } var simultaneous = this.simultaneous; otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); if (!simultaneous[otherRecognizer.id]) { simultaneous[otherRecognizer.id] = otherRecognizer; otherRecognizer.recognizeWith(this); } return this; }, /** * drop the simultaneous link. it doesnt remove the link on the other recognizer. * @param {Recognizer} otherRecognizer * @returns {Recognizer} this */ dropRecognizeWith: function(otherRecognizer) { if (invokeArrayArg(otherRecognizer, 'dropRecognizeWith', this)) { return this; } otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); delete this.simultaneous[otherRecognizer.id]; return this; }, /** * recognizer can only run when an other is failing * @param {Recognizer} otherRecognizer * @returns {Recognizer} this */ requireFailure: function(otherRecognizer) { if (invokeArrayArg(otherRecognizer, 'requireFailure', this)) { return this; } var requireFail = this.requireFail; otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); if (inArray(requireFail, otherRecognizer) === -1) { requireFail.push(otherRecognizer); otherRecognizer.requireFailure(this); } return this; }, /** * drop the requireFailure link. it does not remove the link on the other recognizer. * @param {Recognizer} otherRecognizer * @returns {Recognizer} this */ dropRequireFailure: function(otherRecognizer) { if (invokeArrayArg(otherRecognizer, 'dropRequireFailure', this)) { return this; } otherRecognizer = getRecognizerByNameIfManager(otherRecognizer, this); var index = inArray(this.requireFail, otherRecognizer); if (index > -1) { this.requireFail.splice(index, 1); } return this; }, /** * has require failures boolean * @returns {boolean} */ hasRequireFailures: function() { return this.requireFail.length > 0; }, /** * if the recognizer can recognize simultaneous with an other recognizer * @param {Recognizer} otherRecognizer * @returns {Boolean} */ canRecognizeWith: function(otherRecognizer) { return !!this.simultaneous[otherRecognizer.id]; }, /** * You should use `tryEmit` instead of `emit` directly to check * that all the needed recognizers has failed before emitting. * @param {Object} input */ emit: function(input) { var self = this; var state = this.state; function emit(withState) { self.manager.emit(self.options.event + (withState ? stateStr(state) : ''), input); } // 'panstart' and 'panmove' if (state < STATE_ENDED) { emit(true); } emit(); // simple 'eventName' events // panend and pancancel if (state >= STATE_ENDED) { emit(true); } }, /** * Check that all the require failure recognizers has failed, * if true, it emits a gesture event, * otherwise, setup the state to FAILED. * @param {Object} input */ tryEmit: function(input) { if (this.canEmit()) { return this.emit(input); } // it's failing anyway this.state = STATE_FAILED; }, /** * can we emit? * @returns {boolean} */ canEmit: function() { var i = 0; while (i < this.requireFail.length) { if (!(this.requireFail[i].state & (STATE_FAILED | STATE_POSSIBLE))) { return false; } i++; } return true; }, /** * update the recognizer * @param {Object} inputData */ recognize: function(inputData) { // make a new copy of the inputData // so we can change the inputData without messing up the other recognizers var inputDataClone = extend({}, inputData); // is is enabled and allow recognizing? if (!boolOrFn(this.options.enable, [this, inputDataClone])) { this.reset(); this.state = STATE_FAILED; return; } // reset when we've reached the end if (this.state & (STATE_RECOGNIZED | STATE_CANCELLED | STATE_FAILED)) { this.state = STATE_POSSIBLE; } this.state = this.process(inputDataClone); // the recognizer has recognized a gesture // so trigger an event if (this.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED | STATE_CANCELLED)) { this.tryEmit(inputDataClone); } }, /** * return the state of the recognizer * the actual recognizing happens in this method * @virtual * @param {Object} inputData * @returns {Const} STATE */ process: function(inputData) { }, // jshint ignore:line /** * return the preferred touch-action * @virtual * @returns {Array} */ getTouchAction: function() { }, /** * called when the gesture isn't allowed to recognize * like when another is being recognized or it is disabled * @virtual */ reset: function() { } }; /** * get a usable string, used as event postfix * @param {Const} state * @returns {String} state */ function stateStr(state) { if (state & STATE_CANCELLED) { return 'cancel'; } else if (state & STATE_ENDED) { return 'end'; } else if (state & STATE_CHANGED) { return 'move'; } else if (state & STATE_BEGAN) { return 'start'; } return ''; } /** * direction cons to string * @param {Const} direction * @returns {String} */ function directionStr(direction) { if (direction == DIRECTION_DOWN) { return 'down'; } else if (direction == DIRECTION_UP) { return 'up'; } else if (direction == DIRECTION_LEFT) { return 'left'; } else if (direction == DIRECTION_RIGHT) { return 'right'; } return ''; } /** * get a recognizer by name if it is bound to a manager * @param {Recognizer|String} otherRecognizer * @param {Recognizer} recognizer * @returns {Recognizer} */ function getRecognizerByNameIfManager(otherRecognizer, recognizer) { var manager = recognizer.manager; if (manager) { return manager.get(otherRecognizer); } return otherRecognizer; } /** * This recognizer is just used as a base for the simple attribute recognizers. * @constructor * @extends Recognizer */ function AttrRecognizer() { Recognizer.apply(this, arguments); } inherit(AttrRecognizer, Recognizer, { /** * @namespace * @memberof AttrRecognizer */ defaults: { /** * @type {Number} * @default 1 */ pointers: 1 }, /** * Used to check if it the recognizer receives valid input, like input.distance > 10. * @memberof AttrRecognizer * @param {Object} input * @returns {Boolean} recognized */ attrTest: function(input) { var optionPointers = this.options.pointers; return optionPointers === 0 || input.pointers.length === optionPointers; }, /** * Process the input and return the state for the recognizer * @memberof AttrRecognizer * @param {Object} input * @returns {*} State */ process: function(input) { var state = this.state; var eventType = input.eventType; var isRecognized = state & (STATE_BEGAN | STATE_CHANGED); var isValid = this.attrTest(input); // on cancel input and we've recognized before, return STATE_CANCELLED if (isRecognized && (eventType & INPUT_CANCEL || !isValid)) { return state | STATE_CANCELLED; } else if (isRecognized || isValid) { if (eventType & INPUT_END) { return state | STATE_ENDED; } else if (!(state & STATE_BEGAN)) { return STATE_BEGAN; } return state | STATE_CHANGED; } return STATE_FAILED; } }); /** * Pan * Recognized when the pointer is down and moved in the allowed direction. * @constructor * @extends AttrRecognizer */ function PanRecognizer() { AttrRecognizer.apply(this, arguments); this.pX = null; this.pY = null; } inherit(PanRecognizer, AttrRecognizer, { /** * @namespace * @memberof PanRecognizer */ defaults: { event: 'pan', threshold: 10, pointers: 1, direction: DIRECTION_ALL }, getTouchAction: function() { var direction = this.options.direction; var actions = []; if (direction & DIRECTION_HORIZONTAL) { actions.push(TOUCH_ACTION_PAN_Y); } if (direction & DIRECTION_VERTICAL) { actions.push(TOUCH_ACTION_PAN_X); } return actions; }, directionTest: function(input) { var options = this.options; var hasMoved = true; var distance = input.distance; var direction = input.direction; var x = input.deltaX; var y = input.deltaY; // lock to axis? if (!(direction & options.direction)) { if (options.direction & DIRECTION_HORIZONTAL) { direction = (x === 0) ? DIRECTION_NONE : (x < 0) ? DIRECTION_LEFT : DIRECTION_RIGHT; hasMoved = x != this.pX; distance = Math.abs(input.deltaX); } else { direction = (y === 0) ? DIRECTION_NONE : (y < 0) ? DIRECTION_UP : DIRECTION_DOWN; hasMoved = y != this.pY; distance = Math.abs(input.deltaY); } } input.direction = direction; return hasMoved && distance > options.threshold && direction & options.direction; }, attrTest: function(input) { return AttrRecognizer.prototype.attrTest.call(this, input) && (this.state & STATE_BEGAN || (!(this.state & STATE_BEGAN) && this.directionTest(input))); }, emit: function(input) { this.pX = input.deltaX; this.pY = input.deltaY; var direction = directionStr(input.direction); if (direction) { this.manager.emit(this.options.event + direction, input); } this._super.emit.call(this, input); } }); /** * Pinch * Recognized when two or more pointers are moving toward (zoom-in) or away from each other (zoom-out). * @constructor * @extends AttrRecognizer */ function PinchRecognizer() { AttrRecognizer.apply(this, arguments); } inherit(PinchRecognizer, AttrRecognizer, { /** * @namespace * @memberof PinchRecognizer */ defaults: { event: 'pinch', threshold: 0, pointers: 2 }, getTouchAction: function() { return [TOUCH_ACTION_NONE]; }, attrTest: function(input) { return this._super.attrTest.call(this, input) && (Math.abs(input.scale - 1) > this.options.threshold || this.state & STATE_BEGAN); }, emit: function(input) { this._super.emit.call(this, input); if (input.scale !== 1) { var inOut = input.scale < 1 ? 'in' : 'out'; this.manager.emit(this.options.event + inOut, input); } } }); /** * Press * Recognized when the pointer is down for x ms without any movement. * @constructor * @extends Recognizer */ function PressRecognizer() { Recognizer.apply(this, arguments); this._timer = null; this._input = null; } inherit(PressRecognizer, Recognizer, { /** * @namespace * @memberof PressRecognizer */ defaults: { event: 'press', pointers: 1, time: 500, // minimal time of the pointer to be pressed threshold: 5 // a minimal movement is ok, but keep it low }, getTouchAction: function() { return [TOUCH_ACTION_AUTO]; }, process: function(input) { var options = this.options; var validPointers = input.pointers.length === options.pointers; var validMovement = input.distance < options.threshold; var validTime = input.deltaTime > options.time; this._input = input; // we only allow little movement // and we've reached an end event, so a tap is possible if (!validMovement || !validPointers || (input.eventType & (INPUT_END | INPUT_CANCEL) && !validTime)) { this.reset(); } else if (input.eventType & INPUT_START) { this.reset(); this._timer = setTimeoutContext(function() { this.state = STATE_RECOGNIZED; this.tryEmit(); }, options.time, this); } else if (input.eventType & INPUT_END) { return STATE_RECOGNIZED; } return STATE_FAILED; }, reset: function() { clearTimeout(this._timer); }, emit: function(input) { if (this.state !== STATE_RECOGNIZED) { return; } if (input && (input.eventType & INPUT_END)) { this.manager.emit(this.options.event + 'up', input); } else { this._input.timeStamp = now(); this.manager.emit(this.options.event, this._input); } } }); /** * Rotate * Recognized when two or more pointer are moving in a circular motion. * @constructor * @extends AttrRecognizer */ function RotateRecognizer() { AttrRecognizer.apply(this, arguments); } inherit(RotateRecognizer, AttrRecognizer, { /** * @namespace * @memberof RotateRecognizer */ defaults: { event: 'rotate', threshold: 0, pointers: 2 }, getTouchAction: function() { return [TOUCH_ACTION_NONE]; }, attrTest: function(input) { return this._super.attrTest.call(this, input) && (Math.abs(input.rotation) > this.options.threshold || this.state & STATE_BEGAN); } }); /** * Swipe * Recognized when the pointer is moving fast (velocity), with enough distance in the allowed direction. * @constructor * @extends AttrRecognizer */ function SwipeRecognizer() { AttrRecognizer.apply(this, arguments); } inherit(SwipeRecognizer, AttrRecognizer, { /** * @namespace * @memberof SwipeRecognizer */ defaults: { event: 'swipe', threshold: 10, velocity: 0.65, direction: DIRECTION_HORIZONTAL | DIRECTION_VERTICAL, pointers: 1 }, getTouchAction: function() { return PanRecognizer.prototype.getTouchAction.call(this); }, attrTest: function(input) { var direction = this.options.direction; var velocity; if (direction & (DIRECTION_HORIZONTAL | DIRECTION_VERTICAL)) { velocity = input.velocity; } else if (direction & DIRECTION_HORIZONTAL) { velocity = input.velocityX; } else if (direction & DIRECTION_VERTICAL) { velocity = input.velocityY; } return this._super.attrTest.call(this, input) && direction & input.direction && input.distance > this.options.threshold && abs(velocity) > this.options.velocity && input.eventType & INPUT_END; }, emit: function(input) { var direction = directionStr(input.direction); if (direction) { this.manager.emit(this.options.event + direction, input); } this.manager.emit(this.options.event, input); } }); /** * A tap is ecognized when the pointer is doing a small tap/click. Multiple taps are recognized if they occur * between the given interval and position. The delay option can be used to recognize multi-taps without firing * a single tap. * * The eventData from the emitted event contains the property `tapCount`, which contains the amount of * multi-taps being recognized. * @constructor * @extends Recognizer */ function TapRecognizer() { Recognizer.apply(this, arguments); // previous time and center, // used for tap counting this.pTime = false; this.pCenter = false; this._timer = null; this._input = null; this.count = 0; } inherit(TapRecognizer, Recognizer, { /** * @namespace * @memberof PinchRecognizer */ defaults: { event: 'tap', pointers: 1, taps: 1, interval: 300, // max time between the multi-tap taps time: 250, // max time of the pointer to be down (like finger on the screen) threshold: 2, // a minimal movement is ok, but keep it low posThreshold: 10 // a multi-tap can be a bit off the initial position }, getTouchAction: function() { return [TOUCH_ACTION_MANIPULATION]; }, process: function(input) { var options = this.options; var validPointers = input.pointers.length === options.pointers; var validMovement = input.distance < options.threshold; var validTouchTime = input.deltaTime < options.time; this.reset(); if ((input.eventType & INPUT_START) && (this.count === 0)) { return this.failTimeout(); } // we only allow little movement // and we've reached an end event, so a tap is possible if (validMovement && validTouchTime && validPointers) { if (input.eventType != INPUT_END) { return this.failTimeout(); } var validInterval = this.pTime ? (input.timeStamp - this.pTime < options.interval) : true; var validMultiTap = !this.pCenter || getDistance(this.pCenter, input.center) < options.posThreshold; this.pTime = input.timeStamp; this.pCenter = input.center; if (!validMultiTap || !validInterval) { this.count = 1; } else { this.count += 1; } this._input = input; // if tap count matches we have recognized it, // else it has began recognizing... var tapCount = this.count % options.taps; if (tapCount === 0) { // no failing requirements, immediately trigger the tap event // or wait as long as the multitap interval to trigger if (!this.hasRequireFailures()) { return STATE_RECOGNIZED; } else { this._timer = setTimeoutContext(function() { this.state = STATE_RECOGNIZED; this.tryEmit(); }, options.interval, this); return STATE_BEGAN; } } } return STATE_FAILED; }, failTimeout: function() { this._timer = setTimeoutContext(function() { this.state = STATE_FAILED; }, this.options.interval, this); return STATE_FAILED; }, reset: function() { clearTimeout(this._timer); }, emit: function() { if (this.state == STATE_RECOGNIZED ) { this._input.tapCount = this.count; this.manager.emit(this.options.event, this._input); } } }); /** * Simple way to create an manager with a default set of recognizers. * @param {HTMLElement} element * @param {Object} [options] * @constructor */ function Hammer(element, options) { options = options || {}; options.recognizers = ifUndefined(options.recognizers, Hammer.defaults.preset); return new Manager(element, options); } /** * @const {string} */ Hammer.VERSION = '2.0.3'; /** * default settings * @namespace */ Hammer.defaults = { /** * set if DOM events are being triggered. * But this is slower and unused by simple implementations, so disabled by default. * @type {Boolean} * @default false */ domEvents: false, /** * The value for the touchAction property/fallback. * When set to `compute` it will magically set the correct value based on the added recognizers. * @type {String} * @default compute */ touchAction: TOUCH_ACTION_COMPUTE, /** * @type {Boolean} * @default true */ enable: true, /** * EXPERIMENTAL FEATURE -- can be removed/changed * Change the parent input target element. * If Null, then it is being set the to main element. * @type {Null|EventTarget} * @default null */ inputTarget: null, /** * force an input class * @type {Null|Function} * @default null */ inputClass: null, /** * Default recognizer setup when calling `Hammer()` * When creating a new Manager these will be skipped. * @type {Array} */ preset: [ // RecognizerClass, options, [recognizeWith, ...], [requireFailure, ...] [RotateRecognizer, { enable: false }], [PinchRecognizer, { enable: false }, ['rotate']], [SwipeRecognizer,{ direction: DIRECTION_HORIZONTAL }], [PanRecognizer, { direction: DIRECTION_HORIZONTAL }, ['swipe']], [TapRecognizer], [TapRecognizer, { event: 'doubletap', taps: 2 }, ['tap']], [PressRecognizer] ], /** * Some CSS properties can be used to improve the working of Hammer. * Add them to this method and they will be set when creating a new Manager. * @namespace */ cssProps: { /** * Disables text selection to improve the dragging gesture. Mainly for desktop browsers. * @type {String} * @default 'none' */ userSelect: 'none', /** * Disable the Windows Phone grippers when pressing an element. * @type {String} * @default 'none' */ touchSelect: 'none', /** * Disables the default callout shown when you touch and hold a touch target. * On iOS, when you touch and hold a touch target such as a link, Safari displays * a callout containing information about the link. This property allows you to disable that callout. * @type {String} * @default 'none' */ touchCallout: 'none', /** * Specifies whether zooming is enabled. Used by IE10> * @type {String} * @default 'none' */ contentZooming: 'none', /** * Specifies that an entire element should be draggable instead of its contents. Mainly for desktop browsers. * @type {String} * @default 'none' */ userDrag: 'none', /** * Overrides the highlight color shown when the user taps a link or a JavaScript * clickable element in iOS. This property obeys the alpha value, if specified. * @type {String} * @default 'rgba(0,0,0,0)' */ tapHighlightColor: 'rgba(0,0,0,0)' } }; var STOP = 1; var FORCED_STOP = 2; /** * Manager * @param {HTMLElement} element * @param {Object} [options] * @constructor */ function Manager(element, options) { options = options || {}; this.options = merge(options, Hammer.defaults); this.options.inputTarget = this.options.inputTarget || element; this.handlers = {}; this.session = {}; this.recognizers = []; this.element = element; this.input = createInputInstance(this); this.touchAction = new TouchAction(this, this.options.touchAction); toggleCssProps(this, true); each(options.recognizers, function(item) { var recognizer = this.add(new (item[0])(item[1])); item[2] && recognizer.recognizeWith(item[2]); item[3] && recognizer.requireFailure(item[3]); }, this); } Manager.prototype = { /** * set options * @param {Object} options * @returns {Manager} */ set: function(options) { extend(this.options, options); // Options that need a little more setup if (options.touchAction) { this.touchAction.update(); } if (options.inputTarget) { // Clean up existing event listeners and reinitialize this.input.destroy(); this.input.target = options.inputTarget; this.input.init(); } return this; }, /** * stop recognizing for this session. * This session will be discarded, when a new [input]start event is fired. * When forced, the recognizer cycle is stopped immediately. * @param {Boolean} [force] */ stop: function(force) { this.session.stopped = force ? FORCED_STOP : STOP; }, /** * run the recognizers! * called by the inputHandler function on every movement of the pointers (touches) * it walks through all the recognizers and tries to detect the gesture that is being made * @param {Object} inputData */ recognize: function(inputData) { var session = this.session; if (session.stopped) { return; } // run the touch-action polyfill this.touchAction.preventDefaults(inputData); var recognizer; var recognizers = this.recognizers; // this holds the recognizer that is being recognized. // so the recognizer's state needs to be BEGAN, CHANGED, ENDED or RECOGNIZED // if no recognizer is detecting a thing, it is set to `null` var curRecognizer = session.curRecognizer; // reset when the last recognizer is recognized // or when we're in a new session if (!curRecognizer || (curRecognizer && curRecognizer.state & STATE_RECOGNIZED)) { curRecognizer = session.curRecognizer = null; } var i = 0; while (i < recognizers.length) { recognizer = recognizers[i]; // find out if we are allowed try to recognize the input for this one. // 1. allow if the session is NOT forced stopped (see the .stop() method) // 2. allow if we still haven't recognized a gesture in this session, or the this recognizer is the one // that is being recognized. // 3. allow if the recognizer is allowed to run simultaneous with the current recognized recognizer. // this can be setup with the `recognizeWith()` method on the recognizer. if (session.stopped !== FORCED_STOP && ( // 1 !curRecognizer || recognizer == curRecognizer || // 2 recognizer.canRecognizeWith(curRecognizer))) { // 3 recognizer.recognize(inputData); } else { recognizer.reset(); } // if the recognizer has been recognizing the input as a valid gesture, we want to store this one as the // current active recognizer. but only if we don't already have an active recognizer if (!curRecognizer && recognizer.state & (STATE_BEGAN | STATE_CHANGED | STATE_ENDED)) { curRecognizer = session.curRecognizer = recognizer; } i++; } }, /** * get a recognizer by its event name. * @param {Recognizer|String} recognizer * @returns {Recognizer|Null} */ get: function(recognizer) { if (recognizer instanceof Recognizer) { return recognizer; } var recognizers = this.recognizers; for (var i = 0; i < recognizers.length; i++) { if (recognizers[i].options.event == recognizer) { return recognizers[i]; } } return null; }, /** * add a recognizer to the manager * existing recognizers with the same event name will be removed * @param {Recognizer} recognizer * @returns {Recognizer|Manager} */ add: function(recognizer) { if (invokeArrayArg(recognizer, 'add', this)) { return this; } // remove existing var existing = this.get(recognizer.options.event); if (existing) { this.remove(existing); } this.recognizers.push(recognizer); recognizer.manager = this; this.touchAction.update(); return recognizer; }, /** * remove a recognizer by name or instance * @param {Recognizer|String} recognizer * @returns {Manager} */ remove: function(recognizer) { if (invokeArrayArg(recognizer, 'remove', this)) { return this; } var recognizers = this.recognizers; recognizer = this.get(recognizer); recognizers.splice(inArray(recognizers, recognizer), 1); this.touchAction.update(); return this; }, /** * bind event * @param {String} events * @param {Function} handler * @returns {EventEmitter} this */ on: function(events, handler) { var handlers = this.handlers; each(splitStr(events), function(event) { handlers[event] = handlers[event] || []; handlers[event].push(handler); }); return this; }, /** * unbind event, leave emit blank to remove all handlers * @param {String} events * @param {Function} [handler] * @returns {EventEmitter} this */ off: function(events, handler) { var handlers = this.handlers; each(splitStr(events), function(event) { if (!handler) { delete handlers[event]; } else { handlers[event].splice(inArray(handlers[event], handler), 1); } }); return this; }, /** * emit event to the listeners * @param {String} event * @param {Object} data */ emit: function(event, data) { // we also want to trigger dom events if (this.options.domEvents) { triggerDomEvent(event, data); } // no handlers, so skip it all var handlers = this.handlers[event] && this.handlers[event].slice(); if (!handlers || !handlers.length) { return; } data.type = event; data.preventDefault = function() { data.srcEvent.preventDefault(); }; var i = 0; while (i < handlers.length) { handlers[i](data); i++; } }, /** * destroy the manager and unbinds all events * it doesn't unbind dom events, that is the user own responsibility */ destroy: function() { this.element && toggleCssProps(this, false); this.handlers = {}; this.session = {}; this.input.destroy(); this.element = null; } }; /** * add/remove the css properties as defined in manager.options.cssProps * @param {Manager} manager * @param {Boolean} add */ function toggleCssProps(manager, add) { var element = manager.element; each(manager.options.cssProps, function(value, name) { element.style[prefixed(element.style, name)] = add ? value : ''; }); } /** * trigger dom event * @param {String} event * @param {Object} data */ function triggerDomEvent(event, data) { var gestureEvent = document.createEvent('Event'); gestureEvent.initEvent(event, true, true); gestureEvent.gesture = data; data.target.dispatchEvent(gestureEvent); } extend(Hammer, { INPUT_START: INPUT_START, INPUT_MOVE: INPUT_MOVE, INPUT_END: INPUT_END, INPUT_CANCEL: INPUT_CANCEL, STATE_POSSIBLE: STATE_POSSIBLE, STATE_BEGAN: STATE_BEGAN, STATE_CHANGED: STATE_CHANGED, STATE_ENDED: STATE_ENDED, STATE_RECOGNIZED: STATE_RECOGNIZED, STATE_CANCELLED: STATE_CANCELLED, STATE_FAILED: STATE_FAILED, DIRECTION_NONE: DIRECTION_NONE, DIRECTION_LEFT: DIRECTION_LEFT, DIRECTION_RIGHT: DIRECTION_RIGHT, DIRECTION_UP: DIRECTION_UP, DIRECTION_DOWN: DIRECTION_DOWN, DIRECTION_HORIZONTAL: DIRECTION_HORIZONTAL, DIRECTION_VERTICAL: DIRECTION_VERTICAL, DIRECTION_ALL: DIRECTION_ALL, Manager: Manager, Input: Input, TouchAction: TouchAction, TouchInput: TouchInput, MouseInput: MouseInput, PointerEventInput: PointerEventInput, TouchMouseInput: TouchMouseInput, Recognizer: Recognizer, AttrRecognizer: AttrRecognizer, Tap: TapRecognizer, Pan: PanRecognizer, Swipe: SwipeRecognizer, Pinch: PinchRecognizer, Rotate: RotateRecognizer, Press: PressRecognizer, on: addEventListeners, off: removeEventListeners, each: each, merge: merge, extend: extend, inherit: inherit, bindFn: bindFn, prefixed: prefixed }); if (typeof define == TYPE_FUNCTION && define.amd) { define(function() { return Hammer; }); } else if (typeof module != 'undefined' && module.exports) { module.exports = Hammer; } else { window[exportName] = Hammer; } })(window, document, 'Hammer'); ;/*! * Select2 4.0.1 * https://select2.github.io * * Released under the MIT license * https://github.com/select2/select2/blob/master/LICENSE.md */ (function (factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else if (typeof exports === 'object') { // Node/CommonJS factory(require('jquery')); } else { // Browser globals factory(jQuery); } }(function (jQuery) { // This is needed so we can catch the AMD loader configuration and use it // The inner file should be wrapped (by `banner.start.js`) in a function that // returns the AMD loader references. var S2 = (function () { // Restore the Select2 AMD loader so it can be used // Needed mostly in the language files, where the loader is not inserted if (jQuery && jQuery.fn && jQuery.fn.select2 && jQuery.fn.select2.amd) { var S2 = jQuery.fn.select2.amd; } var S2;(function () { if (!S2 || !S2.requirejs) { if (!S2) { S2 = {}; } else { require = S2; } /** * @license almond 0.3.1 Copyright (c) 2011-2014, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/jrburke/almond for details */ //Going sloppy to avoid 'use strict' string cost, but strict practices should //be followed. /*jslint sloppy: true */ /*global setTimeout: false */ var requirejs, require, define; (function (undef) { var main, req, makeMap, handlers, defined = {}, waiting = {}, config = {}, defining = {}, hasOwn = Object.prototype.hasOwnProperty, aps = [].slice, jsSuffixRegExp = /\.js$/; function hasProp(obj, prop) { return hasOwn.call(obj, prop); } /** * Given a relative module name, like ./something, normalize it to * a real name that can be mapped to a path. * @param {String} name the relative name * @param {String} baseName a real name that the name arg is relative * to. * @returns {String} normalized name */ function normalize(name, baseName) { var nameParts, nameSegment, mapValue, foundMap, lastIndex, foundI, foundStarMap, starI, i, j, part, baseParts = baseName && baseName.split("/"), map = config.map, starMap = (map && map['*']) || {}; //Adjust any relative paths. if (name && name.charAt(0) === ".") { //If have a base name, try to normalize against it, //otherwise, assume it is a top-level require that will //be relative to baseUrl in the end. if (baseName) { name = name.split('/'); lastIndex = name.length - 1; // Node .js allowance: if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) { name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, ''); } //Lop off the last part of baseParts, so that . matches the //"directory" and not name of the baseName's module. For instance, //baseName of "one/two/three", maps to "one/two/three.js", but we //want the directory, "one/two" for this normalization. name = baseParts.slice(0, baseParts.length - 1).concat(name); //start trimDots for (i = 0; i < name.length; i += 1) { part = name[i]; if (part === ".") { name.splice(i, 1); i -= 1; } else if (part === "..") { if (i === 1 && (name[2] === '..' || name[0] === '..')) { //End of the line. Keep at least one non-dot //path segment at the front so it can be mapped //correctly to disk. Otherwise, there is likely //no path mapping for a path starting with '..'. //This can still fail, but catches the most reasonable //uses of .. break; } else if (i > 0) { name.splice(i - 1, 2); i -= 2; } } } //end trimDots name = name.join("/"); } else if (name.indexOf('./') === 0) { // No baseName, so this is ID is resolved relative // to baseUrl, pull off the leading dot. name = name.substring(2); } } //Apply map config if available. if ((baseParts || starMap) && map) { nameParts = name.split('/'); for (i = nameParts.length; i > 0; i -= 1) { nameSegment = nameParts.slice(0, i).join("/"); if (baseParts) { //Find the longest baseName segment match in the config. //So, do joins on the biggest to smallest lengths of baseParts. for (j = baseParts.length; j > 0; j -= 1) { mapValue = map[baseParts.slice(0, j).join('/')]; //baseName segment has config, find if it has one for //this name. if (mapValue) { mapValue = mapValue[nameSegment]; if (mapValue) { //Match, update name to the new value. foundMap = mapValue; foundI = i; break; } } } } if (foundMap) { break; } //Check for a star map match, but just hold on to it, //if there is a shorter segment match later in a matching //config, then favor over this star map. if (!foundStarMap && starMap && starMap[nameSegment]) { foundStarMap = starMap[nameSegment]; starI = i; } } if (!foundMap && foundStarMap) { foundMap = foundStarMap; foundI = starI; } if (foundMap) { nameParts.splice(0, foundI, foundMap); name = nameParts.join('/'); } } return name; } function makeRequire(relName, forceSync) { return function () { //A version of a require function that passes a moduleName //value for items that may need to //look up paths relative to the moduleName var args = aps.call(arguments, 0); //If first arg is not require('string'), and there is only //one arg, it is the array form without a callback. Insert //a null so that the following concat is correct. if (typeof args[0] !== 'string' && args.length === 1) { args.push(null); } return req.apply(undef, args.concat([relName, forceSync])); }; } function makeNormalize(relName) { return function (name) { return normalize(name, relName); }; } function makeLoad(depName) { return function (value) { defined[depName] = value; }; } function callDep(name) { if (hasProp(waiting, name)) { var args = waiting[name]; delete waiting[name]; defining[name] = true; main.apply(undef, args); } if (!hasProp(defined, name) && !hasProp(defining, name)) { throw new Error('No ' + name); } return defined[name]; } //Turns a plugin!resource to [plugin, resource] //with the plugin being undefined if the name //did not have a plugin prefix. function splitPrefix(name) { var prefix, index = name ? name.indexOf('!') : -1; if (index > -1) { prefix = name.substring(0, index); name = name.substring(index + 1, name.length); } return [prefix, name]; } /** * Makes a name map, normalizing the name, and using a plugin * for normalization if necessary. Grabs a ref to plugin * too, as an optimization. */ makeMap = function (name, relName) { var plugin, parts = splitPrefix(name), prefix = parts[0]; name = parts[1]; if (prefix) { prefix = normalize(prefix, relName); plugin = callDep(prefix); } //Normalize according if (prefix) { if (plugin && plugin.normalize) { name = plugin.normalize(name, makeNormalize(relName)); } else { name = normalize(name, relName); } } else { name = normalize(name, relName); parts = splitPrefix(name); prefix = parts[0]; name = parts[1]; if (prefix) { plugin = callDep(prefix); } } //Using ridiculous property names for space reasons return { f: prefix ? prefix + '!' + name : name, //fullName n: name, pr: prefix, p: plugin }; }; function makeConfig(name) { return function () { return (config && config.config && config.config[name]) || {}; }; } handlers = { require: function (name) { return makeRequire(name); }, exports: function (name) { var e = defined[name]; if (typeof e !== 'undefined') { return e; } else { return (defined[name] = {}); } }, module: function (name) { return { id: name, uri: '', exports: defined[name], config: makeConfig(name) }; } }; main = function (name, deps, callback, relName) { var cjsModule, depName, ret, map, i, args = [], callbackType = typeof callback, usingExports; //Use name if no relName relName = relName || name; //Call the callback to define the module, if necessary. if (callbackType === 'undefined' || callbackType === 'function') { //Pull out the defined dependencies and pass the ordered //values to the callback. //Default to [require, exports, module] if no deps deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps; for (i = 0; i < deps.length; i += 1) { map = makeMap(deps[i], relName); depName = map.f; //Fast path CommonJS standard dependencies. if (depName === "require") { args[i] = handlers.require(name); } else if (depName === "exports") { //CommonJS module spec 1.1 args[i] = handlers.exports(name); usingExports = true; } else if (depName === "module") { //CommonJS module spec 1.1 cjsModule = args[i] = handlers.module(name); } else if (hasProp(defined, depName) || hasProp(waiting, depName) || hasProp(defining, depName)) { args[i] = callDep(depName); } else if (map.p) { map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {}); args[i] = defined[depName]; } else { throw new Error(name + ' missing ' + depName); } } ret = callback ? callback.apply(defined[name], args) : undefined; if (name) { //If setting exports via "module" is in play, //favor that over return value and exports. After that, //favor a non-undefined return value over exports use. if (cjsModule && cjsModule.exports !== undef && cjsModule.exports !== defined[name]) { defined[name] = cjsModule.exports; } else if (ret !== undef || !usingExports) { //Use the return value from the function. defined[name] = ret; } } } else if (name) { //May just be an object definition for the module. Only //worry about defining if have a module name. defined[name] = callback; } }; requirejs = require = req = function (deps, callback, relName, forceSync, alt) { if (typeof deps === "string") { if (handlers[deps]) { //callback in this case is really relName return handlers[deps](callback); } //Just return the module wanted. In this scenario, the //deps arg is the module name, and second arg (if passed) //is just the relName. //Normalize module name, if it contains . or .. return callDep(makeMap(deps, callback).f); } else if (!deps.splice) { //deps is a config object, not an array. config = deps; if (config.deps) { req(config.deps, config.callback); } if (!callback) { return; } if (callback.splice) { //callback is an array, which means it is a dependency list. //Adjust args if there are dependencies deps = callback; callback = relName; relName = null; } else { deps = undef; } } //Support require(['a']) callback = callback || function () {}; //If relName is a function, it is an errback handler, //so remove it. if (typeof relName === 'function') { relName = forceSync; forceSync = alt; } //Simulate async callback; if (forceSync) { main(undef, deps, callback, relName); } else { //Using a non-zero value because of concern for what old browsers //do, and latest browsers "upgrade" to 4 if lower value is used: //http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout: //If want a value immediately, use require('id') instead -- something //that works in almond on the global level, but not guaranteed and //unlikely to work in other AMD implementations. setTimeout(function () { main(undef, deps, callback, relName); }, 4); } return req; }; /** * Just drops the config on the floor, but returns req in case * the config return value is used. */ req.config = function (cfg) { return req(cfg); }; /** * Expose module registry for debugging and tooling */ requirejs._defined = defined; define = function (name, deps, callback) { if (typeof name !== 'string') { throw new Error('See almond README: incorrect module build, no module name'); } //This module may not have dependencies if (!deps.splice) { //deps is not an array, so probably means //an object literal or factory function for //the value. Adjust args. callback = deps; deps = []; } if (!hasProp(defined, name) && !hasProp(waiting, name)) { waiting[name] = [name, deps, callback]; } }; define.amd = { jQuery: true }; }()); S2.requirejs = requirejs;S2.require = require;S2.define = define; } }()); S2.define("almond", function(){}); /* global jQuery:false, $:false */ S2.define('jquery',[],function () { var _$ = jQuery || $; if (_$ == null && console && console.error) { console.error( 'Select2: An instance of jQuery or a jQuery-compatible library was not ' + 'found. Make sure that you are including jQuery before Select2 on your ' + 'web page.' ); } return _$; }); S2.define('select2/utils',[ 'jquery' ], function ($) { var Utils = {}; Utils.Extend = function (ChildClass, SuperClass) { var __hasProp = {}.hasOwnProperty; function BaseConstructor () { this.constructor = ChildClass; } for (var key in SuperClass) { if (__hasProp.call(SuperClass, key)) { ChildClass[key] = SuperClass[key]; } } BaseConstructor.prototype = SuperClass.prototype; ChildClass.prototype = new BaseConstructor(); ChildClass.__super__ = SuperClass.prototype; return ChildClass; }; function getMethods (theClass) { var proto = theClass.prototype; var methods = []; for (var methodName in proto) { var m = proto[methodName]; if (typeof m !== 'function') { continue; } if (methodName === 'constructor') { continue; } methods.push(methodName); } return methods; } Utils.Decorate = function (SuperClass, DecoratorClass) { var decoratedMethods = getMethods(DecoratorClass); var superMethods = getMethods(SuperClass); function DecoratedClass () { var unshift = Array.prototype.unshift; var argCount = DecoratorClass.prototype.constructor.length; var calledConstructor = SuperClass.prototype.constructor; if (argCount > 0) { unshift.call(arguments, SuperClass.prototype.constructor); calledConstructor = DecoratorClass.prototype.constructor; } calledConstructor.apply(this, arguments); } DecoratorClass.displayName = SuperClass.displayName; function ctr () { this.constructor = DecoratedClass; } DecoratedClass.prototype = new ctr(); for (var m = 0; m < superMethods.length; m++) { var superMethod = superMethods[m]; DecoratedClass.prototype[superMethod] = SuperClass.prototype[superMethod]; } var calledMethod = function (methodName) { // Stub out the original method if it's not decorating an actual method var originalMethod = function () {}; if (methodName in DecoratedClass.prototype) { originalMethod = DecoratedClass.prototype[methodName]; } var decoratedMethod = DecoratorClass.prototype[methodName]; return function () { var unshift = Array.prototype.unshift; unshift.call(arguments, originalMethod); return decoratedMethod.apply(this, arguments); }; }; for (var d = 0; d < decoratedMethods.length; d++) { var decoratedMethod = decoratedMethods[d]; DecoratedClass.prototype[decoratedMethod] = calledMethod(decoratedMethod); } return DecoratedClass; }; var Observable = function () { this.listeners = {}; }; Observable.prototype.on = function (event, callback) { this.listeners = this.listeners || {}; if (event in this.listeners) { this.listeners[event].push(callback); } else { this.listeners[event] = [callback]; } }; Observable.prototype.trigger = function (event) { var slice = Array.prototype.slice; this.listeners = this.listeners || {}; if (event in this.listeners) { this.invoke(this.listeners[event], slice.call(arguments, 1)); } if ('*' in this.listeners) { this.invoke(this.listeners['*'], arguments); } }; Observable.prototype.invoke = function (listeners, params) { for (var i = 0, len = listeners.length; i < len; i++) { listeners[i].apply(this, params); } }; Utils.Observable = Observable; Utils.generateChars = function (length) { var chars = ''; for (var i = 0; i < length; i++) { var randomChar = Math.floor(Math.random() * 36); chars += randomChar.toString(36); } return chars; }; Utils.bind = function (func, context) { return function () { func.apply(context, arguments); }; }; Utils._convertData = function (data) { for (var originalKey in data) { var keys = originalKey.split('-'); var dataLevel = data; if (keys.length === 1) { continue; } for (var k = 0; k < keys.length; k++) { var key = keys[k]; // Lowercase the first letter // By default, dash-separated becomes camelCase key = key.substring(0, 1).toLowerCase() + key.substring(1); if (!(key in dataLevel)) { dataLevel[key] = {}; } if (k == keys.length - 1) { dataLevel[key] = data[originalKey]; } dataLevel = dataLevel[key]; } delete data[originalKey]; } return data; }; Utils.hasScroll = function (index, el) { // Adapted from the function created by @ShadowScripter // and adapted by @BillBarry on the Stack Exchange Code Review website. // The original code can be found at // http://codereview.stackexchange.com/q/13338 // and was designed to be used with the Sizzle selector engine. var $el = $(el); var overflowX = el.style.overflowX; var overflowY = el.style.overflowY; //Check both x and y declarations if (overflowX === overflowY && (overflowY === 'hidden' || overflowY === 'visible')) { return false; } if (overflowX === 'scroll' || overflowY === 'scroll') { return true; } return ($el.innerHeight() < el.scrollHeight || $el.innerWidth() < el.scrollWidth); }; Utils.escapeMarkup = function (markup) { var replaceMap = { '\\': '\', '&': '&', '<': '<', '>': '>', '"': '"', '\'': ''', '/': '/' }; // Do not try to escape the markup if it's not a string if (typeof markup !== 'string') { return markup; } return String(markup).replace(/[&<>"'\/\\]/g, function (match) { return replaceMap[match]; }); }; // Append an array of jQuery nodes to a given element. Utils.appendMany = function ($element, $nodes) { // jQuery 1.7.x does not support $.fn.append() with an array // Fall back to a jQuery object collection using $.fn.add() if ($.fn.jquery.substr(0, 3) === '1.7') { var $jqNodes = $(); $.map($nodes, function (node) { $jqNodes = $jqNodes.add(node); }); $nodes = $jqNodes; } $element.append($nodes); }; return Utils; }); S2.define('select2/results',[ 'jquery', './utils' ], function ($, Utils) { function Results ($element, options, dataAdapter) { this.$element = $element; this.data = dataAdapter; this.options = options; Results.__super__.constructor.call(this); } Utils.Extend(Results, Utils.Observable); Results.prototype.render = function () { var $results = $( '' ); if (this.options.get('multiple')) { $results.attr('aria-multiselectable', 'true'); } this.$results = $results; return $results; }; Results.prototype.clear = function () { this.$results.empty(); }; Results.prototype.displayMessage = function (params) { var escapeMarkup = this.options.get('escapeMarkup'); this.clear(); this.hideLoading(); var $message = $( '
  • ' ); var message = this.options.get('translations').get(params.message); $message.append( escapeMarkup( message(params.args) ) ); $message[0].className += ' select2-results__message'; this.$results.append($message); }; Results.prototype.hideMessages = function () { this.$results.find('.select2-results__message').remove(); }; Results.prototype.append = function (data) { this.hideLoading(); var $options = []; if (data.results == null || data.results.length === 0) { if (this.$results.children().length === 0) { this.trigger('results:message', { message: 'noResults' }); } return; } data.results = this.sort(data.results); for (var d = 0; d < data.results.length; d++) { var item = data.results[d]; var $option = this.option(item); $options.push($option); } this.$results.append($options); }; Results.prototype.position = function ($results, $dropdown) { var $resultsContainer = $dropdown.find('.select2-results'); $resultsContainer.append($results); }; Results.prototype.sort = function (data) { var sorter = this.options.get('sorter'); return sorter(data); }; Results.prototype.setClasses = function () { var self = this; this.data.current(function (selected) { var selectedIds = $.map(selected, function (s) { return s.id.toString(); }); var $options = self.$results .find('.select2-results__option[aria-selected]'); $options.each(function () { var $option = $(this); var item = $.data(this, 'data'); // id needs to be converted to a string when comparing var id = '' + item.id; if ((item.element != null && item.element.selected) || (item.element == null && $.inArray(id, selectedIds) > -1)) { $option.attr('aria-selected', 'true'); } else { $option.attr('aria-selected', 'false'); } }); var $selected = $options.filter('[aria-selected=true]'); // Check if there are any selected options if ($selected.length > 0) { // If there are selected options, highlight the first $selected.first().trigger('mouseenter'); } else { // If there are no selected options, highlight the first option // in the dropdown $options.first().trigger('mouseenter'); } }); }; Results.prototype.showLoading = function (params) { this.hideLoading(); var loadingMore = this.options.get('translations').get('searching'); var loading = { disabled: true, loading: true, text: loadingMore(params) }; var $loading = this.option(loading); $loading.className += ' loading-results'; this.$results.prepend($loading); }; Results.prototype.hideLoading = function () { this.$results.find('.loading-results').remove(); }; Results.prototype.option = function (data) { var option = document.createElement('li'); option.className = 'select2-results__option'; var attrs = { 'role': 'treeitem', 'aria-selected': 'false' }; if (data.disabled) { delete attrs['aria-selected']; attrs['aria-disabled'] = 'true'; } if (data.id == null) { delete attrs['aria-selected']; } if (data._resultId != null) { option.id = data._resultId; } if (data.title) { option.title = data.title; } if (data.children) { attrs.role = 'group'; attrs['aria-label'] = data.text; delete attrs['aria-selected']; } for (var attr in attrs) { var val = attrs[attr]; option.setAttribute(attr, val); } if (data.children) { var $option = $(option); var label = document.createElement('strong'); label.className = 'select2-results__group'; var $label = $(label); this.template(data, label); var $children = []; for (var c = 0; c < data.children.length; c++) { var child = data.children[c]; var $child = this.option(child); $children.push($child); } var $childrenContainer = $('', { 'class': 'select2-results__options select2-results__options--nested' }); $childrenContainer.append($children); $option.append(label); $option.append($childrenContainer); } else { this.template(data, option); } $.data(option, 'data', data); return option; }; Results.prototype.bind = function (container, $container) { var self = this; var id = container.id + '-results'; this.$results.attr('id', id); container.on('results:all', function (params) { self.clear(); self.append(params.data); if (container.isOpen()) { self.setClasses(); } }); container.on('results:append', function (params) { self.append(params.data); if (container.isOpen()) { self.setClasses(); } }); container.on('query', function (params) { self.hideMessages(); self.showLoading(params); }); container.on('select', function () { if (!container.isOpen()) { return; } self.setClasses(); }); container.on('unselect', function () { if (!container.isOpen()) { return; } self.setClasses(); }); container.on('open', function () { // When the dropdown is open, aria-expended="true" self.$results.attr('aria-expanded', 'true'); self.$results.attr('aria-hidden', 'false'); self.setClasses(); self.ensureHighlightVisible(); }); container.on('close', function () { // When the dropdown is closed, aria-expended="false" self.$results.attr('aria-expanded', 'false'); self.$results.attr('aria-hidden', 'true'); self.$results.removeAttr('aria-activedescendant'); }); container.on('results:toggle', function () { var $highlighted = self.getHighlightedResults(); if ($highlighted.length === 0) { return; } $highlighted.trigger('mouseup'); }); container.on('results:select', function () { var $highlighted = self.getHighlightedResults(); if ($highlighted.length === 0) { return; } var data = $highlighted.data('data'); if ($highlighted.attr('aria-selected') == 'true') { self.trigger('close', {}); } else { self.trigger('select', { data: data }); } }); container.on('results:previous', function () { var $highlighted = self.getHighlightedResults(); var $options = self.$results.find('[aria-selected]'); var currentIndex = $options.index($highlighted); // If we are already at te top, don't move further if (currentIndex === 0) { return; } var nextIndex = currentIndex - 1; // If none are highlighted, highlight the first if ($highlighted.length === 0) { nextIndex = 0; } var $next = $options.eq(nextIndex); $next.trigger('mouseenter'); var currentOffset = self.$results.offset().top; var nextTop = $next.offset().top; var nextOffset = self.$results.scrollTop() + (nextTop - currentOffset); if (nextIndex === 0) { self.$results.scrollTop(0); } else if (nextTop - currentOffset < 0) { self.$results.scrollTop(nextOffset); } }); container.on('results:next', function () { var $highlighted = self.getHighlightedResults(); var $options = self.$results.find('[aria-selected]'); var currentIndex = $options.index($highlighted); var nextIndex = currentIndex + 1; // If we are at the last option, stay there if (nextIndex >= $options.length) { return; } var $next = $options.eq(nextIndex); $next.trigger('mouseenter'); var currentOffset = self.$results.offset().top + self.$results.outerHeight(false); var nextBottom = $next.offset().top + $next.outerHeight(false); var nextOffset = self.$results.scrollTop() + nextBottom - currentOffset; if (nextIndex === 0) { self.$results.scrollTop(0); } else if (nextBottom > currentOffset) { self.$results.scrollTop(nextOffset); } }); container.on('results:focus', function (params) { params.element.addClass('select2-results__option--highlighted'); }); container.on('results:message', function (params) { self.displayMessage(params); }); if ($.fn.mousewheel) { this.$results.on('mousewheel', function (e) { var top = self.$results.scrollTop(); var bottom = ( self.$results.get(0).scrollHeight - self.$results.scrollTop() + e.deltaY ); var isAtTop = e.deltaY > 0 && top - e.deltaY <= 0; var isAtBottom = e.deltaY < 0 && bottom <= self.$results.height(); if (isAtTop) { self.$results.scrollTop(0); e.preventDefault(); e.stopPropagation(); } else if (isAtBottom) { self.$results.scrollTop( self.$results.get(0).scrollHeight - self.$results.height() ); e.preventDefault(); e.stopPropagation(); } }); } this.$results.on('mouseup', '.select2-results__option[aria-selected]', function (evt) { var $this = $(this); var data = $this.data('data'); if ($this.attr('aria-selected') === 'true') { if (self.options.get('multiple')) { self.trigger('unselect', { originalEvent: evt, data: data }); } else { self.trigger('close', {}); } return; } self.trigger('select', { originalEvent: evt, data: data }); }); this.$results.on('mouseenter', '.select2-results__option[aria-selected]', function (evt) { var data = $(this).data('data'); self.getHighlightedResults() .removeClass('select2-results__option--highlighted'); self.trigger('results:focus', { data: data, element: $(this) }); }); }; Results.prototype.getHighlightedResults = function () { var $highlighted = this.$results .find('.select2-results__option--highlighted'); return $highlighted; }; Results.prototype.destroy = function () { this.$results.remove(); }; Results.prototype.ensureHighlightVisible = function () { var $highlighted = this.getHighlightedResults(); if ($highlighted.length === 0) { return; } var $options = this.$results.find('[aria-selected]'); var currentIndex = $options.index($highlighted); var currentOffset = this.$results.offset().top; var nextTop = $highlighted.offset().top; var nextOffset = this.$results.scrollTop() + (nextTop - currentOffset); var offsetDelta = nextTop - currentOffset; nextOffset -= $highlighted.outerHeight(false) * 2; if (currentIndex <= 2) { this.$results.scrollTop(0); } else if (offsetDelta > this.$results.outerHeight() || offsetDelta < 0) { this.$results.scrollTop(nextOffset); } }; Results.prototype.template = function (result, container) { var template = this.options.get('templateResult'); var escapeMarkup = this.options.get('escapeMarkup'); var content = template(result, container); if (content == null) { container.style.display = 'none'; } else if (typeof content === 'string') { container.innerHTML = escapeMarkup(content); } else { $(container).append(content); } }; return Results; }); S2.define('select2/keys',[ ], function () { var KEYS = { BACKSPACE: 8, TAB: 9, ENTER: 13, SHIFT: 16, CTRL: 17, ALT: 18, ESC: 27, SPACE: 32, PAGE_UP: 33, PAGE_DOWN: 34, END: 35, HOME: 36, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, DELETE: 46 }; return KEYS; }); S2.define('select2/selection/base',[ 'jquery', '../utils', '../keys' ], function ($, Utils, KEYS) { function BaseSelection ($element, options) { this.$element = $element; this.options = options; BaseSelection.__super__.constructor.call(this); } Utils.Extend(BaseSelection, Utils.Observable); BaseSelection.prototype.render = function () { var $selection = $( '' ); this._tabindex = 0; if (this.$element.data('old-tabindex') != null) { this._tabindex = this.$element.data('old-tabindex'); } else if (this.$element.attr('tabindex') != null) { this._tabindex = this.$element.attr('tabindex'); } $selection.attr('title', this.$element.attr('title')); $selection.attr('tabindex', this._tabindex); this.$selection = $selection; return $selection; }; BaseSelection.prototype.bind = function (container, $container) { var self = this; var id = container.id + '-container'; var resultsId = container.id + '-results'; this.container = container; this.$selection.on('focus', function (evt) { self.trigger('focus', evt); }); this.$selection.on('blur', function (evt) { self._handleBlur(evt); }); this.$selection.on('keydown', function (evt) { self.trigger('keypress', evt); if (evt.which === KEYS.SPACE) { evt.preventDefault(); } }); container.on('results:focus', function (params) { self.$selection.attr('aria-activedescendant', params.data._resultId); }); container.on('selection:update', function (params) { self.update(params.data); }); container.on('open', function () { // When the dropdown is open, aria-expanded="true" self.$selection.attr('aria-expanded', 'true'); self.$selection.attr('aria-owns', resultsId); self._attachCloseHandler(container); }); container.on('close', function () { // When the dropdown is closed, aria-expanded="false" self.$selection.attr('aria-expanded', 'false'); self.$selection.removeAttr('aria-activedescendant'); self.$selection.removeAttr('aria-owns'); self.$selection.focus(); self._detachCloseHandler(container); }); container.on('enable', function () { self.$selection.attr('tabindex', self._tabindex); }); container.on('disable', function () { self.$selection.attr('tabindex', '-1'); }); }; BaseSelection.prototype._handleBlur = function (evt) { var self = this; // This needs to be delayed as the active element is the body when the tab // key is pressed, possibly along with others. window.setTimeout(function () { // Don't trigger `blur` if the focus is still in the selection if ( (document.activeElement == self.$selection[0]) || ($.contains(self.$selection[0], document.activeElement)) ) { return; } self.trigger('blur', evt); }, 1); }; BaseSelection.prototype._attachCloseHandler = function (container) { var self = this; $(document.body).on('mousedown.select2.' + container.id, function (e) { var $target = $(e.target); var $select = $target.closest('.select2'); var $all = $('.select2.select2-container--open'); $all.each(function () { var $this = $(this); if (this == $select[0]) { return; } var $element = $this.data('element'); $element.select2('close'); }); }); }; BaseSelection.prototype._detachCloseHandler = function (container) { $(document.body).off('mousedown.select2.' + container.id); }; BaseSelection.prototype.position = function ($selection, $container) { var $selectionContainer = $container.find('.selection'); $selectionContainer.append($selection); }; BaseSelection.prototype.destroy = function () { this._detachCloseHandler(this.container); }; BaseSelection.prototype.update = function (data) { throw new Error('The `update` method must be defined in child classes.'); }; return BaseSelection; }); S2.define('select2/selection/single',[ 'jquery', './base', '../utils', '../keys' ], function ($, BaseSelection, Utils, KEYS) { function SingleSelection () { SingleSelection.__super__.constructor.apply(this, arguments); } Utils.Extend(SingleSelection, BaseSelection); SingleSelection.prototype.render = function () { var $selection = SingleSelection.__super__.render.call(this); $selection.addClass('select2-selection--single'); $selection.html( '' + '' + '' + '' ); return $selection; }; SingleSelection.prototype.bind = function (container, $container) { var self = this; SingleSelection.__super__.bind.apply(this, arguments); var id = container.id + '-container'; this.$selection.find('.select2-selection__rendered').attr('id', id); this.$selection.attr('aria-labelledby', id); this.$selection.on('mousedown', function (evt) { // Only respond to left clicks if (evt.which !== 1) { return; } self.trigger('toggle', { originalEvent: evt }); }); this.$selection.on('focus', function (evt) { // User focuses on the container }); this.$selection.on('blur', function (evt) { // User exits the container }); container.on('selection:update', function (params) { self.update(params.data); }); }; SingleSelection.prototype.clear = function () { this.$selection.find('.select2-selection__rendered').empty(); }; SingleSelection.prototype.display = function (data, container) { var template = this.options.get('templateSelection'); var escapeMarkup = this.options.get('escapeMarkup'); return escapeMarkup(template(data, container)); }; SingleSelection.prototype.selectionContainer = function () { return $(''); }; SingleSelection.prototype.update = function (data) { if (data.length === 0) { this.clear(); return; } var selection = data[0]; var $rendered = this.$selection.find('.select2-selection__rendered'); var formatted = this.display(selection, $rendered); $rendered.empty().append(formatted); $rendered.prop('title', selection.title || selection.text); }; return SingleSelection; }); S2.define('select2/selection/multiple',[ 'jquery', './base', '../utils' ], function ($, BaseSelection, Utils) { function MultipleSelection ($element, options) { MultipleSelection.__super__.constructor.apply(this, arguments); } Utils.Extend(MultipleSelection, BaseSelection); MultipleSelection.prototype.render = function () { var $selection = MultipleSelection.__super__.render.call(this); $selection.addClass('select2-selection--multiple'); $selection.html( '' ); return $selection; }; MultipleSelection.prototype.bind = function (container, $container) { var self = this; MultipleSelection.__super__.bind.apply(this, arguments); this.$selection.on('click', function (evt) { self.trigger('toggle', { originalEvent: evt }); }); this.$selection.on( 'click', '.select2-selection__choice__remove', function (evt) { // Ignore the event if it is disabled if (self.options.get('disabled')) { return; } var $remove = $(this); var $selection = $remove.parent(); var data = $selection.data('data'); self.trigger('unselect', { originalEvent: evt, data: data }); } ); }; MultipleSelection.prototype.clear = function () { this.$selection.find('.select2-selection__rendered').empty(); }; MultipleSelection.prototype.display = function (data, container) { var template = this.options.get('templateSelection'); var escapeMarkup = this.options.get('escapeMarkup'); return escapeMarkup(template(data, container)); }; MultipleSelection.prototype.selectionContainer = function () { var $container = $( '
  • ' + '' + '×' + '' + '
  • ' ); return $container; }; MultipleSelection.prototype.update = function (data) { this.clear(); if (data.length === 0) { return; } var $selections = []; for (var d = 0; d < data.length; d++) { var selection = data[d]; var $selection = this.selectionContainer(); var formatted = this.display(selection, $selection); $selection.append(formatted); $selection.prop('title', selection.title || selection.text); $selection.data('data', selection); $selections.push($selection); } var $rendered = this.$selection.find('.select2-selection__rendered'); Utils.appendMany($rendered, $selections); }; return MultipleSelection; }); S2.define('select2/selection/placeholder',[ '../utils' ], function (Utils) { function Placeholder (decorated, $element, options) { this.placeholder = this.normalizePlaceholder(options.get('placeholder')); decorated.call(this, $element, options); } Placeholder.prototype.normalizePlaceholder = function (_, placeholder) { if (typeof placeholder === 'string') { placeholder = { id: '', text: placeholder }; } return placeholder; }; Placeholder.prototype.createPlaceholder = function (decorated, placeholder) { var $placeholder = this.selectionContainer(); $placeholder.html(this.display(placeholder)); $placeholder.addClass('select2-selection__placeholder') .removeClass('select2-selection__choice'); return $placeholder; }; Placeholder.prototype.update = function (decorated, data) { var singlePlaceholder = ( data.length == 1 && data[0].id != this.placeholder.id ); var multipleSelections = data.length > 1; if (multipleSelections || singlePlaceholder) { return decorated.call(this, data); } this.clear(); var $placeholder = this.createPlaceholder(this.placeholder); this.$selection.find('.select2-selection__rendered').append($placeholder); }; return Placeholder; }); S2.define('select2/selection/allowClear',[ 'jquery', '../keys' ], function ($, KEYS) { function AllowClear () { } AllowClear.prototype.bind = function (decorated, container, $container) { var self = this; decorated.call(this, container, $container); if (this.placeholder == null) { if (this.options.get('debug') && window.console && console.error) { console.error( 'Select2: The `allowClear` option should be used in combination ' + 'with the `placeholder` option.' ); } } this.$selection.on('mousedown', '.select2-selection__clear', function (evt) { self._handleClear(evt); }); container.on('keypress', function (evt) { self._handleKeyboardClear(evt, container); }); }; AllowClear.prototype._handleClear = function (_, evt) { // Ignore the event if it is disabled if (this.options.get('disabled')) { return; } var $clear = this.$selection.find('.select2-selection__clear'); // Ignore the event if nothing has been selected if ($clear.length === 0) { return; } evt.stopPropagation(); var data = $clear.data('data'); for (var d = 0; d < data.length; d++) { var unselectData = { data: data[d] }; // Trigger the `unselect` event, so people can prevent it from being // cleared. this.trigger('unselect', unselectData); // If the event was prevented, don't clear it out. if (unselectData.prevented) { return; } } this.$element.val(this.placeholder.id).trigger('change'); this.trigger('toggle', {}); }; AllowClear.prototype._handleKeyboardClear = function (_, evt, container) { if (container.isOpen()) { return; } if (evt.which == KEYS.DELETE || evt.which == KEYS.BACKSPACE) { this._handleClear(evt); } }; AllowClear.prototype.update = function (decorated, data) { decorated.call(this, data); if (this.$selection.find('.select2-selection__placeholder').length > 0 || data.length === 0) { return; } var $remove = $( '' + '×' + '' ); $remove.data('data', data); this.$selection.find('.select2-selection__rendered').prepend($remove); }; return AllowClear; }); S2.define('select2/selection/search',[ 'jquery', '../utils', '../keys' ], function ($, Utils, KEYS) { function Search (decorated, $element, options) { decorated.call(this, $element, options); } Search.prototype.render = function (decorated) { var $search = $( '' ); this.$searchContainer = $search; this.$search = $search.find('input'); var $rendered = decorated.call(this); this._transferTabIndex(); return $rendered; }; Search.prototype.bind = function (decorated, container, $container) { var self = this; decorated.call(this, container, $container); container.on('open', function () { self.$search.trigger('focus'); }); container.on('close', function () { self.$search.val(''); self.$search.removeAttr('aria-activedescendant'); self.$search.trigger('focus'); }); container.on('enable', function () { self.$search.prop('disabled', false); self._transferTabIndex(); }); container.on('disable', function () { self.$search.prop('disabled', true); }); container.on('focus', function (evt) { self.$search.trigger('focus'); }); container.on('results:focus', function (params) { self.$search.attr('aria-activedescendant', params.id); }); this.$selection.on('focusin', '.select2-search--inline', function (evt) { self.trigger('focus', evt); }); this.$selection.on('focusout', '.select2-search--inline', function (evt) { self._handleBlur(evt); }); this.$selection.on('keydown', '.select2-search--inline', function (evt) { evt.stopPropagation(); self.trigger('keypress', evt); self._keyUpPrevented = evt.isDefaultPrevented(); var key = evt.which; if (key === KEYS.BACKSPACE && self.$search.val() === '') { var $previousChoice = self.$searchContainer .prev('.select2-selection__choice'); if ($previousChoice.length > 0) { var item = $previousChoice.data('data'); self.searchRemoveChoice(item); evt.preventDefault(); } } }); // Try to detect the IE version should the `documentMode` property that // is stored on the document. This is only implemented in IE and is // slightly cleaner than doing a user agent check. // This property is not available in Edge, but Edge also doesn't have // this bug. var msie = document.documentMode; var disableInputEvents = msie && msie <= 11; // Workaround for browsers which do not support the `input` event // This will prevent double-triggering of events for browsers which support // both the `keyup` and `input` events. this.$selection.on( 'input.searchcheck', '.select2-search--inline', function (evt) { // IE will trigger the `input` event when a placeholder is used on a // search box. To get around this issue, we are forced to ignore all // `input` events in IE and keep using `keyup`. if (disableInputEvents) { self.$selection.off('input.search input.searchcheck'); return; } // Unbind the duplicated `keyup` event self.$selection.off('keyup.search'); } ); this.$selection.on( 'keyup.search input.search', '.select2-search--inline', function (evt) { // IE will trigger the `input` event when a placeholder is used on a // search box. To get around this issue, we are forced to ignore all // `input` events in IE and keep using `keyup`. if (disableInputEvents && evt.type === 'input') { self.$selection.off('input.search input.searchcheck'); return; } var key = evt.which; // We can freely ignore events from modifier keys if (key == KEYS.SHIFT || key == KEYS.CTRL || key == KEYS.ALT) { return; } // Tabbing will be handled during the `keydown` phase if (key == KEYS.TAB) { return; } self.handleSearch(evt); } ); }; /** * This method will transfer the tabindex attribute from the rendered * selection to the search box. This allows for the search box to be used as * the primary focus instead of the selection container. * * @private */ Search.prototype._transferTabIndex = function (decorated) { this.$search.attr('tabindex', this.$selection.attr('tabindex')); this.$selection.attr('tabindex', '-1'); }; Search.prototype.createPlaceholder = function (decorated, placeholder) { this.$search.attr('placeholder', placeholder.text); }; Search.prototype.update = function (decorated, data) { var searchHadFocus = this.$search[0] == document.activeElement; this.$search.attr('placeholder', ''); decorated.call(this, data); this.$selection.find('.select2-selection__rendered') .append(this.$searchContainer); this.resizeSearch(); if (searchHadFocus) { this.$search.focus(); } }; Search.prototype.handleSearch = function () { this.resizeSearch(); if (!this._keyUpPrevented) { var input = this.$search.val(); this.trigger('query', { term: input }); } this._keyUpPrevented = false; }; Search.prototype.searchRemoveChoice = function (decorated, item) { this.trigger('unselect', { data: item }); this.$search.val(item.text); this.handleSearch(); }; Search.prototype.resizeSearch = function () { this.$search.css('width', '25px'); var width = ''; if (this.$search.attr('placeholder') !== '') { width = this.$selection.find('.select2-selection__rendered').innerWidth(); } else { var minimumWidth = this.$search.val().length + 1; width = (minimumWidth * 0.75) + 'em'; } this.$search.css('width', width); }; return Search; }); S2.define('select2/selection/eventRelay',[ 'jquery' ], function ($) { function EventRelay () { } EventRelay.prototype.bind = function (decorated, container, $container) { var self = this; var relayEvents = [ 'open', 'opening', 'close', 'closing', 'select', 'selecting', 'unselect', 'unselecting' ]; var preventableEvents = ['opening', 'closing', 'selecting', 'unselecting']; decorated.call(this, container, $container); container.on('*', function (name, params) { // Ignore events that should not be relayed if ($.inArray(name, relayEvents) === -1) { return; } // The parameters should always be an object params = params || {}; // Generate the jQuery event for the Select2 event var evt = $.Event('select2:' + name, { params: params }); self.$element.trigger(evt); // Only handle preventable events if it was one if ($.inArray(name, preventableEvents) === -1) { return; } params.prevented = evt.isDefaultPrevented(); }); }; return EventRelay; }); S2.define('select2/translation',[ 'jquery', 'require' ], function ($, require) { function Translation (dict) { this.dict = dict || {}; } Translation.prototype.all = function () { return this.dict; }; Translation.prototype.get = function (key) { return this.dict[key]; }; Translation.prototype.extend = function (translation) { this.dict = $.extend({}, translation.all(), this.dict); }; // Static functions Translation._cache = {}; Translation.loadPath = function (path) { if (!(path in Translation._cache)) { var translations = require(path); Translation._cache[path] = translations; } return new Translation(Translation._cache[path]); }; return Translation; }); S2.define('select2/diacritics',[ ], function () { var diacritics = { '\u24B6': 'A', '\uFF21': 'A', '\u00C0': 'A', '\u00C1': 'A', '\u00C2': 'A', '\u1EA6': 'A', '\u1EA4': 'A', '\u1EAA': 'A', '\u1EA8': 'A', '\u00C3': 'A', '\u0100': 'A', '\u0102': 'A', '\u1EB0': 'A', '\u1EAE': 'A', '\u1EB4': 'A', '\u1EB2': 'A', '\u0226': 'A', '\u01E0': 'A', '\u00C4': 'A', '\u01DE': 'A', '\u1EA2': 'A', '\u00C5': 'A', '\u01FA': 'A', '\u01CD': 'A', '\u0200': 'A', '\u0202': 'A', '\u1EA0': 'A', '\u1EAC': 'A', '\u1EB6': 'A', '\u1E00': 'A', '\u0104': 'A', '\u023A': 'A', '\u2C6F': 'A', '\uA732': 'AA', '\u00C6': 'AE', '\u01FC': 'AE', '\u01E2': 'AE', '\uA734': 'AO', '\uA736': 'AU', '\uA738': 'AV', '\uA73A': 'AV', '\uA73C': 'AY', '\u24B7': 'B', '\uFF22': 'B', '\u1E02': 'B', '\u1E04': 'B', '\u1E06': 'B', '\u0243': 'B', '\u0182': 'B', '\u0181': 'B', '\u24B8': 'C', '\uFF23': 'C', '\u0106': 'C', '\u0108': 'C', '\u010A': 'C', '\u010C': 'C', '\u00C7': 'C', '\u1E08': 'C', '\u0187': 'C', '\u023B': 'C', '\uA73E': 'C', '\u24B9': 'D', '\uFF24': 'D', '\u1E0A': 'D', '\u010E': 'D', '\u1E0C': 'D', '\u1E10': 'D', '\u1E12': 'D', '\u1E0E': 'D', '\u0110': 'D', '\u018B': 'D', '\u018A': 'D', '\u0189': 'D', '\uA779': 'D', '\u01F1': 'DZ', '\u01C4': 'DZ', '\u01F2': 'Dz', '\u01C5': 'Dz', '\u24BA': 'E', '\uFF25': 'E', '\u00C8': 'E', '\u00C9': 'E', '\u00CA': 'E', '\u1EC0': 'E', '\u1EBE': 'E', '\u1EC4': 'E', '\u1EC2': 'E', '\u1EBC': 'E', '\u0112': 'E', '\u1E14': 'E', '\u1E16': 'E', '\u0114': 'E', '\u0116': 'E', '\u00CB': 'E', '\u1EBA': 'E', '\u011A': 'E', '\u0204': 'E', '\u0206': 'E', '\u1EB8': 'E', '\u1EC6': 'E', '\u0228': 'E', '\u1E1C': 'E', '\u0118': 'E', '\u1E18': 'E', '\u1E1A': 'E', '\u0190': 'E', '\u018E': 'E', '\u24BB': 'F', '\uFF26': 'F', '\u1E1E': 'F', '\u0191': 'F', '\uA77B': 'F', '\u24BC': 'G', '\uFF27': 'G', '\u01F4': 'G', '\u011C': 'G', '\u1E20': 'G', '\u011E': 'G', '\u0120': 'G', '\u01E6': 'G', '\u0122': 'G', '\u01E4': 'G', '\u0193': 'G', '\uA7A0': 'G', '\uA77D': 'G', '\uA77E': 'G', '\u24BD': 'H', '\uFF28': 'H', '\u0124': 'H', '\u1E22': 'H', '\u1E26': 'H', '\u021E': 'H', '\u1E24': 'H', '\u1E28': 'H', '\u1E2A': 'H', '\u0126': 'H', '\u2C67': 'H', '\u2C75': 'H', '\uA78D': 'H', '\u24BE': 'I', '\uFF29': 'I', '\u00CC': 'I', '\u00CD': 'I', '\u00CE': 'I', '\u0128': 'I', '\u012A': 'I', '\u012C': 'I', '\u0130': 'I', '\u00CF': 'I', '\u1E2E': 'I', '\u1EC8': 'I', '\u01CF': 'I', '\u0208': 'I', '\u020A': 'I', '\u1ECA': 'I', '\u012E': 'I', '\u1E2C': 'I', '\u0197': 'I', '\u24BF': 'J', '\uFF2A': 'J', '\u0134': 'J', '\u0248': 'J', '\u24C0': 'K', '\uFF2B': 'K', '\u1E30': 'K', '\u01E8': 'K', '\u1E32': 'K', '\u0136': 'K', '\u1E34': 'K', '\u0198': 'K', '\u2C69': 'K', '\uA740': 'K', '\uA742': 'K', '\uA744': 'K', '\uA7A2': 'K', '\u24C1': 'L', '\uFF2C': 'L', '\u013F': 'L', '\u0139': 'L', '\u013D': 'L', '\u1E36': 'L', '\u1E38': 'L', '\u013B': 'L', '\u1E3C': 'L', '\u1E3A': 'L', '\u0141': 'L', '\u023D': 'L', '\u2C62': 'L', '\u2C60': 'L', '\uA748': 'L', '\uA746': 'L', '\uA780': 'L', '\u01C7': 'LJ', '\u01C8': 'Lj', '\u24C2': 'M', '\uFF2D': 'M', '\u1E3E': 'M', '\u1E40': 'M', '\u1E42': 'M', '\u2C6E': 'M', '\u019C': 'M', '\u24C3': 'N', '\uFF2E': 'N', '\u01F8': 'N', '\u0143': 'N', '\u00D1': 'N', '\u1E44': 'N', '\u0147': 'N', '\u1E46': 'N', '\u0145': 'N', '\u1E4A': 'N', '\u1E48': 'N', '\u0220': 'N', '\u019D': 'N', '\uA790': 'N', '\uA7A4': 'N', '\u01CA': 'NJ', '\u01CB': 'Nj', '\u24C4': 'O', '\uFF2F': 'O', '\u00D2': 'O', '\u00D3': 'O', '\u00D4': 'O', '\u1ED2': 'O', '\u1ED0': 'O', '\u1ED6': 'O', '\u1ED4': 'O', '\u00D5': 'O', '\u1E4C': 'O', '\u022C': 'O', '\u1E4E': 'O', '\u014C': 'O', '\u1E50': 'O', '\u1E52': 'O', '\u014E': 'O', '\u022E': 'O', '\u0230': 'O', '\u00D6': 'O', '\u022A': 'O', '\u1ECE': 'O', '\u0150': 'O', '\u01D1': 'O', '\u020C': 'O', '\u020E': 'O', '\u01A0': 'O', '\u1EDC': 'O', '\u1EDA': 'O', '\u1EE0': 'O', '\u1EDE': 'O', '\u1EE2': 'O', '\u1ECC': 'O', '\u1ED8': 'O', '\u01EA': 'O', '\u01EC': 'O', '\u00D8': 'O', '\u01FE': 'O', '\u0186': 'O', '\u019F': 'O', '\uA74A': 'O', '\uA74C': 'O', '\u01A2': 'OI', '\uA74E': 'OO', '\u0222': 'OU', '\u24C5': 'P', '\uFF30': 'P', '\u1E54': 'P', '\u1E56': 'P', '\u01A4': 'P', '\u2C63': 'P', '\uA750': 'P', '\uA752': 'P', '\uA754': 'P', '\u24C6': 'Q', '\uFF31': 'Q', '\uA756': 'Q', '\uA758': 'Q', '\u024A': 'Q', '\u24C7': 'R', '\uFF32': 'R', '\u0154': 'R', '\u1E58': 'R', '\u0158': 'R', '\u0210': 'R', '\u0212': 'R', '\u1E5A': 'R', '\u1E5C': 'R', '\u0156': 'R', '\u1E5E': 'R', '\u024C': 'R', '\u2C64': 'R', '\uA75A': 'R', '\uA7A6': 'R', '\uA782': 'R', '\u24C8': 'S', '\uFF33': 'S', '\u1E9E': 'S', '\u015A': 'S', '\u1E64': 'S', '\u015C': 'S', '\u1E60': 'S', '\u0160': 'S', '\u1E66': 'S', '\u1E62': 'S', '\u1E68': 'S', '\u0218': 'S', '\u015E': 'S', '\u2C7E': 'S', '\uA7A8': 'S', '\uA784': 'S', '\u24C9': 'T', '\uFF34': 'T', '\u1E6A': 'T', '\u0164': 'T', '\u1E6C': 'T', '\u021A': 'T', '\u0162': 'T', '\u1E70': 'T', '\u1E6E': 'T', '\u0166': 'T', '\u01AC': 'T', '\u01AE': 'T', '\u023E': 'T', '\uA786': 'T', '\uA728': 'TZ', '\u24CA': 'U', '\uFF35': 'U', '\u00D9': 'U', '\u00DA': 'U', '\u00DB': 'U', '\u0168': 'U', '\u1E78': 'U', '\u016A': 'U', '\u1E7A': 'U', '\u016C': 'U', '\u00DC': 'U', '\u01DB': 'U', '\u01D7': 'U', '\u01D5': 'U', '\u01D9': 'U', '\u1EE6': 'U', '\u016E': 'U', '\u0170': 'U', '\u01D3': 'U', '\u0214': 'U', '\u0216': 'U', '\u01AF': 'U', '\u1EEA': 'U', '\u1EE8': 'U', '\u1EEE': 'U', '\u1EEC': 'U', '\u1EF0': 'U', '\u1EE4': 'U', '\u1E72': 'U', '\u0172': 'U', '\u1E76': 'U', '\u1E74': 'U', '\u0244': 'U', '\u24CB': 'V', '\uFF36': 'V', '\u1E7C': 'V', '\u1E7E': 'V', '\u01B2': 'V', '\uA75E': 'V', '\u0245': 'V', '\uA760': 'VY', '\u24CC': 'W', '\uFF37': 'W', '\u1E80': 'W', '\u1E82': 'W', '\u0174': 'W', '\u1E86': 'W', '\u1E84': 'W', '\u1E88': 'W', '\u2C72': 'W', '\u24CD': 'X', '\uFF38': 'X', '\u1E8A': 'X', '\u1E8C': 'X', '\u24CE': 'Y', '\uFF39': 'Y', '\u1EF2': 'Y', '\u00DD': 'Y', '\u0176': 'Y', '\u1EF8': 'Y', '\u0232': 'Y', '\u1E8E': 'Y', '\u0178': 'Y', '\u1EF6': 'Y', '\u1EF4': 'Y', '\u01B3': 'Y', '\u024E': 'Y', '\u1EFE': 'Y', '\u24CF': 'Z', '\uFF3A': 'Z', '\u0179': 'Z', '\u1E90': 'Z', '\u017B': 'Z', '\u017D': 'Z', '\u1E92': 'Z', '\u1E94': 'Z', '\u01B5': 'Z', '\u0224': 'Z', '\u2C7F': 'Z', '\u2C6B': 'Z', '\uA762': 'Z', '\u24D0': 'a', '\uFF41': 'a', '\u1E9A': 'a', '\u00E0': 'a', '\u00E1': 'a', '\u00E2': 'a', '\u1EA7': 'a', '\u1EA5': 'a', '\u1EAB': 'a', '\u1EA9': 'a', '\u00E3': 'a', '\u0101': 'a', '\u0103': 'a', '\u1EB1': 'a', '\u1EAF': 'a', '\u1EB5': 'a', '\u1EB3': 'a', '\u0227': 'a', '\u01E1': 'a', '\u00E4': 'a', '\u01DF': 'a', '\u1EA3': 'a', '\u00E5': 'a', '\u01FB': 'a', '\u01CE': 'a', '\u0201': 'a', '\u0203': 'a', '\u1EA1': 'a', '\u1EAD': 'a', '\u1EB7': 'a', '\u1E01': 'a', '\u0105': 'a', '\u2C65': 'a', '\u0250': 'a', '\uA733': 'aa', '\u00E6': 'ae', '\u01FD': 'ae', '\u01E3': 'ae', '\uA735': 'ao', '\uA737': 'au', '\uA739': 'av', '\uA73B': 'av', '\uA73D': 'ay', '\u24D1': 'b', '\uFF42': 'b', '\u1E03': 'b', '\u1E05': 'b', '\u1E07': 'b', '\u0180': 'b', '\u0183': 'b', '\u0253': 'b', '\u24D2': 'c', '\uFF43': 'c', '\u0107': 'c', '\u0109': 'c', '\u010B': 'c', '\u010D': 'c', '\u00E7': 'c', '\u1E09': 'c', '\u0188': 'c', '\u023C': 'c', '\uA73F': 'c', '\u2184': 'c', '\u24D3': 'd', '\uFF44': 'd', '\u1E0B': 'd', '\u010F': 'd', '\u1E0D': 'd', '\u1E11': 'd', '\u1E13': 'd', '\u1E0F': 'd', '\u0111': 'd', '\u018C': 'd', '\u0256': 'd', '\u0257': 'd', '\uA77A': 'd', '\u01F3': 'dz', '\u01C6': 'dz', '\u24D4': 'e', '\uFF45': 'e', '\u00E8': 'e', '\u00E9': 'e', '\u00EA': 'e', '\u1EC1': 'e', '\u1EBF': 'e', '\u1EC5': 'e', '\u1EC3': 'e', '\u1EBD': 'e', '\u0113': 'e', '\u1E15': 'e', '\u1E17': 'e', '\u0115': 'e', '\u0117': 'e', '\u00EB': 'e', '\u1EBB': 'e', '\u011B': 'e', '\u0205': 'e', '\u0207': 'e', '\u1EB9': 'e', '\u1EC7': 'e', '\u0229': 'e', '\u1E1D': 'e', '\u0119': 'e', '\u1E19': 'e', '\u1E1B': 'e', '\u0247': 'e', '\u025B': 'e', '\u01DD': 'e', '\u24D5': 'f', '\uFF46': 'f', '\u1E1F': 'f', '\u0192': 'f', '\uA77C': 'f', '\u24D6': 'g', '\uFF47': 'g', '\u01F5': 'g', '\u011D': 'g', '\u1E21': 'g', '\u011F': 'g', '\u0121': 'g', '\u01E7': 'g', '\u0123': 'g', '\u01E5': 'g', '\u0260': 'g', '\uA7A1': 'g', '\u1D79': 'g', '\uA77F': 'g', '\u24D7': 'h', '\uFF48': 'h', '\u0125': 'h', '\u1E23': 'h', '\u1E27': 'h', '\u021F': 'h', '\u1E25': 'h', '\u1E29': 'h', '\u1E2B': 'h', '\u1E96': 'h', '\u0127': 'h', '\u2C68': 'h', '\u2C76': 'h', '\u0265': 'h', '\u0195': 'hv', '\u24D8': 'i', '\uFF49': 'i', '\u00EC': 'i', '\u00ED': 'i', '\u00EE': 'i', '\u0129': 'i', '\u012B': 'i', '\u012D': 'i', '\u00EF': 'i', '\u1E2F': 'i', '\u1EC9': 'i', '\u01D0': 'i', '\u0209': 'i', '\u020B': 'i', '\u1ECB': 'i', '\u012F': 'i', '\u1E2D': 'i', '\u0268': 'i', '\u0131': 'i', '\u24D9': 'j', '\uFF4A': 'j', '\u0135': 'j', '\u01F0': 'j', '\u0249': 'j', '\u24DA': 'k', '\uFF4B': 'k', '\u1E31': 'k', '\u01E9': 'k', '\u1E33': 'k', '\u0137': 'k', '\u1E35': 'k', '\u0199': 'k', '\u2C6A': 'k', '\uA741': 'k', '\uA743': 'k', '\uA745': 'k', '\uA7A3': 'k', '\u24DB': 'l', '\uFF4C': 'l', '\u0140': 'l', '\u013A': 'l', '\u013E': 'l', '\u1E37': 'l', '\u1E39': 'l', '\u013C': 'l', '\u1E3D': 'l', '\u1E3B': 'l', '\u017F': 'l', '\u0142': 'l', '\u019A': 'l', '\u026B': 'l', '\u2C61': 'l', '\uA749': 'l', '\uA781': 'l', '\uA747': 'l', '\u01C9': 'lj', '\u24DC': 'm', '\uFF4D': 'm', '\u1E3F': 'm', '\u1E41': 'm', '\u1E43': 'm', '\u0271': 'm', '\u026F': 'm', '\u24DD': 'n', '\uFF4E': 'n', '\u01F9': 'n', '\u0144': 'n', '\u00F1': 'n', '\u1E45': 'n', '\u0148': 'n', '\u1E47': 'n', '\u0146': 'n', '\u1E4B': 'n', '\u1E49': 'n', '\u019E': 'n', '\u0272': 'n', '\u0149': 'n', '\uA791': 'n', '\uA7A5': 'n', '\u01CC': 'nj', '\u24DE': 'o', '\uFF4F': 'o', '\u00F2': 'o', '\u00F3': 'o', '\u00F4': 'o', '\u1ED3': 'o', '\u1ED1': 'o', '\u1ED7': 'o', '\u1ED5': 'o', '\u00F5': 'o', '\u1E4D': 'o', '\u022D': 'o', '\u1E4F': 'o', '\u014D': 'o', '\u1E51': 'o', '\u1E53': 'o', '\u014F': 'o', '\u022F': 'o', '\u0231': 'o', '\u00F6': 'o', '\u022B': 'o', '\u1ECF': 'o', '\u0151': 'o', '\u01D2': 'o', '\u020D': 'o', '\u020F': 'o', '\u01A1': 'o', '\u1EDD': 'o', '\u1EDB': 'o', '\u1EE1': 'o', '\u1EDF': 'o', '\u1EE3': 'o', '\u1ECD': 'o', '\u1ED9': 'o', '\u01EB': 'o', '\u01ED': 'o', '\u00F8': 'o', '\u01FF': 'o', '\u0254': 'o', '\uA74B': 'o', '\uA74D': 'o', '\u0275': 'o', '\u01A3': 'oi', '\u0223': 'ou', '\uA74F': 'oo', '\u24DF': 'p', '\uFF50': 'p', '\u1E55': 'p', '\u1E57': 'p', '\u01A5': 'p', '\u1D7D': 'p', '\uA751': 'p', '\uA753': 'p', '\uA755': 'p', '\u24E0': 'q', '\uFF51': 'q', '\u024B': 'q', '\uA757': 'q', '\uA759': 'q', '\u24E1': 'r', '\uFF52': 'r', '\u0155': 'r', '\u1E59': 'r', '\u0159': 'r', '\u0211': 'r', '\u0213': 'r', '\u1E5B': 'r', '\u1E5D': 'r', '\u0157': 'r', '\u1E5F': 'r', '\u024D': 'r', '\u027D': 'r', '\uA75B': 'r', '\uA7A7': 'r', '\uA783': 'r', '\u24E2': 's', '\uFF53': 's', '\u00DF': 's', '\u015B': 's', '\u1E65': 's', '\u015D': 's', '\u1E61': 's', '\u0161': 's', '\u1E67': 's', '\u1E63': 's', '\u1E69': 's', '\u0219': 's', '\u015F': 's', '\u023F': 's', '\uA7A9': 's', '\uA785': 's', '\u1E9B': 's', '\u24E3': 't', '\uFF54': 't', '\u1E6B': 't', '\u1E97': 't', '\u0165': 't', '\u1E6D': 't', '\u021B': 't', '\u0163': 't', '\u1E71': 't', '\u1E6F': 't', '\u0167': 't', '\u01AD': 't', '\u0288': 't', '\u2C66': 't', '\uA787': 't', '\uA729': 'tz', '\u24E4': 'u', '\uFF55': 'u', '\u00F9': 'u', '\u00FA': 'u', '\u00FB': 'u', '\u0169': 'u', '\u1E79': 'u', '\u016B': 'u', '\u1E7B': 'u', '\u016D': 'u', '\u00FC': 'u', '\u01DC': 'u', '\u01D8': 'u', '\u01D6': 'u', '\u01DA': 'u', '\u1EE7': 'u', '\u016F': 'u', '\u0171': 'u', '\u01D4': 'u', '\u0215': 'u', '\u0217': 'u', '\u01B0': 'u', '\u1EEB': 'u', '\u1EE9': 'u', '\u1EEF': 'u', '\u1EED': 'u', '\u1EF1': 'u', '\u1EE5': 'u', '\u1E73': 'u', '\u0173': 'u', '\u1E77': 'u', '\u1E75': 'u', '\u0289': 'u', '\u24E5': 'v', '\uFF56': 'v', '\u1E7D': 'v', '\u1E7F': 'v', '\u028B': 'v', '\uA75F': 'v', '\u028C': 'v', '\uA761': 'vy', '\u24E6': 'w', '\uFF57': 'w', '\u1E81': 'w', '\u1E83': 'w', '\u0175': 'w', '\u1E87': 'w', '\u1E85': 'w', '\u1E98': 'w', '\u1E89': 'w', '\u2C73': 'w', '\u24E7': 'x', '\uFF58': 'x', '\u1E8B': 'x', '\u1E8D': 'x', '\u24E8': 'y', '\uFF59': 'y', '\u1EF3': 'y', '\u00FD': 'y', '\u0177': 'y', '\u1EF9': 'y', '\u0233': 'y', '\u1E8F': 'y', '\u00FF': 'y', '\u1EF7': 'y', '\u1E99': 'y', '\u1EF5': 'y', '\u01B4': 'y', '\u024F': 'y', '\u1EFF': 'y', '\u24E9': 'z', '\uFF5A': 'z', '\u017A': 'z', '\u1E91': 'z', '\u017C': 'z', '\u017E': 'z', '\u1E93': 'z', '\u1E95': 'z', '\u01B6': 'z', '\u0225': 'z', '\u0240': 'z', '\u2C6C': 'z', '\uA763': 'z', '\u0386': '\u0391', '\u0388': '\u0395', '\u0389': '\u0397', '\u038A': '\u0399', '\u03AA': '\u0399', '\u038C': '\u039F', '\u038E': '\u03A5', '\u03AB': '\u03A5', '\u038F': '\u03A9', '\u03AC': '\u03B1', '\u03AD': '\u03B5', '\u03AE': '\u03B7', '\u03AF': '\u03B9', '\u03CA': '\u03B9', '\u0390': '\u03B9', '\u03CC': '\u03BF', '\u03CD': '\u03C5', '\u03CB': '\u03C5', '\u03B0': '\u03C5', '\u03C9': '\u03C9', '\u03C2': '\u03C3' }; return diacritics; }); S2.define('select2/data/base',[ '../utils' ], function (Utils) { function BaseAdapter ($element, options) { BaseAdapter.__super__.constructor.call(this); } Utils.Extend(BaseAdapter, Utils.Observable); BaseAdapter.prototype.current = function (callback) { throw new Error('The `current` method must be defined in child classes.'); }; BaseAdapter.prototype.query = function (params, callback) { throw new Error('The `query` method must be defined in child classes.'); }; BaseAdapter.prototype.bind = function (container, $container) { // Can be implemented in subclasses }; BaseAdapter.prototype.destroy = function () { // Can be implemented in subclasses }; BaseAdapter.prototype.generateResultId = function (container, data) { var id = container.id + '-result-'; id += Utils.generateChars(4); if (data.id != null) { id += '-' + data.id.toString(); } else { id += '-' + Utils.generateChars(4); } return id; }; return BaseAdapter; }); S2.define('select2/data/select',[ './base', '../utils', 'jquery' ], function (BaseAdapter, Utils, $) { function SelectAdapter ($element, options) { this.$element = $element; this.options = options; SelectAdapter.__super__.constructor.call(this); } Utils.Extend(SelectAdapter, BaseAdapter); SelectAdapter.prototype.current = function (callback) { var data = []; var self = this; this.$element.find(':selected').each(function () { var $option = $(this); var option = self.item($option); data.push(option); }); callback(data); }; SelectAdapter.prototype.select = function (data) { var self = this; data.selected = true; // If data.element is a DOM node, use it instead if ($(data.element).is('option')) { data.element.selected = true; this.$element.trigger('change'); return; } if (this.$element.prop('multiple')) { this.current(function (currentData) { var val = []; data = [data]; data.push.apply(data, currentData); for (var d = 0; d < data.length; d++) { var id = data[d].id; if ($.inArray(id, val) === -1) { val.push(id); } } self.$element.val(val); self.$element.trigger('change'); }); } else { var val = data.id; this.$element.val(val); this.$element.trigger('change'); } }; SelectAdapter.prototype.unselect = function (data) { var self = this; if (!this.$element.prop('multiple')) { return; } data.selected = false; if ($(data.element).is('option')) { data.element.selected = false; this.$element.trigger('change'); return; } this.current(function (currentData) { var val = []; for (var d = 0; d < currentData.length; d++) { var id = currentData[d].id; if (id !== data.id && $.inArray(id, val) === -1) { val.push(id); } } self.$element.val(val); self.$element.trigger('change'); }); }; SelectAdapter.prototype.bind = function (container, $container) { var self = this; this.container = container; container.on('select', function (params) { self.select(params.data); }); container.on('unselect', function (params) { self.unselect(params.data); }); }; SelectAdapter.prototype.destroy = function () { // Remove anything added to child elements this.$element.find('*').each(function () { // Remove any custom data set by Select2 $.removeData(this, 'data'); }); }; SelectAdapter.prototype.query = function (params, callback) { var data = []; var self = this; var $options = this.$element.children(); $options.each(function () { var $option = $(this); if (!$option.is('option') && !$option.is('optgroup')) { return; } var option = self.item($option); var matches = self.matches(params, option); if (matches !== null) { data.push(matches); } }); callback({ results: data }); }; SelectAdapter.prototype.addOptions = function ($options) { Utils.appendMany(this.$element, $options); }; SelectAdapter.prototype.option = function (data) { var option; if (data.children) { option = document.createElement('optgroup'); option.label = data.text; } else { option = document.createElement('option'); if (option.textContent !== undefined) { option.textContent = data.text; } else { option.innerText = data.text; } } if (data.id) { option.value = data.id; } if (data.disabled) { option.disabled = true; } if (data.selected) { option.selected = true; } if (data.title) { option.title = data.title; } var $option = $(option); var normalizedData = this._normalizeItem(data); normalizedData.element = option; // Override the option's data with the combined data $.data(option, 'data', normalizedData); return $option; }; SelectAdapter.prototype.item = function ($option) { var data = {}; data = $.data($option[0], 'data'); if (data != null) { return data; } if ($option.is('option')) { data = { id: $option.val(), text: $option.text(), disabled: $option.prop('disabled'), selected: $option.prop('selected'), title: $option.prop('title') }; } else if ($option.is('optgroup')) { data = { text: $option.prop('label'), children: [], title: $option.prop('title') }; var $children = $option.children('option'); var children = []; for (var c = 0; c < $children.length; c++) { var $child = $($children[c]); var child = this.item($child); children.push(child); } data.children = children; } data = this._normalizeItem(data); data.element = $option[0]; $.data($option[0], 'data', data); return data; }; SelectAdapter.prototype._normalizeItem = function (item) { if (!$.isPlainObject(item)) { item = { id: item, text: item }; } item = $.extend({}, { text: '' }, item); var defaults = { selected: false, disabled: false }; if (item.id != null) { item.id = item.id.toString(); } if (item.text != null) { item.text = item.text.toString(); } if (item._resultId == null && item.id && this.container != null) { item._resultId = this.generateResultId(this.container, item); } return $.extend({}, defaults, item); }; SelectAdapter.prototype.matches = function (params, data) { var matcher = this.options.get('matcher'); return matcher(params, data); }; return SelectAdapter; }); S2.define('select2/data/array',[ './select', '../utils', 'jquery' ], function (SelectAdapter, Utils, $) { function ArrayAdapter ($element, options) { var data = options.get('data') || []; ArrayAdapter.__super__.constructor.call(this, $element, options); this.addOptions(this.convertToOptions(data)); } Utils.Extend(ArrayAdapter, SelectAdapter); ArrayAdapter.prototype.select = function (data) { var $option = this.$element.find('option').filter(function (i, elm) { return elm.value == data.id.toString(); }); if ($option.length === 0) { $option = this.option(data); this.addOptions($option); } ArrayAdapter.__super__.select.call(this, data); }; ArrayAdapter.prototype.convertToOptions = function (data) { var self = this; var $existing = this.$element.find('option'); var existingIds = $existing.map(function () { return self.item($(this)).id; }).get(); var $options = []; // Filter out all items except for the one passed in the argument function onlyItem (item) { return function () { return $(this).val() == item.id; }; } for (var d = 0; d < data.length; d++) { var item = this._normalizeItem(data[d]); // Skip items which were pre-loaded, only merge the data if ($.inArray(item.id, existingIds) >= 0) { var $existingOption = $existing.filter(onlyItem(item)); var existingData = this.item($existingOption); var newData = $.extend(true, {}, existingData, item); var $newOption = this.option(newData); $existingOption.replaceWith($newOption); continue; } var $option = this.option(item); if (item.children) { var $children = this.convertToOptions(item.children); Utils.appendMany($option, $children); } $options.push($option); } return $options; }; return ArrayAdapter; }); S2.define('select2/data/ajax',[ './array', '../utils', 'jquery' ], function (ArrayAdapter, Utils, $) { function AjaxAdapter ($element, options) { this.ajaxOptions = this._applyDefaults(options.get('ajax')); if (this.ajaxOptions.processResults != null) { this.processResults = this.ajaxOptions.processResults; } AjaxAdapter.__super__.constructor.call(this, $element, options); } Utils.Extend(AjaxAdapter, ArrayAdapter); AjaxAdapter.prototype._applyDefaults = function (options) { var defaults = { data: function (params) { return $.extend({}, params, { q: params.term }); }, transport: function (params, success, failure) { var $request = $.ajax(params); $request.then(success); $request.fail(failure); return $request; } }; return $.extend({}, defaults, options, true); }; AjaxAdapter.prototype.processResults = function (results) { return results; }; AjaxAdapter.prototype.query = function (params, callback) { var matches = []; var self = this; if (this._request != null) { // JSONP requests cannot always be aborted if ($.isFunction(this._request.abort)) { this._request.abort(); } this._request = null; } var options = $.extend({ type: 'GET' }, this.ajaxOptions); if (typeof options.url === 'function') { options.url = options.url.call(this.$element, params); } if (typeof options.data === 'function') { options.data = options.data.call(this.$element, params); } function request () { var $request = options.transport(options, function (data) { var results = self.processResults(data, params); if (self.options.get('debug') && window.console && console.error) { // Check to make sure that the response included a `results` key. if (!results || !results.results || !$.isArray(results.results)) { console.error( 'Select2: The AJAX results did not return an array in the ' + '`results` key of the response.' ); } } callback(results); }, function () { // TODO: Handle AJAX errors }); self._request = $request; } if (this.ajaxOptions.delay && params.term !== '') { if (this._queryTimeout) { window.clearTimeout(this._queryTimeout); } this._queryTimeout = window.setTimeout(request, this.ajaxOptions.delay); } else { request(); } }; return AjaxAdapter; }); S2.define('select2/data/tags',[ 'jquery' ], function ($) { function Tags (decorated, $element, options) { var tags = options.get('tags'); var createTag = options.get('createTag'); if (createTag !== undefined) { this.createTag = createTag; } decorated.call(this, $element, options); if ($.isArray(tags)) { for (var t = 0; t < tags.length; t++) { var tag = tags[t]; var item = this._normalizeItem(tag); var $option = this.option(item); this.$element.append($option); } } } Tags.prototype.query = function (decorated, params, callback) { var self = this; this._removeOldTags(); if (params.term == null || params.page != null) { decorated.call(this, params, callback); return; } function wrapper (obj, child) { var data = obj.results; for (var i = 0; i < data.length; i++) { var option = data[i]; var checkChildren = ( option.children != null && !wrapper({ results: option.children }, true) ); var checkText = option.text === params.term; if (checkText || checkChildren) { if (child) { return false; } obj.data = data; callback(obj); return; } } if (child) { return true; } var tag = self.createTag(params); if (tag != null) { var $option = self.option(tag); $option.attr('data-select2-tag', true); self.addOptions([$option]); self.insertTag(data, tag); } obj.results = data; callback(obj); } decorated.call(this, params, wrapper); }; Tags.prototype.createTag = function (decorated, params) { var term = $.trim(params.term); if (term === '') { return null; } return { id: term, text: term }; }; Tags.prototype.insertTag = function (_, data, tag) { data.unshift(tag); }; Tags.prototype._removeOldTags = function (_) { var tag = this._lastTag; var $options = this.$element.find('option[data-select2-tag]'); $options.each(function () { if (this.selected) { return; } $(this).remove(); }); }; return Tags; }); S2.define('select2/data/tokenizer',[ 'jquery' ], function ($) { function Tokenizer (decorated, $element, options) { var tokenizer = options.get('tokenizer'); if (tokenizer !== undefined) { this.tokenizer = tokenizer; } decorated.call(this, $element, options); } Tokenizer.prototype.bind = function (decorated, container, $container) { decorated.call(this, container, $container); this.$search = container.dropdown.$search || container.selection.$search || $container.find('.select2-search__field'); }; Tokenizer.prototype.query = function (decorated, params, callback) { var self = this; function select (data) { self.trigger('select', { data: data }); } params.term = params.term || ''; var tokenData = this.tokenizer(params, this.options, select); if (tokenData.term !== params.term) { // Replace the search term if we have the search box if (this.$search.length) { this.$search.val(tokenData.term); this.$search.focus(); } params.term = tokenData.term; } decorated.call(this, params, callback); }; Tokenizer.prototype.tokenizer = function (_, params, options, callback) { var separators = options.get('tokenSeparators') || []; var term = params.term; var i = 0; var createTag = this.createTag || function (params) { return { id: params.term, text: params.term }; }; while (i < term.length) { var termChar = term[i]; if ($.inArray(termChar, separators) === -1) { i++; continue; } var part = term.substr(0, i); var partParams = $.extend({}, params, { term: part }); var data = createTag(partParams); if (data == null) { i++; continue; } callback(data); // Reset the term to not include the tokenized portion term = term.substr(i + 1) || ''; i = 0; } return { term: term }; }; return Tokenizer; }); S2.define('select2/data/minimumInputLength',[ ], function () { function MinimumInputLength (decorated, $e, options) { this.minimumInputLength = options.get('minimumInputLength'); decorated.call(this, $e, options); } MinimumInputLength.prototype.query = function (decorated, params, callback) { params.term = params.term || ''; if (params.term.length < this.minimumInputLength) { this.trigger('results:message', { message: 'inputTooShort', args: { minimum: this.minimumInputLength, input: params.term, params: params } }); return; } decorated.call(this, params, callback); }; return MinimumInputLength; }); S2.define('select2/data/maximumInputLength',[ ], function () { function MaximumInputLength (decorated, $e, options) { this.maximumInputLength = options.get('maximumInputLength'); decorated.call(this, $e, options); } MaximumInputLength.prototype.query = function (decorated, params, callback) { params.term = params.term || ''; if (this.maximumInputLength > 0 && params.term.length > this.maximumInputLength) { this.trigger('results:message', { message: 'inputTooLong', args: { maximum: this.maximumInputLength, input: params.term, params: params } }); return; } decorated.call(this, params, callback); }; return MaximumInputLength; }); S2.define('select2/data/maximumSelectionLength',[ ], function (){ function MaximumSelectionLength (decorated, $e, options) { this.maximumSelectionLength = options.get('maximumSelectionLength'); decorated.call(this, $e, options); } MaximumSelectionLength.prototype.query = function (decorated, params, callback) { var self = this; this.current(function (currentData) { var count = currentData != null ? currentData.length : 0; if (self.maximumSelectionLength > 0 && count >= self.maximumSelectionLength) { self.trigger('results:message', { message: 'maximumSelected', args: { maximum: self.maximumSelectionLength } }); return; } decorated.call(self, params, callback); }); }; return MaximumSelectionLength; }); S2.define('select2/dropdown',[ 'jquery', './utils' ], function ($, Utils) { function Dropdown ($element, options) { this.$element = $element; this.options = options; Dropdown.__super__.constructor.call(this); } Utils.Extend(Dropdown, Utils.Observable); Dropdown.prototype.render = function () { var $dropdown = $( '' + '' + '' ); $dropdown.attr('dir', this.options.get('dir')); this.$dropdown = $dropdown; return $dropdown; }; Dropdown.prototype.bind = function () { // Should be implemented in subclasses }; Dropdown.prototype.position = function ($dropdown, $container) { // Should be implmented in subclasses }; Dropdown.prototype.destroy = function () { // Remove the dropdown from the DOM this.$dropdown.remove(); }; return Dropdown; }); S2.define('select2/dropdown/search',[ 'jquery', '../utils' ], function ($, Utils) { function Search () { } Search.prototype.render = function (decorated) { var $rendered = decorated.call(this); var $search = $( '' + '' + '' ); this.$searchContainer = $search; this.$search = $search.find('input'); $rendered.prepend($search); return $rendered; }; Search.prototype.bind = function (decorated, container, $container) { var self = this; decorated.call(this, container, $container); this.$search.on('keydown', function (evt) { self.trigger('keypress', evt); self._keyUpPrevented = evt.isDefaultPrevented(); }); // Workaround for browsers which do not support the `input` event // This will prevent double-triggering of events for browsers which support // both the `keyup` and `input` events. this.$search.on('input', function (evt) { // Unbind the duplicated `keyup` event $(this).off('keyup'); }); this.$search.on('keyup input', function (evt) { self.handleSearch(evt); }); container.on('open', function () { self.$search.attr('tabindex', 0); self.$search.focus(); window.setTimeout(function () { self.$search.focus(); }, 0); }); container.on('close', function () { self.$search.attr('tabindex', -1); self.$search.val(''); }); container.on('results:all', function (params) { if (params.query.term == null || params.query.term === '') { var showSearch = self.showSearch(params); if (showSearch) { self.$searchContainer.removeClass('select2-search--hide'); } else { self.$searchContainer.addClass('select2-search--hide'); } } }); }; Search.prototype.handleSearch = function (evt) { if (!this._keyUpPrevented) { var input = this.$search.val(); this.trigger('query', { term: input }); } this._keyUpPrevented = false; }; Search.prototype.showSearch = function (_, params) { return true; }; return Search; }); S2.define('select2/dropdown/hidePlaceholder',[ ], function () { function HidePlaceholder (decorated, $element, options, dataAdapter) { this.placeholder = this.normalizePlaceholder(options.get('placeholder')); decorated.call(this, $element, options, dataAdapter); } HidePlaceholder.prototype.append = function (decorated, data) { data.results = this.removePlaceholder(data.results); decorated.call(this, data); }; HidePlaceholder.prototype.normalizePlaceholder = function (_, placeholder) { if (typeof placeholder === 'string') { placeholder = { id: '', text: placeholder }; } return placeholder; }; HidePlaceholder.prototype.removePlaceholder = function (_, data) { var modifiedData = data.slice(0); for (var d = data.length - 1; d >= 0; d--) { var item = data[d]; if (this.placeholder.id === item.id) { modifiedData.splice(d, 1); } } return modifiedData; }; return HidePlaceholder; }); S2.define('select2/dropdown/infiniteScroll',[ 'jquery' ], function ($) { function InfiniteScroll (decorated, $element, options, dataAdapter) { this.lastParams = {}; decorated.call(this, $element, options, dataAdapter); this.$loadingMore = this.createLoadingMore(); this.loading = false; } InfiniteScroll.prototype.append = function (decorated, data) { this.$loadingMore.remove(); this.loading = false; decorated.call(this, data); if (this.showLoadingMore(data)) { this.$results.append(this.$loadingMore); } }; InfiniteScroll.prototype.bind = function (decorated, container, $container) { var self = this; decorated.call(this, container, $container); container.on('query', function (params) { self.lastParams = params; self.loading = true; }); container.on('query:append', function (params) { self.lastParams = params; self.loading = true; }); this.$results.on('scroll', function () { var isLoadMoreVisible = $.contains( document.documentElement, self.$loadingMore[0] ); if (self.loading || !isLoadMoreVisible) { return; } var currentOffset = self.$results.offset().top + self.$results.outerHeight(false); var loadingMoreOffset = self.$loadingMore.offset().top + self.$loadingMore.outerHeight(false); if (currentOffset + 50 >= loadingMoreOffset) { self.loadMore(); } }); }; InfiniteScroll.prototype.loadMore = function () { this.loading = true; var params = $.extend({}, {page: 1}, this.lastParams); params.page++; this.trigger('query:append', params); }; InfiniteScroll.prototype.showLoadingMore = function (_, data) { return data.pagination && data.pagination.more; }; InfiniteScroll.prototype.createLoadingMore = function () { var $option = $( '
  • ' ); var message = this.options.get('translations').get('loadingMore'); $option.html(message(this.lastParams)); return $option; }; return InfiniteScroll; }); S2.define('select2/dropdown/attachBody',[ 'jquery', '../utils' ], function ($, Utils) { function AttachBody (decorated, $element, options) { this.$dropdownParent = options.get('dropdownParent') || $(document.body); decorated.call(this, $element, options); } AttachBody.prototype.bind = function (decorated, container, $container) { var self = this; var setupResultsEvents = false; decorated.call(this, container, $container); container.on('open', function () { self._showDropdown(); self._attachPositioningHandler(container); if (!setupResultsEvents) { setupResultsEvents = true; container.on('results:all', function () { self._positionDropdown(); self._resizeDropdown(); }); container.on('results:append', function () { self._positionDropdown(); self._resizeDropdown(); }); } }); container.on('close', function () { self._hideDropdown(); self._detachPositioningHandler(container); }); this.$dropdownContainer.on('mousedown', function (evt) { evt.stopPropagation(); }); }; AttachBody.prototype.destroy = function (decorated) { decorated.call(this); this.$dropdownContainer.remove(); }; AttachBody.prototype.position = function (decorated, $dropdown, $container) { // Clone all of the container classes $dropdown.attr('class', $container.attr('class')); $dropdown.removeClass('select2'); $dropdown.addClass('select2-container--open'); $dropdown.css({ position: 'absolute', top: -999999 }); this.$container = $container; }; AttachBody.prototype.render = function (decorated) { var $container = $(''); var $dropdown = decorated.call(this); $container.append($dropdown); this.$dropdownContainer = $container; return $container; }; AttachBody.prototype._hideDropdown = function (decorated) { this.$dropdownContainer.detach(); }; AttachBody.prototype._attachPositioningHandler = function (decorated, container) { var self = this; var scrollEvent = 'scroll.select2.' + container.id; var resizeEvent = 'resize.select2.' + container.id; var orientationEvent = 'orientationchange.select2.' + container.id; var $watchers = this.$container.parents().filter(Utils.hasScroll); $watchers.each(function () { $(this).data('select2-scroll-position', { x: $(this).scrollLeft(), y: $(this).scrollTop() }); }); $watchers.on(scrollEvent, function (ev) { var position = $(this).data('select2-scroll-position'); $(this).scrollTop(position.y); }); $(window).on(scrollEvent + ' ' + resizeEvent + ' ' + orientationEvent, function (e) { self._positionDropdown(); self._resizeDropdown(); }); }; AttachBody.prototype._detachPositioningHandler = function (decorated, container) { var scrollEvent = 'scroll.select2.' + container.id; var resizeEvent = 'resize.select2.' + container.id; var orientationEvent = 'orientationchange.select2.' + container.id; var $watchers = this.$container.parents().filter(Utils.hasScroll); $watchers.off(scrollEvent); $(window).off(scrollEvent + ' ' + resizeEvent + ' ' + orientationEvent); }; AttachBody.prototype._positionDropdown = function () { var $window = $(window); var isCurrentlyAbove = this.$dropdown.hasClass('select2-dropdown--above'); var isCurrentlyBelow = this.$dropdown.hasClass('select2-dropdown--below'); var newDirection = null; var position = this.$container.position(); var offset = this.$container.offset(); offset.bottom = offset.top + this.$container.outerHeight(false); var container = { height: this.$container.outerHeight(false) }; container.top = offset.top; container.bottom = offset.top + container.height; var dropdown = { height: this.$dropdown.outerHeight(false) }; var viewport = { top: $window.scrollTop(), bottom: $window.scrollTop() + $window.height() }; var enoughRoomAbove = viewport.top < (offset.top - dropdown.height); var enoughRoomBelow = viewport.bottom > (offset.bottom + dropdown.height); var css = { left: offset.left, top: container.bottom }; // Fix positioning with static parents if (this.$dropdownParent[0].style.position !== 'static') { var parentOffset = this.$dropdownParent.offset(); css.top -= parentOffset.top; css.left -= parentOffset.left; } if (!isCurrentlyAbove && !isCurrentlyBelow) { newDirection = 'below'; } if (!enoughRoomBelow && enoughRoomAbove && !isCurrentlyAbove) { newDirection = 'above'; } else if (!enoughRoomAbove && enoughRoomBelow && isCurrentlyAbove) { newDirection = 'below'; } if (newDirection == 'above' || (isCurrentlyAbove && newDirection !== 'below')) { css.top = container.top - dropdown.height; } if (newDirection != null) { this.$dropdown .removeClass('select2-dropdown--below select2-dropdown--above') .addClass('select2-dropdown--' + newDirection); this.$container .removeClass('select2-container--below select2-container--above') .addClass('select2-container--' + newDirection); } this.$dropdownContainer.css(css); }; AttachBody.prototype._resizeDropdown = function () { var css = { width: this.$container.outerWidth(false) + 'px' }; if (this.options.get('dropdownAutoWidth')) { css.minWidth = css.width; css.width = 'auto'; } this.$dropdown.css(css); }; AttachBody.prototype._showDropdown = function (decorated) { this.$dropdownContainer.appendTo(this.$dropdownParent); this._positionDropdown(); this._resizeDropdown(); }; return AttachBody; }); S2.define('select2/dropdown/minimumResultsForSearch',[ ], function () { function countResults (data) { var count = 0; for (var d = 0; d < data.length; d++) { var item = data[d]; if (item.children) { count += countResults(item.children); } else { count++; } } return count; } function MinimumResultsForSearch (decorated, $element, options, dataAdapter) { this.minimumResultsForSearch = options.get('minimumResultsForSearch'); if (this.minimumResultsForSearch < 0) { this.minimumResultsForSearch = Infinity; } decorated.call(this, $element, options, dataAdapter); } MinimumResultsForSearch.prototype.showSearch = function (decorated, params) { if (countResults(params.data.results) < this.minimumResultsForSearch) { return false; } return decorated.call(this, params); }; return MinimumResultsForSearch; }); S2.define('select2/dropdown/selectOnClose',[ ], function () { function SelectOnClose () { } SelectOnClose.prototype.bind = function (decorated, container, $container) { var self = this; decorated.call(this, container, $container); container.on('close', function () { self._handleSelectOnClose(); }); }; SelectOnClose.prototype._handleSelectOnClose = function () { var $highlightedResults = this.getHighlightedResults(); // Only select highlighted results if ($highlightedResults.length < 1) { return; } var data = $highlightedResults.data('data'); // Don't re-select already selected resulte if ( (data.element != null && data.element.selected) || (data.element == null && data.selected) ) { return; } this.trigger('select', { data: data }); }; return SelectOnClose; }); S2.define('select2/dropdown/closeOnSelect',[ ], function () { function CloseOnSelect () { } CloseOnSelect.prototype.bind = function (decorated, container, $container) { var self = this; decorated.call(this, container, $container); container.on('select', function (evt) { self._selectTriggered(evt); }); container.on('unselect', function (evt) { self._selectTriggered(evt); }); }; CloseOnSelect.prototype._selectTriggered = function (_, evt) { var originalEvent = evt.originalEvent; // Don't close if the control key is being held if (originalEvent && originalEvent.ctrlKey) { return; } this.trigger('close', {}); }; return CloseOnSelect; }); S2.define('select2/i18n/en',[],function () { // English return { errorLoading: function () { return 'The results could not be loaded.'; }, inputTooLong: function (args) { var overChars = args.input.length - args.maximum; var message = 'Please delete ' + overChars + ' character'; if (overChars != 1) { message += 's'; } return message; }, inputTooShort: function (args) { var remainingChars = args.minimum - args.input.length; var message = 'Please enter ' + remainingChars + ' or more characters'; return message; }, loadingMore: function () { return 'Loading more results…'; }, maximumSelected: function (args) { var message = 'You can only select ' + args.maximum + ' item'; if (args.maximum != 1) { message += 's'; } return message; }, noResults: function () { return 'No results found'; }, searching: function () { return 'Searching…'; } }; }); S2.define('select2/defaults',[ 'jquery', 'require', './results', './selection/single', './selection/multiple', './selection/placeholder', './selection/allowClear', './selection/search', './selection/eventRelay', './utils', './translation', './diacritics', './data/select', './data/array', './data/ajax', './data/tags', './data/tokenizer', './data/minimumInputLength', './data/maximumInputLength', './data/maximumSelectionLength', './dropdown', './dropdown/search', './dropdown/hidePlaceholder', './dropdown/infiniteScroll', './dropdown/attachBody', './dropdown/minimumResultsForSearch', './dropdown/selectOnClose', './dropdown/closeOnSelect', './i18n/en' ], function ($, require, ResultsList, SingleSelection, MultipleSelection, Placeholder, AllowClear, SelectionSearch, EventRelay, Utils, Translation, DIACRITICS, SelectData, ArrayData, AjaxData, Tags, Tokenizer, MinimumInputLength, MaximumInputLength, MaximumSelectionLength, Dropdown, DropdownSearch, HidePlaceholder, InfiniteScroll, AttachBody, MinimumResultsForSearch, SelectOnClose, CloseOnSelect, EnglishTranslation) { function Defaults () { this.reset(); } Defaults.prototype.apply = function (options) { options = $.extend({}, this.defaults, options); if (options.dataAdapter == null) { if (options.ajax != null) { options.dataAdapter = AjaxData; } else if (options.data != null) { options.dataAdapter = ArrayData; } else { options.dataAdapter = SelectData; } if (options.minimumInputLength > 0) { options.dataAdapter = Utils.Decorate( options.dataAdapter, MinimumInputLength ); } if (options.maximumInputLength > 0) { options.dataAdapter = Utils.Decorate( options.dataAdapter, MaximumInputLength ); } if (options.maximumSelectionLength > 0) { options.dataAdapter = Utils.Decorate( options.dataAdapter, MaximumSelectionLength ); } if (options.tags) { options.dataAdapter = Utils.Decorate(options.dataAdapter, Tags); } if (options.tokenSeparators != null || options.tokenizer != null) { options.dataAdapter = Utils.Decorate( options.dataAdapter, Tokenizer ); } if (options.query != null) { var Query = require(options.amdBase + 'compat/query'); options.dataAdapter = Utils.Decorate( options.dataAdapter, Query ); } if (options.initSelection != null) { var InitSelection = require(options.amdBase + 'compat/initSelection'); options.dataAdapter = Utils.Decorate( options.dataAdapter, InitSelection ); } } if (options.resultsAdapter == null) { options.resultsAdapter = ResultsList; if (options.ajax != null) { options.resultsAdapter = Utils.Decorate( options.resultsAdapter, InfiniteScroll ); } if (options.placeholder != null) { options.resultsAdapter = Utils.Decorate( options.resultsAdapter, HidePlaceholder ); } if (options.selectOnClose) { options.resultsAdapter = Utils.Decorate( options.resultsAdapter, SelectOnClose ); } } if (options.dropdownAdapter == null) { if (options.multiple) { options.dropdownAdapter = Dropdown; } else { var SearchableDropdown = Utils.Decorate(Dropdown, DropdownSearch); options.dropdownAdapter = SearchableDropdown; } if (options.minimumResultsForSearch !== 0) { options.dropdownAdapter = Utils.Decorate( options.dropdownAdapter, MinimumResultsForSearch ); } if (options.closeOnSelect) { options.dropdownAdapter = Utils.Decorate( options.dropdownAdapter, CloseOnSelect ); } if ( options.dropdownCssClass != null || options.dropdownCss != null || options.adaptDropdownCssClass != null ) { var DropdownCSS = require(options.amdBase + 'compat/dropdownCss'); options.dropdownAdapter = Utils.Decorate( options.dropdownAdapter, DropdownCSS ); } options.dropdownAdapter = Utils.Decorate( options.dropdownAdapter, AttachBody ); } if (options.selectionAdapter == null) { if (options.multiple) { options.selectionAdapter = MultipleSelection; } else { options.selectionAdapter = SingleSelection; } // Add the placeholder mixin if a placeholder was specified if (options.placeholder != null) { options.selectionAdapter = Utils.Decorate( options.selectionAdapter, Placeholder ); } if (options.allowClear) { options.selectionAdapter = Utils.Decorate( options.selectionAdapter, AllowClear ); } if (options.multiple) { options.selectionAdapter = Utils.Decorate( options.selectionAdapter, SelectionSearch ); } if ( options.containerCssClass != null || options.containerCss != null || options.adaptContainerCssClass != null ) { var ContainerCSS = require(options.amdBase + 'compat/containerCss'); options.selectionAdapter = Utils.Decorate( options.selectionAdapter, ContainerCSS ); } options.selectionAdapter = Utils.Decorate( options.selectionAdapter, EventRelay ); } if (typeof options.language === 'string') { // Check if the language is specified with a region if (options.language.indexOf('-') > 0) { // Extract the region information if it is included var languageParts = options.language.split('-'); var baseLanguage = languageParts[0]; options.language = [options.language, baseLanguage]; } else { options.language = [options.language]; } } if ($.isArray(options.language)) { var languages = new Translation(); options.language.push('en'); var languageNames = options.language; for (var l = 0; l < languageNames.length; l++) { var name = languageNames[l]; var language = {}; try { // Try to load it with the original name language = Translation.loadPath(name); } catch (e) { try { // If we couldn't load it, check if it wasn't the full path name = this.defaults.amdLanguageBase + name; language = Translation.loadPath(name); } catch (ex) { // The translation could not be loaded at all. Sometimes this is // because of a configuration problem, other times this can be // because of how Select2 helps load all possible translation files. if (options.debug && window.console && console.warn) { console.warn( 'Select2: The language file for "' + name + '" could not be ' + 'automatically loaded. A fallback will be used instead.' ); } continue; } } languages.extend(language); } options.translations = languages; } else { var baseTranslation = Translation.loadPath( this.defaults.amdLanguageBase + 'en' ); var customTranslation = new Translation(options.language); customTranslation.extend(baseTranslation); options.translations = customTranslation; } return options; }; Defaults.prototype.reset = function () { function stripDiacritics (text) { // Used 'uni range + named function' from http://jsperf.com/diacritics/18 function match(a) { return DIACRITICS[a] || a; } return text.replace(/[^\u0000-\u007E]/g, match); } function matcher (params, data) { // Always return the object if there is nothing to compare if ($.trim(params.term) === '') { return data; } // Do a recursive check for options with children if (data.children && data.children.length > 0) { // Clone the data object if there are children // This is required as we modify the object to remove any non-matches var match = $.extend(true, {}, data); // Check each child of the option for (var c = data.children.length - 1; c >= 0; c--) { var child = data.children[c]; var matches = matcher(params, child); // If there wasn't a match, remove the object in the array if (matches == null) { match.children.splice(c, 1); } } // If any children matched, return the new object if (match.children.length > 0) { return match; } // If there were no matching children, check just the plain object return matcher(params, match); } var original = stripDiacritics(data.text).toUpperCase(); var term = stripDiacritics(params.term).toUpperCase(); // Check if the text contains the term if (original.indexOf(term) > -1) { return data; } // If it doesn't contain the term, don't return anything return null; } this.defaults = { amdBase: './', amdLanguageBase: './i18n/', closeOnSelect: true, debug: false, dropdownAutoWidth: false, escapeMarkup: Utils.escapeMarkup, language: EnglishTranslation, matcher: matcher, minimumInputLength: 0, maximumInputLength: 0, maximumSelectionLength: 0, minimumResultsForSearch: 0, selectOnClose: false, sorter: function (data) { return data; }, templateResult: function (result) { return result.text; }, templateSelection: function (selection) { return selection.text; }, theme: 'default', width: 'resolve' }; }; Defaults.prototype.set = function (key, value) { var camelKey = $.camelCase(key); var data = {}; data[camelKey] = value; var convertedData = Utils._convertData(data); $.extend(this.defaults, convertedData); }; var defaults = new Defaults(); return defaults; }); S2.define('select2/options',[ 'require', 'jquery', './defaults', './utils' ], function (require, $, Defaults, Utils) { function Options (options, $element) { this.options = options; if ($element != null) { this.fromElement($element); } this.options = Defaults.apply(this.options); if ($element && $element.is('input')) { var InputCompat = require(this.get('amdBase') + 'compat/inputData'); this.options.dataAdapter = Utils.Decorate( this.options.dataAdapter, InputCompat ); } } Options.prototype.fromElement = function ($e) { var excludedData = ['select2']; if (this.options.multiple == null) { this.options.multiple = $e.prop('multiple'); } if (this.options.disabled == null) { this.options.disabled = $e.prop('disabled'); } if (this.options.language == null) { if ($e.prop('lang')) { this.options.language = $e.prop('lang').toLowerCase(); } else if ($e.closest('[lang]').prop('lang')) { this.options.language = $e.closest('[lang]').prop('lang'); } } if (this.options.dir == null) { if ($e.prop('dir')) { this.options.dir = $e.prop('dir'); } else if ($e.closest('[dir]').prop('dir')) { this.options.dir = $e.closest('[dir]').prop('dir'); } else { this.options.dir = 'ltr'; } } $e.prop('disabled', this.options.disabled); $e.prop('multiple', this.options.multiple); if ($e.data('select2Tags')) { if (this.options.debug && window.console && console.warn) { console.warn( 'Select2: The `data-select2-tags` attribute has been changed to ' + 'use the `data-data` and `data-tags="true"` attributes and will be ' + 'removed in future versions of Select2.' ); } $e.data('data', $e.data('select2Tags')); $e.data('tags', true); } if ($e.data('ajaxUrl')) { if (this.options.debug && window.console && console.warn) { console.warn( 'Select2: The `data-ajax-url` attribute has been changed to ' + '`data-ajax--url` and support for the old attribute will be removed' + ' in future versions of Select2.' ); } $e.attr('ajax--url', $e.data('ajaxUrl')); $e.data('ajax--url', $e.data('ajaxUrl')); } var dataset = {}; // Prefer the element's `dataset` attribute if it exists // jQuery 1.x does not correctly handle data attributes with multiple dashes if ($.fn.jquery && $.fn.jquery.substr(0, 2) == '1.' && $e[0].dataset) { dataset = $.extend(true, {}, $e[0].dataset, $e.data()); } else { dataset = $e.data(); } var data = $.extend(true, {}, dataset); data = Utils._convertData(data); for (var key in data) { if ($.inArray(key, excludedData) > -1) { continue; } if ($.isPlainObject(this.options[key])) { $.extend(this.options[key], data[key]); } else { this.options[key] = data[key]; } } return this; }; Options.prototype.get = function (key) { return this.options[key]; }; Options.prototype.set = function (key, val) { this.options[key] = val; }; return Options; }); S2.define('select2/core',[ 'jquery', './options', './utils', './keys' ], function ($, Options, Utils, KEYS) { var Select2 = function ($element, options) { if ($element.data('select2') != null) { $element.data('select2').destroy(); } this.$element = $element; this.id = this._generateId($element); options = options || {}; this.options = new Options(options, $element); Select2.__super__.constructor.call(this); // Set up the tabindex var tabindex = $element.attr('tabindex') || 0; $element.data('old-tabindex', tabindex); $element.attr('tabindex', '-1'); // Set up containers and adapters var DataAdapter = this.options.get('dataAdapter'); this.dataAdapter = new DataAdapter($element, this.options); var $container = this.render(); this._placeContainer($container); var SelectionAdapter = this.options.get('selectionAdapter'); this.selection = new SelectionAdapter($element, this.options); this.$selection = this.selection.render(); this.selection.position(this.$selection, $container); var DropdownAdapter = this.options.get('dropdownAdapter'); this.dropdown = new DropdownAdapter($element, this.options); this.$dropdown = this.dropdown.render(); this.dropdown.position(this.$dropdown, $container); var ResultsAdapter = this.options.get('resultsAdapter'); this.results = new ResultsAdapter($element, this.options, this.dataAdapter); this.$results = this.results.render(); this.results.position(this.$results, this.$dropdown); // Bind events var self = this; // Bind the container to all of the adapters this._bindAdapters(); // Register any DOM event handlers this._registerDomEvents(); // Register any internal event handlers this._registerDataEvents(); this._registerSelectionEvents(); this._registerDropdownEvents(); this._registerResultsEvents(); this._registerEvents(); // Set the initial state this.dataAdapter.current(function (initialData) { self.trigger('selection:update', { data: initialData }); }); // Hide the original select $element.addClass('select2-hidden-accessible'); $element.attr('aria-hidden', 'true'); // Synchronize any monitored attributes this._syncAttributes(); $element.data('select2', this); }; Utils.Extend(Select2, Utils.Observable); Select2.prototype._generateId = function ($element) { var id = ''; if ($element.attr('id') != null) { id = $element.attr('id'); } else if ($element.attr('name') != null) { id = $element.attr('name') + '-' + Utils.generateChars(2); } else { id = Utils.generateChars(4); } id = 'select2-' + id; return id; }; Select2.prototype._placeContainer = function ($container) { $container.insertAfter(this.$element); var width = this._resolveWidth(this.$element, this.options.get('width')); if (width != null) { $container.css('width', width); } }; Select2.prototype._resolveWidth = function ($element, method) { var WIDTH = /^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i; if (method == 'resolve') { var styleWidth = this._resolveWidth($element, 'style'); if (styleWidth != null) { return styleWidth; } return this._resolveWidth($element, 'element'); } if (method == 'element') { var elementWidth = $element.outerWidth(false); if (elementWidth <= 0) { return 'auto'; } return elementWidth + 'px'; } if (method == 'style') { var style = $element.attr('style'); if (typeof(style) !== 'string') { return null; } var attrs = style.split(';'); for (var i = 0, l = attrs.length; i < l; i = i + 1) { var attr = attrs[i].replace(/\s/g, ''); var matches = attr.match(WIDTH); if (matches !== null && matches.length >= 1) { return matches[1]; } } return null; } return method; }; Select2.prototype._bindAdapters = function () { this.dataAdapter.bind(this, this.$container); this.selection.bind(this, this.$container); this.dropdown.bind(this, this.$container); this.results.bind(this, this.$container); }; Select2.prototype._registerDomEvents = function () { var self = this; this.$element.on('change.select2', function () { self.dataAdapter.current(function (data) { self.trigger('selection:update', { data: data }); }); }); this._sync = Utils.bind(this._syncAttributes, this); if (this.$element[0].attachEvent) { this.$element[0].attachEvent('onpropertychange', this._sync); } var observer = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver ; if (observer != null) { this._observer = new observer(function (mutations) { $.each(mutations, self._sync); }); this._observer.observe(this.$element[0], { attributes: true, subtree: false }); } else if (this.$element[0].addEventListener) { this.$element[0].addEventListener('DOMAttrModified', self._sync, false); } }; Select2.prototype._registerDataEvents = function () { var self = this; this.dataAdapter.on('*', function (name, params) { self.trigger(name, params); }); }; Select2.prototype._registerSelectionEvents = function () { var self = this; var nonRelayEvents = ['toggle', 'focus']; this.selection.on('toggle', function () { self.toggleDropdown(); }); this.selection.on('focus', function (params) { self.focus(params); }); this.selection.on('*', function (name, params) { if ($.inArray(name, nonRelayEvents) !== -1) { return; } self.trigger(name, params); }); }; Select2.prototype._registerDropdownEvents = function () { var self = this; this.dropdown.on('*', function (name, params) { self.trigger(name, params); }); }; Select2.prototype._registerResultsEvents = function () { var self = this; this.results.on('*', function (name, params) { self.trigger(name, params); }); }; Select2.prototype._registerEvents = function () { var self = this; this.on('open', function () { self.$container.addClass('select2-container--open'); }); this.on('close', function () { self.$container.removeClass('select2-container--open'); }); this.on('enable', function () { self.$container.removeClass('select2-container--disabled'); }); this.on('disable', function () { self.$container.addClass('select2-container--disabled'); }); this.on('blur', function () { self.$container.removeClass('select2-container--focus'); }); this.on('query', function (params) { if (!self.isOpen()) { self.trigger('open', {}); } this.dataAdapter.query(params, function (data) { self.trigger('results:all', { data: data, query: params }); }); }); this.on('query:append', function (params) { this.dataAdapter.query(params, function (data) { self.trigger('results:append', { data: data, query: params }); }); }); this.on('keypress', function (evt) { var key = evt.which; if (self.isOpen()) { if (key === KEYS.ESC || key === KEYS.TAB || (key === KEYS.UP && evt.altKey)) { self.close(); evt.preventDefault(); } else if (key === KEYS.ENTER) { self.trigger('results:select', {}); evt.preventDefault(); } else if ((key === KEYS.SPACE && evt.ctrlKey)) { self.trigger('results:toggle', {}); evt.preventDefault(); } else if (key === KEYS.UP) { self.trigger('results:previous', {}); evt.preventDefault(); } else if (key === KEYS.DOWN) { self.trigger('results:next', {}); evt.preventDefault(); } } else { if (key === KEYS.ENTER || key === KEYS.SPACE || (key === KEYS.DOWN && evt.altKey)) { self.open(); evt.preventDefault(); } } }); }; Select2.prototype._syncAttributes = function () { this.options.set('disabled', this.$element.prop('disabled')); if (this.options.get('disabled')) { if (this.isOpen()) { this.close(); } this.trigger('disable', {}); } else { this.trigger('enable', {}); } }; /** * Override the trigger method to automatically trigger pre-events when * there are events that can be prevented. */ Select2.prototype.trigger = function (name, args) { var actualTrigger = Select2.__super__.trigger; var preTriggerMap = { 'open': 'opening', 'close': 'closing', 'select': 'selecting', 'unselect': 'unselecting' }; if (args === undefined) { args = {}; } if (name in preTriggerMap) { var preTriggerName = preTriggerMap[name]; var preTriggerArgs = { prevented: false, name: name, args: args }; actualTrigger.call(this, preTriggerName, preTriggerArgs); if (preTriggerArgs.prevented) { args.prevented = true; return; } } actualTrigger.call(this, name, args); }; Select2.prototype.toggleDropdown = function () { if (this.options.get('disabled')) { return; } if (this.isOpen()) { this.close(); } else { this.open(); } }; Select2.prototype.open = function () { if (this.isOpen()) { return; } this.trigger('query', {}); }; Select2.prototype.close = function () { if (!this.isOpen()) { return; } this.trigger('close', {}); }; Select2.prototype.isOpen = function () { return this.$container.hasClass('select2-container--open'); }; Select2.prototype.hasFocus = function () { return this.$container.hasClass('select2-container--focus'); }; Select2.prototype.focus = function (data) { // No need to re-trigger focus events if we are already focused if (this.hasFocus()) { return; } this.$container.addClass('select2-container--focus'); this.trigger('focus', {}); }; Select2.prototype.enable = function (args) { if (this.options.get('debug') && window.console && console.warn) { console.warn( 'Select2: The `select2("enable")` method has been deprecated and will' + ' be removed in later Select2 versions. Use $element.prop("disabled")' + ' instead.' ); } if (args == null || args.length === 0) { args = [true]; } var disabled = !args[0]; this.$element.prop('disabled', disabled); }; Select2.prototype.data = function () { if (this.options.get('debug') && arguments.length > 0 && window.console && console.warn) { console.warn( 'Select2: Data can no longer be set using `select2("data")`. You ' + 'should consider setting the value instead using `$element.val()`.' ); } var data = []; this.dataAdapter.current(function (currentData) { data = currentData; }); return data; }; Select2.prototype.val = function (args) { if (this.options.get('debug') && window.console && console.warn) { console.warn( 'Select2: The `select2("val")` method has been deprecated and will be' + ' removed in later Select2 versions. Use $element.val() instead.' ); } if (args == null || args.length === 0) { return this.$element.val(); } var newVal = args[0]; if ($.isArray(newVal)) { newVal = $.map(newVal, function (obj) { return obj.toString(); }); } this.$element.val(newVal).trigger('change'); }; Select2.prototype.destroy = function () { this.$container.remove(); if (this.$element[0].detachEvent) { this.$element[0].detachEvent('onpropertychange', this._sync); } if (this._observer != null) { this._observer.disconnect(); this._observer = null; } else if (this.$element[0].removeEventListener) { this.$element[0] .removeEventListener('DOMAttrModified', this._sync, false); } this._sync = null; this.$element.off('.select2'); this.$element.attr('tabindex', this.$element.data('old-tabindex')); this.$element.removeClass('select2-hidden-accessible'); this.$element.attr('aria-hidden', 'false'); this.$element.removeData('select2'); this.dataAdapter.destroy(); this.selection.destroy(); this.dropdown.destroy(); this.results.destroy(); this.dataAdapter = null; this.selection = null; this.dropdown = null; this.results = null; }; Select2.prototype.render = function () { var $container = $( '' + '' + '' + '' ); $container.attr('dir', this.options.get('dir')); this.$container = $container; this.$container.addClass('select2-container--' + this.options.get('theme')); $container.data('element', this.$element); return $container; }; return Select2; }); S2.define('jquery-mousewheel',[ 'jquery' ], function ($) { // Used to shim jQuery.mousewheel for non-full builds. return $; }); S2.define('jquery.select2',[ 'jquery', 'jquery-mousewheel', './select2/core', './select2/defaults' ], function ($, _, Select2, Defaults) { if ($.fn.select2 == null) { // All methods that should return the element var thisMethods = ['open', 'close', 'destroy']; $.fn.select2 = function (options) { options = options || {}; if (typeof options === 'object') { this.each(function () { var instanceOptions = $.extend(true, {}, options); var instance = new Select2($(this), instanceOptions); }); return this; } else if (typeof options === 'string') { var ret; this.each(function () { var instance = $(this).data('select2'); if (instance == null && window.console && console.error) { console.error( 'The select2(\'' + options + '\') method was called on an ' + 'element that is not using Select2.' ); } var args = Array.prototype.slice.call(arguments, 1); ret = instance[options].apply(instance, args); }); // Check if we should be returning `this` if ($.inArray(options, thisMethods) > -1) { return this; } return ret; } else { throw new Error('Invalid arguments for Select2: ' + options); } }; } if ($.fn.select2.defaults == null) { $.fn.select2.defaults = Defaults; } return Select2; }); // Return the AMD loader configuration so it can be used outside of this file return { define: S2.define, require: S2.require }; }()); // Autoload the jQuery bindings // We know that all of the modules exist above this, so we're safe var select2 = S2.require('jquery.select2'); // Hold the AMD module references on the jQuery function that was just loaded // This allows Select2 to use the internal loader outside of this file, such // as in the language files. jQuery.fn.select2.amd = S2; // Return the Select2 instance for anyone who is importing it. return select2; })); ;(function() { var supportCustomEvent = window.CustomEvent; if (!supportCustomEvent || typeof supportCustomEvent == 'object') { supportCustomEvent = function CustomEvent(event, x) { x = x || {}; var ev = document.createEvent('CustomEvent'); ev.initCustomEvent(event, !!x.bubbles, !!x.cancelable, x.detail || null); return ev; }; supportCustomEvent.prototype = window.Event.prototype; } /** * Finds the nearest from the passed element. * * @param {Element} el to search from * @return {HTMLDialogElement} dialog found */ function findNearestDialog(el) { while (el) { if (el.nodeName.toUpperCase() == 'DIALOG') { return /** @type {HTMLDialogElement} */ (el); } el = el.parentElement; } return null; } /** * Blur the specified element, as long as it's not the HTML body element. * This works around an IE9/10 bug - blurring the body causes Windows to * blur the whole application. * * @param {Element} el to blur */ function safeBlur(el) { if (el && el.blur && el != document.body) { el.blur(); } } /** * @param {!NodeList} nodeList to search * @param {Node} node to find * @return {boolean} whether node is inside nodeList */ function inNodeList(nodeList, node) { for (var i = 0; i < nodeList.length; ++i) { if (nodeList[i] == node) { return true; } } return false; } /** * @param {!HTMLDialogElement} dialog to upgrade * @constructor */ function dialogPolyfillInfo(dialog) { this.dialog_ = dialog; this.replacedStyleTop_ = false; this.openAsModal_ = false; // Set a11y role. Browsers that support dialog implicitly know this already. if (!dialog.hasAttribute('role')) { dialog.setAttribute('role', 'dialog'); } dialog.show = this.show.bind(this); dialog.showModal = this.showModal.bind(this); dialog.close = this.close.bind(this); if (!('returnValue' in dialog)) { dialog.returnValue = ''; } this.maybeHideModal = this.maybeHideModal.bind(this); if ('MutationObserver' in window) { // IE11+, most other browsers. var mo = new MutationObserver(this.maybeHideModal); mo.observe(dialog, { attributes: true, attributeFilter: ['open'] }); } else { dialog.addEventListener('DOMAttrModified', this.maybeHideModal); } // Note that the DOM is observed inside DialogManager while any dialog // is being displayed as a modal, to catch modal removal from the DOM. Object.defineProperty(dialog, 'open', { set: this.setOpen.bind(this), get: dialog.hasAttribute.bind(dialog, 'open') }); this.backdrop_ = document.createElement('div'); this.backdrop_.className = 'backdrop'; this.backdropClick_ = this.backdropClick_.bind(this); } dialogPolyfillInfo.prototype = { get dialog() { return this.dialog_; }, /** * Maybe remove this dialog from the modal top layer. This is called when * a modal dialog may no longer be tenable, e.g., when the dialog is no * longer open or is no longer part of the DOM. */ maybeHideModal: function() { if (!this.openAsModal_) { return; } if (this.dialog_.hasAttribute('open') && document.body.contains(this.dialog_)) { return; } this.openAsModal_ = false; this.dialog_.style.zIndex = ''; // This won't match the native exactly because if the user set // top on a centered polyfill dialog, that top gets thrown away when the // dialog is closed. Not sure it's possible to polyfill this perfectly. if (this.replacedStyleTop_) { this.dialog_.style.top = ''; this.replacedStyleTop_ = false; } // Optimistically clear the modal part of this . this.backdrop_.removeEventListener('click', this.backdropClick_); if (this.backdrop_.parentElement) { this.backdrop_.parentElement.removeChild(this.backdrop_); } dialogPolyfill.dm.removeDialog(this); }, /** * @param {boolean} value whether to open or close this dialog */ setOpen: function(value) { if (value) { this.dialog_.hasAttribute('open') || this.dialog_.setAttribute('open', ''); } else { this.dialog_.removeAttribute('open'); this.maybeHideModal(); // nb. redundant with MutationObserver } }, /** * Handles clicks on the fake .backdrop element, redirecting them as if * they were on the dialog itself. * * @param {!Event} e to redirect */ backdropClick_: function(e) { var redirectedEvent = document.createEvent('MouseEvents'); redirectedEvent.initMouseEvent(e.type, e.bubbles, e.cancelable, window, e.detail, e.screenX, e.screenY, e.clientX, e.clientY, e.ctrlKey, e.altKey, e.shiftKey, e.metaKey, e.button, e.relatedTarget); this.dialog_.dispatchEvent(redirectedEvent); e.stopPropagation(); }, /** * Sets the zIndex for the backdrop and dialog. * * @param {number} backdropZ * @param {number} dialogZ */ updateZIndex: function(backdropZ, dialogZ) { this.backdrop_.style.zIndex = backdropZ; this.dialog_.style.zIndex = dialogZ; }, /** * Shows the dialog. This is idempotent and will always succeed. */ show: function() { this.setOpen(true); }, /** * Show this dialog modally. */ showModal: function() { if (this.dialog_.hasAttribute('open')) { throw new Error('Failed to execute \'showModal\' on dialog: The element is already open, and therefore cannot be opened modally.'); } if (!document.body.contains(this.dialog_)) { throw new Error('Failed to execute \'showModal\' on dialog: The element is not in a Document.'); } if (!dialogPolyfill.dm.pushDialog(this)) { throw new Error('Failed to execute \'showModal\' on dialog: There are too many open modal dialogs.'); } this.show(); this.openAsModal_ = true; // Optionally center vertically, relative to the current viewport. if (dialogPolyfill.needsCentering(this.dialog_)) { dialogPolyfill.reposition(this.dialog_); this.replacedStyleTop_ = true; } else { this.replacedStyleTop_ = false; } // Insert backdrop. this.backdrop_.addEventListener('click', this.backdropClick_); this.dialog_.parentNode.insertBefore(this.backdrop_, this.dialog_.nextSibling); // Find element with `autofocus` attribute or first form control. var target = this.dialog_.querySelector('[autofocus]:not([disabled])'); if (!target) { // TODO: technically this is 'any focusable area' var opts = ['button', 'input', 'keygen', 'select', 'textarea']; var query = opts.map(function(el) { return el + ':not([disabled])'; }).join(', '); target = this.dialog_.querySelector(query); } safeBlur(document.activeElement); target && target.focus(); }, /** * Closes this HTMLDialogElement. This is optional vs clearing the open * attribute, however this fires a 'close' event. * * @param {string=} opt_returnValue to use as the returnValue */ close: function(opt_returnValue) { if (!this.dialog_.hasAttribute('open')) { throw new Error('Failed to execute \'close\' on dialog: The element does not have an \'open\' attribute, and therefore cannot be closed.'); } this.setOpen(false); // Leave returnValue untouched in case it was set directly on the element if (opt_returnValue !== undefined) { this.dialog_.returnValue = opt_returnValue; } // Triggering "close" event for any attached listeners on the . var closeEvent = new supportCustomEvent('close', { bubbles: false, cancelable: false }); this.dialog_.dispatchEvent(closeEvent); } }; var dialogPolyfill = {}; dialogPolyfill.reposition = function(element) { var scrollTop = document.body.scrollTop || document.documentElement.scrollTop; var topValue = scrollTop + (window.innerHeight - element.offsetHeight) / 2; element.style.top = Math.max(scrollTop, topValue) + 'px'; }; dialogPolyfill.isInlinePositionSetByStylesheet = function(element) { for (var i = 0; i < document.styleSheets.length; ++i) { var styleSheet = document.styleSheets[i]; var cssRules = null; // Some browsers throw on cssRules. try { cssRules = styleSheet.cssRules; } catch (e) {} if (!cssRules) continue; for (var j = 0; j < cssRules.length; ++j) { var rule = cssRules[j]; var selectedNodes = null; // Ignore errors on invalid selector texts. try { selectedNodes = document.querySelectorAll(rule.selectorText); } catch(e) {} if (!selectedNodes || !inNodeList(selectedNodes, element)) continue; var cssTop = rule.style.getPropertyValue('top'); var cssBottom = rule.style.getPropertyValue('bottom'); if ((cssTop && cssTop != 'auto') || (cssBottom && cssBottom != 'auto')) return true; } } return false; }; dialogPolyfill.needsCentering = function(dialog) { var computedStyle = window.getComputedStyle(dialog); if (computedStyle.position != 'absolute') { return false; } // We must determine whether the top/bottom specified value is non-auto. In // WebKit/Blink, checking computedStyle.top == 'auto' is sufficient, but // Firefox returns the used value. So we do this crazy thing instead: check // the inline style and then go through CSS rules. if ((dialog.style.top != 'auto' && dialog.style.top != '') || (dialog.style.bottom != 'auto' && dialog.style.bottom != '')) return false; return !dialogPolyfill.isInlinePositionSetByStylesheet(dialog); }; /** * @param {!Element} element to force upgrade */ dialogPolyfill.forceRegisterDialog = function(element) { if (element.showModal) { console.warn('This browser already supports , the polyfill ' + 'may not work correctly', element); } if (element.nodeName.toUpperCase() != 'DIALOG') { throw new Error('Failed to register dialog: The element is not a dialog.'); } new dialogPolyfillInfo(/** @type {!HTMLDialogElement} */ (element)); }; /** * @param {!Element} element to upgrade */ dialogPolyfill.registerDialog = function(element) { if (element.showModal) { console.warn('Can\'t upgrade : already supported', element); } else { dialogPolyfill.forceRegisterDialog(element); } }; /** * @constructor */ dialogPolyfill.DialogManager = function() { /** @type {!Array} */ this.pendingDialogStack = []; // The overlay is used to simulate how a modal dialog blocks the document. // The blocking dialog is positioned on top of the overlay, and the rest of // the dialogs on the pending dialog stack are positioned below it. In the // actual implementation, the modal dialog stacking is controlled by the // top layer, where z-index has no effect. this.overlay = document.createElement('div'); this.overlay.className = '_dialog_overlay'; this.overlay.addEventListener('click', function(e) { e.stopPropagation(); }); this.handleKey_ = this.handleKey_.bind(this); this.handleFocus_ = this.handleFocus_.bind(this); this.handleRemove_ = this.handleRemove_.bind(this); this.zIndexLow_ = 100000; this.zIndexHigh_ = 100000 + 150; }; /** * @return {Element} the top HTML dialog element, if any */ dialogPolyfill.DialogManager.prototype.topDialogElement = function() { if (this.pendingDialogStack.length) { var t = this.pendingDialogStack[this.pendingDialogStack.length - 1]; return t.dialog; } return null; }; /** * Called on the first modal dialog being shown. Adds the overlay and related * handlers. */ dialogPolyfill.DialogManager.prototype.blockDocument = function() { document.body.appendChild(this.overlay); document.body.addEventListener('focus', this.handleFocus_, true); document.addEventListener('keydown', this.handleKey_); document.addEventListener('DOMNodeRemoved', this.handleRemove_); }; /** * Called on the first modal dialog being removed, i.e., when no more modal * dialogs are visible. */ dialogPolyfill.DialogManager.prototype.unblockDocument = function() { document.body.removeChild(this.overlay); document.body.removeEventListener('focus', this.handleFocus_, true); document.removeEventListener('keydown', this.handleKey_); document.removeEventListener('DOMNodeRemoved', this.handleRemove_); }; dialogPolyfill.DialogManager.prototype.updateStacking = function() { var zIndex = this.zIndexLow_; for (var i = 0; i < this.pendingDialogStack.length; i++) { if (i == this.pendingDialogStack.length - 1) { this.overlay.style.zIndex = zIndex++; } this.pendingDialogStack[i].updateZIndex(zIndex++, zIndex++); } }; dialogPolyfill.DialogManager.prototype.handleFocus_ = function(event) { var candidate = findNearestDialog(/** @type {Element} */ (event.target)); if (candidate != this.topDialogElement()) { event.preventDefault(); event.stopPropagation(); safeBlur(/** @type {Element} */ (event.target)); // TODO: Focus on the browser chrome (aka document) or the dialog itself // depending on the tab direction. return false; } }; dialogPolyfill.DialogManager.prototype.handleKey_ = function(event) { if (event.keyCode == 27) { event.preventDefault(); event.stopPropagation(); var cancelEvent = new supportCustomEvent('cancel', { bubbles: false, cancelable: true }); var dialog = this.topDialogElement(); if (dialog.dispatchEvent(cancelEvent)) { dialog.close(); } } }; dialogPolyfill.DialogManager.prototype.handleRemove_ = function(event) { if (event.target.nodeName.toUpperCase() != 'DIALOG') { return; } var dialog = /** @type {HTMLDialogElement} */ (event.target); if (!dialog.open) { return; } // Find a dialogPolyfillInfo which matches the removed . this.pendingDialogStack.some(function(dpi) { if (dpi.dialog == dialog) { // This call will clear the dialogPolyfillInfo on this DialogManager // as a side effect. dpi.maybeHideModal(); return true; } }); }; /** * @param {!dialogPolyfillInfo} dpi * @return {boolean} whether the dialog was allowed */ dialogPolyfill.DialogManager.prototype.pushDialog = function(dpi) { var allowed = (this.zIndexHigh_ - this.zIndexLow_) / 2 - 1; if (this.pendingDialogStack.length >= allowed) { return false; } this.pendingDialogStack.push(dpi); if (this.pendingDialogStack.length == 1) { this.blockDocument(); } this.updateStacking(); return true; }; /** * @param {dialogPolyfillInfo} dpi */ dialogPolyfill.DialogManager.prototype.removeDialog = function(dpi) { var index = this.pendingDialogStack.indexOf(dpi); if (index == -1) { return; } this.pendingDialogStack.splice(index, 1); this.updateStacking(); if (this.pendingDialogStack.length == 0) { this.unblockDocument(); } }; dialogPolyfill.dm = new dialogPolyfill.DialogManager(); /** * Global form 'dialog' method handler. Closes a dialog correctly on submit * and possibly sets its return value. */ document.addEventListener('submit', function(ev) { var target = ev.target; if (!target || !target.hasAttribute('method')) { return; } if (target.getAttribute('method').toLowerCase() != 'dialog') { return; } ev.preventDefault(); var dialog = findNearestDialog(/** @type {Element} */ (ev.target)); if (!dialog) { return; } // FIXME: The original event doesn't contain the element used to submit the // form (if any). Look in some possible places. var returnValue; var cands = [document.activeElement, ev.explicitOriginalTarget]; var els = ['BUTTON', 'INPUT']; cands.some(function(cand) { if (cand && cand.form == ev.target && els.indexOf(cand.nodeName.toUpperCase()) != -1) { returnValue = cand.value; return true; } }); dialog.close(returnValue); }, true); dialogPolyfill['forceRegisterDialog'] = dialogPolyfill.forceRegisterDialog; dialogPolyfill['registerDialog'] = dialogPolyfill.registerDialog; if (typeof module === 'object' && typeof module['exports'] === 'object') { // CommonJS support module['exports'] = dialogPolyfill; } else if (typeof define === 'function' && 'amd' in define) { // AMD support define(function() { return dialogPolyfill; }); } else { // all others window['dialogPolyfill'] = dialogPolyfill; } })(); ;;(function( win, $ ) { function featureTest( property, value, noPrefixes ) { // Thanks Modernizr! https://github.com/phistuck/Modernizr/commit/3fb7217f5f8274e2f11fe6cfeda7cfaf9948a1f5 var prop = property + ':', el = document.createElement( 'test' ), mStyle = el.style; if( !noPrefixes ) { mStyle.cssText = prop + [ '-webkit-', '-moz-', '-ms-', '-o-', '' ].join( value + ';' + prop ) + value + ';'; } else { mStyle.cssText = prop + value; } return mStyle[ property ].indexOf( value ) !== -1; } function getPx( unit ) { return parseInt( unit, 10 ) || 0; } var uniqueIdCounter = 0; var S = { classes: { plugin: 'fixedsticky', active: 'fixedsticky-on', inactive: 'fixedsticky-off', clone: 'fixedsticky-dummy', withoutFixedFixed: 'fixedsticky-withoutfixedfixed' }, keys: { offset: 'fixedStickyOffset', position: 'fixedStickyPosition', id: 'fixedStickyId' }, tests: { sticky: featureTest( 'position', 'sticky' ), fixed: featureTest( 'position', 'fixed', true ) }, // Thanks jQuery! getScrollTop: function() { var prop = 'pageYOffset', method = 'scrollTop'; return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : win.document.body[ method ]; }, bypass: function() { // Check native sticky, check fixed and if fixed-fixed is also included on the page and is supported return ( S.tests.sticky && !S.optOut ) || !S.tests.fixed || win.FixedFixed && !$( win.document.documentElement ).hasClass( 'fixed-supported' ); }, update: function( el ) { if( !el.offsetWidth ) { return; } var $el = $( el ), height = $el.outerHeight(), initialOffset = $el.data( S.keys.offset ), scroll = S.getScrollTop(), isAlreadyOn = $el.is( '.' + S.classes.active ), toggle = function( turnOn ) { $el[ turnOn ? 'addClass' : 'removeClass' ]( S.classes.active ) [ !turnOn ? 'addClass' : 'removeClass' ]( S.classes.inactive ); }, viewportHeight = $( window ).height(), position = $el.data( S.keys.position ), skipSettingToFixed, elTop, elBottom, $parent = $el.parent(), parentOffset = $parent.offset().top, parentHeight = $parent.outerHeight(); if( initialOffset === undefined ) { initialOffset = $el.offset().top; $el.data( S.keys.offset, initialOffset ); $el.after( $( '
    ' ).addClass( S.classes.clone ).height( height ) ); } if( !position ) { // Some browsers require fixed/absolute to report accurate top/left values. skipSettingToFixed = $el.css( 'top' ) !== 'auto' || $el.css( 'bottom' ) !== 'auto'; if( !skipSettingToFixed ) { $el.css( 'position', 'fixed' ); } position = { top: $el.css( 'top' ) !== 'auto', bottom: $el.css( 'bottom' ) !== 'auto' }; if( !skipSettingToFixed ) { $el.css( 'position', '' ); } $el.data( S.keys.position, position ); } function isFixedToTop() { var offsetTop = scroll + elTop; // Initial Offset Top return initialOffset < offsetTop && // Container Bottom offsetTop + height <= parentOffset + parentHeight; } function isFixedToBottom() { // Initial Offset Top + Height return initialOffset + ( height || 0 ) > scroll + viewportHeight - elBottom && // Container Top scroll + viewportHeight - elBottom >= parentOffset + ( height || 0 ); } elTop = getPx( $el.css( 'top' ) ); elBottom = getPx( $el.css( 'bottom' ) ); if( position.top && isFixedToTop() || position.bottom && isFixedToBottom() ) { if( !isAlreadyOn ) { toggle( true ); } } else { if( isAlreadyOn ) { toggle( false ); } } }, destroy: function( el ) { var $el = $( el ); if (S.bypass()) { return $el; } return $el.each(function() { var $this = $( this ); var id = $this.data( S.keys.id ); $( win ).unbind( '.fixedsticky' + id ); $this .removeData( [ S.keys.offset, S.keys.position, S.keys.id ] ) .removeClass( S.classes.active ) .removeClass( S.classes.inactive ) .next( '.' + S.classes.clone ).remove(); }); }, init: function( el ) { var $el = $( el ); if( S.bypass() ) { return $el; } return $el.each(function() { var _this = this; var id = uniqueIdCounter++; $( this ).data( S.keys.id, id ); $( win ).bind( 'scroll.fixedsticky' + id, function() { S.update( _this ); }).trigger( 'scroll.fixedsticky' + id ); $( win ).bind( 'resize.fixedsticky' + id , function() { if( $el.is( '.' + S.classes.active ) ) { S.update( _this ); } }); }); } }; win.FixedSticky = S; // Plugin $.fn.fixedsticky = function( method ) { if ( typeof S[ method ] === 'function') { return S[ method ].call( S, this); } else if ( typeof method === 'object' || ! method ) { return S.init.call( S, this ); } else { throw new Error( 'Method `' + method + '` does not exist on jQuery.fixedsticky' ); } }; // Add fallback when fixed-fixed is not available. if( !win.FixedFixed ) { $( win.document.documentElement ).addClass( S.classes.withoutFixedFixed ); } })( window, jQuery ); ;(function(window){ 'use strict'; var initHasBeenCalled = false, initCallbacks = []; var ACE = { version: function() { return '201606081006-DEV'; }, _throttle: function(fn, tn) { var timeoutCounter = null; return function() { var that, args; that = this; args = arguments; if (!timeoutCounter) { timeoutCounter = setTimeout(function() { fn.apply(that, args); timeoutCounter = null; }, tn); } }; }, /*eslint-disable complexity */ //Complexity of an OS detect is necessarily high /** * Private: Returns string of OS name * @param {String} uastring Defaults to navigator.userAgent but allows test string * @returns {String} as per detectBrowser */ _detectOS: function(uastring) { var na = uastring || navigator.userAgent, os = 'os-undetected'; if (na.indexOf('Win') !== -1) { os = 'windows'; } if (na.indexOf('Mac') !== -1) { os = 'mac'; } if (na.indexOf('Linux') !== -1) { os = 'linux'; } if (na.indexOf('Android') !== -1) { os = 'android'; } if (na.match(/(iPad|iPhone|iPod)/g)) { os = 'ios'; } if (na.indexOf('Windows Phone') !== -1) { os = 'windowsphone'; } return os; }, /** * Returns string with name of operating system * @param {String} uastring Defaults to navigator.userAgent but allows test string * @returns {String} os Name of the operating system. */ detectOS: function() { return ACE._detectOS(navigator.userAgent); }, /** * Private: Returns object with browser details * @param {String} uastring User Agent string * @returns {Object} as per detectBrowser */ _detectBrowser: function(uastring) { var ua = uastring || navigator.userAgent, tmp, uamatch = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*([\d\.]+)/i) || [], edge = ua.indexOf('Edge/'), browserName, browserVersion, browserMajorVersion; if (edge > 0) { // IE12/edge browserName = 'msie'; browserVersion = ua.substring(edge + 5); browserMajorVersion = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10) + ''; } else if(/trident/i.test(uamatch[1])) { // IE10 & IE11 browserName = 'msie'; browserVersion = /\brv[ :]+(\d+)/g.exec(ua)[1]; browserMajorVersion = parseInt(browserVersion, 10) + ''; } else { // Most browsers... uamatch = uamatch[2] ? [uamatch[1], uamatch[2]] : [navigator.appName, navigator.appVersion, '-?']; tmp = ua.match(/version\/([\.\d]+)/i); if(tmp !== null) { uamatch[2] = tmp[1]; } browserName = uamatch[0].toLowerCase(); browserVersion = uamatch[1]; browserMajorVersion = uamatch[1].substring(0, uamatch[1].indexOf('.')); } return { 'name': browserName, 'version': browserVersion, 'majorVersion': browserMajorVersion }; }, /** * Public: exposes _detectBrowser * @returns {Object} object.name string Name of the browser * @returns {Object} object.version string Full version of the browser. String because they are not always numbers. * @returns {Object} object.majorVersion string Just the major version of the browser, eg. 12 not 12.12345. String for API consistency. */ detectBrowser: function() { return ACE._detectBrowser(navigator.userAgent); }, /*eslint-enable complexity */ /*eslint-disable no-console */ //Creating a safe form of console log log: function() { if (typeof console !== 'undefined' && console.log) { Function.prototype.apply.call(console.log, console, Array.prototype.slice.call(arguments) ); } }, /*eslint-enable no-console */ init: function() { var i, len; if(initHasBeenCalled) return; initHasBeenCalled = true; for(i = 0, len = initCallbacks.length; i < len; i++){ initCallbacks[i](); } initCallbacks = null; }, registerInit : function(callback){ if(initHasBeenCalled){ //We want to ensure that the callback is always called async setTimeout(callback, 0); } else { initCallbacks.push(callback); } } }; window.ACE = ACE; })(window); (function(ACE){ 'use strict'; var maxIE = 12, minIE = 8, browser = ACE.detectBrowser(), browserName = browser.name, browserVersion = browser.majorVersion, html = document.getElementsByTagName('html')[0], uaClass = html.className, ieBand = '', i; // remove no-js if it's there uaClass = uaClass.replace(/(?:^|\s)ace-no-js(?!\S)/, ''); // construct browser class and set has-js uaClass += ' ace-has-js ' + ACE.detectOS() + ' ' + browserName + ' ' + browserName + '-' + browserVersion; // set IE banding (classes range between set limits) if (browserName === 'msie') { if (browserVersion >= minIE) { i = maxIE; while (i >= browserVersion) { ieBand += ' msie-lte-' + i; i--; } } else { ieBand = ' msie-version-unsupported'; } uaClass += ieBand; } else { uaClass += ' not-ie'; } // Clean up any leading or trailing whitespace. aka the Anf Cleanup uaClass = uaClass.replace(/^\s+|\s+$/g, ''); // Apply the new class string. html.className = uaClass; html.setAttribute('data-ace-version', ACE.version()); })(window.ACE); ;(function(ACE, $){ 'use strict'; // We're decorating select2 with bits of our markup $.fn.select2.amd.require([ 'select2/utils', 'select2/selection/multiple' ], function(Utils, MultipleSelection){ var oldMultipleRender, oldMultipleClear, oldMultipleBind; // Edit multiselect to use ace lozenge oldMultipleRender = MultipleSelection.prototype.render; oldMultipleClear = MultipleSelection.prototype.clear; oldMultipleBind = MultipleSelection.prototype.bind; MultipleSelection.prototype.render = function(){ var $selection = oldMultipleRender.apply(this, arguments); $selection.append( '' + '' + '' ); return $selection; }; MultipleSelection.prototype.bind = function(){ var self = this; this.$selection.on('removeLozenge', function(evt){ var removedOption = $(evt.target); var data = removedOption.data('data'); self.trigger('unselect', { originalEvent: evt, data: data }); }); return oldMultipleBind.apply(this, arguments); }; MultipleSelection.prototype.clear = function(){ ACE.Lozenges.destroy(this.$selection.find('.select2-selection__rendered')); return oldMultipleClear.apply(this, arguments); }; MultipleSelection.prototype.update = function (data) { var $selections = [], d, l, selection, formatted, $selection, $rendered; this.clear(); if (data.length === 0) { return; } for (d = 0, l = data.length; d < l; d++) { selection = data[d]; formatted = this.display(selection); $selection = this.selectionContainer(formatted); $selection.prop('title', selection.title || selection.text); $selection.data('data', selection); $selections.push($selection); } $rendered = this.$selection.find('.select2-selection__rendered'); Utils.appendMany($rendered, $selections); }; MultipleSelection.prototype.selectionContainer = function(formatted){ var $lozenge = $('
  • ' + formatted + '
  • ').lozenges(); return $lozenge; }; // End edit multiselect to use ace lozenge // Setting up some defaults $.fn.select2.defaults.set('theme', 'ace'); }, undefined, true); /** * @constructor * @alias ACE.Autocomplete * @description ACE's autocomplete element * * @param {HTMLElement} element - Parent element to bind the autocomplete to. Will be wrapped in jQuery. * @param {Object} options - override default options. See Autocomplete.defaults */ function Autocomplete(element, options){ this._options = $.extend(true, {}, Autocomplete.defaults, options); this._select2Options = {}; // $.extend(true, {}, this._options); this._$element = $(element); this._$input = this._$element.find('select'); if (this._options.placeholder) { this._select2Options.placeholder = this._options.placeholder; } if (this._options.data) { this._select2Options.data = this._options.data; } if (this._options.ajax) { this._select2Options.ajax = this._options.ajax; } if (this._options.matcher) { this._select2Options.matcher = this._options.matcher; } if (this._options.language) { this._select2Options.language = this._options.language; } this._$input.select2(this._select2Options); } /** * @description * * Default options used to initialise an autocomplete input * * @static */ Autocomplete.defaults = { }; /** * Finds all autocomplete elements and initialises them * @param {elementSelector} elementSelector - Context for element. Defaults to whole document * @param {options} options - Options for configuring autocomplete. Can pass in undefined. * @returns {jQuery} - The found elements */ Autocomplete.init = function(elementSelector, options) { if (elementSelector === undefined) { elementSelector = $('.ace-autocomplete').not('[data-ace-autoinit="false"]'); } else if (typeof elementSelector === 'string') { elementSelector = $(elementSelector); } else if (!(elementSelector instanceof jQuery)) { return $(); } return elementSelector.autocomplete(options); }; /** * Finds all autocomplete elements and destroys them * @param {jQuerySelector} [parent] - search for elements within this context. Defaults to whole document * @returns {jQuery} - The destroyed elements */ Autocomplete.destroy = function(parent) { parent = parent || null; return $('.ace-autocomplete', parent).each(function() { var $this = $(this), instance = $this.data('ACE.autocomplete'); if(instance) { instance.destroy(); } }); }; Autocomplete.prototype = { destroy : function(){ } }; $.fn.autocomplete = function(options) { this.each(function() { var $this = $(this), instance = $this.data('ACE.autocomplete'), instOptions; if(!instance) { instOptions = $.extend({}, options); $this.data('ACE.autocomplete', new ACE.Autocomplete($this, instOptions)); } }); }; ACE.Autocomplete = Autocomplete; ACE.registerInit(function(){ ACE.Autocomplete.init(); }); }(window.ACE, window.jQuery)); ;// Dependency: Yet Another Datepicker 1.0 https://github.com/ansarada/datePicker (function (ACE, DatePickerLib, $) { 'use strict'; /** * @constructor * @alias ACE.Datepicker * @description ACE's datepicker element * @param {HTMLElement} element - Parent element to bind the datepicker to. Will be wrapped in jQuery. * @param {Object} options - override default options. See DatePicker.defaults * @returns {Object} - Datepicker instance */ function Datepicker(element, options){ //This is the default action button text var actionButtonText = 'Open date picker', placeHolder; //Check if the element has ace datepicker added if(typeof ($(element).data('ACE.datepicker')) !== 'undefined') { return; } this._$datePickerDomInput = element.find('.ace-form-input-datepicker'); if(this._$datePickerDomInput.attr('data-ace-datepicker-action-text')){ actionButtonText = this._$datePickerDomInput.attr('data-ace-datepicker-action-text'); } if(this._$datePickerDomInput.attr('placeholder')){ placeHolder = this._$datePickerDomInput.attr('placeHolder'); this._placeHolderExisting = true; } if(this._$datePickerDomInput.attr('type') && this._$datePickerDomInput.attr('type') === 'date' && !this._useNativeControl()) { this._$datePickerInput = this._createTextInputElement(this._$datePickerDomInput.attr('class'), this._$datePickerDomInput, this._createIdFromDomElementId(this._$datePickerDomInput), placeHolder, this._$datePickerDomInput.val()); this._$datePickerDomInput.hide(); this._domInputDateType = true; } else { this._$datePickerInput = this._$datePickerDomInput; this._domInputDateType = false; } if(!this._useNativeControl()) { this._$datePickerCalendar = element.find('.ace-button-datepicker-trigger'); if(!this._$datePickerCalendar.length){ this._$datePickerCalendar = this._createButtonElement(this._$datePickerInput, actionButtonText); } else { this._actionButtonExisting = true; } this._datePickerId = this._$datePickerInput.attr('id'); this._options = $.extend(true, {}, Datepicker.defaults, options); this._$element = $(element); this._initDatePicker(); this._bindEvents(); this._$datePickerDomInput.trigger('ace-datepicker-initialized'); } } /** * ACE Datepicker default values overrights * @property {object} defaults - the defaults options for datepicker * @property {String} defaults.dateFormat - date format used for input * @property {String} defaults.displayDateFormat - the display date format */ Datepicker.defaults = { dateFormat: '%d/%m/%Y', displayDateFormat: 'DD/MM/YYYY' }; /** * Finds all datepicker elements and initialises them * @param {jQuerySelector} [parentSelector] - search for elements within this context. Defaults to whole document * @returns {jQuery} - The found elements */ Datepicker.init = function(parentSelector){ parentSelector = parentSelector || null; return $('.ace-datepicker', parentSelector).datepicker(); }; /** * Finds all datepicker elements and destroys them * @param {jQuerySelector} [parent] - search for elements within this context. Defaults to whole document * @returns {jQuery} - The destroyed elements */ Datepicker.destroy = function(parentSelector){ parentSelector = parentSelector || null; return $('.ace-datepicker', parentSelector).each(function() { var $this = $(this), instance = $this.data('ACE.datepicker'); if(instance) { instance.destroy(); } }); }; /** * Set date select in calendar * @param {string} [datePickerSelector] DOM selector * @param {string|date} [dateInput] date as string YYYY-MM-DD * @returns {void} **/ Datepicker.setDate = function(datePickerSelector, dateInput){ if (dateInput.constructor === Date && !isNaN(dateInput.valueOf())) { dateInput = dateInput.toISOString().replace(/-/g, '').split('T')[0]; } else { if (typeof (dateInput) === 'string' && dateInput.match(/^(\d{4})-(\d{2})-(\d{2})/) != null) { dateInput = dateInput.replace(/(-)/g, ''); } else { dateInput = ''; } } DatePickerLib.setSelectedDate($(datePickerSelector).data('ACE.datepicker')._datePickerId, dateInput); }; /** * Set minimum date range for calendar * @param {string} [datePickerSelector] DOM selector * @param {string|date} [dateInput] date as string YYYY-MM-DD * @returns {void} **/ Datepicker.setRangeMin = function(datePickerSelector, dateInput){ if (dateInput.constructor === Date && !isNaN(dateInput.valueOf())) { dateInput = dateInput.toISOString().replace(/-/g, '').split('T')[0]; } else { if (typeof (dateInput) === 'string' && dateInput.match(/^(\d{4})-(\d{2})-(\d{2})/) != null) { dateInput = dateInput.replace(/(-)/g, ''); } else { dateInput = ''; } } DatePickerLib.setRangeLow($(datePickerSelector).data('ACE.datepicker')._datePickerId, dateInput); }; /** * Set maximum date range for calendar * @param {string} [datePickerSelector] DOM selector * @param {string|date} [dateInput] date as string YYYY-MM-DD * @returns {void} **/ Datepicker.setRangeMax = function(datePickerSelector, dateInput){ if (dateInput.constructor === Date && !isNaN(dateInput.valueOf())) { dateInput = dateInput.toISOString().replace(/-/g, '').split('T')[0]; } else { if (typeof (dateInput) === 'string' && dateInput.match(/^(\d{4})-(\d{2})-(\d{2})/) != null) { dateInput = dateInput.replace(/(-)/g, ''); } else { dateInput = ''; } } DatePickerLib.setRangeHigh($(datePickerSelector).data('ACE.datepicker')._datePickerId, dateInput); }; Datepicker.prototype = { //Keep a reference to the bound element _$element: null, _$datePickerInput: null, _datePickerId: null, _$datePickerCalendar: null, _$datePickerDomInput: null, _domInputDateType: false, _actionButtonExisting: false, _placeHolderExisting: false, /** * Show the calendar * @returns {void} **/ show: function(){ this._$datePickerCalendar.addClass('ace-button-active'); DatePickerLib.show(this._datePickerId, true); }, /** * Hide the calendar * @returns {void} **/ hide: function(){ DatePickerLib.hide(this._datePickerId); this._$datePickerCalendar.removeClass('ace-button-active'); }, /** * Creates the date picker object instance * @returns {void} * @private **/ _initDatePicker: function() { var datePickerSettingsObject = {}, min = this._$datePickerDomInput.attr('min'), rangeLow = min ? min.replace(/-/g, '') : undefined, max = this._$datePickerDomInput.attr('max'), rangeHigh = max ? max.replace(/-/g, '') : undefined; if(this._$datePickerDomInput.attr('data-ace-datepicker-format')){ this._options.dateFormat = this._$datePickerDomInput.attr('data-ace-datepicker-format'); this._options.displayDateFormat = this._options.dateFormat.replace('%d', 'DD').replace('%m', 'MM').replace('%Y', 'YYYY').replace('%y', 'YY'); } if(!this._$datePickerInput.attr('placeholder')){ this._$datePickerInput.attr('placeholder', this._options.displayDateFormat); } datePickerSettingsObject[this._datePickerId] = this._options.dateFormat; this._datePickerInst = DatePickerLib.createDatePicker({ formElements: datePickerSettingsObject, noFadeEffect: true, noTodayButton: true, dragDisabled: true, showActionButton: false, customCssClassName: 'ace-datepicker-content', noYearForwardBack: true, callbackFunctions: { 'hideControl': [this._onHideCalendar], 'dateset': [this._onSetDateValue] }, actionElement: this._$element.get(0), rangeLow: rangeLow, rangeHigh: rangeHigh }); }, /** * Destroy datepicker Object * @param {String} id - The id of date picker instance * @return {void} * @private */ _destroyDatePicker: function(id) { DatePickerLib.destroyDatePicker(id); }, /** * bind all ace events for date picker * @return {void} * @private */ _bindEvents: function(){ this._$datePickerCalendar.on('click.ace.datepicker', this._onShowCalendar.bind(this)); }, /** * Remove all ace events for date picker * @return {void} * @private */ _unbindEvents: function(){ this._$datePickerCalendar.off('click.ace.datepicker'); }, /** * Show calendar control * @return {void} * @private */ _onShowCalendar: function(){ this.show(); }, _onHideCalendar: function(e){ var _this = $('#' + e.id).parent().data('ACE.datepicker'); if(_this && _this._$datePickerCalendar){ _this._$datePickerCalendar.removeClass('ace-button-active'); } }, /** * The event callback function after a date is entered or selected * @param {object} e - event data * @param {Date} e.date - data object of the entered/selected date * @param {int} e.yyyy - year part of the date * @param {int} e.mm - the month part of the date * @param {int} e.dd - the day part of the date * @return {void} * @private */ _onSetDateValue: function(e){ var _this = $('#' + e.id).parent().data('ACE.datepicker'), dateISOstring; if(e.date){ dateISOstring = _this._dateParseToString(e.yyyy, e.mm, e.dd); //Check if the existing input element a date input if(_this && _this._domInputDateType) { _this._$datePickerDomInput.val(dateISOstring); _this._$datePickerDomInput.trigger('change'); } } else { if(_this && _this._domInputDateType) { _this._$datePickerDomInput.val(''); _this._$datePickerDomInput.trigger('change'); } } }, /** * Create text input element * @param {string} cssClass - CSS classes * @param {jQuery|Element} dateInputElement - the element to insert after * @param {string} id - id of the new element * @param {string} placeholder - placeholder text * @param {string} value - value to set for the input control * @return {jQuery} - The created element * @private */ _createTextInputElement: function(cssClass, dateInputElement, id, placeholder, value) { var $textBoxInput = $('', { type: 'text', 'class': cssClass, id: id, placeholder: placeholder, value: value }); $textBoxInput.insertAfter(dateInputElement); return $textBoxInput; }, /** * Create action button element * @param {jQuery|Element} inputElement - element to insert after * @param {string} actionButtonText - Text for the action button * @return {jQuery} - The created element * @private */ _createButtonElement: function(inputElement, actionButtonText) { var $actionButton = $('', { type: 'button', 'class': 'ace-button ace-button-icon ace-button-datepicker-trigger'}), $actionContentWrapper = $(''), $actionContentIcon = $('', { 'class': 'ace-icon ace-icon-objects-date' }); $actionContentIcon.text(actionButtonText); $actionContentWrapper.append($actionContentIcon); $actionButton.append($actionContentWrapper); $actionButton.insertAfter(inputElement); return $actionButton; }, /** * Create new id from existing DOM element * @param {jQuery} element - Existing date input DOM element * @return {string} - newly created id; * @private */ _createIdFromDomElementId: function (element) { if(element.attr('id')){ return element.attr('id') + '-ace-datepicker-input'; } return ''; }, /** * Parse a date object to a ISO String * @param {int} year - the year * @param {int} month - the month * @param {int} day - the day * @return {string} - the formatted string * @private */ _dateParseToString: function(year, month, day){ var dateISOMonth = month.toString(), dateISODay = day.toString(), dateISOYear = year.toString(), lengthOfYearDiff, zeroOutput = ''; if(dateISOMonth.length < 2){ dateISOMonth = '0' + dateISOMonth; } if(dateISODay.length < 2){ dateISODay = '0' + dateISODay; } if(dateISOYear.length < 4){ lengthOfYearDiff = 4 - dateISOYear.length; while (lengthOfYearDiff-- > 0) { zeroOutput += '0'; } dateISOYear = zeroOutput + dateISOYear; } return dateISOYear + '-' + dateISOMonth + '-' + dateISODay; }, /** * Use the native date picker control * @return {boolean} - whether or not to use native controls * @private */ _useNativeControl: function () { var os = ACE.detectOS(); if(os === 'android' || os === 'ios' || os === 'windowsphone') { return true; } return false; }, /** * Destoy the datepicker * @returns {void} */ destroy: function() { this._destroyDatePicker(this._datePickerId); this._unbindEvents(); if(this._$datePickerInput !== this._$datePickerDomInput) { this._$datePickerInput.remove(); this._$datePickerDomInput.show(); } if(!this._actionButtonExisting) { this._$datePickerCalendar.remove(); } if(!this._placeHolderExisting) { this._$datePickerDomInput.removeAttr('placeholder'); } this._$element = null; this._$datePickerInput = null; this._datePickerId = null; this._$datePickerDomInput = null; this._$datePickerCalendar = null; } }; /** * Default options used to initialise a datepicker * @param {Object} options - the options to initialise with * @return {void} */ $.fn.datepicker = function(options) { this.each(function() { var $this = $(this), instance = $this.data('ACE.datepicker'), instOptions; if(!instance) { instOptions = $.extend({}, options); } $this.data('ACE.datepicker', new ACE.Datepicker($this, instOptions)); }); }; ACE.Datepicker = Datepicker; ACE.registerInit(function(){ ACE.Datepicker.init(); }); return Datepicker; })(window.ACE, window.datePicker, window.jQuery); ;// Dependency: jQuery 1.10.2 http://jquery.com/ (function (ACE, $, dialogPolyfill) { 'use strict'; ACE.Dialog = function (element) { var _setMoreContent = ACE._throttle(function() { var dialogContentContainer, dialogContentContent; dialogContentContainer = element.find('.ace-dialog-content'); dialogContentContent = dialogContentContainer.children().first(); element.toggleClass('ace-more-content', dialogContentContent.outerHeight(true) > dialogContentContainer.scrollTop() + dialogContentContainer.innerHeight()); }, 100); function _bindEvents() { $(element).on('close', _closeEvent); $(element).find('.ace-dialog-content').on('scroll', _setMoreContent); $(window).on('resize', _setMoreContent); } function _destroyEvents() { $(element).off('close', _closeEvent); $(element).find('.ace-dialog-content').off('scroll', _setMoreContent); $(window).off('resize', _setMoreContent); } // need to do special stuff to update pseudoelement styling function _setFadeRightMargin(rightMargin) { var styleId, selector, style; styleId = 'SetFadeRightMargin'; selector = '.ace-dialog .ace-dialog-footer:before'; style = ''; $('#' + styleId).remove(); $('body').append(style); } function _open() { var scrollbarWidth; if(element && element.length > 0){ scrollbarWidth = ACE.page.getScrollbarWidth(); // we still want to update the the fade's right 'margin' if scrollbarWidth is 0 but not if it is null or indeterminate if (!isNaN(parseFloat(scrollbarWidth)) && isFinite(scrollbarWidth)) { _setFadeRightMargin(scrollbarWidth); } $('html').css('overflow', 'hidden'); element[0].showModal(); $(element[0]).attr('aria-hidden', 'false'); headerTruncated(); $(element[0]).trigger('ace-dialog-displayed', { element: element[0] }); _bindEvents(); _setMoreContent(); } else { ACE.log('Error: No dialog element defined'); } } function _closeEvent() { $('html').css('overflow', ''); $(element[0]).trigger('ace-dialog-closed', { element: element[0] }); $(element[0]).attr('aria-hidden', 'true'); } function _close() { if(element && element.length > 0){ element[0].close(); } else { ACE.log('Error: No dialog element defined'); } } function headerTruncated() { var $headerElement = $(element).find('.ace-dialog-header'); var headerCopy = $headerElement.text(); if ($headerElement[0].scrollWidth > $headerElement.innerWidth()) { $headerElement.prop('title', headerCopy); } else if($headerElement.prop('title')) { $headerElement.removeProp('title'); } } function _destroy() { _destroyEvents(); } this._destroy = _destroy; this._open = _open; this._close = _close; }; $.fn.dialog = function() { var dialogsupport = false; if($('')[0].showModal){ dialogsupport = true; } this.each(function(){ var $this = $(this), instance = $this.data('ACE.dialog'); if(!instance){ $this.data('ACE.dialog', new ACE.Dialog($this)); if(!dialogsupport){ dialogPolyfill.registerDialog($this[0]); } } }); return this; }; ACE.Dialog.close = function(element) { $(element).data('ACE.dialog')._close(); }; ACE.Dialog.open = function(element) { $(element).data('ACE.dialog')._open(); }; ACE.Dialog.init = function(element) { return $(element).dialog(); }; ACE.Dialog.destroy = function(elementSelector){ $(elementSelector).each(function(){ var $this = $(this); $this.data('ACE.Dialog')._destroy(); }); }; ACE.registerInit(function(){ ACE.Dialog.init('.ace-dialog'); }); })(window.ACE, window.jQuery, window.dialogPolyfill); ; // When document is ready run ACE.init (function (ACE) { 'use strict'; if (document.addEventListener) { document.addEventListener('DOMContentLoaded', ACE.init); } else { document.attachEvent('onreadystatechange', function() { if (document.readyState === 'interactive') { ACE.init(); } }); } })(window.ACE); ;(function(ACE, $) { 'use strict'; var ESCAPE_KEY = 27, UP_ARROW = 38, DOWN_ARROW = 40, TAB_KEY = 9; var singleton; /** * @constructor * @alias ACE.DropdownManager * * @todo Consider extending this service to manage all overlays * * @description * Provides a global service to manage the active dropdown on the page. * Binds events that respond to global clicks and key presses to close the active dropdown * and provides global methods to access the currently active dropdown. */ function DropdownManager() { if(!(this instanceof DropdownManager)) return new DropdownManager(); if(singleton) return singleton; singleton = this; this._bindEvents(); } DropdownManager.init = function(){ return new DropdownManager(); }; DropdownManager.destroy = function(){ if(singleton){ singleton.destroy(); singleton = null; } }; DropdownManager.DROPDOWN_TRIGGER_SELECTOR = '[data-ace-dropdown-trigger]'; DropdownManager.DROPDOWN_SELECTOR = '.ace-dropdown'; DropdownManager.prototype = { /** * currently active instance of dropdown * @type {ACE.Dropdown} * @private */ _activeInstance : null, /** * Whether or not the document level events have been bound * @type {Boolean} * @private */ _areEventsBound : false, /** * Destructor * @return {void} */ destroy : function() { singleton = null; this.activeInstance = null; this._unbindEvents(); }, /** * Sets the provided instance of the dropdown as the active one, closing the previous active instance * @param {ACE.Dropdown} instance - The instance to activate * @returns {void} */ setAsActive : function(instance) { if(this._activeInstance === instance) return; this.closeActive(); this._activeInstance = instance; }, /** * Unsets the active instance if the passed in dropdown is the active one * @param {ACE.Dropdown} instance - The instance to deactivate * @returns {void} */ unsetActive : function(instance) { if(this._activeInstance === instance) { this._activeInstance = null; } }, /** * Close the currently active instance * @returns {void} */ closeActive : function() { if(this._activeInstance) { this._activeInstance.close(); this._activeInstance = null; } }, /** * Return the currently active instance * @returns {ACE.Dropdown} - the active dropdown */ getActiveDropdown : function() { return this._activeInstance; }, /** * Return dropdown instance referenced from a trigger element * * Searches the DOM by the id specified in the 'data-ace-dropdown-trigger' attribute and returns the inst if there is one * If data-ace-dropdown-trigger has no id, or is '^' then search its parents for the dropdown. * * @param {jQuery} $triggerElement - the trigger element to search from * @returns {ACE.Dropdown | null} - the instance if found, else null */ findDropdownFromTrigger : function($triggerElement) { var dropdownId = $triggerElement.attr('data-ace-dropdown-trigger') || ''; if(dropdownId === '' || dropdownId === '^') { return $triggerElement.closest(DropdownManager.DROPDOWN_SELECTOR).data('ACE.dropdown') || null; } return $(document.getElementById(dropdownId)).data('ACE.dropdown') || null; }, /** * Binds the global keyboard events * @returns {void} * @private */ _bindEvents : function() { var $document; if(!this._areEventsBound) { this._areEventsBound = true; $document = $(document); //Dropdown events $document.on('dropdown-open.dropdown-manager', this._onOpen.bind(this)); $document.on('dropdown-close.dropdown-manager', this._onClose.bind(this)); //Trigger events $document.on('click.ace.dropdown-manager', DropdownManager.DROPDOWN_TRIGGER_SELECTOR, this._onTriggerClick.bind(this)); $document.on('keydown.ace.dropdown-manager', DropdownManager.DROPDOWN_TRIGGER_SELECTOR, this._onTriggerKeydown.bind(this)); //Global DOM events $document.on('click.ace.dropdown-manager', this._onOutsideClickOrFocus.bind(this)); $document.on('keydown.ace.dropdown-manager', this._onEscapeKey.bind(this)); $document.on('scroll.ace.dropdown-manager', this._onScrollOrResize.bind(this)); $document.on('focusin.ace.dropdown-manager', this._onOutsideClickOrFocus.bind(this)); $(window).on('resize.ace.dropdown-manager', this._onScrollOrResize.bind(this)); } }, /** * Unbinds the global keyboard events * @returns {void} * @private */ _unbindEvents : function() { var $document; if(this._areEventsBound) { this._areEventsBound = false; $document = $(document); $document.off('dropdown-open.dropdown-manager'); $document.off('dropdown-close.dropdown-manager'); $document.off('click.ace.dropdown-manager'); $document.off('keydown.ace.dropdown-manager'); $document.off('scroll.ace.dropdown-manager'); $document.off('focusin.ace.dropdown-manager'); $(window).off('resize.ace.dropdown-manager'); } }, _onOutsideClickOrFocus : function(e) { //Only close if the active element does not include the target of the click event if(this._activeInstance && this._activeInstance.shouldCloseOnOutsideClick(e.target)) { this.closeActive(); } }, _onOpen : function(e){ var inst = $(e.target).data('ACE.dropdown'); if(inst){ this.setAsActive(inst); } }, _onClose : function(e){ var inst = $(e.target).data('ACE.dropdown'); if(inst){ this.unsetActive(inst); } }, _onEscapeKey : function(e) { if(this._activeInstance && e.which === ESCAPE_KEY) { this._activeInstance.focusTriggerElement(); this.closeActive(); } }, _onScrollOrResize : function() { if(this._activeInstance) { this._activeInstance.focusTriggerElement(); this.closeActive(); } }, _onTriggerClick : function(e){ var $triggerElement = $(e.currentTarget), inst = this.findDropdownFromTrigger($triggerElement); if(inst){ e.preventDefault(); inst.updateActiveTriggerElement(e.currentTarget); inst.toggle(); } }, _onTriggerKeydown : function(e){ var $triggerElement, inst; //Quick escape for only keys we care about if(e.which !== UP_ARROW && e.which !== DOWN_ARROW && e.which !== TAB_KEY) return; //Make sure the key presses don't work on inputs, textareas and selects if(/input|textarea|select/i.test(e.target.tagName)) return; $triggerElement = $(e.currentTarget); inst = this.findDropdownFromTrigger($triggerElement); if(!inst) return; switch(e.which){ //Tabbing on the trigger while its open should put focus to the first action in the dropdown case TAB_KEY : if(!e.shiftKey && this._activeInstance && this._activeInstance === inst && inst.isOpen()) { if(inst.focusFirstActionItem()){ //Only prevent default if there is something to focus e.preventDefault(); } } break; //Down arrow to open the dropdown and focus on first item case DOWN_ARROW : e.preventDefault(); inst.updateActiveTriggerElement(e.currentTarget); inst.open(); inst.focusFirstActionItem(); break; //Up arrow to open the dropdown and focus on last item case UP_ARROW : e.preventDefault(); inst.updateActiveTriggerElement(e.currentTarget); inst.open(); inst.focusLastActionItem(); break; default: //Do nothing } } }; ACE.DropdownManager = DropdownManager; ACE.registerInit(function(){ ACE.DropdownManager.init(); }); }(window.ACE, window.jQuery)); ;(function(ACE, $) { 'use strict'; var UP_ARROW = 38, DOWN_ARROW = 40, TAB_KEY = 9; /** * @constructor * @alias ACE.Dropdown * @description ACE's dropdown element * * @param {HTMLElement} element - Parent element to bind the dropdown to. Will be wrapped in jQuery. * @param {Object} options - override default options. See Dropdown.defaults */ function Dropdown(element, options) { this._options = $.extend(true, {}, Dropdown.defaults, options); this._$element = $(element); this._bindEvents(); } /** * @description * * Default options used to initialise a dropdown * * @property {String} defaults.contentSelector - Selector used to search for menu controls * @property {String} defaults.closeOnClickSelector - Selector used to find which elements constitute elements that are arrow key navigatable * @property {String} defaults.menuActionSelector - Selector used to find which elements constitute elements that are arrow key navigatable * @property {String} defaults.boundingContainerSelector - Selector used to find a bounding container. * The bounding container is used as part of the calculation of which direction the dropdown should open in. * * @property {Boolean} defaults.autoPosition - Whether or not the dropdown is automatically positioned * @static */ Dropdown.defaults = { contentSelector : '.ace-dropdown-content', closeOnClickSelector : '[data-ace-dropdown-close="dropdown"], .ace-dropdown-menu a', menuActionSelector : '.ace-dropdown-menu a', boundingContainerSelector : '[data-ace-dropdown-bounds], .ace-dialog, .ace-page-fixed #page, .ace-page-hybrid #content', autoPosition : true, fixedPositioning : true }; /** * Finds all dropdown elements and initialises them * @param {jQuerySelector} [parent] - search for elements within this context. Defaults to whole document * @returns {jQuery} - The found elements */ Dropdown.init = function(parent) { parent = parent || null; return $('.ace-dropdown', parent).dropdown(); }; /** * Finds all dropdown elements and destroys them * @param {jQuerySelector} [parent] - search for elements within this context. Defaults to whole document * @returns {jQuery} - The destroyed elements */ Dropdown.destroy = function(parent) { parent = parent || null; return $('.ace-dropdown', parent).each(function() { var $this = $(this), instance = $this.data('ACE.dropdown'); if(instance) { instance.destroy(); } }); }; Dropdown.prototype = { //Keep a reference to the bound element _$element : null, //Keep a reference to the element that trigger the opening of this dropdown _$activeTriggerElement : null, //Flag to keep track of open state _isOpen : false, /** * Destructor method. Allows for element to be garbage collected * @returns {void} */ destroy : function() { this._unbindEvents(); this._$element = null; this._$activeTriggerElement = null; }, /** * Opens the dropdown. * @returns {void} */ open : function() { var directionInfo, openEvent; if(this._isOpen) return; if(this._$element.is('.disabled')) return; /** * Dropdown Open event * Event bubbles, and is cancelable * * @todo define a generic interface for Events that have a relatedTarget, ala MouseEvent interface * * @event Dropdown#open * @type {CustomEvent} * @property {DOMElement|null} detail.relatedTarget - the active trigger element */ openEvent = new CustomEvent('dropdown-open', { bubbles : true, cancelable : true, detail : { relatedTarget : this._$activeTriggerElement[0] } }); this._$element[0].dispatchEvent(openEvent); if(openEvent.defaultPrevented) return; this._isOpen = true; //TODO generalise the css animation triggers across ACE ala ng-animate this._$element.addClass('ace-dropdown-open'); //Based on whether or not the element is part of the dropdown or not, //It will determine whether or not the dropdown is fixed positioning or not if(this._options.fixedPositioning){ if(this._$activeTriggerElement && this._$activeTriggerElement.length && !$.contains(this._$element[0], this._$activeTriggerElement[0])){ this._addFixedPositioning(); } else { this._resetFixedPositioning(); } } //Figure which is the best direction to open this dropdown if(this._options.autoPosition) { directionInfo = this._getBestDirection(); if (directionInfo.oversized) { this._$element.attr('data-ace-oversized', 'oversized'); this._$element .find('.ace-dropdown-content') .css({ height: directionInfo.oversizedHeight }); } this._$element.attr('data-ace-vpos', directionInfo.vertical); this._$element.attr('data-ace-halign', directionInfo.horizontal); } }, /** * closes the dropdown. * @returns {void} */ close : function() { var closeEvent; if(!this._isOpen) return; /** * Dropdown Close event * Event bubbles and is cancelable * * @event Dropdown#close * @type {CustomEvent} */ closeEvent = new CustomEvent('dropdown-close', { bubbles : true, cancelable : true }); this._$element[0].dispatchEvent(closeEvent); if(closeEvent.defaultPrevented) return; this._isOpen = false; //TODO generalise the css animation triggers across ACE ala ng-animate this._$element.removeClass('ace-dropdown-open'); this._$element.removeAttr('data-ace-oversized'); this._$element .find('.ace-dropdown-content') .css({ height: 'auto' }); }, /** * toggles the dropdown * @returns {void} */ toggle : function() { if(this.isOpen()) { this.close(); } else { this.open(); } }, /** * Whether or not the dropdown is open * @return {Boolean} - whether or not the dropdown is open */ isOpen : function() { return this._isOpen; }, /** * Sets the element that triggered the opening of this dropdown * @param {jQuery|Element} [triggerElement] - set the element that triggered this opening. * @returns {void} */ updateActiveTriggerElement : function(triggerElement) { var $triggerElement = $(triggerElement); if($triggerElement.length){ this._$activeTriggerElement = $triggerElement; } }, /** * Sets window focus to the element that triggered the open (if one exists) * @returns {Boolean} Whether or not there is anything to focus */ focusTriggerElement : function() { if (this._$activeTriggerElement && this._$activeTriggerElement.length) { this._$activeTriggerElement.focus(); return true; } return false; }, /** * Sets window focus to the first available action item inside the dropdown to focus * @return {Boolean} Whether or not there is anything to focus */ focusFirstActionItem : function(){ return this._focusFirstActionItem(this._getMenuActionItems()); }, /** * Sets window focus to the last available action item inside the dropdown to focus * @return {Boolean} Whether or not there is anything to focus */ focusLastActionItem : function(){ return this._focusLastActionItem(this._getMenuActionItems()); }, /** * Used by the dropdown manager to determine whether or not this instance should close on outside click * @param {Element} triggerElement - element that triggered the outside click. Should not be wrapped with jQuery * @return {Boolean} - Whether or not the dropdown should be closed */ shouldCloseOnOutsideClick : function(triggerElement) { if( this._isElementOrDescendent(this._$element, triggerElement) || //If the target is part of the dropdown this._isElementOrDescendent(this._$activeTriggerElement, triggerElement) // Or if its part of the trigger element ) { return false; //Then don't close the dropdown } return true; }, /** * Checks if one elements contains or is the another element * @param {jQuery} $haystack - the search. Only considers the first node of the collection * @param {Element} needle - the target. * @return {Boolean} - Whether or not needle is part of haystack * @private */ _isElementOrDescendent : function($haystack, needle){ var haystack = $haystack && $haystack.length && $haystack[0]; return !!(haystack && (haystack === needle || $.contains(haystack, needle))); }, /** * Focuses the first item in the passed in list * This method shadows the public method, but doesn't require a search for all the menu items inside the dropdown * @param {jQuery} $menuItems - The list of items * @returns {Boolean} - Whether or not there is anything to focus * @private */ _focusFirstActionItem : function($menuItems){ if($menuItems.length){ $menuItems.first().focus(); return true; } return false; }, /** * Focuses the last item in the passed in list * This method shadows the public method, but doesn't require a search for all the menu items inside the dropdown * @param {jQuery} $menuItems - The list of items * @returns {Boolean} - Whether or not there is anything to focus * @private */ _focusLastActionItem : function($menuItems){ if($menuItems.length){ $menuItems.last().focus(); return true; } return false; }, _addFixedPositioning : function(){ var boundingRect = this._$activeTriggerElement[0].getBoundingClientRect(); this._$element.addClass('ace-dropdown-fixed').css({ left : boundingRect.left, top : boundingRect.top, width : boundingRect.right - boundingRect.left, height : boundingRect.bottom - boundingRect.top }); }, _resetFixedPositioning : function(){ this._$element.removeClass('ace-dropdown-fixed').css({ left : '', top : '', width : '', height : '' }); }, /** * @description * Finds the best direction to put the dropdown menu in relation to the anchor element. * It does this by looking at the available space within the dropdown's overflow parent, intersected with the current viewport. * * By default, it goes to the bottom, and anchored to the left. * If there is no space on the right, but there is enough space on the left, then anchor it to the right of the toggle. * If there is no space at the bottom, but there is enough space at the top, then place it above the toggle. * * @todo figure out a better way to find the overflow parent * * @return {Object} directionInfo - Object with the best directions to put this element * @return {top|bottom} directionInfo.vertical - Whether to put it above or below the anchor * @return {left|right} directionInfo.horizontal - Whether to put it anchored left or anchored right. * * @private */ _getBestDirection : function() { var directionInfo = { vertical : 'bottom', horizontal : 'left', oversized : false, oversizedHeight : null }, $content, $overflowParent, $window, //The various rectangles are used to calculate where to place the dropdown elementRect, contentRect, viewportRect, overflowParentRect; //Check if the element is visible. jQuery's visible selector also checks if its part of the document tree as well if(this._$element.is(':visible')) { $content = this._$element.find(this._options.contentSelector); if($content.length) { $window = $(window); elementRect = this._$element[0].getBoundingClientRect(); contentRect = { width : $content.outerWidth(true), height : $content.outerHeight(true) }; viewportRect = { width : $window.width(), height : $window.height() }; overflowParentRect = { top : 0, bottom : viewportRect.height, left : 0, right : viewportRect.width }; //Sometimes we want the dropdown to conform to another box's boundaries //(perhaps if that element has overflow clipping, or it looks nicer from a design perspective) //This will add that calculation into the mix if(this._options.boundingContainerSelector) { $overflowParent = this._$activeTriggerElement.parent().closest(this._options.boundingContainerSelector); if($overflowParent.length) { overflowParentRect = $overflowParent[0].getBoundingClientRect(); } } //TODO theres a (possible) use case here where if the bounding container has overflow set on it, we may want to force it in 1 direction //or the other // //I.E. container is 500 in height, with overflow hidden. //Dropdown is sitting on the bottom right corner of the container // //By the current calculations, if the dropdown element is scrolled to the top of the screen, //it will place the dropdown to the bottom, which will overflow and make the dropdown hidden. //Better would be to place it at the top of the button, and let focus pull the window up //Vertical directionInfo = (function () { // First check if there is sufficient space to fit content below the trigger if(elementRect.bottom + contentRect.height < Math.min(viewportRect.height, overflowParentRect.bottom)) { directionInfo.vertical = 'bottom'; return directionInfo; } // Check if there is sufficient space to fit content above the tigger if(elementRect.top - contentRect.height > Math.max(0, overflowParentRect.top)) { directionInfo.vertical = 'top'; return directionInfo; } // Otherwise set the conent as oversized directionInfo.oversized = true; // Check if the resized window will be largest below the trigger if(elementRect.bottom < Math.min(viewportRect.height, overflowParentRect.bottom) / 2) { directionInfo.vertical = 'bottom'; directionInfo.oversizedHeight = viewportRect.height - elementRect.bottom - 48; // 48 is 8vgrid units return directionInfo; } // Otherwise set the resized window to be above the trigger directionInfo.vertical = 'top'; directionInfo.oversizedHeight = viewportRect.height - (viewportRect.height - elementRect.top) - 48; // 48 is 8vgrid units return directionInfo; }()); //Horizontal if(elementRect.left + contentRect.width > Math.min(viewportRect.width, overflowParentRect.right)) { //Only set it to anchor right if theres sufficient space on the left if(elementRect.right - contentRect.width > Math.max(0, overflowParentRect.left)) { directionInfo.horizontal = 'right'; } } } } return directionInfo; }, /** * Finds the available and active menu action items within this element * @returns {jQuery} - the found elements * @private */ _getMenuActionItems : function(){ return this._$element.find(this._options.menuActionSelector).not('.disabled, :disabled'); }, _bindEvents : function() { this._$element.on('click.ace.dropdown', this._options.closeOnClickSelector, this._onCloseTriggers.bind(this)); this._$element.on('focusin.ace.dropdown', this._options.contentSelector, this._onContentFocus.bind(this)); this._$element.on('keydown.ace.dropdown', this._options.contentSelector, this._onContentKeydown.bind(this)); }, _unbindEvents : function() { this._$element.off('click.ace.dropdown'); this._$element.off('keydown.ace.dropdown'); }, _onContentFocus : function() { this.open(); }, _onCloseTriggers : function(e) { if($(e.currentTarget).is('.disabled')) return; this.focusTriggerElement(); this.close(); }, _onContentKeydown : function(e) { //Quick escape for only keys we care about if(e.which !== UP_ARROW && e.which !== DOWN_ARROW && e.which !== TAB_KEY) return; //Make sure the key presses don't work on inputs, textareas and selects if(/input|textarea|select/i.test(e.target.tagName)) return; //Ignore if disabled if(this._$element.is('.disabled')) return; switch(e.which){ case UP_ARROW: this._onUpArrowKey(e, this._getMenuActionItems()); break; case DOWN_ARROW: this._onDownArrowKey(e, this._getMenuActionItems()); break; case TAB_KEY: this._onTabKey(e, this._getMenuActionItems()); break; default: //Do nothing } }, _onUpArrowKey : function(e, $actionItems){ var focusedItemIndex = $actionItems.index(document.activeElement); e.preventDefault(); if(focusedItemIndex === -1){ this.open(); //We're focusing the last item in the case of an up arrow in the case if the dropdown appears above the element this._focusLastActionItem($actionItems); } else { if(focusedItemIndex !== 0) { $actionItems.eq(focusedItemIndex - 1).focus(); } else { this.focusTriggerElement(); this.close(); } } }, _onDownArrowKey : function(e, $actionItems){ var focusedItemIndex = $actionItems.index(document.activeElement); e.preventDefault(); if(focusedItemIndex === -1){ this.open(); this._focusFirstActionItem($actionItems); } else { if(focusedItemIndex < $actionItems.length - 1) { $actionItems.eq(focusedItemIndex + 1).focus(); } else { this.focusTriggerElement(); this.close(); } } }, _onTabKey : function(e, $actionItems){ var focusedItemIndex = $actionItems.index(document.activeElement), triggerElementFocused; /** * We're pulling focus on tab key when focus is on the first and last action items * Reason being, the trigger element may not be in the same tab order as the dropdown items, * so the native tabbing order would jump to some random place on the page. * By manually focusing on the trigger element, it should be more intuitive for the user */ if( focusedItemIndex !== -1 && (focusedItemIndex === $actionItems.length - 1 && !e.shiftKey) || (focusedItemIndex === 0 && e.shiftKey) ){ triggerElementFocused = this.focusTriggerElement(); this.close(); if(triggerElementFocused){ e.preventDefault(); } } } }; $.fn.dropdown = function(options) { this.each(function() { var $this = $(this), instance = $this.data('ACE.dropdown'), instOptions; if(!instance) { instOptions = $.extend({}, options); if($this.is('[data-ace-dropdown-disable-positioning]')) { instOptions.autoPosition = false; } $this.data('ACE.dropdown', new ACE.Dropdown($this, instOptions)); } }); }; ACE.Dropdown = Dropdown; ACE.registerInit(function(){ ACE.Dropdown.init(); }); return Dropdown; }(window.ACE, window.jQuery)); ;(function(ACE, $) { 'use strict'; var panelsSelector = '.ace-expander-panel'; var contentSelector = '.ace-expander-content'; var counterControlSelector = '.ace-expander-panel-counter'; var panelHeadingSelector = '.ace-expander-heading'; var expandedClass = 'ace-expander-expanded'; var collapsedClass = 'ace-expander-collapsed'; var counterSelectorAttribute = 'data-ace-counter-selector'; var counterPresetAttribute = 'data-ace-counter-preset'; var controlItemSelector = '.ace-header-controls'; var $el; function ExpanderPanel() {} ExpanderPanel.collapse = function(el) { $(el).each(function(){ $el = $(this); $el.removeClass(expandedClass).addClass(collapsedClass); $el.find(contentSelector).attr('aria-hidden', 'true'); $el.trigger('ACE.ExpanderPanel.Collapsed'); }); }; ExpanderPanel.expand = function(el) { $(el).each(function(){ $el = $(this); $el.removeClass(collapsedClass).addClass(expandedClass); $el.find(contentSelector).attr('aria-hidden', 'false'); $el.trigger('ACE.ExpanderPanel.Expanded'); }); }; ExpanderPanel.toggle = function(el) { $(el).each(function(){ var toggleThis = $(this); var state; if(toggleThis.hasClass(expandedClass)) { ACE.ExpanderPanel.collapse(toggleThis); state = 'collapsed'; } else { ACE.ExpanderPanel.expand(toggleThis); state = 'expanded'; } $(this).trigger('ACE.ExpanderPanel.Toggled', { 'state': state }); }); }; // Should be called again when some part of the DOM that relates to this expander panel is changed // I.E a row is added/removed/changed that should affect the counter ExpanderPanel.update = function(selector) { $(selector).each(function(){ var counterSelector = $(this).attr(counterSelectorAttribute) || false; var counterPreset = $(this).attr(counterPresetAttribute) || false; var $counter = $(this).find(counterControlSelector); var $controlItem = $(this).find(controlItemSelector); var counterValue, width = 0; // If both a custom counter and a preset are declared, the custom counter overrides the preset. if (counterSelector) { // set the counter text to the length of the collection found by the counterSelector counterValue = $(this).find(counterSelector).length; } else if (counterPreset) { // preset for visible ACE table rows if (counterPreset === 'tableRows') { counterSelector = '.ace-table tbody tr:not([aria-hidden="true"])'; } counterValue = $(this).find(counterSelector).length; } // Set content of the counter $counter.text(counterValue); // Shrinkwrap the counter parent for nicer layout $controlItem.css('width', 'auto'); $controlItem.children().each(function(index, item){ width += $(item).outerWidth(true); }); width += 10; // Magic number to fix some whitespace or font issues width += $controlItem.outerWidth() - $controlItem.innerWidth(); // Calculation to used to get the total horizontal padding of the control item $controlItem.width(width); // Emit update event with the final value $(this).trigger('ACE.ExpanderPanel.Updated', { 'counterValue': counterValue }); }); }; ExpanderPanel.init = function(selector) { selector = selector || panelsSelector; $(selector).each(function(){ // find our elements var panel = $(this); var panelCounter = panel.find(counterControlSelector); // check panel hasn't already been initialised if(panel.data('ACE.ExpanderPanel')) { return; } // set init data panel.data('ACE.ExpanderPanel', true); // make counter control focusable panelCounter.attr('tabindex', '0'); // add click event to counter control panelCounter.on('click', function(){ ACE.ExpanderPanel.toggle(panel); }); // add enter keypress to counter control panelCounter.on('keypress', function(e){ var key = e.which || e.keyCode; if(key === 13) { ACE.ExpanderPanel.toggle(panel); e.preventDefault(); } }); // add click event to panel heading // since it's a duplicate control, no need to make it focusable panel.find(panelHeadingSelector).on('click', function(){ ACE.ExpanderPanel.toggle(panel); }); // set the count of visible rows in the counter control ACE.ExpanderPanel.update(panel); // ensure ARIA matches the expand/collapse classes if(panel.hasClass(expandedClass)) { ACE.ExpanderPanel.expand(panel); } else if(panel.hasClass(collapsedClass)) { ACE.ExpanderPanel.collapse(panel); } }); }; ACE.registerInit(function(){ ACE.ExpanderPanel.init(); }); ACE.ExpanderPanel = ExpanderPanel; return ExpanderPanel; }(window.ACE, window.jQuery)); ;(function(ACE, $) { 'use strict'; function Forms() { this.init(); } // Indeterminate checkboxes do not work until JS has initialised them Forms.enableIndeterminateCheckboxes = function(element) { var $indeterminates = element || $('.ace-form-input-checkbox[indeterminate="true"]'); $indeterminates.each(function(){ this.indeterminate = true; }); }; Forms.init = function() { Forms.enableIndeterminateCheckboxes(); }; ACE.registerInit(function(){ ACE.Forms.init(); }); ACE.Forms = Forms; return Forms; }(window.ACE, window.jQuery)); ;//Dependency: jQuery 1.10.2 http://jquery.com/ (function (ACE, $) { 'use strict'; var cid = 0; /** * @constructor * @alias ACE.Lozenges * @description ACE's lozenge element * @param {HTMLElement} element - Parent element to bind the dropdown to. Will be wrapped in jQuery. * @param {Object} options - extra options that lozenges can have. */ ACE.Lozenges = function (element, options) { var lozengeId, isCloseable = false, $closeMessageIcon, $element = $(element), defaultOptions = { closeableText: 'Close' }, finalOptions = $.extend({}, defaultOptions, options || {}); function _addAttributesToLozenge() { if (element[0].id) { lozengeId = element[0].id; } else { cid++; lozengeId = 'ace-lozenge-' + cid; element[0].id = lozengeId; } } function _addCloseMessageIcon(){ if($closeMessageIcon) return; $closeMessageIcon = $('' + finalOptions.closeableText + ''); element[0].tabIndex = '0'; element[0].appendChild($closeMessageIcon[0]); } function _removeCloseMessageIcon(){ if(!$closeMessageIcon) return; $closeMessageIcon.remove(); $closeMessageIcon = null; } function _bindEvents(){ $element.on('keypress.ace.lozenge', _lozengeEnterKeyPressed); $element.on('click.ace.lozenge', '.ace-icon-control-closesmall', _lozengeCloseMessageIconClick); } function _destroyEvents(){ $element.off('keypress.ace.lozenge'); $element.off('click.ace.lozenge'); } function _lozengeEnterKeyPressed(e) { var key; if(isCloseable){ key = e.which; if (key === 13){ //13 is Enter remove(); } } } function _lozengeCloseMessageIconClick() { if(isCloseable){ remove(); } } /** * Destructor method. Allows for element to be garbage collected * @return {void} */ function destroy() { _destroyEvents(); } /** * Removes the lozenge from the dom and destroys it * @return {void} */ function remove() { var event = $.Event('removeLozenge'); // eslint-disable-line $element.trigger(event); if(!event.isDefaultPrevented()){ $element.remove(); destroy(); return true; } return false; } /** * Set whether or not the lozenge is closeable. Should be idempotent * @param {Boolean} closeable - Whether or not its closeable * @return {void} */ function setCloseable(closeable){ if(closeable){ if(isCloseable) return; isCloseable = true; _addCloseMessageIcon(); } else { if(!isCloseable) return; isCloseable = false; _removeCloseMessageIcon(); } } /** * Returns whether or not a lozenge is closable * @return {Boolean} Closeable flag */ function isManuallyCloseable(){ return isCloseable; } this.destroy = destroy; this.remove = remove; this.setCloseable = setCloseable; this.isManuallyCloseable = isManuallyCloseable; _addAttributesToLozenge(); _bindEvents(); if(element[0].hasAttribute('data-ace-closeable') && element[0].getAttribute('data-ace-closeable') === 'true') { setCloseable(true); } }; $.fn.lozenges = function() { this.each(function() { var $this = $(this); var instance = $this.data('ACE.closeableLozenges'); if(!instance) { $this.data('ACE.closeableLozenges', new ACE.Lozenges($this, { closeableText: $(this).attr('data-ace-closeabletext') })); } }); return this; }; /** * Finds all lozenge elements and initialises them * @param {jQuerySelector} [parentSelector] - search for elements within this context. Defaults to whole document * @returns {jQuery} - The found elements */ ACE.Lozenges.init = function(parentSelector) { parentSelector = parentSelector || null; return $('.ace-lozenge', parentSelector).lozenges(); }; /** * Finds all lozenge elements and destroys them * @param {jQuerySelector} [parentSelector] - search for elements within this context. Defaults to whole document * @returns {jQuery} - The destroyed elements */ ACE.Lozenges.destroy = function(parentSelector){ parentSelector = parentSelector || null; return $('.ace-lozenge', parentSelector).each(function(){ var $this = $(this), inst = $this.data('ACE.closeableLozenges'); if(inst){ inst.destroy(); $this.removeData('ACE.closeableLozenges'); } }); }; /** * Removes a lozenge element from the DOM * @param {String} id - the id of the element * @return {Boolean} Whether or not the instance was removed, or false if a matching element could not be found */ ACE.Lozenges.remove = function(id) { var element = $('#' + id), instance = element.data('ACE.closeableLozenges'); if(instance){ return instance.remove(); } return false; }; ACE.registerInit(function(){ ACE.Lozenges.init(); }); })(window.ACE, window.jQuery); ;//Dependency: jQuery 1.10.2 http://jquery.com/ (function (ACE, $) { 'use strict'; var messagesIds = 0; ACE.Messages = function (element, options) { var messageType, defaultOptions = { closeableText: 'Close' }, finalOptions = $.extend({}, defaultOptions, options || {}), $element = $(element); function _addIdToMessage() { if(!$element.attr('id')) { $element.attr('id', 'ace-closeable-message-' + (messagesIds++)); } } function _detectMessageType() { if($element.is('[data-ace-closeable]')) { if ($element.find('.ace-messages-custom-icon').length) { messageType = 'customIcon'; return; } else if(document.querySelectorAll('#' + element.id + '[data-ace-control]')[0]) { messageType = 'control'; return; } messageType = 'icon'; return; } } function _decorateMarkup() { switch(messageType) { case 'icon': _addCloseIcon(); break; case 'control': _addControlToMessage(); break; case 'customIcon': _decorateCustomIcon(); break; default: break; } } function _bindCloseListeners() { $element.on('click.ace.click', '[data-ace-message-close-control]', _closeableClickHandler); $element.on('keypress.ace.keypress', '[data-ace-message-close-control]', _closeableKeyboardHandler); } function _unbindCloseListeners() { $element.off('click.ace.click'); $element.off('keypress.ace.click'); } function _addCloseIcon() { var $closeMessageIcon = $('') .addClass('ace-messages-control') .attr('tabIndex', 0) // Make icon tabbable .attr('data-ace-message-close-control', true) // Make icon a close icon .html(controlMessage); $element.appendChild($controlContainer); } function _decorateCustomIcon() { var $customIcon = $element.find('.ace-messages-custom-icon'); $customIcon .attr('tabIndex', 0) // Make icon tabbable .attr('data-ace-message-close-control', true); // Make icon a close icon } function _closeableKeyboardHandler(e) { var key = e.which || e.keyCode; if (key === 13) { // 13 is enter hide(); } } function _closeableClickHandler(e) { e.preventDefault(); hide(); } function _removeMessage() { var removeEvent = $.Event('messageRemoved', { // eslint-disable-line new-cap bubbles : true, cancelable : true }); $element.trigger(removeEvent, { closed: true, id: $element.attr('id'), time: Date.now() }); if(removeEvent.isDefaultPrevented()) return; $element.remove(); } function destroy() { _unbindCloseListeners(); } function show() { if($element.hasClass('ace-message-pagecontext')){ $element.removeClass('ace-hidden').removeAttr('aria-hidden'); $element.css({ 'transform' : 'translateY(-100%)', '-webkit-transform' : 'translateY(-100%)', '-ms-transform' : 'translateY(-100%)', 'opacity' : 0 }); $element.finish().animate({ // The animation piggybacks off the step function on opacity to animate the transform // DO NOT ADD MORE PROPERTIES WITHOUT LOOKING AT HOW THE STEP FUNCTION WORKS IN JQUERY // http://jqapi.com/#p=animate opacity : 1 }, { duration: 250, step : function(now){ var value = -100 + (now * 100); $element.css({ 'transform' : 'translateY(' + value.toString() + '%)', '-webkit-transform' : 'translateY(' + value.toString() + '%)', '-ms-transform' : 'translateY(' + value.toString() + '%)' }); } }); } else { $element.removeClass('ace-hidden').removeAttr('aria-hidden'); } } function hide() { function onHideComplete() { $element.addClass('ace-hidden').attr('aria-hidden', true); _removeMessage(); } if($element.hasClass('ace-message-pagecontext')){ $element.css({ 'transform' : 'translateY(0%)', '-webkit-transform' : 'translateY(0%)', '-ms-transform' : 'translateY(0%)', 'opacity' : 1 }); $element.finish().animate({ // The animation piggybacks off the step function on opacity to animate the transform // DO NOT ADD MORE PROPERTIES WITHOUT LOOKING AT HOW THE STEP FUNCTION WORKS IN JQUERY // http://jqapi.com/#p=animate opacity : 0 }, { duration: 250, complete : function(){ onHideComplete(); }, step : function(now){ var value = -100 + (now * 100); $element.css({ 'transform' : 'translateY(' + value.toString() + '%)', '-webkit-transform' : 'translateY(' + value.toString() + '%)', '-ms-transform' : 'translateY(' + value.toString() + '%)' }); } }); } else { onHideComplete(); } } _addIdToMessage(); _detectMessageType(); _decorateMarkup(); _bindCloseListeners(); this.destroy = destroy; this.show = show; this.hide = hide; }; $.fn.messages = function() { this.each(function() { var $this = $(this), instance; instance = $this.data('ACE.message'); if(!instance) { instance = new ACE.Messages(this, { closeableText: $(this).attr('data-ace-closeabletext') }); $this.data('ACE.message', instance); $this.data('ACE.closeableMessages', instance); // Left here for legacy reasons } }); return this; }; ACE.Messages.init = function(elementSelector){ return $(elementSelector).messages(); }; ACE.Messages.destroy = function(elementSelector){ $(elementSelector).each(function(){ var $this = $(this); var instance = $this.data('ACE.message'); if(instance){ instance.destroy(); } }); }; ACE.Messages.show = function(elementSelector){ $(elementSelector).each(function(){ var $this = $(this); var instance = $this.data('ACE.message'); if(instance){ instance.show(); } }); }; ACE.Messages.hide = function(elementSelector){ $(elementSelector).each(function(){ var $this = $(this); var instance = $this.data('ACE.message'); if(instance){ instance.hide(); } }); }; ACE.registerInit(function(){ ACE.Messages.init('.ace-message'); }); })(window.ACE, window.jQuery); ;(function(){ 'use strict'; function aceNavHorizontalFix(){ var horizontalNavs = document.getElementsByClassName('ace-nav-horizontal'), i, parentNav, horizontalNavCount; for (i = 0, horizontalNavCount = horizontalNavs.length; i < horizontalNavCount; i++){ parentNav = horizontalNavs[i].parentNode; parentNav.style.overflowX = 'auto'; parentNav.style.overflowY = 'hidden'; } } aceNavHorizontalFix(); })(); ;//Dependency: jQuery 1.10.2 http://jquery.com/ (function (ACE) { 'use strict'; ACE.page = ACE.page || {}; ACE.registerInit(function(){ ACE.page.init(); }); ACE.page.init = function() { FixedSticky.tests.sticky = false; $('.ace-page-popup #header, .ace-page-popup #footer').fixedsticky(); $('.ace-page-popup #header').addClass('fixedsticky-off'); }; function stripUnits(cssValueWithUnits) { return parseInt(cssValueWithUnits, 10); } // more reliable than outerwidth, which fails on IMG elements function getHorizontalPadding($el) { return stripUnits($el.css('padding-left')) + stripUnits($el.css('padding-right')); } function getHorizontalMargin($el) { return stripUnits($el.css('margin-left')) + stripUnits($el.css('margin-right')); } /** * Updates the footer to a fixed location if in viewport or static if it's not. * @returns {boolean} */ ACE.page.renderFooter = function(){ ACE.log('ACE.page.renderFooter is deprecated as of ACE 1.5 and will be removed in ACE 2.0'); }; // https://davidwalsh.name/detect-scrollbar-width ACE.page.getScrollbarWidth = function() { var scrollDiv, scrollbarWidth; // Create the measurement node scrollDiv = document.createElement('div'); scrollDiv.className = 'scrollbar-measure'; document.body.appendChild(scrollDiv); // Get the scrollbar width scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth; // Delete the DIV document.body.removeChild(scrollDiv); return scrollbarWidth; }; // This is a polyfill/hack that we'll use to support old IE when we move layout to use flexbox. ACE.ShrinkWrap = function($wrapper, $wrappee, maintainWrapperPadding, maintainWrapperMargin) { $wrapper.each(function() { var finalWidth = stripUnits($wrappee.innerWidth()); finalWidth += getHorizontalMargin($wrappee); finalWidth += getHorizontalPadding($wrappee); if (maintainWrapperPadding) { finalWidth += getHorizontalPadding($wrapper); } if (maintainWrapperMargin) { finalWidth += getHorizontalMargin($wrapper); } $wrapper.width(finalWidth); }); }; })(window.ACE); ;(function(ACE, $) { 'use strict'; var panelsSelector = '.ace-panel-table'; var counterControlSelector = '.ace-panel-table-counter'; var panelHeadingSelector = '.ace-panel-table-heading'; var expandedClass = 'ace-panel-table-expanded'; var collapsedClass = 'ace-panel-table-collapsed'; function TablePanel() { this.init(); } TablePanel.collapse = function(el) { $(el).each(function(){ $(this).removeClass(expandedClass).addClass(collapsedClass); $(this).find('.ace-table').attr('aria-hidden', 'true'); }); }; TablePanel.expand = function(el) { $(el).each(function(){ $(this).removeClass(collapsedClass).addClass(expandedClass); $(this).find('.ace-table').attr('aria-hidden', 'false'); }); }; TablePanel.toggle = function(el) { $(el).each(function(){ var toggleThis = $(this); if(toggleThis.hasClass(expandedClass)) { ACE.TablePanel.collapse(toggleThis); } else { ACE.TablePanel.expand(toggleThis); } }); }; // Can be called again if rows are added/removed/hidden TablePanel.update = function(selector) { $(selector).each(function(){ $(this).find(counterControlSelector).text($(this).find('.ace-table tbody tr').length); }); }; TablePanel.init = function() { $(panelsSelector).each(function(){ // find our elements var panel = $(this); var panelCounter = panel.find(counterControlSelector); // check panel hasn't already been initialised if(panel.data('ACE.TablePanel')) { return; } // set init data panel.data('ACE.TablePanel', true); // make counter control focusable panelCounter.attr('tabindex', '0'); // add click event to counter control panelCounter.on('click', function(){ ACE.TablePanel.toggle(panel); }); // add enter keypress to counter control panelCounter.on('keypress', function(e){ var key = e.which; if(key === 13) { ACE.TablePanel.toggle(panel); } }); // add click event to panel heading // since it's a duplicate control, no need to make it focusable panel.find(panelHeadingSelector).on('click', function(){ ACE.TablePanel.toggle(panel); }); // set the count of rows in the counter control ACE.TablePanel.update(panel); // ensure ARIA matches the expand/collapse classes if(panel.hasClass(expandedClass)) { ACE.TablePanel.expand(panel); } else if(panel.hasClass(collapsedClass)) { ACE.TablePanel.collapse(panel); } }); }; ACE.TablePanel = TablePanel; return TablePanel; }(window.ACE, window.jQuery)); ;(function(ACE, $) { 'use strict'; var scrollSelector = '.ace-table-scroll-container'; var tableSelector = '.ace-table'; var containerSelector = '.ace-table-container'; var MSIEFieldsetSelector = '.msie fieldset'; function Table() {} /* * Apply to scroll-wrapped table containers * * Calculate the amount of scroll px on either side of the current viewport. * Apply more-content-[side] classes if such a gap exists. * Recalculate whenever the container scroll or window size changes. */ Table.setScrollAffordance = function() { var $container = $(this); var $scroller = $container.closest(scrollSelector); var $table = $container.find(tableSelector); var setAffordance = function() { var left = $container.scrollLeft(); var right = $table.width() - (left + $container.width()); $scroller.toggleClass('more-content-left', left > 0); $scroller.toggleClass('more-content-right', right > 0); }; var setAffordanceSlowly = ACE._throttle(setAffordance, 100); setAffordance(); $container.on('scroll', setAffordanceSlowly); $(window).on('resize', setAffordanceSlowly); }; /* * IE tables won't scroll when they live in fieldsets with the standard css. * This gets IE to scroll but doesn't hook into the affordance above. * * Necessary to do in javascript instead of css; need to apply style to * parent conditionally on existence of child. * * TODO: Incorporate into scroll affordance */ Table.scrollMSIEFieldset = function () { var $fieldset = $(this); if ($fieldset.find(scrollSelector)) { $fieldset.css({ 'overflow-x': 'auto' }); } }; Table.init = function() { $(scrollSelector + ' ' + containerSelector).each(Table.setScrollAffordance); $(MSIEFieldsetSelector).each(Table.scrollMSIEFieldset); }; ACE.registerInit(function(){ ACE.Table.init(); }); ACE.Table = Table; return Table; }(window.ACE, window.jQuery)); ;/* Increasingly-loosely based on SortTable (http://www.kryogenix.org/code/browser/sorttable/) by Stuart Langridge (https://github.com/stuartlangridge) Code taken from: https://github.com/HubSpot/sortable/ */ /* eslint-disable */ (function() { var SELECTOR, addEventListener, clickEvent, numberRegExp, sortable, touchDevice, trimRegExp, __slice = [].slice; SELECTOR = '.ace-table[data-ace-sortable="true"]'; numberRegExp = /^-?[£$¤]?[\d,.]+%?$/; trimRegExp = /^\s+|\s+$/g; touchDevice = 'ontouchstart' in document.documentElement; clickEvent = touchDevice ? 'touchstart' : 'click'; addEventListener = function(el, event, handler) { if (el.addEventListener != null) { return el.addEventListener(event, handler, false); } else { return el.attachEvent("on" + event, handler); } }; sortable = { init: function(options) { var table, tables, _i, _len, _results; if (options == null) { options = {}; } if (options.selector == null) { options.selector = SELECTOR; } tables = document.querySelectorAll(options.selector); _results = []; for (_i = 0, _len = tables.length; _i < _len; _i++) { table = tables[_i]; _results.push(sortable.initTable(table)); } return _results; }, initTable: function(table) { var i, middle, th, ths, tr, _i, _j, _len, _ref, _ref1; _ref1 = (_ref = table.tHead) != null ? _ref.rows : void 0, middle = 2 <= _ref1.length ? __slice.call(_ref1, 0, _i = _ref1.length - 1) : (_i = 0, []), tr = _ref1[_i++]; if (!tr) { return; } if (table.getAttribute('data-sortable-initialized') === 'true') { return; } table.setAttribute('data-sortable-initialized', 'true'); ths = tr.querySelectorAll('th'); for (i = _j = 0, _len = ths.length; _j < _len; i = ++_j) { th = ths[i]; // Support both ace- and non-namespaced options until ACE 2.0 if (th.getAttribute('data-sortable') !== 'false' && th.getAttribute('data-ace-sortable') !== 'false') { sortable.setupClickableTH(table, th, i); } } return table; }, setupClickableTH: function(table, th, i) { var inferredType, specifiedType, type; specifiedType = th.getAttribute('data-ace-sort-type') || th.getAttribute('data-sort-type'); inferredType = sortable.getColumnType(table, i); type = sortable.types[specifiedType] || inferredType; return addEventListener(th, clickEvent, function(e) { var newSortedDirection, row, rowArray, rowArrayObject, sorted, sortedDirection, tBody, ths, _i, _j, _k, _len, _len1, _len2, _ref, _results; sorted = this.getAttribute('data-sorted') === 'true' || this.getAttribute('data-ace-sorted') === 'true'; // Support both ace- and non-namespaced options until ACE 2.0 sortedDirection = this.getAttribute('data-ace-sorted-direction' || this.getAttribute('data-sorted-direction')); if (sorted) { newSortedDirection = sortedDirection === 'ascending' ? 'descending' : 'ascending'; } else { newSortedDirection = type.defaultSortDirection; } ths = this.parentNode.querySelectorAll('th'); // Support both ace- and non-namespaced options until ACE 2.0 for (_i = 0, _len = ths.length; _i < _len; _i++) { th = ths[_i]; th.setAttribute('data-sorted', 'false'); th.setAttribute('data-ace-sorted', 'false'); th.removeAttribute('data-sorted-direction'); th.removeAttribute('data-ace-sorted-direction'); } this.setAttribute('data-sorted', 'true'); this.setAttribute('data-ace-sorted', 'true'); this.setAttribute('data-sorted-direction', newSortedDirection); this.setAttribute('data-ace-sorted-direction', newSortedDirection); tBody = table.tBodies[0]; rowArray = []; _ref = tBody.rows; for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) { row = _ref[_j]; rowArray.push([sortable.getNodeValue(row.cells[i]), row]); } if (sorted) { rowArray.reverse(); } else { rowArray.sort(type.compare); } _results = []; for (_k = 0, _len2 = rowArray.length; _k < _len2; _k++) { rowArrayObject = rowArray[_k]; _results.push(tBody.appendChild(rowArrayObject[1])); } return _results; }); }, getColumnType: function(table, i) { var row, text, _i, _len, _ref; _ref = table.tBodies[0].rows; for (_i = 0, _len = _ref.length; _i < _len; _i++) { row = _ref[_i]; text = sortable.getNodeValue(row.cells[i]); if (text !== '') { if (text.match(numberRegExp)) { return sortable.types.numeric; } if (!isNaN(Date.parse(text))) { return sortable.types.date; } } } return sortable.types.alpha; }, getNodeValue: function(node) { if (!node) { return ''; } if (node.getAttribute('data-ace-value') !== null) { return node.getAttribute('data-ace-value'); } if (typeof node.innerText !== 'undefined') { return node.innerText.replace(trimRegExp, ''); } return node.textContent.replace(trimRegExp, ''); }, types: { numeric: { defaultSortDirection: 'descending', compare: function(a, b) { var aa, bb; aa = parseFloat(a[0].replace(/[^0-9.-]/g, ''), 10); bb = parseFloat(b[0].replace(/[^0-9.-]/g, ''), 10); if (isNaN(aa)) { aa = 0; } if (isNaN(bb)) { bb = 0; } return bb - aa; } }, alpha: { defaultSortDirection: 'ascending', compare: function(a, b) { return a[0].localeCompare(b[0]); } }, date: { defaultSortDirection: 'ascending', compare: function(a, b) { var aa, bb; aa = Date.parse(a[0]); bb = Date.parse(b[0]); if (isNaN(aa)) { aa = 0; } if (isNaN(bb)) { bb = 0; } return aa - bb; } } } }; setTimeout(sortable.init, 0); window.Sortable = sortable; }).call(this); /* eslint-enable */ ;//Dependency: jQuery 1.10.2 http://jquery.com/ (function (ACE, $) { 'use strict'; function Tabs(element) { //define class properties this._$element = $(element); //jQuery object this.$panels = this._$element.find('.ace-tab-panel'); //array of panels this.init(); this.addTabIndex(); this.detectTab(); } /** * Initalises tabs * @param {string} element - element to have tabs applied to. * @return {object} returns tab object instance */ Tabs.init = function(element) { return $(element).tabs(); }; /** * Finds a tab object and destroys it, if none are passed in all are destroyed. * @param {object} element - jQuery tab object to destroy. * @return {void} */ Tabs.destroy = function(element){ var instance, $this; if(element){ instance = element.data('ACE-tabs'); if(instance){ instance.destroy(); } element.remove(); } else { $('.ace-tabs').each(function() { $this = $(this); instance = $this.data('ACE.tabs'); if(instance) { instance.destroy(); } $this.remove(); }); } }; /** * Changes the active Tab * @param {string} tabId - Tab Id to change to. * @return {void} */ Tabs.switchToTabId = function(tabId) { $('.ace-tabs').each(function() { var $this = $(this), instance = $this.data('ACE.tabs'); if(instance) { instance.switchTabs(tabId); } }); }; /** * Changes the active Tab * @param {string} panelId - Panel Id to change to. * @return {void} */ Tabs.switchToPanelId = function(panelId){ $('.ace-tabs').each(function() { var tabId; var $this = $(this), instance = $this.data('ACE.tabs'); if(instance) { tabId = $('.ace-tabs').find('li[aria-controls=' + panelId + ']').attr('id'); instance.switchTabs(tabId); } }); }; Tabs.prototype = { //Keep a reference to the bound element _$element : null, _$activeTab : null, _$activeTabId : null, _$activePanel : null, destroy : function() { this._$element = null; }, init : function(){ var searchActiveTab; //Find active tab - If not found make the first tab active searchActiveTab = this._$element.find('.ace-tab-active'); this._$activeTab = searchActiveTab.length ? searchActiveTab : this._$element.find('li').first().addClass('ace-tab-active'); this._$activeTabId = this._$activeTab[0].id; // Active panel is defined through the aria-controls tag on the active tab. this._$activePanel = this._$activeTab[0].getAttribute('aria-controls'); this.$panels = this._$element.find('.ace-tab-panel'); this.addAria(this._$activeTab); // Removes ARIA hidden from visible panel $('#' + this._$activePanel).attr('aria-hidden', 'false'); $('#' + this._$activePanel).show(); }, /** * Adds Aria values to tabs * @param {jQuery} ActiveTab - The active tab object * @return {void} */ addAria : function(){ var $tabNames = this._$element.find('.ace-tabs-nav'); this.$panels = this._$element.find('.ace-tab-panel'); this.$tabs = this._$element.find('.ace-tabs-nav li'); //Adds ARIA role='tab' this.$tabs.attr('role', 'tab'); //Adds ARIA hidden to every panel this.$panels.attr('aria-hidden', 'true'); //Adds ARIA role='tabpanel' this.$panels.attr('role', 'tabpanel'); // Add aria-labeled-by to panels this.$panels.each(function(){ var tabId = $tabNames.find('li[aria-controls=' + this.id + ']').attr('id'); $(this).attr('aria-labeledby', tabId); }); }, /** * Switchs tabs * @param {string} ActiveTabId - Id of the tab to switch to. * @return {void} */ switchTabs : function(ActiveTabId){ var tabset; var newPanel; this._$activeTab = $('#' + ActiveTabId); // Find the set of tabs to be switched tabset = this._$activeTab.closest('.ace-tabs'); // Remove all active classes and add to just the one active tab tabset.find('.ace-tab-active').removeClass('ace-tab-active'); this._$activeTab.addClass('ace-tab-active'); // Hide all panels and show just he one active panel tabset.find('.ace-tab-panel').css('display', 'none').attr('aria-hidden', 'true'); newPanel = this._$activeTab[0].getAttribute('aria-controls'); $('#' + newPanel).show(); $('#' + newPanel).attr('aria-hidden', 'false'); }, /** * Makes the tabs tabbable with the keyboard if no href is present. * @return {void} */ addTabIndex : function(){ $('.ace-tabs-nav li a').each(function(){ var $this = $(this); if($this.attr('href')){ //Prevents screen jumping on older browsers $this.click(function(event){ event.preventDefault(); }); } else { $this.attr('tabindex', '0'); } return true; }); }, /** * @description Sets listeners * @return {void} */ detectTab : function(){ $('.ace-tabs-nav li').click(function(){ $('.ace-tabs').data('ACE.tabs').switchTabs(this.id); }); } }; $.fn.tabs = function() { this.each(function(index) { var $this = $(this); var instance = $this.data('ACE.tabs'); if(!instance) { $this.data('ACE.tabs', new ACE.Tabs($this, index)); } }); return this; }; ACE.registerInit(function(){ ACE.Tabs.init('.ace-tabs'); }); ACE.Tabs = Tabs; return Tabs; })(window.ACE, window.jQuery); ;// Dependency: jQuery 1.10.2 http://jquery.com/ (function (ACE, Hammer, $) { 'use strict'; ACE.ToggleControl = function (element, hammerInst) { // All the child elements var radioOff = element.find('input[type="radio"]:first'), radioOn = element.find('input[type="radio"]:last'), inputMouse = false; /** * Bind swipe and drag events to child label elements * @return {void} */ function _initHammer() { if(hammerInst) { hammerInst.get('swipe').set({'velocity': 0.3}); hammerInst.on('swipeleft swiperight', _hammerEvents); } } /** * Change the border color on toggle has focus or losts focus * @return {void} */ function _bindEvents() { radioOff.on('focus', _focusControl); radioOff.on('blur', _blurControl); radioOn.on('focus', _focusControl); radioOn.on('blur', _blurControl); radioOff.on('keyup', _keyUpControl); radioOn.on('keyup', _keyUpControl); element.on('mousedown', _mouseDownControl); element.on('click', _clickControl); } /** * Remove change the border color on toggle has focus or losts focus events * @return {void} */ function _destroyEvents() { radioOff.off('focus', _focusControl); radioOff.off('blur', _blurControl); radioOn.off('focus', _focusControl); radioOn.off('blur', _blurControl); radioOff.off('keyup', _keyUpControl); radioOn.off('keyup', _keyUpControl); element.off('mousedown', _mouseDownControl); element.off('click', _clickControl); } /** * Toggle Control has focus * @return {void} */ function _focusControl() { element.addClass('has-focus'); } /** * Toggle Control has lost focus * @return {void} */ function _blurControl() { element.removeClass('has-focus'); } /** * Tell us there has been mouse button pressed * @return {void} */ function _mouseDownControl(){ inputMouse = true; } /** * If Mouse button has been pressed then toggle the controls * @param {object} event - event object * @return {void} */ function _clickControl(event) { if(inputMouse) { toggleControl(event); inputMouse = false; } } /** * If the space bar is press do toggle the controls * @param {object} event - event object * @return {void} */ function _keyUpControl(event){ if(event.keyCode === 32) { toggleControl(event); } } /** * Toggle selected options * @param {object} event - event object * @return {void} */ function toggleControl(event){ event.preventDefault(); if(radioOn.is(':checked')){ _moveToggle(radioOn, radioOff); } else { _moveToggle(radioOff, radioOn); } } /** * Unbind swipe and drag events * @return {void} */ function _destroyHammer() { if(hammerInst) { hammerInst.off('swipeleft swiperight'); hammerInst.destroy(); } } /** * Move toggle state from one radio element to new radio element * @param {object} fromToggleElement - toggle element that has the value * @param {object} toToggleElement - toggle element that is getting the value * @return {void} */ function _moveToggle(fromToggleElement, toToggleElement){ if(element.attr('aria-disabled') !== 'true'){ fromToggleElement.prop('checked', false); toToggleElement.prop('checked', true); toToggleElement.trigger('change'); } } /** * Swipe and drag hammer events * @param {object} event - event object * @return {void} */ function _hammerEvents(event) { // Swipe and drag hammer events switch(event.type){ case 'swipeleft': case 'dragleft': _moveToggle(radioOn, radioOff); break; case 'swiperight': case 'dragright': _moveToggle(radioOff, radioOn); break; default: break; } } /** * destroy toggle object and event binding * @return {void} */ function destroy() { _destroyHammer(); _destroyEvents(); } _bindEvents(); _initHammer(); this.destroy = destroy; }; $.fn.toggleControl = function() { this.each(function(){ var $this = $(this), instance = $this.data('ACE.toggleControl'); if(!instance){ $this.data('ACE.toggleControl', new ACE.ToggleControl($this), new Hammer(this)); } }); return this; }; /** * Toggle object initiate * @param {string} elementSelector - Element selector string * @return {void} */ ACE.ToggleControl.init = function(elementSelector){ return $(elementSelector).toggleControl(); }; /** * Toggle object destroy * @param {string} elementSelector - Element selector string * @return {void} */ ACE.ToggleControl.destroy = function(elementSelector){ $(elementSelector).each(function(){ var $this = $(this); var instance = $this.data('ACE.toggleControl'); if(instance){ instance.destroy(); } }); }; /** * Register object initiate * @return {void} */ ACE.registerInit(function(){ ACE.ToggleControl.init('.ace-toggle'); }); })(window.ACE, window.Hammer, window.jQuery);