From f11f2a72fa742a897e83c2c31cf9f87e6bbb5845 Mon Sep 17 00:00:00 2001 From: "marcos@paliari.com.br" Date: Sat, 24 Aug 2013 23:59:25 -0300 Subject: [PATCH 01/26] jquery-mobile-datebox include --- .../jquery-mobile-datebox/1.1.1/i18n/.empty | 0 .../1.1.1/i18n/.gitignore | 1 + .../1.1.1/jqm-datebox.comp.calbox.js | 1740 +++++++++++++++++ .../1.1.1/jqm-datebox.comp.calbox.min.js | 7 + .../1.1.1/jqm-datebox.comp.custombox.js | 1522 ++++++++++++++ .../1.1.1/jqm-datebox.comp.custombox.min.js | 7 + .../1.1.1/jqm-datebox.comp.customflip.js | 1659 ++++++++++++++++ .../1.1.1/jqm-datebox.comp.customflip.min.js | 7 + .../1.1.1/jqm-datebox.comp.datebox.js | 1684 ++++++++++++++++ .../1.1.1/jqm-datebox.comp.datebox.min.js | 7 + .../1.1.1/jqm-datebox.comp.durationbox.js | 1612 +++++++++++++++ .../1.1.1/jqm-datebox.comp.durationbox.min.js | 7 + .../1.1.1/jqm-datebox.comp.durationflipbox.js | 1571 +++++++++++++++ .../jqm-datebox.comp.durationflipbox.min.js | 7 + .../1.1.1/jqm-datebox.comp.flipbox.js | 1616 +++++++++++++++ .../1.1.1/jqm-datebox.comp.flipbox.min.js | 7 + .../1.1.1/jqm-datebox.comp.slidebox.js | 1590 +++++++++++++++ .../1.1.1/jqm-datebox.comp.slidebox.min.js | 7 + .../1.1.1/jqm-datebox.core.js | 1365 +++++++++++++ .../1.1.1/jqm-datebox.core.min.js | 7 + .../1.1.1/jqm-datebox.css | 112 ++ .../1.1.1/jqm-datebox.min.css | 7 + .../1.1.1/jqm-datebox.mode.calbox.js | 375 ++++ .../1.1.1/jqm-datebox.mode.calbox.min.js | 7 + .../1.1.1/jqm-datebox.mode.custombox.js | 157 ++ .../1.1.1/jqm-datebox.mode.custombox.min.js | 7 + .../1.1.1/jqm-datebox.mode.customflip.js | 294 +++ .../1.1.1/jqm-datebox.mode.customflip.min.js | 7 + .../1.1.1/jqm-datebox.mode.datebox.js | 319 +++ .../1.1.1/jqm-datebox.mode.datebox.min.js | 7 + .../1.1.1/jqm-datebox.mode.durationbox.js | 247 +++ .../1.1.1/jqm-datebox.mode.durationbox.min.js | 7 + .../1.1.1/jqm-datebox.mode.durationflipbox.js | 206 ++ .../jqm-datebox.mode.durationflipbox.min.js | 7 + .../1.1.1/jqm-datebox.mode.flipbox.js | 251 +++ .../1.1.1/jqm-datebox.mode.flipbox.min.js | 7 + .../1.1.1/jqm-datebox.mode.slidebox.js | 225 +++ .../1.1.1/jqm-datebox.mode.slidebox.min.js | 7 + ajax/libs/jquery-mobile-datebox/package.json | 10 + 39 files changed, 16682 insertions(+) create mode 100755 ajax/libs/jquery-mobile-datebox/1.1.1/i18n/.empty create mode 100755 ajax/libs/jquery-mobile-datebox/1.1.1/i18n/.gitignore create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.calbox.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.calbox.min.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.custombox.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.custombox.min.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.customflip.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.customflip.min.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.datebox.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.datebox.min.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.durationbox.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.durationbox.min.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.durationflipbox.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.durationflipbox.min.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.flipbox.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.flipbox.min.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.slidebox.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.slidebox.min.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.core.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.core.min.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.css create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.min.css create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.calbox.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.calbox.min.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.custombox.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.custombox.min.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.customflip.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.customflip.min.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.datebox.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.datebox.min.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.durationbox.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.durationbox.min.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.durationflipbox.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.durationflipbox.min.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.flipbox.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.flipbox.min.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.slidebox.js create mode 100644 ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.slidebox.min.js create mode 100644 ajax/libs/jquery-mobile-datebox/package.json diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/i18n/.empty b/ajax/libs/jquery-mobile-datebox/1.1.1/i18n/.empty new file mode 100755 index 000000000..e69de29bb diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/i18n/.gitignore b/ajax/libs/jquery-mobile-datebox/1.1.1/i18n/.gitignore new file mode 100755 index 000000000..a6c7c2852 --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/i18n/.gitignore @@ -0,0 +1 @@ +*.js diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.calbox.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.calbox.js new file mode 100644 index 000000000..2e653f003 --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.calbox.js @@ -0,0 +1,1740 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +/* CORE Functions */ + +(function($) { + $.widget( "mobile.datebox", $.mobile.widget, { + options: { + // All widget options, including some internal runtime details + version: '2-1.4.0-2013070300', // jQMMajor.jQMMinor.DBoxMinor-YrMoDaySerial + mobVer: parseInt($.mobile.version.replace(/\./g,'')), + theme: false, + themeDefault: 'a', + themeHeader: 'a', + mode: false, + + centerHoriz: false, + centerVert: false, + transition: 'pop', + useAnimation: true, + hideInput: false, + hideFixedToolbars: false, + + lockInput: true, + enhanceInput: true, + + zindex: '500', + clickEvent: 'vclick', + clickEventAlt: 'click', + resizeListener: true, + + defaultValue: false, + showInitialValue: false, + + dialogEnable: false, + dialogForce: false, + enablePopup: false, + + popupPosition: false, + popupForceX: false, + popupForceY: false, + + useModal: false, + useInline: false, + useInlineBlind: false, + useHeader: true, + useImmediate: false, + useNewStyle: false, + useAltIcon: false, + overrideStyleClass: false, + + useButton: true, + useFocus: false, + useClearButton: false, + useCollapsedBut: false, + usePlaceholder: false, + + openCallback: false, + openCallbackArgs: [], + closeCallback: false, + closeCallbackArgs: [], + + startOffsetYears: false, + startOffsetMonths: false, + startOffsetDays: false, + afterToday: false, + beforeToday: false, + notToday: false, + maxDays: false, + minDays: false, + maxYear: false, + minYear: false, + blackDates: false, + blackDatesRec: false, + blackDays: false, + minHour: false, + maxHour: false, + minuteStep: 1, + minuteStepRound: 0, + + rolloverMode: { 'm': true, 'd': true, 'h': true, 'i': true, 's': true }, + + useLang: 'default', + lang: { + 'default' : { + setDateButtonLabel: 'Set Date', + setTimeButtonLabel: 'Set Time', + setDurationButtonLabel: 'Set Duration', + calTodayButtonLabel: 'Jump to Today', + titleDateDialogLabel: 'Set Date', + titleTimeDialogLabel: 'Set Time', + daysOfWeek: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], + daysOfWeekShort: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], + monthsOfYear: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], + monthsOfYearShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + durationLabel: ['Days', 'Hours', 'Minutes', 'Seconds'], + durationDays: ['Day', 'Days'], + timeFormat: 24, + headerFormat: '%A, %B %-d, %Y', + tooltip: 'Open Date Picker', + nextMonth: 'Next Month', + prevMonth: 'Previous Month', + dateFieldOrder: ['m', 'd', 'y'], + timeFieldOrder: ['h', 'i', 'a'], + slideFieldOrder: ['y', 'm', 'd'], + dateFormat: '%Y-%m-%d', + useArabicIndic: false, + isRTL: false, + calStartDay: 0, + clearButton: 'Clear', + durationOrder: ['d', 'h', 'i', 's'], + meridiem: ['AM', 'PM'], + timeOutput: '%k:%M', //{ '12': '%l:%M %p', '24': '%k:%M' }, + durationFormat: '%Dd %DA, %Dl:%DM:%DS', + calDateListLabel: 'Other Dates', + calHeaderFormat: '%B %Y' + } + } + }, + _enhanceDate: function() { + $.extend(this._date.prototype, { + copy: function(adjust, override) { + /* Get a modified copy of the date. + * First array - Offset the new date by # (position determines date part) + * Second array - If non-zero, force the new date by # (position determines date part) + */ + if ( typeof adjust === 'undefined' ) { adjust = [0,0,0,0,0,0,0]; } + if ( typeof override === 'undefined' ) { override = [0,0,0,0,0,0,0]; } + while ( adjust.length < 7 ) { adjust.push(0); } + while ( override.length < 7 ) { override.push(0); } + return new Date( + ((override[0] > 0 ) ? override[0] : this.getFullYear() + adjust[0]), + ((override[1] > 0 ) ? override[1] : this.getMonth() + adjust[1]), + ((override[2] > 0 ) ? override[2] : this.getDate() + adjust[2]), + ((override[3] > 0 ) ? override[3] : this.getHours() + adjust[3]), + ((override[4] > 0 ) ? override[4] : this.getMinutes() + adjust[4]), + ((override[5] > 0 ) ? override[5] : this.getSeconds() + adjust[5]), + ((override[6] > 0 ) ? override[5] : this.getMilliseconds() + adjust[6])); + }, + adj: function (type, amount) { + /* Adjust the date. Yes, this is chainable */ + if ( typeof amount !== 'number' ) { + throw new Error("Adjustment value not specified"); + } + if ( typeof type !== 'number' ) { + throw new Error("Adjustment type not specified"); + } + switch ( type ) { + case 0: this.setFullYear(this.getFullYear() + amount); break; + case 1: this.setMonth(this.getMonth() + amount); break; + case 2: this.setDate(this.getDate() + amount); break; + case 3: this.setHours(this.getHours() + amount); break; + case 4: this.setMinutes(this.getMinutes() + amount); break; + case 5: this.setSeconds(this.getSeconds() + amount); break; + case 6: this.setMilliseconds(this.getMilliseconds() + amount); break; + } + return this; + }, + setD: function(type, amount) { + /* A chainable version of setWhatever() */ + switch ( type ) { + case 0: this.setFullYear(amount); break; + case 1: this.setMonth(amount); break; + case 2: this.setDate(amount); break; + case 3: this.setHours(amount); break; + case 4: this.setMinutes(amount); break; + case 5: this.setSeconds(amount); break; + case 6: this.setMilliseconds(amount); break; + } + return this; + }, + get: function(type) { + switch ( type ) { + case 0: return this.getFullYear(); + case 1: return this.getMonth(); + case 2: return this.getDate(); + case 3: return this.getHours(); + case 4: return this.getMinutes(); + case 5: return this.getSeconds(); + } + return false; + }, + iso: function() { + return String(this.getFullYear()) + '-' + (( this.getMonth() < 9 ) ? "0" : "") + String(this.getMonth()+1) + '-' + ((this.getDate() < 10 ) ? "0" : "") + String(this.getDate()); + }, + comp: function () { + return parseInt(this.iso().replace(/-/g,''),10); + }, + getEpoch: function() { + return (this.getTime() - this.getMilliseconds()) / 1000; + }, + getArray: function() { + return [this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds()]; + }, + setFirstDay: function (day) { + this.setD(2,1).adj(2, (day - this.getDay())); + if ( this.get(2) > 10 ) { this.adj(2,7); } + return this; + }, + setDWeek: function (type,num) { + if ( type === 4 ) { + return this.setD(1,0).setD(2,1).setFirstDay(4).adj(2,-3).adj(2,(num-1)*7); + } + return this.setD(1,0).setD(2,1).setFirstDay(type).adj(2,(num-1)*7); + }, + getDWeek: function (type) { + var t1, t2; + + switch ( type ) { + case 0: + t1 = this.copy([0,-1*this.getMonth()]).setFirstDay(0); + return Math.floor((this.getTime() - ( t1.getTime() + (( this.getTimezoneOffset() - t1.getTimezoneOffset()) * 60000))) / 6048e5) + 1; + //return Math.floor((this.getTime() - t1.getTime()) / 6048e5) + 1; + case 1: + t1 = this.copy([0,-1*this.getMonth()]).setFirstDay(1); + return Math.floor((this.getTime() - ( t1.getTime() + (( this.getTimezoneOffset() - t1.getTimezoneOffset()) * 60000))) / 6048e5) + 1; + //return Math.floor((this.getTime() - t1.getTime()) / 6048e5) + 1; + case 4: + // this line is some bullshit. but it does work. + // (trap for dec 29, 30, or 31st being in the new year's week - these are the + // only 3 that can possibly fall like this) + if ( this.getMonth() === 11 && this.getDate() > 28 ) { return 1; } + + t1 = this.copy([0,-1*this.getMonth()],true).setFirstDay(4).adj(2,-3); + t2 = Math.floor((this.getTime() - ( t1.getTime() + (( this.getTimezoneOffset() - t1.getTimezoneOffset()) * 60000))) / 6048e5) + 1; + + if ( t2 < 1 ) { + t1 = this.copy([-1,-1*this.getMonth()]).setFirstDay(4).adj(2,-3); + return Math.floor((this.getTime() - t1.getTime()) / 6048e5) + 1; + } + return t2; + default: + return 0; + } + } + }); + }, + _event: function(e, p) { + var w = $(this).data(parseInt($.mobile.version.replace(/\./g,''),10) > 110 ? 'mobile-datebox' : 'datebox'); + if ( ! e.isPropagationStopped() ) { + switch (p.method) { + case 'close': + w.close(); break; + case 'open': + w.open(); break; + case 'set': + $(this).val(p.value); + $(this).trigger('change'); + break; + case 'doset': + if ( $.isFunction(w['_'+w.options.mode+'DoSet']) ) { + w['_'+w.options.mode+'DoSet'].apply(w,[]); + } else { + $(this).trigger('datebox', {'method':'set', 'value':w._formatter(w.__fmt(), w.theDate), 'date':w.theDate}); + } + break; + case 'dooffset': + if (p.type) { w._offset(p.type, p.amount, true); } break; + case 'dorefresh': + w.refresh(); break; + case 'doreset': + w.hardreset(); break; + case 'doclear': + $(this).val('').trigger('change'); break; + case 'clear': + $(this).trigger('change'); + } + } + }, + _hoover: function(item) { + // Hover toggle class, for calendar + $(item).toggleClass('ui-btn-up-'+$(item).jqmData('theme')+' ui-btn-down-'+$(item).jqmData('theme')); + }, + _ord: { + 'default': function (num) { + // Return an ordinal suffix (1st, 2nd, 3rd, etc) + var ending = num % 10; + if ( num > 9 && num < 21 ) { return 'th'; } + if ( ending > 3 ) { return 'th'; } + return ['th','st','nd','rd'][ending]; + } + }, + __ : function(val) { + var o = this.options, + oride = 'override' + val.charAt(0).toUpperCase() + val.slice(1); + + if ( typeof o[oride] !== 'undefined' ) { return o[oride]; } + if ( typeof o.lang[o.useLang][val] !== 'undefined' ) { return o.lang[o.useLang][val]; } + if ( typeof o[o.mode+'lang'] !== 'undefined' && typeof o[o.mode+'lang'][val] !== 'undefined' ) { return o[o.mode+'lang'][val]; } + return o.lang['default'][val]; + }, + __fmt: function() { + var w = this, + o = this.options; + + switch ( o.mode ) { + case 'timebox': + case 'timeflipbox': + return w.__('timeOutput'); + case 'durationbox': + case 'durationflipbox': + return w.__('durationFormat'); + default: + return w.__('dateFormat'); + } + }, + _zPad: function(number) { + return (( number < 10 ) ? '0' + String(number) : String(number)); + }, + _dRep: function(oper, direction) { + var start = 48, + end = 57, + adder = 1584, + i = null, + ch = null, + newd = ''; + + if ( direction === -1 ) { + start += adder; + end += adder; + adder = -1584; + } + + for ( i=0; i= start && ch <= end ) { + newd = newd + String.fromCharCode(ch+adder); + } else { + newd = newd + String.fromCharCode(ch); + } + } + + return newd; + }, + _doIndic: function() { + var w = this; + + w.d.intHTML.find('*').each(function() { + if ( $(this).children().length < 1 ) { + $(this).text(w._dRep($(this).text())); + } else if ( $(this).hasClass('ui-datebox-slideday') ) { + $(this).html(w._dRep($(this).html())); + } + }); + w.d.intHTML.find('input').each(function() { + $(this).val(w._dRep($(this).val())); + }); + }, + _parser: { + 'default': function (str) { return false; } + }, + _n: function (val,def) { + return ( val < 0 ) ? def : val; + }, + _pa: function (arr,date) { + if ( typeof date === 'boolean' ) { return new this._date(arr[0],arr[1],arr[2],0,0,0,0); } + return new this._date(date.getFullYear(), date.getMonth(), date.getDate(), arr[0], arr[1], arr[2], 0); + }, + _makeDate: function (str) { + // Date Parser + str = $.trim(((this.__('useArabicIndic') === true)?this._dRep(str, -1):str)); + var w = this, + o = this.options, + adv = w.__fmt(), + exp_input = null, + exp_names = [], + exp_format = null, + exp_temp = null, + date = new w._date(), + d = { year: -1, mont: -1, date: -1, hour: -1, mins: -1, secs: -1, week: false, wtyp: 4, wday: false, yday: false, meri: 0 }, + i; + + if ( typeof o.mode === 'undefined' ) { return date; } + if ( typeof w._parser[o.mode] !== 'undefined' ) { return w._parser[o.mode].apply(w,[str]); } + + if ( o.mode === 'durationbox' || o.mode === 'durationflipbox' ) { + adv = adv.replace(/%D([a-z])/gi, function(match, oper) { + switch (oper) { + case 'd': + case 'l': + case 'M': + case 'S': return '(' + match + '|' +'[0-9]+' + ')'; + default: return '.+?'; + } + }); + + adv = new RegExp('^' + adv + '$'); + exp_input = adv.exec(str); + exp_format = adv.exec(w.__fmt()); + + if ( exp_input === null || exp_input.length !== exp_format.length ) { + if ( typeof o.defaultValue === "number" && o.defaultValue > 0 ) { + return new w._date((w.initDate.getEpoch() + parseInt(o.defaultValue,10))*1000); + } + return new w._date(w.initDate.getTime()); + } + + exp_temp = w.initDate.getEpoch(); + for ( i=0; i -1 ) { d.mont = exp_temp; } + break; + case 'B': + exp_temp = $.inArray(exp_input[i], w.__('monthsOfYear')); + if ( exp_temp > -1 ) { d.mont = exp_temp; } + break; + } + } + if ( d.meri !== 0 ) { + if ( d.meri === -1 && d.hour === 12 ) { d.hour = 0; } + if ( d.meri === 1 && d.hour !== 12 ) { d.hour = d.hour + 12; } + } + + date = new w._date(w._n(d.year,0),w._n(d.mont,0),w._n(d.date,1),w._n(d.hour,0),w._n(d.mins,0),w._n(d.secs,0),0); + + if ( d.year < 100 && d.year !== -1 ) { date.setFullYear(d.year); } + + if ( ( d.mont > -1 && d.date > -1 ) || ( d.hour > -1 && d.mins > -1 && d.secs > -1 ) ) { return date; } + + if ( d.week !== false ) { + date.setDWeek(d.wtyp, d.week); + if ( d.date > -1 ) { date.setDate(d.date); } + } + if ( d.yday !== false ) { date.setD(1,0).setD(2,1).adj(2,(d.yday-1)); } + if ( d.wday !== false ) { date.adj(2,(d.wday - date.getDay())); } + } + return date; + }, + _customformat: { + 'default': function(oper, date) { return false; } + }, + _formatter: function(format, date) { + var w = this, + o = this.options, tmp, + dur = { + part: [0,0,0,0], tp: 0 + }; + + if ( o.mode === 'durationbox' || o.mode === 'durationflipbox' ) { + dur.tp = this.theDate.getEpoch() - this.initDate.getEpoch(); + dur.part[0] = parseInt( dur.tp / (60*60*24),10); dur.tp -=(dur.part[0]*60*60*24); // Days + dur.part[1] = parseInt( dur.tp / (60*60),10); dur.tp -= (dur.part[1]*60*60); // Hours + dur.part[2] = parseInt( dur.tp / (60),10); dur.tp -= (dur.part[2]*60); // Minutes + dur.part[3] = dur.tp; // Seconds + + if ( ! format.match(/%Dd/) ) { dur.part[1] += (dur.part[0]*24);} + if ( ! format.match(/%Dl/) ) { dur.part[2] += (dur.part[1]*60);} + if ( ! format.match(/%DM/) ) { dur.part[3] += (dur.part[2]*60);} + } + + format = format.replace(/%(D|X|0|-)*([1-9a-zA-Z])/g, function(match, pad, oper) { + if ( pad === 'X' ) { + if ( typeof w._customformat[o.mode] !== 'undefined' ) { return w._customformat[o.mode](oper, date, o); } + return match; + } + if ( pad === 'D' ) { + switch ( oper ) { + case 'd': return dur.part[0]; + case 'l': return w._zPad(dur.part[1]); + case 'M': return w._zPad(dur.part[2]); + case 'S': return w._zPad(dur.part[3]); + case 'A': return ((dur.part[0] > 1)?w.__('durationDays')[1]:w.__('durationDays')[0]); + default: return match; + } + } + switch ( oper ) { + case '%': // Literal % + return '%'; + case 'a': // Short Day + return w.__('daysOfWeekShort')[date.getDay()]; + case 'A': // Full Day of week + return w.__('daysOfWeek')[date.getDay()]; + case 'b': // Short month + return w.__('monthsOfYearShort')[date.getMonth()]; + case 'B': // Full month + return w.__('monthsOfYear')[date.getMonth()]; + case 'C': // Century + return date.getFullYear().toString().substr(0,2); + case 'd': // Day of month + return (( pad === '-' ) ? date.getDate() : w._zPad(date.getDate())); + case 'H': // Hour (01..23) + case 'k': + return (( pad === '-' ) ? date.getHours() : w._zPad(date.getHours())); + case 'I': // Hour (01..12) + case 'l': + return (( pad === '-' ) ? ((date.getHours() === 0 || date.getHours() === 12)?12:((date.getHours()<12)?date.getHours():(date.getHours()-12))) : w._zPad(((date.getHours() === 0 || date.getHours() === 12)?12:((date.getHours()<12)?date.getHours():date.getHours()-12)))); + case 'm': // Month + return (( pad === '-' ) ? date.getMonth()+1 : w._zPad(date.getMonth()+1)); + case 'M': // Minutes + return (( pad === '-' ) ? date.getMinutes() : w._zPad(date.getMinutes())); + case 'p': // AM/PM (ucase) + return ((date.getHours() < 12)?w.__('meridiem')[0].toUpperCase():w.__('meridiem')[1].toUpperCase()); + case 'P': // AM/PM (lcase) + return ((date.getHours() < 12)?w.__('meridiem')[0].toLowerCase():w.__('meridiem')[1].toLowerCase()); + case 's': // Unix Seconds + return date.getEpoch(); + case 'S': // Seconds + return (( pad === '-' ) ? date.getSeconds() : w._zPad(date.getSeconds())); + case 'u': // Day of week (1-7) + return (( pad === '-' ) ? date.getDay() + 1 : w._zPad(date.getDay() + 1)); + case 'w': // Day of week + return date.getDay(); + case 'y': // Year (2 digit) + return date.getFullYear().toString().substr(2,2); + case 'Y': // Year (4 digit) + return date.getFullYear(); + case 'E': // BE (Buddist Era, 4 Digit) + return date.getFullYear() + 543; + case 'V': + return (( pad === '-' ) ? date.getDWeek(4) : w._zPad(date.getDWeek(4))); + case 'U': + return (( pad === '-' ) ? date.getDWeek(0) : w._zPad(date.getDWeek(0))); + case 'W': + return (( pad === '-' ) ? date.getDWeek(1) : w._zPad(date.getDWeek(1))); + case 'o': // Ordinals + if ( typeof w._ord[o.useLang] !== 'undefined' ) { return w._ord[o.useLang](date.getDate()); } + return w._ord['default'](date.getDate()); + case 'j': + tmp = new Date(date.getFullYear(),0,1); + tmp = Math.ceil((date - tmp) / 86400000)+1; + return (( tmp < 100 ) ? (( tmp < 10 )? '00' : '0') : '' ) + String(tmp); + case 'G': + if ( date.getDWeek(4) === 1 && date.getMonth() > 0 ) { return date.getFullYear() + 1; } + if ( date.getDWeek(4) > 51 && date.getMonth() < 11 ) { return date.getFullYear() - 1; } + return date.getFullYear(); + case 'g': + if ( date.getDWeek(4) === 1 && date.getMonth() > 0 ) { return parseInt(date.getFullYear().toString().substr(2,2),10) + 1; } + if ( date.getDWeek(4) > 51 && date.getMonth() < 11 ) { return parseInt(date.getFullYear().toString().substr(2,2),10) - 1; } + return date.getFullYear().toString().substr(2,2); + default: + return match; + } + }); + + if ( w.__('useArabicIndic') === true ) { + format = w._dRep(format); + } + + return format; + }, + _btwn: function(value, low, high) { + return ( value > low && value < high ); + }, + _minStepFix: function() { + var tempMin = this.theDate.get(4), tmp, + w = this, + o = this.options; + + if ( o.minuteStep > 1 && tempMin % o.minuteStep > 0 ) { + if ( o.minuteStepRound < 0 ) { + tempMin = tempMin - (tempMin % o.minuteStep); + } else if ( o.minStepRound > 0 ) { + tempMin = tempMin + ( o.minuteStep - ( tempMin % o.minuteStep ) ); + } else { + if ( tempMin % o.minuteStep < o.minuteStep / 2 ) { + tempMin = tempMin - (tempMin % o.minuteStep); + } else { + tempMin = tempMin + ( o.minuteStep - ( tempMin % o.minuteStep ) ); + } + } + w.theDate.setMinutes(tempMin); + } + }, + _offset: function(mode, amount, update) { + // Compute a date/time offset. + // update = false to prevent controls refresh + var w = this, + o = this.options, + ok = false; + + mode = (mode || "").toLowerCase(); + + if ( typeof(update) === "undefined" ) { update = true; } + w.d.input.trigger('datebox', {'method':'offset', 'type':mode, 'amount':amount}); + + if ( mode !== 'a' && ( typeof o.rolloverMode[mode] === 'undefined' || o.rolloverMode[mode] === true )) { + ok = $.inArray(mode, ['y','m','d','h','i','s']); + } else { + switch(mode) { + case 'y': ok = 0; break; + case 'm': + if ( w._btwn(w.theDate.getMonth()+amount,-1,12) ) { ok = 1; } + break; + case 'd': + if ( w._btwn(w.theDate.getDate() + amount,0,(32 - w.theDate.copy([0],[0,0,32,13]).getDate() + 1) )) { ok = 2; } + break; + case 'h': + if ( w._btwn(w.theDate.getHours() + amount,-1,24) ) { ok = 3; } + break; + case 'i': + if ( w._btwn(w.theDate.getMinutes() + amount,-1,60) ) { ok = 4; } + break; + case 's': + if ( w._btwn(w.theDate.getSeconds() + amount,-1,60) ) { ok = 5; } + break; + case 'a': + w._offset('h',((amount>0)?1:-1)*12,false); + break; + } + } + if ( ok !== false ) { w.theDate.adj(ok,amount); } + if ( update === true ) { w.refresh(); } + if ( o.useImmediate ) { w.d.input.trigger('datebox', {'method':'doset'}); } + }, + _startOffset: function(date) { + var o = this.options; + + if ( o.startOffsetYears !== false ) { + date.adj(0, o.startOffsetYears); + } + if ( o.startOffsetMonths !== false ) { + date.adj(1, o.startOffsetMonths); + } + if ( o.startOffsetDays !== false ) { + date.adj(2, o.startOffsetDays); + } + return date; + }, + _create: function() { + // Create the widget, called automatically by widget system + $( document ).trigger( "dateboxcreate" ); + + var w = this, + o = $.extend(this.options, (typeof this.element.jqmData('options') !== 'undefined') ? this.element.jqmData('options') : this._getLongOptions(this.element) ), + thisTheme = ( o.theme === false && typeof($(this).jqmData('theme')) === 'undefined' ) ? + ( ( typeof(this.element.parentsUntil(':jqmData(theme)').parent().jqmData('theme')) === 'undefined' ) ? + o.themeDefault : this.element.parentsUntil(':jqmData(theme)').parent().jqmData('theme') ) + : o.theme, + trans = o.useAnimation ? o.transition : 'none', + d = o.useNewStyle === false ? { + input: this.element, + wrap: this.element.wrap('
').parent(), + mainWrap: $("
", { "class": 'ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden '+trans+' ui-body-'+thisTheme} ).css('zIndex', o.zindex), + intHTML: false + } : { + input: this.element, + wrap: this.element, + mainWrap: $("
", { "class": 'ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden '+trans+' ui-body-'+thisTheme} ).css('zIndex', o.zindex), + intHTML: false + }, + touch = ( typeof window.ontouchstart !== 'undefined' ), + drag = { + eStart : (touch ? 'touchstart' : 'mousedown')+'.datebox', + eMove : (touch ? 'touchmove' : 'mousemove')+'.datebox', + eEnd : (touch ? 'touchend' : 'mouseup')+'.datebox', + eEndA : (touch ? 'mouseup.datebox touchend.datebox touchcancel.datebox touchmove.datebox' : 'mouseup.datebox'), + move : false, + start : false, + end : false, + pos : false, + target : false, + delta : false, + tmp : false + }, + calc = { }, + ns = (typeof $.mobile.ns !== 'undefined')?$.mobile.ns:''; + + $.extend(w, {d: d, ns: ns, drag: drag, touch:touch}); + + if ( o.usePlaceholder !== false ) { + if ( o.usePlaceholder === true && w._grabLabel() !== false ) { w.d.input.attr('placeholder', w._grabLabel()); } + if ( typeof o.usePlaceholder === 'string' ) { w.d.input.attr('placeholder', o.usePlaceholder); } + } + + o.theme = thisTheme; + + w.clearFunc = false; + w.disabled = false; + w.runButton = false; + w._date = window.Date; + w._enhanceDate(); + w.baseID = w.d.input.attr('id'); + + w.initDate = new w._date(); + w.theDate = (o.defaultValue) ? w._makeDate(o.defaultValue) : ( (w.d.input.val() !== "") ? w._makeDate(w.d.input.val()) : new w._date() ); + w.initDone = false; + + if ( o.showInitialValue === true ) { + w.d.input.val(w._formatter(w.__fmt(), w.theDate)); + } + + if ( o.useButton === true && o.useInline === false && o.useNewStyle === false ) { + w.d.open = $(''+this.__('tooltip')+'') + .on(o.clickEvent, function(e) { + e.preventDefault(); + if ( !w.disabled ) { w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.parent().addClass('ui-focus'); w.d.input.parent().removeClass('ui-focus'); } + setTimeout( function() { $(e.target).closest('a').removeClass($.mobile.activeBtnClass); }, 300); + }).appendTo(w.d.wrap).buttonMarkup({icon: 'grid', iconpos: 'notext', corners:true, shadow:true}) + .css({'vertical-align': 'middle', 'display': 'inline-block'}); + } + + w.d.screen = $("
", {'class':'ui-datebox-screen ui-datebox-hidden'+((o.useModal)?' ui-datebox-screen-modal':'')}) + .css({'z-index': o.zindex-1}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.trigger('datebox', {'method':'close'}); + }); + + if ( o.enhanceInput === true && navigator.userAgent.match(/Android/i) ){ + w.inputType = 'number'; + } else { + w.inputType = 'text'; + } + + if ( o.hideInput ) { w.d.wrap.parent().hide(); } + + if ( o.mobVer < 140 ) { + $('label[for=\''+w.d.input.attr('id')+'\']').addClass('ui-input-text').css('verticalAlign', 'middle'); + } + + w.d.wrap.on(o.clickEvent, function() { + if ( !w.disabled && ( o.noButtonFocusMode || o.focusMode ) ) { + w.d.input.trigger('datebox', {'method': 'open'}); + w.d.wrap.addClass('ui-focus'); + w.d.input.removeClass('ui-focus'); + } + }); + + w.d.input + .removeClass('ui-corner-all ui-shadow-inset') + .bind(w.touch?'touchend':'click', function(e){ + if ( w.disabled === false && o.useNewStyle === true && o.useFocus === false ) { + if ( ((w.touch ? e.originalEvent.changedTouches[0].pageX : e.pageX) - e.target.offsetLeft) > (e.target.offsetWidth - 20) ) { + w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.parent().addClass('ui-focus'); w.d.input.removeClass('ui-focus'); + //setTimeout(function(){w.d.wrap.addClass('ui-focus');}, 200); + } + } + }) + .focus(function(){ + if ( w.disabled === false && o.useFocus === true ) { + w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.addClass('ui-focus'); w.d.input.removeClass('ui-focus'); + if ( o.useNewStyle === false ) { w.d.input.parent().removeClass('ui-focus'); w.d.wrap.parent().addClass('ui-focus'); } + } + if ( o.useNewStyle === false ) { w.d.input.removeClass('ui-focus'); } + }) + .blur(function(){ + w.d.wrap.removeClass('ui-focus'); + w.d.input.removeClass('ui-focus'); + }) + .change(function() { + w.theDate = w._makeDate(w.d.input.val()); + w.refresh(); + }) + .attr("readonly", o.lockInput) + .on('datebox', w._event); + + if ( o.useNewStyle === true ) { + w.d.input.addClass('ui-corner-all '+((o.useAltIcon===true)?'ui-icon-datebox-alt':'ui-icon-datebox')); + if ( o.overrideStyleClass !== false ) { w.d.input.addClass(o.overrideStyleClass); } + } else { + w.d.input.parent().css('border', 'none').removeClass('ui-shadow-inset'); + } + + w.d.wrap.parent().on(o.clickEvent, function() { + if ( !w.disabled && o.useFocus === true && o.useNewStyle === false ) { + w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.addClass('ui-focus'); w.d.input.removeClass('ui-focus'); + setTimeout(function(){ + w.d.wrap.removeClass('ui-focus'); + w.d.wrap.parent().addClass('ui-focus'); + }, 500); + } + }); + + // Check if mousewheel plugin is loaded + if ( typeof $.event.special.mousewheel !== 'undefined' ) { w.wheelExists = true; } + + // Disable when done if element attribute disabled is true. + if ( w.d.input.is(':disabled') ) { + w.disable(); + } + + if ( o.useInline === true || o.useInlineBlind ) { w.open(); } + + w.applyMinMax(false, false); + + //Throw dateboxinit event + $( document ).trigger( "dateboxaftercreate" ); + }, + applyMinMax: function(refresh, override) { + var w = this, + o = this.options, + calc = {}; + + if ( typeof refresh === 'undefined' ) { refresh = false; } + if ( typeof override === 'undefined' ) { override = true; } + + if ( ( override === true || o.minDays === false ) && typeof(w.d.input.attr('min')) !== 'undefined' ) { + calc.today = new w._date(); + calc.lod = 24 * 60 * 60 * 1000; + calc.todayc = new w._date(calc.today.getFullYear(), calc.today.getMonth(), calc.today.getDate(), 0,0,0,0); + calc.fromel = w.d.input.attr('min').split('-'); + calc.compdt = new w._date(calc.fromel[0],calc.fromel[1]-1,calc.fromel[2],0,0,0,0); + o.minDays = parseInt((((calc.compdt.getTime() - calc.todayc.getTime()) / calc.lod))*-1,10); + } + if ( ( override === true || o.maxDays === false ) && typeof(w.d.input.attr('max')) !== 'undefined' ) { + calc.today = new w._date(); + calc.lod = 24 * 60 * 60 * 1000; + calc.todayc = new w._date(calc.today.getFullYear(), calc.today.getMonth(), calc.today.getDate(), 0,0,0,0); + calc.fromel = w.d.input.attr('max').split('-'); + calc.compdt = new w._date(calc.fromel[0],calc.fromel[1]-1,calc.fromel[2],0,0,0,0); + o.maxDays = parseInt((((calc.compdt.getTime() - calc.todayc.getTime()) / calc.lod)),10); + } + + if ( refresh === true ) { w.refresh(); } + }, + _build: { + 'default': function () { + this.d.headerText = "Error"; + this.d.intHTML = $("

There is no mode by that name loaded / mode not given

"); + } + }, + _applyCoords: function(e) { + var w = e.widget, + o = e.widget.options, + fixd = { + h: $.mobile.activePage.find('.ui-header').jqmData('position'), + f: $.mobile.activePage.find('.ui-footer').jqmData('position'), + fh: $.mobile.activePage.find('.ui-footer').outerHeight(), + hh: $.mobile.activePage.find('.ui-header').outerHeight() + }, + iput = { + x: w.d.wrap.offset().left + (w.d.wrap.outerWidth() / 2), + y: w.d.wrap.offset().top + (w.d.wrap.outerHeight() / 2) + }, + size = { + w: w.d.mainWrap.outerWidth(), + h: w.d.mainWrap.outerHeight() + }, + doc = { + t: $(window).scrollTop(), + h: $(window).height(), + w: $.mobile.activePage.width(), + ah: $(document).height() + }, + pos = { + y: (o.centerVert) ? doc.t + ((doc.h / 2) - (size.h / 2)) : iput.y - ( size.h / 2 ), + x: (doc.w < 400 || o.centerHoriz ) ? (doc.w / 2) - (size.w /2) : iput.x - (size.w / 2) + }; + + if ( o.centerVert === false ) { + if ( o.hideFixedToolbars === true && ( typeof fixd.f !== 'undefined' || typeof fixd.h !== 'undefined' )) { + $.mobile.activePage.find(":jqmData(position='fixed')").fixedtoolbar('hide'); + fixd.f = undefined; + fixd.h = undefined; + } + + if ( typeof fixd.f !== 'undefined' ) { + if ( ( pos.y + size.h ) > ( doc.h - fixd.fh - 2 ) ) { + pos.y = doc.h - fixd.fh - 2 - size.h; + } + } else { + if ( ( pos.y + size.h ) > ( doc.ah - fixd.fh - 2 ) ) { + pos.y = doc.ah - fixd.fh - 2 - size.h; + } + if ( ( doc.h + doc.t ) < ( size.h + pos.y + 2 ) ) { + pos.y = doc.h + doc.t - size.h - 2; + } + } + + if ( typeof fixd.h !== 'undefined' ) { + if ( ( doc.t + fixd.hh + 2 ) > pos.y ) { + pos.y = doc.t + fixd.hh + 2; + } + } else { + if ( fixd.hh + 2 > pos.y ) { + pos.y = fixd.hh + 2; + } + if ( pos.y < doc.t + 2 ) { + pos.y = doc.t + 2; + } + } + } + w.d.mainWrap.css({'position': 'absolute', 'top': pos.y, 'left': pos.x}); + }, + _drag: { + 'default': function () { return false; } + }, + open: function () { + var w = this, + o = this.options, + popopts = {}, + basepop = {'history':false}, + qns = 'data-'+this.ns, + trans = o.useAnimation ? o.transition : 'none'; + + if ( o.useFocus === true && w.fastReopen === true ) { w.d.input.blur(); return false; } + if ( w.clearFunc !== false ) { + clearTimeout(w.clearFunc); w.clearFunc = false; + } + + // Call the open callback if provided. Additionally, if this + // returns false then the open/update will stop. + if ( o.openCallback !== false ) { + if ( ! $.isFunction(o.openCallback) ) { + if ( typeof window[o.openCallback] !== 'undefined' ) { + o.openCallback = window[o.openCallback]; + } else { + o.openCallback = new Function(o.openCallback); + } + } + if ( o.openCallback.apply(w, $.merge([w.theDate],o.openCallbackArgs)) === false ) { return false; } + } + + w.theDate = w._makeDate(w.d.input.val()); + if ( w.d.input.val() === "" ) { w._startOffset(w.theDate); } + w.d.input.blur(); + + if ( typeof w._build[o.mode] === 'undefined' ) { + w._build['default'].apply(w,[]); + } else { + w._build[o.mode].apply(w,[]); + } + if ( typeof w._drag[o.mode] !== 'undefined' ) { + w._drag[o.mode].apply(w, []); + } + w.d.input.trigger('datebox', {'method':'refresh'}); + if ( w.__('useArabicIndic') === true ) { w._doIndic(); } + + if ( ( o.useInline === true || o.useInlineBlind === true ) && w.initDone === false ) { + w.d.mainWrap.append(w.d.intHTML); + w.d.input.parent().parent().append(w.d.mainWrap); + w.d.mainWrap.removeClass('ui-datebox-hidden'); + if ( o.useInline === true ) { + w.d.mainWrap.addClass('ui-datebox-inline'); + } else { + w.d.mainWrap.addClass('ui-datebox-inlineblind'); + w.d.mainWrap.hide(); + } + w.initDone = false; + w.d.input.trigger('datebox',{'method':'postrefresh'}); + } + + if ( o.useImmediate ) { w.d.input.trigger('datebox', {'method':'doset'}); } + if ( o.useInline ) { return true; } + if ( o.useInlineBlind ) { + if ( w.initDone ) { w.d.mainWrap.slideDown(); } + else { w.initDone = true; } + return true; + } + if ( w.d.intHTML.is(':visible') ) { return false; } // Ignore if already open + + if ( o.enablePopup === true ) { + w.d.dialogPage = false; + w.d.mainWrap.empty(); + if ( o.useHeader === true ) { + w.d.headHTML = $('
'); + $("Close").appendTo(w.d.headHTML) + .buttonMarkup({ theme : o.themeHeader, icon : 'delete', iconpos: 'notext', corners: true, shadow : true }) + .on(o.clickEventAlt, function(e) { e.preventDefault(); w.d.input.trigger('datebox', {'method':'close'}); }); + $('

'+w.d.headerText+'

').appendTo(w.d.headHTML); + w.d.mainWrap.append(w.d.headHTML); + } + w.d.mainWrap.append(w.d.intHTML).css('zIndex', o.zindex); + w.d.input.trigger('datebox',{'method':'postrefresh'}); + + if ( o.useAnimation === true ) { + popopts.transition = o.transition; + } else { + popopts.transition = "none"; + } + + if ( o.popupForceX !== false && o.popupForceY !== false ) { + popopts.x = o.popupForceX; + popopts.y = o.popupForceY; + } + + if ( o.popupPosition !== false ) { + popopts.positionTo = o.popupPosition; + } else { + if ( typeof w.baseID !== undefined ) { + popopts.positionTo = '#' + w.baseID; + } else { + popopts.positionTo = 'window'; + } + } + + if ( o.useModal === true ) { basepop.overlayTheme = "a"; } + + w.d.mainWrap.removeClass('ui-datebox-hidden').popup(basepop).popup("open", popopts); + w.refresh(); + } else { + if ( o.dialogForce || ( o.dialogEnable && window.width() < 400 ) ) { + w.d.dialogPage = $("
" + + "
" + + "

"+w.d.headerText+"

") + .appendTo( $.mobile.pageContainer ) + .page().css('minHeight', '0px').addClass(trans); + w.d.dialogPage.find('.ui-header').find('a').off('click vclick').on(o.clickEventAlt, function(e) { e.preventDefault(); w.d.input.trigger('datebox', {'method':'close'}); }); + w.d.mainWrap.append(w.d.intHTML).css({'marginLeft':'auto', 'marginRight':'auto'}).removeClass('ui-datebox-hidden'); + w.d.dialogPage.find('.ui-content').append(w.d.mainWrap); + w.d.input.trigger('datebox',{'method':'postrefresh'}); + $.mobile.activePage.off( "pagehide.remove" ); + $.mobile.changePage(w.d.dialogPage, {'transition': trans}); + } else { + w.d.dialogPage = false; + w.d.mainWrap.empty(); + if ( o.useHeader === true ) { + w.d.headHTML = $('
'); + $("Close").appendTo(w.d.headHTML) + .buttonMarkup({ theme : o.themeHeader, icon : 'delete', iconpos: 'notext', corners: true, shadow : true }) + .on(o.clickEventAlt, function(e) { e.preventDefault(); w.d.input.trigger('datebox', {'method':'close'}); }); + $('

'+w.d.headerText+'

').appendTo(w.d.headHTML); + w.d.mainWrap.append(w.d.headHTML); + } + w.d.mainWrap.append(w.d.intHTML).css('zIndex', o.zindex); + w.d.mainWrap.appendTo($.mobile.activePage); + w.d.screen.appendTo($.mobile.activePage); + w.d.input.trigger('datebox',{'method':'postrefresh'}); + w._applyCoords({widget:w}); + + if ( o.useModal === true ) { + if(o.useAnimation) { + w.d.screen.fadeIn('slow'); + } else { + w.d.screen.show(); + } + } else { + setTimeout(function () { w.d.screen.removeClass('ui-datebox-hidden');}, 500); + } + + w.d.mainWrap.addClass('ui-overlay-shadow in').removeClass('ui-datebox-hidden'); + + $(document).on('orientationchange.datebox', {widget:w}, function(e) { w._applyCoords(e.data); }); + if ( o.resizeListener === true ) { + $(window).on('resize.datebox', {widget:w}, function (e) { w._applyCoords(e.data); }); + } + } + } + }, + close: function() { + var w = this, + o = this.options; + + if ( o.useInlineBlind === true ) { w.d.mainWrap.slideUp(); return true;} + if ( o.useInline === true || w.d.intHTML === false ) { return true; } + + if ( w.d.dialogPage !== false ) { + $(w.d.dialogPage).dialog('close'); + + if ( ! $.mobile.activePage.jqmData('mobile-page').options.domCache ) { + $.mobile.activePage.on('pagehide.remove', function () { $(this).remove(); }); + } + + w.d.intHTML.detach().empty(); + w.d.mainWrap.detach().empty(); + w.d.wrap.removeClass('ui-focus'); + w.clearFunc = setTimeout(function () { w.d.dialogPage.empty().remove(); w.clearFunc = false; }, 1500); + } else { + if ( o.enablePopup === true ) { + w.d.mainWrap.popup('close'); + w.d.wrap.removeClass('ui-focus'); + } else { + if ( o.useModal ) { + if(o.useAnimation) { + w.d.screen.fadeOut('slow'); + } else { + w.d.screen.hide(); + } + } else { + w.d.screen.addClass('ui-datebox-hidden'); + } + w.d.screen.detach(); + w.d.mainWrap.addClass('ui-datebox-hidden').removeAttr('style').removeClass('in ui-overlay-shadow').empty().detach(); + w.d.intHTML.detach(); + w.d.wrap.removeClass('ui-focus'); + + $(document).off('orientationchange.datebox'); + if ( o.resizeListener === true ) { + $(window).off('resize.datebox'); + } + } + } + w.d.wrap.parent().removeClass('ui-focus'); + + $(document).off(w.drag.eMove); + $(document).off(w.drag.eEnd); + $(document).off(w.drag.eEndA); + + if ( o.useFocus ) { + w.fastReopen = true; + setTimeout(function(t) { return function () { t.fastReopen = false; };}(w), 300); + } + + if ( o.closeCallback !== false ) { + if ( ! $.isFunction(o.closeCallback) ) { + if ( typeof window[o.closeCallback] !== 'undefined' ) { + o.closeCallback = window[o.closeCallback]; + } else { + o.closeCallback = new Function(o.closeCallback); + } + } + o.closeCallback.apply(w, $.merge([w.theDate], o.closeCallbackArgs)); + } + }, + refresh: function() { + if ( typeof this._build[this.options.mode] === 'undefined' ) { + this._build['default'].apply(this,[]); + } else { + this._build[this.options.mode].apply(this,[]); + } + if ( this.__('useArabicIndic') === true ) { this._doIndic(); } + this.d.mainWrap.append(this.d.intHTML); + this.d.input.trigger('datebox',{'method':'postrefresh'}); + }, + _check: function() { + var w = this, + td = null, + o = this.options; + + w.dateOK = true; + + if ( o.afterToday !== false ) { + td = new w._date(); + if ( w.theDate < td ) { w.theDate = td; } + } + if ( o.beforeToday !== false ) { + td = new w._date(); + if ( w.theDate > td ) { w.theDate = td; } + } + if ( o.maxDays !== false ) { + td = new w._date(); + td.adj(2, o.maxDays); + if ( w.theDate > td ) { w.theDate = td; } + } + if ( o.minDays !== false ) { + td = new w._date(); + td.adj(2, -1*o.minDays); + if ( w.theDate < td ) { w.theDate = td; } + } + if ( o.minHour !== false ) { + if ( w.theDate.getHours() < o.minHour ) { + w.theDate.setHours(o.minHour); + } + } + if ( o.maxHour !== false ) { + if ( w.theDate.getHours() > o.maxHour ) { + w.theDate.setHours(o.maxHour); + } + } + if ( o.maxYear !== false ) { + td = new w._date(o.maxYear, 0, 1); + td.adj(2, -1); + if ( w.theDate > td ) { w.theDate = td; } + } + if ( o.minYear !== false ) { + td = new w._date(o.minYear, 0, 1); + if ( w.theDate < td ) { w.theDate = td; } + } + + if ( $.inArray(o.mode, ['timebox','durationbox','durationflipbox','timeflipbox']) > -1 ) { + if ( o.mode === 'timeflipbox' && o.validHours !== false ) { + if ( $.inArray(w.theDate.getHours(), o.validHours) < 0 ) { w.dateOK = false; } + } + } else { + if ( o.blackDatesRec !== false ) { + for ( i=0; i -1 ) { w.dateOK = false; } + } + if ( o.blackDays !== false ) { + if ( $.inArray(w.theDate.getDay(), o.blackDays) > -1 ) { w.dateOK = false; } + } + } + }, + _grabLabel: function() { + var w = this, + o = this.options; + + if ( typeof o.overrideDialogLabel === 'undefined' ) { + if ( typeof w.d.input.attr('placeholder') !== 'undefined' ) { return w.d.input.attr('placeholder'); } + if ( typeof w.d.input.attr('title') !== 'undefined' ) { return w.d.input.attr('title'); } + if ( w.d.wrap.parent().find('label[for=\''+w.d.input.attr('id')+'\']').text() !== '' ) { + return w.d.wrap.parent().find('label[for=\''+w.d.input.attr('id')+'\']').text(); + } + return false; + } + return o.overrideDialogLabel; + }, + _makeEl: function(source, parts) { + var part = false, + retty = false; + + retty = source.clone(); + + if ( typeof parts.attr !== 'undefined' ) { + for ( part in parts.attr ) { + if ( parts.attr.hasOwnProperty(part) ) { + retty.jqmData(part, parts.attr[part]); + } + } + } + return retty; + }, + _getLongOptions: function(element) { + var key, retty = {}, prefix, temp; + + if ( $.mobile.ns === "" ) { + prefix = "datebox"; + } else { + prefix = $.mobile.ns.substr(0, $.mobile.ns.length - 1) + 'Datebox'; + } + + for ( key in element.data() ) { + if ( key.substr(0, prefix.length) === prefix && key.length > prefix.length ) { + temp = key.substr(prefix.length); + temp = temp.charAt(0).toLowerCase() + temp.slice(1); + retty[temp] = element.data(key); + } + } + return retty; + }, + disable: function(){ + // Disable the element + this.d.input.attr("disabled",true); + this.d.wrap.addClass("ui-disabled").blur(); + this.disabled = true; + this.d.input.trigger('datebox', {'method':'disable'}); + }, + enable: function(){ + // Enable the element + this.d.input.attr("disabled", false); + this.d.wrap.removeClass("ui-disabled"); + this.disabled = false; + this.d.input.trigger('datebox', {'method':'enable'}); + }, + _setOption: function() { + $.Widget.prototype._setOption.apply( this, arguments ); + this.refresh(); + }, + getTheDate: function() { + return this.theDate; + }, + getLastDur: function() { + return this.lastDuration; + }, + setTheDate: function(newDate) { + this.theDate = newDate; + this.refresh(); + }, + callFormat: function(format, date) { + return this._formatter(format, date); + } + }); + + // Degrade date inputs to text inputs, suppress standard UI functions. + $( document ).on( "pagebeforecreate", function( e ) { + $( ":jqmData(role='datebox')", e.target ).each(function() { + $(this).prop('type', 'text'); + }); + }); + // Automatically bind to data-role='datebox' items. + $( document ).on( "pagecreate create", function( e ){ + $( document ).trigger( "dateboxbeforecreate" ); + $( ":jqmData(role='datebox')", e.target ).each(function() { + var defed = typeof ($(this).data(parseInt($.mobile.version.replace(/\./g,''),10) > 111 ? 'mobile-datebox' : 'datebox')); + if ( defed === "undefined" ) { + $(this).datebox(); + } + }); + }); +})( jQuery ); +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +/* CALBOX Mode */ +// Version Notes: <140 :: New button theme method, still use _hoover + +(function($) { + $.extend( $.mobile.datebox.prototype.options, { + themeDateToday: 'b', + themeDayHigh: 'b', + themeDatePick: 'b', + themeDateHigh: 'b', + themeDateHighAlt: 'b', + themeDateHighRec: 'b', + themeDate: 'a', + + calHighToday: true, + calHighPick: true, + + calShowDays: true, + calOnlyMonth: false, + calWeekMode: false, + calWeekModeDay: 1, + calWeekHigh: false, + calControlGroup: false, + calShowWeek: false, + calUsePickers: false, + calNoHeader: false, + + useTodayButton: false, + useCollapsedBut: false, + + highDays: false, + highDates: false, + highDatesRec: false, + highDatesAlt: false, + enableDates: false, + calDateList: false, + calShowDateList: false, + }); + $.extend( $.mobile.datebox.prototype, { + _cal_gen: function (start,prev,last,other,month) { + var rc = 0, cc = 0, day = 1, + next = 1, cal = [], row = [], stop = false; + + for ( rc = 0; rc <= 5; rc++ ) { + if ( stop === false ) { + row = []; + for ( cc = 0; cc <= 6; cc++ ) { + if ( rc === 0 && cc < start ) { + if ( other === true ) { + row.push([prev + (cc - start) + 1,month-1]); + } else { + row.push(false); + } + } else if ( rc > 3 && day > last ) { + if ( other === true ) { + row.push([next,month+1]); next++; + } else { + row.push(false); + } + stop = true; + } else { + row.push([day,month]); day++; + if ( day > last ) { stop = true; } + } + } + cal.push(row); + } + } + return cal; + }, + _cal_check : function (cal, year, month, date) { + var w = this, i, + o = this.options, + ret = {}, + day = new this._date(year,month,date,0,0,0,0).getDay(); + + ret.ok = true; + ret.iso = year + '-' + w._zPad(month+1) + '-' + w._zPad(date); + ret.comp = parseInt(ret.iso.replace(/-/g, ''),10); + ret.theme = o.themeDate; + ret.recok = true; + ret.rectheme = false; + + if ( o.blackDatesRec !== false ) { + for ( i=0; i ret.comp ) || + ( o.beforeToday === true && cal.thisDate.comp() < ret.comp ) || + ( o.notToday === true && cal.thisDate.comp() === ret.comp ) || + ( o.maxDays !== false && cal.maxDate.comp() < ret.comp ) || + ( o.minDays !== false && cal.minDate.comp() > ret.comp ) || + ( $.isArray(o.blackDays) && $.inArray(day, o.blackDays) > -1 ) || + ( $.isArray(o.blackDates) && $.inArray(ret.iso, o.blackDates) > -1 ) + ) { + ret.ok = false; + } + } + if ( ret.ok ) { + if ( o.highDatesRec !== false ) { + for ( i=0; i -1) ) { + ret.theme = o.themeDateHighAlt; + } else if ( $.isArray(o.highDates) && ($.inArray(ret.iso, o.highDates) > -1) ) { + ret.theme = o.themeDateHigh; + } else if ( $.isArray(o.highDays) && ($.inArray(day, o.highDays) > -1) ) { + ret.theme = o.themeDayHigh; + } else if ( $.isArray(o.highDatesRec) && ret.rectheme === true ) { + ret.theme = o.themeDateHighRec; + } + } + return ret; + } + }); + $.extend( $.mobile.datebox.prototype._build, { + 'calbox': function () { + var w = this, + o = this.options, i, + cal = false, + uid = 'ui-datebox-', + temp = false, row = false, col = false, hRow = false, checked = false; + + if ( typeof w.d.intHTML !== 'boolean' ) { + w.d.intHTML.remove(); + } + + w.d.headerText = ((w._grabLabel() !== false)?w._grabLabel():w.__('titleDateDialogLabel')); + w.d.intHTML = $(''); + + $('

' + + w._formatter(w.__('calHeaderFormat'), w.theDate) + + '

').appendTo(w.d.intHTML); + + // Previous and next month buttons, define booleans to decide if they should do anything + $("") + .prependTo(w.d.intHTML.find('.'+uid+'gridheader')) + .buttonMarkup({theme: o.themeDate, icon: 'arrow-r', inline: true, iconpos: 'notext', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + if ( w.calNext ) { + if ( w.theDate.getDate() > 28 ) { w.theDate.setDate(1); } + w._offset('m',1); + } + }); + $("") + .prependTo(w.d.intHTML.find('.'+uid+'gridheader')) + .buttonMarkup({theme: o.themeDate, icon: 'arrow-l', inline: true, iconpos: 'notext', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + if ( w.calPrev ) { + if ( w.theDate.getDate() > 28 ) { w.theDate.setDate(1); } + w._offset('m',-1); + } + }); + + if ( o.calNoHeader === true ) { w.d.intHTML.find('.'+uid+'gridheader').remove(); } + + cal = {'today': -1, 'highlightDay': -1, 'presetDay': -1, 'startDay': w.__('calStartDay'), + 'thisDate': new w._date(), 'maxDate': w.initDate.copy(), 'minDate': w.initDate.copy(), + 'currentMonth': false, 'weekMode': 0, 'weekDays': null }; + cal.start = (w.theDate.copy([0],[0,0,1]).getDay() - w.__('calStartDay') + 7) % 7; + cal.thisMonth = w.theDate.getMonth(); + cal.thisYear = w.theDate.getFullYear(); + cal.wk = w.theDate.copy([0],[0,0,1]).adj(2,(-1*cal.start)+(w.__('calStartDay')===0?1:0)).getDWeek(4); + cal.end = 32 - w.theDate.copy([0],[0,0,32,13]).getDate(); + cal.lastend = 32 - w.theDate.copy([0,-1],[0,0,32,13]).getDate(); + cal.presetDate = (w.d.input.val() === "") ? w._startOffset(w._makeDate(w.d.input.val())) : w._makeDate(w.d.input.val()); + cal.thisDateArr = cal.thisDate.getArray(); + cal.theDateArr = w.theDate.getArray(); + cal.checkDates = ( $.inArray(false, [o.afterToday, o.beforeToday, o.notToday, o.maxDays, o.minDays, o.blackDates, o.blackDays]) > -1 ); + + w.calNext = true; + w.calPrev = true; + + if ( cal.thisDateArr[0] === cal.theDateArr[0] && cal.thisDateArr[1] === cal.theDateArr[1] ) { cal.currentMonth = true; } + if ( cal.presetDate.comp() === w.theDate.comp() ) { cal.presetDay = cal.presetDate.getDate(); } + + if ( o.afterToday === true && + ( cal.currentMonth === true || ( cal.thisDateArr[1] >= cal.theDateArr[1] && cal.theDateArr[0] === cal.thisDateArr[0] ) ) ) { + w.calPrev = false; } + if ( o.beforeToday === true && + ( cal.currentMonth === true || ( cal.thisDateArr[1] <= cal.theDateArr[1] && cal.theDateArr[0] === cal.thisDateArr[0] ) ) ) { + w.calNext = false; } + + if ( o.minDays !== false ) { + cal.minDate.adj(2, -1*o.minDays); + if ( cal.theDateArr[0] === cal.minDate.getFullYear() && cal.theDateArr[1] <= cal.minDate.getMonth() ) { w.calPrev = false;} + } + if ( o.maxDays !== false ) { + cal.maxDate.adj(2, o.maxDays); + if ( cal.theDateArr[0] === cal.maxDate.getFullYear() && cal.theDateArr[1] >= cal.maxDate.getMonth() ) { w.calNext = false;} + } + + if ( o.calUsePickers === true ) { + cal.picker = $('
', {'class': 'ui-grid-a ui-datebox-grid','style':'padding-top: 5px; padding-bottom: 5px;'}); + + cal.picker1 = $('
').appendTo(cal.picker).find('select'); + cal.picker2 = $('
').appendTo(cal.picker).find('select'); + + for ( i=0; i<=11; i++ ) { + cal.picker1.append($('')); + } + for ( i=(cal.thisYear-6); i<=cal.thisYear+6; i++ ) { + cal.picker2.append($('')); + } + + cal.picker1.on('change', function () { w.theDate.setMonth($(this).val()); w.refresh(); }); + cal.picker2.on('change', function () { w.theDate.setFullYear($(this).val()); w.refresh(); }); + + cal.picker.find('select').selectmenu({mini:true, nativeMenu: true}); + cal.picker.appendTo(w.d.intHTML); + } + + temp = $('
').appendTo(w.d.intHTML); + + if ( o.calShowDays ) { + w._cal_days = w.__('daysOfWeekShort').concat(w.__('daysOfWeekShort')); + cal.weekDays = $("
", {'class':uid+'gridrow'}).appendTo(temp); + if ( w.__('isRTL') === true ) { cal.weekDays.css('direction', 'rtl'); } + if ( o.calShowWeek ) { + $("
").addClass(uid+'griddate '+uid+'griddate-empty '+uid+'griddate-label').appendTo(cal.weekDays); + } + for ( i=0; i<=6;i++ ) { + $("
"+w._cal_days[(i+cal.startDay)%7]+"
").addClass(uid+'griddate '+uid+'griddate-empty '+uid+'griddate-label').appendTo(cal.weekDays); + } + } + + cal.gen = w._cal_gen(cal.start, cal.lastend, cal.end, !o.calOnlyMonth, w.theDate.getMonth()); + for ( var row=0, rows=cal.gen.length; row < rows; row++ ) { + hRow = $('
', {'class': uid+'gridrow'}); + if ( w.__('isRTL') ) { hRow.css('direction', 'rtl'); } + if ( o.calShowWeek ) { + $('
', {'class':uid+'griddate '+uid+'griddate-empty'}).text('W'+cal.wk).appendTo(hRow); + cal.wk++; + if ( cal.wk > 52 && typeof cal.gen[parseInt(row,10)+1] !== 'undefined' ) { cal.wk = new Date(cal.theDateArr[0],cal.theDateArr[1],((w.__('calStartDay')===0)?cal.gen[parseInt(row,10)+1][1][0]:cal.gen[parseInt(row,10)+1][0][0])).getDWeek(4); } + } + for ( var col=0, cols=cal.gen[row].length; col', {'class':uid+'griddate '+uid+'griddate-empty'}).appendTo(hRow); + } else { + checked = w._cal_check(cal, cal.theDateArr[0], cal.gen[row][col][1], cal.gen[row][col][0]); + if (cal.gen[row][col][0]) { + $("
"+String(cal.gen[row][col][0])+"
") + .addClass( cal.thisMonth === cal.gen[row][col][1] ? + (uid+'griddate ui-corner-all ui-btn ui-btn-'+(o.mobVer<140?'up-':'')+checked.theme + (checked.ok?'':' '+uid+'griddate-disable')): + (uid+'griddate '+uid+'griddate-empty') + ) + .jqmData('date', ((o.calWeekMode)?cal.weekMode:cal.gen[row][col][0])) + .jqmData('theme', cal.thisMonth === cal.gen[row][col][1] ? checked.theme : '-') + .jqmData('enabled', checked.ok) + .jqmData('month', cal.gen[row][((o.calWeekMode)?o.calWeekModeDay:col)][1]) + .appendTo(hRow); + } + } + } + if ( o.calControlGroup === true ) { + hRow.find('.ui-corner-all').removeClass('ui-corner-all').eq(0).addClass('ui-corner-left').end().last().addClass('ui-corner-right').addClass('ui-controlgroup-last'); + } + hRow.appendTo(temp); + } + if ( o.calShowWeek ) { temp.find('.'+uid+'griddate').addClass(uid+'griddate-week'); } + + if ( o.calShowDateList === true && o.calDateList !== false ) { + cal.datelist = $('
'); + cal.datelistpick = $('').appendTo(cal.datelist); + + cal.datelistpick.append(''); + for ( i=0; i'+o.calDateList[i][1]+'')); + } + + cal.datelistpick.on('change', function() { + cal.datelistdate = $(this).val().split('-'); + w.theDate = new w._date(cal.datelistdate[0], cal.datelistdate[1]-1, cal.datelistdate[2], 0,0,0,0); + w.d.input.trigger('datebox',{'method':'doset'}); + }); + + cal.datelist.find('select').selectmenu({mini:true, nativeMenu:true}); + cal.datelist.appendTo(w.d.intHTML); + } + + if ( o.useTodayButton || o.useClearButton ) { + hRow = $('
', {'class':uid+'controls'}); + + if ( o.useTodayButton ) { + $(''+w.__('calTodayButtonLabel')+'') + .appendTo(hRow).buttonMarkup({theme: o.theme, icon: 'check', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEvent, function(e) { + e.preventDefault(); + w.theDate = new w._date(); + w.theDate = new w._date(w.theDate.getFullYear(), w.theDate.getMonth(), w.theDate.getDate(),0,0,0,0); + w.d.input.trigger('datebox',{'method':'doset'}); + }); + } + if ( o.useClearButton ) { + $(''+w.__('clearButton')+'') + .appendTo(hRow).buttonMarkup({theme: o.theme, icon: 'delete', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.val(''); + w.d.input.trigger('datebox',{'method':'clear'}); + w.d.input.trigger('datebox',{'method':'close'}); + }); + } + if ( o.useCollapsedBut ) { + hRow.addClass('ui-datebox-collapse'); + } + hRow.appendTo(temp); + } + + w.d.intHTML.on(o.clickEventAlt+' vmouseover vmouseout', 'div.'+uid+'griddate', function(e) { + if ( e.type === o.clickEventAlt ) { + e.preventDefault(); + if ( $(this).jqmData('enabled') ) { + w.theDate.setD(2,1).setD(1,$(this).jqmData('month')).setD(2,$(this).jqmData('date')); + w.d.input.trigger('datebox', {'method':'set', 'value':w._formatter(w.__fmt(),w.theDate), 'date':w.theDate}); + w.d.input.trigger('datebox', {'method':'close'}); + } + } else { + if ( $(this).jqmData('enabled') && typeof $(this).jqmData('theme') !== 'undefined' && o.mobVer < 140 ) { + if ( o.calWeekMode !== false && o.calWeekHigh === true ) { + $(this).parent().find('div').each(function() { w._hoover(this); }); + } else { w._hoover(this); } + } + } + }); + w.d.intHTML + .on('swipeleft', function() { if ( w.calNext ) { w._offset('m', 1); } }) + .on('swiperight', function() { if ( w.calPrev ) { w._offset('m', -1); } }); + + if ( w.wheelExists) { // Mousewheel operations, if plugin is loaded + w.d.intHTML.on('mousewheel', function(e,d) { + e.preventDefault(); + if ( d > 0 && w.calNext ) { + w.theDate.setD(2,1); + w._offset('m', 1); + } + if ( d < 0 && w.calPrev ) { + w.theDate.setD(2,1); + w._offset('m', -1); + } + }); + } + } + }); +})( jQuery ); diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.calbox.min.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.calbox.min.js new file mode 100644 index 000000000..1d81752e8 --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.calbox.min.js @@ -0,0 +1,7 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +(function(a){a.widget("mobile.datebox",a.mobile.widget,{options:{version:"2-1.4.0-2013070300",mobVer:parseInt(a.mobile.version.replace(/\./g,"")),theme:false,themeDefault:"a",themeHeader:"a",mode:false,centerHoriz:false,centerVert:false,transition:"pop",useAnimation:true,hideInput:false,hideFixedToolbars:false,lockInput:true,enhanceInput:true,zindex:"500",clickEvent:"vclick",clickEventAlt:"click",resizeListener:true,defaultValue:false,showInitialValue:false,dialogEnable:false,dialogForce:false,enablePopup:false,popupPosition:false,popupForceX:false,popupForceY:false,useModal:false,useInline:false,useInlineBlind:false,useHeader:true,useImmediate:false,useNewStyle:false,useAltIcon:false,overrideStyleClass:false,useButton:true,useFocus:false,useClearButton:false,useCollapsedBut:false,usePlaceholder:false,openCallback:false,openCallbackArgs:[],closeCallback:false,closeCallbackArgs:[],startOffsetYears:false,startOffsetMonths:false,startOffsetDays:false,afterToday:false,beforeToday:false,notToday:false,maxDays:false,minDays:false,maxYear:false,minYear:false,blackDates:false,blackDatesRec:false,blackDays:false,minHour:false,maxHour:false,minuteStep:1,minuteStepRound:0,rolloverMode:{m:true,d:true,h:true,i:true,s:true},useLang:"default",lang:{"default":{setDateButtonLabel:"Set Date",setTimeButtonLabel:"Set Time",setDurationButtonLabel:"Set Duration",calTodayButtonLabel:"Jump to Today",titleDateDialogLabel:"Set Date",titleTimeDialogLabel:"Set Time",daysOfWeek:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],daysOfWeekShort:["Su","Mo","Tu","We","Th","Fr","Sa"],monthsOfYear:["January","February","March","April","May","June","July","August","September","October","November","December"],monthsOfYearShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],durationLabel:["Days","Hours","Minutes","Seconds"],durationDays:["Day","Days"],timeFormat:24,headerFormat:"%A, %B %-d, %Y",tooltip:"Open Date Picker",nextMonth:"Next Month",prevMonth:"Previous Month",dateFieldOrder:["m","d","y"],timeFieldOrder:["h","i","a"],slideFieldOrder:["y","m","d"],dateFormat:"%Y-%m-%d",useArabicIndic:false,isRTL:false,calStartDay:0,clearButton:"Clear",durationOrder:["d","h","i","s"],meridiem:["AM","PM"],timeOutput:"%k:%M",durationFormat:"%Dd %DA, %Dl:%DM:%DS",calDateListLabel:"Other Dates",calHeaderFormat:"%B %Y"}}},_enhanceDate:function(){a.extend(this._date.prototype,{copy:function(c,b){if(typeof c==="undefined"){c=[0,0,0,0,0,0,0]}if(typeof b==="undefined"){b=[0,0,0,0,0,0,0]}while(c.length<7){c.push(0)}while(b.length<7){b.push(0)}return new Date(((b[0]>0)?b[0]:this.getFullYear()+c[0]),((b[1]>0)?b[1]:this.getMonth()+c[1]),((b[2]>0)?b[2]:this.getDate()+c[2]),((b[3]>0)?b[3]:this.getHours()+c[3]),((b[4]>0)?b[4]:this.getMinutes()+c[4]),((b[5]>0)?b[5]:this.getSeconds()+c[5]),((b[6]>0)?b[5]:this.getMilliseconds()+c[6]))},adj:function(c,b){if(typeof b!=="number"){throw new Error("Adjustment value not specified")}if(typeof c!=="number"){throw new Error("Adjustment type not specified")}switch(c){case 0:this.setFullYear(this.getFullYear()+b);break;case 1:this.setMonth(this.getMonth()+b);break;case 2:this.setDate(this.getDate()+b);break;case 3:this.setHours(this.getHours()+b);break;case 4:this.setMinutes(this.getMinutes()+b);break;case 5:this.setSeconds(this.getSeconds()+b);break;case 6:this.setMilliseconds(this.getMilliseconds()+b);break}return this},setD:function(c,b){switch(c){case 0:this.setFullYear(b);break;case 1:this.setMonth(b);break;case 2:this.setDate(b);break;case 3:this.setHours(b);break;case 4:this.setMinutes(b);break;case 5:this.setSeconds(b);break;case 6:this.setMilliseconds(b);break}return this},get:function(b){switch(b){case 0:return this.getFullYear();case 1:return this.getMonth();case 2:return this.getDate();case 3:return this.getHours();case 4:return this.getMinutes();case 5:return this.getSeconds()}return false},iso:function(){return String(this.getFullYear())+"-"+((this.getMonth()<9)?"0":"")+String(this.getMonth()+1)+"-"+((this.getDate()<10)?"0":"")+String(this.getDate())},comp:function(){return parseInt(this.iso().replace(/-/g,""),10)},getEpoch:function(){return(this.getTime()-this.getMilliseconds())/1000},getArray:function(){return[this.getFullYear(),this.getMonth(),this.getDate(),this.getHours(),this.getMinutes(),this.getSeconds()]},setFirstDay:function(b){this.setD(2,1).adj(2,(b-this.getDay()));if(this.get(2)>10){this.adj(2,7)}return this},setDWeek:function(c,b){if(c===4){return this.setD(1,0).setD(2,1).setFirstDay(4).adj(2,-3).adj(2,(b-1)*7)}return this.setD(1,0).setD(2,1).setFirstDay(c).adj(2,(b-1)*7)},getDWeek:function(c){var d,b;switch(c){case 0:d=this.copy([0,-1*this.getMonth()]).setFirstDay(0);return Math.floor((this.getTime()-(d.getTime()+((this.getTimezoneOffset()-d.getTimezoneOffset())*60000)))/604800000)+1;case 1:d=this.copy([0,-1*this.getMonth()]).setFirstDay(1);return Math.floor((this.getTime()-(d.getTime()+((this.getTimezoneOffset()-d.getTimezoneOffset())*60000)))/604800000)+1;case 4:if(this.getMonth()===11&&this.getDate()>28){return 1}d=this.copy([0,-1*this.getMonth()],true).setFirstDay(4).adj(2,-3);b=Math.floor((this.getTime()-(d.getTime()+((this.getTimezoneOffset()-d.getTimezoneOffset())*60000)))/604800000)+1;if(b<1){d=this.copy([-1,-1*this.getMonth()]).setFirstDay(4).adj(2,-3);return Math.floor((this.getTime()-d.getTime())/604800000)+1}return b;default:return 0}}})},_event:function(d,c){var b=a(this).data(parseInt(a.mobile.version.replace(/\./g,""),10)>110?"mobile-datebox":"datebox");if(!d.isPropagationStopped()){switch(c.method){case"close":b.close();break;case"open":b.open();break;case"set":a(this).val(c.value);a(this).trigger("change");break;case"doset":if(a.isFunction(b["_"+b.options.mode+"DoSet"])){b["_"+b.options.mode+"DoSet"].apply(b,[])}else{a(this).trigger("datebox",{method:"set",value:b._formatter(b.__fmt(),b.theDate),date:b.theDate})}break;case"dooffset":if(c.type){b._offset(c.type,c.amount,true)}break;case"dorefresh":b.refresh();break;case"doreset":b.hardreset();break;case"doclear":a(this).val("").trigger("change");break;case"clear":a(this).trigger("change")}}},_hoover:function(b){a(b).toggleClass("ui-btn-up-"+a(b).jqmData("theme")+" ui-btn-down-"+a(b).jqmData("theme"))},_ord:{"default":function(c){var b=c%10;if(c>9&&c<21){return"th"}if(b>3){return"th"}return["th","st","nd","rd"][b]}},__:function(d){var c=this.options,b="override"+d.charAt(0).toUpperCase()+d.slice(1);if(typeof c[b]!=="undefined"){return c[b]}if(typeof c.lang[c.useLang][d]!=="undefined"){return c.lang[c.useLang][d]}if(typeof c[c.mode+"lang"]!=="undefined"&&typeof c[c.mode+"lang"][d]!=="undefined"){return c[c.mode+"lang"][d]}return c.lang["default"][d]},__fmt:function(){var b=this,c=this.options;switch(c.mode){case"timebox":case"timeflipbox":return b.__("timeOutput");case"durationbox":case"durationflipbox":return b.__("durationFormat");default:return b.__("dateFormat")}},_zPad:function(b){return((b<10)?"0"+String(b):String(b))},_dRep:function(j,g){var h=48,b=57,c=1584,d=null,e=null,f="";if(g===-1){h+=c;b+=c;c=-1584}for(d=0;d=h&&e<=b){f=f+String.fromCharCode(e+c)}else{f=f+String.fromCharCode(e)}}return f},_doIndic:function(){var b=this;b.d.intHTML.find("*").each(function(){if(a(this).children().length<1){a(this).text(b._dRep(a(this).text()))}else{if(a(this).hasClass("ui-datebox-slideday")){a(this).html(b._dRep(a(this).html()))}}});b.d.intHTML.find("input").each(function(){a(this).val(b._dRep(a(this).val()))})},_parser:{"default":function(b){return false}},_n:function(c,b){return(c<0)?b:c},_pa:function(b,c){if(typeof c==="boolean"){return new this._date(b[0],b[1],b[2],0,0,0,0)}return new this._date(c.getFullYear(),c.getMonth(),c.getDate(),b[0],b[1],b[2],0)},_makeDate:function(k){k=a.trim(((this.__("useArabicIndic")===true)?this._dRep(k,-1):k));var n=this,c=this.options,e=n.__fmt(),m=null,h=[],l=null,b=null,f=new n._date(),j={year:-1,mont:-1,date:-1,hour:-1,mins:-1,secs:-1,week:false,wtyp:4,wday:false,yday:false,meri:0},g;if(typeof c.mode==="undefined"){return f}if(typeof n._parser[c.mode]!=="undefined"){return n._parser[c.mode].apply(n,[k])}if(c.mode==="durationbox"||c.mode==="durationflipbox"){e=e.replace(/%D([a-z])/gi,function(d,o){switch(o){case"d":case"l":case"M":case"S":return"("+d+"|[0-9]+)";default:return".+?"}});e=new RegExp("^"+e+"$");m=e.exec(k);l=e.exec(n.__fmt());if(m===null||m.length!==l.length){if(typeof c.defaultValue==="number"&&c.defaultValue>0){return new n._date((n.initDate.getEpoch()+parseInt(c.defaultValue,10))*1000)}return new n._date(n.initDate.getTime())}b=n.initDate.getEpoch();for(g=0;g-1){j.mont=b}break;case"B":b=a.inArray(m[g],n.__("monthsOfYear"));if(b>-1){j.mont=b}break}}if(j.meri!==0){if(j.meri===-1&&j.hour===12){j.hour=0}if(j.meri===1&&j.hour!==12){j.hour=j.hour+12}}f=new n._date(n._n(j.year,0),n._n(j.mont,0),n._n(j.date,1),n._n(j.hour,0),n._n(j.mins,0),n._n(j.secs,0),0);if(j.year<100&&j.year!==-1){f.setFullYear(j.year)}if((j.mont>-1&&j.date>-1)||(j.hour>-1&&j.mins>-1&&j.secs>-1)){return f}if(j.week!==false){f.setDWeek(j.wtyp,j.week);if(j.date>-1){f.setDate(j.date)}}if(j.yday!==false){f.setD(1,0).setD(2,1).adj(2,(j.yday-1))}if(j.wday!==false){f.adj(2,(j.wday-f.getDay()))}}return f},_customformat:{"default":function(c,b){return false}},_formatter:function(f,c){var b=this,g=this.options,d,e={part:[0,0,0,0],tp:0};if(g.mode==="durationbox"||g.mode==="durationflipbox"){e.tp=this.theDate.getEpoch()-this.initDate.getEpoch();e.part[0]=parseInt(e.tp/(60*60*24),10);e.tp-=(e.part[0]*60*60*24);e.part[1]=parseInt(e.tp/(60*60),10);e.tp-=(e.part[1]*60*60);e.part[2]=parseInt(e.tp/(60),10);e.tp-=(e.part[2]*60);e.part[3]=e.tp;if(!f.match(/%Dd/)){e.part[1]+=(e.part[0]*24)}if(!f.match(/%Dl/)){e.part[2]+=(e.part[1]*60)}if(!f.match(/%DM/)){e.part[3]+=(e.part[2]*60)}}f=f.replace(/%(D|X|0|-)*([1-9a-zA-Z])/g,function(h,j,k){if(j==="X"){if(typeof b._customformat[g.mode]!=="undefined"){return b._customformat[g.mode](k,c,g)}return h}if(j==="D"){switch(k){case"d":return e.part[0];case"l":return b._zPad(e.part[1]);case"M":return b._zPad(e.part[2]);case"S":return b._zPad(e.part[3]);case"A":return((e.part[0]>1)?b.__("durationDays")[1]:b.__("durationDays")[0]);default:return h}}switch(k){case"%":return"%";case"a":return b.__("daysOfWeekShort")[c.getDay()];case"A":return b.__("daysOfWeek")[c.getDay()];case"b":return b.__("monthsOfYearShort")[c.getMonth()];case"B":return b.__("monthsOfYear")[c.getMonth()];case"C":return c.getFullYear().toString().substr(0,2);case"d":return((j==="-")?c.getDate():b._zPad(c.getDate()));case"H":case"k":return((j==="-")?c.getHours():b._zPad(c.getHours()));case"I":case"l":return((j==="-")?((c.getHours()===0||c.getHours()===12)?12:((c.getHours()<12)?c.getHours():(c.getHours()-12))):b._zPad(((c.getHours()===0||c.getHours()===12)?12:((c.getHours()<12)?c.getHours():c.getHours()-12))));case"m":return((j==="-")?c.getMonth()+1:b._zPad(c.getMonth()+1));case"M":return((j==="-")?c.getMinutes():b._zPad(c.getMinutes()));case"p":return((c.getHours()<12)?b.__("meridiem")[0].toUpperCase():b.__("meridiem")[1].toUpperCase());case"P":return((c.getHours()<12)?b.__("meridiem")[0].toLowerCase():b.__("meridiem")[1].toLowerCase());case"s":return c.getEpoch();case"S":return((j==="-")?c.getSeconds():b._zPad(c.getSeconds()));case"u":return((j==="-")?c.getDay()+1:b._zPad(c.getDay()+1));case"w":return c.getDay();case"y":return c.getFullYear().toString().substr(2,2);case"Y":return c.getFullYear();case"E":return c.getFullYear()+543;case"V":return((j==="-")?c.getDWeek(4):b._zPad(c.getDWeek(4)));case"U":return((j==="-")?c.getDWeek(0):b._zPad(c.getDWeek(0)));case"W":return((j==="-")?c.getDWeek(1):b._zPad(c.getDWeek(1)));case"o":if(typeof b._ord[g.useLang]!=="undefined"){return b._ord[g.useLang](c.getDate())}return b._ord["default"](c.getDate());case"j":d=new Date(c.getFullYear(),0,1);d=Math.ceil((c-d)/86400000)+1;return((d<100)?((d<10)?"00":"0"):"")+String(d);case"G":if(c.getDWeek(4)===1&&c.getMonth()>0){return c.getFullYear()+1}if(c.getDWeek(4)>51&&c.getMonth()<11){return c.getFullYear()-1}return c.getFullYear();case"g":if(c.getDWeek(4)===1&&c.getMonth()>0){return parseInt(c.getFullYear().toString().substr(2,2),10)+1}if(c.getDWeek(4)>51&&c.getMonth()<11){return parseInt(c.getFullYear().toString().substr(2,2),10)-1}return c.getFullYear().toString().substr(2,2);default:return h}});if(b.__("useArabicIndic")===true){f=b._dRep(f)}return f},_btwn:function(d,b,c){return(d>b&&d1&&d%e.minuteStep>0){if(e.minuteStepRound<0){d=d-(d%e.minuteStep)}else{if(e.minStepRound>0){d=d+(e.minuteStep-(d%e.minuteStep))}else{if(d%e.minuteStep0)?1:-1)*12,false);break}}if(c!==false){b.theDate.adj(c,d)}if(g===true){b.refresh()}if(e.useImmediate){b.d.input.trigger("datebox",{method:"doset"})}},_startOffset:function(b){var c=this.options;if(c.startOffsetYears!==false){b.adj(0,c.startOffsetYears)}if(c.startOffsetMonths!==false){b.adj(1,c.startOffsetMonths)}if(c.startOffsetDays!==false){b.adj(2,c.startOffsetDays)}return b},_create:function(){a(document).trigger("dateboxcreate");var j=this,b=a.extend(this.options,(typeof this.element.jqmData("options")!=="undefined")?this.element.jqmData("options"):this._getLongOptions(this.element)),k=(b.theme===false&&typeof(a(this).jqmData("theme"))==="undefined")?((typeof(this.element.parentsUntil(":jqmData(theme)").parent().jqmData("theme"))==="undefined")?b.themeDefault:this.element.parentsUntil(":jqmData(theme)").parent().jqmData("theme")):b.theme,l=b.useAnimation?b.transition:"none",g=b.useNewStyle===false?{input:this.element,wrap:this.element.wrap('
').parent(),mainWrap:a("
",{"class":"ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden "+l+" ui-body-"+k}).css("zIndex",b.zindex),intHTML:false}:{input:this.element,wrap:this.element,mainWrap:a("
",{"class":"ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden "+l+" ui-body-"+k}).css("zIndex",b.zindex),intHTML:false},e=(typeof window.ontouchstart!=="undefined"),f={eStart:(e?"touchstart":"mousedown")+".datebox",eMove:(e?"touchmove":"mousemove")+".datebox",eEnd:(e?"touchend":"mouseup")+".datebox",eEndA:(e?"mouseup.datebox touchend.datebox touchcancel.datebox touchmove.datebox":"mouseup.datebox"),move:false,start:false,end:false,pos:false,target:false,delta:false,tmp:false},c={},h=(typeof a.mobile.ns!=="undefined")?a.mobile.ns:"";a.extend(j,{d:g,ns:h,drag:f,touch:e});if(b.usePlaceholder!==false){if(b.usePlaceholder===true&&j._grabLabel()!==false){j.d.input.attr("placeholder",j._grabLabel())}if(typeof b.usePlaceholder==="string"){j.d.input.attr("placeholder",b.usePlaceholder)}}b.theme=k;j.clearFunc=false;j.disabled=false;j.runButton=false;j._date=window.Date;j._enhanceDate();j.baseID=j.d.input.attr("id");j.initDate=new j._date();j.theDate=(b.defaultValue)?j._makeDate(b.defaultValue):((j.d.input.val()!=="")?j._makeDate(j.d.input.val()):new j._date());j.initDone=false;if(b.showInitialValue===true){j.d.input.val(j._formatter(j.__fmt(),j.theDate))}if(b.useButton===true&&b.useInline===false&&b.useNewStyle===false){j.d.open=a(''+this.__("tooltip")+"").on(b.clickEvent,function(d){d.preventDefault();if(!j.disabled){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.parent().addClass("ui-focus");j.d.input.parent().removeClass("ui-focus")}setTimeout(function(){a(d.target).closest("a").removeClass(a.mobile.activeBtnClass)},300)}).appendTo(j.d.wrap).buttonMarkup({icon:"grid",iconpos:"notext",corners:true,shadow:true}).css({"vertical-align":"middle",display:"inline-block"})}j.d.screen=a("
",{"class":"ui-datebox-screen ui-datebox-hidden"+((b.useModal)?" ui-datebox-screen-modal":"")}).css({"z-index":b.zindex-1}).on(b.clickEventAlt,function(d){d.preventDefault();j.d.input.trigger("datebox",{method:"close"})});if(b.enhanceInput===true&&navigator.userAgent.match(/Android/i)){j.inputType="number"}else{j.inputType="text"}if(b.hideInput){j.d.wrap.parent().hide()}if(b.mobVer<140){a("label[for='"+j.d.input.attr("id")+"']").addClass("ui-input-text").css("verticalAlign","middle")}j.d.wrap.on(b.clickEvent,function(){if(!j.disabled&&(b.noButtonFocusMode||b.focusMode)){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.addClass("ui-focus");j.d.input.removeClass("ui-focus")}});j.d.input.removeClass("ui-corner-all ui-shadow-inset").bind(j.touch?"touchend":"click",function(d){if(j.disabled===false&&b.useNewStyle===true&&b.useFocus===false){if(((j.touch?d.originalEvent.changedTouches[0].pageX:d.pageX)-d.target.offsetLeft)>(d.target.offsetWidth-20)){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.parent().addClass("ui-focus");j.d.input.removeClass("ui-focus")}}}).focus(function(){if(j.disabled===false&&b.useFocus===true){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.addClass("ui-focus");j.d.input.removeClass("ui-focus");if(b.useNewStyle===false){j.d.input.parent().removeClass("ui-focus");j.d.wrap.parent().addClass("ui-focus")}}if(b.useNewStyle===false){j.d.input.removeClass("ui-focus")}}).blur(function(){j.d.wrap.removeClass("ui-focus");j.d.input.removeClass("ui-focus")}).change(function(){j.theDate=j._makeDate(j.d.input.val());j.refresh()}).attr("readonly",b.lockInput).on("datebox",j._event);if(b.useNewStyle===true){j.d.input.addClass("ui-corner-all "+((b.useAltIcon===true)?"ui-icon-datebox-alt":"ui-icon-datebox"));if(b.overrideStyleClass!==false){j.d.input.addClass(b.overrideStyleClass)}}else{j.d.input.parent().css("border","none").removeClass("ui-shadow-inset")}j.d.wrap.parent().on(b.clickEvent,function(){if(!j.disabled&&b.useFocus===true&&b.useNewStyle===false){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.addClass("ui-focus");j.d.input.removeClass("ui-focus");setTimeout(function(){j.d.wrap.removeClass("ui-focus");j.d.wrap.parent().addClass("ui-focus")},500)}});if(typeof a.event.special.mousewheel!=="undefined"){j.wheelExists=true}if(j.d.input.is(":disabled")){j.disable()}if(b.useInline===true||b.useInlineBlind){j.open()}j.applyMinMax(false,false);a(document).trigger("dateboxaftercreate")},applyMinMax:function(e,d){var b=this,f=this.options,c={};if(typeof e==="undefined"){e=false}if(typeof d==="undefined"){d=true}if((d===true||f.minDays===false)&&typeof(b.d.input.attr("min"))!=="undefined"){c.today=new b._date();c.lod=24*60*60*1000;c.todayc=new b._date(c.today.getFullYear(),c.today.getMonth(),c.today.getDate(),0,0,0,0);c.fromel=b.d.input.attr("min").split("-");c.compdt=new b._date(c.fromel[0],c.fromel[1]-1,c.fromel[2],0,0,0,0);f.minDays=parseInt((((c.compdt.getTime()-c.todayc.getTime())/c.lod))*-1,10)}if((d===true||f.maxDays===false)&&typeof(b.d.input.attr("max"))!=="undefined"){c.today=new b._date();c.lod=24*60*60*1000;c.todayc=new b._date(c.today.getFullYear(),c.today.getMonth(),c.today.getDate(),0,0,0,0);c.fromel=b.d.input.attr("max").split("-");c.compdt=new b._date(c.fromel[0],c.fromel[1]-1,c.fromel[2],0,0,0,0);f.maxDays=parseInt((((c.compdt.getTime()-c.todayc.getTime())/c.lod)),10)}if(e===true){b.refresh()}},_build:{"default":function(){this.d.headerText="Error";this.d.intHTML=a("

There is no mode by that name loaded / mode not given

")}},_applyCoords:function(h){var b=h.widget,j=h.widget.options,f={h:a.mobile.activePage.find(".ui-header").jqmData("position"),f:a.mobile.activePage.find(".ui-footer").jqmData("position"),fh:a.mobile.activePage.find(".ui-footer").outerHeight(),hh:a.mobile.activePage.find(".ui-header").outerHeight()},c={x:b.d.wrap.offset().left+(b.d.wrap.outerWidth()/2),y:b.d.wrap.offset().top+(b.d.wrap.outerHeight()/2)},d={w:b.d.mainWrap.outerWidth(),h:b.d.mainWrap.outerHeight()},g={t:a(window).scrollTop(),h:a(window).height(),w:a.mobile.activePage.width(),ah:a(document).height()},k={y:(j.centerVert)?g.t+((g.h/2)-(d.h/2)):c.y-(d.h/2),x:(g.w<400||j.centerHoriz)?(g.w/2)-(d.w/2):c.x-(d.w/2)};if(j.centerVert===false){if(j.hideFixedToolbars===true&&(typeof f.f!=="undefined"||typeof f.h!=="undefined")){a.mobile.activePage.find(":jqmData(position='fixed')").fixedtoolbar("hide");f.f=undefined;f.h=undefined}if(typeof f.f!=="undefined"){if((k.y+d.h)>(g.h-f.fh-2)){k.y=g.h-f.fh-2-d.h}}else{if((k.y+d.h)>(g.ah-f.fh-2)){k.y=g.ah-f.fh-2-d.h}if((g.h+g.t)<(d.h+k.y+2)){k.y=g.h+g.t-d.h-2}}if(typeof f.h!=="undefined"){if((g.t+f.hh+2)>k.y){k.y=g.t+f.hh+2}}else{if(f.hh+2>k.y){k.y=f.hh+2}if(k.y
');a("Close").appendTo(b.d.headHTML).buttonMarkup({theme:g.themeHeader,icon:"delete",iconpos:"notext",corners:true,shadow:true}).on(g.clickEventAlt,function(h){h.preventDefault();b.d.input.trigger("datebox",{method:"close"})});a('

'+b.d.headerText+"

").appendTo(b.d.headHTML);b.d.mainWrap.append(b.d.headHTML)}b.d.mainWrap.append(b.d.intHTML).css("zIndex",g.zindex);b.d.input.trigger("datebox",{method:"postrefresh"});if(g.useAnimation===true){e.transition=g.transition}else{e.transition="none"}if(g.popupForceX!==false&&g.popupForceY!==false){e.x=g.popupForceX;e.y=g.popupForceY}if(g.popupPosition!==false){e.positionTo=g.popupPosition}else{if(typeof b.baseID!==undefined){e.positionTo="#"+b.baseID}else{e.positionTo="window"}}if(g.useModal===true){f.overlayTheme="a"}b.d.mainWrap.removeClass("ui-datebox-hidden").popup(f).popup("open",e);b.refresh()}else{if(g.dialogForce||(g.dialogEnable&&window.width()<400)){b.d.dialogPage=a("

"+b.d.headerText+"

").appendTo(a.mobile.pageContainer).page().css("minHeight","0px").addClass(c);b.d.dialogPage.find(".ui-header").find("a").off("click vclick").on(g.clickEventAlt,function(h){h.preventDefault();b.d.input.trigger("datebox",{method:"close"})});b.d.mainWrap.append(b.d.intHTML).css({marginLeft:"auto",marginRight:"auto"}).removeClass("ui-datebox-hidden");b.d.dialogPage.find(".ui-content").append(b.d.mainWrap);b.d.input.trigger("datebox",{method:"postrefresh"});a.mobile.activePage.off("pagehide.remove");a.mobile.changePage(b.d.dialogPage,{transition:c})}else{b.d.dialogPage=false;b.d.mainWrap.empty();if(g.useHeader===true){b.d.headHTML=a('
');a("Close").appendTo(b.d.headHTML).buttonMarkup({theme:g.themeHeader,icon:"delete",iconpos:"notext",corners:true,shadow:true}).on(g.clickEventAlt,function(h){h.preventDefault();b.d.input.trigger("datebox",{method:"close"})});a('

'+b.d.headerText+"

").appendTo(b.d.headHTML);b.d.mainWrap.append(b.d.headHTML)}b.d.mainWrap.append(b.d.intHTML).css("zIndex",g.zindex);b.d.mainWrap.appendTo(a.mobile.activePage);b.d.screen.appendTo(a.mobile.activePage);b.d.input.trigger("datebox",{method:"postrefresh"});b._applyCoords({widget:b});if(g.useModal===true){if(g.useAnimation){b.d.screen.fadeIn("slow")}else{b.d.screen.show()}}else{setTimeout(function(){b.d.screen.removeClass("ui-datebox-hidden")},500)}b.d.mainWrap.addClass("ui-overlay-shadow in").removeClass("ui-datebox-hidden");a(document).on("orientationchange.datebox",{widget:b},function(h){b._applyCoords(h.data)});if(g.resizeListener===true){a(window).on("resize.datebox",{widget:b},function(h){b._applyCoords(h.data)})}}}},close:function(){var b=this,c=this.options;if(c.useInlineBlind===true){b.d.mainWrap.slideUp();return true}if(c.useInline===true||b.d.intHTML===false){return true}if(b.d.dialogPage!==false){a(b.d.dialogPage).dialog("close");if(!a.mobile.activePage.jqmData("mobile-page").options.domCache){a.mobile.activePage.on("pagehide.remove",function(){a(this).remove()})}b.d.intHTML.detach().empty();b.d.mainWrap.detach().empty();b.d.wrap.removeClass("ui-focus");b.clearFunc=setTimeout(function(){b.d.dialogPage.empty().remove();b.clearFunc=false},1500)}else{if(c.enablePopup===true){b.d.mainWrap.popup("close");b.d.wrap.removeClass("ui-focus")}else{if(c.useModal){if(c.useAnimation){b.d.screen.fadeOut("slow")}else{b.d.screen.hide()}}else{b.d.screen.addClass("ui-datebox-hidden")}b.d.screen.detach();b.d.mainWrap.addClass("ui-datebox-hidden").removeAttr("style").removeClass("in ui-overlay-shadow").empty().detach();b.d.intHTML.detach();b.d.wrap.removeClass("ui-focus");a(document).off("orientationchange.datebox");if(c.resizeListener===true){a(window).off("resize.datebox")}}}b.d.wrap.parent().removeClass("ui-focus");a(document).off(b.drag.eMove);a(document).off(b.drag.eEnd);a(document).off(b.drag.eEndA);if(c.useFocus){b.fastReopen=true;setTimeout(function(d){return function(){d.fastReopen=false}}(b),300)}if(c.closeCallback!==false){if(!a.isFunction(c.closeCallback)){if(typeof window[c.closeCallback]!=="undefined"){c.closeCallback=window[c.closeCallback]}else{c.closeCallback=new Function(c.closeCallback)}}c.closeCallback.apply(b,a.merge([b.theDate],c.closeCallbackArgs))}},refresh:function(){if(typeof this._build[this.options.mode]==="undefined"){this._build["default"].apply(this,[])}else{this._build[this.options.mode].apply(this,[])}if(this.__("useArabicIndic")===true){this._doIndic()}this.d.mainWrap.append(this.d.intHTML);this.d.input.trigger("datebox",{method:"postrefresh"})},_check:function(){var b=this,d=null,c=this.options;b.dateOK=true;if(c.afterToday!==false){d=new b._date();if(b.theDated){b.theDate=d}}if(c.maxDays!==false){d=new b._date();d.adj(2,c.maxDays);if(b.theDate>d){b.theDate=d}}if(c.minDays!==false){d=new b._date();d.adj(2,-1*c.minDays);if(b.theDatec.maxHour){b.theDate.setHours(c.maxHour)}}if(c.maxYear!==false){d=new b._date(c.maxYear,0,1);d.adj(2,-1);if(b.theDate>d){b.theDate=d}}if(c.minYear!==false){d=new b._date(c.minYear,0,1);if(b.theDate-1){if(c.mode==="timeflipbox"&&c.validHours!==false){if(a.inArray(b.theDate.getHours(),c.validHours)<0){b.dateOK=false}}}else{if(c.blackDatesRec!==false){for(i=0;i-1){b.dateOK=false}}if(c.blackDays!==false){if(a.inArray(b.theDate.getDay(),c.blackDays)>-1){b.dateOK=false}}}},_grabLabel:function(){var b=this,c=this.options;if(typeof c.overrideDialogLabel==="undefined"){if(typeof b.d.input.attr("placeholder")!=="undefined"){return b.d.input.attr("placeholder")}if(typeof b.d.input.attr("title")!=="undefined"){return b.d.input.attr("title")}if(b.d.wrap.parent().find("label[for='"+b.d.input.attr("id")+"']").text()!==""){return b.d.wrap.parent().find("label[for='"+b.d.input.attr("id")+"']").text()}return false}return c.overrideDialogLabel},_makeEl:function(d,e){var b=false,c=false;c=d.clone();if(typeof e.attr!=="undefined"){for(b in e.attr){if(e.attr.hasOwnProperty(b)){c.jqmData(b,e.attr[b])}}}return c},_getLongOptions:function(d){var c,e={},f,b;if(a.mobile.ns===""){f="datebox"}else{f=a.mobile.ns.substr(0,a.mobile.ns.length-1)+"Datebox"}for(c in d.data()){if(c.substr(0,f.length)===f&&c.length>f.length){b=c.substr(f.length);b=b.charAt(0).toLowerCase()+b.slice(1);e[b]=d.data(c)}}return e},disable:function(){this.d.input.attr("disabled",true);this.d.wrap.addClass("ui-disabled").blur();this.disabled=true;this.d.input.trigger("datebox",{method:"disable"})},enable:function(){this.d.input.attr("disabled",false);this.d.wrap.removeClass("ui-disabled");this.disabled=false;this.d.input.trigger("datebox",{method:"enable"})},_setOption:function(){a.Widget.prototype._setOption.apply(this,arguments);this.refresh()},getTheDate:function(){return this.theDate},getLastDur:function(){return this.lastDuration},setTheDate:function(b){this.theDate=b;this.refresh()},callFormat:function(c,b){return this._formatter(c,b)}});a(document).on("pagebeforecreate",function(b){a(":jqmData(role='datebox')",b.target).each(function(){a(this).prop("type","text")})});a(document).on("pagecreate create",function(b){a(document).trigger("dateboxbeforecreate");a(":jqmData(role='datebox')",b.target).each(function(){var c=typeof(a(this).data(parseInt(a.mobile.version.replace(/\./g,""),10)>111?"mobile-datebox":"datebox"));if(c==="undefined"){a(this).datebox()}})})})(jQuery);(function(a){a.extend(a.mobile.datebox.prototype.options,{themeDateToday:"b",themeDayHigh:"b",themeDatePick:"b",themeDateHigh:"b",themeDateHighAlt:"b",themeDateHighRec:"b",themeDate:"a",calHighToday:true,calHighPick:true,calShowDays:true,calOnlyMonth:false,calWeekMode:false,calWeekModeDay:1,calWeekHigh:false,calControlGroup:false,calShowWeek:false,calUsePickers:false,calNoHeader:false,useTodayButton:false,useCollapsedBut:false,highDays:false,highDates:false,highDatesRec:false,highDatesAlt:false,enableDates:false,calDateList:false,calShowDateList:false,});a.extend(a.mobile.datebox.prototype,{_cal_gen:function(d,f,l,i,h){var b=0,e=0,k=1,g=1,c=[],m=[],j=false;for(b=0;b<=5;b++){if(j===false){m=[];for(e=0;e<=6;e++){if(b===0&&e3&&k>l){if(i===true){m.push([g,h+1]);g++}else{m.push(false)}j=true}else{m.push([k,h]);k++;if(k>l){j=true}}}}c.push(m)}}return c},_cal_check:function(b,h,f,d){var k=this,e,c=this.options,g={},j=new this._date(h,f,d,0,0,0,0).getDay();g.ok=true;g.iso=h+"-"+k._zPad(f+1)+"-"+k._zPad(d);g.comp=parseInt(g.iso.replace(/-/g,""),10);g.theme=c.themeDate;g.recok=true;g.rectheme=false;if(c.blackDatesRec!==false){for(e=0;eg.comp)||(c.beforeToday===true&&b.thisDate.comp()g.comp)||(a.isArray(c.blackDays)&&a.inArray(j,c.blackDays)>-1)||(a.isArray(c.blackDates)&&a.inArray(g.iso,c.blackDates)>-1)){g.ok=false}}}if(g.ok){if(c.highDatesRec!==false){for(e=0;e-1)){g.theme=c.themeDateHighAlt}else{if(a.isArray(c.highDates)&&(a.inArray(g.iso,c.highDates)>-1)){g.theme=c.themeDateHigh}else{if(a.isArray(c.highDays)&&(a.inArray(j,c.highDays)>-1)){g.theme=c.themeDayHigh}else{if(a.isArray(c.highDatesRec)&&g.rectheme===true){g.theme=c.themeDateHighRec}}}}}}}return g}});a.extend(a.mobile.datebox.prototype._build,{calbox:function(){var j=this,c=this.options,e,b=false,f="ui-datebox-",l=false,n=false,d=false,k=false,h=false;if(typeof j.d.intHTML!=="boolean"){j.d.intHTML.remove()}j.d.headerText=((j._grabLabel()!==false)?j._grabLabel():j.__("titleDateDialogLabel"));j.d.intHTML=a("");a('

'+j._formatter(j.__("calHeaderFormat"),j.theDate)+"

").appendTo(j.d.intHTML);a("").prependTo(j.d.intHTML.find("."+f+"gridheader")).buttonMarkup({theme:c.themeDate,icon:"arrow-r",inline:true,iconpos:"notext",corners:true,shadow:true}).on(c.clickEventAlt,function(i){i.preventDefault();if(j.calNext){if(j.theDate.getDate()>28){j.theDate.setDate(1)}j._offset("m",1)}});a("").prependTo(j.d.intHTML.find("."+f+"gridheader")).buttonMarkup({theme:c.themeDate,icon:"arrow-l",inline:true,iconpos:"notext",corners:true,shadow:true}).on(c.clickEventAlt,function(i){i.preventDefault();if(j.calPrev){if(j.theDate.getDate()>28){j.theDate.setDate(1)}j._offset("m",-1)}});if(c.calNoHeader===true){j.d.intHTML.find("."+f+"gridheader").remove()}b={today:-1,highlightDay:-1,presetDay:-1,startDay:j.__("calStartDay"),thisDate:new j._date(),maxDate:j.initDate.copy(),minDate:j.initDate.copy(),currentMonth:false,weekMode:0,weekDays:null};b.start=(j.theDate.copy([0],[0,0,1]).getDay()-j.__("calStartDay")+7)%7;b.thisMonth=j.theDate.getMonth();b.thisYear=j.theDate.getFullYear();b.wk=j.theDate.copy([0],[0,0,1]).adj(2,(-1*b.start)+(j.__("calStartDay")===0?1:0)).getDWeek(4);b.end=32-j.theDate.copy([0],[0,0,32,13]).getDate();b.lastend=32-j.theDate.copy([0,-1],[0,0,32,13]).getDate();b.presetDate=(j.d.input.val()==="")?j._startOffset(j._makeDate(j.d.input.val())):j._makeDate(j.d.input.val());b.thisDateArr=b.thisDate.getArray();b.theDateArr=j.theDate.getArray();b.checkDates=(a.inArray(false,[c.afterToday,c.beforeToday,c.notToday,c.maxDays,c.minDays,c.blackDates,c.blackDays])>-1);j.calNext=true;j.calPrev=true;if(b.thisDateArr[0]===b.theDateArr[0]&&b.thisDateArr[1]===b.theDateArr[1]){b.currentMonth=true}if(b.presetDate.comp()===j.theDate.comp()){b.presetDay=b.presetDate.getDate()}if(c.afterToday===true&&(b.currentMonth===true||(b.thisDateArr[1]>=b.theDateArr[1]&&b.theDateArr[0]===b.thisDateArr[0]))){j.calPrev=false}if(c.beforeToday===true&&(b.currentMonth===true||(b.thisDateArr[1]<=b.theDateArr[1]&&b.theDateArr[0]===b.thisDateArr[0]))){j.calNext=false}if(c.minDays!==false){b.minDate.adj(2,-1*c.minDays);if(b.theDateArr[0]===b.minDate.getFullYear()&&b.theDateArr[1]<=b.minDate.getMonth()){j.calPrev=false}}if(c.maxDays!==false){b.maxDate.adj(2,c.maxDays);if(b.theDateArr[0]===b.maxDate.getFullYear()&&b.theDateArr[1]>=b.maxDate.getMonth()){j.calNext=false}}if(c.calUsePickers===true){b.picker=a("
",{"class":"ui-grid-a ui-datebox-grid",style:"padding-top: 5px; padding-bottom: 5px;"});b.picker1=a('
').appendTo(b.picker).find("select");b.picker2=a('
').appendTo(b.picker).find("select");for(e=0;e<=11;e++){b.picker1.append(a('"))}for(e=(b.thisYear-6);e<=b.thisYear+6;e++){b.picker2.append(a('"))}b.picker1.on("change",function(){j.theDate.setMonth(a(this).val());j.refresh()});b.picker2.on("change",function(){j.theDate.setFullYear(a(this).val());j.refresh()});b.picker.find("select").selectmenu({mini:true,nativeMenu:true});b.picker.appendTo(j.d.intHTML)}l=a('
').appendTo(j.d.intHTML);if(c.calShowDays){j._cal_days=j.__("daysOfWeekShort").concat(j.__("daysOfWeekShort"));b.weekDays=a("
",{"class":f+"gridrow"}).appendTo(l);if(j.__("isRTL")===true){b.weekDays.css("direction","rtl")}if(c.calShowWeek){a("
").addClass(f+"griddate "+f+"griddate-empty "+f+"griddate-label").appendTo(b.weekDays)}for(e=0;e<=6;e++){a("
"+j._cal_days[(e+b.startDay)%7]+"
").addClass(f+"griddate "+f+"griddate-empty "+f+"griddate-label").appendTo(b.weekDays)}}b.gen=j._cal_gen(b.start,b.lastend,b.end,!c.calOnlyMonth,j.theDate.getMonth());for(var n=0,m=b.gen.length;n",{"class":f+"gridrow"});if(j.__("isRTL")){k.css("direction","rtl")}if(c.calShowWeek){a("
",{"class":f+"griddate "+f+"griddate-empty"}).text("W"+b.wk).appendTo(k);b.wk++;if(b.wk>52&&typeof b.gen[parseInt(n,10)+1]!=="undefined"){b.wk=new Date(b.theDateArr[0],b.theDateArr[1],((j.__("calStartDay")===0)?b.gen[parseInt(n,10)+1][1][0]:b.gen[parseInt(n,10)+1][0][0])).getDWeek(4)}}for(var d=0,g=b.gen[n].length;d",{"class":f+"griddate "+f+"griddate-empty"}).appendTo(k)}else{h=j._cal_check(b,b.theDateArr[0],b.gen[n][d][1],b.gen[n][d][0]);if(b.gen[n][d][0]){a("
"+String(b.gen[n][d][0])+"
").addClass(b.thisMonth===b.gen[n][d][1]?(f+"griddate ui-corner-all ui-btn ui-btn-"+(c.mobVer<140?"up-":"")+h.theme+(h.ok?"":" "+f+"griddate-disable")):(f+"griddate "+f+"griddate-empty")).jqmData("date",((c.calWeekMode)?b.weekMode:b.gen[n][d][0])).jqmData("theme",b.thisMonth===b.gen[n][d][1]?h.theme:"-").jqmData("enabled",h.ok).jqmData("month",b.gen[n][((c.calWeekMode)?c.calWeekModeDay:d)][1]).appendTo(k)}}}if(c.calControlGroup===true){k.find(".ui-corner-all").removeClass("ui-corner-all").eq(0).addClass("ui-corner-left").end().last().addClass("ui-corner-right").addClass("ui-controlgroup-last")}k.appendTo(l)}if(c.calShowWeek){l.find("."+f+"griddate").addClass(f+"griddate-week")}if(c.calShowDateList===true&&c.calDateList!==false){b.datelist=a("
");b.datelistpick=a('').appendTo(b.datelist);b.datelistpick.append('");for(e=0;e'+c.calDateList[e][1]+""))}b.datelistpick.on("change",function(){b.datelistdate=a(this).val().split("-");j.theDate=new j._date(b.datelistdate[0],b.datelistdate[1]-1,b.datelistdate[2],0,0,0,0);j.d.input.trigger("datebox",{method:"doset"})});b.datelist.find("select").selectmenu({mini:true,nativeMenu:true});b.datelist.appendTo(j.d.intHTML)}if(c.useTodayButton||c.useClearButton){k=a("
",{"class":f+"controls"});if(c.useTodayButton){a(''+j.__("calTodayButtonLabel")+"").appendTo(k).buttonMarkup({theme:c.theme,icon:"check",iconpos:"left",corners:true,shadow:true}).on(c.clickEvent,function(i){i.preventDefault();j.theDate=new j._date();j.theDate=new j._date(j.theDate.getFullYear(),j.theDate.getMonth(),j.theDate.getDate(),0,0,0,0);j.d.input.trigger("datebox",{method:"doset"})})}if(c.useClearButton){a(''+j.__("clearButton")+"").appendTo(k).buttonMarkup({theme:c.theme,icon:"delete",iconpos:"left",corners:true,shadow:true}).on(c.clickEventAlt,function(i){i.preventDefault();j.d.input.val("");j.d.input.trigger("datebox",{method:"clear"});j.d.input.trigger("datebox",{method:"close"})})}if(c.useCollapsedBut){k.addClass("ui-datebox-collapse")}k.appendTo(l)}j.d.intHTML.on(c.clickEventAlt+" vmouseover vmouseout","div."+f+"griddate",function(i){if(i.type===c.clickEventAlt){i.preventDefault();if(a(this).jqmData("enabled")){j.theDate.setD(2,1).setD(1,a(this).jqmData("month")).setD(2,a(this).jqmData("date"));j.d.input.trigger("datebox",{method:"set",value:j._formatter(j.__fmt(),j.theDate),date:j.theDate});j.d.input.trigger("datebox",{method:"close"})}}else{if(a(this).jqmData("enabled")&&typeof a(this).jqmData("theme")!=="undefined"&&c.mobVer<140){if(c.calWeekMode!==false&&c.calWeekHigh===true){a(this).parent().find("div").each(function(){j._hoover(this)})}else{j._hoover(this)}}}});j.d.intHTML.on("swipeleft",function(){if(j.calNext){j._offset("m",1)}}).on("swiperight",function(){if(j.calPrev){j._offset("m",-1)}});if(j.wheelExists){j.d.intHTML.on("mousewheel",function(i,o){i.preventDefault();if(o>0&&j.calNext){j.theDate.setD(2,1);j._offset("m",1)}if(o<0&&j.calPrev){j.theDate.setD(2,1);j._offset("m",-1)}})}}})})(jQuery); \ No newline at end of file diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.custombox.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.custombox.js new file mode 100644 index 000000000..929bc8670 --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.custombox.js @@ -0,0 +1,1522 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +/* CORE Functions */ + +(function($) { + $.widget( "mobile.datebox", $.mobile.widget, { + options: { + // All widget options, including some internal runtime details + version: '2-1.4.0-2013070300', // jQMMajor.jQMMinor.DBoxMinor-YrMoDaySerial + mobVer: parseInt($.mobile.version.replace(/\./g,'')), + theme: false, + themeDefault: 'a', + themeHeader: 'a', + mode: false, + + centerHoriz: false, + centerVert: false, + transition: 'pop', + useAnimation: true, + hideInput: false, + hideFixedToolbars: false, + + lockInput: true, + enhanceInput: true, + + zindex: '500', + clickEvent: 'vclick', + clickEventAlt: 'click', + resizeListener: true, + + defaultValue: false, + showInitialValue: false, + + dialogEnable: false, + dialogForce: false, + enablePopup: false, + + popupPosition: false, + popupForceX: false, + popupForceY: false, + + useModal: false, + useInline: false, + useInlineBlind: false, + useHeader: true, + useImmediate: false, + useNewStyle: false, + useAltIcon: false, + overrideStyleClass: false, + + useButton: true, + useFocus: false, + useClearButton: false, + useCollapsedBut: false, + usePlaceholder: false, + + openCallback: false, + openCallbackArgs: [], + closeCallback: false, + closeCallbackArgs: [], + + startOffsetYears: false, + startOffsetMonths: false, + startOffsetDays: false, + afterToday: false, + beforeToday: false, + notToday: false, + maxDays: false, + minDays: false, + maxYear: false, + minYear: false, + blackDates: false, + blackDatesRec: false, + blackDays: false, + minHour: false, + maxHour: false, + minuteStep: 1, + minuteStepRound: 0, + + rolloverMode: { 'm': true, 'd': true, 'h': true, 'i': true, 's': true }, + + useLang: 'default', + lang: { + 'default' : { + setDateButtonLabel: 'Set Date', + setTimeButtonLabel: 'Set Time', + setDurationButtonLabel: 'Set Duration', + calTodayButtonLabel: 'Jump to Today', + titleDateDialogLabel: 'Set Date', + titleTimeDialogLabel: 'Set Time', + daysOfWeek: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], + daysOfWeekShort: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], + monthsOfYear: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], + monthsOfYearShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + durationLabel: ['Days', 'Hours', 'Minutes', 'Seconds'], + durationDays: ['Day', 'Days'], + timeFormat: 24, + headerFormat: '%A, %B %-d, %Y', + tooltip: 'Open Date Picker', + nextMonth: 'Next Month', + prevMonth: 'Previous Month', + dateFieldOrder: ['m', 'd', 'y'], + timeFieldOrder: ['h', 'i', 'a'], + slideFieldOrder: ['y', 'm', 'd'], + dateFormat: '%Y-%m-%d', + useArabicIndic: false, + isRTL: false, + calStartDay: 0, + clearButton: 'Clear', + durationOrder: ['d', 'h', 'i', 's'], + meridiem: ['AM', 'PM'], + timeOutput: '%k:%M', //{ '12': '%l:%M %p', '24': '%k:%M' }, + durationFormat: '%Dd %DA, %Dl:%DM:%DS', + calDateListLabel: 'Other Dates', + calHeaderFormat: '%B %Y' + } + } + }, + _enhanceDate: function() { + $.extend(this._date.prototype, { + copy: function(adjust, override) { + /* Get a modified copy of the date. + * First array - Offset the new date by # (position determines date part) + * Second array - If non-zero, force the new date by # (position determines date part) + */ + if ( typeof adjust === 'undefined' ) { adjust = [0,0,0,0,0,0,0]; } + if ( typeof override === 'undefined' ) { override = [0,0,0,0,0,0,0]; } + while ( adjust.length < 7 ) { adjust.push(0); } + while ( override.length < 7 ) { override.push(0); } + return new Date( + ((override[0] > 0 ) ? override[0] : this.getFullYear() + adjust[0]), + ((override[1] > 0 ) ? override[1] : this.getMonth() + adjust[1]), + ((override[2] > 0 ) ? override[2] : this.getDate() + adjust[2]), + ((override[3] > 0 ) ? override[3] : this.getHours() + adjust[3]), + ((override[4] > 0 ) ? override[4] : this.getMinutes() + adjust[4]), + ((override[5] > 0 ) ? override[5] : this.getSeconds() + adjust[5]), + ((override[6] > 0 ) ? override[5] : this.getMilliseconds() + adjust[6])); + }, + adj: function (type, amount) { + /* Adjust the date. Yes, this is chainable */ + if ( typeof amount !== 'number' ) { + throw new Error("Adjustment value not specified"); + } + if ( typeof type !== 'number' ) { + throw new Error("Adjustment type not specified"); + } + switch ( type ) { + case 0: this.setFullYear(this.getFullYear() + amount); break; + case 1: this.setMonth(this.getMonth() + amount); break; + case 2: this.setDate(this.getDate() + amount); break; + case 3: this.setHours(this.getHours() + amount); break; + case 4: this.setMinutes(this.getMinutes() + amount); break; + case 5: this.setSeconds(this.getSeconds() + amount); break; + case 6: this.setMilliseconds(this.getMilliseconds() + amount); break; + } + return this; + }, + setD: function(type, amount) { + /* A chainable version of setWhatever() */ + switch ( type ) { + case 0: this.setFullYear(amount); break; + case 1: this.setMonth(amount); break; + case 2: this.setDate(amount); break; + case 3: this.setHours(amount); break; + case 4: this.setMinutes(amount); break; + case 5: this.setSeconds(amount); break; + case 6: this.setMilliseconds(amount); break; + } + return this; + }, + get: function(type) { + switch ( type ) { + case 0: return this.getFullYear(); + case 1: return this.getMonth(); + case 2: return this.getDate(); + case 3: return this.getHours(); + case 4: return this.getMinutes(); + case 5: return this.getSeconds(); + } + return false; + }, + iso: function() { + return String(this.getFullYear()) + '-' + (( this.getMonth() < 9 ) ? "0" : "") + String(this.getMonth()+1) + '-' + ((this.getDate() < 10 ) ? "0" : "") + String(this.getDate()); + }, + comp: function () { + return parseInt(this.iso().replace(/-/g,''),10); + }, + getEpoch: function() { + return (this.getTime() - this.getMilliseconds()) / 1000; + }, + getArray: function() { + return [this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds()]; + }, + setFirstDay: function (day) { + this.setD(2,1).adj(2, (day - this.getDay())); + if ( this.get(2) > 10 ) { this.adj(2,7); } + return this; + }, + setDWeek: function (type,num) { + if ( type === 4 ) { + return this.setD(1,0).setD(2,1).setFirstDay(4).adj(2,-3).adj(2,(num-1)*7); + } + return this.setD(1,0).setD(2,1).setFirstDay(type).adj(2,(num-1)*7); + }, + getDWeek: function (type) { + var t1, t2; + + switch ( type ) { + case 0: + t1 = this.copy([0,-1*this.getMonth()]).setFirstDay(0); + return Math.floor((this.getTime() - ( t1.getTime() + (( this.getTimezoneOffset() - t1.getTimezoneOffset()) * 60000))) / 6048e5) + 1; + //return Math.floor((this.getTime() - t1.getTime()) / 6048e5) + 1; + case 1: + t1 = this.copy([0,-1*this.getMonth()]).setFirstDay(1); + return Math.floor((this.getTime() - ( t1.getTime() + (( this.getTimezoneOffset() - t1.getTimezoneOffset()) * 60000))) / 6048e5) + 1; + //return Math.floor((this.getTime() - t1.getTime()) / 6048e5) + 1; + case 4: + // this line is some bullshit. but it does work. + // (trap for dec 29, 30, or 31st being in the new year's week - these are the + // only 3 that can possibly fall like this) + if ( this.getMonth() === 11 && this.getDate() > 28 ) { return 1; } + + t1 = this.copy([0,-1*this.getMonth()],true).setFirstDay(4).adj(2,-3); + t2 = Math.floor((this.getTime() - ( t1.getTime() + (( this.getTimezoneOffset() - t1.getTimezoneOffset()) * 60000))) / 6048e5) + 1; + + if ( t2 < 1 ) { + t1 = this.copy([-1,-1*this.getMonth()]).setFirstDay(4).adj(2,-3); + return Math.floor((this.getTime() - t1.getTime()) / 6048e5) + 1; + } + return t2; + default: + return 0; + } + } + }); + }, + _event: function(e, p) { + var w = $(this).data(parseInt($.mobile.version.replace(/\./g,''),10) > 110 ? 'mobile-datebox' : 'datebox'); + if ( ! e.isPropagationStopped() ) { + switch (p.method) { + case 'close': + w.close(); break; + case 'open': + w.open(); break; + case 'set': + $(this).val(p.value); + $(this).trigger('change'); + break; + case 'doset': + if ( $.isFunction(w['_'+w.options.mode+'DoSet']) ) { + w['_'+w.options.mode+'DoSet'].apply(w,[]); + } else { + $(this).trigger('datebox', {'method':'set', 'value':w._formatter(w.__fmt(), w.theDate), 'date':w.theDate}); + } + break; + case 'dooffset': + if (p.type) { w._offset(p.type, p.amount, true); } break; + case 'dorefresh': + w.refresh(); break; + case 'doreset': + w.hardreset(); break; + case 'doclear': + $(this).val('').trigger('change'); break; + case 'clear': + $(this).trigger('change'); + } + } + }, + _hoover: function(item) { + // Hover toggle class, for calendar + $(item).toggleClass('ui-btn-up-'+$(item).jqmData('theme')+' ui-btn-down-'+$(item).jqmData('theme')); + }, + _ord: { + 'default': function (num) { + // Return an ordinal suffix (1st, 2nd, 3rd, etc) + var ending = num % 10; + if ( num > 9 && num < 21 ) { return 'th'; } + if ( ending > 3 ) { return 'th'; } + return ['th','st','nd','rd'][ending]; + } + }, + __ : function(val) { + var o = this.options, + oride = 'override' + val.charAt(0).toUpperCase() + val.slice(1); + + if ( typeof o[oride] !== 'undefined' ) { return o[oride]; } + if ( typeof o.lang[o.useLang][val] !== 'undefined' ) { return o.lang[o.useLang][val]; } + if ( typeof o[o.mode+'lang'] !== 'undefined' && typeof o[o.mode+'lang'][val] !== 'undefined' ) { return o[o.mode+'lang'][val]; } + return o.lang['default'][val]; + }, + __fmt: function() { + var w = this, + o = this.options; + + switch ( o.mode ) { + case 'timebox': + case 'timeflipbox': + return w.__('timeOutput'); + case 'durationbox': + case 'durationflipbox': + return w.__('durationFormat'); + default: + return w.__('dateFormat'); + } + }, + _zPad: function(number) { + return (( number < 10 ) ? '0' + String(number) : String(number)); + }, + _dRep: function(oper, direction) { + var start = 48, + end = 57, + adder = 1584, + i = null, + ch = null, + newd = ''; + + if ( direction === -1 ) { + start += adder; + end += adder; + adder = -1584; + } + + for ( i=0; i= start && ch <= end ) { + newd = newd + String.fromCharCode(ch+adder); + } else { + newd = newd + String.fromCharCode(ch); + } + } + + return newd; + }, + _doIndic: function() { + var w = this; + + w.d.intHTML.find('*').each(function() { + if ( $(this).children().length < 1 ) { + $(this).text(w._dRep($(this).text())); + } else if ( $(this).hasClass('ui-datebox-slideday') ) { + $(this).html(w._dRep($(this).html())); + } + }); + w.d.intHTML.find('input').each(function() { + $(this).val(w._dRep($(this).val())); + }); + }, + _parser: { + 'default': function (str) { return false; } + }, + _n: function (val,def) { + return ( val < 0 ) ? def : val; + }, + _pa: function (arr,date) { + if ( typeof date === 'boolean' ) { return new this._date(arr[0],arr[1],arr[2],0,0,0,0); } + return new this._date(date.getFullYear(), date.getMonth(), date.getDate(), arr[0], arr[1], arr[2], 0); + }, + _makeDate: function (str) { + // Date Parser + str = $.trim(((this.__('useArabicIndic') === true)?this._dRep(str, -1):str)); + var w = this, + o = this.options, + adv = w.__fmt(), + exp_input = null, + exp_names = [], + exp_format = null, + exp_temp = null, + date = new w._date(), + d = { year: -1, mont: -1, date: -1, hour: -1, mins: -1, secs: -1, week: false, wtyp: 4, wday: false, yday: false, meri: 0 }, + i; + + if ( typeof o.mode === 'undefined' ) { return date; } + if ( typeof w._parser[o.mode] !== 'undefined' ) { return w._parser[o.mode].apply(w,[str]); } + + if ( o.mode === 'durationbox' || o.mode === 'durationflipbox' ) { + adv = adv.replace(/%D([a-z])/gi, function(match, oper) { + switch (oper) { + case 'd': + case 'l': + case 'M': + case 'S': return '(' + match + '|' +'[0-9]+' + ')'; + default: return '.+?'; + } + }); + + adv = new RegExp('^' + adv + '$'); + exp_input = adv.exec(str); + exp_format = adv.exec(w.__fmt()); + + if ( exp_input === null || exp_input.length !== exp_format.length ) { + if ( typeof o.defaultValue === "number" && o.defaultValue > 0 ) { + return new w._date((w.initDate.getEpoch() + parseInt(o.defaultValue,10))*1000); + } + return new w._date(w.initDate.getTime()); + } + + exp_temp = w.initDate.getEpoch(); + for ( i=0; i -1 ) { d.mont = exp_temp; } + break; + case 'B': + exp_temp = $.inArray(exp_input[i], w.__('monthsOfYear')); + if ( exp_temp > -1 ) { d.mont = exp_temp; } + break; + } + } + if ( d.meri !== 0 ) { + if ( d.meri === -1 && d.hour === 12 ) { d.hour = 0; } + if ( d.meri === 1 && d.hour !== 12 ) { d.hour = d.hour + 12; } + } + + date = new w._date(w._n(d.year,0),w._n(d.mont,0),w._n(d.date,1),w._n(d.hour,0),w._n(d.mins,0),w._n(d.secs,0),0); + + if ( d.year < 100 && d.year !== -1 ) { date.setFullYear(d.year); } + + if ( ( d.mont > -1 && d.date > -1 ) || ( d.hour > -1 && d.mins > -1 && d.secs > -1 ) ) { return date; } + + if ( d.week !== false ) { + date.setDWeek(d.wtyp, d.week); + if ( d.date > -1 ) { date.setDate(d.date); } + } + if ( d.yday !== false ) { date.setD(1,0).setD(2,1).adj(2,(d.yday-1)); } + if ( d.wday !== false ) { date.adj(2,(d.wday - date.getDay())); } + } + return date; + }, + _customformat: { + 'default': function(oper, date) { return false; } + }, + _formatter: function(format, date) { + var w = this, + o = this.options, tmp, + dur = { + part: [0,0,0,0], tp: 0 + }; + + if ( o.mode === 'durationbox' || o.mode === 'durationflipbox' ) { + dur.tp = this.theDate.getEpoch() - this.initDate.getEpoch(); + dur.part[0] = parseInt( dur.tp / (60*60*24),10); dur.tp -=(dur.part[0]*60*60*24); // Days + dur.part[1] = parseInt( dur.tp / (60*60),10); dur.tp -= (dur.part[1]*60*60); // Hours + dur.part[2] = parseInt( dur.tp / (60),10); dur.tp -= (dur.part[2]*60); // Minutes + dur.part[3] = dur.tp; // Seconds + + if ( ! format.match(/%Dd/) ) { dur.part[1] += (dur.part[0]*24);} + if ( ! format.match(/%Dl/) ) { dur.part[2] += (dur.part[1]*60);} + if ( ! format.match(/%DM/) ) { dur.part[3] += (dur.part[2]*60);} + } + + format = format.replace(/%(D|X|0|-)*([1-9a-zA-Z])/g, function(match, pad, oper) { + if ( pad === 'X' ) { + if ( typeof w._customformat[o.mode] !== 'undefined' ) { return w._customformat[o.mode](oper, date, o); } + return match; + } + if ( pad === 'D' ) { + switch ( oper ) { + case 'd': return dur.part[0]; + case 'l': return w._zPad(dur.part[1]); + case 'M': return w._zPad(dur.part[2]); + case 'S': return w._zPad(dur.part[3]); + case 'A': return ((dur.part[0] > 1)?w.__('durationDays')[1]:w.__('durationDays')[0]); + default: return match; + } + } + switch ( oper ) { + case '%': // Literal % + return '%'; + case 'a': // Short Day + return w.__('daysOfWeekShort')[date.getDay()]; + case 'A': // Full Day of week + return w.__('daysOfWeek')[date.getDay()]; + case 'b': // Short month + return w.__('monthsOfYearShort')[date.getMonth()]; + case 'B': // Full month + return w.__('monthsOfYear')[date.getMonth()]; + case 'C': // Century + return date.getFullYear().toString().substr(0,2); + case 'd': // Day of month + return (( pad === '-' ) ? date.getDate() : w._zPad(date.getDate())); + case 'H': // Hour (01..23) + case 'k': + return (( pad === '-' ) ? date.getHours() : w._zPad(date.getHours())); + case 'I': // Hour (01..12) + case 'l': + return (( pad === '-' ) ? ((date.getHours() === 0 || date.getHours() === 12)?12:((date.getHours()<12)?date.getHours():(date.getHours()-12))) : w._zPad(((date.getHours() === 0 || date.getHours() === 12)?12:((date.getHours()<12)?date.getHours():date.getHours()-12)))); + case 'm': // Month + return (( pad === '-' ) ? date.getMonth()+1 : w._zPad(date.getMonth()+1)); + case 'M': // Minutes + return (( pad === '-' ) ? date.getMinutes() : w._zPad(date.getMinutes())); + case 'p': // AM/PM (ucase) + return ((date.getHours() < 12)?w.__('meridiem')[0].toUpperCase():w.__('meridiem')[1].toUpperCase()); + case 'P': // AM/PM (lcase) + return ((date.getHours() < 12)?w.__('meridiem')[0].toLowerCase():w.__('meridiem')[1].toLowerCase()); + case 's': // Unix Seconds + return date.getEpoch(); + case 'S': // Seconds + return (( pad === '-' ) ? date.getSeconds() : w._zPad(date.getSeconds())); + case 'u': // Day of week (1-7) + return (( pad === '-' ) ? date.getDay() + 1 : w._zPad(date.getDay() + 1)); + case 'w': // Day of week + return date.getDay(); + case 'y': // Year (2 digit) + return date.getFullYear().toString().substr(2,2); + case 'Y': // Year (4 digit) + return date.getFullYear(); + case 'E': // BE (Buddist Era, 4 Digit) + return date.getFullYear() + 543; + case 'V': + return (( pad === '-' ) ? date.getDWeek(4) : w._zPad(date.getDWeek(4))); + case 'U': + return (( pad === '-' ) ? date.getDWeek(0) : w._zPad(date.getDWeek(0))); + case 'W': + return (( pad === '-' ) ? date.getDWeek(1) : w._zPad(date.getDWeek(1))); + case 'o': // Ordinals + if ( typeof w._ord[o.useLang] !== 'undefined' ) { return w._ord[o.useLang](date.getDate()); } + return w._ord['default'](date.getDate()); + case 'j': + tmp = new Date(date.getFullYear(),0,1); + tmp = Math.ceil((date - tmp) / 86400000)+1; + return (( tmp < 100 ) ? (( tmp < 10 )? '00' : '0') : '' ) + String(tmp); + case 'G': + if ( date.getDWeek(4) === 1 && date.getMonth() > 0 ) { return date.getFullYear() + 1; } + if ( date.getDWeek(4) > 51 && date.getMonth() < 11 ) { return date.getFullYear() - 1; } + return date.getFullYear(); + case 'g': + if ( date.getDWeek(4) === 1 && date.getMonth() > 0 ) { return parseInt(date.getFullYear().toString().substr(2,2),10) + 1; } + if ( date.getDWeek(4) > 51 && date.getMonth() < 11 ) { return parseInt(date.getFullYear().toString().substr(2,2),10) - 1; } + return date.getFullYear().toString().substr(2,2); + default: + return match; + } + }); + + if ( w.__('useArabicIndic') === true ) { + format = w._dRep(format); + } + + return format; + }, + _btwn: function(value, low, high) { + return ( value > low && value < high ); + }, + _minStepFix: function() { + var tempMin = this.theDate.get(4), tmp, + w = this, + o = this.options; + + if ( o.minuteStep > 1 && tempMin % o.minuteStep > 0 ) { + if ( o.minuteStepRound < 0 ) { + tempMin = tempMin - (tempMin % o.minuteStep); + } else if ( o.minStepRound > 0 ) { + tempMin = tempMin + ( o.minuteStep - ( tempMin % o.minuteStep ) ); + } else { + if ( tempMin % o.minuteStep < o.minuteStep / 2 ) { + tempMin = tempMin - (tempMin % o.minuteStep); + } else { + tempMin = tempMin + ( o.minuteStep - ( tempMin % o.minuteStep ) ); + } + } + w.theDate.setMinutes(tempMin); + } + }, + _offset: function(mode, amount, update) { + // Compute a date/time offset. + // update = false to prevent controls refresh + var w = this, + o = this.options, + ok = false; + + mode = (mode || "").toLowerCase(); + + if ( typeof(update) === "undefined" ) { update = true; } + w.d.input.trigger('datebox', {'method':'offset', 'type':mode, 'amount':amount}); + + if ( mode !== 'a' && ( typeof o.rolloverMode[mode] === 'undefined' || o.rolloverMode[mode] === true )) { + ok = $.inArray(mode, ['y','m','d','h','i','s']); + } else { + switch(mode) { + case 'y': ok = 0; break; + case 'm': + if ( w._btwn(w.theDate.getMonth()+amount,-1,12) ) { ok = 1; } + break; + case 'd': + if ( w._btwn(w.theDate.getDate() + amount,0,(32 - w.theDate.copy([0],[0,0,32,13]).getDate() + 1) )) { ok = 2; } + break; + case 'h': + if ( w._btwn(w.theDate.getHours() + amount,-1,24) ) { ok = 3; } + break; + case 'i': + if ( w._btwn(w.theDate.getMinutes() + amount,-1,60) ) { ok = 4; } + break; + case 's': + if ( w._btwn(w.theDate.getSeconds() + amount,-1,60) ) { ok = 5; } + break; + case 'a': + w._offset('h',((amount>0)?1:-1)*12,false); + break; + } + } + if ( ok !== false ) { w.theDate.adj(ok,amount); } + if ( update === true ) { w.refresh(); } + if ( o.useImmediate ) { w.d.input.trigger('datebox', {'method':'doset'}); } + }, + _startOffset: function(date) { + var o = this.options; + + if ( o.startOffsetYears !== false ) { + date.adj(0, o.startOffsetYears); + } + if ( o.startOffsetMonths !== false ) { + date.adj(1, o.startOffsetMonths); + } + if ( o.startOffsetDays !== false ) { + date.adj(2, o.startOffsetDays); + } + return date; + }, + _create: function() { + // Create the widget, called automatically by widget system + $( document ).trigger( "dateboxcreate" ); + + var w = this, + o = $.extend(this.options, (typeof this.element.jqmData('options') !== 'undefined') ? this.element.jqmData('options') : this._getLongOptions(this.element) ), + thisTheme = ( o.theme === false && typeof($(this).jqmData('theme')) === 'undefined' ) ? + ( ( typeof(this.element.parentsUntil(':jqmData(theme)').parent().jqmData('theme')) === 'undefined' ) ? + o.themeDefault : this.element.parentsUntil(':jqmData(theme)').parent().jqmData('theme') ) + : o.theme, + trans = o.useAnimation ? o.transition : 'none', + d = o.useNewStyle === false ? { + input: this.element, + wrap: this.element.wrap('
').parent(), + mainWrap: $("
", { "class": 'ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden '+trans+' ui-body-'+thisTheme} ).css('zIndex', o.zindex), + intHTML: false + } : { + input: this.element, + wrap: this.element, + mainWrap: $("
", { "class": 'ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden '+trans+' ui-body-'+thisTheme} ).css('zIndex', o.zindex), + intHTML: false + }, + touch = ( typeof window.ontouchstart !== 'undefined' ), + drag = { + eStart : (touch ? 'touchstart' : 'mousedown')+'.datebox', + eMove : (touch ? 'touchmove' : 'mousemove')+'.datebox', + eEnd : (touch ? 'touchend' : 'mouseup')+'.datebox', + eEndA : (touch ? 'mouseup.datebox touchend.datebox touchcancel.datebox touchmove.datebox' : 'mouseup.datebox'), + move : false, + start : false, + end : false, + pos : false, + target : false, + delta : false, + tmp : false + }, + calc = { }, + ns = (typeof $.mobile.ns !== 'undefined')?$.mobile.ns:''; + + $.extend(w, {d: d, ns: ns, drag: drag, touch:touch}); + + if ( o.usePlaceholder !== false ) { + if ( o.usePlaceholder === true && w._grabLabel() !== false ) { w.d.input.attr('placeholder', w._grabLabel()); } + if ( typeof o.usePlaceholder === 'string' ) { w.d.input.attr('placeholder', o.usePlaceholder); } + } + + o.theme = thisTheme; + + w.clearFunc = false; + w.disabled = false; + w.runButton = false; + w._date = window.Date; + w._enhanceDate(); + w.baseID = w.d.input.attr('id'); + + w.initDate = new w._date(); + w.theDate = (o.defaultValue) ? w._makeDate(o.defaultValue) : ( (w.d.input.val() !== "") ? w._makeDate(w.d.input.val()) : new w._date() ); + w.initDone = false; + + if ( o.showInitialValue === true ) { + w.d.input.val(w._formatter(w.__fmt(), w.theDate)); + } + + if ( o.useButton === true && o.useInline === false && o.useNewStyle === false ) { + w.d.open = $(''+this.__('tooltip')+'') + .on(o.clickEvent, function(e) { + e.preventDefault(); + if ( !w.disabled ) { w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.parent().addClass('ui-focus'); w.d.input.parent().removeClass('ui-focus'); } + setTimeout( function() { $(e.target).closest('a').removeClass($.mobile.activeBtnClass); }, 300); + }).appendTo(w.d.wrap).buttonMarkup({icon: 'grid', iconpos: 'notext', corners:true, shadow:true}) + .css({'vertical-align': 'middle', 'display': 'inline-block'}); + } + + w.d.screen = $("
", {'class':'ui-datebox-screen ui-datebox-hidden'+((o.useModal)?' ui-datebox-screen-modal':'')}) + .css({'z-index': o.zindex-1}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.trigger('datebox', {'method':'close'}); + }); + + if ( o.enhanceInput === true && navigator.userAgent.match(/Android/i) ){ + w.inputType = 'number'; + } else { + w.inputType = 'text'; + } + + if ( o.hideInput ) { w.d.wrap.parent().hide(); } + + if ( o.mobVer < 140 ) { + $('label[for=\''+w.d.input.attr('id')+'\']').addClass('ui-input-text').css('verticalAlign', 'middle'); + } + + w.d.wrap.on(o.clickEvent, function() { + if ( !w.disabled && ( o.noButtonFocusMode || o.focusMode ) ) { + w.d.input.trigger('datebox', {'method': 'open'}); + w.d.wrap.addClass('ui-focus'); + w.d.input.removeClass('ui-focus'); + } + }); + + w.d.input + .removeClass('ui-corner-all ui-shadow-inset') + .bind(w.touch?'touchend':'click', function(e){ + if ( w.disabled === false && o.useNewStyle === true && o.useFocus === false ) { + if ( ((w.touch ? e.originalEvent.changedTouches[0].pageX : e.pageX) - e.target.offsetLeft) > (e.target.offsetWidth - 20) ) { + w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.parent().addClass('ui-focus'); w.d.input.removeClass('ui-focus'); + //setTimeout(function(){w.d.wrap.addClass('ui-focus');}, 200); + } + } + }) + .focus(function(){ + if ( w.disabled === false && o.useFocus === true ) { + w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.addClass('ui-focus'); w.d.input.removeClass('ui-focus'); + if ( o.useNewStyle === false ) { w.d.input.parent().removeClass('ui-focus'); w.d.wrap.parent().addClass('ui-focus'); } + } + if ( o.useNewStyle === false ) { w.d.input.removeClass('ui-focus'); } + }) + .blur(function(){ + w.d.wrap.removeClass('ui-focus'); + w.d.input.removeClass('ui-focus'); + }) + .change(function() { + w.theDate = w._makeDate(w.d.input.val()); + w.refresh(); + }) + .attr("readonly", o.lockInput) + .on('datebox', w._event); + + if ( o.useNewStyle === true ) { + w.d.input.addClass('ui-corner-all '+((o.useAltIcon===true)?'ui-icon-datebox-alt':'ui-icon-datebox')); + if ( o.overrideStyleClass !== false ) { w.d.input.addClass(o.overrideStyleClass); } + } else { + w.d.input.parent().css('border', 'none').removeClass('ui-shadow-inset'); + } + + w.d.wrap.parent().on(o.clickEvent, function() { + if ( !w.disabled && o.useFocus === true && o.useNewStyle === false ) { + w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.addClass('ui-focus'); w.d.input.removeClass('ui-focus'); + setTimeout(function(){ + w.d.wrap.removeClass('ui-focus'); + w.d.wrap.parent().addClass('ui-focus'); + }, 500); + } + }); + + // Check if mousewheel plugin is loaded + if ( typeof $.event.special.mousewheel !== 'undefined' ) { w.wheelExists = true; } + + // Disable when done if element attribute disabled is true. + if ( w.d.input.is(':disabled') ) { + w.disable(); + } + + if ( o.useInline === true || o.useInlineBlind ) { w.open(); } + + w.applyMinMax(false, false); + + //Throw dateboxinit event + $( document ).trigger( "dateboxaftercreate" ); + }, + applyMinMax: function(refresh, override) { + var w = this, + o = this.options, + calc = {}; + + if ( typeof refresh === 'undefined' ) { refresh = false; } + if ( typeof override === 'undefined' ) { override = true; } + + if ( ( override === true || o.minDays === false ) && typeof(w.d.input.attr('min')) !== 'undefined' ) { + calc.today = new w._date(); + calc.lod = 24 * 60 * 60 * 1000; + calc.todayc = new w._date(calc.today.getFullYear(), calc.today.getMonth(), calc.today.getDate(), 0,0,0,0); + calc.fromel = w.d.input.attr('min').split('-'); + calc.compdt = new w._date(calc.fromel[0],calc.fromel[1]-1,calc.fromel[2],0,0,0,0); + o.minDays = parseInt((((calc.compdt.getTime() - calc.todayc.getTime()) / calc.lod))*-1,10); + } + if ( ( override === true || o.maxDays === false ) && typeof(w.d.input.attr('max')) !== 'undefined' ) { + calc.today = new w._date(); + calc.lod = 24 * 60 * 60 * 1000; + calc.todayc = new w._date(calc.today.getFullYear(), calc.today.getMonth(), calc.today.getDate(), 0,0,0,0); + calc.fromel = w.d.input.attr('max').split('-'); + calc.compdt = new w._date(calc.fromel[0],calc.fromel[1]-1,calc.fromel[2],0,0,0,0); + o.maxDays = parseInt((((calc.compdt.getTime() - calc.todayc.getTime()) / calc.lod)),10); + } + + if ( refresh === true ) { w.refresh(); } + }, + _build: { + 'default': function () { + this.d.headerText = "Error"; + this.d.intHTML = $("

There is no mode by that name loaded / mode not given

"); + } + }, + _applyCoords: function(e) { + var w = e.widget, + o = e.widget.options, + fixd = { + h: $.mobile.activePage.find('.ui-header').jqmData('position'), + f: $.mobile.activePage.find('.ui-footer').jqmData('position'), + fh: $.mobile.activePage.find('.ui-footer').outerHeight(), + hh: $.mobile.activePage.find('.ui-header').outerHeight() + }, + iput = { + x: w.d.wrap.offset().left + (w.d.wrap.outerWidth() / 2), + y: w.d.wrap.offset().top + (w.d.wrap.outerHeight() / 2) + }, + size = { + w: w.d.mainWrap.outerWidth(), + h: w.d.mainWrap.outerHeight() + }, + doc = { + t: $(window).scrollTop(), + h: $(window).height(), + w: $.mobile.activePage.width(), + ah: $(document).height() + }, + pos = { + y: (o.centerVert) ? doc.t + ((doc.h / 2) - (size.h / 2)) : iput.y - ( size.h / 2 ), + x: (doc.w < 400 || o.centerHoriz ) ? (doc.w / 2) - (size.w /2) : iput.x - (size.w / 2) + }; + + if ( o.centerVert === false ) { + if ( o.hideFixedToolbars === true && ( typeof fixd.f !== 'undefined' || typeof fixd.h !== 'undefined' )) { + $.mobile.activePage.find(":jqmData(position='fixed')").fixedtoolbar('hide'); + fixd.f = undefined; + fixd.h = undefined; + } + + if ( typeof fixd.f !== 'undefined' ) { + if ( ( pos.y + size.h ) > ( doc.h - fixd.fh - 2 ) ) { + pos.y = doc.h - fixd.fh - 2 - size.h; + } + } else { + if ( ( pos.y + size.h ) > ( doc.ah - fixd.fh - 2 ) ) { + pos.y = doc.ah - fixd.fh - 2 - size.h; + } + if ( ( doc.h + doc.t ) < ( size.h + pos.y + 2 ) ) { + pos.y = doc.h + doc.t - size.h - 2; + } + } + + if ( typeof fixd.h !== 'undefined' ) { + if ( ( doc.t + fixd.hh + 2 ) > pos.y ) { + pos.y = doc.t + fixd.hh + 2; + } + } else { + if ( fixd.hh + 2 > pos.y ) { + pos.y = fixd.hh + 2; + } + if ( pos.y < doc.t + 2 ) { + pos.y = doc.t + 2; + } + } + } + w.d.mainWrap.css({'position': 'absolute', 'top': pos.y, 'left': pos.x}); + }, + _drag: { + 'default': function () { return false; } + }, + open: function () { + var w = this, + o = this.options, + popopts = {}, + basepop = {'history':false}, + qns = 'data-'+this.ns, + trans = o.useAnimation ? o.transition : 'none'; + + if ( o.useFocus === true && w.fastReopen === true ) { w.d.input.blur(); return false; } + if ( w.clearFunc !== false ) { + clearTimeout(w.clearFunc); w.clearFunc = false; + } + + // Call the open callback if provided. Additionally, if this + // returns false then the open/update will stop. + if ( o.openCallback !== false ) { + if ( ! $.isFunction(o.openCallback) ) { + if ( typeof window[o.openCallback] !== 'undefined' ) { + o.openCallback = window[o.openCallback]; + } else { + o.openCallback = new Function(o.openCallback); + } + } + if ( o.openCallback.apply(w, $.merge([w.theDate],o.openCallbackArgs)) === false ) { return false; } + } + + w.theDate = w._makeDate(w.d.input.val()); + if ( w.d.input.val() === "" ) { w._startOffset(w.theDate); } + w.d.input.blur(); + + if ( typeof w._build[o.mode] === 'undefined' ) { + w._build['default'].apply(w,[]); + } else { + w._build[o.mode].apply(w,[]); + } + if ( typeof w._drag[o.mode] !== 'undefined' ) { + w._drag[o.mode].apply(w, []); + } + w.d.input.trigger('datebox', {'method':'refresh'}); + if ( w.__('useArabicIndic') === true ) { w._doIndic(); } + + if ( ( o.useInline === true || o.useInlineBlind === true ) && w.initDone === false ) { + w.d.mainWrap.append(w.d.intHTML); + w.d.input.parent().parent().append(w.d.mainWrap); + w.d.mainWrap.removeClass('ui-datebox-hidden'); + if ( o.useInline === true ) { + w.d.mainWrap.addClass('ui-datebox-inline'); + } else { + w.d.mainWrap.addClass('ui-datebox-inlineblind'); + w.d.mainWrap.hide(); + } + w.initDone = false; + w.d.input.trigger('datebox',{'method':'postrefresh'}); + } + + if ( o.useImmediate ) { w.d.input.trigger('datebox', {'method':'doset'}); } + if ( o.useInline ) { return true; } + if ( o.useInlineBlind ) { + if ( w.initDone ) { w.d.mainWrap.slideDown(); } + else { w.initDone = true; } + return true; + } + if ( w.d.intHTML.is(':visible') ) { return false; } // Ignore if already open + + if ( o.enablePopup === true ) { + w.d.dialogPage = false; + w.d.mainWrap.empty(); + if ( o.useHeader === true ) { + w.d.headHTML = $('
'); + $("Close").appendTo(w.d.headHTML) + .buttonMarkup({ theme : o.themeHeader, icon : 'delete', iconpos: 'notext', corners: true, shadow : true }) + .on(o.clickEventAlt, function(e) { e.preventDefault(); w.d.input.trigger('datebox', {'method':'close'}); }); + $('

'+w.d.headerText+'

').appendTo(w.d.headHTML); + w.d.mainWrap.append(w.d.headHTML); + } + w.d.mainWrap.append(w.d.intHTML).css('zIndex', o.zindex); + w.d.input.trigger('datebox',{'method':'postrefresh'}); + + if ( o.useAnimation === true ) { + popopts.transition = o.transition; + } else { + popopts.transition = "none"; + } + + if ( o.popupForceX !== false && o.popupForceY !== false ) { + popopts.x = o.popupForceX; + popopts.y = o.popupForceY; + } + + if ( o.popupPosition !== false ) { + popopts.positionTo = o.popupPosition; + } else { + if ( typeof w.baseID !== undefined ) { + popopts.positionTo = '#' + w.baseID; + } else { + popopts.positionTo = 'window'; + } + } + + if ( o.useModal === true ) { basepop.overlayTheme = "a"; } + + w.d.mainWrap.removeClass('ui-datebox-hidden').popup(basepop).popup("open", popopts); + w.refresh(); + } else { + if ( o.dialogForce || ( o.dialogEnable && window.width() < 400 ) ) { + w.d.dialogPage = $("
" + + "
" + + "

"+w.d.headerText+"

") + .appendTo( $.mobile.pageContainer ) + .page().css('minHeight', '0px').addClass(trans); + w.d.dialogPage.find('.ui-header').find('a').off('click vclick').on(o.clickEventAlt, function(e) { e.preventDefault(); w.d.input.trigger('datebox', {'method':'close'}); }); + w.d.mainWrap.append(w.d.intHTML).css({'marginLeft':'auto', 'marginRight':'auto'}).removeClass('ui-datebox-hidden'); + w.d.dialogPage.find('.ui-content').append(w.d.mainWrap); + w.d.input.trigger('datebox',{'method':'postrefresh'}); + $.mobile.activePage.off( "pagehide.remove" ); + $.mobile.changePage(w.d.dialogPage, {'transition': trans}); + } else { + w.d.dialogPage = false; + w.d.mainWrap.empty(); + if ( o.useHeader === true ) { + w.d.headHTML = $('
'); + $("Close").appendTo(w.d.headHTML) + .buttonMarkup({ theme : o.themeHeader, icon : 'delete', iconpos: 'notext', corners: true, shadow : true }) + .on(o.clickEventAlt, function(e) { e.preventDefault(); w.d.input.trigger('datebox', {'method':'close'}); }); + $('

'+w.d.headerText+'

').appendTo(w.d.headHTML); + w.d.mainWrap.append(w.d.headHTML); + } + w.d.mainWrap.append(w.d.intHTML).css('zIndex', o.zindex); + w.d.mainWrap.appendTo($.mobile.activePage); + w.d.screen.appendTo($.mobile.activePage); + w.d.input.trigger('datebox',{'method':'postrefresh'}); + w._applyCoords({widget:w}); + + if ( o.useModal === true ) { + if(o.useAnimation) { + w.d.screen.fadeIn('slow'); + } else { + w.d.screen.show(); + } + } else { + setTimeout(function () { w.d.screen.removeClass('ui-datebox-hidden');}, 500); + } + + w.d.mainWrap.addClass('ui-overlay-shadow in').removeClass('ui-datebox-hidden'); + + $(document).on('orientationchange.datebox', {widget:w}, function(e) { w._applyCoords(e.data); }); + if ( o.resizeListener === true ) { + $(window).on('resize.datebox', {widget:w}, function (e) { w._applyCoords(e.data); }); + } + } + } + }, + close: function() { + var w = this, + o = this.options; + + if ( o.useInlineBlind === true ) { w.d.mainWrap.slideUp(); return true;} + if ( o.useInline === true || w.d.intHTML === false ) { return true; } + + if ( w.d.dialogPage !== false ) { + $(w.d.dialogPage).dialog('close'); + + if ( ! $.mobile.activePage.jqmData('mobile-page').options.domCache ) { + $.mobile.activePage.on('pagehide.remove', function () { $(this).remove(); }); + } + + w.d.intHTML.detach().empty(); + w.d.mainWrap.detach().empty(); + w.d.wrap.removeClass('ui-focus'); + w.clearFunc = setTimeout(function () { w.d.dialogPage.empty().remove(); w.clearFunc = false; }, 1500); + } else { + if ( o.enablePopup === true ) { + w.d.mainWrap.popup('close'); + w.d.wrap.removeClass('ui-focus'); + } else { + if ( o.useModal ) { + if(o.useAnimation) { + w.d.screen.fadeOut('slow'); + } else { + w.d.screen.hide(); + } + } else { + w.d.screen.addClass('ui-datebox-hidden'); + } + w.d.screen.detach(); + w.d.mainWrap.addClass('ui-datebox-hidden').removeAttr('style').removeClass('in ui-overlay-shadow').empty().detach(); + w.d.intHTML.detach(); + w.d.wrap.removeClass('ui-focus'); + + $(document).off('orientationchange.datebox'); + if ( o.resizeListener === true ) { + $(window).off('resize.datebox'); + } + } + } + w.d.wrap.parent().removeClass('ui-focus'); + + $(document).off(w.drag.eMove); + $(document).off(w.drag.eEnd); + $(document).off(w.drag.eEndA); + + if ( o.useFocus ) { + w.fastReopen = true; + setTimeout(function(t) { return function () { t.fastReopen = false; };}(w), 300); + } + + if ( o.closeCallback !== false ) { + if ( ! $.isFunction(o.closeCallback) ) { + if ( typeof window[o.closeCallback] !== 'undefined' ) { + o.closeCallback = window[o.closeCallback]; + } else { + o.closeCallback = new Function(o.closeCallback); + } + } + o.closeCallback.apply(w, $.merge([w.theDate], o.closeCallbackArgs)); + } + }, + refresh: function() { + if ( typeof this._build[this.options.mode] === 'undefined' ) { + this._build['default'].apply(this,[]); + } else { + this._build[this.options.mode].apply(this,[]); + } + if ( this.__('useArabicIndic') === true ) { this._doIndic(); } + this.d.mainWrap.append(this.d.intHTML); + this.d.input.trigger('datebox',{'method':'postrefresh'}); + }, + _check: function() { + var w = this, + td = null, + o = this.options; + + w.dateOK = true; + + if ( o.afterToday !== false ) { + td = new w._date(); + if ( w.theDate < td ) { w.theDate = td; } + } + if ( o.beforeToday !== false ) { + td = new w._date(); + if ( w.theDate > td ) { w.theDate = td; } + } + if ( o.maxDays !== false ) { + td = new w._date(); + td.adj(2, o.maxDays); + if ( w.theDate > td ) { w.theDate = td; } + } + if ( o.minDays !== false ) { + td = new w._date(); + td.adj(2, -1*o.minDays); + if ( w.theDate < td ) { w.theDate = td; } + } + if ( o.minHour !== false ) { + if ( w.theDate.getHours() < o.minHour ) { + w.theDate.setHours(o.minHour); + } + } + if ( o.maxHour !== false ) { + if ( w.theDate.getHours() > o.maxHour ) { + w.theDate.setHours(o.maxHour); + } + } + if ( o.maxYear !== false ) { + td = new w._date(o.maxYear, 0, 1); + td.adj(2, -1); + if ( w.theDate > td ) { w.theDate = td; } + } + if ( o.minYear !== false ) { + td = new w._date(o.minYear, 0, 1); + if ( w.theDate < td ) { w.theDate = td; } + } + + if ( $.inArray(o.mode, ['timebox','durationbox','durationflipbox','timeflipbox']) > -1 ) { + if ( o.mode === 'timeflipbox' && o.validHours !== false ) { + if ( $.inArray(w.theDate.getHours(), o.validHours) < 0 ) { w.dateOK = false; } + } + } else { + if ( o.blackDatesRec !== false ) { + for ( i=0; i -1 ) { w.dateOK = false; } + } + if ( o.blackDays !== false ) { + if ( $.inArray(w.theDate.getDay(), o.blackDays) > -1 ) { w.dateOK = false; } + } + } + }, + _grabLabel: function() { + var w = this, + o = this.options; + + if ( typeof o.overrideDialogLabel === 'undefined' ) { + if ( typeof w.d.input.attr('placeholder') !== 'undefined' ) { return w.d.input.attr('placeholder'); } + if ( typeof w.d.input.attr('title') !== 'undefined' ) { return w.d.input.attr('title'); } + if ( w.d.wrap.parent().find('label[for=\''+w.d.input.attr('id')+'\']').text() !== '' ) { + return w.d.wrap.parent().find('label[for=\''+w.d.input.attr('id')+'\']').text(); + } + return false; + } + return o.overrideDialogLabel; + }, + _makeEl: function(source, parts) { + var part = false, + retty = false; + + retty = source.clone(); + + if ( typeof parts.attr !== 'undefined' ) { + for ( part in parts.attr ) { + if ( parts.attr.hasOwnProperty(part) ) { + retty.jqmData(part, parts.attr[part]); + } + } + } + return retty; + }, + _getLongOptions: function(element) { + var key, retty = {}, prefix, temp; + + if ( $.mobile.ns === "" ) { + prefix = "datebox"; + } else { + prefix = $.mobile.ns.substr(0, $.mobile.ns.length - 1) + 'Datebox'; + } + + for ( key in element.data() ) { + if ( key.substr(0, prefix.length) === prefix && key.length > prefix.length ) { + temp = key.substr(prefix.length); + temp = temp.charAt(0).toLowerCase() + temp.slice(1); + retty[temp] = element.data(key); + } + } + return retty; + }, + disable: function(){ + // Disable the element + this.d.input.attr("disabled",true); + this.d.wrap.addClass("ui-disabled").blur(); + this.disabled = true; + this.d.input.trigger('datebox', {'method':'disable'}); + }, + enable: function(){ + // Enable the element + this.d.input.attr("disabled", false); + this.d.wrap.removeClass("ui-disabled"); + this.disabled = false; + this.d.input.trigger('datebox', {'method':'enable'}); + }, + _setOption: function() { + $.Widget.prototype._setOption.apply( this, arguments ); + this.refresh(); + }, + getTheDate: function() { + return this.theDate; + }, + getLastDur: function() { + return this.lastDuration; + }, + setTheDate: function(newDate) { + this.theDate = newDate; + this.refresh(); + }, + callFormat: function(format, date) { + return this._formatter(format, date); + } + }); + + // Degrade date inputs to text inputs, suppress standard UI functions. + $( document ).on( "pagebeforecreate", function( e ) { + $( ":jqmData(role='datebox')", e.target ).each(function() { + $(this).prop('type', 'text'); + }); + }); + // Automatically bind to data-role='datebox' items. + $( document ).on( "pagecreate create", function( e ){ + $( document ).trigger( "dateboxbeforecreate" ); + $( ":jqmData(role='datebox')", e.target ).each(function() { + var defed = typeof ($(this).data(parseInt($.mobile.version.replace(/\./g,''),10) > 111 ? 'mobile-datebox' : 'datebox')); + if ( defed === "undefined" ) { + $(this).datebox(); + } + }); + }); +})( jQuery ); +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ + +(function($) { + $.extend( $.mobile.datebox.prototype.options, { + themeButton: 'a', + themeInput: 'a', + useSetButton: true, + customData: [ + {'input': true, 'name':'Letter', 'data':['a','b','c','d','e']}, + {'input': true, 'name':'Text', 'data':['some','bull','shtuff','here']}, + {'input': false, 'name':'Image', 'data':['','','','']} + ], + customDefault: [0,0,0], + customFormat: false, + customboxlang: { + // This structure interfaces with __() -> if it exists, strings are looked up here after i8n fails, + // and before going to 'default' - the name syntax is lang + 'customSet':'Looks Good' + } + + }); + $.extend( $.mobile.datebox.prototype, { + _cbox_offset: function (fld,amount) { + // This is *not* an automatic override, used below specificly. + var w = this, x, + o = this.options; + + tmp = (w.customCurrent[fld] + amount) % o.customData[fld]['data'].length; + if ( tmp < 0 ) { tmp = o.customData[fld]['data'].length + tmp; } + + w.customCurrent[fld] = tmp; + if ( o.useImmediate ) { w.d.input.trigger('datebox', {'method':'set', 'value':w._formatter(o.customFormat,w.customCurrent), 'date':w.customCurrent}); } + w.refresh(); + } + }); + $.extend( $.mobile.datebox.prototype._parser, { + // If this stucture exists, it is called instead of the usual date input parser. + // The name of the structure is the same as the mode name - it recieves a string + // as the input, which is the current value of the input element, pre-sanitized + 'custombox' : function ( str ) { + return ( str.length < 1 || ! str.match(/,/) ) ? this.options.customDefault : str.split(","); + } + }); + $.extend( $.mobile.datebox.prototype._customformat, { + // If this stucture exists, the formatter will call it when it encounters a special string + // %X - it recieves the single letter operater, and the current "date" value + 'custombox' : function ( oper, val ) { + return val[oper-1]; + } + }); + $.extend( $.mobile.datebox.prototype._build, { + 'custombox': function () { + var w = this, + o = this.options, i, y, tmp, cnt = -2, + uid = 'ui-datebox-', + divBase = $("
"), + divPlus = $('
'), + divIn = divBase.clone(), + divMinus = divPlus.clone(), + customCurrent = this._makeDate(this.d.input.val()), + inBase = $("").addClass('ui-input-text ui-corner-all ui-shadow-inset ui-body-'+o.themeInput), + inDiv = $("
").addClass('ui-input-text ui-corner-all ui-shadow-inset ui-body-'+o.themeInput).css({'padding':'.4em','margin':'.5em 0','text-align':'center'}), + butBase = $("
"), + butPTheme = {theme: o.themeButton, icon: 'plus', iconpos: 'bottom', corners:true, shadow:true}, + butMTheme = $.extend({}, butPTheme, {icon: 'minus', iconpos: 'top'}); + + if ( typeof w.customCurrent === "undefined" ) { w.customCurrent = customCurrent; } + + if ( o.customFormat === false ) { + tmp = []; + for ( i = 0; i'); + + + for(i=0; i').append(inBase.clone().attr('value', o.customData[i]['data'][w.customCurrent[i]])).addClass('ui-block-'+tmp).appendTo(divIn); + } else { + $('
').append(inDiv.clone().html(o.customData[i]['data'][w.customCurrent[i]])).addClass('ui-block-'+tmp).appendTo(divIn); + } + w._makeEl(butBase, {'attr': {'field':i, 'amount':1}}).addClass('ui-block-'+tmp).buttonMarkup(butPTheme).appendTo(divPlus); + w._makeEl(butBase, {'attr': {'field':i, 'amount':1}}).addClass('ui-block-'+tmp).buttonMarkup(butMTheme).appendTo(divMinus); + cnt++; + } + + divPlus.addClass('ui-grid-'+['a','b','c','d','e'][cnt]).appendTo(w.d.intHTML); + divIn.addClass('ui-datebox-dboxin').addClass('ui-grid-'+['a','b','c','d','e'][cnt]).appendTo(w.d.intHTML); + divMinus.addClass('ui-grid-'+['a','b','c','d','e'][cnt]).appendTo(w.d.intHTML); + + if (o.mobVer >= 140) { + divMinus.find('div').css({'min-height': '2.3em'}); + divPlus.find('div').css({'min-height': '2.3em'}); + } + + if (o.mobVer >= 140) { + divMinus.find('div').css({'min-height': '2.3em'}); + divPlus.find('div').css({'min-height': '2.3em'}); + } + + if ( o.useSetButton || o.useClearButton ) { + y = $('
', {'class':uid+'controls'}); + + if ( o.useSetButton ) { + $(''+w.__('customSet')+'') + .appendTo(y).buttonMarkup({theme: o.theme, icon: 'check', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.trigger('datebox', {'method':'set', 'value':w._formatter(o.customFormat,w.customCurrent), 'date':w.customCurrent}); + w.d.input.trigger('datebox', {'method':'close'}); + }); + } + if ( o.useClearButton ) { + $(''+w.__('clearButton')+'') + .appendTo(y).buttonMarkup({theme: o.theme, icon: 'delete', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.val(''); + w.d.input.trigger('datebox',{'method':'clear'}); + w.d.input.trigger('datebox',{'method':'close'}); + }); + } + if ( o.useCollapsedBut ) { + y.addClass('ui-datebox-collapse'); + } + y.appendTo(w.d.intHTML); + } + + divIn.on('change', 'input', function() { w.refresh(); }); + + divPlus.on(o.clickEvent, 'div', function(e) { + e.preventDefault(); + w._cbox_offset($(this).jqmData('field'), $(this).jqmData('amount')); + }); + divMinus.on(o.clickEvent, 'div', function(e) { + e.preventDefault(); + w._cbox_offset($(this).jqmData('field'), $(this).jqmData('amount')*-1); + }); + + } + }); +})( jQuery ); diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.custombox.min.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.custombox.min.js new file mode 100644 index 000000000..ab0eddc1c --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.custombox.min.js @@ -0,0 +1,7 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +(function(a){a.widget("mobile.datebox",a.mobile.widget,{options:{version:"2-1.4.0-2013070300",mobVer:parseInt(a.mobile.version.replace(/\./g,"")),theme:false,themeDefault:"a",themeHeader:"a",mode:false,centerHoriz:false,centerVert:false,transition:"pop",useAnimation:true,hideInput:false,hideFixedToolbars:false,lockInput:true,enhanceInput:true,zindex:"500",clickEvent:"vclick",clickEventAlt:"click",resizeListener:true,defaultValue:false,showInitialValue:false,dialogEnable:false,dialogForce:false,enablePopup:false,popupPosition:false,popupForceX:false,popupForceY:false,useModal:false,useInline:false,useInlineBlind:false,useHeader:true,useImmediate:false,useNewStyle:false,useAltIcon:false,overrideStyleClass:false,useButton:true,useFocus:false,useClearButton:false,useCollapsedBut:false,usePlaceholder:false,openCallback:false,openCallbackArgs:[],closeCallback:false,closeCallbackArgs:[],startOffsetYears:false,startOffsetMonths:false,startOffsetDays:false,afterToday:false,beforeToday:false,notToday:false,maxDays:false,minDays:false,maxYear:false,minYear:false,blackDates:false,blackDatesRec:false,blackDays:false,minHour:false,maxHour:false,minuteStep:1,minuteStepRound:0,rolloverMode:{m:true,d:true,h:true,i:true,s:true},useLang:"default",lang:{"default":{setDateButtonLabel:"Set Date",setTimeButtonLabel:"Set Time",setDurationButtonLabel:"Set Duration",calTodayButtonLabel:"Jump to Today",titleDateDialogLabel:"Set Date",titleTimeDialogLabel:"Set Time",daysOfWeek:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],daysOfWeekShort:["Su","Mo","Tu","We","Th","Fr","Sa"],monthsOfYear:["January","February","March","April","May","June","July","August","September","October","November","December"],monthsOfYearShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],durationLabel:["Days","Hours","Minutes","Seconds"],durationDays:["Day","Days"],timeFormat:24,headerFormat:"%A, %B %-d, %Y",tooltip:"Open Date Picker",nextMonth:"Next Month",prevMonth:"Previous Month",dateFieldOrder:["m","d","y"],timeFieldOrder:["h","i","a"],slideFieldOrder:["y","m","d"],dateFormat:"%Y-%m-%d",useArabicIndic:false,isRTL:false,calStartDay:0,clearButton:"Clear",durationOrder:["d","h","i","s"],meridiem:["AM","PM"],timeOutput:"%k:%M",durationFormat:"%Dd %DA, %Dl:%DM:%DS",calDateListLabel:"Other Dates",calHeaderFormat:"%B %Y"}}},_enhanceDate:function(){a.extend(this._date.prototype,{copy:function(c,b){if(typeof c==="undefined"){c=[0,0,0,0,0,0,0]}if(typeof b==="undefined"){b=[0,0,0,0,0,0,0]}while(c.length<7){c.push(0)}while(b.length<7){b.push(0)}return new Date(((b[0]>0)?b[0]:this.getFullYear()+c[0]),((b[1]>0)?b[1]:this.getMonth()+c[1]),((b[2]>0)?b[2]:this.getDate()+c[2]),((b[3]>0)?b[3]:this.getHours()+c[3]),((b[4]>0)?b[4]:this.getMinutes()+c[4]),((b[5]>0)?b[5]:this.getSeconds()+c[5]),((b[6]>0)?b[5]:this.getMilliseconds()+c[6]))},adj:function(c,b){if(typeof b!=="number"){throw new Error("Adjustment value not specified")}if(typeof c!=="number"){throw new Error("Adjustment type not specified")}switch(c){case 0:this.setFullYear(this.getFullYear()+b);break;case 1:this.setMonth(this.getMonth()+b);break;case 2:this.setDate(this.getDate()+b);break;case 3:this.setHours(this.getHours()+b);break;case 4:this.setMinutes(this.getMinutes()+b);break;case 5:this.setSeconds(this.getSeconds()+b);break;case 6:this.setMilliseconds(this.getMilliseconds()+b);break}return this},setD:function(c,b){switch(c){case 0:this.setFullYear(b);break;case 1:this.setMonth(b);break;case 2:this.setDate(b);break;case 3:this.setHours(b);break;case 4:this.setMinutes(b);break;case 5:this.setSeconds(b);break;case 6:this.setMilliseconds(b);break}return this},get:function(b){switch(b){case 0:return this.getFullYear();case 1:return this.getMonth();case 2:return this.getDate();case 3:return this.getHours();case 4:return this.getMinutes();case 5:return this.getSeconds()}return false},iso:function(){return String(this.getFullYear())+"-"+((this.getMonth()<9)?"0":"")+String(this.getMonth()+1)+"-"+((this.getDate()<10)?"0":"")+String(this.getDate())},comp:function(){return parseInt(this.iso().replace(/-/g,""),10)},getEpoch:function(){return(this.getTime()-this.getMilliseconds())/1000},getArray:function(){return[this.getFullYear(),this.getMonth(),this.getDate(),this.getHours(),this.getMinutes(),this.getSeconds()]},setFirstDay:function(b){this.setD(2,1).adj(2,(b-this.getDay()));if(this.get(2)>10){this.adj(2,7)}return this},setDWeek:function(c,b){if(c===4){return this.setD(1,0).setD(2,1).setFirstDay(4).adj(2,-3).adj(2,(b-1)*7)}return this.setD(1,0).setD(2,1).setFirstDay(c).adj(2,(b-1)*7)},getDWeek:function(c){var d,b;switch(c){case 0:d=this.copy([0,-1*this.getMonth()]).setFirstDay(0);return Math.floor((this.getTime()-(d.getTime()+((this.getTimezoneOffset()-d.getTimezoneOffset())*60000)))/604800000)+1;case 1:d=this.copy([0,-1*this.getMonth()]).setFirstDay(1);return Math.floor((this.getTime()-(d.getTime()+((this.getTimezoneOffset()-d.getTimezoneOffset())*60000)))/604800000)+1;case 4:if(this.getMonth()===11&&this.getDate()>28){return 1}d=this.copy([0,-1*this.getMonth()],true).setFirstDay(4).adj(2,-3);b=Math.floor((this.getTime()-(d.getTime()+((this.getTimezoneOffset()-d.getTimezoneOffset())*60000)))/604800000)+1;if(b<1){d=this.copy([-1,-1*this.getMonth()]).setFirstDay(4).adj(2,-3);return Math.floor((this.getTime()-d.getTime())/604800000)+1}return b;default:return 0}}})},_event:function(d,c){var b=a(this).data(parseInt(a.mobile.version.replace(/\./g,""),10)>110?"mobile-datebox":"datebox");if(!d.isPropagationStopped()){switch(c.method){case"close":b.close();break;case"open":b.open();break;case"set":a(this).val(c.value);a(this).trigger("change");break;case"doset":if(a.isFunction(b["_"+b.options.mode+"DoSet"])){b["_"+b.options.mode+"DoSet"].apply(b,[])}else{a(this).trigger("datebox",{method:"set",value:b._formatter(b.__fmt(),b.theDate),date:b.theDate})}break;case"dooffset":if(c.type){b._offset(c.type,c.amount,true)}break;case"dorefresh":b.refresh();break;case"doreset":b.hardreset();break;case"doclear":a(this).val("").trigger("change");break;case"clear":a(this).trigger("change")}}},_hoover:function(b){a(b).toggleClass("ui-btn-up-"+a(b).jqmData("theme")+" ui-btn-down-"+a(b).jqmData("theme"))},_ord:{"default":function(c){var b=c%10;if(c>9&&c<21){return"th"}if(b>3){return"th"}return["th","st","nd","rd"][b]}},__:function(d){var c=this.options,b="override"+d.charAt(0).toUpperCase()+d.slice(1);if(typeof c[b]!=="undefined"){return c[b]}if(typeof c.lang[c.useLang][d]!=="undefined"){return c.lang[c.useLang][d]}if(typeof c[c.mode+"lang"]!=="undefined"&&typeof c[c.mode+"lang"][d]!=="undefined"){return c[c.mode+"lang"][d]}return c.lang["default"][d]},__fmt:function(){var b=this,c=this.options;switch(c.mode){case"timebox":case"timeflipbox":return b.__("timeOutput");case"durationbox":case"durationflipbox":return b.__("durationFormat");default:return b.__("dateFormat")}},_zPad:function(b){return((b<10)?"0"+String(b):String(b))},_dRep:function(j,g){var h=48,b=57,c=1584,d=null,e=null,f="";if(g===-1){h+=c;b+=c;c=-1584}for(d=0;d=h&&e<=b){f=f+String.fromCharCode(e+c)}else{f=f+String.fromCharCode(e)}}return f},_doIndic:function(){var b=this;b.d.intHTML.find("*").each(function(){if(a(this).children().length<1){a(this).text(b._dRep(a(this).text()))}else{if(a(this).hasClass("ui-datebox-slideday")){a(this).html(b._dRep(a(this).html()))}}});b.d.intHTML.find("input").each(function(){a(this).val(b._dRep(a(this).val()))})},_parser:{"default":function(b){return false}},_n:function(c,b){return(c<0)?b:c},_pa:function(b,c){if(typeof c==="boolean"){return new this._date(b[0],b[1],b[2],0,0,0,0)}return new this._date(c.getFullYear(),c.getMonth(),c.getDate(),b[0],b[1],b[2],0)},_makeDate:function(k){k=a.trim(((this.__("useArabicIndic")===true)?this._dRep(k,-1):k));var n=this,c=this.options,e=n.__fmt(),m=null,h=[],l=null,b=null,f=new n._date(),j={year:-1,mont:-1,date:-1,hour:-1,mins:-1,secs:-1,week:false,wtyp:4,wday:false,yday:false,meri:0},g;if(typeof c.mode==="undefined"){return f}if(typeof n._parser[c.mode]!=="undefined"){return n._parser[c.mode].apply(n,[k])}if(c.mode==="durationbox"||c.mode==="durationflipbox"){e=e.replace(/%D([a-z])/gi,function(d,o){switch(o){case"d":case"l":case"M":case"S":return"("+d+"|[0-9]+)";default:return".+?"}});e=new RegExp("^"+e+"$");m=e.exec(k);l=e.exec(n.__fmt());if(m===null||m.length!==l.length){if(typeof c.defaultValue==="number"&&c.defaultValue>0){return new n._date((n.initDate.getEpoch()+parseInt(c.defaultValue,10))*1000)}return new n._date(n.initDate.getTime())}b=n.initDate.getEpoch();for(g=0;g-1){j.mont=b}break;case"B":b=a.inArray(m[g],n.__("monthsOfYear"));if(b>-1){j.mont=b}break}}if(j.meri!==0){if(j.meri===-1&&j.hour===12){j.hour=0}if(j.meri===1&&j.hour!==12){j.hour=j.hour+12}}f=new n._date(n._n(j.year,0),n._n(j.mont,0),n._n(j.date,1),n._n(j.hour,0),n._n(j.mins,0),n._n(j.secs,0),0);if(j.year<100&&j.year!==-1){f.setFullYear(j.year)}if((j.mont>-1&&j.date>-1)||(j.hour>-1&&j.mins>-1&&j.secs>-1)){return f}if(j.week!==false){f.setDWeek(j.wtyp,j.week);if(j.date>-1){f.setDate(j.date)}}if(j.yday!==false){f.setD(1,0).setD(2,1).adj(2,(j.yday-1))}if(j.wday!==false){f.adj(2,(j.wday-f.getDay()))}}return f},_customformat:{"default":function(c,b){return false}},_formatter:function(f,c){var b=this,g=this.options,d,e={part:[0,0,0,0],tp:0};if(g.mode==="durationbox"||g.mode==="durationflipbox"){e.tp=this.theDate.getEpoch()-this.initDate.getEpoch();e.part[0]=parseInt(e.tp/(60*60*24),10);e.tp-=(e.part[0]*60*60*24);e.part[1]=parseInt(e.tp/(60*60),10);e.tp-=(e.part[1]*60*60);e.part[2]=parseInt(e.tp/(60),10);e.tp-=(e.part[2]*60);e.part[3]=e.tp;if(!f.match(/%Dd/)){e.part[1]+=(e.part[0]*24)}if(!f.match(/%Dl/)){e.part[2]+=(e.part[1]*60)}if(!f.match(/%DM/)){e.part[3]+=(e.part[2]*60)}}f=f.replace(/%(D|X|0|-)*([1-9a-zA-Z])/g,function(h,j,k){if(j==="X"){if(typeof b._customformat[g.mode]!=="undefined"){return b._customformat[g.mode](k,c,g)}return h}if(j==="D"){switch(k){case"d":return e.part[0];case"l":return b._zPad(e.part[1]);case"M":return b._zPad(e.part[2]);case"S":return b._zPad(e.part[3]);case"A":return((e.part[0]>1)?b.__("durationDays")[1]:b.__("durationDays")[0]);default:return h}}switch(k){case"%":return"%";case"a":return b.__("daysOfWeekShort")[c.getDay()];case"A":return b.__("daysOfWeek")[c.getDay()];case"b":return b.__("monthsOfYearShort")[c.getMonth()];case"B":return b.__("monthsOfYear")[c.getMonth()];case"C":return c.getFullYear().toString().substr(0,2);case"d":return((j==="-")?c.getDate():b._zPad(c.getDate()));case"H":case"k":return((j==="-")?c.getHours():b._zPad(c.getHours()));case"I":case"l":return((j==="-")?((c.getHours()===0||c.getHours()===12)?12:((c.getHours()<12)?c.getHours():(c.getHours()-12))):b._zPad(((c.getHours()===0||c.getHours()===12)?12:((c.getHours()<12)?c.getHours():c.getHours()-12))));case"m":return((j==="-")?c.getMonth()+1:b._zPad(c.getMonth()+1));case"M":return((j==="-")?c.getMinutes():b._zPad(c.getMinutes()));case"p":return((c.getHours()<12)?b.__("meridiem")[0].toUpperCase():b.__("meridiem")[1].toUpperCase());case"P":return((c.getHours()<12)?b.__("meridiem")[0].toLowerCase():b.__("meridiem")[1].toLowerCase());case"s":return c.getEpoch();case"S":return((j==="-")?c.getSeconds():b._zPad(c.getSeconds()));case"u":return((j==="-")?c.getDay()+1:b._zPad(c.getDay()+1));case"w":return c.getDay();case"y":return c.getFullYear().toString().substr(2,2);case"Y":return c.getFullYear();case"E":return c.getFullYear()+543;case"V":return((j==="-")?c.getDWeek(4):b._zPad(c.getDWeek(4)));case"U":return((j==="-")?c.getDWeek(0):b._zPad(c.getDWeek(0)));case"W":return((j==="-")?c.getDWeek(1):b._zPad(c.getDWeek(1)));case"o":if(typeof b._ord[g.useLang]!=="undefined"){return b._ord[g.useLang](c.getDate())}return b._ord["default"](c.getDate());case"j":d=new Date(c.getFullYear(),0,1);d=Math.ceil((c-d)/86400000)+1;return((d<100)?((d<10)?"00":"0"):"")+String(d);case"G":if(c.getDWeek(4)===1&&c.getMonth()>0){return c.getFullYear()+1}if(c.getDWeek(4)>51&&c.getMonth()<11){return c.getFullYear()-1}return c.getFullYear();case"g":if(c.getDWeek(4)===1&&c.getMonth()>0){return parseInt(c.getFullYear().toString().substr(2,2),10)+1}if(c.getDWeek(4)>51&&c.getMonth()<11){return parseInt(c.getFullYear().toString().substr(2,2),10)-1}return c.getFullYear().toString().substr(2,2);default:return h}});if(b.__("useArabicIndic")===true){f=b._dRep(f)}return f},_btwn:function(d,b,c){return(d>b&&d1&&d%e.minuteStep>0){if(e.minuteStepRound<0){d=d-(d%e.minuteStep)}else{if(e.minStepRound>0){d=d+(e.minuteStep-(d%e.minuteStep))}else{if(d%e.minuteStep0)?1:-1)*12,false);break}}if(c!==false){b.theDate.adj(c,d)}if(g===true){b.refresh()}if(e.useImmediate){b.d.input.trigger("datebox",{method:"doset"})}},_startOffset:function(b){var c=this.options;if(c.startOffsetYears!==false){b.adj(0,c.startOffsetYears)}if(c.startOffsetMonths!==false){b.adj(1,c.startOffsetMonths)}if(c.startOffsetDays!==false){b.adj(2,c.startOffsetDays)}return b},_create:function(){a(document).trigger("dateboxcreate");var j=this,b=a.extend(this.options,(typeof this.element.jqmData("options")!=="undefined")?this.element.jqmData("options"):this._getLongOptions(this.element)),k=(b.theme===false&&typeof(a(this).jqmData("theme"))==="undefined")?((typeof(this.element.parentsUntil(":jqmData(theme)").parent().jqmData("theme"))==="undefined")?b.themeDefault:this.element.parentsUntil(":jqmData(theme)").parent().jqmData("theme")):b.theme,l=b.useAnimation?b.transition:"none",g=b.useNewStyle===false?{input:this.element,wrap:this.element.wrap('
').parent(),mainWrap:a("
",{"class":"ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden "+l+" ui-body-"+k}).css("zIndex",b.zindex),intHTML:false}:{input:this.element,wrap:this.element,mainWrap:a("
",{"class":"ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden "+l+" ui-body-"+k}).css("zIndex",b.zindex),intHTML:false},e=(typeof window.ontouchstart!=="undefined"),f={eStart:(e?"touchstart":"mousedown")+".datebox",eMove:(e?"touchmove":"mousemove")+".datebox",eEnd:(e?"touchend":"mouseup")+".datebox",eEndA:(e?"mouseup.datebox touchend.datebox touchcancel.datebox touchmove.datebox":"mouseup.datebox"),move:false,start:false,end:false,pos:false,target:false,delta:false,tmp:false},c={},h=(typeof a.mobile.ns!=="undefined")?a.mobile.ns:"";a.extend(j,{d:g,ns:h,drag:f,touch:e});if(b.usePlaceholder!==false){if(b.usePlaceholder===true&&j._grabLabel()!==false){j.d.input.attr("placeholder",j._grabLabel())}if(typeof b.usePlaceholder==="string"){j.d.input.attr("placeholder",b.usePlaceholder)}}b.theme=k;j.clearFunc=false;j.disabled=false;j.runButton=false;j._date=window.Date;j._enhanceDate();j.baseID=j.d.input.attr("id");j.initDate=new j._date();j.theDate=(b.defaultValue)?j._makeDate(b.defaultValue):((j.d.input.val()!=="")?j._makeDate(j.d.input.val()):new j._date());j.initDone=false;if(b.showInitialValue===true){j.d.input.val(j._formatter(j.__fmt(),j.theDate))}if(b.useButton===true&&b.useInline===false&&b.useNewStyle===false){j.d.open=a(''+this.__("tooltip")+"").on(b.clickEvent,function(d){d.preventDefault();if(!j.disabled){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.parent().addClass("ui-focus");j.d.input.parent().removeClass("ui-focus")}setTimeout(function(){a(d.target).closest("a").removeClass(a.mobile.activeBtnClass)},300)}).appendTo(j.d.wrap).buttonMarkup({icon:"grid",iconpos:"notext",corners:true,shadow:true}).css({"vertical-align":"middle",display:"inline-block"})}j.d.screen=a("
",{"class":"ui-datebox-screen ui-datebox-hidden"+((b.useModal)?" ui-datebox-screen-modal":"")}).css({"z-index":b.zindex-1}).on(b.clickEventAlt,function(d){d.preventDefault();j.d.input.trigger("datebox",{method:"close"})});if(b.enhanceInput===true&&navigator.userAgent.match(/Android/i)){j.inputType="number"}else{j.inputType="text"}if(b.hideInput){j.d.wrap.parent().hide()}if(b.mobVer<140){a("label[for='"+j.d.input.attr("id")+"']").addClass("ui-input-text").css("verticalAlign","middle")}j.d.wrap.on(b.clickEvent,function(){if(!j.disabled&&(b.noButtonFocusMode||b.focusMode)){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.addClass("ui-focus");j.d.input.removeClass("ui-focus")}});j.d.input.removeClass("ui-corner-all ui-shadow-inset").bind(j.touch?"touchend":"click",function(d){if(j.disabled===false&&b.useNewStyle===true&&b.useFocus===false){if(((j.touch?d.originalEvent.changedTouches[0].pageX:d.pageX)-d.target.offsetLeft)>(d.target.offsetWidth-20)){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.parent().addClass("ui-focus");j.d.input.removeClass("ui-focus")}}}).focus(function(){if(j.disabled===false&&b.useFocus===true){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.addClass("ui-focus");j.d.input.removeClass("ui-focus");if(b.useNewStyle===false){j.d.input.parent().removeClass("ui-focus");j.d.wrap.parent().addClass("ui-focus")}}if(b.useNewStyle===false){j.d.input.removeClass("ui-focus")}}).blur(function(){j.d.wrap.removeClass("ui-focus");j.d.input.removeClass("ui-focus")}).change(function(){j.theDate=j._makeDate(j.d.input.val());j.refresh()}).attr("readonly",b.lockInput).on("datebox",j._event);if(b.useNewStyle===true){j.d.input.addClass("ui-corner-all "+((b.useAltIcon===true)?"ui-icon-datebox-alt":"ui-icon-datebox"));if(b.overrideStyleClass!==false){j.d.input.addClass(b.overrideStyleClass)}}else{j.d.input.parent().css("border","none").removeClass("ui-shadow-inset")}j.d.wrap.parent().on(b.clickEvent,function(){if(!j.disabled&&b.useFocus===true&&b.useNewStyle===false){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.addClass("ui-focus");j.d.input.removeClass("ui-focus");setTimeout(function(){j.d.wrap.removeClass("ui-focus");j.d.wrap.parent().addClass("ui-focus")},500)}});if(typeof a.event.special.mousewheel!=="undefined"){j.wheelExists=true}if(j.d.input.is(":disabled")){j.disable()}if(b.useInline===true||b.useInlineBlind){j.open()}j.applyMinMax(false,false);a(document).trigger("dateboxaftercreate")},applyMinMax:function(e,d){var b=this,f=this.options,c={};if(typeof e==="undefined"){e=false}if(typeof d==="undefined"){d=true}if((d===true||f.minDays===false)&&typeof(b.d.input.attr("min"))!=="undefined"){c.today=new b._date();c.lod=24*60*60*1000;c.todayc=new b._date(c.today.getFullYear(),c.today.getMonth(),c.today.getDate(),0,0,0,0);c.fromel=b.d.input.attr("min").split("-");c.compdt=new b._date(c.fromel[0],c.fromel[1]-1,c.fromel[2],0,0,0,0);f.minDays=parseInt((((c.compdt.getTime()-c.todayc.getTime())/c.lod))*-1,10)}if((d===true||f.maxDays===false)&&typeof(b.d.input.attr("max"))!=="undefined"){c.today=new b._date();c.lod=24*60*60*1000;c.todayc=new b._date(c.today.getFullYear(),c.today.getMonth(),c.today.getDate(),0,0,0,0);c.fromel=b.d.input.attr("max").split("-");c.compdt=new b._date(c.fromel[0],c.fromel[1]-1,c.fromel[2],0,0,0,0);f.maxDays=parseInt((((c.compdt.getTime()-c.todayc.getTime())/c.lod)),10)}if(e===true){b.refresh()}},_build:{"default":function(){this.d.headerText="Error";this.d.intHTML=a("

There is no mode by that name loaded / mode not given

")}},_applyCoords:function(h){var b=h.widget,j=h.widget.options,f={h:a.mobile.activePage.find(".ui-header").jqmData("position"),f:a.mobile.activePage.find(".ui-footer").jqmData("position"),fh:a.mobile.activePage.find(".ui-footer").outerHeight(),hh:a.mobile.activePage.find(".ui-header").outerHeight()},c={x:b.d.wrap.offset().left+(b.d.wrap.outerWidth()/2),y:b.d.wrap.offset().top+(b.d.wrap.outerHeight()/2)},d={w:b.d.mainWrap.outerWidth(),h:b.d.mainWrap.outerHeight()},g={t:a(window).scrollTop(),h:a(window).height(),w:a.mobile.activePage.width(),ah:a(document).height()},k={y:(j.centerVert)?g.t+((g.h/2)-(d.h/2)):c.y-(d.h/2),x:(g.w<400||j.centerHoriz)?(g.w/2)-(d.w/2):c.x-(d.w/2)};if(j.centerVert===false){if(j.hideFixedToolbars===true&&(typeof f.f!=="undefined"||typeof f.h!=="undefined")){a.mobile.activePage.find(":jqmData(position='fixed')").fixedtoolbar("hide");f.f=undefined;f.h=undefined}if(typeof f.f!=="undefined"){if((k.y+d.h)>(g.h-f.fh-2)){k.y=g.h-f.fh-2-d.h}}else{if((k.y+d.h)>(g.ah-f.fh-2)){k.y=g.ah-f.fh-2-d.h}if((g.h+g.t)<(d.h+k.y+2)){k.y=g.h+g.t-d.h-2}}if(typeof f.h!=="undefined"){if((g.t+f.hh+2)>k.y){k.y=g.t+f.hh+2}}else{if(f.hh+2>k.y){k.y=f.hh+2}if(k.y
');a("Close").appendTo(b.d.headHTML).buttonMarkup({theme:g.themeHeader,icon:"delete",iconpos:"notext",corners:true,shadow:true}).on(g.clickEventAlt,function(h){h.preventDefault();b.d.input.trigger("datebox",{method:"close"})});a('

'+b.d.headerText+"

").appendTo(b.d.headHTML);b.d.mainWrap.append(b.d.headHTML)}b.d.mainWrap.append(b.d.intHTML).css("zIndex",g.zindex);b.d.input.trigger("datebox",{method:"postrefresh"});if(g.useAnimation===true){e.transition=g.transition}else{e.transition="none"}if(g.popupForceX!==false&&g.popupForceY!==false){e.x=g.popupForceX;e.y=g.popupForceY}if(g.popupPosition!==false){e.positionTo=g.popupPosition}else{if(typeof b.baseID!==undefined){e.positionTo="#"+b.baseID}else{e.positionTo="window"}}if(g.useModal===true){f.overlayTheme="a"}b.d.mainWrap.removeClass("ui-datebox-hidden").popup(f).popup("open",e);b.refresh()}else{if(g.dialogForce||(g.dialogEnable&&window.width()<400)){b.d.dialogPage=a("

"+b.d.headerText+"

").appendTo(a.mobile.pageContainer).page().css("minHeight","0px").addClass(c);b.d.dialogPage.find(".ui-header").find("a").off("click vclick").on(g.clickEventAlt,function(h){h.preventDefault();b.d.input.trigger("datebox",{method:"close"})});b.d.mainWrap.append(b.d.intHTML).css({marginLeft:"auto",marginRight:"auto"}).removeClass("ui-datebox-hidden");b.d.dialogPage.find(".ui-content").append(b.d.mainWrap);b.d.input.trigger("datebox",{method:"postrefresh"});a.mobile.activePage.off("pagehide.remove");a.mobile.changePage(b.d.dialogPage,{transition:c})}else{b.d.dialogPage=false;b.d.mainWrap.empty();if(g.useHeader===true){b.d.headHTML=a('
');a("Close").appendTo(b.d.headHTML).buttonMarkup({theme:g.themeHeader,icon:"delete",iconpos:"notext",corners:true,shadow:true}).on(g.clickEventAlt,function(h){h.preventDefault();b.d.input.trigger("datebox",{method:"close"})});a('

'+b.d.headerText+"

").appendTo(b.d.headHTML);b.d.mainWrap.append(b.d.headHTML)}b.d.mainWrap.append(b.d.intHTML).css("zIndex",g.zindex);b.d.mainWrap.appendTo(a.mobile.activePage);b.d.screen.appendTo(a.mobile.activePage);b.d.input.trigger("datebox",{method:"postrefresh"});b._applyCoords({widget:b});if(g.useModal===true){if(g.useAnimation){b.d.screen.fadeIn("slow")}else{b.d.screen.show()}}else{setTimeout(function(){b.d.screen.removeClass("ui-datebox-hidden")},500)}b.d.mainWrap.addClass("ui-overlay-shadow in").removeClass("ui-datebox-hidden");a(document).on("orientationchange.datebox",{widget:b},function(h){b._applyCoords(h.data)});if(g.resizeListener===true){a(window).on("resize.datebox",{widget:b},function(h){b._applyCoords(h.data)})}}}},close:function(){var b=this,c=this.options;if(c.useInlineBlind===true){b.d.mainWrap.slideUp();return true}if(c.useInline===true||b.d.intHTML===false){return true}if(b.d.dialogPage!==false){a(b.d.dialogPage).dialog("close");if(!a.mobile.activePage.jqmData("mobile-page").options.domCache){a.mobile.activePage.on("pagehide.remove",function(){a(this).remove()})}b.d.intHTML.detach().empty();b.d.mainWrap.detach().empty();b.d.wrap.removeClass("ui-focus");b.clearFunc=setTimeout(function(){b.d.dialogPage.empty().remove();b.clearFunc=false},1500)}else{if(c.enablePopup===true){b.d.mainWrap.popup("close");b.d.wrap.removeClass("ui-focus")}else{if(c.useModal){if(c.useAnimation){b.d.screen.fadeOut("slow")}else{b.d.screen.hide()}}else{b.d.screen.addClass("ui-datebox-hidden")}b.d.screen.detach();b.d.mainWrap.addClass("ui-datebox-hidden").removeAttr("style").removeClass("in ui-overlay-shadow").empty().detach();b.d.intHTML.detach();b.d.wrap.removeClass("ui-focus");a(document).off("orientationchange.datebox");if(c.resizeListener===true){a(window).off("resize.datebox")}}}b.d.wrap.parent().removeClass("ui-focus");a(document).off(b.drag.eMove);a(document).off(b.drag.eEnd);a(document).off(b.drag.eEndA);if(c.useFocus){b.fastReopen=true;setTimeout(function(d){return function(){d.fastReopen=false}}(b),300)}if(c.closeCallback!==false){if(!a.isFunction(c.closeCallback)){if(typeof window[c.closeCallback]!=="undefined"){c.closeCallback=window[c.closeCallback]}else{c.closeCallback=new Function(c.closeCallback)}}c.closeCallback.apply(b,a.merge([b.theDate],c.closeCallbackArgs))}},refresh:function(){if(typeof this._build[this.options.mode]==="undefined"){this._build["default"].apply(this,[])}else{this._build[this.options.mode].apply(this,[])}if(this.__("useArabicIndic")===true){this._doIndic()}this.d.mainWrap.append(this.d.intHTML);this.d.input.trigger("datebox",{method:"postrefresh"})},_check:function(){var b=this,d=null,c=this.options;b.dateOK=true;if(c.afterToday!==false){d=new b._date();if(b.theDated){b.theDate=d}}if(c.maxDays!==false){d=new b._date();d.adj(2,c.maxDays);if(b.theDate>d){b.theDate=d}}if(c.minDays!==false){d=new b._date();d.adj(2,-1*c.minDays);if(b.theDatec.maxHour){b.theDate.setHours(c.maxHour)}}if(c.maxYear!==false){d=new b._date(c.maxYear,0,1);d.adj(2,-1);if(b.theDate>d){b.theDate=d}}if(c.minYear!==false){d=new b._date(c.minYear,0,1);if(b.theDate-1){if(c.mode==="timeflipbox"&&c.validHours!==false){if(a.inArray(b.theDate.getHours(),c.validHours)<0){b.dateOK=false}}}else{if(c.blackDatesRec!==false){for(i=0;i-1){b.dateOK=false}}if(c.blackDays!==false){if(a.inArray(b.theDate.getDay(),c.blackDays)>-1){b.dateOK=false}}}},_grabLabel:function(){var b=this,c=this.options;if(typeof c.overrideDialogLabel==="undefined"){if(typeof b.d.input.attr("placeholder")!=="undefined"){return b.d.input.attr("placeholder")}if(typeof b.d.input.attr("title")!=="undefined"){return b.d.input.attr("title")}if(b.d.wrap.parent().find("label[for='"+b.d.input.attr("id")+"']").text()!==""){return b.d.wrap.parent().find("label[for='"+b.d.input.attr("id")+"']").text()}return false}return c.overrideDialogLabel},_makeEl:function(d,e){var b=false,c=false;c=d.clone();if(typeof e.attr!=="undefined"){for(b in e.attr){if(e.attr.hasOwnProperty(b)){c.jqmData(b,e.attr[b])}}}return c},_getLongOptions:function(d){var c,e={},f,b;if(a.mobile.ns===""){f="datebox"}else{f=a.mobile.ns.substr(0,a.mobile.ns.length-1)+"Datebox"}for(c in d.data()){if(c.substr(0,f.length)===f&&c.length>f.length){b=c.substr(f.length);b=b.charAt(0).toLowerCase()+b.slice(1);e[b]=d.data(c)}}return e},disable:function(){this.d.input.attr("disabled",true);this.d.wrap.addClass("ui-disabled").blur();this.disabled=true;this.d.input.trigger("datebox",{method:"disable"})},enable:function(){this.d.input.attr("disabled",false);this.d.wrap.removeClass("ui-disabled");this.disabled=false;this.d.input.trigger("datebox",{method:"enable"})},_setOption:function(){a.Widget.prototype._setOption.apply(this,arguments);this.refresh()},getTheDate:function(){return this.theDate},getLastDur:function(){return this.lastDuration},setTheDate:function(b){this.theDate=b;this.refresh()},callFormat:function(c,b){return this._formatter(c,b)}});a(document).on("pagebeforecreate",function(b){a(":jqmData(role='datebox')",b.target).each(function(){a(this).prop("type","text")})});a(document).on("pagecreate create",function(b){a(document).trigger("dateboxbeforecreate");a(":jqmData(role='datebox')",b.target).each(function(){var c=typeof(a(this).data(parseInt(a.mobile.version.replace(/\./g,""),10)>111?"mobile-datebox":"datebox"));if(c==="undefined"){a(this).datebox()}})})})(jQuery);(function(a){a.extend(a.mobile.datebox.prototype.options,{themeButton:"a",themeInput:"a",useSetButton:true,customData:[{input:true,name:"Letter",data:["a","b","c","d","e"]},{input:true,name:"Text",data:["some","bull","shtuff","here"]},{input:false,name:"Image",data:['','','','']}],customDefault:[0,0,0],customFormat:false,customboxlang:{customSet:"Looks Good"}});a.extend(a.mobile.datebox.prototype,{_cbox_offset:function(e,d){var c=this,b,f=this.options;tmp=(c.customCurrent[e]+d)%f.customData[e]["data"].length;if(tmp<0){tmp=f.customData[e]["data"].length+tmp}c.customCurrent[e]=tmp;if(f.useImmediate){c.d.input.trigger("datebox",{method:"set",value:c._formatter(f.customFormat,c.customCurrent),date:c.customCurrent})}c.refresh()}});a.extend(a.mobile.datebox.prototype._parser,{custombox:function(b){return(b.length<1||!b.match(/,/))?this.options.customDefault:b.split(",")}});a.extend(a.mobile.datebox.prototype._customformat,{custombox:function(c,b){return b[c-1]}});a.extend(a.mobile.datebox.prototype._build,{custombox:function(){var t=this,f=this.options,l,s,m,g=-2,q="ui-datebox-",r=a("
"),c=a("
"),j=r.clone(),k=c.clone(),n=this._makeDate(this.d.input.val()),e=a("").addClass("ui-input-text ui-corner-all ui-shadow-inset ui-body-"+f.themeInput),h=a("
").addClass("ui-input-text ui-corner-all ui-shadow-inset ui-body-"+f.themeInput).css({padding:".4em",margin:".5em 0","text-align":"center"}),p=a("
"),b={theme:f.themeButton,icon:"plus",iconpos:"bottom",corners:true,shadow:true},d=a.extend({},b,{icon:"minus",iconpos:"top"});if(typeof t.customCurrent==="undefined"){t.customCurrent=n}if(f.customFormat===false){m=[];for(l=0;l");for(l=0;l").append(e.clone().attr("value",f.customData[l]["data"][t.customCurrent[l]])).addClass("ui-block-"+m).appendTo(j)}else{a("
").append(h.clone().html(f.customData[l]["data"][t.customCurrent[l]])).addClass("ui-block-"+m).appendTo(j)}t._makeEl(p,{attr:{field:l,amount:1}}).addClass("ui-block-"+m).buttonMarkup(b).appendTo(c);t._makeEl(p,{attr:{field:l,amount:1}}).addClass("ui-block-"+m).buttonMarkup(d).appendTo(k);g++}c.addClass("ui-grid-"+["a","b","c","d","e"][g]).appendTo(t.d.intHTML);j.addClass("ui-datebox-dboxin").addClass("ui-grid-"+["a","b","c","d","e"][g]).appendTo(t.d.intHTML);k.addClass("ui-grid-"+["a","b","c","d","e"][g]).appendTo(t.d.intHTML);if(f.mobVer>=140){k.find("div").css({"min-height":"2.3em"});c.find("div").css({"min-height":"2.3em"})}if(f.mobVer>=140){k.find("div").css({"min-height":"2.3em"});c.find("div").css({"min-height":"2.3em"})}if(f.useSetButton||f.useClearButton){s=a("
",{"class":q+"controls"});if(f.useSetButton){a(''+t.__("customSet")+"").appendTo(s).buttonMarkup({theme:f.theme,icon:"check",iconpos:"left",corners:true,shadow:true}).on(f.clickEventAlt,function(i){i.preventDefault();t.d.input.trigger("datebox",{method:"set",value:t._formatter(f.customFormat,t.customCurrent),date:t.customCurrent});t.d.input.trigger("datebox",{method:"close"})})}if(f.useClearButton){a(''+t.__("clearButton")+"").appendTo(s).buttonMarkup({theme:f.theme,icon:"delete",iconpos:"left",corners:true,shadow:true}).on(f.clickEventAlt,function(i){i.preventDefault();t.d.input.val("");t.d.input.trigger("datebox",{method:"clear"});t.d.input.trigger("datebox",{method:"close"})})}if(f.useCollapsedBut){s.addClass("ui-datebox-collapse")}s.appendTo(t.d.intHTML)}j.on("change","input",function(){t.refresh()});c.on(f.clickEvent,"div",function(i){i.preventDefault();t._cbox_offset(a(this).jqmData("field"),a(this).jqmData("amount"))});k.on(f.clickEvent,"div",function(i){i.preventDefault();t._cbox_offset(a(this).jqmData("field"),a(this).jqmData("amount")*-1)})}})})(jQuery); \ No newline at end of file diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.customflip.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.customflip.js new file mode 100644 index 000000000..fce6e73f1 --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.customflip.js @@ -0,0 +1,1659 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +/* CORE Functions */ + +(function($) { + $.widget( "mobile.datebox", $.mobile.widget, { + options: { + // All widget options, including some internal runtime details + version: '2-1.4.0-2013070300', // jQMMajor.jQMMinor.DBoxMinor-YrMoDaySerial + mobVer: parseInt($.mobile.version.replace(/\./g,'')), + theme: false, + themeDefault: 'a', + themeHeader: 'a', + mode: false, + + centerHoriz: false, + centerVert: false, + transition: 'pop', + useAnimation: true, + hideInput: false, + hideFixedToolbars: false, + + lockInput: true, + enhanceInput: true, + + zindex: '500', + clickEvent: 'vclick', + clickEventAlt: 'click', + resizeListener: true, + + defaultValue: false, + showInitialValue: false, + + dialogEnable: false, + dialogForce: false, + enablePopup: false, + + popupPosition: false, + popupForceX: false, + popupForceY: false, + + useModal: false, + useInline: false, + useInlineBlind: false, + useHeader: true, + useImmediate: false, + useNewStyle: false, + useAltIcon: false, + overrideStyleClass: false, + + useButton: true, + useFocus: false, + useClearButton: false, + useCollapsedBut: false, + usePlaceholder: false, + + openCallback: false, + openCallbackArgs: [], + closeCallback: false, + closeCallbackArgs: [], + + startOffsetYears: false, + startOffsetMonths: false, + startOffsetDays: false, + afterToday: false, + beforeToday: false, + notToday: false, + maxDays: false, + minDays: false, + maxYear: false, + minYear: false, + blackDates: false, + blackDatesRec: false, + blackDays: false, + minHour: false, + maxHour: false, + minuteStep: 1, + minuteStepRound: 0, + + rolloverMode: { 'm': true, 'd': true, 'h': true, 'i': true, 's': true }, + + useLang: 'default', + lang: { + 'default' : { + setDateButtonLabel: 'Set Date', + setTimeButtonLabel: 'Set Time', + setDurationButtonLabel: 'Set Duration', + calTodayButtonLabel: 'Jump to Today', + titleDateDialogLabel: 'Set Date', + titleTimeDialogLabel: 'Set Time', + daysOfWeek: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], + daysOfWeekShort: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], + monthsOfYear: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], + monthsOfYearShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + durationLabel: ['Days', 'Hours', 'Minutes', 'Seconds'], + durationDays: ['Day', 'Days'], + timeFormat: 24, + headerFormat: '%A, %B %-d, %Y', + tooltip: 'Open Date Picker', + nextMonth: 'Next Month', + prevMonth: 'Previous Month', + dateFieldOrder: ['m', 'd', 'y'], + timeFieldOrder: ['h', 'i', 'a'], + slideFieldOrder: ['y', 'm', 'd'], + dateFormat: '%Y-%m-%d', + useArabicIndic: false, + isRTL: false, + calStartDay: 0, + clearButton: 'Clear', + durationOrder: ['d', 'h', 'i', 's'], + meridiem: ['AM', 'PM'], + timeOutput: '%k:%M', //{ '12': '%l:%M %p', '24': '%k:%M' }, + durationFormat: '%Dd %DA, %Dl:%DM:%DS', + calDateListLabel: 'Other Dates', + calHeaderFormat: '%B %Y' + } + } + }, + _enhanceDate: function() { + $.extend(this._date.prototype, { + copy: function(adjust, override) { + /* Get a modified copy of the date. + * First array - Offset the new date by # (position determines date part) + * Second array - If non-zero, force the new date by # (position determines date part) + */ + if ( typeof adjust === 'undefined' ) { adjust = [0,0,0,0,0,0,0]; } + if ( typeof override === 'undefined' ) { override = [0,0,0,0,0,0,0]; } + while ( adjust.length < 7 ) { adjust.push(0); } + while ( override.length < 7 ) { override.push(0); } + return new Date( + ((override[0] > 0 ) ? override[0] : this.getFullYear() + adjust[0]), + ((override[1] > 0 ) ? override[1] : this.getMonth() + adjust[1]), + ((override[2] > 0 ) ? override[2] : this.getDate() + adjust[2]), + ((override[3] > 0 ) ? override[3] : this.getHours() + adjust[3]), + ((override[4] > 0 ) ? override[4] : this.getMinutes() + adjust[4]), + ((override[5] > 0 ) ? override[5] : this.getSeconds() + adjust[5]), + ((override[6] > 0 ) ? override[5] : this.getMilliseconds() + adjust[6])); + }, + adj: function (type, amount) { + /* Adjust the date. Yes, this is chainable */ + if ( typeof amount !== 'number' ) { + throw new Error("Adjustment value not specified"); + } + if ( typeof type !== 'number' ) { + throw new Error("Adjustment type not specified"); + } + switch ( type ) { + case 0: this.setFullYear(this.getFullYear() + amount); break; + case 1: this.setMonth(this.getMonth() + amount); break; + case 2: this.setDate(this.getDate() + amount); break; + case 3: this.setHours(this.getHours() + amount); break; + case 4: this.setMinutes(this.getMinutes() + amount); break; + case 5: this.setSeconds(this.getSeconds() + amount); break; + case 6: this.setMilliseconds(this.getMilliseconds() + amount); break; + } + return this; + }, + setD: function(type, amount) { + /* A chainable version of setWhatever() */ + switch ( type ) { + case 0: this.setFullYear(amount); break; + case 1: this.setMonth(amount); break; + case 2: this.setDate(amount); break; + case 3: this.setHours(amount); break; + case 4: this.setMinutes(amount); break; + case 5: this.setSeconds(amount); break; + case 6: this.setMilliseconds(amount); break; + } + return this; + }, + get: function(type) { + switch ( type ) { + case 0: return this.getFullYear(); + case 1: return this.getMonth(); + case 2: return this.getDate(); + case 3: return this.getHours(); + case 4: return this.getMinutes(); + case 5: return this.getSeconds(); + } + return false; + }, + iso: function() { + return String(this.getFullYear()) + '-' + (( this.getMonth() < 9 ) ? "0" : "") + String(this.getMonth()+1) + '-' + ((this.getDate() < 10 ) ? "0" : "") + String(this.getDate()); + }, + comp: function () { + return parseInt(this.iso().replace(/-/g,''),10); + }, + getEpoch: function() { + return (this.getTime() - this.getMilliseconds()) / 1000; + }, + getArray: function() { + return [this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds()]; + }, + setFirstDay: function (day) { + this.setD(2,1).adj(2, (day - this.getDay())); + if ( this.get(2) > 10 ) { this.adj(2,7); } + return this; + }, + setDWeek: function (type,num) { + if ( type === 4 ) { + return this.setD(1,0).setD(2,1).setFirstDay(4).adj(2,-3).adj(2,(num-1)*7); + } + return this.setD(1,0).setD(2,1).setFirstDay(type).adj(2,(num-1)*7); + }, + getDWeek: function (type) { + var t1, t2; + + switch ( type ) { + case 0: + t1 = this.copy([0,-1*this.getMonth()]).setFirstDay(0); + return Math.floor((this.getTime() - ( t1.getTime() + (( this.getTimezoneOffset() - t1.getTimezoneOffset()) * 60000))) / 6048e5) + 1; + //return Math.floor((this.getTime() - t1.getTime()) / 6048e5) + 1; + case 1: + t1 = this.copy([0,-1*this.getMonth()]).setFirstDay(1); + return Math.floor((this.getTime() - ( t1.getTime() + (( this.getTimezoneOffset() - t1.getTimezoneOffset()) * 60000))) / 6048e5) + 1; + //return Math.floor((this.getTime() - t1.getTime()) / 6048e5) + 1; + case 4: + // this line is some bullshit. but it does work. + // (trap for dec 29, 30, or 31st being in the new year's week - these are the + // only 3 that can possibly fall like this) + if ( this.getMonth() === 11 && this.getDate() > 28 ) { return 1; } + + t1 = this.copy([0,-1*this.getMonth()],true).setFirstDay(4).adj(2,-3); + t2 = Math.floor((this.getTime() - ( t1.getTime() + (( this.getTimezoneOffset() - t1.getTimezoneOffset()) * 60000))) / 6048e5) + 1; + + if ( t2 < 1 ) { + t1 = this.copy([-1,-1*this.getMonth()]).setFirstDay(4).adj(2,-3); + return Math.floor((this.getTime() - t1.getTime()) / 6048e5) + 1; + } + return t2; + default: + return 0; + } + } + }); + }, + _event: function(e, p) { + var w = $(this).data(parseInt($.mobile.version.replace(/\./g,''),10) > 110 ? 'mobile-datebox' : 'datebox'); + if ( ! e.isPropagationStopped() ) { + switch (p.method) { + case 'close': + w.close(); break; + case 'open': + w.open(); break; + case 'set': + $(this).val(p.value); + $(this).trigger('change'); + break; + case 'doset': + if ( $.isFunction(w['_'+w.options.mode+'DoSet']) ) { + w['_'+w.options.mode+'DoSet'].apply(w,[]); + } else { + $(this).trigger('datebox', {'method':'set', 'value':w._formatter(w.__fmt(), w.theDate), 'date':w.theDate}); + } + break; + case 'dooffset': + if (p.type) { w._offset(p.type, p.amount, true); } break; + case 'dorefresh': + w.refresh(); break; + case 'doreset': + w.hardreset(); break; + case 'doclear': + $(this).val('').trigger('change'); break; + case 'clear': + $(this).trigger('change'); + } + } + }, + _hoover: function(item) { + // Hover toggle class, for calendar + $(item).toggleClass('ui-btn-up-'+$(item).jqmData('theme')+' ui-btn-down-'+$(item).jqmData('theme')); + }, + _ord: { + 'default': function (num) { + // Return an ordinal suffix (1st, 2nd, 3rd, etc) + var ending = num % 10; + if ( num > 9 && num < 21 ) { return 'th'; } + if ( ending > 3 ) { return 'th'; } + return ['th','st','nd','rd'][ending]; + } + }, + __ : function(val) { + var o = this.options, + oride = 'override' + val.charAt(0).toUpperCase() + val.slice(1); + + if ( typeof o[oride] !== 'undefined' ) { return o[oride]; } + if ( typeof o.lang[o.useLang][val] !== 'undefined' ) { return o.lang[o.useLang][val]; } + if ( typeof o[o.mode+'lang'] !== 'undefined' && typeof o[o.mode+'lang'][val] !== 'undefined' ) { return o[o.mode+'lang'][val]; } + return o.lang['default'][val]; + }, + __fmt: function() { + var w = this, + o = this.options; + + switch ( o.mode ) { + case 'timebox': + case 'timeflipbox': + return w.__('timeOutput'); + case 'durationbox': + case 'durationflipbox': + return w.__('durationFormat'); + default: + return w.__('dateFormat'); + } + }, + _zPad: function(number) { + return (( number < 10 ) ? '0' + String(number) : String(number)); + }, + _dRep: function(oper, direction) { + var start = 48, + end = 57, + adder = 1584, + i = null, + ch = null, + newd = ''; + + if ( direction === -1 ) { + start += adder; + end += adder; + adder = -1584; + } + + for ( i=0; i= start && ch <= end ) { + newd = newd + String.fromCharCode(ch+adder); + } else { + newd = newd + String.fromCharCode(ch); + } + } + + return newd; + }, + _doIndic: function() { + var w = this; + + w.d.intHTML.find('*').each(function() { + if ( $(this).children().length < 1 ) { + $(this).text(w._dRep($(this).text())); + } else if ( $(this).hasClass('ui-datebox-slideday') ) { + $(this).html(w._dRep($(this).html())); + } + }); + w.d.intHTML.find('input').each(function() { + $(this).val(w._dRep($(this).val())); + }); + }, + _parser: { + 'default': function (str) { return false; } + }, + _n: function (val,def) { + return ( val < 0 ) ? def : val; + }, + _pa: function (arr,date) { + if ( typeof date === 'boolean' ) { return new this._date(arr[0],arr[1],arr[2],0,0,0,0); } + return new this._date(date.getFullYear(), date.getMonth(), date.getDate(), arr[0], arr[1], arr[2], 0); + }, + _makeDate: function (str) { + // Date Parser + str = $.trim(((this.__('useArabicIndic') === true)?this._dRep(str, -1):str)); + var w = this, + o = this.options, + adv = w.__fmt(), + exp_input = null, + exp_names = [], + exp_format = null, + exp_temp = null, + date = new w._date(), + d = { year: -1, mont: -1, date: -1, hour: -1, mins: -1, secs: -1, week: false, wtyp: 4, wday: false, yday: false, meri: 0 }, + i; + + if ( typeof o.mode === 'undefined' ) { return date; } + if ( typeof w._parser[o.mode] !== 'undefined' ) { return w._parser[o.mode].apply(w,[str]); } + + if ( o.mode === 'durationbox' || o.mode === 'durationflipbox' ) { + adv = adv.replace(/%D([a-z])/gi, function(match, oper) { + switch (oper) { + case 'd': + case 'l': + case 'M': + case 'S': return '(' + match + '|' +'[0-9]+' + ')'; + default: return '.+?'; + } + }); + + adv = new RegExp('^' + adv + '$'); + exp_input = adv.exec(str); + exp_format = adv.exec(w.__fmt()); + + if ( exp_input === null || exp_input.length !== exp_format.length ) { + if ( typeof o.defaultValue === "number" && o.defaultValue > 0 ) { + return new w._date((w.initDate.getEpoch() + parseInt(o.defaultValue,10))*1000); + } + return new w._date(w.initDate.getTime()); + } + + exp_temp = w.initDate.getEpoch(); + for ( i=0; i -1 ) { d.mont = exp_temp; } + break; + case 'B': + exp_temp = $.inArray(exp_input[i], w.__('monthsOfYear')); + if ( exp_temp > -1 ) { d.mont = exp_temp; } + break; + } + } + if ( d.meri !== 0 ) { + if ( d.meri === -1 && d.hour === 12 ) { d.hour = 0; } + if ( d.meri === 1 && d.hour !== 12 ) { d.hour = d.hour + 12; } + } + + date = new w._date(w._n(d.year,0),w._n(d.mont,0),w._n(d.date,1),w._n(d.hour,0),w._n(d.mins,0),w._n(d.secs,0),0); + + if ( d.year < 100 && d.year !== -1 ) { date.setFullYear(d.year); } + + if ( ( d.mont > -1 && d.date > -1 ) || ( d.hour > -1 && d.mins > -1 && d.secs > -1 ) ) { return date; } + + if ( d.week !== false ) { + date.setDWeek(d.wtyp, d.week); + if ( d.date > -1 ) { date.setDate(d.date); } + } + if ( d.yday !== false ) { date.setD(1,0).setD(2,1).adj(2,(d.yday-1)); } + if ( d.wday !== false ) { date.adj(2,(d.wday - date.getDay())); } + } + return date; + }, + _customformat: { + 'default': function(oper, date) { return false; } + }, + _formatter: function(format, date) { + var w = this, + o = this.options, tmp, + dur = { + part: [0,0,0,0], tp: 0 + }; + + if ( o.mode === 'durationbox' || o.mode === 'durationflipbox' ) { + dur.tp = this.theDate.getEpoch() - this.initDate.getEpoch(); + dur.part[0] = parseInt( dur.tp / (60*60*24),10); dur.tp -=(dur.part[0]*60*60*24); // Days + dur.part[1] = parseInt( dur.tp / (60*60),10); dur.tp -= (dur.part[1]*60*60); // Hours + dur.part[2] = parseInt( dur.tp / (60),10); dur.tp -= (dur.part[2]*60); // Minutes + dur.part[3] = dur.tp; // Seconds + + if ( ! format.match(/%Dd/) ) { dur.part[1] += (dur.part[0]*24);} + if ( ! format.match(/%Dl/) ) { dur.part[2] += (dur.part[1]*60);} + if ( ! format.match(/%DM/) ) { dur.part[3] += (dur.part[2]*60);} + } + + format = format.replace(/%(D|X|0|-)*([1-9a-zA-Z])/g, function(match, pad, oper) { + if ( pad === 'X' ) { + if ( typeof w._customformat[o.mode] !== 'undefined' ) { return w._customformat[o.mode](oper, date, o); } + return match; + } + if ( pad === 'D' ) { + switch ( oper ) { + case 'd': return dur.part[0]; + case 'l': return w._zPad(dur.part[1]); + case 'M': return w._zPad(dur.part[2]); + case 'S': return w._zPad(dur.part[3]); + case 'A': return ((dur.part[0] > 1)?w.__('durationDays')[1]:w.__('durationDays')[0]); + default: return match; + } + } + switch ( oper ) { + case '%': // Literal % + return '%'; + case 'a': // Short Day + return w.__('daysOfWeekShort')[date.getDay()]; + case 'A': // Full Day of week + return w.__('daysOfWeek')[date.getDay()]; + case 'b': // Short month + return w.__('monthsOfYearShort')[date.getMonth()]; + case 'B': // Full month + return w.__('monthsOfYear')[date.getMonth()]; + case 'C': // Century + return date.getFullYear().toString().substr(0,2); + case 'd': // Day of month + return (( pad === '-' ) ? date.getDate() : w._zPad(date.getDate())); + case 'H': // Hour (01..23) + case 'k': + return (( pad === '-' ) ? date.getHours() : w._zPad(date.getHours())); + case 'I': // Hour (01..12) + case 'l': + return (( pad === '-' ) ? ((date.getHours() === 0 || date.getHours() === 12)?12:((date.getHours()<12)?date.getHours():(date.getHours()-12))) : w._zPad(((date.getHours() === 0 || date.getHours() === 12)?12:((date.getHours()<12)?date.getHours():date.getHours()-12)))); + case 'm': // Month + return (( pad === '-' ) ? date.getMonth()+1 : w._zPad(date.getMonth()+1)); + case 'M': // Minutes + return (( pad === '-' ) ? date.getMinutes() : w._zPad(date.getMinutes())); + case 'p': // AM/PM (ucase) + return ((date.getHours() < 12)?w.__('meridiem')[0].toUpperCase():w.__('meridiem')[1].toUpperCase()); + case 'P': // AM/PM (lcase) + return ((date.getHours() < 12)?w.__('meridiem')[0].toLowerCase():w.__('meridiem')[1].toLowerCase()); + case 's': // Unix Seconds + return date.getEpoch(); + case 'S': // Seconds + return (( pad === '-' ) ? date.getSeconds() : w._zPad(date.getSeconds())); + case 'u': // Day of week (1-7) + return (( pad === '-' ) ? date.getDay() + 1 : w._zPad(date.getDay() + 1)); + case 'w': // Day of week + return date.getDay(); + case 'y': // Year (2 digit) + return date.getFullYear().toString().substr(2,2); + case 'Y': // Year (4 digit) + return date.getFullYear(); + case 'E': // BE (Buddist Era, 4 Digit) + return date.getFullYear() + 543; + case 'V': + return (( pad === '-' ) ? date.getDWeek(4) : w._zPad(date.getDWeek(4))); + case 'U': + return (( pad === '-' ) ? date.getDWeek(0) : w._zPad(date.getDWeek(0))); + case 'W': + return (( pad === '-' ) ? date.getDWeek(1) : w._zPad(date.getDWeek(1))); + case 'o': // Ordinals + if ( typeof w._ord[o.useLang] !== 'undefined' ) { return w._ord[o.useLang](date.getDate()); } + return w._ord['default'](date.getDate()); + case 'j': + tmp = new Date(date.getFullYear(),0,1); + tmp = Math.ceil((date - tmp) / 86400000)+1; + return (( tmp < 100 ) ? (( tmp < 10 )? '00' : '0') : '' ) + String(tmp); + case 'G': + if ( date.getDWeek(4) === 1 && date.getMonth() > 0 ) { return date.getFullYear() + 1; } + if ( date.getDWeek(4) > 51 && date.getMonth() < 11 ) { return date.getFullYear() - 1; } + return date.getFullYear(); + case 'g': + if ( date.getDWeek(4) === 1 && date.getMonth() > 0 ) { return parseInt(date.getFullYear().toString().substr(2,2),10) + 1; } + if ( date.getDWeek(4) > 51 && date.getMonth() < 11 ) { return parseInt(date.getFullYear().toString().substr(2,2),10) - 1; } + return date.getFullYear().toString().substr(2,2); + default: + return match; + } + }); + + if ( w.__('useArabicIndic') === true ) { + format = w._dRep(format); + } + + return format; + }, + _btwn: function(value, low, high) { + return ( value > low && value < high ); + }, + _minStepFix: function() { + var tempMin = this.theDate.get(4), tmp, + w = this, + o = this.options; + + if ( o.minuteStep > 1 && tempMin % o.minuteStep > 0 ) { + if ( o.minuteStepRound < 0 ) { + tempMin = tempMin - (tempMin % o.minuteStep); + } else if ( o.minStepRound > 0 ) { + tempMin = tempMin + ( o.minuteStep - ( tempMin % o.minuteStep ) ); + } else { + if ( tempMin % o.minuteStep < o.minuteStep / 2 ) { + tempMin = tempMin - (tempMin % o.minuteStep); + } else { + tempMin = tempMin + ( o.minuteStep - ( tempMin % o.minuteStep ) ); + } + } + w.theDate.setMinutes(tempMin); + } + }, + _offset: function(mode, amount, update) { + // Compute a date/time offset. + // update = false to prevent controls refresh + var w = this, + o = this.options, + ok = false; + + mode = (mode || "").toLowerCase(); + + if ( typeof(update) === "undefined" ) { update = true; } + w.d.input.trigger('datebox', {'method':'offset', 'type':mode, 'amount':amount}); + + if ( mode !== 'a' && ( typeof o.rolloverMode[mode] === 'undefined' || o.rolloverMode[mode] === true )) { + ok = $.inArray(mode, ['y','m','d','h','i','s']); + } else { + switch(mode) { + case 'y': ok = 0; break; + case 'm': + if ( w._btwn(w.theDate.getMonth()+amount,-1,12) ) { ok = 1; } + break; + case 'd': + if ( w._btwn(w.theDate.getDate() + amount,0,(32 - w.theDate.copy([0],[0,0,32,13]).getDate() + 1) )) { ok = 2; } + break; + case 'h': + if ( w._btwn(w.theDate.getHours() + amount,-1,24) ) { ok = 3; } + break; + case 'i': + if ( w._btwn(w.theDate.getMinutes() + amount,-1,60) ) { ok = 4; } + break; + case 's': + if ( w._btwn(w.theDate.getSeconds() + amount,-1,60) ) { ok = 5; } + break; + case 'a': + w._offset('h',((amount>0)?1:-1)*12,false); + break; + } + } + if ( ok !== false ) { w.theDate.adj(ok,amount); } + if ( update === true ) { w.refresh(); } + if ( o.useImmediate ) { w.d.input.trigger('datebox', {'method':'doset'}); } + }, + _startOffset: function(date) { + var o = this.options; + + if ( o.startOffsetYears !== false ) { + date.adj(0, o.startOffsetYears); + } + if ( o.startOffsetMonths !== false ) { + date.adj(1, o.startOffsetMonths); + } + if ( o.startOffsetDays !== false ) { + date.adj(2, o.startOffsetDays); + } + return date; + }, + _create: function() { + // Create the widget, called automatically by widget system + $( document ).trigger( "dateboxcreate" ); + + var w = this, + o = $.extend(this.options, (typeof this.element.jqmData('options') !== 'undefined') ? this.element.jqmData('options') : this._getLongOptions(this.element) ), + thisTheme = ( o.theme === false && typeof($(this).jqmData('theme')) === 'undefined' ) ? + ( ( typeof(this.element.parentsUntil(':jqmData(theme)').parent().jqmData('theme')) === 'undefined' ) ? + o.themeDefault : this.element.parentsUntil(':jqmData(theme)').parent().jqmData('theme') ) + : o.theme, + trans = o.useAnimation ? o.transition : 'none', + d = o.useNewStyle === false ? { + input: this.element, + wrap: this.element.wrap('
').parent(), + mainWrap: $("
", { "class": 'ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden '+trans+' ui-body-'+thisTheme} ).css('zIndex', o.zindex), + intHTML: false + } : { + input: this.element, + wrap: this.element, + mainWrap: $("
", { "class": 'ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden '+trans+' ui-body-'+thisTheme} ).css('zIndex', o.zindex), + intHTML: false + }, + touch = ( typeof window.ontouchstart !== 'undefined' ), + drag = { + eStart : (touch ? 'touchstart' : 'mousedown')+'.datebox', + eMove : (touch ? 'touchmove' : 'mousemove')+'.datebox', + eEnd : (touch ? 'touchend' : 'mouseup')+'.datebox', + eEndA : (touch ? 'mouseup.datebox touchend.datebox touchcancel.datebox touchmove.datebox' : 'mouseup.datebox'), + move : false, + start : false, + end : false, + pos : false, + target : false, + delta : false, + tmp : false + }, + calc = { }, + ns = (typeof $.mobile.ns !== 'undefined')?$.mobile.ns:''; + + $.extend(w, {d: d, ns: ns, drag: drag, touch:touch}); + + if ( o.usePlaceholder !== false ) { + if ( o.usePlaceholder === true && w._grabLabel() !== false ) { w.d.input.attr('placeholder', w._grabLabel()); } + if ( typeof o.usePlaceholder === 'string' ) { w.d.input.attr('placeholder', o.usePlaceholder); } + } + + o.theme = thisTheme; + + w.clearFunc = false; + w.disabled = false; + w.runButton = false; + w._date = window.Date; + w._enhanceDate(); + w.baseID = w.d.input.attr('id'); + + w.initDate = new w._date(); + w.theDate = (o.defaultValue) ? w._makeDate(o.defaultValue) : ( (w.d.input.val() !== "") ? w._makeDate(w.d.input.val()) : new w._date() ); + w.initDone = false; + + if ( o.showInitialValue === true ) { + w.d.input.val(w._formatter(w.__fmt(), w.theDate)); + } + + if ( o.useButton === true && o.useInline === false && o.useNewStyle === false ) { + w.d.open = $(''+this.__('tooltip')+'') + .on(o.clickEvent, function(e) { + e.preventDefault(); + if ( !w.disabled ) { w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.parent().addClass('ui-focus'); w.d.input.parent().removeClass('ui-focus'); } + setTimeout( function() { $(e.target).closest('a').removeClass($.mobile.activeBtnClass); }, 300); + }).appendTo(w.d.wrap).buttonMarkup({icon: 'grid', iconpos: 'notext', corners:true, shadow:true}) + .css({'vertical-align': 'middle', 'display': 'inline-block'}); + } + + w.d.screen = $("
", {'class':'ui-datebox-screen ui-datebox-hidden'+((o.useModal)?' ui-datebox-screen-modal':'')}) + .css({'z-index': o.zindex-1}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.trigger('datebox', {'method':'close'}); + }); + + if ( o.enhanceInput === true && navigator.userAgent.match(/Android/i) ){ + w.inputType = 'number'; + } else { + w.inputType = 'text'; + } + + if ( o.hideInput ) { w.d.wrap.parent().hide(); } + + if ( o.mobVer < 140 ) { + $('label[for=\''+w.d.input.attr('id')+'\']').addClass('ui-input-text').css('verticalAlign', 'middle'); + } + + w.d.wrap.on(o.clickEvent, function() { + if ( !w.disabled && ( o.noButtonFocusMode || o.focusMode ) ) { + w.d.input.trigger('datebox', {'method': 'open'}); + w.d.wrap.addClass('ui-focus'); + w.d.input.removeClass('ui-focus'); + } + }); + + w.d.input + .removeClass('ui-corner-all ui-shadow-inset') + .bind(w.touch?'touchend':'click', function(e){ + if ( w.disabled === false && o.useNewStyle === true && o.useFocus === false ) { + if ( ((w.touch ? e.originalEvent.changedTouches[0].pageX : e.pageX) - e.target.offsetLeft) > (e.target.offsetWidth - 20) ) { + w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.parent().addClass('ui-focus'); w.d.input.removeClass('ui-focus'); + //setTimeout(function(){w.d.wrap.addClass('ui-focus');}, 200); + } + } + }) + .focus(function(){ + if ( w.disabled === false && o.useFocus === true ) { + w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.addClass('ui-focus'); w.d.input.removeClass('ui-focus'); + if ( o.useNewStyle === false ) { w.d.input.parent().removeClass('ui-focus'); w.d.wrap.parent().addClass('ui-focus'); } + } + if ( o.useNewStyle === false ) { w.d.input.removeClass('ui-focus'); } + }) + .blur(function(){ + w.d.wrap.removeClass('ui-focus'); + w.d.input.removeClass('ui-focus'); + }) + .change(function() { + w.theDate = w._makeDate(w.d.input.val()); + w.refresh(); + }) + .attr("readonly", o.lockInput) + .on('datebox', w._event); + + if ( o.useNewStyle === true ) { + w.d.input.addClass('ui-corner-all '+((o.useAltIcon===true)?'ui-icon-datebox-alt':'ui-icon-datebox')); + if ( o.overrideStyleClass !== false ) { w.d.input.addClass(o.overrideStyleClass); } + } else { + w.d.input.parent().css('border', 'none').removeClass('ui-shadow-inset'); + } + + w.d.wrap.parent().on(o.clickEvent, function() { + if ( !w.disabled && o.useFocus === true && o.useNewStyle === false ) { + w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.addClass('ui-focus'); w.d.input.removeClass('ui-focus'); + setTimeout(function(){ + w.d.wrap.removeClass('ui-focus'); + w.d.wrap.parent().addClass('ui-focus'); + }, 500); + } + }); + + // Check if mousewheel plugin is loaded + if ( typeof $.event.special.mousewheel !== 'undefined' ) { w.wheelExists = true; } + + // Disable when done if element attribute disabled is true. + if ( w.d.input.is(':disabled') ) { + w.disable(); + } + + if ( o.useInline === true || o.useInlineBlind ) { w.open(); } + + w.applyMinMax(false, false); + + //Throw dateboxinit event + $( document ).trigger( "dateboxaftercreate" ); + }, + applyMinMax: function(refresh, override) { + var w = this, + o = this.options, + calc = {}; + + if ( typeof refresh === 'undefined' ) { refresh = false; } + if ( typeof override === 'undefined' ) { override = true; } + + if ( ( override === true || o.minDays === false ) && typeof(w.d.input.attr('min')) !== 'undefined' ) { + calc.today = new w._date(); + calc.lod = 24 * 60 * 60 * 1000; + calc.todayc = new w._date(calc.today.getFullYear(), calc.today.getMonth(), calc.today.getDate(), 0,0,0,0); + calc.fromel = w.d.input.attr('min').split('-'); + calc.compdt = new w._date(calc.fromel[0],calc.fromel[1]-1,calc.fromel[2],0,0,0,0); + o.minDays = parseInt((((calc.compdt.getTime() - calc.todayc.getTime()) / calc.lod))*-1,10); + } + if ( ( override === true || o.maxDays === false ) && typeof(w.d.input.attr('max')) !== 'undefined' ) { + calc.today = new w._date(); + calc.lod = 24 * 60 * 60 * 1000; + calc.todayc = new w._date(calc.today.getFullYear(), calc.today.getMonth(), calc.today.getDate(), 0,0,0,0); + calc.fromel = w.d.input.attr('max').split('-'); + calc.compdt = new w._date(calc.fromel[0],calc.fromel[1]-1,calc.fromel[2],0,0,0,0); + o.maxDays = parseInt((((calc.compdt.getTime() - calc.todayc.getTime()) / calc.lod)),10); + } + + if ( refresh === true ) { w.refresh(); } + }, + _build: { + 'default': function () { + this.d.headerText = "Error"; + this.d.intHTML = $("

There is no mode by that name loaded / mode not given

"); + } + }, + _applyCoords: function(e) { + var w = e.widget, + o = e.widget.options, + fixd = { + h: $.mobile.activePage.find('.ui-header').jqmData('position'), + f: $.mobile.activePage.find('.ui-footer').jqmData('position'), + fh: $.mobile.activePage.find('.ui-footer').outerHeight(), + hh: $.mobile.activePage.find('.ui-header').outerHeight() + }, + iput = { + x: w.d.wrap.offset().left + (w.d.wrap.outerWidth() / 2), + y: w.d.wrap.offset().top + (w.d.wrap.outerHeight() / 2) + }, + size = { + w: w.d.mainWrap.outerWidth(), + h: w.d.mainWrap.outerHeight() + }, + doc = { + t: $(window).scrollTop(), + h: $(window).height(), + w: $.mobile.activePage.width(), + ah: $(document).height() + }, + pos = { + y: (o.centerVert) ? doc.t + ((doc.h / 2) - (size.h / 2)) : iput.y - ( size.h / 2 ), + x: (doc.w < 400 || o.centerHoriz ) ? (doc.w / 2) - (size.w /2) : iput.x - (size.w / 2) + }; + + if ( o.centerVert === false ) { + if ( o.hideFixedToolbars === true && ( typeof fixd.f !== 'undefined' || typeof fixd.h !== 'undefined' )) { + $.mobile.activePage.find(":jqmData(position='fixed')").fixedtoolbar('hide'); + fixd.f = undefined; + fixd.h = undefined; + } + + if ( typeof fixd.f !== 'undefined' ) { + if ( ( pos.y + size.h ) > ( doc.h - fixd.fh - 2 ) ) { + pos.y = doc.h - fixd.fh - 2 - size.h; + } + } else { + if ( ( pos.y + size.h ) > ( doc.ah - fixd.fh - 2 ) ) { + pos.y = doc.ah - fixd.fh - 2 - size.h; + } + if ( ( doc.h + doc.t ) < ( size.h + pos.y + 2 ) ) { + pos.y = doc.h + doc.t - size.h - 2; + } + } + + if ( typeof fixd.h !== 'undefined' ) { + if ( ( doc.t + fixd.hh + 2 ) > pos.y ) { + pos.y = doc.t + fixd.hh + 2; + } + } else { + if ( fixd.hh + 2 > pos.y ) { + pos.y = fixd.hh + 2; + } + if ( pos.y < doc.t + 2 ) { + pos.y = doc.t + 2; + } + } + } + w.d.mainWrap.css({'position': 'absolute', 'top': pos.y, 'left': pos.x}); + }, + _drag: { + 'default': function () { return false; } + }, + open: function () { + var w = this, + o = this.options, + popopts = {}, + basepop = {'history':false}, + qns = 'data-'+this.ns, + trans = o.useAnimation ? o.transition : 'none'; + + if ( o.useFocus === true && w.fastReopen === true ) { w.d.input.blur(); return false; } + if ( w.clearFunc !== false ) { + clearTimeout(w.clearFunc); w.clearFunc = false; + } + + // Call the open callback if provided. Additionally, if this + // returns false then the open/update will stop. + if ( o.openCallback !== false ) { + if ( ! $.isFunction(o.openCallback) ) { + if ( typeof window[o.openCallback] !== 'undefined' ) { + o.openCallback = window[o.openCallback]; + } else { + o.openCallback = new Function(o.openCallback); + } + } + if ( o.openCallback.apply(w, $.merge([w.theDate],o.openCallbackArgs)) === false ) { return false; } + } + + w.theDate = w._makeDate(w.d.input.val()); + if ( w.d.input.val() === "" ) { w._startOffset(w.theDate); } + w.d.input.blur(); + + if ( typeof w._build[o.mode] === 'undefined' ) { + w._build['default'].apply(w,[]); + } else { + w._build[o.mode].apply(w,[]); + } + if ( typeof w._drag[o.mode] !== 'undefined' ) { + w._drag[o.mode].apply(w, []); + } + w.d.input.trigger('datebox', {'method':'refresh'}); + if ( w.__('useArabicIndic') === true ) { w._doIndic(); } + + if ( ( o.useInline === true || o.useInlineBlind === true ) && w.initDone === false ) { + w.d.mainWrap.append(w.d.intHTML); + w.d.input.parent().parent().append(w.d.mainWrap); + w.d.mainWrap.removeClass('ui-datebox-hidden'); + if ( o.useInline === true ) { + w.d.mainWrap.addClass('ui-datebox-inline'); + } else { + w.d.mainWrap.addClass('ui-datebox-inlineblind'); + w.d.mainWrap.hide(); + } + w.initDone = false; + w.d.input.trigger('datebox',{'method':'postrefresh'}); + } + + if ( o.useImmediate ) { w.d.input.trigger('datebox', {'method':'doset'}); } + if ( o.useInline ) { return true; } + if ( o.useInlineBlind ) { + if ( w.initDone ) { w.d.mainWrap.slideDown(); } + else { w.initDone = true; } + return true; + } + if ( w.d.intHTML.is(':visible') ) { return false; } // Ignore if already open + + if ( o.enablePopup === true ) { + w.d.dialogPage = false; + w.d.mainWrap.empty(); + if ( o.useHeader === true ) { + w.d.headHTML = $('
'); + $("Close").appendTo(w.d.headHTML) + .buttonMarkup({ theme : o.themeHeader, icon : 'delete', iconpos: 'notext', corners: true, shadow : true }) + .on(o.clickEventAlt, function(e) { e.preventDefault(); w.d.input.trigger('datebox', {'method':'close'}); }); + $('

'+w.d.headerText+'

').appendTo(w.d.headHTML); + w.d.mainWrap.append(w.d.headHTML); + } + w.d.mainWrap.append(w.d.intHTML).css('zIndex', o.zindex); + w.d.input.trigger('datebox',{'method':'postrefresh'}); + + if ( o.useAnimation === true ) { + popopts.transition = o.transition; + } else { + popopts.transition = "none"; + } + + if ( o.popupForceX !== false && o.popupForceY !== false ) { + popopts.x = o.popupForceX; + popopts.y = o.popupForceY; + } + + if ( o.popupPosition !== false ) { + popopts.positionTo = o.popupPosition; + } else { + if ( typeof w.baseID !== undefined ) { + popopts.positionTo = '#' + w.baseID; + } else { + popopts.positionTo = 'window'; + } + } + + if ( o.useModal === true ) { basepop.overlayTheme = "a"; } + + w.d.mainWrap.removeClass('ui-datebox-hidden').popup(basepop).popup("open", popopts); + w.refresh(); + } else { + if ( o.dialogForce || ( o.dialogEnable && window.width() < 400 ) ) { + w.d.dialogPage = $("
" + + "
" + + "

"+w.d.headerText+"

") + .appendTo( $.mobile.pageContainer ) + .page().css('minHeight', '0px').addClass(trans); + w.d.dialogPage.find('.ui-header').find('a').off('click vclick').on(o.clickEventAlt, function(e) { e.preventDefault(); w.d.input.trigger('datebox', {'method':'close'}); }); + w.d.mainWrap.append(w.d.intHTML).css({'marginLeft':'auto', 'marginRight':'auto'}).removeClass('ui-datebox-hidden'); + w.d.dialogPage.find('.ui-content').append(w.d.mainWrap); + w.d.input.trigger('datebox',{'method':'postrefresh'}); + $.mobile.activePage.off( "pagehide.remove" ); + $.mobile.changePage(w.d.dialogPage, {'transition': trans}); + } else { + w.d.dialogPage = false; + w.d.mainWrap.empty(); + if ( o.useHeader === true ) { + w.d.headHTML = $('
'); + $("Close").appendTo(w.d.headHTML) + .buttonMarkup({ theme : o.themeHeader, icon : 'delete', iconpos: 'notext', corners: true, shadow : true }) + .on(o.clickEventAlt, function(e) { e.preventDefault(); w.d.input.trigger('datebox', {'method':'close'}); }); + $('

'+w.d.headerText+'

').appendTo(w.d.headHTML); + w.d.mainWrap.append(w.d.headHTML); + } + w.d.mainWrap.append(w.d.intHTML).css('zIndex', o.zindex); + w.d.mainWrap.appendTo($.mobile.activePage); + w.d.screen.appendTo($.mobile.activePage); + w.d.input.trigger('datebox',{'method':'postrefresh'}); + w._applyCoords({widget:w}); + + if ( o.useModal === true ) { + if(o.useAnimation) { + w.d.screen.fadeIn('slow'); + } else { + w.d.screen.show(); + } + } else { + setTimeout(function () { w.d.screen.removeClass('ui-datebox-hidden');}, 500); + } + + w.d.mainWrap.addClass('ui-overlay-shadow in').removeClass('ui-datebox-hidden'); + + $(document).on('orientationchange.datebox', {widget:w}, function(e) { w._applyCoords(e.data); }); + if ( o.resizeListener === true ) { + $(window).on('resize.datebox', {widget:w}, function (e) { w._applyCoords(e.data); }); + } + } + } + }, + close: function() { + var w = this, + o = this.options; + + if ( o.useInlineBlind === true ) { w.d.mainWrap.slideUp(); return true;} + if ( o.useInline === true || w.d.intHTML === false ) { return true; } + + if ( w.d.dialogPage !== false ) { + $(w.d.dialogPage).dialog('close'); + + if ( ! $.mobile.activePage.jqmData('mobile-page').options.domCache ) { + $.mobile.activePage.on('pagehide.remove', function () { $(this).remove(); }); + } + + w.d.intHTML.detach().empty(); + w.d.mainWrap.detach().empty(); + w.d.wrap.removeClass('ui-focus'); + w.clearFunc = setTimeout(function () { w.d.dialogPage.empty().remove(); w.clearFunc = false; }, 1500); + } else { + if ( o.enablePopup === true ) { + w.d.mainWrap.popup('close'); + w.d.wrap.removeClass('ui-focus'); + } else { + if ( o.useModal ) { + if(o.useAnimation) { + w.d.screen.fadeOut('slow'); + } else { + w.d.screen.hide(); + } + } else { + w.d.screen.addClass('ui-datebox-hidden'); + } + w.d.screen.detach(); + w.d.mainWrap.addClass('ui-datebox-hidden').removeAttr('style').removeClass('in ui-overlay-shadow').empty().detach(); + w.d.intHTML.detach(); + w.d.wrap.removeClass('ui-focus'); + + $(document).off('orientationchange.datebox'); + if ( o.resizeListener === true ) { + $(window).off('resize.datebox'); + } + } + } + w.d.wrap.parent().removeClass('ui-focus'); + + $(document).off(w.drag.eMove); + $(document).off(w.drag.eEnd); + $(document).off(w.drag.eEndA); + + if ( o.useFocus ) { + w.fastReopen = true; + setTimeout(function(t) { return function () { t.fastReopen = false; };}(w), 300); + } + + if ( o.closeCallback !== false ) { + if ( ! $.isFunction(o.closeCallback) ) { + if ( typeof window[o.closeCallback] !== 'undefined' ) { + o.closeCallback = window[o.closeCallback]; + } else { + o.closeCallback = new Function(o.closeCallback); + } + } + o.closeCallback.apply(w, $.merge([w.theDate], o.closeCallbackArgs)); + } + }, + refresh: function() { + if ( typeof this._build[this.options.mode] === 'undefined' ) { + this._build['default'].apply(this,[]); + } else { + this._build[this.options.mode].apply(this,[]); + } + if ( this.__('useArabicIndic') === true ) { this._doIndic(); } + this.d.mainWrap.append(this.d.intHTML); + this.d.input.trigger('datebox',{'method':'postrefresh'}); + }, + _check: function() { + var w = this, + td = null, + o = this.options; + + w.dateOK = true; + + if ( o.afterToday !== false ) { + td = new w._date(); + if ( w.theDate < td ) { w.theDate = td; } + } + if ( o.beforeToday !== false ) { + td = new w._date(); + if ( w.theDate > td ) { w.theDate = td; } + } + if ( o.maxDays !== false ) { + td = new w._date(); + td.adj(2, o.maxDays); + if ( w.theDate > td ) { w.theDate = td; } + } + if ( o.minDays !== false ) { + td = new w._date(); + td.adj(2, -1*o.minDays); + if ( w.theDate < td ) { w.theDate = td; } + } + if ( o.minHour !== false ) { + if ( w.theDate.getHours() < o.minHour ) { + w.theDate.setHours(o.minHour); + } + } + if ( o.maxHour !== false ) { + if ( w.theDate.getHours() > o.maxHour ) { + w.theDate.setHours(o.maxHour); + } + } + if ( o.maxYear !== false ) { + td = new w._date(o.maxYear, 0, 1); + td.adj(2, -1); + if ( w.theDate > td ) { w.theDate = td; } + } + if ( o.minYear !== false ) { + td = new w._date(o.minYear, 0, 1); + if ( w.theDate < td ) { w.theDate = td; } + } + + if ( $.inArray(o.mode, ['timebox','durationbox','durationflipbox','timeflipbox']) > -1 ) { + if ( o.mode === 'timeflipbox' && o.validHours !== false ) { + if ( $.inArray(w.theDate.getHours(), o.validHours) < 0 ) { w.dateOK = false; } + } + } else { + if ( o.blackDatesRec !== false ) { + for ( i=0; i -1 ) { w.dateOK = false; } + } + if ( o.blackDays !== false ) { + if ( $.inArray(w.theDate.getDay(), o.blackDays) > -1 ) { w.dateOK = false; } + } + } + }, + _grabLabel: function() { + var w = this, + o = this.options; + + if ( typeof o.overrideDialogLabel === 'undefined' ) { + if ( typeof w.d.input.attr('placeholder') !== 'undefined' ) { return w.d.input.attr('placeholder'); } + if ( typeof w.d.input.attr('title') !== 'undefined' ) { return w.d.input.attr('title'); } + if ( w.d.wrap.parent().find('label[for=\''+w.d.input.attr('id')+'\']').text() !== '' ) { + return w.d.wrap.parent().find('label[for=\''+w.d.input.attr('id')+'\']').text(); + } + return false; + } + return o.overrideDialogLabel; + }, + _makeEl: function(source, parts) { + var part = false, + retty = false; + + retty = source.clone(); + + if ( typeof parts.attr !== 'undefined' ) { + for ( part in parts.attr ) { + if ( parts.attr.hasOwnProperty(part) ) { + retty.jqmData(part, parts.attr[part]); + } + } + } + return retty; + }, + _getLongOptions: function(element) { + var key, retty = {}, prefix, temp; + + if ( $.mobile.ns === "" ) { + prefix = "datebox"; + } else { + prefix = $.mobile.ns.substr(0, $.mobile.ns.length - 1) + 'Datebox'; + } + + for ( key in element.data() ) { + if ( key.substr(0, prefix.length) === prefix && key.length > prefix.length ) { + temp = key.substr(prefix.length); + temp = temp.charAt(0).toLowerCase() + temp.slice(1); + retty[temp] = element.data(key); + } + } + return retty; + }, + disable: function(){ + // Disable the element + this.d.input.attr("disabled",true); + this.d.wrap.addClass("ui-disabled").blur(); + this.disabled = true; + this.d.input.trigger('datebox', {'method':'disable'}); + }, + enable: function(){ + // Enable the element + this.d.input.attr("disabled", false); + this.d.wrap.removeClass("ui-disabled"); + this.disabled = false; + this.d.input.trigger('datebox', {'method':'enable'}); + }, + _setOption: function() { + $.Widget.prototype._setOption.apply( this, arguments ); + this.refresh(); + }, + getTheDate: function() { + return this.theDate; + }, + getLastDur: function() { + return this.lastDuration; + }, + setTheDate: function(newDate) { + this.theDate = newDate; + this.refresh(); + }, + callFormat: function(format, date) { + return this._formatter(format, date); + } + }); + + // Degrade date inputs to text inputs, suppress standard UI functions. + $( document ).on( "pagebeforecreate", function( e ) { + $( ":jqmData(role='datebox')", e.target ).each(function() { + $(this).prop('type', 'text'); + }); + }); + // Automatically bind to data-role='datebox' items. + $( document ).on( "pagecreate create", function( e ){ + $( document ).trigger( "dateboxbeforecreate" ); + $( ":jqmData(role='datebox')", e.target ).each(function() { + var defed = typeof ($(this).data(parseInt($.mobile.version.replace(/\./g,''),10) > 111 ? 'mobile-datebox' : 'datebox')); + if ( defed === "undefined" ) { + $(this).datebox(); + } + }); + }); +})( jQuery ); +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +/* CUSTOMFLIP Mode */ + +(function($) { + $.extend( $.mobile.datebox.prototype.options, { + themeOptPick: 'b', + themeOpt: 'a', + useSetButton: true, + customData: [ + {'input': true, 'name':'Letter', 'data':['a','b','c','d','e']}, + {'input': true, 'name':'Text', 'data':['some','bull','shtuff','here']}, + {'input': false, 'name':'Image', 'data':['','','','']} + ], + customDefault: [0,0,0], + customFormat: false, + customfliplang: { + // This structure interfaces with __() -> if it exists, strings are looked up here after i8n fails, + // and before going to 'default' - the name syntax is lang + 'customSet':'Looks Good' + } + }); + $.extend( $.mobile.datebox.prototype, { + '_customflipDoSet': function () { + // If this function exists, it overrides the 'doset' method of the 'datebox' event. + // The name syntax is _DoSet + var w = this, o = this.options; + if ( typeof w.customCurrent === 'undefined' ) { w.customCurrent = this._makeDate(this.d.input.val()); } + w.d.input.trigger('datebox', {'method':'set', 'value':w._formatter(o.customFormat,w.customCurrent), 'date':w.customCurrent}); + }, + '_cubox_offset': function (fld, amount) { + // This is *not* an automatic override, used below specificly. + var w = this, x, + o = this.options; + + tmp = (w.customCurrent[fld] + amount) % o.customData[fld]['data'].length; + if ( tmp < 0 ) { tmp = o.customData[fld]['data'].length + tmp; } + + w.customCurrent[fld] = tmp; + if ( o.useImmediate ) { w.d.input.trigger('datebox', {'method':'set', 'value':w._formatter(o.customFormat,w.customCurrent), 'date':w.customCurrent}); } + w.refresh(); + }, + '_cubox_arr': function (data, choice) { + var base = data, x, + before = data.slice(0,choice), + after = data.slice(choice+1); + + while ( before.length < 10 ) { + for ( x = base.length; x > 0; x-- ) { + before.unshift(base[x-1]); + } + } + while ( before.length > 10 ) { + before.shift(); + } + + while ( after.length < 10 ) { + for ( x = 0; x < base.length; x++ ) { + after.push(base[x]); + } + } + after.length = 10; + + before.push(data[choice]); + + return $.merge($.merge([], before), after); + }, + '_cubox_pos': function () { + var w = this, + ech = null, + top = null, + par = this.d.intHTML.find('.ui-datebox-flipcontent').innerHeight(), + tot = null; + + w.d.intHTML.find('.ui-datebox-flipcenter').each(function() { + ech = $(this); + top = ech.innerHeight(); + ech.css('top', ((par/2)-(top/2)+4)*-1); + }); + w.d.intHTML.find('ul').each(function () { + ech = $(this); + par = ech.parent().innerHeight(); + top = ech.find('li').first(); + tot = ech.find('li').size() * top.outerHeight(); + top.css('marginTop', ((tot/2)-(par/2)+(top.outerHeight()/2))*-1); + }); + } + }); + $.extend( $.mobile.datebox.prototype._parser, { + // If this stucture exists, it is called instead of the usual date input parser. + // The name of the structure is the same as the mode name - it recieves a string + // as the input, which is the current value of the input element, pre-sanitized + 'customflip' : function ( str ) { + var w = this, + o = this.options, + adv = o.customFormat, + exp_input, exp_format, tmp, tmp2, retty_val=[0,0,0,0,0,0]; + + if ( typeof(adv) !== 'string' ) { adv = ''; } + + adv = adv.replace(/%X([0-9a-f])/gi, function(match, oper) { + switch (oper) { + case 'a': + case 'b': + case 'c': + case 'd': + case 'e': + case 'f': + return '(' + match + '|' + '.+?' + ')'; break; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + return '(' + match + '|' + '[0-9]+' + ')'; break; + default: + return '.+?'; + } + }); + + adv = new RegExp('^' + adv + '$'); + exp_input = adv.exec(str); + exp_format = adv.exec(o.customFormat); + + if ( exp_input !== null ) { + for ( var x = 1; x - it recieves the single letter operater, and the current "date" value + 'customflip' : function ( oper, val, o ) { + var per = parseInt(oper), tmp; + + if ( typeof(per) === 'number' && !isNaN(per) ) { + return val[oper-1]; + } else { + tmp = $.inArray(oper, ['a','b','c','d','e','f']); + return o.customData[tmp].data[val[tmp]]; + } + } + }); + $.extend( $.mobile.datebox.prototype._build, { + // This builds the actual interface, and is called on *every* refresh. (after each "movement") + 'customflip': function () { + var w = this, + o = this.options, i, y, hRow, tmp, lineArr, + uid = 'ui-datebox-', + customCurrent = this._makeDate(this.d.input.val()), + flipBase = $("
    "), + ctrl = $("
    ", {"class":uid+'flipcontent'}); + + if ( typeof w.customCurrent === "undefined" ) { w.customCurrent = customCurrent; } + + if ( o.customFormat === false ) { + tmp = []; + for ( i = 0; i'); + + w.fldOrder = o.tireFieldOrder; + + tmp = $('
    '); + for ( y=0; y'+o.customData[y]['name']+'
    ').css('textAlign','center').appendTo(tmp); + } + tmp.appendTo(w.d.intHTML); + + w.d.intHTML.append(ctrl); + + for ( y=0; y', {'class':'ui-body-'+tmp}) + .html(''+lineArr[i]+'').appendTo(hRow.find('ul')); + } + hRow.appendTo(ctrl); + } + + $("
    ", {"class":uid+'flipcenter ui-overlay-shadow'}).css('pointerEvents', 'none').appendTo(w.d.intHTML); + + if ( o.useSetButton ) { + y = $('
    ', {'class':uid+'controls'}); + + if ( o.useSetButton ) { + $(''+w.__('customSet')+'') + .appendTo(y).buttonMarkup({theme: o.theme, icon: 'check', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.trigger('datebox', {'method':'set', 'value':w._formatter(o.customFormat,w.customCurrent), 'date':w.tireChoice}); + w.d.input.trigger('datebox', {'method':'close'}); + }); + } + y.appendTo(w.d.intHTML); + } + + if ( w.wheelExists ) { // Mousewheel operation, if plugin is loaded + w.d.intHTML.on('mousewheel', '.ui-overlay-shadow', function(e,d) { + e.preventDefault(); + w._cubox_offset($(this).jqmData('field'), ((d<0)?1:-1)*$(this).jqmData('amount')); + }); + } + + w.d.intHTML.on(w.drag.eStart, 'ul', function(e,f) { + if ( !w.drag.move ) { + if ( typeof f !== "undefined" ) { e = f; } + w.drag.move = true; + w.drag.target = $(this).find('li').first(); + w.drag.pos = parseInt(w.drag.target.css('marginTop').replace(/px/i, ''),10); + w.drag.start = w.touch ? e.originalEvent.changedTouches[0].pageY : e.pageY; + w.drag.end = false; + e.stopPropagation(); + e.preventDefault(); + } + }); + + w.d.intHTML.on(w.drag.eStart, '.'+uid+'flipcenter', function(e) { // Used only on old browsers and IE. + if ( !w.drag.move ) { + w.drag.target = w.touch ? e.originalEvent.changedTouches[0].pageX - $(e.currentTarget).offset().left : e.pageX - $(e.currentTarget).offset().left; + w.drag.tmp = w.d.intHTML.find('.'+uid+'flipcenter').innerWidth() / (( $.inArray('a', w.fldOrder) > -1 && w.__('timeFormat') !== 12 )?w.fldOrder.length-1:w.fldOrder.length); + $(w.d.intHTML.find('ul').get(parseInt(w.drag.target / w.drag.tmp,10))).trigger(w.drag.eStart,e); + } + }); + } + }); + $.extend( $.mobile.datebox.prototype._drag, { + // This contains the code that the drag and drop (or touch move) code uses + 'customflip': function() { + var w = this, + o = this.options, + g = this.drag; + + $(document).on(g.eMove, function(e) { + if ( g.move && o.mode === 'customflip' ) { + g.end = w.touch ? e.originalEvent.changedTouches[0].pageY : e.pageY; + g.target.css('marginTop', (g.pos + g.end - g.start) + 'px'); + e.preventDefault(); + e.stopPropagation(); + return false; + } + }); + + $(document).on(g.eEnd, function(e) { + if ( g.move && o.mode === 'customflip' ) { + g.move = false; + if ( g.end !== false ) { + e.preventDefault(); + e.stopPropagation(); + g.tmp = g.target.parent().parent(); + w._cubox_offset(g.tmp.jqmData('field'), (parseInt((g.start - g.end) / g.target.innerHeight(),10) * g.tmp.jqmData('amount'))); + } + g.start = false; + g.end = false; + } + }); + } + }); +})( jQuery ); diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.customflip.min.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.customflip.min.js new file mode 100644 index 000000000..3f3677020 --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.customflip.min.js @@ -0,0 +1,7 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +(function(a){a.widget("mobile.datebox",a.mobile.widget,{options:{version:"2-1.4.0-2013070300",mobVer:parseInt(a.mobile.version.replace(/\./g,"")),theme:false,themeDefault:"a",themeHeader:"a",mode:false,centerHoriz:false,centerVert:false,transition:"pop",useAnimation:true,hideInput:false,hideFixedToolbars:false,lockInput:true,enhanceInput:true,zindex:"500",clickEvent:"vclick",clickEventAlt:"click",resizeListener:true,defaultValue:false,showInitialValue:false,dialogEnable:false,dialogForce:false,enablePopup:false,popupPosition:false,popupForceX:false,popupForceY:false,useModal:false,useInline:false,useInlineBlind:false,useHeader:true,useImmediate:false,useNewStyle:false,useAltIcon:false,overrideStyleClass:false,useButton:true,useFocus:false,useClearButton:false,useCollapsedBut:false,usePlaceholder:false,openCallback:false,openCallbackArgs:[],closeCallback:false,closeCallbackArgs:[],startOffsetYears:false,startOffsetMonths:false,startOffsetDays:false,afterToday:false,beforeToday:false,notToday:false,maxDays:false,minDays:false,maxYear:false,minYear:false,blackDates:false,blackDatesRec:false,blackDays:false,minHour:false,maxHour:false,minuteStep:1,minuteStepRound:0,rolloverMode:{m:true,d:true,h:true,i:true,s:true},useLang:"default",lang:{"default":{setDateButtonLabel:"Set Date",setTimeButtonLabel:"Set Time",setDurationButtonLabel:"Set Duration",calTodayButtonLabel:"Jump to Today",titleDateDialogLabel:"Set Date",titleTimeDialogLabel:"Set Time",daysOfWeek:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],daysOfWeekShort:["Su","Mo","Tu","We","Th","Fr","Sa"],monthsOfYear:["January","February","March","April","May","June","July","August","September","October","November","December"],monthsOfYearShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],durationLabel:["Days","Hours","Minutes","Seconds"],durationDays:["Day","Days"],timeFormat:24,headerFormat:"%A, %B %-d, %Y",tooltip:"Open Date Picker",nextMonth:"Next Month",prevMonth:"Previous Month",dateFieldOrder:["m","d","y"],timeFieldOrder:["h","i","a"],slideFieldOrder:["y","m","d"],dateFormat:"%Y-%m-%d",useArabicIndic:false,isRTL:false,calStartDay:0,clearButton:"Clear",durationOrder:["d","h","i","s"],meridiem:["AM","PM"],timeOutput:"%k:%M",durationFormat:"%Dd %DA, %Dl:%DM:%DS",calDateListLabel:"Other Dates",calHeaderFormat:"%B %Y"}}},_enhanceDate:function(){a.extend(this._date.prototype,{copy:function(c,b){if(typeof c==="undefined"){c=[0,0,0,0,0,0,0]}if(typeof b==="undefined"){b=[0,0,0,0,0,0,0]}while(c.length<7){c.push(0)}while(b.length<7){b.push(0)}return new Date(((b[0]>0)?b[0]:this.getFullYear()+c[0]),((b[1]>0)?b[1]:this.getMonth()+c[1]),((b[2]>0)?b[2]:this.getDate()+c[2]),((b[3]>0)?b[3]:this.getHours()+c[3]),((b[4]>0)?b[4]:this.getMinutes()+c[4]),((b[5]>0)?b[5]:this.getSeconds()+c[5]),((b[6]>0)?b[5]:this.getMilliseconds()+c[6]))},adj:function(c,b){if(typeof b!=="number"){throw new Error("Adjustment value not specified")}if(typeof c!=="number"){throw new Error("Adjustment type not specified")}switch(c){case 0:this.setFullYear(this.getFullYear()+b);break;case 1:this.setMonth(this.getMonth()+b);break;case 2:this.setDate(this.getDate()+b);break;case 3:this.setHours(this.getHours()+b);break;case 4:this.setMinutes(this.getMinutes()+b);break;case 5:this.setSeconds(this.getSeconds()+b);break;case 6:this.setMilliseconds(this.getMilliseconds()+b);break}return this},setD:function(c,b){switch(c){case 0:this.setFullYear(b);break;case 1:this.setMonth(b);break;case 2:this.setDate(b);break;case 3:this.setHours(b);break;case 4:this.setMinutes(b);break;case 5:this.setSeconds(b);break;case 6:this.setMilliseconds(b);break}return this},get:function(b){switch(b){case 0:return this.getFullYear();case 1:return this.getMonth();case 2:return this.getDate();case 3:return this.getHours();case 4:return this.getMinutes();case 5:return this.getSeconds()}return false},iso:function(){return String(this.getFullYear())+"-"+((this.getMonth()<9)?"0":"")+String(this.getMonth()+1)+"-"+((this.getDate()<10)?"0":"")+String(this.getDate())},comp:function(){return parseInt(this.iso().replace(/-/g,""),10)},getEpoch:function(){return(this.getTime()-this.getMilliseconds())/1000},getArray:function(){return[this.getFullYear(),this.getMonth(),this.getDate(),this.getHours(),this.getMinutes(),this.getSeconds()]},setFirstDay:function(b){this.setD(2,1).adj(2,(b-this.getDay()));if(this.get(2)>10){this.adj(2,7)}return this},setDWeek:function(c,b){if(c===4){return this.setD(1,0).setD(2,1).setFirstDay(4).adj(2,-3).adj(2,(b-1)*7)}return this.setD(1,0).setD(2,1).setFirstDay(c).adj(2,(b-1)*7)},getDWeek:function(c){var d,b;switch(c){case 0:d=this.copy([0,-1*this.getMonth()]).setFirstDay(0);return Math.floor((this.getTime()-(d.getTime()+((this.getTimezoneOffset()-d.getTimezoneOffset())*60000)))/604800000)+1;case 1:d=this.copy([0,-1*this.getMonth()]).setFirstDay(1);return Math.floor((this.getTime()-(d.getTime()+((this.getTimezoneOffset()-d.getTimezoneOffset())*60000)))/604800000)+1;case 4:if(this.getMonth()===11&&this.getDate()>28){return 1}d=this.copy([0,-1*this.getMonth()],true).setFirstDay(4).adj(2,-3);b=Math.floor((this.getTime()-(d.getTime()+((this.getTimezoneOffset()-d.getTimezoneOffset())*60000)))/604800000)+1;if(b<1){d=this.copy([-1,-1*this.getMonth()]).setFirstDay(4).adj(2,-3);return Math.floor((this.getTime()-d.getTime())/604800000)+1}return b;default:return 0}}})},_event:function(d,c){var b=a(this).data(parseInt(a.mobile.version.replace(/\./g,""),10)>110?"mobile-datebox":"datebox");if(!d.isPropagationStopped()){switch(c.method){case"close":b.close();break;case"open":b.open();break;case"set":a(this).val(c.value);a(this).trigger("change");break;case"doset":if(a.isFunction(b["_"+b.options.mode+"DoSet"])){b["_"+b.options.mode+"DoSet"].apply(b,[])}else{a(this).trigger("datebox",{method:"set",value:b._formatter(b.__fmt(),b.theDate),date:b.theDate})}break;case"dooffset":if(c.type){b._offset(c.type,c.amount,true)}break;case"dorefresh":b.refresh();break;case"doreset":b.hardreset();break;case"doclear":a(this).val("").trigger("change");break;case"clear":a(this).trigger("change")}}},_hoover:function(b){a(b).toggleClass("ui-btn-up-"+a(b).jqmData("theme")+" ui-btn-down-"+a(b).jqmData("theme"))},_ord:{"default":function(c){var b=c%10;if(c>9&&c<21){return"th"}if(b>3){return"th"}return["th","st","nd","rd"][b]}},__:function(d){var c=this.options,b="override"+d.charAt(0).toUpperCase()+d.slice(1);if(typeof c[b]!=="undefined"){return c[b]}if(typeof c.lang[c.useLang][d]!=="undefined"){return c.lang[c.useLang][d]}if(typeof c[c.mode+"lang"]!=="undefined"&&typeof c[c.mode+"lang"][d]!=="undefined"){return c[c.mode+"lang"][d]}return c.lang["default"][d]},__fmt:function(){var b=this,c=this.options;switch(c.mode){case"timebox":case"timeflipbox":return b.__("timeOutput");case"durationbox":case"durationflipbox":return b.__("durationFormat");default:return b.__("dateFormat")}},_zPad:function(b){return((b<10)?"0"+String(b):String(b))},_dRep:function(j,g){var h=48,b=57,c=1584,d=null,e=null,f="";if(g===-1){h+=c;b+=c;c=-1584}for(d=0;d=h&&e<=b){f=f+String.fromCharCode(e+c)}else{f=f+String.fromCharCode(e)}}return f},_doIndic:function(){var b=this;b.d.intHTML.find("*").each(function(){if(a(this).children().length<1){a(this).text(b._dRep(a(this).text()))}else{if(a(this).hasClass("ui-datebox-slideday")){a(this).html(b._dRep(a(this).html()))}}});b.d.intHTML.find("input").each(function(){a(this).val(b._dRep(a(this).val()))})},_parser:{"default":function(b){return false}},_n:function(c,b){return(c<0)?b:c},_pa:function(b,c){if(typeof c==="boolean"){return new this._date(b[0],b[1],b[2],0,0,0,0)}return new this._date(c.getFullYear(),c.getMonth(),c.getDate(),b[0],b[1],b[2],0)},_makeDate:function(k){k=a.trim(((this.__("useArabicIndic")===true)?this._dRep(k,-1):k));var n=this,c=this.options,e=n.__fmt(),m=null,h=[],l=null,b=null,f=new n._date(),j={year:-1,mont:-1,date:-1,hour:-1,mins:-1,secs:-1,week:false,wtyp:4,wday:false,yday:false,meri:0},g;if(typeof c.mode==="undefined"){return f}if(typeof n._parser[c.mode]!=="undefined"){return n._parser[c.mode].apply(n,[k])}if(c.mode==="durationbox"||c.mode==="durationflipbox"){e=e.replace(/%D([a-z])/gi,function(d,o){switch(o){case"d":case"l":case"M":case"S":return"("+d+"|[0-9]+)";default:return".+?"}});e=new RegExp("^"+e+"$");m=e.exec(k);l=e.exec(n.__fmt());if(m===null||m.length!==l.length){if(typeof c.defaultValue==="number"&&c.defaultValue>0){return new n._date((n.initDate.getEpoch()+parseInt(c.defaultValue,10))*1000)}return new n._date(n.initDate.getTime())}b=n.initDate.getEpoch();for(g=0;g-1){j.mont=b}break;case"B":b=a.inArray(m[g],n.__("monthsOfYear"));if(b>-1){j.mont=b}break}}if(j.meri!==0){if(j.meri===-1&&j.hour===12){j.hour=0}if(j.meri===1&&j.hour!==12){j.hour=j.hour+12}}f=new n._date(n._n(j.year,0),n._n(j.mont,0),n._n(j.date,1),n._n(j.hour,0),n._n(j.mins,0),n._n(j.secs,0),0);if(j.year<100&&j.year!==-1){f.setFullYear(j.year)}if((j.mont>-1&&j.date>-1)||(j.hour>-1&&j.mins>-1&&j.secs>-1)){return f}if(j.week!==false){f.setDWeek(j.wtyp,j.week);if(j.date>-1){f.setDate(j.date)}}if(j.yday!==false){f.setD(1,0).setD(2,1).adj(2,(j.yday-1))}if(j.wday!==false){f.adj(2,(j.wday-f.getDay()))}}return f},_customformat:{"default":function(c,b){return false}},_formatter:function(f,c){var b=this,g=this.options,d,e={part:[0,0,0,0],tp:0};if(g.mode==="durationbox"||g.mode==="durationflipbox"){e.tp=this.theDate.getEpoch()-this.initDate.getEpoch();e.part[0]=parseInt(e.tp/(60*60*24),10);e.tp-=(e.part[0]*60*60*24);e.part[1]=parseInt(e.tp/(60*60),10);e.tp-=(e.part[1]*60*60);e.part[2]=parseInt(e.tp/(60),10);e.tp-=(e.part[2]*60);e.part[3]=e.tp;if(!f.match(/%Dd/)){e.part[1]+=(e.part[0]*24)}if(!f.match(/%Dl/)){e.part[2]+=(e.part[1]*60)}if(!f.match(/%DM/)){e.part[3]+=(e.part[2]*60)}}f=f.replace(/%(D|X|0|-)*([1-9a-zA-Z])/g,function(h,j,k){if(j==="X"){if(typeof b._customformat[g.mode]!=="undefined"){return b._customformat[g.mode](k,c,g)}return h}if(j==="D"){switch(k){case"d":return e.part[0];case"l":return b._zPad(e.part[1]);case"M":return b._zPad(e.part[2]);case"S":return b._zPad(e.part[3]);case"A":return((e.part[0]>1)?b.__("durationDays")[1]:b.__("durationDays")[0]);default:return h}}switch(k){case"%":return"%";case"a":return b.__("daysOfWeekShort")[c.getDay()];case"A":return b.__("daysOfWeek")[c.getDay()];case"b":return b.__("monthsOfYearShort")[c.getMonth()];case"B":return b.__("monthsOfYear")[c.getMonth()];case"C":return c.getFullYear().toString().substr(0,2);case"d":return((j==="-")?c.getDate():b._zPad(c.getDate()));case"H":case"k":return((j==="-")?c.getHours():b._zPad(c.getHours()));case"I":case"l":return((j==="-")?((c.getHours()===0||c.getHours()===12)?12:((c.getHours()<12)?c.getHours():(c.getHours()-12))):b._zPad(((c.getHours()===0||c.getHours()===12)?12:((c.getHours()<12)?c.getHours():c.getHours()-12))));case"m":return((j==="-")?c.getMonth()+1:b._zPad(c.getMonth()+1));case"M":return((j==="-")?c.getMinutes():b._zPad(c.getMinutes()));case"p":return((c.getHours()<12)?b.__("meridiem")[0].toUpperCase():b.__("meridiem")[1].toUpperCase());case"P":return((c.getHours()<12)?b.__("meridiem")[0].toLowerCase():b.__("meridiem")[1].toLowerCase());case"s":return c.getEpoch();case"S":return((j==="-")?c.getSeconds():b._zPad(c.getSeconds()));case"u":return((j==="-")?c.getDay()+1:b._zPad(c.getDay()+1));case"w":return c.getDay();case"y":return c.getFullYear().toString().substr(2,2);case"Y":return c.getFullYear();case"E":return c.getFullYear()+543;case"V":return((j==="-")?c.getDWeek(4):b._zPad(c.getDWeek(4)));case"U":return((j==="-")?c.getDWeek(0):b._zPad(c.getDWeek(0)));case"W":return((j==="-")?c.getDWeek(1):b._zPad(c.getDWeek(1)));case"o":if(typeof b._ord[g.useLang]!=="undefined"){return b._ord[g.useLang](c.getDate())}return b._ord["default"](c.getDate());case"j":d=new Date(c.getFullYear(),0,1);d=Math.ceil((c-d)/86400000)+1;return((d<100)?((d<10)?"00":"0"):"")+String(d);case"G":if(c.getDWeek(4)===1&&c.getMonth()>0){return c.getFullYear()+1}if(c.getDWeek(4)>51&&c.getMonth()<11){return c.getFullYear()-1}return c.getFullYear();case"g":if(c.getDWeek(4)===1&&c.getMonth()>0){return parseInt(c.getFullYear().toString().substr(2,2),10)+1}if(c.getDWeek(4)>51&&c.getMonth()<11){return parseInt(c.getFullYear().toString().substr(2,2),10)-1}return c.getFullYear().toString().substr(2,2);default:return h}});if(b.__("useArabicIndic")===true){f=b._dRep(f)}return f},_btwn:function(d,b,c){return(d>b&&d1&&d%e.minuteStep>0){if(e.minuteStepRound<0){d=d-(d%e.minuteStep)}else{if(e.minStepRound>0){d=d+(e.minuteStep-(d%e.minuteStep))}else{if(d%e.minuteStep0)?1:-1)*12,false);break}}if(c!==false){b.theDate.adj(c,d)}if(g===true){b.refresh()}if(e.useImmediate){b.d.input.trigger("datebox",{method:"doset"})}},_startOffset:function(b){var c=this.options;if(c.startOffsetYears!==false){b.adj(0,c.startOffsetYears)}if(c.startOffsetMonths!==false){b.adj(1,c.startOffsetMonths)}if(c.startOffsetDays!==false){b.adj(2,c.startOffsetDays)}return b},_create:function(){a(document).trigger("dateboxcreate");var j=this,b=a.extend(this.options,(typeof this.element.jqmData("options")!=="undefined")?this.element.jqmData("options"):this._getLongOptions(this.element)),k=(b.theme===false&&typeof(a(this).jqmData("theme"))==="undefined")?((typeof(this.element.parentsUntil(":jqmData(theme)").parent().jqmData("theme"))==="undefined")?b.themeDefault:this.element.parentsUntil(":jqmData(theme)").parent().jqmData("theme")):b.theme,l=b.useAnimation?b.transition:"none",g=b.useNewStyle===false?{input:this.element,wrap:this.element.wrap('
    ').parent(),mainWrap:a("
    ",{"class":"ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden "+l+" ui-body-"+k}).css("zIndex",b.zindex),intHTML:false}:{input:this.element,wrap:this.element,mainWrap:a("
    ",{"class":"ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden "+l+" ui-body-"+k}).css("zIndex",b.zindex),intHTML:false},e=(typeof window.ontouchstart!=="undefined"),f={eStart:(e?"touchstart":"mousedown")+".datebox",eMove:(e?"touchmove":"mousemove")+".datebox",eEnd:(e?"touchend":"mouseup")+".datebox",eEndA:(e?"mouseup.datebox touchend.datebox touchcancel.datebox touchmove.datebox":"mouseup.datebox"),move:false,start:false,end:false,pos:false,target:false,delta:false,tmp:false},c={},h=(typeof a.mobile.ns!=="undefined")?a.mobile.ns:"";a.extend(j,{d:g,ns:h,drag:f,touch:e});if(b.usePlaceholder!==false){if(b.usePlaceholder===true&&j._grabLabel()!==false){j.d.input.attr("placeholder",j._grabLabel())}if(typeof b.usePlaceholder==="string"){j.d.input.attr("placeholder",b.usePlaceholder)}}b.theme=k;j.clearFunc=false;j.disabled=false;j.runButton=false;j._date=window.Date;j._enhanceDate();j.baseID=j.d.input.attr("id");j.initDate=new j._date();j.theDate=(b.defaultValue)?j._makeDate(b.defaultValue):((j.d.input.val()!=="")?j._makeDate(j.d.input.val()):new j._date());j.initDone=false;if(b.showInitialValue===true){j.d.input.val(j._formatter(j.__fmt(),j.theDate))}if(b.useButton===true&&b.useInline===false&&b.useNewStyle===false){j.d.open=a(''+this.__("tooltip")+"").on(b.clickEvent,function(d){d.preventDefault();if(!j.disabled){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.parent().addClass("ui-focus");j.d.input.parent().removeClass("ui-focus")}setTimeout(function(){a(d.target).closest("a").removeClass(a.mobile.activeBtnClass)},300)}).appendTo(j.d.wrap).buttonMarkup({icon:"grid",iconpos:"notext",corners:true,shadow:true}).css({"vertical-align":"middle",display:"inline-block"})}j.d.screen=a("
    ",{"class":"ui-datebox-screen ui-datebox-hidden"+((b.useModal)?" ui-datebox-screen-modal":"")}).css({"z-index":b.zindex-1}).on(b.clickEventAlt,function(d){d.preventDefault();j.d.input.trigger("datebox",{method:"close"})});if(b.enhanceInput===true&&navigator.userAgent.match(/Android/i)){j.inputType="number"}else{j.inputType="text"}if(b.hideInput){j.d.wrap.parent().hide()}if(b.mobVer<140){a("label[for='"+j.d.input.attr("id")+"']").addClass("ui-input-text").css("verticalAlign","middle")}j.d.wrap.on(b.clickEvent,function(){if(!j.disabled&&(b.noButtonFocusMode||b.focusMode)){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.addClass("ui-focus");j.d.input.removeClass("ui-focus")}});j.d.input.removeClass("ui-corner-all ui-shadow-inset").bind(j.touch?"touchend":"click",function(d){if(j.disabled===false&&b.useNewStyle===true&&b.useFocus===false){if(((j.touch?d.originalEvent.changedTouches[0].pageX:d.pageX)-d.target.offsetLeft)>(d.target.offsetWidth-20)){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.parent().addClass("ui-focus");j.d.input.removeClass("ui-focus")}}}).focus(function(){if(j.disabled===false&&b.useFocus===true){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.addClass("ui-focus");j.d.input.removeClass("ui-focus");if(b.useNewStyle===false){j.d.input.parent().removeClass("ui-focus");j.d.wrap.parent().addClass("ui-focus")}}if(b.useNewStyle===false){j.d.input.removeClass("ui-focus")}}).blur(function(){j.d.wrap.removeClass("ui-focus");j.d.input.removeClass("ui-focus")}).change(function(){j.theDate=j._makeDate(j.d.input.val());j.refresh()}).attr("readonly",b.lockInput).on("datebox",j._event);if(b.useNewStyle===true){j.d.input.addClass("ui-corner-all "+((b.useAltIcon===true)?"ui-icon-datebox-alt":"ui-icon-datebox"));if(b.overrideStyleClass!==false){j.d.input.addClass(b.overrideStyleClass)}}else{j.d.input.parent().css("border","none").removeClass("ui-shadow-inset")}j.d.wrap.parent().on(b.clickEvent,function(){if(!j.disabled&&b.useFocus===true&&b.useNewStyle===false){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.addClass("ui-focus");j.d.input.removeClass("ui-focus");setTimeout(function(){j.d.wrap.removeClass("ui-focus");j.d.wrap.parent().addClass("ui-focus")},500)}});if(typeof a.event.special.mousewheel!=="undefined"){j.wheelExists=true}if(j.d.input.is(":disabled")){j.disable()}if(b.useInline===true||b.useInlineBlind){j.open()}j.applyMinMax(false,false);a(document).trigger("dateboxaftercreate")},applyMinMax:function(e,d){var b=this,f=this.options,c={};if(typeof e==="undefined"){e=false}if(typeof d==="undefined"){d=true}if((d===true||f.minDays===false)&&typeof(b.d.input.attr("min"))!=="undefined"){c.today=new b._date();c.lod=24*60*60*1000;c.todayc=new b._date(c.today.getFullYear(),c.today.getMonth(),c.today.getDate(),0,0,0,0);c.fromel=b.d.input.attr("min").split("-");c.compdt=new b._date(c.fromel[0],c.fromel[1]-1,c.fromel[2],0,0,0,0);f.minDays=parseInt((((c.compdt.getTime()-c.todayc.getTime())/c.lod))*-1,10)}if((d===true||f.maxDays===false)&&typeof(b.d.input.attr("max"))!=="undefined"){c.today=new b._date();c.lod=24*60*60*1000;c.todayc=new b._date(c.today.getFullYear(),c.today.getMonth(),c.today.getDate(),0,0,0,0);c.fromel=b.d.input.attr("max").split("-");c.compdt=new b._date(c.fromel[0],c.fromel[1]-1,c.fromel[2],0,0,0,0);f.maxDays=parseInt((((c.compdt.getTime()-c.todayc.getTime())/c.lod)),10)}if(e===true){b.refresh()}},_build:{"default":function(){this.d.headerText="Error";this.d.intHTML=a("

    There is no mode by that name loaded / mode not given

    ")}},_applyCoords:function(h){var b=h.widget,j=h.widget.options,f={h:a.mobile.activePage.find(".ui-header").jqmData("position"),f:a.mobile.activePage.find(".ui-footer").jqmData("position"),fh:a.mobile.activePage.find(".ui-footer").outerHeight(),hh:a.mobile.activePage.find(".ui-header").outerHeight()},c={x:b.d.wrap.offset().left+(b.d.wrap.outerWidth()/2),y:b.d.wrap.offset().top+(b.d.wrap.outerHeight()/2)},d={w:b.d.mainWrap.outerWidth(),h:b.d.mainWrap.outerHeight()},g={t:a(window).scrollTop(),h:a(window).height(),w:a.mobile.activePage.width(),ah:a(document).height()},k={y:(j.centerVert)?g.t+((g.h/2)-(d.h/2)):c.y-(d.h/2),x:(g.w<400||j.centerHoriz)?(g.w/2)-(d.w/2):c.x-(d.w/2)};if(j.centerVert===false){if(j.hideFixedToolbars===true&&(typeof f.f!=="undefined"||typeof f.h!=="undefined")){a.mobile.activePage.find(":jqmData(position='fixed')").fixedtoolbar("hide");f.f=undefined;f.h=undefined}if(typeof f.f!=="undefined"){if((k.y+d.h)>(g.h-f.fh-2)){k.y=g.h-f.fh-2-d.h}}else{if((k.y+d.h)>(g.ah-f.fh-2)){k.y=g.ah-f.fh-2-d.h}if((g.h+g.t)<(d.h+k.y+2)){k.y=g.h+g.t-d.h-2}}if(typeof f.h!=="undefined"){if((g.t+f.hh+2)>k.y){k.y=g.t+f.hh+2}}else{if(f.hh+2>k.y){k.y=f.hh+2}if(k.y
    ');a("Close").appendTo(b.d.headHTML).buttonMarkup({theme:g.themeHeader,icon:"delete",iconpos:"notext",corners:true,shadow:true}).on(g.clickEventAlt,function(h){h.preventDefault();b.d.input.trigger("datebox",{method:"close"})});a('

    '+b.d.headerText+"

    ").appendTo(b.d.headHTML);b.d.mainWrap.append(b.d.headHTML)}b.d.mainWrap.append(b.d.intHTML).css("zIndex",g.zindex);b.d.input.trigger("datebox",{method:"postrefresh"});if(g.useAnimation===true){e.transition=g.transition}else{e.transition="none"}if(g.popupForceX!==false&&g.popupForceY!==false){e.x=g.popupForceX;e.y=g.popupForceY}if(g.popupPosition!==false){e.positionTo=g.popupPosition}else{if(typeof b.baseID!==undefined){e.positionTo="#"+b.baseID}else{e.positionTo="window"}}if(g.useModal===true){f.overlayTheme="a"}b.d.mainWrap.removeClass("ui-datebox-hidden").popup(f).popup("open",e);b.refresh()}else{if(g.dialogForce||(g.dialogEnable&&window.width()<400)){b.d.dialogPage=a("

    "+b.d.headerText+"

    ").appendTo(a.mobile.pageContainer).page().css("minHeight","0px").addClass(c);b.d.dialogPage.find(".ui-header").find("a").off("click vclick").on(g.clickEventAlt,function(h){h.preventDefault();b.d.input.trigger("datebox",{method:"close"})});b.d.mainWrap.append(b.d.intHTML).css({marginLeft:"auto",marginRight:"auto"}).removeClass("ui-datebox-hidden");b.d.dialogPage.find(".ui-content").append(b.d.mainWrap);b.d.input.trigger("datebox",{method:"postrefresh"});a.mobile.activePage.off("pagehide.remove");a.mobile.changePage(b.d.dialogPage,{transition:c})}else{b.d.dialogPage=false;b.d.mainWrap.empty();if(g.useHeader===true){b.d.headHTML=a('
    ');a("Close").appendTo(b.d.headHTML).buttonMarkup({theme:g.themeHeader,icon:"delete",iconpos:"notext",corners:true,shadow:true}).on(g.clickEventAlt,function(h){h.preventDefault();b.d.input.trigger("datebox",{method:"close"})});a('

    '+b.d.headerText+"

    ").appendTo(b.d.headHTML);b.d.mainWrap.append(b.d.headHTML)}b.d.mainWrap.append(b.d.intHTML).css("zIndex",g.zindex);b.d.mainWrap.appendTo(a.mobile.activePage);b.d.screen.appendTo(a.mobile.activePage);b.d.input.trigger("datebox",{method:"postrefresh"});b._applyCoords({widget:b});if(g.useModal===true){if(g.useAnimation){b.d.screen.fadeIn("slow")}else{b.d.screen.show()}}else{setTimeout(function(){b.d.screen.removeClass("ui-datebox-hidden")},500)}b.d.mainWrap.addClass("ui-overlay-shadow in").removeClass("ui-datebox-hidden");a(document).on("orientationchange.datebox",{widget:b},function(h){b._applyCoords(h.data)});if(g.resizeListener===true){a(window).on("resize.datebox",{widget:b},function(h){b._applyCoords(h.data)})}}}},close:function(){var b=this,c=this.options;if(c.useInlineBlind===true){b.d.mainWrap.slideUp();return true}if(c.useInline===true||b.d.intHTML===false){return true}if(b.d.dialogPage!==false){a(b.d.dialogPage).dialog("close");if(!a.mobile.activePage.jqmData("mobile-page").options.domCache){a.mobile.activePage.on("pagehide.remove",function(){a(this).remove()})}b.d.intHTML.detach().empty();b.d.mainWrap.detach().empty();b.d.wrap.removeClass("ui-focus");b.clearFunc=setTimeout(function(){b.d.dialogPage.empty().remove();b.clearFunc=false},1500)}else{if(c.enablePopup===true){b.d.mainWrap.popup("close");b.d.wrap.removeClass("ui-focus")}else{if(c.useModal){if(c.useAnimation){b.d.screen.fadeOut("slow")}else{b.d.screen.hide()}}else{b.d.screen.addClass("ui-datebox-hidden")}b.d.screen.detach();b.d.mainWrap.addClass("ui-datebox-hidden").removeAttr("style").removeClass("in ui-overlay-shadow").empty().detach();b.d.intHTML.detach();b.d.wrap.removeClass("ui-focus");a(document).off("orientationchange.datebox");if(c.resizeListener===true){a(window).off("resize.datebox")}}}b.d.wrap.parent().removeClass("ui-focus");a(document).off(b.drag.eMove);a(document).off(b.drag.eEnd);a(document).off(b.drag.eEndA);if(c.useFocus){b.fastReopen=true;setTimeout(function(d){return function(){d.fastReopen=false}}(b),300)}if(c.closeCallback!==false){if(!a.isFunction(c.closeCallback)){if(typeof window[c.closeCallback]!=="undefined"){c.closeCallback=window[c.closeCallback]}else{c.closeCallback=new Function(c.closeCallback)}}c.closeCallback.apply(b,a.merge([b.theDate],c.closeCallbackArgs))}},refresh:function(){if(typeof this._build[this.options.mode]==="undefined"){this._build["default"].apply(this,[])}else{this._build[this.options.mode].apply(this,[])}if(this.__("useArabicIndic")===true){this._doIndic()}this.d.mainWrap.append(this.d.intHTML);this.d.input.trigger("datebox",{method:"postrefresh"})},_check:function(){var b=this,d=null,c=this.options;b.dateOK=true;if(c.afterToday!==false){d=new b._date();if(b.theDated){b.theDate=d}}if(c.maxDays!==false){d=new b._date();d.adj(2,c.maxDays);if(b.theDate>d){b.theDate=d}}if(c.minDays!==false){d=new b._date();d.adj(2,-1*c.minDays);if(b.theDatec.maxHour){b.theDate.setHours(c.maxHour)}}if(c.maxYear!==false){d=new b._date(c.maxYear,0,1);d.adj(2,-1);if(b.theDate>d){b.theDate=d}}if(c.minYear!==false){d=new b._date(c.minYear,0,1);if(b.theDate-1){if(c.mode==="timeflipbox"&&c.validHours!==false){if(a.inArray(b.theDate.getHours(),c.validHours)<0){b.dateOK=false}}}else{if(c.blackDatesRec!==false){for(i=0;i-1){b.dateOK=false}}if(c.blackDays!==false){if(a.inArray(b.theDate.getDay(),c.blackDays)>-1){b.dateOK=false}}}},_grabLabel:function(){var b=this,c=this.options;if(typeof c.overrideDialogLabel==="undefined"){if(typeof b.d.input.attr("placeholder")!=="undefined"){return b.d.input.attr("placeholder")}if(typeof b.d.input.attr("title")!=="undefined"){return b.d.input.attr("title")}if(b.d.wrap.parent().find("label[for='"+b.d.input.attr("id")+"']").text()!==""){return b.d.wrap.parent().find("label[for='"+b.d.input.attr("id")+"']").text()}return false}return c.overrideDialogLabel},_makeEl:function(d,e){var b=false,c=false;c=d.clone();if(typeof e.attr!=="undefined"){for(b in e.attr){if(e.attr.hasOwnProperty(b)){c.jqmData(b,e.attr[b])}}}return c},_getLongOptions:function(d){var c,e={},f,b;if(a.mobile.ns===""){f="datebox"}else{f=a.mobile.ns.substr(0,a.mobile.ns.length-1)+"Datebox"}for(c in d.data()){if(c.substr(0,f.length)===f&&c.length>f.length){b=c.substr(f.length);b=b.charAt(0).toLowerCase()+b.slice(1);e[b]=d.data(c)}}return e},disable:function(){this.d.input.attr("disabled",true);this.d.wrap.addClass("ui-disabled").blur();this.disabled=true;this.d.input.trigger("datebox",{method:"disable"})},enable:function(){this.d.input.attr("disabled",false);this.d.wrap.removeClass("ui-disabled");this.disabled=false;this.d.input.trigger("datebox",{method:"enable"})},_setOption:function(){a.Widget.prototype._setOption.apply(this,arguments);this.refresh()},getTheDate:function(){return this.theDate},getLastDur:function(){return this.lastDuration},setTheDate:function(b){this.theDate=b;this.refresh()},callFormat:function(c,b){return this._formatter(c,b)}});a(document).on("pagebeforecreate",function(b){a(":jqmData(role='datebox')",b.target).each(function(){a(this).prop("type","text")})});a(document).on("pagecreate create",function(b){a(document).trigger("dateboxbeforecreate");a(":jqmData(role='datebox')",b.target).each(function(){var c=typeof(a(this).data(parseInt(a.mobile.version.replace(/\./g,""),10)>111?"mobile-datebox":"datebox"));if(c==="undefined"){a(this).datebox()}})})})(jQuery);(function(a){a.extend(a.mobile.datebox.prototype.options,{themeOptPick:"b",themeOpt:"a",useSetButton:true,customData:[{input:true,name:"Letter",data:["a","b","c","d","e"]},{input:true,name:"Text",data:["some","bull","shtuff","here"]},{input:false,name:"Image",data:['','','','']}],customDefault:[0,0,0],customFormat:false,customfliplang:{customSet:"Looks Good"}});a.extend(a.mobile.datebox.prototype,{_customflipDoSet:function(){var b=this,c=this.options;if(typeof b.customCurrent==="undefined"){b.customCurrent=this._makeDate(this.d.input.val())}b.d.input.trigger("datebox",{method:"set",value:b._formatter(c.customFormat,b.customCurrent),date:b.customCurrent})},_cubox_offset:function(e,d){var c=this,b,f=this.options;tmp=(c.customCurrent[e]+d)%f.customData[e]["data"].length;if(tmp<0){tmp=f.customData[e]["data"].length+tmp}c.customCurrent[e]=tmp;if(f.useImmediate){c.d.input.trigger("datebox",{method:"set",value:c._formatter(f.customFormat,c.customCurrent),date:c.customCurrent})}c.refresh()},_cubox_arr:function(f,c){var e=f,b,d=f.slice(0,c),g=f.slice(c+1);while(d.length<10){for(b=e.length;b>0;b--){d.unshift(e[b-1])}}while(d.length>10){d.shift()}while(g.length<10){for(b=0;b
      "),b=a("
      ",{"class":j+"flipcontent"});if(typeof l.customCurrent==="undefined"){l.customCurrent=g}if(d.customFormat===false){f=[];for(e=0;e");l.fldOrder=d.tireFieldOrder;f=a('
      ');for(k=0;k'+d.customData[k]["name"]+"
      ").css("textAlign","center").appendTo(f)}f.appendTo(l.d.intHTML);l.d.intHTML.append(b);for(k=0;k",{"class":"ui-body-"+f}).html(""+h[e]+"").appendTo(m.find("ul"))}m.appendTo(b)}a("
      ",{"class":j+"flipcenter ui-overlay-shadow"}).css("pointerEvents","none").appendTo(l.d.intHTML);if(d.useSetButton){k=a("
      ",{"class":j+"controls"});if(d.useSetButton){a(''+l.__("customSet")+"").appendTo(k).buttonMarkup({theme:d.theme,icon:"check",iconpos:"left",corners:true,shadow:true}).on(d.clickEventAlt,function(i){i.preventDefault();l.d.input.trigger("datebox",{method:"set",value:l._formatter(d.customFormat,l.customCurrent),date:l.tireChoice});l.d.input.trigger("datebox",{method:"close"})})}k.appendTo(l.d.intHTML)}if(l.wheelExists){l.d.intHTML.on("mousewheel",".ui-overlay-shadow",function(i,n){i.preventDefault();l._cubox_offset(a(this).jqmData("field"),((n<0)?1:-1)*a(this).jqmData("amount"))})}l.d.intHTML.on(l.drag.eStart,"ul",function(n,i){if(!l.drag.move){if(typeof i!=="undefined"){n=i}l.drag.move=true;l.drag.target=a(this).find("li").first();l.drag.pos=parseInt(l.drag.target.css("marginTop").replace(/px/i,""),10);l.drag.start=l.touch?n.originalEvent.changedTouches[0].pageY:n.pageY;l.drag.end=false;n.stopPropagation();n.preventDefault()}});l.d.intHTML.on(l.drag.eStart,"."+j+"flipcenter",function(i){if(!l.drag.move){l.drag.target=l.touch?i.originalEvent.changedTouches[0].pageX-a(i.currentTarget).offset().left:i.pageX-a(i.currentTarget).offset().left;l.drag.tmp=l.d.intHTML.find("."+j+"flipcenter").innerWidth()/((a.inArray("a",l.fldOrder)>-1&&l.__("timeFormat")!==12)?l.fldOrder.length-1:l.fldOrder.length);a(l.d.intHTML.find("ul").get(parseInt(l.drag.target/l.drag.tmp,10))).trigger(l.drag.eStart,i)}})}});a.extend(a.mobile.datebox.prototype._drag,{customflip:function(){var b=this,d=this.options,c=this.drag;a(document).on(c.eMove,function(f){if(c.move&&d.mode==="customflip"){c.end=b.touch?f.originalEvent.changedTouches[0].pageY:f.pageY;c.target.css("marginTop",(c.pos+c.end-c.start)+"px");f.preventDefault();f.stopPropagation();return false}});a(document).on(c.eEnd,function(f){if(c.move&&d.mode==="customflip"){c.move=false;if(c.end!==false){f.preventDefault();f.stopPropagation();c.tmp=c.target.parent().parent();b._cubox_offset(c.tmp.jqmData("field"),(parseInt((c.start-c.end)/c.target.innerHeight(),10)*c.tmp.jqmData("amount")))}c.start=false;c.end=false}})}})})(jQuery); \ No newline at end of file diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.datebox.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.datebox.js new file mode 100644 index 000000000..cdc06cc91 --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.datebox.js @@ -0,0 +1,1684 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +/* CORE Functions */ + +(function($) { + $.widget( "mobile.datebox", $.mobile.widget, { + options: { + // All widget options, including some internal runtime details + version: '2-1.4.0-2013070300', // jQMMajor.jQMMinor.DBoxMinor-YrMoDaySerial + mobVer: parseInt($.mobile.version.replace(/\./g,'')), + theme: false, + themeDefault: 'a', + themeHeader: 'a', + mode: false, + + centerHoriz: false, + centerVert: false, + transition: 'pop', + useAnimation: true, + hideInput: false, + hideFixedToolbars: false, + + lockInput: true, + enhanceInput: true, + + zindex: '500', + clickEvent: 'vclick', + clickEventAlt: 'click', + resizeListener: true, + + defaultValue: false, + showInitialValue: false, + + dialogEnable: false, + dialogForce: false, + enablePopup: false, + + popupPosition: false, + popupForceX: false, + popupForceY: false, + + useModal: false, + useInline: false, + useInlineBlind: false, + useHeader: true, + useImmediate: false, + useNewStyle: false, + useAltIcon: false, + overrideStyleClass: false, + + useButton: true, + useFocus: false, + useClearButton: false, + useCollapsedBut: false, + usePlaceholder: false, + + openCallback: false, + openCallbackArgs: [], + closeCallback: false, + closeCallbackArgs: [], + + startOffsetYears: false, + startOffsetMonths: false, + startOffsetDays: false, + afterToday: false, + beforeToday: false, + notToday: false, + maxDays: false, + minDays: false, + maxYear: false, + minYear: false, + blackDates: false, + blackDatesRec: false, + blackDays: false, + minHour: false, + maxHour: false, + minuteStep: 1, + minuteStepRound: 0, + + rolloverMode: { 'm': true, 'd': true, 'h': true, 'i': true, 's': true }, + + useLang: 'default', + lang: { + 'default' : { + setDateButtonLabel: 'Set Date', + setTimeButtonLabel: 'Set Time', + setDurationButtonLabel: 'Set Duration', + calTodayButtonLabel: 'Jump to Today', + titleDateDialogLabel: 'Set Date', + titleTimeDialogLabel: 'Set Time', + daysOfWeek: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], + daysOfWeekShort: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], + monthsOfYear: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], + monthsOfYearShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + durationLabel: ['Days', 'Hours', 'Minutes', 'Seconds'], + durationDays: ['Day', 'Days'], + timeFormat: 24, + headerFormat: '%A, %B %-d, %Y', + tooltip: 'Open Date Picker', + nextMonth: 'Next Month', + prevMonth: 'Previous Month', + dateFieldOrder: ['m', 'd', 'y'], + timeFieldOrder: ['h', 'i', 'a'], + slideFieldOrder: ['y', 'm', 'd'], + dateFormat: '%Y-%m-%d', + useArabicIndic: false, + isRTL: false, + calStartDay: 0, + clearButton: 'Clear', + durationOrder: ['d', 'h', 'i', 's'], + meridiem: ['AM', 'PM'], + timeOutput: '%k:%M', //{ '12': '%l:%M %p', '24': '%k:%M' }, + durationFormat: '%Dd %DA, %Dl:%DM:%DS', + calDateListLabel: 'Other Dates', + calHeaderFormat: '%B %Y' + } + } + }, + _enhanceDate: function() { + $.extend(this._date.prototype, { + copy: function(adjust, override) { + /* Get a modified copy of the date. + * First array - Offset the new date by # (position determines date part) + * Second array - If non-zero, force the new date by # (position determines date part) + */ + if ( typeof adjust === 'undefined' ) { adjust = [0,0,0,0,0,0,0]; } + if ( typeof override === 'undefined' ) { override = [0,0,0,0,0,0,0]; } + while ( adjust.length < 7 ) { adjust.push(0); } + while ( override.length < 7 ) { override.push(0); } + return new Date( + ((override[0] > 0 ) ? override[0] : this.getFullYear() + adjust[0]), + ((override[1] > 0 ) ? override[1] : this.getMonth() + adjust[1]), + ((override[2] > 0 ) ? override[2] : this.getDate() + adjust[2]), + ((override[3] > 0 ) ? override[3] : this.getHours() + adjust[3]), + ((override[4] > 0 ) ? override[4] : this.getMinutes() + adjust[4]), + ((override[5] > 0 ) ? override[5] : this.getSeconds() + adjust[5]), + ((override[6] > 0 ) ? override[5] : this.getMilliseconds() + adjust[6])); + }, + adj: function (type, amount) { + /* Adjust the date. Yes, this is chainable */ + if ( typeof amount !== 'number' ) { + throw new Error("Adjustment value not specified"); + } + if ( typeof type !== 'number' ) { + throw new Error("Adjustment type not specified"); + } + switch ( type ) { + case 0: this.setFullYear(this.getFullYear() + amount); break; + case 1: this.setMonth(this.getMonth() + amount); break; + case 2: this.setDate(this.getDate() + amount); break; + case 3: this.setHours(this.getHours() + amount); break; + case 4: this.setMinutes(this.getMinutes() + amount); break; + case 5: this.setSeconds(this.getSeconds() + amount); break; + case 6: this.setMilliseconds(this.getMilliseconds() + amount); break; + } + return this; + }, + setD: function(type, amount) { + /* A chainable version of setWhatever() */ + switch ( type ) { + case 0: this.setFullYear(amount); break; + case 1: this.setMonth(amount); break; + case 2: this.setDate(amount); break; + case 3: this.setHours(amount); break; + case 4: this.setMinutes(amount); break; + case 5: this.setSeconds(amount); break; + case 6: this.setMilliseconds(amount); break; + } + return this; + }, + get: function(type) { + switch ( type ) { + case 0: return this.getFullYear(); + case 1: return this.getMonth(); + case 2: return this.getDate(); + case 3: return this.getHours(); + case 4: return this.getMinutes(); + case 5: return this.getSeconds(); + } + return false; + }, + iso: function() { + return String(this.getFullYear()) + '-' + (( this.getMonth() < 9 ) ? "0" : "") + String(this.getMonth()+1) + '-' + ((this.getDate() < 10 ) ? "0" : "") + String(this.getDate()); + }, + comp: function () { + return parseInt(this.iso().replace(/-/g,''),10); + }, + getEpoch: function() { + return (this.getTime() - this.getMilliseconds()) / 1000; + }, + getArray: function() { + return [this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds()]; + }, + setFirstDay: function (day) { + this.setD(2,1).adj(2, (day - this.getDay())); + if ( this.get(2) > 10 ) { this.adj(2,7); } + return this; + }, + setDWeek: function (type,num) { + if ( type === 4 ) { + return this.setD(1,0).setD(2,1).setFirstDay(4).adj(2,-3).adj(2,(num-1)*7); + } + return this.setD(1,0).setD(2,1).setFirstDay(type).adj(2,(num-1)*7); + }, + getDWeek: function (type) { + var t1, t2; + + switch ( type ) { + case 0: + t1 = this.copy([0,-1*this.getMonth()]).setFirstDay(0); + return Math.floor((this.getTime() - ( t1.getTime() + (( this.getTimezoneOffset() - t1.getTimezoneOffset()) * 60000))) / 6048e5) + 1; + //return Math.floor((this.getTime() - t1.getTime()) / 6048e5) + 1; + case 1: + t1 = this.copy([0,-1*this.getMonth()]).setFirstDay(1); + return Math.floor((this.getTime() - ( t1.getTime() + (( this.getTimezoneOffset() - t1.getTimezoneOffset()) * 60000))) / 6048e5) + 1; + //return Math.floor((this.getTime() - t1.getTime()) / 6048e5) + 1; + case 4: + // this line is some bullshit. but it does work. + // (trap for dec 29, 30, or 31st being in the new year's week - these are the + // only 3 that can possibly fall like this) + if ( this.getMonth() === 11 && this.getDate() > 28 ) { return 1; } + + t1 = this.copy([0,-1*this.getMonth()],true).setFirstDay(4).adj(2,-3); + t2 = Math.floor((this.getTime() - ( t1.getTime() + (( this.getTimezoneOffset() - t1.getTimezoneOffset()) * 60000))) / 6048e5) + 1; + + if ( t2 < 1 ) { + t1 = this.copy([-1,-1*this.getMonth()]).setFirstDay(4).adj(2,-3); + return Math.floor((this.getTime() - t1.getTime()) / 6048e5) + 1; + } + return t2; + default: + return 0; + } + } + }); + }, + _event: function(e, p) { + var w = $(this).data(parseInt($.mobile.version.replace(/\./g,''),10) > 110 ? 'mobile-datebox' : 'datebox'); + if ( ! e.isPropagationStopped() ) { + switch (p.method) { + case 'close': + w.close(); break; + case 'open': + w.open(); break; + case 'set': + $(this).val(p.value); + $(this).trigger('change'); + break; + case 'doset': + if ( $.isFunction(w['_'+w.options.mode+'DoSet']) ) { + w['_'+w.options.mode+'DoSet'].apply(w,[]); + } else { + $(this).trigger('datebox', {'method':'set', 'value':w._formatter(w.__fmt(), w.theDate), 'date':w.theDate}); + } + break; + case 'dooffset': + if (p.type) { w._offset(p.type, p.amount, true); } break; + case 'dorefresh': + w.refresh(); break; + case 'doreset': + w.hardreset(); break; + case 'doclear': + $(this).val('').trigger('change'); break; + case 'clear': + $(this).trigger('change'); + } + } + }, + _hoover: function(item) { + // Hover toggle class, for calendar + $(item).toggleClass('ui-btn-up-'+$(item).jqmData('theme')+' ui-btn-down-'+$(item).jqmData('theme')); + }, + _ord: { + 'default': function (num) { + // Return an ordinal suffix (1st, 2nd, 3rd, etc) + var ending = num % 10; + if ( num > 9 && num < 21 ) { return 'th'; } + if ( ending > 3 ) { return 'th'; } + return ['th','st','nd','rd'][ending]; + } + }, + __ : function(val) { + var o = this.options, + oride = 'override' + val.charAt(0).toUpperCase() + val.slice(1); + + if ( typeof o[oride] !== 'undefined' ) { return o[oride]; } + if ( typeof o.lang[o.useLang][val] !== 'undefined' ) { return o.lang[o.useLang][val]; } + if ( typeof o[o.mode+'lang'] !== 'undefined' && typeof o[o.mode+'lang'][val] !== 'undefined' ) { return o[o.mode+'lang'][val]; } + return o.lang['default'][val]; + }, + __fmt: function() { + var w = this, + o = this.options; + + switch ( o.mode ) { + case 'timebox': + case 'timeflipbox': + return w.__('timeOutput'); + case 'durationbox': + case 'durationflipbox': + return w.__('durationFormat'); + default: + return w.__('dateFormat'); + } + }, + _zPad: function(number) { + return (( number < 10 ) ? '0' + String(number) : String(number)); + }, + _dRep: function(oper, direction) { + var start = 48, + end = 57, + adder = 1584, + i = null, + ch = null, + newd = ''; + + if ( direction === -1 ) { + start += adder; + end += adder; + adder = -1584; + } + + for ( i=0; i= start && ch <= end ) { + newd = newd + String.fromCharCode(ch+adder); + } else { + newd = newd + String.fromCharCode(ch); + } + } + + return newd; + }, + _doIndic: function() { + var w = this; + + w.d.intHTML.find('*').each(function() { + if ( $(this).children().length < 1 ) { + $(this).text(w._dRep($(this).text())); + } else if ( $(this).hasClass('ui-datebox-slideday') ) { + $(this).html(w._dRep($(this).html())); + } + }); + w.d.intHTML.find('input').each(function() { + $(this).val(w._dRep($(this).val())); + }); + }, + _parser: { + 'default': function (str) { return false; } + }, + _n: function (val,def) { + return ( val < 0 ) ? def : val; + }, + _pa: function (arr,date) { + if ( typeof date === 'boolean' ) { return new this._date(arr[0],arr[1],arr[2],0,0,0,0); } + return new this._date(date.getFullYear(), date.getMonth(), date.getDate(), arr[0], arr[1], arr[2], 0); + }, + _makeDate: function (str) { + // Date Parser + str = $.trim(((this.__('useArabicIndic') === true)?this._dRep(str, -1):str)); + var w = this, + o = this.options, + adv = w.__fmt(), + exp_input = null, + exp_names = [], + exp_format = null, + exp_temp = null, + date = new w._date(), + d = { year: -1, mont: -1, date: -1, hour: -1, mins: -1, secs: -1, week: false, wtyp: 4, wday: false, yday: false, meri: 0 }, + i; + + if ( typeof o.mode === 'undefined' ) { return date; } + if ( typeof w._parser[o.mode] !== 'undefined' ) { return w._parser[o.mode].apply(w,[str]); } + + if ( o.mode === 'durationbox' || o.mode === 'durationflipbox' ) { + adv = adv.replace(/%D([a-z])/gi, function(match, oper) { + switch (oper) { + case 'd': + case 'l': + case 'M': + case 'S': return '(' + match + '|' +'[0-9]+' + ')'; + default: return '.+?'; + } + }); + + adv = new RegExp('^' + adv + '$'); + exp_input = adv.exec(str); + exp_format = adv.exec(w.__fmt()); + + if ( exp_input === null || exp_input.length !== exp_format.length ) { + if ( typeof o.defaultValue === "number" && o.defaultValue > 0 ) { + return new w._date((w.initDate.getEpoch() + parseInt(o.defaultValue,10))*1000); + } + return new w._date(w.initDate.getTime()); + } + + exp_temp = w.initDate.getEpoch(); + for ( i=0; i -1 ) { d.mont = exp_temp; } + break; + case 'B': + exp_temp = $.inArray(exp_input[i], w.__('monthsOfYear')); + if ( exp_temp > -1 ) { d.mont = exp_temp; } + break; + } + } + if ( d.meri !== 0 ) { + if ( d.meri === -1 && d.hour === 12 ) { d.hour = 0; } + if ( d.meri === 1 && d.hour !== 12 ) { d.hour = d.hour + 12; } + } + + date = new w._date(w._n(d.year,0),w._n(d.mont,0),w._n(d.date,1),w._n(d.hour,0),w._n(d.mins,0),w._n(d.secs,0),0); + + if ( d.year < 100 && d.year !== -1 ) { date.setFullYear(d.year); } + + if ( ( d.mont > -1 && d.date > -1 ) || ( d.hour > -1 && d.mins > -1 && d.secs > -1 ) ) { return date; } + + if ( d.week !== false ) { + date.setDWeek(d.wtyp, d.week); + if ( d.date > -1 ) { date.setDate(d.date); } + } + if ( d.yday !== false ) { date.setD(1,0).setD(2,1).adj(2,(d.yday-1)); } + if ( d.wday !== false ) { date.adj(2,(d.wday - date.getDay())); } + } + return date; + }, + _customformat: { + 'default': function(oper, date) { return false; } + }, + _formatter: function(format, date) { + var w = this, + o = this.options, tmp, + dur = { + part: [0,0,0,0], tp: 0 + }; + + if ( o.mode === 'durationbox' || o.mode === 'durationflipbox' ) { + dur.tp = this.theDate.getEpoch() - this.initDate.getEpoch(); + dur.part[0] = parseInt( dur.tp / (60*60*24),10); dur.tp -=(dur.part[0]*60*60*24); // Days + dur.part[1] = parseInt( dur.tp / (60*60),10); dur.tp -= (dur.part[1]*60*60); // Hours + dur.part[2] = parseInt( dur.tp / (60),10); dur.tp -= (dur.part[2]*60); // Minutes + dur.part[3] = dur.tp; // Seconds + + if ( ! format.match(/%Dd/) ) { dur.part[1] += (dur.part[0]*24);} + if ( ! format.match(/%Dl/) ) { dur.part[2] += (dur.part[1]*60);} + if ( ! format.match(/%DM/) ) { dur.part[3] += (dur.part[2]*60);} + } + + format = format.replace(/%(D|X|0|-)*([1-9a-zA-Z])/g, function(match, pad, oper) { + if ( pad === 'X' ) { + if ( typeof w._customformat[o.mode] !== 'undefined' ) { return w._customformat[o.mode](oper, date, o); } + return match; + } + if ( pad === 'D' ) { + switch ( oper ) { + case 'd': return dur.part[0]; + case 'l': return w._zPad(dur.part[1]); + case 'M': return w._zPad(dur.part[2]); + case 'S': return w._zPad(dur.part[3]); + case 'A': return ((dur.part[0] > 1)?w.__('durationDays')[1]:w.__('durationDays')[0]); + default: return match; + } + } + switch ( oper ) { + case '%': // Literal % + return '%'; + case 'a': // Short Day + return w.__('daysOfWeekShort')[date.getDay()]; + case 'A': // Full Day of week + return w.__('daysOfWeek')[date.getDay()]; + case 'b': // Short month + return w.__('monthsOfYearShort')[date.getMonth()]; + case 'B': // Full month + return w.__('monthsOfYear')[date.getMonth()]; + case 'C': // Century + return date.getFullYear().toString().substr(0,2); + case 'd': // Day of month + return (( pad === '-' ) ? date.getDate() : w._zPad(date.getDate())); + case 'H': // Hour (01..23) + case 'k': + return (( pad === '-' ) ? date.getHours() : w._zPad(date.getHours())); + case 'I': // Hour (01..12) + case 'l': + return (( pad === '-' ) ? ((date.getHours() === 0 || date.getHours() === 12)?12:((date.getHours()<12)?date.getHours():(date.getHours()-12))) : w._zPad(((date.getHours() === 0 || date.getHours() === 12)?12:((date.getHours()<12)?date.getHours():date.getHours()-12)))); + case 'm': // Month + return (( pad === '-' ) ? date.getMonth()+1 : w._zPad(date.getMonth()+1)); + case 'M': // Minutes + return (( pad === '-' ) ? date.getMinutes() : w._zPad(date.getMinutes())); + case 'p': // AM/PM (ucase) + return ((date.getHours() < 12)?w.__('meridiem')[0].toUpperCase():w.__('meridiem')[1].toUpperCase()); + case 'P': // AM/PM (lcase) + return ((date.getHours() < 12)?w.__('meridiem')[0].toLowerCase():w.__('meridiem')[1].toLowerCase()); + case 's': // Unix Seconds + return date.getEpoch(); + case 'S': // Seconds + return (( pad === '-' ) ? date.getSeconds() : w._zPad(date.getSeconds())); + case 'u': // Day of week (1-7) + return (( pad === '-' ) ? date.getDay() + 1 : w._zPad(date.getDay() + 1)); + case 'w': // Day of week + return date.getDay(); + case 'y': // Year (2 digit) + return date.getFullYear().toString().substr(2,2); + case 'Y': // Year (4 digit) + return date.getFullYear(); + case 'E': // BE (Buddist Era, 4 Digit) + return date.getFullYear() + 543; + case 'V': + return (( pad === '-' ) ? date.getDWeek(4) : w._zPad(date.getDWeek(4))); + case 'U': + return (( pad === '-' ) ? date.getDWeek(0) : w._zPad(date.getDWeek(0))); + case 'W': + return (( pad === '-' ) ? date.getDWeek(1) : w._zPad(date.getDWeek(1))); + case 'o': // Ordinals + if ( typeof w._ord[o.useLang] !== 'undefined' ) { return w._ord[o.useLang](date.getDate()); } + return w._ord['default'](date.getDate()); + case 'j': + tmp = new Date(date.getFullYear(),0,1); + tmp = Math.ceil((date - tmp) / 86400000)+1; + return (( tmp < 100 ) ? (( tmp < 10 )? '00' : '0') : '' ) + String(tmp); + case 'G': + if ( date.getDWeek(4) === 1 && date.getMonth() > 0 ) { return date.getFullYear() + 1; } + if ( date.getDWeek(4) > 51 && date.getMonth() < 11 ) { return date.getFullYear() - 1; } + return date.getFullYear(); + case 'g': + if ( date.getDWeek(4) === 1 && date.getMonth() > 0 ) { return parseInt(date.getFullYear().toString().substr(2,2),10) + 1; } + if ( date.getDWeek(4) > 51 && date.getMonth() < 11 ) { return parseInt(date.getFullYear().toString().substr(2,2),10) - 1; } + return date.getFullYear().toString().substr(2,2); + default: + return match; + } + }); + + if ( w.__('useArabicIndic') === true ) { + format = w._dRep(format); + } + + return format; + }, + _btwn: function(value, low, high) { + return ( value > low && value < high ); + }, + _minStepFix: function() { + var tempMin = this.theDate.get(4), tmp, + w = this, + o = this.options; + + if ( o.minuteStep > 1 && tempMin % o.minuteStep > 0 ) { + if ( o.minuteStepRound < 0 ) { + tempMin = tempMin - (tempMin % o.minuteStep); + } else if ( o.minStepRound > 0 ) { + tempMin = tempMin + ( o.minuteStep - ( tempMin % o.minuteStep ) ); + } else { + if ( tempMin % o.minuteStep < o.minuteStep / 2 ) { + tempMin = tempMin - (tempMin % o.minuteStep); + } else { + tempMin = tempMin + ( o.minuteStep - ( tempMin % o.minuteStep ) ); + } + } + w.theDate.setMinutes(tempMin); + } + }, + _offset: function(mode, amount, update) { + // Compute a date/time offset. + // update = false to prevent controls refresh + var w = this, + o = this.options, + ok = false; + + mode = (mode || "").toLowerCase(); + + if ( typeof(update) === "undefined" ) { update = true; } + w.d.input.trigger('datebox', {'method':'offset', 'type':mode, 'amount':amount}); + + if ( mode !== 'a' && ( typeof o.rolloverMode[mode] === 'undefined' || o.rolloverMode[mode] === true )) { + ok = $.inArray(mode, ['y','m','d','h','i','s']); + } else { + switch(mode) { + case 'y': ok = 0; break; + case 'm': + if ( w._btwn(w.theDate.getMonth()+amount,-1,12) ) { ok = 1; } + break; + case 'd': + if ( w._btwn(w.theDate.getDate() + amount,0,(32 - w.theDate.copy([0],[0,0,32,13]).getDate() + 1) )) { ok = 2; } + break; + case 'h': + if ( w._btwn(w.theDate.getHours() + amount,-1,24) ) { ok = 3; } + break; + case 'i': + if ( w._btwn(w.theDate.getMinutes() + amount,-1,60) ) { ok = 4; } + break; + case 's': + if ( w._btwn(w.theDate.getSeconds() + amount,-1,60) ) { ok = 5; } + break; + case 'a': + w._offset('h',((amount>0)?1:-1)*12,false); + break; + } + } + if ( ok !== false ) { w.theDate.adj(ok,amount); } + if ( update === true ) { w.refresh(); } + if ( o.useImmediate ) { w.d.input.trigger('datebox', {'method':'doset'}); } + }, + _startOffset: function(date) { + var o = this.options; + + if ( o.startOffsetYears !== false ) { + date.adj(0, o.startOffsetYears); + } + if ( o.startOffsetMonths !== false ) { + date.adj(1, o.startOffsetMonths); + } + if ( o.startOffsetDays !== false ) { + date.adj(2, o.startOffsetDays); + } + return date; + }, + _create: function() { + // Create the widget, called automatically by widget system + $( document ).trigger( "dateboxcreate" ); + + var w = this, + o = $.extend(this.options, (typeof this.element.jqmData('options') !== 'undefined') ? this.element.jqmData('options') : this._getLongOptions(this.element) ), + thisTheme = ( o.theme === false && typeof($(this).jqmData('theme')) === 'undefined' ) ? + ( ( typeof(this.element.parentsUntil(':jqmData(theme)').parent().jqmData('theme')) === 'undefined' ) ? + o.themeDefault : this.element.parentsUntil(':jqmData(theme)').parent().jqmData('theme') ) + : o.theme, + trans = o.useAnimation ? o.transition : 'none', + d = o.useNewStyle === false ? { + input: this.element, + wrap: this.element.wrap('
      ').parent(), + mainWrap: $("
      ", { "class": 'ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden '+trans+' ui-body-'+thisTheme} ).css('zIndex', o.zindex), + intHTML: false + } : { + input: this.element, + wrap: this.element, + mainWrap: $("
      ", { "class": 'ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden '+trans+' ui-body-'+thisTheme} ).css('zIndex', o.zindex), + intHTML: false + }, + touch = ( typeof window.ontouchstart !== 'undefined' ), + drag = { + eStart : (touch ? 'touchstart' : 'mousedown')+'.datebox', + eMove : (touch ? 'touchmove' : 'mousemove')+'.datebox', + eEnd : (touch ? 'touchend' : 'mouseup')+'.datebox', + eEndA : (touch ? 'mouseup.datebox touchend.datebox touchcancel.datebox touchmove.datebox' : 'mouseup.datebox'), + move : false, + start : false, + end : false, + pos : false, + target : false, + delta : false, + tmp : false + }, + calc = { }, + ns = (typeof $.mobile.ns !== 'undefined')?$.mobile.ns:''; + + $.extend(w, {d: d, ns: ns, drag: drag, touch:touch}); + + if ( o.usePlaceholder !== false ) { + if ( o.usePlaceholder === true && w._grabLabel() !== false ) { w.d.input.attr('placeholder', w._grabLabel()); } + if ( typeof o.usePlaceholder === 'string' ) { w.d.input.attr('placeholder', o.usePlaceholder); } + } + + o.theme = thisTheme; + + w.clearFunc = false; + w.disabled = false; + w.runButton = false; + w._date = window.Date; + w._enhanceDate(); + w.baseID = w.d.input.attr('id'); + + w.initDate = new w._date(); + w.theDate = (o.defaultValue) ? w._makeDate(o.defaultValue) : ( (w.d.input.val() !== "") ? w._makeDate(w.d.input.val()) : new w._date() ); + w.initDone = false; + + if ( o.showInitialValue === true ) { + w.d.input.val(w._formatter(w.__fmt(), w.theDate)); + } + + if ( o.useButton === true && o.useInline === false && o.useNewStyle === false ) { + w.d.open = $(''+this.__('tooltip')+'') + .on(o.clickEvent, function(e) { + e.preventDefault(); + if ( !w.disabled ) { w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.parent().addClass('ui-focus'); w.d.input.parent().removeClass('ui-focus'); } + setTimeout( function() { $(e.target).closest('a').removeClass($.mobile.activeBtnClass); }, 300); + }).appendTo(w.d.wrap).buttonMarkup({icon: 'grid', iconpos: 'notext', corners:true, shadow:true}) + .css({'vertical-align': 'middle', 'display': 'inline-block'}); + } + + w.d.screen = $("
      ", {'class':'ui-datebox-screen ui-datebox-hidden'+((o.useModal)?' ui-datebox-screen-modal':'')}) + .css({'z-index': o.zindex-1}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.trigger('datebox', {'method':'close'}); + }); + + if ( o.enhanceInput === true && navigator.userAgent.match(/Android/i) ){ + w.inputType = 'number'; + } else { + w.inputType = 'text'; + } + + if ( o.hideInput ) { w.d.wrap.parent().hide(); } + + if ( o.mobVer < 140 ) { + $('label[for=\''+w.d.input.attr('id')+'\']').addClass('ui-input-text').css('verticalAlign', 'middle'); + } + + w.d.wrap.on(o.clickEvent, function() { + if ( !w.disabled && ( o.noButtonFocusMode || o.focusMode ) ) { + w.d.input.trigger('datebox', {'method': 'open'}); + w.d.wrap.addClass('ui-focus'); + w.d.input.removeClass('ui-focus'); + } + }); + + w.d.input + .removeClass('ui-corner-all ui-shadow-inset') + .bind(w.touch?'touchend':'click', function(e){ + if ( w.disabled === false && o.useNewStyle === true && o.useFocus === false ) { + if ( ((w.touch ? e.originalEvent.changedTouches[0].pageX : e.pageX) - e.target.offsetLeft) > (e.target.offsetWidth - 20) ) { + w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.parent().addClass('ui-focus'); w.d.input.removeClass('ui-focus'); + //setTimeout(function(){w.d.wrap.addClass('ui-focus');}, 200); + } + } + }) + .focus(function(){ + if ( w.disabled === false && o.useFocus === true ) { + w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.addClass('ui-focus'); w.d.input.removeClass('ui-focus'); + if ( o.useNewStyle === false ) { w.d.input.parent().removeClass('ui-focus'); w.d.wrap.parent().addClass('ui-focus'); } + } + if ( o.useNewStyle === false ) { w.d.input.removeClass('ui-focus'); } + }) + .blur(function(){ + w.d.wrap.removeClass('ui-focus'); + w.d.input.removeClass('ui-focus'); + }) + .change(function() { + w.theDate = w._makeDate(w.d.input.val()); + w.refresh(); + }) + .attr("readonly", o.lockInput) + .on('datebox', w._event); + + if ( o.useNewStyle === true ) { + w.d.input.addClass('ui-corner-all '+((o.useAltIcon===true)?'ui-icon-datebox-alt':'ui-icon-datebox')); + if ( o.overrideStyleClass !== false ) { w.d.input.addClass(o.overrideStyleClass); } + } else { + w.d.input.parent().css('border', 'none').removeClass('ui-shadow-inset'); + } + + w.d.wrap.parent().on(o.clickEvent, function() { + if ( !w.disabled && o.useFocus === true && o.useNewStyle === false ) { + w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.addClass('ui-focus'); w.d.input.removeClass('ui-focus'); + setTimeout(function(){ + w.d.wrap.removeClass('ui-focus'); + w.d.wrap.parent().addClass('ui-focus'); + }, 500); + } + }); + + // Check if mousewheel plugin is loaded + if ( typeof $.event.special.mousewheel !== 'undefined' ) { w.wheelExists = true; } + + // Disable when done if element attribute disabled is true. + if ( w.d.input.is(':disabled') ) { + w.disable(); + } + + if ( o.useInline === true || o.useInlineBlind ) { w.open(); } + + w.applyMinMax(false, false); + + //Throw dateboxinit event + $( document ).trigger( "dateboxaftercreate" ); + }, + applyMinMax: function(refresh, override) { + var w = this, + o = this.options, + calc = {}; + + if ( typeof refresh === 'undefined' ) { refresh = false; } + if ( typeof override === 'undefined' ) { override = true; } + + if ( ( override === true || o.minDays === false ) && typeof(w.d.input.attr('min')) !== 'undefined' ) { + calc.today = new w._date(); + calc.lod = 24 * 60 * 60 * 1000; + calc.todayc = new w._date(calc.today.getFullYear(), calc.today.getMonth(), calc.today.getDate(), 0,0,0,0); + calc.fromel = w.d.input.attr('min').split('-'); + calc.compdt = new w._date(calc.fromel[0],calc.fromel[1]-1,calc.fromel[2],0,0,0,0); + o.minDays = parseInt((((calc.compdt.getTime() - calc.todayc.getTime()) / calc.lod))*-1,10); + } + if ( ( override === true || o.maxDays === false ) && typeof(w.d.input.attr('max')) !== 'undefined' ) { + calc.today = new w._date(); + calc.lod = 24 * 60 * 60 * 1000; + calc.todayc = new w._date(calc.today.getFullYear(), calc.today.getMonth(), calc.today.getDate(), 0,0,0,0); + calc.fromel = w.d.input.attr('max').split('-'); + calc.compdt = new w._date(calc.fromel[0],calc.fromel[1]-1,calc.fromel[2],0,0,0,0); + o.maxDays = parseInt((((calc.compdt.getTime() - calc.todayc.getTime()) / calc.lod)),10); + } + + if ( refresh === true ) { w.refresh(); } + }, + _build: { + 'default': function () { + this.d.headerText = "Error"; + this.d.intHTML = $("

      There is no mode by that name loaded / mode not given

      "); + } + }, + _applyCoords: function(e) { + var w = e.widget, + o = e.widget.options, + fixd = { + h: $.mobile.activePage.find('.ui-header').jqmData('position'), + f: $.mobile.activePage.find('.ui-footer').jqmData('position'), + fh: $.mobile.activePage.find('.ui-footer').outerHeight(), + hh: $.mobile.activePage.find('.ui-header').outerHeight() + }, + iput = { + x: w.d.wrap.offset().left + (w.d.wrap.outerWidth() / 2), + y: w.d.wrap.offset().top + (w.d.wrap.outerHeight() / 2) + }, + size = { + w: w.d.mainWrap.outerWidth(), + h: w.d.mainWrap.outerHeight() + }, + doc = { + t: $(window).scrollTop(), + h: $(window).height(), + w: $.mobile.activePage.width(), + ah: $(document).height() + }, + pos = { + y: (o.centerVert) ? doc.t + ((doc.h / 2) - (size.h / 2)) : iput.y - ( size.h / 2 ), + x: (doc.w < 400 || o.centerHoriz ) ? (doc.w / 2) - (size.w /2) : iput.x - (size.w / 2) + }; + + if ( o.centerVert === false ) { + if ( o.hideFixedToolbars === true && ( typeof fixd.f !== 'undefined' || typeof fixd.h !== 'undefined' )) { + $.mobile.activePage.find(":jqmData(position='fixed')").fixedtoolbar('hide'); + fixd.f = undefined; + fixd.h = undefined; + } + + if ( typeof fixd.f !== 'undefined' ) { + if ( ( pos.y + size.h ) > ( doc.h - fixd.fh - 2 ) ) { + pos.y = doc.h - fixd.fh - 2 - size.h; + } + } else { + if ( ( pos.y + size.h ) > ( doc.ah - fixd.fh - 2 ) ) { + pos.y = doc.ah - fixd.fh - 2 - size.h; + } + if ( ( doc.h + doc.t ) < ( size.h + pos.y + 2 ) ) { + pos.y = doc.h + doc.t - size.h - 2; + } + } + + if ( typeof fixd.h !== 'undefined' ) { + if ( ( doc.t + fixd.hh + 2 ) > pos.y ) { + pos.y = doc.t + fixd.hh + 2; + } + } else { + if ( fixd.hh + 2 > pos.y ) { + pos.y = fixd.hh + 2; + } + if ( pos.y < doc.t + 2 ) { + pos.y = doc.t + 2; + } + } + } + w.d.mainWrap.css({'position': 'absolute', 'top': pos.y, 'left': pos.x}); + }, + _drag: { + 'default': function () { return false; } + }, + open: function () { + var w = this, + o = this.options, + popopts = {}, + basepop = {'history':false}, + qns = 'data-'+this.ns, + trans = o.useAnimation ? o.transition : 'none'; + + if ( o.useFocus === true && w.fastReopen === true ) { w.d.input.blur(); return false; } + if ( w.clearFunc !== false ) { + clearTimeout(w.clearFunc); w.clearFunc = false; + } + + // Call the open callback if provided. Additionally, if this + // returns false then the open/update will stop. + if ( o.openCallback !== false ) { + if ( ! $.isFunction(o.openCallback) ) { + if ( typeof window[o.openCallback] !== 'undefined' ) { + o.openCallback = window[o.openCallback]; + } else { + o.openCallback = new Function(o.openCallback); + } + } + if ( o.openCallback.apply(w, $.merge([w.theDate],o.openCallbackArgs)) === false ) { return false; } + } + + w.theDate = w._makeDate(w.d.input.val()); + if ( w.d.input.val() === "" ) { w._startOffset(w.theDate); } + w.d.input.blur(); + + if ( typeof w._build[o.mode] === 'undefined' ) { + w._build['default'].apply(w,[]); + } else { + w._build[o.mode].apply(w,[]); + } + if ( typeof w._drag[o.mode] !== 'undefined' ) { + w._drag[o.mode].apply(w, []); + } + w.d.input.trigger('datebox', {'method':'refresh'}); + if ( w.__('useArabicIndic') === true ) { w._doIndic(); } + + if ( ( o.useInline === true || o.useInlineBlind === true ) && w.initDone === false ) { + w.d.mainWrap.append(w.d.intHTML); + w.d.input.parent().parent().append(w.d.mainWrap); + w.d.mainWrap.removeClass('ui-datebox-hidden'); + if ( o.useInline === true ) { + w.d.mainWrap.addClass('ui-datebox-inline'); + } else { + w.d.mainWrap.addClass('ui-datebox-inlineblind'); + w.d.mainWrap.hide(); + } + w.initDone = false; + w.d.input.trigger('datebox',{'method':'postrefresh'}); + } + + if ( o.useImmediate ) { w.d.input.trigger('datebox', {'method':'doset'}); } + if ( o.useInline ) { return true; } + if ( o.useInlineBlind ) { + if ( w.initDone ) { w.d.mainWrap.slideDown(); } + else { w.initDone = true; } + return true; + } + if ( w.d.intHTML.is(':visible') ) { return false; } // Ignore if already open + + if ( o.enablePopup === true ) { + w.d.dialogPage = false; + w.d.mainWrap.empty(); + if ( o.useHeader === true ) { + w.d.headHTML = $('
      '); + $("Close").appendTo(w.d.headHTML) + .buttonMarkup({ theme : o.themeHeader, icon : 'delete', iconpos: 'notext', corners: true, shadow : true }) + .on(o.clickEventAlt, function(e) { e.preventDefault(); w.d.input.trigger('datebox', {'method':'close'}); }); + $('

      '+w.d.headerText+'

      ').appendTo(w.d.headHTML); + w.d.mainWrap.append(w.d.headHTML); + } + w.d.mainWrap.append(w.d.intHTML).css('zIndex', o.zindex); + w.d.input.trigger('datebox',{'method':'postrefresh'}); + + if ( o.useAnimation === true ) { + popopts.transition = o.transition; + } else { + popopts.transition = "none"; + } + + if ( o.popupForceX !== false && o.popupForceY !== false ) { + popopts.x = o.popupForceX; + popopts.y = o.popupForceY; + } + + if ( o.popupPosition !== false ) { + popopts.positionTo = o.popupPosition; + } else { + if ( typeof w.baseID !== undefined ) { + popopts.positionTo = '#' + w.baseID; + } else { + popopts.positionTo = 'window'; + } + } + + if ( o.useModal === true ) { basepop.overlayTheme = "a"; } + + w.d.mainWrap.removeClass('ui-datebox-hidden').popup(basepop).popup("open", popopts); + w.refresh(); + } else { + if ( o.dialogForce || ( o.dialogEnable && window.width() < 400 ) ) { + w.d.dialogPage = $("
      " + + "
      " + + "

      "+w.d.headerText+"

      ") + .appendTo( $.mobile.pageContainer ) + .page().css('minHeight', '0px').addClass(trans); + w.d.dialogPage.find('.ui-header').find('a').off('click vclick').on(o.clickEventAlt, function(e) { e.preventDefault(); w.d.input.trigger('datebox', {'method':'close'}); }); + w.d.mainWrap.append(w.d.intHTML).css({'marginLeft':'auto', 'marginRight':'auto'}).removeClass('ui-datebox-hidden'); + w.d.dialogPage.find('.ui-content').append(w.d.mainWrap); + w.d.input.trigger('datebox',{'method':'postrefresh'}); + $.mobile.activePage.off( "pagehide.remove" ); + $.mobile.changePage(w.d.dialogPage, {'transition': trans}); + } else { + w.d.dialogPage = false; + w.d.mainWrap.empty(); + if ( o.useHeader === true ) { + w.d.headHTML = $('
      '); + $("Close").appendTo(w.d.headHTML) + .buttonMarkup({ theme : o.themeHeader, icon : 'delete', iconpos: 'notext', corners: true, shadow : true }) + .on(o.clickEventAlt, function(e) { e.preventDefault(); w.d.input.trigger('datebox', {'method':'close'}); }); + $('

      '+w.d.headerText+'

      ').appendTo(w.d.headHTML); + w.d.mainWrap.append(w.d.headHTML); + } + w.d.mainWrap.append(w.d.intHTML).css('zIndex', o.zindex); + w.d.mainWrap.appendTo($.mobile.activePage); + w.d.screen.appendTo($.mobile.activePage); + w.d.input.trigger('datebox',{'method':'postrefresh'}); + w._applyCoords({widget:w}); + + if ( o.useModal === true ) { + if(o.useAnimation) { + w.d.screen.fadeIn('slow'); + } else { + w.d.screen.show(); + } + } else { + setTimeout(function () { w.d.screen.removeClass('ui-datebox-hidden');}, 500); + } + + w.d.mainWrap.addClass('ui-overlay-shadow in').removeClass('ui-datebox-hidden'); + + $(document).on('orientationchange.datebox', {widget:w}, function(e) { w._applyCoords(e.data); }); + if ( o.resizeListener === true ) { + $(window).on('resize.datebox', {widget:w}, function (e) { w._applyCoords(e.data); }); + } + } + } + }, + close: function() { + var w = this, + o = this.options; + + if ( o.useInlineBlind === true ) { w.d.mainWrap.slideUp(); return true;} + if ( o.useInline === true || w.d.intHTML === false ) { return true; } + + if ( w.d.dialogPage !== false ) { + $(w.d.dialogPage).dialog('close'); + + if ( ! $.mobile.activePage.jqmData('mobile-page').options.domCache ) { + $.mobile.activePage.on('pagehide.remove', function () { $(this).remove(); }); + } + + w.d.intHTML.detach().empty(); + w.d.mainWrap.detach().empty(); + w.d.wrap.removeClass('ui-focus'); + w.clearFunc = setTimeout(function () { w.d.dialogPage.empty().remove(); w.clearFunc = false; }, 1500); + } else { + if ( o.enablePopup === true ) { + w.d.mainWrap.popup('close'); + w.d.wrap.removeClass('ui-focus'); + } else { + if ( o.useModal ) { + if(o.useAnimation) { + w.d.screen.fadeOut('slow'); + } else { + w.d.screen.hide(); + } + } else { + w.d.screen.addClass('ui-datebox-hidden'); + } + w.d.screen.detach(); + w.d.mainWrap.addClass('ui-datebox-hidden').removeAttr('style').removeClass('in ui-overlay-shadow').empty().detach(); + w.d.intHTML.detach(); + w.d.wrap.removeClass('ui-focus'); + + $(document).off('orientationchange.datebox'); + if ( o.resizeListener === true ) { + $(window).off('resize.datebox'); + } + } + } + w.d.wrap.parent().removeClass('ui-focus'); + + $(document).off(w.drag.eMove); + $(document).off(w.drag.eEnd); + $(document).off(w.drag.eEndA); + + if ( o.useFocus ) { + w.fastReopen = true; + setTimeout(function(t) { return function () { t.fastReopen = false; };}(w), 300); + } + + if ( o.closeCallback !== false ) { + if ( ! $.isFunction(o.closeCallback) ) { + if ( typeof window[o.closeCallback] !== 'undefined' ) { + o.closeCallback = window[o.closeCallback]; + } else { + o.closeCallback = new Function(o.closeCallback); + } + } + o.closeCallback.apply(w, $.merge([w.theDate], o.closeCallbackArgs)); + } + }, + refresh: function() { + if ( typeof this._build[this.options.mode] === 'undefined' ) { + this._build['default'].apply(this,[]); + } else { + this._build[this.options.mode].apply(this,[]); + } + if ( this.__('useArabicIndic') === true ) { this._doIndic(); } + this.d.mainWrap.append(this.d.intHTML); + this.d.input.trigger('datebox',{'method':'postrefresh'}); + }, + _check: function() { + var w = this, + td = null, + o = this.options; + + w.dateOK = true; + + if ( o.afterToday !== false ) { + td = new w._date(); + if ( w.theDate < td ) { w.theDate = td; } + } + if ( o.beforeToday !== false ) { + td = new w._date(); + if ( w.theDate > td ) { w.theDate = td; } + } + if ( o.maxDays !== false ) { + td = new w._date(); + td.adj(2, o.maxDays); + if ( w.theDate > td ) { w.theDate = td; } + } + if ( o.minDays !== false ) { + td = new w._date(); + td.adj(2, -1*o.minDays); + if ( w.theDate < td ) { w.theDate = td; } + } + if ( o.minHour !== false ) { + if ( w.theDate.getHours() < o.minHour ) { + w.theDate.setHours(o.minHour); + } + } + if ( o.maxHour !== false ) { + if ( w.theDate.getHours() > o.maxHour ) { + w.theDate.setHours(o.maxHour); + } + } + if ( o.maxYear !== false ) { + td = new w._date(o.maxYear, 0, 1); + td.adj(2, -1); + if ( w.theDate > td ) { w.theDate = td; } + } + if ( o.minYear !== false ) { + td = new w._date(o.minYear, 0, 1); + if ( w.theDate < td ) { w.theDate = td; } + } + + if ( $.inArray(o.mode, ['timebox','durationbox','durationflipbox','timeflipbox']) > -1 ) { + if ( o.mode === 'timeflipbox' && o.validHours !== false ) { + if ( $.inArray(w.theDate.getHours(), o.validHours) < 0 ) { w.dateOK = false; } + } + } else { + if ( o.blackDatesRec !== false ) { + for ( i=0; i -1 ) { w.dateOK = false; } + } + if ( o.blackDays !== false ) { + if ( $.inArray(w.theDate.getDay(), o.blackDays) > -1 ) { w.dateOK = false; } + } + } + }, + _grabLabel: function() { + var w = this, + o = this.options; + + if ( typeof o.overrideDialogLabel === 'undefined' ) { + if ( typeof w.d.input.attr('placeholder') !== 'undefined' ) { return w.d.input.attr('placeholder'); } + if ( typeof w.d.input.attr('title') !== 'undefined' ) { return w.d.input.attr('title'); } + if ( w.d.wrap.parent().find('label[for=\''+w.d.input.attr('id')+'\']').text() !== '' ) { + return w.d.wrap.parent().find('label[for=\''+w.d.input.attr('id')+'\']').text(); + } + return false; + } + return o.overrideDialogLabel; + }, + _makeEl: function(source, parts) { + var part = false, + retty = false; + + retty = source.clone(); + + if ( typeof parts.attr !== 'undefined' ) { + for ( part in parts.attr ) { + if ( parts.attr.hasOwnProperty(part) ) { + retty.jqmData(part, parts.attr[part]); + } + } + } + return retty; + }, + _getLongOptions: function(element) { + var key, retty = {}, prefix, temp; + + if ( $.mobile.ns === "" ) { + prefix = "datebox"; + } else { + prefix = $.mobile.ns.substr(0, $.mobile.ns.length - 1) + 'Datebox'; + } + + for ( key in element.data() ) { + if ( key.substr(0, prefix.length) === prefix && key.length > prefix.length ) { + temp = key.substr(prefix.length); + temp = temp.charAt(0).toLowerCase() + temp.slice(1); + retty[temp] = element.data(key); + } + } + return retty; + }, + disable: function(){ + // Disable the element + this.d.input.attr("disabled",true); + this.d.wrap.addClass("ui-disabled").blur(); + this.disabled = true; + this.d.input.trigger('datebox', {'method':'disable'}); + }, + enable: function(){ + // Enable the element + this.d.input.attr("disabled", false); + this.d.wrap.removeClass("ui-disabled"); + this.disabled = false; + this.d.input.trigger('datebox', {'method':'enable'}); + }, + _setOption: function() { + $.Widget.prototype._setOption.apply( this, arguments ); + this.refresh(); + }, + getTheDate: function() { + return this.theDate; + }, + getLastDur: function() { + return this.lastDuration; + }, + setTheDate: function(newDate) { + this.theDate = newDate; + this.refresh(); + }, + callFormat: function(format, date) { + return this._formatter(format, date); + } + }); + + // Degrade date inputs to text inputs, suppress standard UI functions. + $( document ).on( "pagebeforecreate", function( e ) { + $( ":jqmData(role='datebox')", e.target ).each(function() { + $(this).prop('type', 'text'); + }); + }); + // Automatically bind to data-role='datebox' items. + $( document ).on( "pagecreate create", function( e ){ + $( document ).trigger( "dateboxbeforecreate" ); + $( ":jqmData(role='datebox')", e.target ).each(function() { + var defed = typeof ($(this).data(parseInt($.mobile.version.replace(/\./g,''),10) > 111 ? 'mobile-datebox' : 'datebox')); + if ( defed === "undefined" ) { + $(this).datebox(); + } + }); + }); +})( jQuery ); +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ + +(function($) { + $.extend( $.mobile.datebox.prototype.options, { + themeButton: 'a', + themeInput: 'a', + useSetButton: true, + validHours: false, + repButton: true + + }); + $.extend( $.mobile.datebox.prototype, { + _dbox_run: function() { + var w = this; + w.drag.didRun = true; + w._offset(w.drag.target[0], w.drag.target[1], false); + w._dbox_run_update(); + w.runButton = setTimeout(function() {w._dbox_run();}, 150); + }, + _dbox_run_update: function() { + var w = this, + o = this.options; + + if ( o.mode === 'datebox' ) { + w.d.intHTML.find('.ui-datebox-header').find('h4').text(w._formatter(w.__('headerFormat'), w.theDate)); + } + + w.d.divIn.find('input').each(function () { + switch ( $(this).jqmData('field') ) { + case 'y': + $(this).val(w.theDate.getFullYear()); break; + case 'm': + $(this).val(w.theDate.getMonth() + 1); break; + case 'd': + $(this).val(w.theDate.getDate()); break; + case 'h': + if ( w.__('timeFormat') === 12 ) { + if ( w.theDate.getHours() > 12 ) { + $(this).val(w.theDate.getHours()-12); break; + } else if ( w.theDate.getHours() === 0 ) { + $(this).val(12); break; + } + } + $(this).val(w.theDate.getHours()); break; + case 'i': + $(this).val(w._zPad(w.theDate.getMinutes())); break; + case 'M': + $(this).val(w.__('monthsOfYearShort')[w.theDate.getMonth()]); break; + case 'a': + $(this).val((w.theDate.getHours() > 11)?w.__('meridiem')[1]:w.__('meridiem')[0]); + break; + } + }); + }, + _dbox_vhour: function (delta) { + var w = this, + o = this.options, tmp, + closeya = [25,0], + closenay = [25,0]; + + if ( o.validHours === false ) { return true; } + if ( $.inArray(w.theDate.getHours(), o.validHours) > -1 ) { return true; } + + tmp = w.theDate.getHours(); + $.each(o.validHours, function(){ + if ( ((tmp < this)?1:-1) === delta ) { + if ( closeya[0] > Math.abs(this-tmp) ) { + closeya = [Math.abs(this-tmp),parseInt(this,10)]; + } + } else { + if ( closenay[0] > Math.abs(this-tmp) ) { + closenay = [Math.abs(this-tmp),parseInt(this,10)]; + } + } + }); + if ( closeya[1] !== 0 ) { w.theDate.setHours(closeya[1]); } + else { w.theDate.setHours(closenay[1]); } + }, + _dbox_enter: function (item) { + var w = this; + + if ( item.jqmData('field') === 'M' && $.inArray(item.val(), w.__('monthsOfYearShort')) > -1 ) { + w.theDate.setMonth($.inArray(item.val(), w.__('monthsOfYearShort'))); + } + + if ( item.val() !== '' && item.val().toString().search(/^[0-9]+$/) === 0 ) { + switch ( item.jqmData('field') ) { + case 'y': + w.theDate.setFullYear(parseInt(item.val(),10)); break; + case 'm': + w.theDate.setMonth(parseInt(item.val(),10)-1); break; + case 'd': + w.theDate.setDate(parseInt(item.val(),10)); break; + case 'h': + w.theDate.setHours(parseInt(item.val(),10)); break; + case 'i': + w.theDate.setMinutes(parseInt(item.val(),10)); break; + } + } + w.refresh(); + } + }); + $.extend( $.mobile.datebox.prototype._build, { + 'timebox': function () { + this._build.datebox.apply(this,[]); + }, + 'datebox': function () { + var w = this, + g = this.drag, + o = this.options, i, y, tmp, cnt = -2, + uid = 'ui-datebox-', + divBase = $("
      "), + divPlus = $('
      '), + divIn = divBase.clone(), + divMinus = divPlus.clone(), + inBase = $("").addClass('ui-input-text ui-corner-all ui-shadow-inset ui-body-'+o.themeInput), + inBaseT = $("").addClass('ui-input-text ui-corner-all ui-shadow-inset ui-body-'+o.themeInput), + butBase = $("
      "), + butPTheme = {theme: o.themeButton, icon: 'plus', iconpos: 'bottom', corners:true, shadow:true, inline:true}, + butMTheme = $.extend({}, butPTheme, {icon: 'minus', iconpos: 'top'}); + + if ( typeof w.d.intHTML !== 'boolean' ) { + w.d.intHTML.empty().remove(); + } + + w.d.headerText = ((w._grabLabel() !== false)?w._grabLabel():((o.mode==='datebox')?w.__('titleDateDialogLabel'):w.__('titleTimeDialogLabel'))); + w.d.intHTML = $(''); + + if ( w.inputType !== 'number' ) { inBase.attr('pattern', '[0-9]*'); } + + w.fldOrder = ((o.mode==='datebox')?w.__('dateFieldOrder'):w.__('timeFieldOrder')); + w._check(); + w._minStepFix(); + w._dbox_vhour(typeof w._dbox_delta !== 'undefined'?w._dbox_delta:1); + + if ( o.mode === 'datebox' ) { $('

      '+w._formatter(w.__('headerFormat'), w.theDate)+'

      ').appendTo(w.d.intHTML); } + + for(i=0; i<=w.fldOrder.length; i++) { + tmp = ['a','b','c','d','e','f'][i]; + switch (w.fldOrder[i]) { + case 'y': + case 'm': + case 'd': + case 'h': + $('
      ').append(w._makeEl(inBase, {'attr': {'field':w.fldOrder[i], 'amount':1}})).addClass('ui-block-'+tmp).appendTo(divIn); + w._makeEl(butBase, {'attr': {'field':w.fldOrder[i], 'amount':1}}).addClass('ui-block-'+tmp).buttonMarkup(butPTheme).appendTo(divPlus); + w._makeEl(butBase, {'attr': {'field':w.fldOrder[i], 'amount':1}}).addClass('ui-block-'+tmp).buttonMarkup(butMTheme).appendTo(divMinus); + cnt++; + break; + case 'a': + if ( w.__('timeFormat') === 12 ) { + $('
      ').append(w._makeEl(inBaseT, {'attr': {'field':w.fldOrder[i], 'amount':1}})).addClass('ui-block-'+tmp).appendTo(divIn); + w._makeEl(butBase, {'attr': {'field':w.fldOrder[i], 'amount':1}}).addClass('ui-block-'+tmp).buttonMarkup(butPTheme).appendTo(divPlus); + w._makeEl(butBase, {'attr': {'field':w.fldOrder[i], 'amount':1}}).addClass('ui-block-'+tmp).buttonMarkup(butMTheme).appendTo(divMinus); + cnt++; + } + break; + case 'M': + $('
      ').append(w._makeEl(inBaseT, {'attr': {'field':w.fldOrder[i], 'amount':1}})).addClass('ui-block-'+tmp).appendTo(divIn); + w._makeEl(butBase, {'attr': {'field':w.fldOrder[i], 'amount':1}}).addClass('ui-block-'+tmp).buttonMarkup(butPTheme).appendTo(divPlus); + w._makeEl(butBase, {'attr': {'field':w.fldOrder[i], 'amount':1}}).addClass('ui-block-'+tmp).buttonMarkup(butMTheme).appendTo(divMinus); + cnt++; + break; + case 'i': + $('
      ').append(w._makeEl(inBase, {'attr': {'field':w.fldOrder[i], 'amount':o.minuteStep}})).addClass('ui-block-'+tmp).appendTo(divIn); + w._makeEl(butBase, {'attr': {'field':w.fldOrder[i], 'amount':o.minuteStep}}).addClass('ui-block-'+tmp).buttonMarkup(butPTheme).appendTo(divPlus); + w._makeEl(butBase, {'attr': {'field':w.fldOrder[i], 'amount':o.minuteStep}}).addClass('ui-block-'+tmp).buttonMarkup(butMTheme).appendTo(divMinus); + cnt++; + break; + } + } + + divPlus.addClass('ui-grid-'+['a','b','c','d','e'][cnt]).appendTo(w.d.intHTML); + divIn.addClass('ui-datebox-dboxin').addClass('ui-grid-'+['a','b','c','d','e'][cnt]).appendTo(w.d.intHTML); + divMinus.addClass('ui-grid-'+['a','b','c','d','e'][cnt]).appendTo(w.d.intHTML); + + if ( o.mobVer >= 140 ) { + divMinus.find('div').css({'min-height':'2.3em'}); + divPlus.find('div').css({'min-height':'2.3em'}); + } + + divIn.find('input').each(function () { + switch ( $(this).jqmData('field') ) { + case 'y': + $(this).val(w.theDate.getFullYear()); break; + case 'm': + $(this).val(w.theDate.getMonth() + 1); break; + case 'd': + $(this).val(w.theDate.getDate()); break; + case 'h': + if ( w.__('timeFormat') === 12 ) { + if ( w.theDate.getHours() > 12 ) { + $(this).val(w.theDate.getHours()-12); break; + } else if ( w.theDate.getHours() === 0 ) { + $(this).val(12); break; + } + } + $(this).val(w.theDate.getHours()); break; + case 'i': + $(this).val(w._zPad(w.theDate.getMinutes())); break; + case 'M': + $(this).val(w.__('monthsOfYearShort')[w.theDate.getMonth()]); break; + case 'a': + $(this).val((w.theDate.getHours() > 11)?w.__('meridiem')[1]:w.__('meridiem')[0]); + break; + } + }); + + w.d.divIn = divIn; + + if ( w.dateOK !== true ) { + divIn.find('input').addClass(uid+'griddate-disable'); + } else { + divIn.find('.'+uid+'griddate-disable').removeClass(uid+'griddate-disable'); + } + + if ( o.useSetButton || o.useClearButton ) { + y = $('
      ', {'class':uid+'controls'}); + + if ( o.useSetButton ) { + $(''+((o.mode==='datebox')?w.__('setDateButtonLabel'):w.__('setTimeButtonLabel'))+'') + .appendTo(y).buttonMarkup({theme: o.theme, icon: 'check', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + if ( w.dateOK === true ) { + w.d.input.trigger('datebox', {'method':'set', 'value':w._formatter(w.__fmt(),w.theDate), 'date':w.theDate}); + w.d.input.trigger('datebox', {'method':'close'}); + } + }); + } + if ( o.useClearButton ) { + $(''+w.__('clearButton')+'') + .appendTo(y).buttonMarkup({theme: o.theme, icon: 'delete', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.val(''); + w.d.input.trigger('datebox',{'method':'clear'}); + w.d.input.trigger('datebox',{'method':'close'}); + }); + } + if ( o.useCollapsedBut ) { + y.addClass('ui-datebox-collapse'); + } + y.appendTo(w.d.intHTML); + } + + if ( o.repButton === false ) { + divPlus.on(o.clickEvent, 'div', function(e) { + e.preventDefault(); + w._dbox_delta = 1; + w._offset($(this).jqmData('field'), $(this).jqmData('amount')); + }); + divMinus.on(o.clickEvent, 'div', function(e) { + e.preventDefault(); + w._dbox_delta = -1; + w._offset($(this).jqmData('field'), $(this).jqmData('amount')*-1); + }); + } + + divIn.on('change', 'input', function() { w._dbox_enter($(this)); }); + + if ( w.wheelExists ) { // Mousewheel operation, if plugin is loaded + divIn.on('mousewheel', 'input', function(e,d) { + e.preventDefault(); + w._dbox_delta = d<0?-1:1; + w._offset($(this).jqmData('field'), ((d<0)?-1:1)*$(this).jqmData('amount')); + }); + } + + if ( o.repButton === true ) { + divPlus.on(w.drag.eStart, 'div', function(e) { + tmp = [$(this).jqmData('field'), $(this).jqmData('amount')]; + w.drag.move = true; + w._dbox_delta = 1; + w._offset(tmp[0], tmp[1], false); + w._dbox_run_update(); + if ( !w.runButton ) { + w.drag.target = tmp; + w.runButton = setTimeout(function() {w._dbox_run();}, 500); + } + }); + + divMinus.on(w.drag.eStart, 'div', function(e) { + tmp = [$(this).jqmData('field'), $(this).jqmData('amount')*-1]; + w.drag.move = true; + w._dbox_delta = -1; + w._offset(tmp[0], tmp[1], false); + w._dbox_run_update(); + if ( !w.runButton ) { + w.drag.target = tmp; + w.runButton = setTimeout(function() {w._dbox_run();}, 500); + } + }); + + divPlus.on(g.eEndA, function(e) { + if ( g.move ) { + e.preventDefault(); + clearTimeout(w.runButton); + w.runButton = false; + g.move = false; + } + }); + divMinus.on(g.eEndA, function(e) { + if ( g.move ) { + e.preventDefault(); + clearTimeout(w.runButton); + w.runButton = false; + g.move = false; + } + }); + } + } + }); +})( jQuery ); diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.datebox.min.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.datebox.min.js new file mode 100644 index 000000000..b643d2636 --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.datebox.min.js @@ -0,0 +1,7 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +(function(a){a.widget("mobile.datebox",a.mobile.widget,{options:{version:"2-1.4.0-2013070300",mobVer:parseInt(a.mobile.version.replace(/\./g,"")),theme:false,themeDefault:"a",themeHeader:"a",mode:false,centerHoriz:false,centerVert:false,transition:"pop",useAnimation:true,hideInput:false,hideFixedToolbars:false,lockInput:true,enhanceInput:true,zindex:"500",clickEvent:"vclick",clickEventAlt:"click",resizeListener:true,defaultValue:false,showInitialValue:false,dialogEnable:false,dialogForce:false,enablePopup:false,popupPosition:false,popupForceX:false,popupForceY:false,useModal:false,useInline:false,useInlineBlind:false,useHeader:true,useImmediate:false,useNewStyle:false,useAltIcon:false,overrideStyleClass:false,useButton:true,useFocus:false,useClearButton:false,useCollapsedBut:false,usePlaceholder:false,openCallback:false,openCallbackArgs:[],closeCallback:false,closeCallbackArgs:[],startOffsetYears:false,startOffsetMonths:false,startOffsetDays:false,afterToday:false,beforeToday:false,notToday:false,maxDays:false,minDays:false,maxYear:false,minYear:false,blackDates:false,blackDatesRec:false,blackDays:false,minHour:false,maxHour:false,minuteStep:1,minuteStepRound:0,rolloverMode:{m:true,d:true,h:true,i:true,s:true},useLang:"default",lang:{"default":{setDateButtonLabel:"Set Date",setTimeButtonLabel:"Set Time",setDurationButtonLabel:"Set Duration",calTodayButtonLabel:"Jump to Today",titleDateDialogLabel:"Set Date",titleTimeDialogLabel:"Set Time",daysOfWeek:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],daysOfWeekShort:["Su","Mo","Tu","We","Th","Fr","Sa"],monthsOfYear:["January","February","March","April","May","June","July","August","September","October","November","December"],monthsOfYearShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],durationLabel:["Days","Hours","Minutes","Seconds"],durationDays:["Day","Days"],timeFormat:24,headerFormat:"%A, %B %-d, %Y",tooltip:"Open Date Picker",nextMonth:"Next Month",prevMonth:"Previous Month",dateFieldOrder:["m","d","y"],timeFieldOrder:["h","i","a"],slideFieldOrder:["y","m","d"],dateFormat:"%Y-%m-%d",useArabicIndic:false,isRTL:false,calStartDay:0,clearButton:"Clear",durationOrder:["d","h","i","s"],meridiem:["AM","PM"],timeOutput:"%k:%M",durationFormat:"%Dd %DA, %Dl:%DM:%DS",calDateListLabel:"Other Dates",calHeaderFormat:"%B %Y"}}},_enhanceDate:function(){a.extend(this._date.prototype,{copy:function(c,b){if(typeof c==="undefined"){c=[0,0,0,0,0,0,0]}if(typeof b==="undefined"){b=[0,0,0,0,0,0,0]}while(c.length<7){c.push(0)}while(b.length<7){b.push(0)}return new Date(((b[0]>0)?b[0]:this.getFullYear()+c[0]),((b[1]>0)?b[1]:this.getMonth()+c[1]),((b[2]>0)?b[2]:this.getDate()+c[2]),((b[3]>0)?b[3]:this.getHours()+c[3]),((b[4]>0)?b[4]:this.getMinutes()+c[4]),((b[5]>0)?b[5]:this.getSeconds()+c[5]),((b[6]>0)?b[5]:this.getMilliseconds()+c[6]))},adj:function(c,b){if(typeof b!=="number"){throw new Error("Adjustment value not specified")}if(typeof c!=="number"){throw new Error("Adjustment type not specified")}switch(c){case 0:this.setFullYear(this.getFullYear()+b);break;case 1:this.setMonth(this.getMonth()+b);break;case 2:this.setDate(this.getDate()+b);break;case 3:this.setHours(this.getHours()+b);break;case 4:this.setMinutes(this.getMinutes()+b);break;case 5:this.setSeconds(this.getSeconds()+b);break;case 6:this.setMilliseconds(this.getMilliseconds()+b);break}return this},setD:function(c,b){switch(c){case 0:this.setFullYear(b);break;case 1:this.setMonth(b);break;case 2:this.setDate(b);break;case 3:this.setHours(b);break;case 4:this.setMinutes(b);break;case 5:this.setSeconds(b);break;case 6:this.setMilliseconds(b);break}return this},get:function(b){switch(b){case 0:return this.getFullYear();case 1:return this.getMonth();case 2:return this.getDate();case 3:return this.getHours();case 4:return this.getMinutes();case 5:return this.getSeconds()}return false},iso:function(){return String(this.getFullYear())+"-"+((this.getMonth()<9)?"0":"")+String(this.getMonth()+1)+"-"+((this.getDate()<10)?"0":"")+String(this.getDate())},comp:function(){return parseInt(this.iso().replace(/-/g,""),10)},getEpoch:function(){return(this.getTime()-this.getMilliseconds())/1000},getArray:function(){return[this.getFullYear(),this.getMonth(),this.getDate(),this.getHours(),this.getMinutes(),this.getSeconds()]},setFirstDay:function(b){this.setD(2,1).adj(2,(b-this.getDay()));if(this.get(2)>10){this.adj(2,7)}return this},setDWeek:function(c,b){if(c===4){return this.setD(1,0).setD(2,1).setFirstDay(4).adj(2,-3).adj(2,(b-1)*7)}return this.setD(1,0).setD(2,1).setFirstDay(c).adj(2,(b-1)*7)},getDWeek:function(c){var d,b;switch(c){case 0:d=this.copy([0,-1*this.getMonth()]).setFirstDay(0);return Math.floor((this.getTime()-(d.getTime()+((this.getTimezoneOffset()-d.getTimezoneOffset())*60000)))/604800000)+1;case 1:d=this.copy([0,-1*this.getMonth()]).setFirstDay(1);return Math.floor((this.getTime()-(d.getTime()+((this.getTimezoneOffset()-d.getTimezoneOffset())*60000)))/604800000)+1;case 4:if(this.getMonth()===11&&this.getDate()>28){return 1}d=this.copy([0,-1*this.getMonth()],true).setFirstDay(4).adj(2,-3);b=Math.floor((this.getTime()-(d.getTime()+((this.getTimezoneOffset()-d.getTimezoneOffset())*60000)))/604800000)+1;if(b<1){d=this.copy([-1,-1*this.getMonth()]).setFirstDay(4).adj(2,-3);return Math.floor((this.getTime()-d.getTime())/604800000)+1}return b;default:return 0}}})},_event:function(d,c){var b=a(this).data(parseInt(a.mobile.version.replace(/\./g,""),10)>110?"mobile-datebox":"datebox");if(!d.isPropagationStopped()){switch(c.method){case"close":b.close();break;case"open":b.open();break;case"set":a(this).val(c.value);a(this).trigger("change");break;case"doset":if(a.isFunction(b["_"+b.options.mode+"DoSet"])){b["_"+b.options.mode+"DoSet"].apply(b,[])}else{a(this).trigger("datebox",{method:"set",value:b._formatter(b.__fmt(),b.theDate),date:b.theDate})}break;case"dooffset":if(c.type){b._offset(c.type,c.amount,true)}break;case"dorefresh":b.refresh();break;case"doreset":b.hardreset();break;case"doclear":a(this).val("").trigger("change");break;case"clear":a(this).trigger("change")}}},_hoover:function(b){a(b).toggleClass("ui-btn-up-"+a(b).jqmData("theme")+" ui-btn-down-"+a(b).jqmData("theme"))},_ord:{"default":function(c){var b=c%10;if(c>9&&c<21){return"th"}if(b>3){return"th"}return["th","st","nd","rd"][b]}},__:function(d){var c=this.options,b="override"+d.charAt(0).toUpperCase()+d.slice(1);if(typeof c[b]!=="undefined"){return c[b]}if(typeof c.lang[c.useLang][d]!=="undefined"){return c.lang[c.useLang][d]}if(typeof c[c.mode+"lang"]!=="undefined"&&typeof c[c.mode+"lang"][d]!=="undefined"){return c[c.mode+"lang"][d]}return c.lang["default"][d]},__fmt:function(){var b=this,c=this.options;switch(c.mode){case"timebox":case"timeflipbox":return b.__("timeOutput");case"durationbox":case"durationflipbox":return b.__("durationFormat");default:return b.__("dateFormat")}},_zPad:function(b){return((b<10)?"0"+String(b):String(b))},_dRep:function(j,g){var h=48,b=57,c=1584,d=null,e=null,f="";if(g===-1){h+=c;b+=c;c=-1584}for(d=0;d=h&&e<=b){f=f+String.fromCharCode(e+c)}else{f=f+String.fromCharCode(e)}}return f},_doIndic:function(){var b=this;b.d.intHTML.find("*").each(function(){if(a(this).children().length<1){a(this).text(b._dRep(a(this).text()))}else{if(a(this).hasClass("ui-datebox-slideday")){a(this).html(b._dRep(a(this).html()))}}});b.d.intHTML.find("input").each(function(){a(this).val(b._dRep(a(this).val()))})},_parser:{"default":function(b){return false}},_n:function(c,b){return(c<0)?b:c},_pa:function(b,c){if(typeof c==="boolean"){return new this._date(b[0],b[1],b[2],0,0,0,0)}return new this._date(c.getFullYear(),c.getMonth(),c.getDate(),b[0],b[1],b[2],0)},_makeDate:function(k){k=a.trim(((this.__("useArabicIndic")===true)?this._dRep(k,-1):k));var n=this,c=this.options,e=n.__fmt(),m=null,h=[],l=null,b=null,f=new n._date(),j={year:-1,mont:-1,date:-1,hour:-1,mins:-1,secs:-1,week:false,wtyp:4,wday:false,yday:false,meri:0},g;if(typeof c.mode==="undefined"){return f}if(typeof n._parser[c.mode]!=="undefined"){return n._parser[c.mode].apply(n,[k])}if(c.mode==="durationbox"||c.mode==="durationflipbox"){e=e.replace(/%D([a-z])/gi,function(d,o){switch(o){case"d":case"l":case"M":case"S":return"("+d+"|[0-9]+)";default:return".+?"}});e=new RegExp("^"+e+"$");m=e.exec(k);l=e.exec(n.__fmt());if(m===null||m.length!==l.length){if(typeof c.defaultValue==="number"&&c.defaultValue>0){return new n._date((n.initDate.getEpoch()+parseInt(c.defaultValue,10))*1000)}return new n._date(n.initDate.getTime())}b=n.initDate.getEpoch();for(g=0;g-1){j.mont=b}break;case"B":b=a.inArray(m[g],n.__("monthsOfYear"));if(b>-1){j.mont=b}break}}if(j.meri!==0){if(j.meri===-1&&j.hour===12){j.hour=0}if(j.meri===1&&j.hour!==12){j.hour=j.hour+12}}f=new n._date(n._n(j.year,0),n._n(j.mont,0),n._n(j.date,1),n._n(j.hour,0),n._n(j.mins,0),n._n(j.secs,0),0);if(j.year<100&&j.year!==-1){f.setFullYear(j.year)}if((j.mont>-1&&j.date>-1)||(j.hour>-1&&j.mins>-1&&j.secs>-1)){return f}if(j.week!==false){f.setDWeek(j.wtyp,j.week);if(j.date>-1){f.setDate(j.date)}}if(j.yday!==false){f.setD(1,0).setD(2,1).adj(2,(j.yday-1))}if(j.wday!==false){f.adj(2,(j.wday-f.getDay()))}}return f},_customformat:{"default":function(c,b){return false}},_formatter:function(f,c){var b=this,g=this.options,d,e={part:[0,0,0,0],tp:0};if(g.mode==="durationbox"||g.mode==="durationflipbox"){e.tp=this.theDate.getEpoch()-this.initDate.getEpoch();e.part[0]=parseInt(e.tp/(60*60*24),10);e.tp-=(e.part[0]*60*60*24);e.part[1]=parseInt(e.tp/(60*60),10);e.tp-=(e.part[1]*60*60);e.part[2]=parseInt(e.tp/(60),10);e.tp-=(e.part[2]*60);e.part[3]=e.tp;if(!f.match(/%Dd/)){e.part[1]+=(e.part[0]*24)}if(!f.match(/%Dl/)){e.part[2]+=(e.part[1]*60)}if(!f.match(/%DM/)){e.part[3]+=(e.part[2]*60)}}f=f.replace(/%(D|X|0|-)*([1-9a-zA-Z])/g,function(h,j,k){if(j==="X"){if(typeof b._customformat[g.mode]!=="undefined"){return b._customformat[g.mode](k,c,g)}return h}if(j==="D"){switch(k){case"d":return e.part[0];case"l":return b._zPad(e.part[1]);case"M":return b._zPad(e.part[2]);case"S":return b._zPad(e.part[3]);case"A":return((e.part[0]>1)?b.__("durationDays")[1]:b.__("durationDays")[0]);default:return h}}switch(k){case"%":return"%";case"a":return b.__("daysOfWeekShort")[c.getDay()];case"A":return b.__("daysOfWeek")[c.getDay()];case"b":return b.__("monthsOfYearShort")[c.getMonth()];case"B":return b.__("monthsOfYear")[c.getMonth()];case"C":return c.getFullYear().toString().substr(0,2);case"d":return((j==="-")?c.getDate():b._zPad(c.getDate()));case"H":case"k":return((j==="-")?c.getHours():b._zPad(c.getHours()));case"I":case"l":return((j==="-")?((c.getHours()===0||c.getHours()===12)?12:((c.getHours()<12)?c.getHours():(c.getHours()-12))):b._zPad(((c.getHours()===0||c.getHours()===12)?12:((c.getHours()<12)?c.getHours():c.getHours()-12))));case"m":return((j==="-")?c.getMonth()+1:b._zPad(c.getMonth()+1));case"M":return((j==="-")?c.getMinutes():b._zPad(c.getMinutes()));case"p":return((c.getHours()<12)?b.__("meridiem")[0].toUpperCase():b.__("meridiem")[1].toUpperCase());case"P":return((c.getHours()<12)?b.__("meridiem")[0].toLowerCase():b.__("meridiem")[1].toLowerCase());case"s":return c.getEpoch();case"S":return((j==="-")?c.getSeconds():b._zPad(c.getSeconds()));case"u":return((j==="-")?c.getDay()+1:b._zPad(c.getDay()+1));case"w":return c.getDay();case"y":return c.getFullYear().toString().substr(2,2);case"Y":return c.getFullYear();case"E":return c.getFullYear()+543;case"V":return((j==="-")?c.getDWeek(4):b._zPad(c.getDWeek(4)));case"U":return((j==="-")?c.getDWeek(0):b._zPad(c.getDWeek(0)));case"W":return((j==="-")?c.getDWeek(1):b._zPad(c.getDWeek(1)));case"o":if(typeof b._ord[g.useLang]!=="undefined"){return b._ord[g.useLang](c.getDate())}return b._ord["default"](c.getDate());case"j":d=new Date(c.getFullYear(),0,1);d=Math.ceil((c-d)/86400000)+1;return((d<100)?((d<10)?"00":"0"):"")+String(d);case"G":if(c.getDWeek(4)===1&&c.getMonth()>0){return c.getFullYear()+1}if(c.getDWeek(4)>51&&c.getMonth()<11){return c.getFullYear()-1}return c.getFullYear();case"g":if(c.getDWeek(4)===1&&c.getMonth()>0){return parseInt(c.getFullYear().toString().substr(2,2),10)+1}if(c.getDWeek(4)>51&&c.getMonth()<11){return parseInt(c.getFullYear().toString().substr(2,2),10)-1}return c.getFullYear().toString().substr(2,2);default:return h}});if(b.__("useArabicIndic")===true){f=b._dRep(f)}return f},_btwn:function(d,b,c){return(d>b&&d1&&d%e.minuteStep>0){if(e.minuteStepRound<0){d=d-(d%e.minuteStep)}else{if(e.minStepRound>0){d=d+(e.minuteStep-(d%e.minuteStep))}else{if(d%e.minuteStep0)?1:-1)*12,false);break}}if(c!==false){b.theDate.adj(c,d)}if(g===true){b.refresh()}if(e.useImmediate){b.d.input.trigger("datebox",{method:"doset"})}},_startOffset:function(b){var c=this.options;if(c.startOffsetYears!==false){b.adj(0,c.startOffsetYears)}if(c.startOffsetMonths!==false){b.adj(1,c.startOffsetMonths)}if(c.startOffsetDays!==false){b.adj(2,c.startOffsetDays)}return b},_create:function(){a(document).trigger("dateboxcreate");var j=this,b=a.extend(this.options,(typeof this.element.jqmData("options")!=="undefined")?this.element.jqmData("options"):this._getLongOptions(this.element)),k=(b.theme===false&&typeof(a(this).jqmData("theme"))==="undefined")?((typeof(this.element.parentsUntil(":jqmData(theme)").parent().jqmData("theme"))==="undefined")?b.themeDefault:this.element.parentsUntil(":jqmData(theme)").parent().jqmData("theme")):b.theme,l=b.useAnimation?b.transition:"none",g=b.useNewStyle===false?{input:this.element,wrap:this.element.wrap('
      ').parent(),mainWrap:a("
      ",{"class":"ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden "+l+" ui-body-"+k}).css("zIndex",b.zindex),intHTML:false}:{input:this.element,wrap:this.element,mainWrap:a("
      ",{"class":"ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden "+l+" ui-body-"+k}).css("zIndex",b.zindex),intHTML:false},e=(typeof window.ontouchstart!=="undefined"),f={eStart:(e?"touchstart":"mousedown")+".datebox",eMove:(e?"touchmove":"mousemove")+".datebox",eEnd:(e?"touchend":"mouseup")+".datebox",eEndA:(e?"mouseup.datebox touchend.datebox touchcancel.datebox touchmove.datebox":"mouseup.datebox"),move:false,start:false,end:false,pos:false,target:false,delta:false,tmp:false},c={},h=(typeof a.mobile.ns!=="undefined")?a.mobile.ns:"";a.extend(j,{d:g,ns:h,drag:f,touch:e});if(b.usePlaceholder!==false){if(b.usePlaceholder===true&&j._grabLabel()!==false){j.d.input.attr("placeholder",j._grabLabel())}if(typeof b.usePlaceholder==="string"){j.d.input.attr("placeholder",b.usePlaceholder)}}b.theme=k;j.clearFunc=false;j.disabled=false;j.runButton=false;j._date=window.Date;j._enhanceDate();j.baseID=j.d.input.attr("id");j.initDate=new j._date();j.theDate=(b.defaultValue)?j._makeDate(b.defaultValue):((j.d.input.val()!=="")?j._makeDate(j.d.input.val()):new j._date());j.initDone=false;if(b.showInitialValue===true){j.d.input.val(j._formatter(j.__fmt(),j.theDate))}if(b.useButton===true&&b.useInline===false&&b.useNewStyle===false){j.d.open=a(''+this.__("tooltip")+"").on(b.clickEvent,function(d){d.preventDefault();if(!j.disabled){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.parent().addClass("ui-focus");j.d.input.parent().removeClass("ui-focus")}setTimeout(function(){a(d.target).closest("a").removeClass(a.mobile.activeBtnClass)},300)}).appendTo(j.d.wrap).buttonMarkup({icon:"grid",iconpos:"notext",corners:true,shadow:true}).css({"vertical-align":"middle",display:"inline-block"})}j.d.screen=a("
      ",{"class":"ui-datebox-screen ui-datebox-hidden"+((b.useModal)?" ui-datebox-screen-modal":"")}).css({"z-index":b.zindex-1}).on(b.clickEventAlt,function(d){d.preventDefault();j.d.input.trigger("datebox",{method:"close"})});if(b.enhanceInput===true&&navigator.userAgent.match(/Android/i)){j.inputType="number"}else{j.inputType="text"}if(b.hideInput){j.d.wrap.parent().hide()}if(b.mobVer<140){a("label[for='"+j.d.input.attr("id")+"']").addClass("ui-input-text").css("verticalAlign","middle")}j.d.wrap.on(b.clickEvent,function(){if(!j.disabled&&(b.noButtonFocusMode||b.focusMode)){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.addClass("ui-focus");j.d.input.removeClass("ui-focus")}});j.d.input.removeClass("ui-corner-all ui-shadow-inset").bind(j.touch?"touchend":"click",function(d){if(j.disabled===false&&b.useNewStyle===true&&b.useFocus===false){if(((j.touch?d.originalEvent.changedTouches[0].pageX:d.pageX)-d.target.offsetLeft)>(d.target.offsetWidth-20)){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.parent().addClass("ui-focus");j.d.input.removeClass("ui-focus")}}}).focus(function(){if(j.disabled===false&&b.useFocus===true){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.addClass("ui-focus");j.d.input.removeClass("ui-focus");if(b.useNewStyle===false){j.d.input.parent().removeClass("ui-focus");j.d.wrap.parent().addClass("ui-focus")}}if(b.useNewStyle===false){j.d.input.removeClass("ui-focus")}}).blur(function(){j.d.wrap.removeClass("ui-focus");j.d.input.removeClass("ui-focus")}).change(function(){j.theDate=j._makeDate(j.d.input.val());j.refresh()}).attr("readonly",b.lockInput).on("datebox",j._event);if(b.useNewStyle===true){j.d.input.addClass("ui-corner-all "+((b.useAltIcon===true)?"ui-icon-datebox-alt":"ui-icon-datebox"));if(b.overrideStyleClass!==false){j.d.input.addClass(b.overrideStyleClass)}}else{j.d.input.parent().css("border","none").removeClass("ui-shadow-inset")}j.d.wrap.parent().on(b.clickEvent,function(){if(!j.disabled&&b.useFocus===true&&b.useNewStyle===false){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.addClass("ui-focus");j.d.input.removeClass("ui-focus");setTimeout(function(){j.d.wrap.removeClass("ui-focus");j.d.wrap.parent().addClass("ui-focus")},500)}});if(typeof a.event.special.mousewheel!=="undefined"){j.wheelExists=true}if(j.d.input.is(":disabled")){j.disable()}if(b.useInline===true||b.useInlineBlind){j.open()}j.applyMinMax(false,false);a(document).trigger("dateboxaftercreate")},applyMinMax:function(e,d){var b=this,f=this.options,c={};if(typeof e==="undefined"){e=false}if(typeof d==="undefined"){d=true}if((d===true||f.minDays===false)&&typeof(b.d.input.attr("min"))!=="undefined"){c.today=new b._date();c.lod=24*60*60*1000;c.todayc=new b._date(c.today.getFullYear(),c.today.getMonth(),c.today.getDate(),0,0,0,0);c.fromel=b.d.input.attr("min").split("-");c.compdt=new b._date(c.fromel[0],c.fromel[1]-1,c.fromel[2],0,0,0,0);f.minDays=parseInt((((c.compdt.getTime()-c.todayc.getTime())/c.lod))*-1,10)}if((d===true||f.maxDays===false)&&typeof(b.d.input.attr("max"))!=="undefined"){c.today=new b._date();c.lod=24*60*60*1000;c.todayc=new b._date(c.today.getFullYear(),c.today.getMonth(),c.today.getDate(),0,0,0,0);c.fromel=b.d.input.attr("max").split("-");c.compdt=new b._date(c.fromel[0],c.fromel[1]-1,c.fromel[2],0,0,0,0);f.maxDays=parseInt((((c.compdt.getTime()-c.todayc.getTime())/c.lod)),10)}if(e===true){b.refresh()}},_build:{"default":function(){this.d.headerText="Error";this.d.intHTML=a("

      There is no mode by that name loaded / mode not given

      ")}},_applyCoords:function(h){var b=h.widget,j=h.widget.options,f={h:a.mobile.activePage.find(".ui-header").jqmData("position"),f:a.mobile.activePage.find(".ui-footer").jqmData("position"),fh:a.mobile.activePage.find(".ui-footer").outerHeight(),hh:a.mobile.activePage.find(".ui-header").outerHeight()},c={x:b.d.wrap.offset().left+(b.d.wrap.outerWidth()/2),y:b.d.wrap.offset().top+(b.d.wrap.outerHeight()/2)},d={w:b.d.mainWrap.outerWidth(),h:b.d.mainWrap.outerHeight()},g={t:a(window).scrollTop(),h:a(window).height(),w:a.mobile.activePage.width(),ah:a(document).height()},k={y:(j.centerVert)?g.t+((g.h/2)-(d.h/2)):c.y-(d.h/2),x:(g.w<400||j.centerHoriz)?(g.w/2)-(d.w/2):c.x-(d.w/2)};if(j.centerVert===false){if(j.hideFixedToolbars===true&&(typeof f.f!=="undefined"||typeof f.h!=="undefined")){a.mobile.activePage.find(":jqmData(position='fixed')").fixedtoolbar("hide");f.f=undefined;f.h=undefined}if(typeof f.f!=="undefined"){if((k.y+d.h)>(g.h-f.fh-2)){k.y=g.h-f.fh-2-d.h}}else{if((k.y+d.h)>(g.ah-f.fh-2)){k.y=g.ah-f.fh-2-d.h}if((g.h+g.t)<(d.h+k.y+2)){k.y=g.h+g.t-d.h-2}}if(typeof f.h!=="undefined"){if((g.t+f.hh+2)>k.y){k.y=g.t+f.hh+2}}else{if(f.hh+2>k.y){k.y=f.hh+2}if(k.y
      ');a("Close").appendTo(b.d.headHTML).buttonMarkup({theme:g.themeHeader,icon:"delete",iconpos:"notext",corners:true,shadow:true}).on(g.clickEventAlt,function(h){h.preventDefault();b.d.input.trigger("datebox",{method:"close"})});a('

      '+b.d.headerText+"

      ").appendTo(b.d.headHTML);b.d.mainWrap.append(b.d.headHTML)}b.d.mainWrap.append(b.d.intHTML).css("zIndex",g.zindex);b.d.input.trigger("datebox",{method:"postrefresh"});if(g.useAnimation===true){e.transition=g.transition}else{e.transition="none"}if(g.popupForceX!==false&&g.popupForceY!==false){e.x=g.popupForceX;e.y=g.popupForceY}if(g.popupPosition!==false){e.positionTo=g.popupPosition}else{if(typeof b.baseID!==undefined){e.positionTo="#"+b.baseID}else{e.positionTo="window"}}if(g.useModal===true){f.overlayTheme="a"}b.d.mainWrap.removeClass("ui-datebox-hidden").popup(f).popup("open",e);b.refresh()}else{if(g.dialogForce||(g.dialogEnable&&window.width()<400)){b.d.dialogPage=a("

      "+b.d.headerText+"

      ").appendTo(a.mobile.pageContainer).page().css("minHeight","0px").addClass(c);b.d.dialogPage.find(".ui-header").find("a").off("click vclick").on(g.clickEventAlt,function(h){h.preventDefault();b.d.input.trigger("datebox",{method:"close"})});b.d.mainWrap.append(b.d.intHTML).css({marginLeft:"auto",marginRight:"auto"}).removeClass("ui-datebox-hidden");b.d.dialogPage.find(".ui-content").append(b.d.mainWrap);b.d.input.trigger("datebox",{method:"postrefresh"});a.mobile.activePage.off("pagehide.remove");a.mobile.changePage(b.d.dialogPage,{transition:c})}else{b.d.dialogPage=false;b.d.mainWrap.empty();if(g.useHeader===true){b.d.headHTML=a('
      ');a("Close").appendTo(b.d.headHTML).buttonMarkup({theme:g.themeHeader,icon:"delete",iconpos:"notext",corners:true,shadow:true}).on(g.clickEventAlt,function(h){h.preventDefault();b.d.input.trigger("datebox",{method:"close"})});a('

      '+b.d.headerText+"

      ").appendTo(b.d.headHTML);b.d.mainWrap.append(b.d.headHTML)}b.d.mainWrap.append(b.d.intHTML).css("zIndex",g.zindex);b.d.mainWrap.appendTo(a.mobile.activePage);b.d.screen.appendTo(a.mobile.activePage);b.d.input.trigger("datebox",{method:"postrefresh"});b._applyCoords({widget:b});if(g.useModal===true){if(g.useAnimation){b.d.screen.fadeIn("slow")}else{b.d.screen.show()}}else{setTimeout(function(){b.d.screen.removeClass("ui-datebox-hidden")},500)}b.d.mainWrap.addClass("ui-overlay-shadow in").removeClass("ui-datebox-hidden");a(document).on("orientationchange.datebox",{widget:b},function(h){b._applyCoords(h.data)});if(g.resizeListener===true){a(window).on("resize.datebox",{widget:b},function(h){b._applyCoords(h.data)})}}}},close:function(){var b=this,c=this.options;if(c.useInlineBlind===true){b.d.mainWrap.slideUp();return true}if(c.useInline===true||b.d.intHTML===false){return true}if(b.d.dialogPage!==false){a(b.d.dialogPage).dialog("close");if(!a.mobile.activePage.jqmData("mobile-page").options.domCache){a.mobile.activePage.on("pagehide.remove",function(){a(this).remove()})}b.d.intHTML.detach().empty();b.d.mainWrap.detach().empty();b.d.wrap.removeClass("ui-focus");b.clearFunc=setTimeout(function(){b.d.dialogPage.empty().remove();b.clearFunc=false},1500)}else{if(c.enablePopup===true){b.d.mainWrap.popup("close");b.d.wrap.removeClass("ui-focus")}else{if(c.useModal){if(c.useAnimation){b.d.screen.fadeOut("slow")}else{b.d.screen.hide()}}else{b.d.screen.addClass("ui-datebox-hidden")}b.d.screen.detach();b.d.mainWrap.addClass("ui-datebox-hidden").removeAttr("style").removeClass("in ui-overlay-shadow").empty().detach();b.d.intHTML.detach();b.d.wrap.removeClass("ui-focus");a(document).off("orientationchange.datebox");if(c.resizeListener===true){a(window).off("resize.datebox")}}}b.d.wrap.parent().removeClass("ui-focus");a(document).off(b.drag.eMove);a(document).off(b.drag.eEnd);a(document).off(b.drag.eEndA);if(c.useFocus){b.fastReopen=true;setTimeout(function(d){return function(){d.fastReopen=false}}(b),300)}if(c.closeCallback!==false){if(!a.isFunction(c.closeCallback)){if(typeof window[c.closeCallback]!=="undefined"){c.closeCallback=window[c.closeCallback]}else{c.closeCallback=new Function(c.closeCallback)}}c.closeCallback.apply(b,a.merge([b.theDate],c.closeCallbackArgs))}},refresh:function(){if(typeof this._build[this.options.mode]==="undefined"){this._build["default"].apply(this,[])}else{this._build[this.options.mode].apply(this,[])}if(this.__("useArabicIndic")===true){this._doIndic()}this.d.mainWrap.append(this.d.intHTML);this.d.input.trigger("datebox",{method:"postrefresh"})},_check:function(){var b=this,d=null,c=this.options;b.dateOK=true;if(c.afterToday!==false){d=new b._date();if(b.theDated){b.theDate=d}}if(c.maxDays!==false){d=new b._date();d.adj(2,c.maxDays);if(b.theDate>d){b.theDate=d}}if(c.minDays!==false){d=new b._date();d.adj(2,-1*c.minDays);if(b.theDatec.maxHour){b.theDate.setHours(c.maxHour)}}if(c.maxYear!==false){d=new b._date(c.maxYear,0,1);d.adj(2,-1);if(b.theDate>d){b.theDate=d}}if(c.minYear!==false){d=new b._date(c.minYear,0,1);if(b.theDate-1){if(c.mode==="timeflipbox"&&c.validHours!==false){if(a.inArray(b.theDate.getHours(),c.validHours)<0){b.dateOK=false}}}else{if(c.blackDatesRec!==false){for(i=0;i-1){b.dateOK=false}}if(c.blackDays!==false){if(a.inArray(b.theDate.getDay(),c.blackDays)>-1){b.dateOK=false}}}},_grabLabel:function(){var b=this,c=this.options;if(typeof c.overrideDialogLabel==="undefined"){if(typeof b.d.input.attr("placeholder")!=="undefined"){return b.d.input.attr("placeholder")}if(typeof b.d.input.attr("title")!=="undefined"){return b.d.input.attr("title")}if(b.d.wrap.parent().find("label[for='"+b.d.input.attr("id")+"']").text()!==""){return b.d.wrap.parent().find("label[for='"+b.d.input.attr("id")+"']").text()}return false}return c.overrideDialogLabel},_makeEl:function(d,e){var b=false,c=false;c=d.clone();if(typeof e.attr!=="undefined"){for(b in e.attr){if(e.attr.hasOwnProperty(b)){c.jqmData(b,e.attr[b])}}}return c},_getLongOptions:function(d){var c,e={},f,b;if(a.mobile.ns===""){f="datebox"}else{f=a.mobile.ns.substr(0,a.mobile.ns.length-1)+"Datebox"}for(c in d.data()){if(c.substr(0,f.length)===f&&c.length>f.length){b=c.substr(f.length);b=b.charAt(0).toLowerCase()+b.slice(1);e[b]=d.data(c)}}return e},disable:function(){this.d.input.attr("disabled",true);this.d.wrap.addClass("ui-disabled").blur();this.disabled=true;this.d.input.trigger("datebox",{method:"disable"})},enable:function(){this.d.input.attr("disabled",false);this.d.wrap.removeClass("ui-disabled");this.disabled=false;this.d.input.trigger("datebox",{method:"enable"})},_setOption:function(){a.Widget.prototype._setOption.apply(this,arguments);this.refresh()},getTheDate:function(){return this.theDate},getLastDur:function(){return this.lastDuration},setTheDate:function(b){this.theDate=b;this.refresh()},callFormat:function(c,b){return this._formatter(c,b)}});a(document).on("pagebeforecreate",function(b){a(":jqmData(role='datebox')",b.target).each(function(){a(this).prop("type","text")})});a(document).on("pagecreate create",function(b){a(document).trigger("dateboxbeforecreate");a(":jqmData(role='datebox')",b.target).each(function(){var c=typeof(a(this).data(parseInt(a.mobile.version.replace(/\./g,""),10)>111?"mobile-datebox":"datebox"));if(c==="undefined"){a(this).datebox()}})})})(jQuery);(function(a){a.extend(a.mobile.datebox.prototype.options,{themeButton:"a",themeInput:"a",useSetButton:true,validHours:false,repButton:true});a.extend(a.mobile.datebox.prototype,{_dbox_run:function(){var b=this;b.drag.didRun=true;b._offset(b.drag.target[0],b.drag.target[1],false);b._dbox_run_update();b.runButton=setTimeout(function(){b._dbox_run()},150)},_dbox_run_update:function(){var b=this,c=this.options;if(c.mode==="datebox"){b.d.intHTML.find(".ui-datebox-header").find("h4").text(b._formatter(b.__("headerFormat"),b.theDate))}b.d.divIn.find("input").each(function(){switch(a(this).jqmData("field")){case"y":a(this).val(b.theDate.getFullYear());break;case"m":a(this).val(b.theDate.getMonth()+1);break;case"d":a(this).val(b.theDate.getDate());break;case"h":if(b.__("timeFormat")===12){if(b.theDate.getHours()>12){a(this).val(b.theDate.getHours()-12);break}else{if(b.theDate.getHours()===0){a(this).val(12);break}}}a(this).val(b.theDate.getHours());break;case"i":a(this).val(b._zPad(b.theDate.getMinutes()));break;case"M":a(this).val(b.__("monthsOfYearShort")[b.theDate.getMonth()]);break;case"a":a(this).val((b.theDate.getHours()>11)?b.__("meridiem")[1]:b.__("meridiem")[0]);break}})},_dbox_vhour:function(g){var b=this,f=this.options,e,d=[25,0],c=[25,0];if(f.validHours===false){return true}if(a.inArray(b.theDate.getHours(),f.validHours)>-1){return true}e=b.theDate.getHours();a.each(f.validHours,function(){if(((eMath.abs(this-e)){d=[Math.abs(this-e),parseInt(this,10)]}}else{if(c[0]>Math.abs(this-e)){c=[Math.abs(this-e),parseInt(this,10)]}}});if(d[1]!==0){b.theDate.setHours(d[1])}else{b.theDate.setHours(c[1])}},_dbox_enter:function(c){var b=this;if(c.jqmData("field")==="M"&&a.inArray(c.val(),b.__("monthsOfYearShort"))>-1){b.theDate.setMonth(a.inArray(c.val(),b.__("monthsOfYearShort")))}if(c.val()!==""&&c.val().toString().search(/^[0-9]+$/)===0){switch(c.jqmData("field")){case"y":b.theDate.setFullYear(parseInt(c.val(),10));break;case"m":b.theDate.setMonth(parseInt(c.val(),10)-1);break;case"d":b.theDate.setDate(parseInt(c.val(),10));break;case"h":b.theDate.setHours(parseInt(c.val(),10));break;case"i":b.theDate.setMinutes(parseInt(c.val(),10));break}}b.refresh()}});a.extend(a.mobile.datebox.prototype._build,{timebox:function(){this._build.datebox.apply(this,[])},datebox:function(){var u=this,n=this.drag,f=this.options,l,s,m,h=-2,q="ui-datebox-",r=a("
      "),c=a("
      "),j=r.clone(),k=c.clone(),e=a("").addClass("ui-input-text ui-corner-all ui-shadow-inset ui-body-"+f.themeInput),t=a("").addClass("ui-input-text ui-corner-all ui-shadow-inset ui-body-"+f.themeInput),p=a("
      "),b={theme:f.themeButton,icon:"plus",iconpos:"bottom",corners:true,shadow:true,inline:true},d=a.extend({},b,{icon:"minus",iconpos:"top"});if(typeof u.d.intHTML!=="boolean"){u.d.intHTML.empty().remove()}u.d.headerText=((u._grabLabel()!==false)?u._grabLabel():((f.mode==="datebox")?u.__("titleDateDialogLabel"):u.__("titleTimeDialogLabel")));u.d.intHTML=a("");if(u.inputType!=="number"){e.attr("pattern","[0-9]*")}u.fldOrder=((f.mode==="datebox")?u.__("dateFieldOrder"):u.__("timeFieldOrder"));u._check();u._minStepFix();u._dbox_vhour(typeof u._dbox_delta!=="undefined"?u._dbox_delta:1);if(f.mode==="datebox"){a('

      '+u._formatter(u.__("headerFormat"),u.theDate)+"

      ").appendTo(u.d.intHTML)}for(l=0;l<=u.fldOrder.length;l++){m=["a","b","c","d","e","f"][l];switch(u.fldOrder[l]){case"y":case"m":case"d":case"h":a("
      ").append(u._makeEl(e,{attr:{field:u.fldOrder[l],amount:1}})).addClass("ui-block-"+m).appendTo(j);u._makeEl(p,{attr:{field:u.fldOrder[l],amount:1}}).addClass("ui-block-"+m).buttonMarkup(b).appendTo(c);u._makeEl(p,{attr:{field:u.fldOrder[l],amount:1}}).addClass("ui-block-"+m).buttonMarkup(d).appendTo(k);h++;break;case"a":if(u.__("timeFormat")===12){a("
      ").append(u._makeEl(t,{attr:{field:u.fldOrder[l],amount:1}})).addClass("ui-block-"+m).appendTo(j);u._makeEl(p,{attr:{field:u.fldOrder[l],amount:1}}).addClass("ui-block-"+m).buttonMarkup(b).appendTo(c);u._makeEl(p,{attr:{field:u.fldOrder[l],amount:1}}).addClass("ui-block-"+m).buttonMarkup(d).appendTo(k);h++}break;case"M":a("
      ").append(u._makeEl(t,{attr:{field:u.fldOrder[l],amount:1}})).addClass("ui-block-"+m).appendTo(j);u._makeEl(p,{attr:{field:u.fldOrder[l],amount:1}}).addClass("ui-block-"+m).buttonMarkup(b).appendTo(c);u._makeEl(p,{attr:{field:u.fldOrder[l],amount:1}}).addClass("ui-block-"+m).buttonMarkup(d).appendTo(k);h++;break;case"i":a("
      ").append(u._makeEl(e,{attr:{field:u.fldOrder[l],amount:f.minuteStep}})).addClass("ui-block-"+m).appendTo(j);u._makeEl(p,{attr:{field:u.fldOrder[l],amount:f.minuteStep}}).addClass("ui-block-"+m).buttonMarkup(b).appendTo(c);u._makeEl(p,{attr:{field:u.fldOrder[l],amount:f.minuteStep}}).addClass("ui-block-"+m).buttonMarkup(d).appendTo(k);h++;break}}c.addClass("ui-grid-"+["a","b","c","d","e"][h]).appendTo(u.d.intHTML);j.addClass("ui-datebox-dboxin").addClass("ui-grid-"+["a","b","c","d","e"][h]).appendTo(u.d.intHTML);k.addClass("ui-grid-"+["a","b","c","d","e"][h]).appendTo(u.d.intHTML);if(f.mobVer>=140){k.find("div").css({"min-height":"2.3em"});c.find("div").css({"min-height":"2.3em"})}j.find("input").each(function(){switch(a(this).jqmData("field")){case"y":a(this).val(u.theDate.getFullYear());break;case"m":a(this).val(u.theDate.getMonth()+1);break;case"d":a(this).val(u.theDate.getDate());break;case"h":if(u.__("timeFormat")===12){if(u.theDate.getHours()>12){a(this).val(u.theDate.getHours()-12);break}else{if(u.theDate.getHours()===0){a(this).val(12);break}}}a(this).val(u.theDate.getHours());break;case"i":a(this).val(u._zPad(u.theDate.getMinutes()));break;case"M":a(this).val(u.__("monthsOfYearShort")[u.theDate.getMonth()]);break;case"a":a(this).val((u.theDate.getHours()>11)?u.__("meridiem")[1]:u.__("meridiem")[0]);break}});u.d.divIn=j;if(u.dateOK!==true){j.find("input").addClass(q+"griddate-disable")}else{j.find("."+q+"griddate-disable").removeClass(q+"griddate-disable")}if(f.useSetButton||f.useClearButton){s=a("
      ",{"class":q+"controls"});if(f.useSetButton){a(''+((f.mode==="datebox")?u.__("setDateButtonLabel"):u.__("setTimeButtonLabel"))+"").appendTo(s).buttonMarkup({theme:f.theme,icon:"check",iconpos:"left",corners:true,shadow:true}).on(f.clickEventAlt,function(g){g.preventDefault();if(u.dateOK===true){u.d.input.trigger("datebox",{method:"set",value:u._formatter(u.__fmt(),u.theDate),date:u.theDate});u.d.input.trigger("datebox",{method:"close"})}})}if(f.useClearButton){a(''+u.__("clearButton")+"").appendTo(s).buttonMarkup({theme:f.theme,icon:"delete",iconpos:"left",corners:true,shadow:true}).on(f.clickEventAlt,function(g){g.preventDefault();u.d.input.val("");u.d.input.trigger("datebox",{method:"clear"});u.d.input.trigger("datebox",{method:"close"})})}if(f.useCollapsedBut){s.addClass("ui-datebox-collapse")}s.appendTo(u.d.intHTML)}if(f.repButton===false){c.on(f.clickEvent,"div",function(g){g.preventDefault();u._dbox_delta=1;u._offset(a(this).jqmData("field"),a(this).jqmData("amount"))});k.on(f.clickEvent,"div",function(g){g.preventDefault();u._dbox_delta=-1;u._offset(a(this).jqmData("field"),a(this).jqmData("amount")*-1)})}j.on("change","input",function(){u._dbox_enter(a(this))});if(u.wheelExists){j.on("mousewheel","input",function(g,i){g.preventDefault();u._dbox_delta=i<0?-1:1;u._offset(a(this).jqmData("field"),((i<0)?-1:1)*a(this).jqmData("amount"))})}if(f.repButton===true){c.on(u.drag.eStart,"div",function(g){m=[a(this).jqmData("field"),a(this).jqmData("amount")];u.drag.move=true;u._dbox_delta=1;u._offset(m[0],m[1],false);u._dbox_run_update();if(!u.runButton){u.drag.target=m;u.runButton=setTimeout(function(){u._dbox_run()},500)}});k.on(u.drag.eStart,"div",function(g){m=[a(this).jqmData("field"),a(this).jqmData("amount")*-1];u.drag.move=true;u._dbox_delta=-1;u._offset(m[0],m[1],false);u._dbox_run_update();if(!u.runButton){u.drag.target=m;u.runButton=setTimeout(function(){u._dbox_run()},500)}});c.on(n.eEndA,function(g){if(n.move){g.preventDefault();clearTimeout(u.runButton);u.runButton=false;n.move=false}});k.on(n.eEndA,function(g){if(n.move){g.preventDefault();clearTimeout(u.runButton);u.runButton=false;n.move=false}})}}})})(jQuery); \ No newline at end of file diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.durationbox.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.durationbox.js new file mode 100644 index 000000000..6f9831fdf --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.durationbox.js @@ -0,0 +1,1612 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +/* CORE Functions */ + +(function($) { + $.widget( "mobile.datebox", $.mobile.widget, { + options: { + // All widget options, including some internal runtime details + version: '2-1.4.0-2013070300', // jQMMajor.jQMMinor.DBoxMinor-YrMoDaySerial + mobVer: parseInt($.mobile.version.replace(/\./g,'')), + theme: false, + themeDefault: 'a', + themeHeader: 'a', + mode: false, + + centerHoriz: false, + centerVert: false, + transition: 'pop', + useAnimation: true, + hideInput: false, + hideFixedToolbars: false, + + lockInput: true, + enhanceInput: true, + + zindex: '500', + clickEvent: 'vclick', + clickEventAlt: 'click', + resizeListener: true, + + defaultValue: false, + showInitialValue: false, + + dialogEnable: false, + dialogForce: false, + enablePopup: false, + + popupPosition: false, + popupForceX: false, + popupForceY: false, + + useModal: false, + useInline: false, + useInlineBlind: false, + useHeader: true, + useImmediate: false, + useNewStyle: false, + useAltIcon: false, + overrideStyleClass: false, + + useButton: true, + useFocus: false, + useClearButton: false, + useCollapsedBut: false, + usePlaceholder: false, + + openCallback: false, + openCallbackArgs: [], + closeCallback: false, + closeCallbackArgs: [], + + startOffsetYears: false, + startOffsetMonths: false, + startOffsetDays: false, + afterToday: false, + beforeToday: false, + notToday: false, + maxDays: false, + minDays: false, + maxYear: false, + minYear: false, + blackDates: false, + blackDatesRec: false, + blackDays: false, + minHour: false, + maxHour: false, + minuteStep: 1, + minuteStepRound: 0, + + rolloverMode: { 'm': true, 'd': true, 'h': true, 'i': true, 's': true }, + + useLang: 'default', + lang: { + 'default' : { + setDateButtonLabel: 'Set Date', + setTimeButtonLabel: 'Set Time', + setDurationButtonLabel: 'Set Duration', + calTodayButtonLabel: 'Jump to Today', + titleDateDialogLabel: 'Set Date', + titleTimeDialogLabel: 'Set Time', + daysOfWeek: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], + daysOfWeekShort: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], + monthsOfYear: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], + monthsOfYearShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + durationLabel: ['Days', 'Hours', 'Minutes', 'Seconds'], + durationDays: ['Day', 'Days'], + timeFormat: 24, + headerFormat: '%A, %B %-d, %Y', + tooltip: 'Open Date Picker', + nextMonth: 'Next Month', + prevMonth: 'Previous Month', + dateFieldOrder: ['m', 'd', 'y'], + timeFieldOrder: ['h', 'i', 'a'], + slideFieldOrder: ['y', 'm', 'd'], + dateFormat: '%Y-%m-%d', + useArabicIndic: false, + isRTL: false, + calStartDay: 0, + clearButton: 'Clear', + durationOrder: ['d', 'h', 'i', 's'], + meridiem: ['AM', 'PM'], + timeOutput: '%k:%M', //{ '12': '%l:%M %p', '24': '%k:%M' }, + durationFormat: '%Dd %DA, %Dl:%DM:%DS', + calDateListLabel: 'Other Dates', + calHeaderFormat: '%B %Y' + } + } + }, + _enhanceDate: function() { + $.extend(this._date.prototype, { + copy: function(adjust, override) { + /* Get a modified copy of the date. + * First array - Offset the new date by # (position determines date part) + * Second array - If non-zero, force the new date by # (position determines date part) + */ + if ( typeof adjust === 'undefined' ) { adjust = [0,0,0,0,0,0,0]; } + if ( typeof override === 'undefined' ) { override = [0,0,0,0,0,0,0]; } + while ( adjust.length < 7 ) { adjust.push(0); } + while ( override.length < 7 ) { override.push(0); } + return new Date( + ((override[0] > 0 ) ? override[0] : this.getFullYear() + adjust[0]), + ((override[1] > 0 ) ? override[1] : this.getMonth() + adjust[1]), + ((override[2] > 0 ) ? override[2] : this.getDate() + adjust[2]), + ((override[3] > 0 ) ? override[3] : this.getHours() + adjust[3]), + ((override[4] > 0 ) ? override[4] : this.getMinutes() + adjust[4]), + ((override[5] > 0 ) ? override[5] : this.getSeconds() + adjust[5]), + ((override[6] > 0 ) ? override[5] : this.getMilliseconds() + adjust[6])); + }, + adj: function (type, amount) { + /* Adjust the date. Yes, this is chainable */ + if ( typeof amount !== 'number' ) { + throw new Error("Adjustment value not specified"); + } + if ( typeof type !== 'number' ) { + throw new Error("Adjustment type not specified"); + } + switch ( type ) { + case 0: this.setFullYear(this.getFullYear() + amount); break; + case 1: this.setMonth(this.getMonth() + amount); break; + case 2: this.setDate(this.getDate() + amount); break; + case 3: this.setHours(this.getHours() + amount); break; + case 4: this.setMinutes(this.getMinutes() + amount); break; + case 5: this.setSeconds(this.getSeconds() + amount); break; + case 6: this.setMilliseconds(this.getMilliseconds() + amount); break; + } + return this; + }, + setD: function(type, amount) { + /* A chainable version of setWhatever() */ + switch ( type ) { + case 0: this.setFullYear(amount); break; + case 1: this.setMonth(amount); break; + case 2: this.setDate(amount); break; + case 3: this.setHours(amount); break; + case 4: this.setMinutes(amount); break; + case 5: this.setSeconds(amount); break; + case 6: this.setMilliseconds(amount); break; + } + return this; + }, + get: function(type) { + switch ( type ) { + case 0: return this.getFullYear(); + case 1: return this.getMonth(); + case 2: return this.getDate(); + case 3: return this.getHours(); + case 4: return this.getMinutes(); + case 5: return this.getSeconds(); + } + return false; + }, + iso: function() { + return String(this.getFullYear()) + '-' + (( this.getMonth() < 9 ) ? "0" : "") + String(this.getMonth()+1) + '-' + ((this.getDate() < 10 ) ? "0" : "") + String(this.getDate()); + }, + comp: function () { + return parseInt(this.iso().replace(/-/g,''),10); + }, + getEpoch: function() { + return (this.getTime() - this.getMilliseconds()) / 1000; + }, + getArray: function() { + return [this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds()]; + }, + setFirstDay: function (day) { + this.setD(2,1).adj(2, (day - this.getDay())); + if ( this.get(2) > 10 ) { this.adj(2,7); } + return this; + }, + setDWeek: function (type,num) { + if ( type === 4 ) { + return this.setD(1,0).setD(2,1).setFirstDay(4).adj(2,-3).adj(2,(num-1)*7); + } + return this.setD(1,0).setD(2,1).setFirstDay(type).adj(2,(num-1)*7); + }, + getDWeek: function (type) { + var t1, t2; + + switch ( type ) { + case 0: + t1 = this.copy([0,-1*this.getMonth()]).setFirstDay(0); + return Math.floor((this.getTime() - ( t1.getTime() + (( this.getTimezoneOffset() - t1.getTimezoneOffset()) * 60000))) / 6048e5) + 1; + //return Math.floor((this.getTime() - t1.getTime()) / 6048e5) + 1; + case 1: + t1 = this.copy([0,-1*this.getMonth()]).setFirstDay(1); + return Math.floor((this.getTime() - ( t1.getTime() + (( this.getTimezoneOffset() - t1.getTimezoneOffset()) * 60000))) / 6048e5) + 1; + //return Math.floor((this.getTime() - t1.getTime()) / 6048e5) + 1; + case 4: + // this line is some bullshit. but it does work. + // (trap for dec 29, 30, or 31st being in the new year's week - these are the + // only 3 that can possibly fall like this) + if ( this.getMonth() === 11 && this.getDate() > 28 ) { return 1; } + + t1 = this.copy([0,-1*this.getMonth()],true).setFirstDay(4).adj(2,-3); + t2 = Math.floor((this.getTime() - ( t1.getTime() + (( this.getTimezoneOffset() - t1.getTimezoneOffset()) * 60000))) / 6048e5) + 1; + + if ( t2 < 1 ) { + t1 = this.copy([-1,-1*this.getMonth()]).setFirstDay(4).adj(2,-3); + return Math.floor((this.getTime() - t1.getTime()) / 6048e5) + 1; + } + return t2; + default: + return 0; + } + } + }); + }, + _event: function(e, p) { + var w = $(this).data(parseInt($.mobile.version.replace(/\./g,''),10) > 110 ? 'mobile-datebox' : 'datebox'); + if ( ! e.isPropagationStopped() ) { + switch (p.method) { + case 'close': + w.close(); break; + case 'open': + w.open(); break; + case 'set': + $(this).val(p.value); + $(this).trigger('change'); + break; + case 'doset': + if ( $.isFunction(w['_'+w.options.mode+'DoSet']) ) { + w['_'+w.options.mode+'DoSet'].apply(w,[]); + } else { + $(this).trigger('datebox', {'method':'set', 'value':w._formatter(w.__fmt(), w.theDate), 'date':w.theDate}); + } + break; + case 'dooffset': + if (p.type) { w._offset(p.type, p.amount, true); } break; + case 'dorefresh': + w.refresh(); break; + case 'doreset': + w.hardreset(); break; + case 'doclear': + $(this).val('').trigger('change'); break; + case 'clear': + $(this).trigger('change'); + } + } + }, + _hoover: function(item) { + // Hover toggle class, for calendar + $(item).toggleClass('ui-btn-up-'+$(item).jqmData('theme')+' ui-btn-down-'+$(item).jqmData('theme')); + }, + _ord: { + 'default': function (num) { + // Return an ordinal suffix (1st, 2nd, 3rd, etc) + var ending = num % 10; + if ( num > 9 && num < 21 ) { return 'th'; } + if ( ending > 3 ) { return 'th'; } + return ['th','st','nd','rd'][ending]; + } + }, + __ : function(val) { + var o = this.options, + oride = 'override' + val.charAt(0).toUpperCase() + val.slice(1); + + if ( typeof o[oride] !== 'undefined' ) { return o[oride]; } + if ( typeof o.lang[o.useLang][val] !== 'undefined' ) { return o.lang[o.useLang][val]; } + if ( typeof o[o.mode+'lang'] !== 'undefined' && typeof o[o.mode+'lang'][val] !== 'undefined' ) { return o[o.mode+'lang'][val]; } + return o.lang['default'][val]; + }, + __fmt: function() { + var w = this, + o = this.options; + + switch ( o.mode ) { + case 'timebox': + case 'timeflipbox': + return w.__('timeOutput'); + case 'durationbox': + case 'durationflipbox': + return w.__('durationFormat'); + default: + return w.__('dateFormat'); + } + }, + _zPad: function(number) { + return (( number < 10 ) ? '0' + String(number) : String(number)); + }, + _dRep: function(oper, direction) { + var start = 48, + end = 57, + adder = 1584, + i = null, + ch = null, + newd = ''; + + if ( direction === -1 ) { + start += adder; + end += adder; + adder = -1584; + } + + for ( i=0; i= start && ch <= end ) { + newd = newd + String.fromCharCode(ch+adder); + } else { + newd = newd + String.fromCharCode(ch); + } + } + + return newd; + }, + _doIndic: function() { + var w = this; + + w.d.intHTML.find('*').each(function() { + if ( $(this).children().length < 1 ) { + $(this).text(w._dRep($(this).text())); + } else if ( $(this).hasClass('ui-datebox-slideday') ) { + $(this).html(w._dRep($(this).html())); + } + }); + w.d.intHTML.find('input').each(function() { + $(this).val(w._dRep($(this).val())); + }); + }, + _parser: { + 'default': function (str) { return false; } + }, + _n: function (val,def) { + return ( val < 0 ) ? def : val; + }, + _pa: function (arr,date) { + if ( typeof date === 'boolean' ) { return new this._date(arr[0],arr[1],arr[2],0,0,0,0); } + return new this._date(date.getFullYear(), date.getMonth(), date.getDate(), arr[0], arr[1], arr[2], 0); + }, + _makeDate: function (str) { + // Date Parser + str = $.trim(((this.__('useArabicIndic') === true)?this._dRep(str, -1):str)); + var w = this, + o = this.options, + adv = w.__fmt(), + exp_input = null, + exp_names = [], + exp_format = null, + exp_temp = null, + date = new w._date(), + d = { year: -1, mont: -1, date: -1, hour: -1, mins: -1, secs: -1, week: false, wtyp: 4, wday: false, yday: false, meri: 0 }, + i; + + if ( typeof o.mode === 'undefined' ) { return date; } + if ( typeof w._parser[o.mode] !== 'undefined' ) { return w._parser[o.mode].apply(w,[str]); } + + if ( o.mode === 'durationbox' || o.mode === 'durationflipbox' ) { + adv = adv.replace(/%D([a-z])/gi, function(match, oper) { + switch (oper) { + case 'd': + case 'l': + case 'M': + case 'S': return '(' + match + '|' +'[0-9]+' + ')'; + default: return '.+?'; + } + }); + + adv = new RegExp('^' + adv + '$'); + exp_input = adv.exec(str); + exp_format = adv.exec(w.__fmt()); + + if ( exp_input === null || exp_input.length !== exp_format.length ) { + if ( typeof o.defaultValue === "number" && o.defaultValue > 0 ) { + return new w._date((w.initDate.getEpoch() + parseInt(o.defaultValue,10))*1000); + } + return new w._date(w.initDate.getTime()); + } + + exp_temp = w.initDate.getEpoch(); + for ( i=0; i -1 ) { d.mont = exp_temp; } + break; + case 'B': + exp_temp = $.inArray(exp_input[i], w.__('monthsOfYear')); + if ( exp_temp > -1 ) { d.mont = exp_temp; } + break; + } + } + if ( d.meri !== 0 ) { + if ( d.meri === -1 && d.hour === 12 ) { d.hour = 0; } + if ( d.meri === 1 && d.hour !== 12 ) { d.hour = d.hour + 12; } + } + + date = new w._date(w._n(d.year,0),w._n(d.mont,0),w._n(d.date,1),w._n(d.hour,0),w._n(d.mins,0),w._n(d.secs,0),0); + + if ( d.year < 100 && d.year !== -1 ) { date.setFullYear(d.year); } + + if ( ( d.mont > -1 && d.date > -1 ) || ( d.hour > -1 && d.mins > -1 && d.secs > -1 ) ) { return date; } + + if ( d.week !== false ) { + date.setDWeek(d.wtyp, d.week); + if ( d.date > -1 ) { date.setDate(d.date); } + } + if ( d.yday !== false ) { date.setD(1,0).setD(2,1).adj(2,(d.yday-1)); } + if ( d.wday !== false ) { date.adj(2,(d.wday - date.getDay())); } + } + return date; + }, + _customformat: { + 'default': function(oper, date) { return false; } + }, + _formatter: function(format, date) { + var w = this, + o = this.options, tmp, + dur = { + part: [0,0,0,0], tp: 0 + }; + + if ( o.mode === 'durationbox' || o.mode === 'durationflipbox' ) { + dur.tp = this.theDate.getEpoch() - this.initDate.getEpoch(); + dur.part[0] = parseInt( dur.tp / (60*60*24),10); dur.tp -=(dur.part[0]*60*60*24); // Days + dur.part[1] = parseInt( dur.tp / (60*60),10); dur.tp -= (dur.part[1]*60*60); // Hours + dur.part[2] = parseInt( dur.tp / (60),10); dur.tp -= (dur.part[2]*60); // Minutes + dur.part[3] = dur.tp; // Seconds + + if ( ! format.match(/%Dd/) ) { dur.part[1] += (dur.part[0]*24);} + if ( ! format.match(/%Dl/) ) { dur.part[2] += (dur.part[1]*60);} + if ( ! format.match(/%DM/) ) { dur.part[3] += (dur.part[2]*60);} + } + + format = format.replace(/%(D|X|0|-)*([1-9a-zA-Z])/g, function(match, pad, oper) { + if ( pad === 'X' ) { + if ( typeof w._customformat[o.mode] !== 'undefined' ) { return w._customformat[o.mode](oper, date, o); } + return match; + } + if ( pad === 'D' ) { + switch ( oper ) { + case 'd': return dur.part[0]; + case 'l': return w._zPad(dur.part[1]); + case 'M': return w._zPad(dur.part[2]); + case 'S': return w._zPad(dur.part[3]); + case 'A': return ((dur.part[0] > 1)?w.__('durationDays')[1]:w.__('durationDays')[0]); + default: return match; + } + } + switch ( oper ) { + case '%': // Literal % + return '%'; + case 'a': // Short Day + return w.__('daysOfWeekShort')[date.getDay()]; + case 'A': // Full Day of week + return w.__('daysOfWeek')[date.getDay()]; + case 'b': // Short month + return w.__('monthsOfYearShort')[date.getMonth()]; + case 'B': // Full month + return w.__('monthsOfYear')[date.getMonth()]; + case 'C': // Century + return date.getFullYear().toString().substr(0,2); + case 'd': // Day of month + return (( pad === '-' ) ? date.getDate() : w._zPad(date.getDate())); + case 'H': // Hour (01..23) + case 'k': + return (( pad === '-' ) ? date.getHours() : w._zPad(date.getHours())); + case 'I': // Hour (01..12) + case 'l': + return (( pad === '-' ) ? ((date.getHours() === 0 || date.getHours() === 12)?12:((date.getHours()<12)?date.getHours():(date.getHours()-12))) : w._zPad(((date.getHours() === 0 || date.getHours() === 12)?12:((date.getHours()<12)?date.getHours():date.getHours()-12)))); + case 'm': // Month + return (( pad === '-' ) ? date.getMonth()+1 : w._zPad(date.getMonth()+1)); + case 'M': // Minutes + return (( pad === '-' ) ? date.getMinutes() : w._zPad(date.getMinutes())); + case 'p': // AM/PM (ucase) + return ((date.getHours() < 12)?w.__('meridiem')[0].toUpperCase():w.__('meridiem')[1].toUpperCase()); + case 'P': // AM/PM (lcase) + return ((date.getHours() < 12)?w.__('meridiem')[0].toLowerCase():w.__('meridiem')[1].toLowerCase()); + case 's': // Unix Seconds + return date.getEpoch(); + case 'S': // Seconds + return (( pad === '-' ) ? date.getSeconds() : w._zPad(date.getSeconds())); + case 'u': // Day of week (1-7) + return (( pad === '-' ) ? date.getDay() + 1 : w._zPad(date.getDay() + 1)); + case 'w': // Day of week + return date.getDay(); + case 'y': // Year (2 digit) + return date.getFullYear().toString().substr(2,2); + case 'Y': // Year (4 digit) + return date.getFullYear(); + case 'E': // BE (Buddist Era, 4 Digit) + return date.getFullYear() + 543; + case 'V': + return (( pad === '-' ) ? date.getDWeek(4) : w._zPad(date.getDWeek(4))); + case 'U': + return (( pad === '-' ) ? date.getDWeek(0) : w._zPad(date.getDWeek(0))); + case 'W': + return (( pad === '-' ) ? date.getDWeek(1) : w._zPad(date.getDWeek(1))); + case 'o': // Ordinals + if ( typeof w._ord[o.useLang] !== 'undefined' ) { return w._ord[o.useLang](date.getDate()); } + return w._ord['default'](date.getDate()); + case 'j': + tmp = new Date(date.getFullYear(),0,1); + tmp = Math.ceil((date - tmp) / 86400000)+1; + return (( tmp < 100 ) ? (( tmp < 10 )? '00' : '0') : '' ) + String(tmp); + case 'G': + if ( date.getDWeek(4) === 1 && date.getMonth() > 0 ) { return date.getFullYear() + 1; } + if ( date.getDWeek(4) > 51 && date.getMonth() < 11 ) { return date.getFullYear() - 1; } + return date.getFullYear(); + case 'g': + if ( date.getDWeek(4) === 1 && date.getMonth() > 0 ) { return parseInt(date.getFullYear().toString().substr(2,2),10) + 1; } + if ( date.getDWeek(4) > 51 && date.getMonth() < 11 ) { return parseInt(date.getFullYear().toString().substr(2,2),10) - 1; } + return date.getFullYear().toString().substr(2,2); + default: + return match; + } + }); + + if ( w.__('useArabicIndic') === true ) { + format = w._dRep(format); + } + + return format; + }, + _btwn: function(value, low, high) { + return ( value > low && value < high ); + }, + _minStepFix: function() { + var tempMin = this.theDate.get(4), tmp, + w = this, + o = this.options; + + if ( o.minuteStep > 1 && tempMin % o.minuteStep > 0 ) { + if ( o.minuteStepRound < 0 ) { + tempMin = tempMin - (tempMin % o.minuteStep); + } else if ( o.minStepRound > 0 ) { + tempMin = tempMin + ( o.minuteStep - ( tempMin % o.minuteStep ) ); + } else { + if ( tempMin % o.minuteStep < o.minuteStep / 2 ) { + tempMin = tempMin - (tempMin % o.minuteStep); + } else { + tempMin = tempMin + ( o.minuteStep - ( tempMin % o.minuteStep ) ); + } + } + w.theDate.setMinutes(tempMin); + } + }, + _offset: function(mode, amount, update) { + // Compute a date/time offset. + // update = false to prevent controls refresh + var w = this, + o = this.options, + ok = false; + + mode = (mode || "").toLowerCase(); + + if ( typeof(update) === "undefined" ) { update = true; } + w.d.input.trigger('datebox', {'method':'offset', 'type':mode, 'amount':amount}); + + if ( mode !== 'a' && ( typeof o.rolloverMode[mode] === 'undefined' || o.rolloverMode[mode] === true )) { + ok = $.inArray(mode, ['y','m','d','h','i','s']); + } else { + switch(mode) { + case 'y': ok = 0; break; + case 'm': + if ( w._btwn(w.theDate.getMonth()+amount,-1,12) ) { ok = 1; } + break; + case 'd': + if ( w._btwn(w.theDate.getDate() + amount,0,(32 - w.theDate.copy([0],[0,0,32,13]).getDate() + 1) )) { ok = 2; } + break; + case 'h': + if ( w._btwn(w.theDate.getHours() + amount,-1,24) ) { ok = 3; } + break; + case 'i': + if ( w._btwn(w.theDate.getMinutes() + amount,-1,60) ) { ok = 4; } + break; + case 's': + if ( w._btwn(w.theDate.getSeconds() + amount,-1,60) ) { ok = 5; } + break; + case 'a': + w._offset('h',((amount>0)?1:-1)*12,false); + break; + } + } + if ( ok !== false ) { w.theDate.adj(ok,amount); } + if ( update === true ) { w.refresh(); } + if ( o.useImmediate ) { w.d.input.trigger('datebox', {'method':'doset'}); } + }, + _startOffset: function(date) { + var o = this.options; + + if ( o.startOffsetYears !== false ) { + date.adj(0, o.startOffsetYears); + } + if ( o.startOffsetMonths !== false ) { + date.adj(1, o.startOffsetMonths); + } + if ( o.startOffsetDays !== false ) { + date.adj(2, o.startOffsetDays); + } + return date; + }, + _create: function() { + // Create the widget, called automatically by widget system + $( document ).trigger( "dateboxcreate" ); + + var w = this, + o = $.extend(this.options, (typeof this.element.jqmData('options') !== 'undefined') ? this.element.jqmData('options') : this._getLongOptions(this.element) ), + thisTheme = ( o.theme === false && typeof($(this).jqmData('theme')) === 'undefined' ) ? + ( ( typeof(this.element.parentsUntil(':jqmData(theme)').parent().jqmData('theme')) === 'undefined' ) ? + o.themeDefault : this.element.parentsUntil(':jqmData(theme)').parent().jqmData('theme') ) + : o.theme, + trans = o.useAnimation ? o.transition : 'none', + d = o.useNewStyle === false ? { + input: this.element, + wrap: this.element.wrap('
      ').parent(), + mainWrap: $("
      ", { "class": 'ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden '+trans+' ui-body-'+thisTheme} ).css('zIndex', o.zindex), + intHTML: false + } : { + input: this.element, + wrap: this.element, + mainWrap: $("
      ", { "class": 'ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden '+trans+' ui-body-'+thisTheme} ).css('zIndex', o.zindex), + intHTML: false + }, + touch = ( typeof window.ontouchstart !== 'undefined' ), + drag = { + eStart : (touch ? 'touchstart' : 'mousedown')+'.datebox', + eMove : (touch ? 'touchmove' : 'mousemove')+'.datebox', + eEnd : (touch ? 'touchend' : 'mouseup')+'.datebox', + eEndA : (touch ? 'mouseup.datebox touchend.datebox touchcancel.datebox touchmove.datebox' : 'mouseup.datebox'), + move : false, + start : false, + end : false, + pos : false, + target : false, + delta : false, + tmp : false + }, + calc = { }, + ns = (typeof $.mobile.ns !== 'undefined')?$.mobile.ns:''; + + $.extend(w, {d: d, ns: ns, drag: drag, touch:touch}); + + if ( o.usePlaceholder !== false ) { + if ( o.usePlaceholder === true && w._grabLabel() !== false ) { w.d.input.attr('placeholder', w._grabLabel()); } + if ( typeof o.usePlaceholder === 'string' ) { w.d.input.attr('placeholder', o.usePlaceholder); } + } + + o.theme = thisTheme; + + w.clearFunc = false; + w.disabled = false; + w.runButton = false; + w._date = window.Date; + w._enhanceDate(); + w.baseID = w.d.input.attr('id'); + + w.initDate = new w._date(); + w.theDate = (o.defaultValue) ? w._makeDate(o.defaultValue) : ( (w.d.input.val() !== "") ? w._makeDate(w.d.input.val()) : new w._date() ); + w.initDone = false; + + if ( o.showInitialValue === true ) { + w.d.input.val(w._formatter(w.__fmt(), w.theDate)); + } + + if ( o.useButton === true && o.useInline === false && o.useNewStyle === false ) { + w.d.open = $(''+this.__('tooltip')+'') + .on(o.clickEvent, function(e) { + e.preventDefault(); + if ( !w.disabled ) { w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.parent().addClass('ui-focus'); w.d.input.parent().removeClass('ui-focus'); } + setTimeout( function() { $(e.target).closest('a').removeClass($.mobile.activeBtnClass); }, 300); + }).appendTo(w.d.wrap).buttonMarkup({icon: 'grid', iconpos: 'notext', corners:true, shadow:true}) + .css({'vertical-align': 'middle', 'display': 'inline-block'}); + } + + w.d.screen = $("
      ", {'class':'ui-datebox-screen ui-datebox-hidden'+((o.useModal)?' ui-datebox-screen-modal':'')}) + .css({'z-index': o.zindex-1}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.trigger('datebox', {'method':'close'}); + }); + + if ( o.enhanceInput === true && navigator.userAgent.match(/Android/i) ){ + w.inputType = 'number'; + } else { + w.inputType = 'text'; + } + + if ( o.hideInput ) { w.d.wrap.parent().hide(); } + + if ( o.mobVer < 140 ) { + $('label[for=\''+w.d.input.attr('id')+'\']').addClass('ui-input-text').css('verticalAlign', 'middle'); + } + + w.d.wrap.on(o.clickEvent, function() { + if ( !w.disabled && ( o.noButtonFocusMode || o.focusMode ) ) { + w.d.input.trigger('datebox', {'method': 'open'}); + w.d.wrap.addClass('ui-focus'); + w.d.input.removeClass('ui-focus'); + } + }); + + w.d.input + .removeClass('ui-corner-all ui-shadow-inset') + .bind(w.touch?'touchend':'click', function(e){ + if ( w.disabled === false && o.useNewStyle === true && o.useFocus === false ) { + if ( ((w.touch ? e.originalEvent.changedTouches[0].pageX : e.pageX) - e.target.offsetLeft) > (e.target.offsetWidth - 20) ) { + w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.parent().addClass('ui-focus'); w.d.input.removeClass('ui-focus'); + //setTimeout(function(){w.d.wrap.addClass('ui-focus');}, 200); + } + } + }) + .focus(function(){ + if ( w.disabled === false && o.useFocus === true ) { + w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.addClass('ui-focus'); w.d.input.removeClass('ui-focus'); + if ( o.useNewStyle === false ) { w.d.input.parent().removeClass('ui-focus'); w.d.wrap.parent().addClass('ui-focus'); } + } + if ( o.useNewStyle === false ) { w.d.input.removeClass('ui-focus'); } + }) + .blur(function(){ + w.d.wrap.removeClass('ui-focus'); + w.d.input.removeClass('ui-focus'); + }) + .change(function() { + w.theDate = w._makeDate(w.d.input.val()); + w.refresh(); + }) + .attr("readonly", o.lockInput) + .on('datebox', w._event); + + if ( o.useNewStyle === true ) { + w.d.input.addClass('ui-corner-all '+((o.useAltIcon===true)?'ui-icon-datebox-alt':'ui-icon-datebox')); + if ( o.overrideStyleClass !== false ) { w.d.input.addClass(o.overrideStyleClass); } + } else { + w.d.input.parent().css('border', 'none').removeClass('ui-shadow-inset'); + } + + w.d.wrap.parent().on(o.clickEvent, function() { + if ( !w.disabled && o.useFocus === true && o.useNewStyle === false ) { + w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.addClass('ui-focus'); w.d.input.removeClass('ui-focus'); + setTimeout(function(){ + w.d.wrap.removeClass('ui-focus'); + w.d.wrap.parent().addClass('ui-focus'); + }, 500); + } + }); + + // Check if mousewheel plugin is loaded + if ( typeof $.event.special.mousewheel !== 'undefined' ) { w.wheelExists = true; } + + // Disable when done if element attribute disabled is true. + if ( w.d.input.is(':disabled') ) { + w.disable(); + } + + if ( o.useInline === true || o.useInlineBlind ) { w.open(); } + + w.applyMinMax(false, false); + + //Throw dateboxinit event + $( document ).trigger( "dateboxaftercreate" ); + }, + applyMinMax: function(refresh, override) { + var w = this, + o = this.options, + calc = {}; + + if ( typeof refresh === 'undefined' ) { refresh = false; } + if ( typeof override === 'undefined' ) { override = true; } + + if ( ( override === true || o.minDays === false ) && typeof(w.d.input.attr('min')) !== 'undefined' ) { + calc.today = new w._date(); + calc.lod = 24 * 60 * 60 * 1000; + calc.todayc = new w._date(calc.today.getFullYear(), calc.today.getMonth(), calc.today.getDate(), 0,0,0,0); + calc.fromel = w.d.input.attr('min').split('-'); + calc.compdt = new w._date(calc.fromel[0],calc.fromel[1]-1,calc.fromel[2],0,0,0,0); + o.minDays = parseInt((((calc.compdt.getTime() - calc.todayc.getTime()) / calc.lod))*-1,10); + } + if ( ( override === true || o.maxDays === false ) && typeof(w.d.input.attr('max')) !== 'undefined' ) { + calc.today = new w._date(); + calc.lod = 24 * 60 * 60 * 1000; + calc.todayc = new w._date(calc.today.getFullYear(), calc.today.getMonth(), calc.today.getDate(), 0,0,0,0); + calc.fromel = w.d.input.attr('max').split('-'); + calc.compdt = new w._date(calc.fromel[0],calc.fromel[1]-1,calc.fromel[2],0,0,0,0); + o.maxDays = parseInt((((calc.compdt.getTime() - calc.todayc.getTime()) / calc.lod)),10); + } + + if ( refresh === true ) { w.refresh(); } + }, + _build: { + 'default': function () { + this.d.headerText = "Error"; + this.d.intHTML = $("

      There is no mode by that name loaded / mode not given

      "); + } + }, + _applyCoords: function(e) { + var w = e.widget, + o = e.widget.options, + fixd = { + h: $.mobile.activePage.find('.ui-header').jqmData('position'), + f: $.mobile.activePage.find('.ui-footer').jqmData('position'), + fh: $.mobile.activePage.find('.ui-footer').outerHeight(), + hh: $.mobile.activePage.find('.ui-header').outerHeight() + }, + iput = { + x: w.d.wrap.offset().left + (w.d.wrap.outerWidth() / 2), + y: w.d.wrap.offset().top + (w.d.wrap.outerHeight() / 2) + }, + size = { + w: w.d.mainWrap.outerWidth(), + h: w.d.mainWrap.outerHeight() + }, + doc = { + t: $(window).scrollTop(), + h: $(window).height(), + w: $.mobile.activePage.width(), + ah: $(document).height() + }, + pos = { + y: (o.centerVert) ? doc.t + ((doc.h / 2) - (size.h / 2)) : iput.y - ( size.h / 2 ), + x: (doc.w < 400 || o.centerHoriz ) ? (doc.w / 2) - (size.w /2) : iput.x - (size.w / 2) + }; + + if ( o.centerVert === false ) { + if ( o.hideFixedToolbars === true && ( typeof fixd.f !== 'undefined' || typeof fixd.h !== 'undefined' )) { + $.mobile.activePage.find(":jqmData(position='fixed')").fixedtoolbar('hide'); + fixd.f = undefined; + fixd.h = undefined; + } + + if ( typeof fixd.f !== 'undefined' ) { + if ( ( pos.y + size.h ) > ( doc.h - fixd.fh - 2 ) ) { + pos.y = doc.h - fixd.fh - 2 - size.h; + } + } else { + if ( ( pos.y + size.h ) > ( doc.ah - fixd.fh - 2 ) ) { + pos.y = doc.ah - fixd.fh - 2 - size.h; + } + if ( ( doc.h + doc.t ) < ( size.h + pos.y + 2 ) ) { + pos.y = doc.h + doc.t - size.h - 2; + } + } + + if ( typeof fixd.h !== 'undefined' ) { + if ( ( doc.t + fixd.hh + 2 ) > pos.y ) { + pos.y = doc.t + fixd.hh + 2; + } + } else { + if ( fixd.hh + 2 > pos.y ) { + pos.y = fixd.hh + 2; + } + if ( pos.y < doc.t + 2 ) { + pos.y = doc.t + 2; + } + } + } + w.d.mainWrap.css({'position': 'absolute', 'top': pos.y, 'left': pos.x}); + }, + _drag: { + 'default': function () { return false; } + }, + open: function () { + var w = this, + o = this.options, + popopts = {}, + basepop = {'history':false}, + qns = 'data-'+this.ns, + trans = o.useAnimation ? o.transition : 'none'; + + if ( o.useFocus === true && w.fastReopen === true ) { w.d.input.blur(); return false; } + if ( w.clearFunc !== false ) { + clearTimeout(w.clearFunc); w.clearFunc = false; + } + + // Call the open callback if provided. Additionally, if this + // returns false then the open/update will stop. + if ( o.openCallback !== false ) { + if ( ! $.isFunction(o.openCallback) ) { + if ( typeof window[o.openCallback] !== 'undefined' ) { + o.openCallback = window[o.openCallback]; + } else { + o.openCallback = new Function(o.openCallback); + } + } + if ( o.openCallback.apply(w, $.merge([w.theDate],o.openCallbackArgs)) === false ) { return false; } + } + + w.theDate = w._makeDate(w.d.input.val()); + if ( w.d.input.val() === "" ) { w._startOffset(w.theDate); } + w.d.input.blur(); + + if ( typeof w._build[o.mode] === 'undefined' ) { + w._build['default'].apply(w,[]); + } else { + w._build[o.mode].apply(w,[]); + } + if ( typeof w._drag[o.mode] !== 'undefined' ) { + w._drag[o.mode].apply(w, []); + } + w.d.input.trigger('datebox', {'method':'refresh'}); + if ( w.__('useArabicIndic') === true ) { w._doIndic(); } + + if ( ( o.useInline === true || o.useInlineBlind === true ) && w.initDone === false ) { + w.d.mainWrap.append(w.d.intHTML); + w.d.input.parent().parent().append(w.d.mainWrap); + w.d.mainWrap.removeClass('ui-datebox-hidden'); + if ( o.useInline === true ) { + w.d.mainWrap.addClass('ui-datebox-inline'); + } else { + w.d.mainWrap.addClass('ui-datebox-inlineblind'); + w.d.mainWrap.hide(); + } + w.initDone = false; + w.d.input.trigger('datebox',{'method':'postrefresh'}); + } + + if ( o.useImmediate ) { w.d.input.trigger('datebox', {'method':'doset'}); } + if ( o.useInline ) { return true; } + if ( o.useInlineBlind ) { + if ( w.initDone ) { w.d.mainWrap.slideDown(); } + else { w.initDone = true; } + return true; + } + if ( w.d.intHTML.is(':visible') ) { return false; } // Ignore if already open + + if ( o.enablePopup === true ) { + w.d.dialogPage = false; + w.d.mainWrap.empty(); + if ( o.useHeader === true ) { + w.d.headHTML = $('
      '); + $("Close").appendTo(w.d.headHTML) + .buttonMarkup({ theme : o.themeHeader, icon : 'delete', iconpos: 'notext', corners: true, shadow : true }) + .on(o.clickEventAlt, function(e) { e.preventDefault(); w.d.input.trigger('datebox', {'method':'close'}); }); + $('

      '+w.d.headerText+'

      ').appendTo(w.d.headHTML); + w.d.mainWrap.append(w.d.headHTML); + } + w.d.mainWrap.append(w.d.intHTML).css('zIndex', o.zindex); + w.d.input.trigger('datebox',{'method':'postrefresh'}); + + if ( o.useAnimation === true ) { + popopts.transition = o.transition; + } else { + popopts.transition = "none"; + } + + if ( o.popupForceX !== false && o.popupForceY !== false ) { + popopts.x = o.popupForceX; + popopts.y = o.popupForceY; + } + + if ( o.popupPosition !== false ) { + popopts.positionTo = o.popupPosition; + } else { + if ( typeof w.baseID !== undefined ) { + popopts.positionTo = '#' + w.baseID; + } else { + popopts.positionTo = 'window'; + } + } + + if ( o.useModal === true ) { basepop.overlayTheme = "a"; } + + w.d.mainWrap.removeClass('ui-datebox-hidden').popup(basepop).popup("open", popopts); + w.refresh(); + } else { + if ( o.dialogForce || ( o.dialogEnable && window.width() < 400 ) ) { + w.d.dialogPage = $("
      " + + "
      " + + "

      "+w.d.headerText+"

      ") + .appendTo( $.mobile.pageContainer ) + .page().css('minHeight', '0px').addClass(trans); + w.d.dialogPage.find('.ui-header').find('a').off('click vclick').on(o.clickEventAlt, function(e) { e.preventDefault(); w.d.input.trigger('datebox', {'method':'close'}); }); + w.d.mainWrap.append(w.d.intHTML).css({'marginLeft':'auto', 'marginRight':'auto'}).removeClass('ui-datebox-hidden'); + w.d.dialogPage.find('.ui-content').append(w.d.mainWrap); + w.d.input.trigger('datebox',{'method':'postrefresh'}); + $.mobile.activePage.off( "pagehide.remove" ); + $.mobile.changePage(w.d.dialogPage, {'transition': trans}); + } else { + w.d.dialogPage = false; + w.d.mainWrap.empty(); + if ( o.useHeader === true ) { + w.d.headHTML = $('
      '); + $("Close").appendTo(w.d.headHTML) + .buttonMarkup({ theme : o.themeHeader, icon : 'delete', iconpos: 'notext', corners: true, shadow : true }) + .on(o.clickEventAlt, function(e) { e.preventDefault(); w.d.input.trigger('datebox', {'method':'close'}); }); + $('

      '+w.d.headerText+'

      ').appendTo(w.d.headHTML); + w.d.mainWrap.append(w.d.headHTML); + } + w.d.mainWrap.append(w.d.intHTML).css('zIndex', o.zindex); + w.d.mainWrap.appendTo($.mobile.activePage); + w.d.screen.appendTo($.mobile.activePage); + w.d.input.trigger('datebox',{'method':'postrefresh'}); + w._applyCoords({widget:w}); + + if ( o.useModal === true ) { + if(o.useAnimation) { + w.d.screen.fadeIn('slow'); + } else { + w.d.screen.show(); + } + } else { + setTimeout(function () { w.d.screen.removeClass('ui-datebox-hidden');}, 500); + } + + w.d.mainWrap.addClass('ui-overlay-shadow in').removeClass('ui-datebox-hidden'); + + $(document).on('orientationchange.datebox', {widget:w}, function(e) { w._applyCoords(e.data); }); + if ( o.resizeListener === true ) { + $(window).on('resize.datebox', {widget:w}, function (e) { w._applyCoords(e.data); }); + } + } + } + }, + close: function() { + var w = this, + o = this.options; + + if ( o.useInlineBlind === true ) { w.d.mainWrap.slideUp(); return true;} + if ( o.useInline === true || w.d.intHTML === false ) { return true; } + + if ( w.d.dialogPage !== false ) { + $(w.d.dialogPage).dialog('close'); + + if ( ! $.mobile.activePage.jqmData('mobile-page').options.domCache ) { + $.mobile.activePage.on('pagehide.remove', function () { $(this).remove(); }); + } + + w.d.intHTML.detach().empty(); + w.d.mainWrap.detach().empty(); + w.d.wrap.removeClass('ui-focus'); + w.clearFunc = setTimeout(function () { w.d.dialogPage.empty().remove(); w.clearFunc = false; }, 1500); + } else { + if ( o.enablePopup === true ) { + w.d.mainWrap.popup('close'); + w.d.wrap.removeClass('ui-focus'); + } else { + if ( o.useModal ) { + if(o.useAnimation) { + w.d.screen.fadeOut('slow'); + } else { + w.d.screen.hide(); + } + } else { + w.d.screen.addClass('ui-datebox-hidden'); + } + w.d.screen.detach(); + w.d.mainWrap.addClass('ui-datebox-hidden').removeAttr('style').removeClass('in ui-overlay-shadow').empty().detach(); + w.d.intHTML.detach(); + w.d.wrap.removeClass('ui-focus'); + + $(document).off('orientationchange.datebox'); + if ( o.resizeListener === true ) { + $(window).off('resize.datebox'); + } + } + } + w.d.wrap.parent().removeClass('ui-focus'); + + $(document).off(w.drag.eMove); + $(document).off(w.drag.eEnd); + $(document).off(w.drag.eEndA); + + if ( o.useFocus ) { + w.fastReopen = true; + setTimeout(function(t) { return function () { t.fastReopen = false; };}(w), 300); + } + + if ( o.closeCallback !== false ) { + if ( ! $.isFunction(o.closeCallback) ) { + if ( typeof window[o.closeCallback] !== 'undefined' ) { + o.closeCallback = window[o.closeCallback]; + } else { + o.closeCallback = new Function(o.closeCallback); + } + } + o.closeCallback.apply(w, $.merge([w.theDate], o.closeCallbackArgs)); + } + }, + refresh: function() { + if ( typeof this._build[this.options.mode] === 'undefined' ) { + this._build['default'].apply(this,[]); + } else { + this._build[this.options.mode].apply(this,[]); + } + if ( this.__('useArabicIndic') === true ) { this._doIndic(); } + this.d.mainWrap.append(this.d.intHTML); + this.d.input.trigger('datebox',{'method':'postrefresh'}); + }, + _check: function() { + var w = this, + td = null, + o = this.options; + + w.dateOK = true; + + if ( o.afterToday !== false ) { + td = new w._date(); + if ( w.theDate < td ) { w.theDate = td; } + } + if ( o.beforeToday !== false ) { + td = new w._date(); + if ( w.theDate > td ) { w.theDate = td; } + } + if ( o.maxDays !== false ) { + td = new w._date(); + td.adj(2, o.maxDays); + if ( w.theDate > td ) { w.theDate = td; } + } + if ( o.minDays !== false ) { + td = new w._date(); + td.adj(2, -1*o.minDays); + if ( w.theDate < td ) { w.theDate = td; } + } + if ( o.minHour !== false ) { + if ( w.theDate.getHours() < o.minHour ) { + w.theDate.setHours(o.minHour); + } + } + if ( o.maxHour !== false ) { + if ( w.theDate.getHours() > o.maxHour ) { + w.theDate.setHours(o.maxHour); + } + } + if ( o.maxYear !== false ) { + td = new w._date(o.maxYear, 0, 1); + td.adj(2, -1); + if ( w.theDate > td ) { w.theDate = td; } + } + if ( o.minYear !== false ) { + td = new w._date(o.minYear, 0, 1); + if ( w.theDate < td ) { w.theDate = td; } + } + + if ( $.inArray(o.mode, ['timebox','durationbox','durationflipbox','timeflipbox']) > -1 ) { + if ( o.mode === 'timeflipbox' && o.validHours !== false ) { + if ( $.inArray(w.theDate.getHours(), o.validHours) < 0 ) { w.dateOK = false; } + } + } else { + if ( o.blackDatesRec !== false ) { + for ( i=0; i -1 ) { w.dateOK = false; } + } + if ( o.blackDays !== false ) { + if ( $.inArray(w.theDate.getDay(), o.blackDays) > -1 ) { w.dateOK = false; } + } + } + }, + _grabLabel: function() { + var w = this, + o = this.options; + + if ( typeof o.overrideDialogLabel === 'undefined' ) { + if ( typeof w.d.input.attr('placeholder') !== 'undefined' ) { return w.d.input.attr('placeholder'); } + if ( typeof w.d.input.attr('title') !== 'undefined' ) { return w.d.input.attr('title'); } + if ( w.d.wrap.parent().find('label[for=\''+w.d.input.attr('id')+'\']').text() !== '' ) { + return w.d.wrap.parent().find('label[for=\''+w.d.input.attr('id')+'\']').text(); + } + return false; + } + return o.overrideDialogLabel; + }, + _makeEl: function(source, parts) { + var part = false, + retty = false; + + retty = source.clone(); + + if ( typeof parts.attr !== 'undefined' ) { + for ( part in parts.attr ) { + if ( parts.attr.hasOwnProperty(part) ) { + retty.jqmData(part, parts.attr[part]); + } + } + } + return retty; + }, + _getLongOptions: function(element) { + var key, retty = {}, prefix, temp; + + if ( $.mobile.ns === "" ) { + prefix = "datebox"; + } else { + prefix = $.mobile.ns.substr(0, $.mobile.ns.length - 1) + 'Datebox'; + } + + for ( key in element.data() ) { + if ( key.substr(0, prefix.length) === prefix && key.length > prefix.length ) { + temp = key.substr(prefix.length); + temp = temp.charAt(0).toLowerCase() + temp.slice(1); + retty[temp] = element.data(key); + } + } + return retty; + }, + disable: function(){ + // Disable the element + this.d.input.attr("disabled",true); + this.d.wrap.addClass("ui-disabled").blur(); + this.disabled = true; + this.d.input.trigger('datebox', {'method':'disable'}); + }, + enable: function(){ + // Enable the element + this.d.input.attr("disabled", false); + this.d.wrap.removeClass("ui-disabled"); + this.disabled = false; + this.d.input.trigger('datebox', {'method':'enable'}); + }, + _setOption: function() { + $.Widget.prototype._setOption.apply( this, arguments ); + this.refresh(); + }, + getTheDate: function() { + return this.theDate; + }, + getLastDur: function() { + return this.lastDuration; + }, + setTheDate: function(newDate) { + this.theDate = newDate; + this.refresh(); + }, + callFormat: function(format, date) { + return this._formatter(format, date); + } + }); + + // Degrade date inputs to text inputs, suppress standard UI functions. + $( document ).on( "pagebeforecreate", function( e ) { + $( ":jqmData(role='datebox')", e.target ).each(function() { + $(this).prop('type', 'text'); + }); + }); + // Automatically bind to data-role='datebox' items. + $( document ).on( "pagecreate create", function( e ){ + $( document ).trigger( "dateboxbeforecreate" ); + $( ":jqmData(role='datebox')", e.target ).each(function() { + var defed = typeof ($(this).data(parseInt($.mobile.version.replace(/\./g,''),10) > 111 ? 'mobile-datebox' : 'datebox')); + if ( defed === "undefined" ) { + $(this).datebox(); + } + }); + }); +})( jQuery ); +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ + /* DurationBox Mode */ + +(function($) { + $.extend( $.mobile.datebox.prototype.options, { + themeButton: 'a', + themeInput: 'a', + useSetButton: true, + repButton: true, + durationSteppers: {'d': 1, 'h': 1, 'i': 1, 's': 1} + }); + $.extend( $.mobile.datebox.prototype, { + _durbox_run: function() { + var w = this; + w.drag.didRun = true; + w._offset(w.drag.target[0], w.drag.target[1], false); + w._durbox_run_update(); + w.runButton = setTimeout(function() {w._durbox_run();}, 100); + }, + _durbox_run_update: function () { + var w = this, i, cDur = [], + ival = {'d': 60*60*24, 'h': 60*60, 'i': 60}; + + i = w.theDate.getEpoch() - w.initDate.getEpoch(); + if ( i<0 ) { i = 0; w.theDate.setTime(w.initDate.getTime()); } + w.lastDuration = i; // Let the number of seconds be sort of public. + + // DAYS + cDur[0] = parseInt( i / ival.d,10); i = i % ival.d; + // HOURS + cDur[1] = parseInt( i / ival.h, 10); i = i % ival.h; + // MINS AND SECS + cDur[2] = parseInt( i / ival.i, 10); + cDur[3] = i % ival.i; + + w.d.divIn.find('input').each(function () { + switch ( $(this).parent().jqmData('field') ) { + case 'd': + $(this).val(cDur[0]); break; + case 'h': + $(this).val(cDur[1]); break; + case 'i': + $(this).val(cDur[2]); break; + case 's': + $(this).val(cDur[3]); break; + } + }); + }, + _durbox_valid: function (num) { + if ( num.toString().search(/^[0-9]+$/) === 0 ) { return parseInt(num,10); } + return 0; + }, + _durbox_enter: function (item) { + var w = this, + t = w.initDate.getEpoch(); + + w.d.intHTML.find('input').each( function() { + switch ( $(this).parent().jqmData('field') ) { + case 'd': + t += (60*60*24) * w._durbox_valid($(this).val()); break; + case 'h': + t += (60*60) * w._durbox_valid($(this).val()); break; + case 'i': + t += (60) * w._durbox_valid($(this).val()); break; + case 's': + t += w._durbox_valid($(this).val()); break; + } + }); + w.theDate.setTime( t * 1000 ); + w.refresh(); + } + }); + $.extend( $.mobile.datebox.prototype._build, { + 'durationbox': function () { + var w = this, + g = this.drag, + o = this.options, i, y, cDur = [0,0,0,0], tmp, + ival = {'d': 60*60*24, 'h': 60*60, 'i': 60}, + uid = 'ui-datebox-', + divBase = $("
      "), + divPlus = $('
      '), + divIn = divBase.clone().addClass('ui-datebox-dboxin'), + divMinus = divPlus.clone(), + inBase = $("").addClass('ui-input-text ui-corner-all ui-shadow-inset ui-body-'+o.themeInput), + butBase = $(""), + butPTheme = {theme: o.themeButton, icon: 'plus', iconpos: 'bottom', corners:true, shadow:true}, + butMTheme = $.extend({}, butPTheme, {icon: 'minus', iconpos: 'top'}); + + if ( typeof w.d.intHTML !== 'boolean' ) { + w.d.intHTML.empty().remove(); + } + + w.d.headerText = ((w._grabLabel() !== false)?w._grabLabel():w.__('titleDateDialogLabel')); + w.d.intHTML = $(''); + + if ( w.inputType !== 'number' ) { inBase.attr('pattern', '[0-9]*'); } + + w.fldOrder = w.__('durationOrder'); + + for(i=0; i<=w.fldOrder.length; i++) { + switch (w.fldOrder[i]) { + case 'd': + case 'h': + case 'i': + case 's': + y = $.inArray(w.fldOrder[i], ['d','h','i','s']); + $('
      ').jqmData('field', w.fldOrder[i]).addClass('ui-block-'+['a','b','c','d'][i]).append(inBase.clone()).appendTo(divIn).prepend(''); + w._makeEl(butBase, {'attr': {'field':w.fldOrder[i]}}).addClass('ui-block-'+['a','b','c','d'][i]).buttonMarkup(butPTheme).appendTo(divPlus); + w._makeEl(butBase, {'attr': {'field':w.fldOrder[i]}}).addClass('ui-block-'+['a','b','c','d'][i]).buttonMarkup(butMTheme).appendTo(divMinus); + break; + } + } + + i = w.theDate.getEpoch() - w.initDate.getEpoch(); + if ( i<0 ) { i = 0; w.theDate.setTime(w.initDate.getTime()); } + w.lastDuration = i; // Let the number of seconds be sort of public. + + // DAYS + cDur[0] = parseInt( i / ival.d,10); i = i % ival.d; + // HOURS + cDur[1] = parseInt( i / ival.h, 10); i = i % ival.h; + // MINS AND SECS + cDur[2] = parseInt( i / ival.i, 10); + cDur[3] = i % ival.i; + + divIn.find('input').each(function () { + switch ( $(this).parent().jqmData('field') ) { + case 'd': + $(this).val(cDur[0]); break; + case 'h': + $(this).val(cDur[1]); break; + case 'i': + $(this).val(cDur[2]); break; + case 's': + $(this).val(cDur[3]); break; + } + }); + + w.d.divIn = divIn; + + divPlus.addClass('ui-grid-'+['a','b','c'][w.fldOrder.length-2]).appendTo(w.d.intHTML); + divIn.addClass('ui-grid-'+['a','b','c'][w.fldOrder.length-2]).appendTo(w.d.intHTML); + divMinus.addClass('ui-grid-'+['a','b','c'][w.fldOrder.length-2]).appendTo(w.d.intHTML); + + if (o.mobVer >= 140) { + divMinus.find('div').css({'min-height': '2.3em'}); + divPlus.find('div').css({'min-height': '2.3em'}); + } + + if ( o.useSetButton || o.useClearButton ) { + y = $('
      ', {'class':uid+'controls'}); + + if ( o.useSetButton ) { + $(''+w.__('setDurationButtonLabel')+'') + .appendTo(y).buttonMarkup({theme: o.theme, icon: 'check', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.trigger('datebox', {'method':'set', 'value':w._formatter(w.__fmt(),w.theDate), 'date':w.theDate}); + w.d.input.trigger('datebox', {'method':'close'}); + }); + } + if ( o.useClearButton ) { + $(''+w.__('clearButton')+'') + .appendTo(y).buttonMarkup({theme: o.theme, icon: 'delete', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.val(''); + w.d.input.trigger('datebox',{'method':'clear'}); + w.d.input.trigger('datebox',{'method':'close'}); + }); + } + if ( o.useCollapsedBut ) { + y.addClass('ui-datebox-collapse'); + } + y.appendTo(w.d.intHTML); + } + + if ( o.repButton === false ) { + divPlus.on(o.clickEvent, 'div', function(e) { + e.preventDefault(); + w._offset($(this).jqmData('field'), o.durationSteppers[$(this).jqmData('field')]); + }); + divMinus.on(o.clickEvent, 'div', function(e) { + e.preventDefault(); + w._offset($(this).jqmData('field'), o.durationSteppers[$(this).jqmData('field')]*-1); + }); + } + + divIn.on('change', 'input', function() { w._durbox_enter($(this)); }); + + if ( w.wheelExists ) { // Mousewheel operation, if plugin is loaded + divIn.on('mousewheel', 'input', function(e,d) { + e.preventDefault(); + w._offset($(this).parent().jqmData('field'), ((d<0)?-1:1)*o.durationSteppers[$(this).parent().jqmData('field')]); + }); + } + + if ( o.repButton === true ) { + divPlus.on(w.drag.eStart, 'div', function(e) { + tmp = [$(this).jqmData('field'), o.durationSteppers[$(this).jqmData('field')]]; + w.drag.move = true; + w._dbox_delta = 1; + w._offset(tmp[0], tmp[1], false); + w._durbox_run_update(); + if ( !w.runButton ) { + w.drag.target = tmp; + w.runButton = setTimeout(function() {w._durbox_run();}, 500); + } + }); + + divMinus.on(w.drag.eStart, 'div', function(e) { + tmp = [$(this).jqmData('field'), o.durationSteppers[$(this).jqmData('field')]*-1]; + w.drag.move = true; + w._dbox_delta = -1; + w._offset(tmp[0], tmp[1], false); + w._durbox_run_update(); + if ( !w.runButton ) { + w.drag.target = tmp; + w.runButton = setTimeout(function() {w._durbox_run();}, 500); + } + }); + + divPlus.on(g.eEndA, function(e) { + if ( g.move ) { + e.preventDefault(); + clearTimeout(w.runButton); + w.runButton = false; + g.move = false; + } + }); + divMinus.on(g.eEndA, function(e) { + if ( g.move ) { + e.preventDefault(); + clearTimeout(w.runButton); + w.runButton = false; + g.move = false; + } + }); + } + } + }); +})( jQuery ); diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.durationbox.min.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.durationbox.min.js new file mode 100644 index 000000000..57f5642ff --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.durationbox.min.js @@ -0,0 +1,7 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +(function(a){a.widget("mobile.datebox",a.mobile.widget,{options:{version:"2-1.4.0-2013070300",mobVer:parseInt(a.mobile.version.replace(/\./g,"")),theme:false,themeDefault:"a",themeHeader:"a",mode:false,centerHoriz:false,centerVert:false,transition:"pop",useAnimation:true,hideInput:false,hideFixedToolbars:false,lockInput:true,enhanceInput:true,zindex:"500",clickEvent:"vclick",clickEventAlt:"click",resizeListener:true,defaultValue:false,showInitialValue:false,dialogEnable:false,dialogForce:false,enablePopup:false,popupPosition:false,popupForceX:false,popupForceY:false,useModal:false,useInline:false,useInlineBlind:false,useHeader:true,useImmediate:false,useNewStyle:false,useAltIcon:false,overrideStyleClass:false,useButton:true,useFocus:false,useClearButton:false,useCollapsedBut:false,usePlaceholder:false,openCallback:false,openCallbackArgs:[],closeCallback:false,closeCallbackArgs:[],startOffsetYears:false,startOffsetMonths:false,startOffsetDays:false,afterToday:false,beforeToday:false,notToday:false,maxDays:false,minDays:false,maxYear:false,minYear:false,blackDates:false,blackDatesRec:false,blackDays:false,minHour:false,maxHour:false,minuteStep:1,minuteStepRound:0,rolloverMode:{m:true,d:true,h:true,i:true,s:true},useLang:"default",lang:{"default":{setDateButtonLabel:"Set Date",setTimeButtonLabel:"Set Time",setDurationButtonLabel:"Set Duration",calTodayButtonLabel:"Jump to Today",titleDateDialogLabel:"Set Date",titleTimeDialogLabel:"Set Time",daysOfWeek:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],daysOfWeekShort:["Su","Mo","Tu","We","Th","Fr","Sa"],monthsOfYear:["January","February","March","April","May","June","July","August","September","October","November","December"],monthsOfYearShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],durationLabel:["Days","Hours","Minutes","Seconds"],durationDays:["Day","Days"],timeFormat:24,headerFormat:"%A, %B %-d, %Y",tooltip:"Open Date Picker",nextMonth:"Next Month",prevMonth:"Previous Month",dateFieldOrder:["m","d","y"],timeFieldOrder:["h","i","a"],slideFieldOrder:["y","m","d"],dateFormat:"%Y-%m-%d",useArabicIndic:false,isRTL:false,calStartDay:0,clearButton:"Clear",durationOrder:["d","h","i","s"],meridiem:["AM","PM"],timeOutput:"%k:%M",durationFormat:"%Dd %DA, %Dl:%DM:%DS",calDateListLabel:"Other Dates",calHeaderFormat:"%B %Y"}}},_enhanceDate:function(){a.extend(this._date.prototype,{copy:function(c,b){if(typeof c==="undefined"){c=[0,0,0,0,0,0,0]}if(typeof b==="undefined"){b=[0,0,0,0,0,0,0]}while(c.length<7){c.push(0)}while(b.length<7){b.push(0)}return new Date(((b[0]>0)?b[0]:this.getFullYear()+c[0]),((b[1]>0)?b[1]:this.getMonth()+c[1]),((b[2]>0)?b[2]:this.getDate()+c[2]),((b[3]>0)?b[3]:this.getHours()+c[3]),((b[4]>0)?b[4]:this.getMinutes()+c[4]),((b[5]>0)?b[5]:this.getSeconds()+c[5]),((b[6]>0)?b[5]:this.getMilliseconds()+c[6]))},adj:function(c,b){if(typeof b!=="number"){throw new Error("Adjustment value not specified")}if(typeof c!=="number"){throw new Error("Adjustment type not specified")}switch(c){case 0:this.setFullYear(this.getFullYear()+b);break;case 1:this.setMonth(this.getMonth()+b);break;case 2:this.setDate(this.getDate()+b);break;case 3:this.setHours(this.getHours()+b);break;case 4:this.setMinutes(this.getMinutes()+b);break;case 5:this.setSeconds(this.getSeconds()+b);break;case 6:this.setMilliseconds(this.getMilliseconds()+b);break}return this},setD:function(c,b){switch(c){case 0:this.setFullYear(b);break;case 1:this.setMonth(b);break;case 2:this.setDate(b);break;case 3:this.setHours(b);break;case 4:this.setMinutes(b);break;case 5:this.setSeconds(b);break;case 6:this.setMilliseconds(b);break}return this},get:function(b){switch(b){case 0:return this.getFullYear();case 1:return this.getMonth();case 2:return this.getDate();case 3:return this.getHours();case 4:return this.getMinutes();case 5:return this.getSeconds()}return false},iso:function(){return String(this.getFullYear())+"-"+((this.getMonth()<9)?"0":"")+String(this.getMonth()+1)+"-"+((this.getDate()<10)?"0":"")+String(this.getDate())},comp:function(){return parseInt(this.iso().replace(/-/g,""),10)},getEpoch:function(){return(this.getTime()-this.getMilliseconds())/1000},getArray:function(){return[this.getFullYear(),this.getMonth(),this.getDate(),this.getHours(),this.getMinutes(),this.getSeconds()]},setFirstDay:function(b){this.setD(2,1).adj(2,(b-this.getDay()));if(this.get(2)>10){this.adj(2,7)}return this},setDWeek:function(c,b){if(c===4){return this.setD(1,0).setD(2,1).setFirstDay(4).adj(2,-3).adj(2,(b-1)*7)}return this.setD(1,0).setD(2,1).setFirstDay(c).adj(2,(b-1)*7)},getDWeek:function(c){var d,b;switch(c){case 0:d=this.copy([0,-1*this.getMonth()]).setFirstDay(0);return Math.floor((this.getTime()-(d.getTime()+((this.getTimezoneOffset()-d.getTimezoneOffset())*60000)))/604800000)+1;case 1:d=this.copy([0,-1*this.getMonth()]).setFirstDay(1);return Math.floor((this.getTime()-(d.getTime()+((this.getTimezoneOffset()-d.getTimezoneOffset())*60000)))/604800000)+1;case 4:if(this.getMonth()===11&&this.getDate()>28){return 1}d=this.copy([0,-1*this.getMonth()],true).setFirstDay(4).adj(2,-3);b=Math.floor((this.getTime()-(d.getTime()+((this.getTimezoneOffset()-d.getTimezoneOffset())*60000)))/604800000)+1;if(b<1){d=this.copy([-1,-1*this.getMonth()]).setFirstDay(4).adj(2,-3);return Math.floor((this.getTime()-d.getTime())/604800000)+1}return b;default:return 0}}})},_event:function(d,c){var b=a(this).data(parseInt(a.mobile.version.replace(/\./g,""),10)>110?"mobile-datebox":"datebox");if(!d.isPropagationStopped()){switch(c.method){case"close":b.close();break;case"open":b.open();break;case"set":a(this).val(c.value);a(this).trigger("change");break;case"doset":if(a.isFunction(b["_"+b.options.mode+"DoSet"])){b["_"+b.options.mode+"DoSet"].apply(b,[])}else{a(this).trigger("datebox",{method:"set",value:b._formatter(b.__fmt(),b.theDate),date:b.theDate})}break;case"dooffset":if(c.type){b._offset(c.type,c.amount,true)}break;case"dorefresh":b.refresh();break;case"doreset":b.hardreset();break;case"doclear":a(this).val("").trigger("change");break;case"clear":a(this).trigger("change")}}},_hoover:function(b){a(b).toggleClass("ui-btn-up-"+a(b).jqmData("theme")+" ui-btn-down-"+a(b).jqmData("theme"))},_ord:{"default":function(c){var b=c%10;if(c>9&&c<21){return"th"}if(b>3){return"th"}return["th","st","nd","rd"][b]}},__:function(d){var c=this.options,b="override"+d.charAt(0).toUpperCase()+d.slice(1);if(typeof c[b]!=="undefined"){return c[b]}if(typeof c.lang[c.useLang][d]!=="undefined"){return c.lang[c.useLang][d]}if(typeof c[c.mode+"lang"]!=="undefined"&&typeof c[c.mode+"lang"][d]!=="undefined"){return c[c.mode+"lang"][d]}return c.lang["default"][d]},__fmt:function(){var b=this,c=this.options;switch(c.mode){case"timebox":case"timeflipbox":return b.__("timeOutput");case"durationbox":case"durationflipbox":return b.__("durationFormat");default:return b.__("dateFormat")}},_zPad:function(b){return((b<10)?"0"+String(b):String(b))},_dRep:function(j,g){var h=48,b=57,c=1584,d=null,e=null,f="";if(g===-1){h+=c;b+=c;c=-1584}for(d=0;d=h&&e<=b){f=f+String.fromCharCode(e+c)}else{f=f+String.fromCharCode(e)}}return f},_doIndic:function(){var b=this;b.d.intHTML.find("*").each(function(){if(a(this).children().length<1){a(this).text(b._dRep(a(this).text()))}else{if(a(this).hasClass("ui-datebox-slideday")){a(this).html(b._dRep(a(this).html()))}}});b.d.intHTML.find("input").each(function(){a(this).val(b._dRep(a(this).val()))})},_parser:{"default":function(b){return false}},_n:function(c,b){return(c<0)?b:c},_pa:function(b,c){if(typeof c==="boolean"){return new this._date(b[0],b[1],b[2],0,0,0,0)}return new this._date(c.getFullYear(),c.getMonth(),c.getDate(),b[0],b[1],b[2],0)},_makeDate:function(k){k=a.trim(((this.__("useArabicIndic")===true)?this._dRep(k,-1):k));var n=this,c=this.options,e=n.__fmt(),m=null,h=[],l=null,b=null,f=new n._date(),j={year:-1,mont:-1,date:-1,hour:-1,mins:-1,secs:-1,week:false,wtyp:4,wday:false,yday:false,meri:0},g;if(typeof c.mode==="undefined"){return f}if(typeof n._parser[c.mode]!=="undefined"){return n._parser[c.mode].apply(n,[k])}if(c.mode==="durationbox"||c.mode==="durationflipbox"){e=e.replace(/%D([a-z])/gi,function(d,o){switch(o){case"d":case"l":case"M":case"S":return"("+d+"|[0-9]+)";default:return".+?"}});e=new RegExp("^"+e+"$");m=e.exec(k);l=e.exec(n.__fmt());if(m===null||m.length!==l.length){if(typeof c.defaultValue==="number"&&c.defaultValue>0){return new n._date((n.initDate.getEpoch()+parseInt(c.defaultValue,10))*1000)}return new n._date(n.initDate.getTime())}b=n.initDate.getEpoch();for(g=0;g-1){j.mont=b}break;case"B":b=a.inArray(m[g],n.__("monthsOfYear"));if(b>-1){j.mont=b}break}}if(j.meri!==0){if(j.meri===-1&&j.hour===12){j.hour=0}if(j.meri===1&&j.hour!==12){j.hour=j.hour+12}}f=new n._date(n._n(j.year,0),n._n(j.mont,0),n._n(j.date,1),n._n(j.hour,0),n._n(j.mins,0),n._n(j.secs,0),0);if(j.year<100&&j.year!==-1){f.setFullYear(j.year)}if((j.mont>-1&&j.date>-1)||(j.hour>-1&&j.mins>-1&&j.secs>-1)){return f}if(j.week!==false){f.setDWeek(j.wtyp,j.week);if(j.date>-1){f.setDate(j.date)}}if(j.yday!==false){f.setD(1,0).setD(2,1).adj(2,(j.yday-1))}if(j.wday!==false){f.adj(2,(j.wday-f.getDay()))}}return f},_customformat:{"default":function(c,b){return false}},_formatter:function(f,c){var b=this,g=this.options,d,e={part:[0,0,0,0],tp:0};if(g.mode==="durationbox"||g.mode==="durationflipbox"){e.tp=this.theDate.getEpoch()-this.initDate.getEpoch();e.part[0]=parseInt(e.tp/(60*60*24),10);e.tp-=(e.part[0]*60*60*24);e.part[1]=parseInt(e.tp/(60*60),10);e.tp-=(e.part[1]*60*60);e.part[2]=parseInt(e.tp/(60),10);e.tp-=(e.part[2]*60);e.part[3]=e.tp;if(!f.match(/%Dd/)){e.part[1]+=(e.part[0]*24)}if(!f.match(/%Dl/)){e.part[2]+=(e.part[1]*60)}if(!f.match(/%DM/)){e.part[3]+=(e.part[2]*60)}}f=f.replace(/%(D|X|0|-)*([1-9a-zA-Z])/g,function(h,j,k){if(j==="X"){if(typeof b._customformat[g.mode]!=="undefined"){return b._customformat[g.mode](k,c,g)}return h}if(j==="D"){switch(k){case"d":return e.part[0];case"l":return b._zPad(e.part[1]);case"M":return b._zPad(e.part[2]);case"S":return b._zPad(e.part[3]);case"A":return((e.part[0]>1)?b.__("durationDays")[1]:b.__("durationDays")[0]);default:return h}}switch(k){case"%":return"%";case"a":return b.__("daysOfWeekShort")[c.getDay()];case"A":return b.__("daysOfWeek")[c.getDay()];case"b":return b.__("monthsOfYearShort")[c.getMonth()];case"B":return b.__("monthsOfYear")[c.getMonth()];case"C":return c.getFullYear().toString().substr(0,2);case"d":return((j==="-")?c.getDate():b._zPad(c.getDate()));case"H":case"k":return((j==="-")?c.getHours():b._zPad(c.getHours()));case"I":case"l":return((j==="-")?((c.getHours()===0||c.getHours()===12)?12:((c.getHours()<12)?c.getHours():(c.getHours()-12))):b._zPad(((c.getHours()===0||c.getHours()===12)?12:((c.getHours()<12)?c.getHours():c.getHours()-12))));case"m":return((j==="-")?c.getMonth()+1:b._zPad(c.getMonth()+1));case"M":return((j==="-")?c.getMinutes():b._zPad(c.getMinutes()));case"p":return((c.getHours()<12)?b.__("meridiem")[0].toUpperCase():b.__("meridiem")[1].toUpperCase());case"P":return((c.getHours()<12)?b.__("meridiem")[0].toLowerCase():b.__("meridiem")[1].toLowerCase());case"s":return c.getEpoch();case"S":return((j==="-")?c.getSeconds():b._zPad(c.getSeconds()));case"u":return((j==="-")?c.getDay()+1:b._zPad(c.getDay()+1));case"w":return c.getDay();case"y":return c.getFullYear().toString().substr(2,2);case"Y":return c.getFullYear();case"E":return c.getFullYear()+543;case"V":return((j==="-")?c.getDWeek(4):b._zPad(c.getDWeek(4)));case"U":return((j==="-")?c.getDWeek(0):b._zPad(c.getDWeek(0)));case"W":return((j==="-")?c.getDWeek(1):b._zPad(c.getDWeek(1)));case"o":if(typeof b._ord[g.useLang]!=="undefined"){return b._ord[g.useLang](c.getDate())}return b._ord["default"](c.getDate());case"j":d=new Date(c.getFullYear(),0,1);d=Math.ceil((c-d)/86400000)+1;return((d<100)?((d<10)?"00":"0"):"")+String(d);case"G":if(c.getDWeek(4)===1&&c.getMonth()>0){return c.getFullYear()+1}if(c.getDWeek(4)>51&&c.getMonth()<11){return c.getFullYear()-1}return c.getFullYear();case"g":if(c.getDWeek(4)===1&&c.getMonth()>0){return parseInt(c.getFullYear().toString().substr(2,2),10)+1}if(c.getDWeek(4)>51&&c.getMonth()<11){return parseInt(c.getFullYear().toString().substr(2,2),10)-1}return c.getFullYear().toString().substr(2,2);default:return h}});if(b.__("useArabicIndic")===true){f=b._dRep(f)}return f},_btwn:function(d,b,c){return(d>b&&d1&&d%e.minuteStep>0){if(e.minuteStepRound<0){d=d-(d%e.minuteStep)}else{if(e.minStepRound>0){d=d+(e.minuteStep-(d%e.minuteStep))}else{if(d%e.minuteStep0)?1:-1)*12,false);break}}if(c!==false){b.theDate.adj(c,d)}if(g===true){b.refresh()}if(e.useImmediate){b.d.input.trigger("datebox",{method:"doset"})}},_startOffset:function(b){var c=this.options;if(c.startOffsetYears!==false){b.adj(0,c.startOffsetYears)}if(c.startOffsetMonths!==false){b.adj(1,c.startOffsetMonths)}if(c.startOffsetDays!==false){b.adj(2,c.startOffsetDays)}return b},_create:function(){a(document).trigger("dateboxcreate");var j=this,b=a.extend(this.options,(typeof this.element.jqmData("options")!=="undefined")?this.element.jqmData("options"):this._getLongOptions(this.element)),k=(b.theme===false&&typeof(a(this).jqmData("theme"))==="undefined")?((typeof(this.element.parentsUntil(":jqmData(theme)").parent().jqmData("theme"))==="undefined")?b.themeDefault:this.element.parentsUntil(":jqmData(theme)").parent().jqmData("theme")):b.theme,l=b.useAnimation?b.transition:"none",g=b.useNewStyle===false?{input:this.element,wrap:this.element.wrap('
      ').parent(),mainWrap:a("
      ",{"class":"ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden "+l+" ui-body-"+k}).css("zIndex",b.zindex),intHTML:false}:{input:this.element,wrap:this.element,mainWrap:a("
      ",{"class":"ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden "+l+" ui-body-"+k}).css("zIndex",b.zindex),intHTML:false},e=(typeof window.ontouchstart!=="undefined"),f={eStart:(e?"touchstart":"mousedown")+".datebox",eMove:(e?"touchmove":"mousemove")+".datebox",eEnd:(e?"touchend":"mouseup")+".datebox",eEndA:(e?"mouseup.datebox touchend.datebox touchcancel.datebox touchmove.datebox":"mouseup.datebox"),move:false,start:false,end:false,pos:false,target:false,delta:false,tmp:false},c={},h=(typeof a.mobile.ns!=="undefined")?a.mobile.ns:"";a.extend(j,{d:g,ns:h,drag:f,touch:e});if(b.usePlaceholder!==false){if(b.usePlaceholder===true&&j._grabLabel()!==false){j.d.input.attr("placeholder",j._grabLabel())}if(typeof b.usePlaceholder==="string"){j.d.input.attr("placeholder",b.usePlaceholder)}}b.theme=k;j.clearFunc=false;j.disabled=false;j.runButton=false;j._date=window.Date;j._enhanceDate();j.baseID=j.d.input.attr("id");j.initDate=new j._date();j.theDate=(b.defaultValue)?j._makeDate(b.defaultValue):((j.d.input.val()!=="")?j._makeDate(j.d.input.val()):new j._date());j.initDone=false;if(b.showInitialValue===true){j.d.input.val(j._formatter(j.__fmt(),j.theDate))}if(b.useButton===true&&b.useInline===false&&b.useNewStyle===false){j.d.open=a(''+this.__("tooltip")+"").on(b.clickEvent,function(d){d.preventDefault();if(!j.disabled){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.parent().addClass("ui-focus");j.d.input.parent().removeClass("ui-focus")}setTimeout(function(){a(d.target).closest("a").removeClass(a.mobile.activeBtnClass)},300)}).appendTo(j.d.wrap).buttonMarkup({icon:"grid",iconpos:"notext",corners:true,shadow:true}).css({"vertical-align":"middle",display:"inline-block"})}j.d.screen=a("
      ",{"class":"ui-datebox-screen ui-datebox-hidden"+((b.useModal)?" ui-datebox-screen-modal":"")}).css({"z-index":b.zindex-1}).on(b.clickEventAlt,function(d){d.preventDefault();j.d.input.trigger("datebox",{method:"close"})});if(b.enhanceInput===true&&navigator.userAgent.match(/Android/i)){j.inputType="number"}else{j.inputType="text"}if(b.hideInput){j.d.wrap.parent().hide()}if(b.mobVer<140){a("label[for='"+j.d.input.attr("id")+"']").addClass("ui-input-text").css("verticalAlign","middle")}j.d.wrap.on(b.clickEvent,function(){if(!j.disabled&&(b.noButtonFocusMode||b.focusMode)){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.addClass("ui-focus");j.d.input.removeClass("ui-focus")}});j.d.input.removeClass("ui-corner-all ui-shadow-inset").bind(j.touch?"touchend":"click",function(d){if(j.disabled===false&&b.useNewStyle===true&&b.useFocus===false){if(((j.touch?d.originalEvent.changedTouches[0].pageX:d.pageX)-d.target.offsetLeft)>(d.target.offsetWidth-20)){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.parent().addClass("ui-focus");j.d.input.removeClass("ui-focus")}}}).focus(function(){if(j.disabled===false&&b.useFocus===true){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.addClass("ui-focus");j.d.input.removeClass("ui-focus");if(b.useNewStyle===false){j.d.input.parent().removeClass("ui-focus");j.d.wrap.parent().addClass("ui-focus")}}if(b.useNewStyle===false){j.d.input.removeClass("ui-focus")}}).blur(function(){j.d.wrap.removeClass("ui-focus");j.d.input.removeClass("ui-focus")}).change(function(){j.theDate=j._makeDate(j.d.input.val());j.refresh()}).attr("readonly",b.lockInput).on("datebox",j._event);if(b.useNewStyle===true){j.d.input.addClass("ui-corner-all "+((b.useAltIcon===true)?"ui-icon-datebox-alt":"ui-icon-datebox"));if(b.overrideStyleClass!==false){j.d.input.addClass(b.overrideStyleClass)}}else{j.d.input.parent().css("border","none").removeClass("ui-shadow-inset")}j.d.wrap.parent().on(b.clickEvent,function(){if(!j.disabled&&b.useFocus===true&&b.useNewStyle===false){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.addClass("ui-focus");j.d.input.removeClass("ui-focus");setTimeout(function(){j.d.wrap.removeClass("ui-focus");j.d.wrap.parent().addClass("ui-focus")},500)}});if(typeof a.event.special.mousewheel!=="undefined"){j.wheelExists=true}if(j.d.input.is(":disabled")){j.disable()}if(b.useInline===true||b.useInlineBlind){j.open()}j.applyMinMax(false,false);a(document).trigger("dateboxaftercreate")},applyMinMax:function(e,d){var b=this,f=this.options,c={};if(typeof e==="undefined"){e=false}if(typeof d==="undefined"){d=true}if((d===true||f.minDays===false)&&typeof(b.d.input.attr("min"))!=="undefined"){c.today=new b._date();c.lod=24*60*60*1000;c.todayc=new b._date(c.today.getFullYear(),c.today.getMonth(),c.today.getDate(),0,0,0,0);c.fromel=b.d.input.attr("min").split("-");c.compdt=new b._date(c.fromel[0],c.fromel[1]-1,c.fromel[2],0,0,0,0);f.minDays=parseInt((((c.compdt.getTime()-c.todayc.getTime())/c.lod))*-1,10)}if((d===true||f.maxDays===false)&&typeof(b.d.input.attr("max"))!=="undefined"){c.today=new b._date();c.lod=24*60*60*1000;c.todayc=new b._date(c.today.getFullYear(),c.today.getMonth(),c.today.getDate(),0,0,0,0);c.fromel=b.d.input.attr("max").split("-");c.compdt=new b._date(c.fromel[0],c.fromel[1]-1,c.fromel[2],0,0,0,0);f.maxDays=parseInt((((c.compdt.getTime()-c.todayc.getTime())/c.lod)),10)}if(e===true){b.refresh()}},_build:{"default":function(){this.d.headerText="Error";this.d.intHTML=a("

      There is no mode by that name loaded / mode not given

      ")}},_applyCoords:function(h){var b=h.widget,j=h.widget.options,f={h:a.mobile.activePage.find(".ui-header").jqmData("position"),f:a.mobile.activePage.find(".ui-footer").jqmData("position"),fh:a.mobile.activePage.find(".ui-footer").outerHeight(),hh:a.mobile.activePage.find(".ui-header").outerHeight()},c={x:b.d.wrap.offset().left+(b.d.wrap.outerWidth()/2),y:b.d.wrap.offset().top+(b.d.wrap.outerHeight()/2)},d={w:b.d.mainWrap.outerWidth(),h:b.d.mainWrap.outerHeight()},g={t:a(window).scrollTop(),h:a(window).height(),w:a.mobile.activePage.width(),ah:a(document).height()},k={y:(j.centerVert)?g.t+((g.h/2)-(d.h/2)):c.y-(d.h/2),x:(g.w<400||j.centerHoriz)?(g.w/2)-(d.w/2):c.x-(d.w/2)};if(j.centerVert===false){if(j.hideFixedToolbars===true&&(typeof f.f!=="undefined"||typeof f.h!=="undefined")){a.mobile.activePage.find(":jqmData(position='fixed')").fixedtoolbar("hide");f.f=undefined;f.h=undefined}if(typeof f.f!=="undefined"){if((k.y+d.h)>(g.h-f.fh-2)){k.y=g.h-f.fh-2-d.h}}else{if((k.y+d.h)>(g.ah-f.fh-2)){k.y=g.ah-f.fh-2-d.h}if((g.h+g.t)<(d.h+k.y+2)){k.y=g.h+g.t-d.h-2}}if(typeof f.h!=="undefined"){if((g.t+f.hh+2)>k.y){k.y=g.t+f.hh+2}}else{if(f.hh+2>k.y){k.y=f.hh+2}if(k.y
      ');a("Close").appendTo(b.d.headHTML).buttonMarkup({theme:g.themeHeader,icon:"delete",iconpos:"notext",corners:true,shadow:true}).on(g.clickEventAlt,function(h){h.preventDefault();b.d.input.trigger("datebox",{method:"close"})});a('

      '+b.d.headerText+"

      ").appendTo(b.d.headHTML);b.d.mainWrap.append(b.d.headHTML)}b.d.mainWrap.append(b.d.intHTML).css("zIndex",g.zindex);b.d.input.trigger("datebox",{method:"postrefresh"});if(g.useAnimation===true){e.transition=g.transition}else{e.transition="none"}if(g.popupForceX!==false&&g.popupForceY!==false){e.x=g.popupForceX;e.y=g.popupForceY}if(g.popupPosition!==false){e.positionTo=g.popupPosition}else{if(typeof b.baseID!==undefined){e.positionTo="#"+b.baseID}else{e.positionTo="window"}}if(g.useModal===true){f.overlayTheme="a"}b.d.mainWrap.removeClass("ui-datebox-hidden").popup(f).popup("open",e);b.refresh()}else{if(g.dialogForce||(g.dialogEnable&&window.width()<400)){b.d.dialogPage=a("

      "+b.d.headerText+"

      ").appendTo(a.mobile.pageContainer).page().css("minHeight","0px").addClass(c);b.d.dialogPage.find(".ui-header").find("a").off("click vclick").on(g.clickEventAlt,function(h){h.preventDefault();b.d.input.trigger("datebox",{method:"close"})});b.d.mainWrap.append(b.d.intHTML).css({marginLeft:"auto",marginRight:"auto"}).removeClass("ui-datebox-hidden");b.d.dialogPage.find(".ui-content").append(b.d.mainWrap);b.d.input.trigger("datebox",{method:"postrefresh"});a.mobile.activePage.off("pagehide.remove");a.mobile.changePage(b.d.dialogPage,{transition:c})}else{b.d.dialogPage=false;b.d.mainWrap.empty();if(g.useHeader===true){b.d.headHTML=a('
      ');a("Close").appendTo(b.d.headHTML).buttonMarkup({theme:g.themeHeader,icon:"delete",iconpos:"notext",corners:true,shadow:true}).on(g.clickEventAlt,function(h){h.preventDefault();b.d.input.trigger("datebox",{method:"close"})});a('

      '+b.d.headerText+"

      ").appendTo(b.d.headHTML);b.d.mainWrap.append(b.d.headHTML)}b.d.mainWrap.append(b.d.intHTML).css("zIndex",g.zindex);b.d.mainWrap.appendTo(a.mobile.activePage);b.d.screen.appendTo(a.mobile.activePage);b.d.input.trigger("datebox",{method:"postrefresh"});b._applyCoords({widget:b});if(g.useModal===true){if(g.useAnimation){b.d.screen.fadeIn("slow")}else{b.d.screen.show()}}else{setTimeout(function(){b.d.screen.removeClass("ui-datebox-hidden")},500)}b.d.mainWrap.addClass("ui-overlay-shadow in").removeClass("ui-datebox-hidden");a(document).on("orientationchange.datebox",{widget:b},function(h){b._applyCoords(h.data)});if(g.resizeListener===true){a(window).on("resize.datebox",{widget:b},function(h){b._applyCoords(h.data)})}}}},close:function(){var b=this,c=this.options;if(c.useInlineBlind===true){b.d.mainWrap.slideUp();return true}if(c.useInline===true||b.d.intHTML===false){return true}if(b.d.dialogPage!==false){a(b.d.dialogPage).dialog("close");if(!a.mobile.activePage.jqmData("mobile-page").options.domCache){a.mobile.activePage.on("pagehide.remove",function(){a(this).remove()})}b.d.intHTML.detach().empty();b.d.mainWrap.detach().empty();b.d.wrap.removeClass("ui-focus");b.clearFunc=setTimeout(function(){b.d.dialogPage.empty().remove();b.clearFunc=false},1500)}else{if(c.enablePopup===true){b.d.mainWrap.popup("close");b.d.wrap.removeClass("ui-focus")}else{if(c.useModal){if(c.useAnimation){b.d.screen.fadeOut("slow")}else{b.d.screen.hide()}}else{b.d.screen.addClass("ui-datebox-hidden")}b.d.screen.detach();b.d.mainWrap.addClass("ui-datebox-hidden").removeAttr("style").removeClass("in ui-overlay-shadow").empty().detach();b.d.intHTML.detach();b.d.wrap.removeClass("ui-focus");a(document).off("orientationchange.datebox");if(c.resizeListener===true){a(window).off("resize.datebox")}}}b.d.wrap.parent().removeClass("ui-focus");a(document).off(b.drag.eMove);a(document).off(b.drag.eEnd);a(document).off(b.drag.eEndA);if(c.useFocus){b.fastReopen=true;setTimeout(function(d){return function(){d.fastReopen=false}}(b),300)}if(c.closeCallback!==false){if(!a.isFunction(c.closeCallback)){if(typeof window[c.closeCallback]!=="undefined"){c.closeCallback=window[c.closeCallback]}else{c.closeCallback=new Function(c.closeCallback)}}c.closeCallback.apply(b,a.merge([b.theDate],c.closeCallbackArgs))}},refresh:function(){if(typeof this._build[this.options.mode]==="undefined"){this._build["default"].apply(this,[])}else{this._build[this.options.mode].apply(this,[])}if(this.__("useArabicIndic")===true){this._doIndic()}this.d.mainWrap.append(this.d.intHTML);this.d.input.trigger("datebox",{method:"postrefresh"})},_check:function(){var b=this,d=null,c=this.options;b.dateOK=true;if(c.afterToday!==false){d=new b._date();if(b.theDated){b.theDate=d}}if(c.maxDays!==false){d=new b._date();d.adj(2,c.maxDays);if(b.theDate>d){b.theDate=d}}if(c.minDays!==false){d=new b._date();d.adj(2,-1*c.minDays);if(b.theDatec.maxHour){b.theDate.setHours(c.maxHour)}}if(c.maxYear!==false){d=new b._date(c.maxYear,0,1);d.adj(2,-1);if(b.theDate>d){b.theDate=d}}if(c.minYear!==false){d=new b._date(c.minYear,0,1);if(b.theDate-1){if(c.mode==="timeflipbox"&&c.validHours!==false){if(a.inArray(b.theDate.getHours(),c.validHours)<0){b.dateOK=false}}}else{if(c.blackDatesRec!==false){for(i=0;i-1){b.dateOK=false}}if(c.blackDays!==false){if(a.inArray(b.theDate.getDay(),c.blackDays)>-1){b.dateOK=false}}}},_grabLabel:function(){var b=this,c=this.options;if(typeof c.overrideDialogLabel==="undefined"){if(typeof b.d.input.attr("placeholder")!=="undefined"){return b.d.input.attr("placeholder")}if(typeof b.d.input.attr("title")!=="undefined"){return b.d.input.attr("title")}if(b.d.wrap.parent().find("label[for='"+b.d.input.attr("id")+"']").text()!==""){return b.d.wrap.parent().find("label[for='"+b.d.input.attr("id")+"']").text()}return false}return c.overrideDialogLabel},_makeEl:function(d,e){var b=false,c=false;c=d.clone();if(typeof e.attr!=="undefined"){for(b in e.attr){if(e.attr.hasOwnProperty(b)){c.jqmData(b,e.attr[b])}}}return c},_getLongOptions:function(d){var c,e={},f,b;if(a.mobile.ns===""){f="datebox"}else{f=a.mobile.ns.substr(0,a.mobile.ns.length-1)+"Datebox"}for(c in d.data()){if(c.substr(0,f.length)===f&&c.length>f.length){b=c.substr(f.length);b=b.charAt(0).toLowerCase()+b.slice(1);e[b]=d.data(c)}}return e},disable:function(){this.d.input.attr("disabled",true);this.d.wrap.addClass("ui-disabled").blur();this.disabled=true;this.d.input.trigger("datebox",{method:"disable"})},enable:function(){this.d.input.attr("disabled",false);this.d.wrap.removeClass("ui-disabled");this.disabled=false;this.d.input.trigger("datebox",{method:"enable"})},_setOption:function(){a.Widget.prototype._setOption.apply(this,arguments);this.refresh()},getTheDate:function(){return this.theDate},getLastDur:function(){return this.lastDuration},setTheDate:function(b){this.theDate=b;this.refresh()},callFormat:function(c,b){return this._formatter(c,b)}});a(document).on("pagebeforecreate",function(b){a(":jqmData(role='datebox')",b.target).each(function(){a(this).prop("type","text")})});a(document).on("pagecreate create",function(b){a(document).trigger("dateboxbeforecreate");a(":jqmData(role='datebox')",b.target).each(function(){var c=typeof(a(this).data(parseInt(a.mobile.version.replace(/\./g,""),10)>111?"mobile-datebox":"datebox"));if(c==="undefined"){a(this).datebox()}})})})(jQuery);(function(a){a.extend(a.mobile.datebox.prototype.options,{themeButton:"a",themeInput:"a",useSetButton:true,repButton:true,durationSteppers:{d:1,h:1,i:1,s:1}});a.extend(a.mobile.datebox.prototype,{_durbox_run:function(){var b=this;b.drag.didRun=true;b._offset(b.drag.target[0],b.drag.target[1],false);b._durbox_run_update();b.runButton=setTimeout(function(){b._durbox_run()},100)},_durbox_run_update:function(){var c=this,e,b=[],d={d:60*60*24,h:60*60,i:60};e=c.theDate.getEpoch()-c.initDate.getEpoch();if(e<0){e=0;c.theDate.setTime(c.initDate.getTime())}c.lastDuration=e;b[0]=parseInt(e/d.d,10);e=e%d.d;b[1]=parseInt(e/d.h,10);e=e%d.h;b[2]=parseInt(e/d.i,10);b[3]=e%d.i;c.d.divIn.find("input").each(function(){switch(a(this).parent().jqmData("field")){case"d":a(this).val(b[0]);break;case"h":a(this).val(b[1]);break;case"i":a(this).val(b[2]);break;case"s":a(this).val(b[3]);break}})},_durbox_valid:function(b){if(b.toString().search(/^[0-9]+$/)===0){return parseInt(b,10)}return 0},_durbox_enter:function(d){var b=this,c=b.initDate.getEpoch();b.d.intHTML.find("input").each(function(){switch(a(this).parent().jqmData("field")){case"d":c+=(60*60*24)*b._durbox_valid(a(this).val());break;case"h":c+=(60*60)*b._durbox_valid(a(this).val());break;case"i":c+=(60)*b._durbox_valid(a(this).val());break;case"s":c+=b._durbox_valid(a(this).val());break}});b.theDate.setTime(c*1000);b.refresh()}});a.extend(a.mobile.datebox.prototype._build,{durationbox:function(){var u=this,n=this.drag,f=this.options,l,s,h=[0,0,0,0],m,t={d:60*60*24,h:60*60,i:60},q="ui-datebox-",r=a("
      "),c=a("
      "),j=r.clone().addClass("ui-datebox-dboxin"),k=c.clone(),e=a("").addClass("ui-input-text ui-corner-all ui-shadow-inset ui-body-"+f.themeInput),p=a(""),b={theme:f.themeButton,icon:"plus",iconpos:"bottom",corners:true,shadow:true},d=a.extend({},b,{icon:"minus",iconpos:"top"});if(typeof u.d.intHTML!=="boolean"){u.d.intHTML.empty().remove()}u.d.headerText=((u._grabLabel()!==false)?u._grabLabel():u.__("titleDateDialogLabel"));u.d.intHTML=a("");if(u.inputType!=="number"){e.attr("pattern","[0-9]*")}u.fldOrder=u.__("durationOrder");for(l=0;l<=u.fldOrder.length;l++){switch(u.fldOrder[l]){case"d":case"h":case"i":case"s":s=a.inArray(u.fldOrder[l],["d","h","i","s"]);a("
      ").jqmData("field",u.fldOrder[l]).addClass("ui-block-"+["a","b","c","d"][l]).append(e.clone()).appendTo(j).prepend("");u._makeEl(p,{attr:{field:u.fldOrder[l]}}).addClass("ui-block-"+["a","b","c","d"][l]).buttonMarkup(b).appendTo(c);u._makeEl(p,{attr:{field:u.fldOrder[l]}}).addClass("ui-block-"+["a","b","c","d"][l]).buttonMarkup(d).appendTo(k);break}}l=u.theDate.getEpoch()-u.initDate.getEpoch();if(l<0){l=0;u.theDate.setTime(u.initDate.getTime())}u.lastDuration=l;h[0]=parseInt(l/t.d,10);l=l%t.d;h[1]=parseInt(l/t.h,10);l=l%t.h;h[2]=parseInt(l/t.i,10);h[3]=l%t.i;j.find("input").each(function(){switch(a(this).parent().jqmData("field")){case"d":a(this).val(h[0]);break;case"h":a(this).val(h[1]);break;case"i":a(this).val(h[2]);break;case"s":a(this).val(h[3]);break}});u.d.divIn=j;c.addClass("ui-grid-"+["a","b","c"][u.fldOrder.length-2]).appendTo(u.d.intHTML);j.addClass("ui-grid-"+["a","b","c"][u.fldOrder.length-2]).appendTo(u.d.intHTML);k.addClass("ui-grid-"+["a","b","c"][u.fldOrder.length-2]).appendTo(u.d.intHTML);if(f.mobVer>=140){k.find("div").css({"min-height":"2.3em"});c.find("div").css({"min-height":"2.3em"})}if(f.useSetButton||f.useClearButton){s=a("
      ",{"class":q+"controls"});if(f.useSetButton){a(''+u.__("setDurationButtonLabel")+"").appendTo(s).buttonMarkup({theme:f.theme,icon:"check",iconpos:"left",corners:true,shadow:true}).on(f.clickEventAlt,function(g){g.preventDefault();u.d.input.trigger("datebox",{method:"set",value:u._formatter(u.__fmt(),u.theDate),date:u.theDate});u.d.input.trigger("datebox",{method:"close"})})}if(f.useClearButton){a(''+u.__("clearButton")+"").appendTo(s).buttonMarkup({theme:f.theme,icon:"delete",iconpos:"left",corners:true,shadow:true}).on(f.clickEventAlt,function(g){g.preventDefault();u.d.input.val("");u.d.input.trigger("datebox",{method:"clear"});u.d.input.trigger("datebox",{method:"close"})})}if(f.useCollapsedBut){s.addClass("ui-datebox-collapse")}s.appendTo(u.d.intHTML)}if(f.repButton===false){c.on(f.clickEvent,"div",function(g){g.preventDefault();u._offset(a(this).jqmData("field"),f.durationSteppers[a(this).jqmData("field")])});k.on(f.clickEvent,"div",function(g){g.preventDefault();u._offset(a(this).jqmData("field"),f.durationSteppers[a(this).jqmData("field")]*-1)})}j.on("change","input",function(){u._durbox_enter(a(this))});if(u.wheelExists){j.on("mousewheel","input",function(g,i){g.preventDefault();u._offset(a(this).parent().jqmData("field"),((i<0)?-1:1)*f.durationSteppers[a(this).parent().jqmData("field")])})}if(f.repButton===true){c.on(u.drag.eStart,"div",function(g){m=[a(this).jqmData("field"),f.durationSteppers[a(this).jqmData("field")]];u.drag.move=true;u._dbox_delta=1;u._offset(m[0],m[1],false);u._durbox_run_update();if(!u.runButton){u.drag.target=m;u.runButton=setTimeout(function(){u._durbox_run()},500)}});k.on(u.drag.eStart,"div",function(g){m=[a(this).jqmData("field"),f.durationSteppers[a(this).jqmData("field")]*-1];u.drag.move=true;u._dbox_delta=-1;u._offset(m[0],m[1],false);u._durbox_run_update();if(!u.runButton){u.drag.target=m;u.runButton=setTimeout(function(){u._durbox_run()},500)}});c.on(n.eEndA,function(g){if(n.move){g.preventDefault();clearTimeout(u.runButton);u.runButton=false;n.move=false}});k.on(n.eEndA,function(g){if(n.move){g.preventDefault();clearTimeout(u.runButton);u.runButton=false;n.move=false}})}}})})(jQuery); \ No newline at end of file diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.durationflipbox.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.durationflipbox.js new file mode 100644 index 000000000..d8006de15 --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.durationflipbox.js @@ -0,0 +1,1571 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +/* CORE Functions */ + +(function($) { + $.widget( "mobile.datebox", $.mobile.widget, { + options: { + // All widget options, including some internal runtime details + version: '2-1.4.0-2013070300', // jQMMajor.jQMMinor.DBoxMinor-YrMoDaySerial + mobVer: parseInt($.mobile.version.replace(/\./g,'')), + theme: false, + themeDefault: 'a', + themeHeader: 'a', + mode: false, + + centerHoriz: false, + centerVert: false, + transition: 'pop', + useAnimation: true, + hideInput: false, + hideFixedToolbars: false, + + lockInput: true, + enhanceInput: true, + + zindex: '500', + clickEvent: 'vclick', + clickEventAlt: 'click', + resizeListener: true, + + defaultValue: false, + showInitialValue: false, + + dialogEnable: false, + dialogForce: false, + enablePopup: false, + + popupPosition: false, + popupForceX: false, + popupForceY: false, + + useModal: false, + useInline: false, + useInlineBlind: false, + useHeader: true, + useImmediate: false, + useNewStyle: false, + useAltIcon: false, + overrideStyleClass: false, + + useButton: true, + useFocus: false, + useClearButton: false, + useCollapsedBut: false, + usePlaceholder: false, + + openCallback: false, + openCallbackArgs: [], + closeCallback: false, + closeCallbackArgs: [], + + startOffsetYears: false, + startOffsetMonths: false, + startOffsetDays: false, + afterToday: false, + beforeToday: false, + notToday: false, + maxDays: false, + minDays: false, + maxYear: false, + minYear: false, + blackDates: false, + blackDatesRec: false, + blackDays: false, + minHour: false, + maxHour: false, + minuteStep: 1, + minuteStepRound: 0, + + rolloverMode: { 'm': true, 'd': true, 'h': true, 'i': true, 's': true }, + + useLang: 'default', + lang: { + 'default' : { + setDateButtonLabel: 'Set Date', + setTimeButtonLabel: 'Set Time', + setDurationButtonLabel: 'Set Duration', + calTodayButtonLabel: 'Jump to Today', + titleDateDialogLabel: 'Set Date', + titleTimeDialogLabel: 'Set Time', + daysOfWeek: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], + daysOfWeekShort: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], + monthsOfYear: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], + monthsOfYearShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + durationLabel: ['Days', 'Hours', 'Minutes', 'Seconds'], + durationDays: ['Day', 'Days'], + timeFormat: 24, + headerFormat: '%A, %B %-d, %Y', + tooltip: 'Open Date Picker', + nextMonth: 'Next Month', + prevMonth: 'Previous Month', + dateFieldOrder: ['m', 'd', 'y'], + timeFieldOrder: ['h', 'i', 'a'], + slideFieldOrder: ['y', 'm', 'd'], + dateFormat: '%Y-%m-%d', + useArabicIndic: false, + isRTL: false, + calStartDay: 0, + clearButton: 'Clear', + durationOrder: ['d', 'h', 'i', 's'], + meridiem: ['AM', 'PM'], + timeOutput: '%k:%M', //{ '12': '%l:%M %p', '24': '%k:%M' }, + durationFormat: '%Dd %DA, %Dl:%DM:%DS', + calDateListLabel: 'Other Dates', + calHeaderFormat: '%B %Y' + } + } + }, + _enhanceDate: function() { + $.extend(this._date.prototype, { + copy: function(adjust, override) { + /* Get a modified copy of the date. + * First array - Offset the new date by # (position determines date part) + * Second array - If non-zero, force the new date by # (position determines date part) + */ + if ( typeof adjust === 'undefined' ) { adjust = [0,0,0,0,0,0,0]; } + if ( typeof override === 'undefined' ) { override = [0,0,0,0,0,0,0]; } + while ( adjust.length < 7 ) { adjust.push(0); } + while ( override.length < 7 ) { override.push(0); } + return new Date( + ((override[0] > 0 ) ? override[0] : this.getFullYear() + adjust[0]), + ((override[1] > 0 ) ? override[1] : this.getMonth() + adjust[1]), + ((override[2] > 0 ) ? override[2] : this.getDate() + adjust[2]), + ((override[3] > 0 ) ? override[3] : this.getHours() + adjust[3]), + ((override[4] > 0 ) ? override[4] : this.getMinutes() + adjust[4]), + ((override[5] > 0 ) ? override[5] : this.getSeconds() + adjust[5]), + ((override[6] > 0 ) ? override[5] : this.getMilliseconds() + adjust[6])); + }, + adj: function (type, amount) { + /* Adjust the date. Yes, this is chainable */ + if ( typeof amount !== 'number' ) { + throw new Error("Adjustment value not specified"); + } + if ( typeof type !== 'number' ) { + throw new Error("Adjustment type not specified"); + } + switch ( type ) { + case 0: this.setFullYear(this.getFullYear() + amount); break; + case 1: this.setMonth(this.getMonth() + amount); break; + case 2: this.setDate(this.getDate() + amount); break; + case 3: this.setHours(this.getHours() + amount); break; + case 4: this.setMinutes(this.getMinutes() + amount); break; + case 5: this.setSeconds(this.getSeconds() + amount); break; + case 6: this.setMilliseconds(this.getMilliseconds() + amount); break; + } + return this; + }, + setD: function(type, amount) { + /* A chainable version of setWhatever() */ + switch ( type ) { + case 0: this.setFullYear(amount); break; + case 1: this.setMonth(amount); break; + case 2: this.setDate(amount); break; + case 3: this.setHours(amount); break; + case 4: this.setMinutes(amount); break; + case 5: this.setSeconds(amount); break; + case 6: this.setMilliseconds(amount); break; + } + return this; + }, + get: function(type) { + switch ( type ) { + case 0: return this.getFullYear(); + case 1: return this.getMonth(); + case 2: return this.getDate(); + case 3: return this.getHours(); + case 4: return this.getMinutes(); + case 5: return this.getSeconds(); + } + return false; + }, + iso: function() { + return String(this.getFullYear()) + '-' + (( this.getMonth() < 9 ) ? "0" : "") + String(this.getMonth()+1) + '-' + ((this.getDate() < 10 ) ? "0" : "") + String(this.getDate()); + }, + comp: function () { + return parseInt(this.iso().replace(/-/g,''),10); + }, + getEpoch: function() { + return (this.getTime() - this.getMilliseconds()) / 1000; + }, + getArray: function() { + return [this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds()]; + }, + setFirstDay: function (day) { + this.setD(2,1).adj(2, (day - this.getDay())); + if ( this.get(2) > 10 ) { this.adj(2,7); } + return this; + }, + setDWeek: function (type,num) { + if ( type === 4 ) { + return this.setD(1,0).setD(2,1).setFirstDay(4).adj(2,-3).adj(2,(num-1)*7); + } + return this.setD(1,0).setD(2,1).setFirstDay(type).adj(2,(num-1)*7); + }, + getDWeek: function (type) { + var t1, t2; + + switch ( type ) { + case 0: + t1 = this.copy([0,-1*this.getMonth()]).setFirstDay(0); + return Math.floor((this.getTime() - ( t1.getTime() + (( this.getTimezoneOffset() - t1.getTimezoneOffset()) * 60000))) / 6048e5) + 1; + //return Math.floor((this.getTime() - t1.getTime()) / 6048e5) + 1; + case 1: + t1 = this.copy([0,-1*this.getMonth()]).setFirstDay(1); + return Math.floor((this.getTime() - ( t1.getTime() + (( this.getTimezoneOffset() - t1.getTimezoneOffset()) * 60000))) / 6048e5) + 1; + //return Math.floor((this.getTime() - t1.getTime()) / 6048e5) + 1; + case 4: + // this line is some bullshit. but it does work. + // (trap for dec 29, 30, or 31st being in the new year's week - these are the + // only 3 that can possibly fall like this) + if ( this.getMonth() === 11 && this.getDate() > 28 ) { return 1; } + + t1 = this.copy([0,-1*this.getMonth()],true).setFirstDay(4).adj(2,-3); + t2 = Math.floor((this.getTime() - ( t1.getTime() + (( this.getTimezoneOffset() - t1.getTimezoneOffset()) * 60000))) / 6048e5) + 1; + + if ( t2 < 1 ) { + t1 = this.copy([-1,-1*this.getMonth()]).setFirstDay(4).adj(2,-3); + return Math.floor((this.getTime() - t1.getTime()) / 6048e5) + 1; + } + return t2; + default: + return 0; + } + } + }); + }, + _event: function(e, p) { + var w = $(this).data(parseInt($.mobile.version.replace(/\./g,''),10) > 110 ? 'mobile-datebox' : 'datebox'); + if ( ! e.isPropagationStopped() ) { + switch (p.method) { + case 'close': + w.close(); break; + case 'open': + w.open(); break; + case 'set': + $(this).val(p.value); + $(this).trigger('change'); + break; + case 'doset': + if ( $.isFunction(w['_'+w.options.mode+'DoSet']) ) { + w['_'+w.options.mode+'DoSet'].apply(w,[]); + } else { + $(this).trigger('datebox', {'method':'set', 'value':w._formatter(w.__fmt(), w.theDate), 'date':w.theDate}); + } + break; + case 'dooffset': + if (p.type) { w._offset(p.type, p.amount, true); } break; + case 'dorefresh': + w.refresh(); break; + case 'doreset': + w.hardreset(); break; + case 'doclear': + $(this).val('').trigger('change'); break; + case 'clear': + $(this).trigger('change'); + } + } + }, + _hoover: function(item) { + // Hover toggle class, for calendar + $(item).toggleClass('ui-btn-up-'+$(item).jqmData('theme')+' ui-btn-down-'+$(item).jqmData('theme')); + }, + _ord: { + 'default': function (num) { + // Return an ordinal suffix (1st, 2nd, 3rd, etc) + var ending = num % 10; + if ( num > 9 && num < 21 ) { return 'th'; } + if ( ending > 3 ) { return 'th'; } + return ['th','st','nd','rd'][ending]; + } + }, + __ : function(val) { + var o = this.options, + oride = 'override' + val.charAt(0).toUpperCase() + val.slice(1); + + if ( typeof o[oride] !== 'undefined' ) { return o[oride]; } + if ( typeof o.lang[o.useLang][val] !== 'undefined' ) { return o.lang[o.useLang][val]; } + if ( typeof o[o.mode+'lang'] !== 'undefined' && typeof o[o.mode+'lang'][val] !== 'undefined' ) { return o[o.mode+'lang'][val]; } + return o.lang['default'][val]; + }, + __fmt: function() { + var w = this, + o = this.options; + + switch ( o.mode ) { + case 'timebox': + case 'timeflipbox': + return w.__('timeOutput'); + case 'durationbox': + case 'durationflipbox': + return w.__('durationFormat'); + default: + return w.__('dateFormat'); + } + }, + _zPad: function(number) { + return (( number < 10 ) ? '0' + String(number) : String(number)); + }, + _dRep: function(oper, direction) { + var start = 48, + end = 57, + adder = 1584, + i = null, + ch = null, + newd = ''; + + if ( direction === -1 ) { + start += adder; + end += adder; + adder = -1584; + } + + for ( i=0; i= start && ch <= end ) { + newd = newd + String.fromCharCode(ch+adder); + } else { + newd = newd + String.fromCharCode(ch); + } + } + + return newd; + }, + _doIndic: function() { + var w = this; + + w.d.intHTML.find('*').each(function() { + if ( $(this).children().length < 1 ) { + $(this).text(w._dRep($(this).text())); + } else if ( $(this).hasClass('ui-datebox-slideday') ) { + $(this).html(w._dRep($(this).html())); + } + }); + w.d.intHTML.find('input').each(function() { + $(this).val(w._dRep($(this).val())); + }); + }, + _parser: { + 'default': function (str) { return false; } + }, + _n: function (val,def) { + return ( val < 0 ) ? def : val; + }, + _pa: function (arr,date) { + if ( typeof date === 'boolean' ) { return new this._date(arr[0],arr[1],arr[2],0,0,0,0); } + return new this._date(date.getFullYear(), date.getMonth(), date.getDate(), arr[0], arr[1], arr[2], 0); + }, + _makeDate: function (str) { + // Date Parser + str = $.trim(((this.__('useArabicIndic') === true)?this._dRep(str, -1):str)); + var w = this, + o = this.options, + adv = w.__fmt(), + exp_input = null, + exp_names = [], + exp_format = null, + exp_temp = null, + date = new w._date(), + d = { year: -1, mont: -1, date: -1, hour: -1, mins: -1, secs: -1, week: false, wtyp: 4, wday: false, yday: false, meri: 0 }, + i; + + if ( typeof o.mode === 'undefined' ) { return date; } + if ( typeof w._parser[o.mode] !== 'undefined' ) { return w._parser[o.mode].apply(w,[str]); } + + if ( o.mode === 'durationbox' || o.mode === 'durationflipbox' ) { + adv = adv.replace(/%D([a-z])/gi, function(match, oper) { + switch (oper) { + case 'd': + case 'l': + case 'M': + case 'S': return '(' + match + '|' +'[0-9]+' + ')'; + default: return '.+?'; + } + }); + + adv = new RegExp('^' + adv + '$'); + exp_input = adv.exec(str); + exp_format = adv.exec(w.__fmt()); + + if ( exp_input === null || exp_input.length !== exp_format.length ) { + if ( typeof o.defaultValue === "number" && o.defaultValue > 0 ) { + return new w._date((w.initDate.getEpoch() + parseInt(o.defaultValue,10))*1000); + } + return new w._date(w.initDate.getTime()); + } + + exp_temp = w.initDate.getEpoch(); + for ( i=0; i -1 ) { d.mont = exp_temp; } + break; + case 'B': + exp_temp = $.inArray(exp_input[i], w.__('monthsOfYear')); + if ( exp_temp > -1 ) { d.mont = exp_temp; } + break; + } + } + if ( d.meri !== 0 ) { + if ( d.meri === -1 && d.hour === 12 ) { d.hour = 0; } + if ( d.meri === 1 && d.hour !== 12 ) { d.hour = d.hour + 12; } + } + + date = new w._date(w._n(d.year,0),w._n(d.mont,0),w._n(d.date,1),w._n(d.hour,0),w._n(d.mins,0),w._n(d.secs,0),0); + + if ( d.year < 100 && d.year !== -1 ) { date.setFullYear(d.year); } + + if ( ( d.mont > -1 && d.date > -1 ) || ( d.hour > -1 && d.mins > -1 && d.secs > -1 ) ) { return date; } + + if ( d.week !== false ) { + date.setDWeek(d.wtyp, d.week); + if ( d.date > -1 ) { date.setDate(d.date); } + } + if ( d.yday !== false ) { date.setD(1,0).setD(2,1).adj(2,(d.yday-1)); } + if ( d.wday !== false ) { date.adj(2,(d.wday - date.getDay())); } + } + return date; + }, + _customformat: { + 'default': function(oper, date) { return false; } + }, + _formatter: function(format, date) { + var w = this, + o = this.options, tmp, + dur = { + part: [0,0,0,0], tp: 0 + }; + + if ( o.mode === 'durationbox' || o.mode === 'durationflipbox' ) { + dur.tp = this.theDate.getEpoch() - this.initDate.getEpoch(); + dur.part[0] = parseInt( dur.tp / (60*60*24),10); dur.tp -=(dur.part[0]*60*60*24); // Days + dur.part[1] = parseInt( dur.tp / (60*60),10); dur.tp -= (dur.part[1]*60*60); // Hours + dur.part[2] = parseInt( dur.tp / (60),10); dur.tp -= (dur.part[2]*60); // Minutes + dur.part[3] = dur.tp; // Seconds + + if ( ! format.match(/%Dd/) ) { dur.part[1] += (dur.part[0]*24);} + if ( ! format.match(/%Dl/) ) { dur.part[2] += (dur.part[1]*60);} + if ( ! format.match(/%DM/) ) { dur.part[3] += (dur.part[2]*60);} + } + + format = format.replace(/%(D|X|0|-)*([1-9a-zA-Z])/g, function(match, pad, oper) { + if ( pad === 'X' ) { + if ( typeof w._customformat[o.mode] !== 'undefined' ) { return w._customformat[o.mode](oper, date, o); } + return match; + } + if ( pad === 'D' ) { + switch ( oper ) { + case 'd': return dur.part[0]; + case 'l': return w._zPad(dur.part[1]); + case 'M': return w._zPad(dur.part[2]); + case 'S': return w._zPad(dur.part[3]); + case 'A': return ((dur.part[0] > 1)?w.__('durationDays')[1]:w.__('durationDays')[0]); + default: return match; + } + } + switch ( oper ) { + case '%': // Literal % + return '%'; + case 'a': // Short Day + return w.__('daysOfWeekShort')[date.getDay()]; + case 'A': // Full Day of week + return w.__('daysOfWeek')[date.getDay()]; + case 'b': // Short month + return w.__('monthsOfYearShort')[date.getMonth()]; + case 'B': // Full month + return w.__('monthsOfYear')[date.getMonth()]; + case 'C': // Century + return date.getFullYear().toString().substr(0,2); + case 'd': // Day of month + return (( pad === '-' ) ? date.getDate() : w._zPad(date.getDate())); + case 'H': // Hour (01..23) + case 'k': + return (( pad === '-' ) ? date.getHours() : w._zPad(date.getHours())); + case 'I': // Hour (01..12) + case 'l': + return (( pad === '-' ) ? ((date.getHours() === 0 || date.getHours() === 12)?12:((date.getHours()<12)?date.getHours():(date.getHours()-12))) : w._zPad(((date.getHours() === 0 || date.getHours() === 12)?12:((date.getHours()<12)?date.getHours():date.getHours()-12)))); + case 'm': // Month + return (( pad === '-' ) ? date.getMonth()+1 : w._zPad(date.getMonth()+1)); + case 'M': // Minutes + return (( pad === '-' ) ? date.getMinutes() : w._zPad(date.getMinutes())); + case 'p': // AM/PM (ucase) + return ((date.getHours() < 12)?w.__('meridiem')[0].toUpperCase():w.__('meridiem')[1].toUpperCase()); + case 'P': // AM/PM (lcase) + return ((date.getHours() < 12)?w.__('meridiem')[0].toLowerCase():w.__('meridiem')[1].toLowerCase()); + case 's': // Unix Seconds + return date.getEpoch(); + case 'S': // Seconds + return (( pad === '-' ) ? date.getSeconds() : w._zPad(date.getSeconds())); + case 'u': // Day of week (1-7) + return (( pad === '-' ) ? date.getDay() + 1 : w._zPad(date.getDay() + 1)); + case 'w': // Day of week + return date.getDay(); + case 'y': // Year (2 digit) + return date.getFullYear().toString().substr(2,2); + case 'Y': // Year (4 digit) + return date.getFullYear(); + case 'E': // BE (Buddist Era, 4 Digit) + return date.getFullYear() + 543; + case 'V': + return (( pad === '-' ) ? date.getDWeek(4) : w._zPad(date.getDWeek(4))); + case 'U': + return (( pad === '-' ) ? date.getDWeek(0) : w._zPad(date.getDWeek(0))); + case 'W': + return (( pad === '-' ) ? date.getDWeek(1) : w._zPad(date.getDWeek(1))); + case 'o': // Ordinals + if ( typeof w._ord[o.useLang] !== 'undefined' ) { return w._ord[o.useLang](date.getDate()); } + return w._ord['default'](date.getDate()); + case 'j': + tmp = new Date(date.getFullYear(),0,1); + tmp = Math.ceil((date - tmp) / 86400000)+1; + return (( tmp < 100 ) ? (( tmp < 10 )? '00' : '0') : '' ) + String(tmp); + case 'G': + if ( date.getDWeek(4) === 1 && date.getMonth() > 0 ) { return date.getFullYear() + 1; } + if ( date.getDWeek(4) > 51 && date.getMonth() < 11 ) { return date.getFullYear() - 1; } + return date.getFullYear(); + case 'g': + if ( date.getDWeek(4) === 1 && date.getMonth() > 0 ) { return parseInt(date.getFullYear().toString().substr(2,2),10) + 1; } + if ( date.getDWeek(4) > 51 && date.getMonth() < 11 ) { return parseInt(date.getFullYear().toString().substr(2,2),10) - 1; } + return date.getFullYear().toString().substr(2,2); + default: + return match; + } + }); + + if ( w.__('useArabicIndic') === true ) { + format = w._dRep(format); + } + + return format; + }, + _btwn: function(value, low, high) { + return ( value > low && value < high ); + }, + _minStepFix: function() { + var tempMin = this.theDate.get(4), tmp, + w = this, + o = this.options; + + if ( o.minuteStep > 1 && tempMin % o.minuteStep > 0 ) { + if ( o.minuteStepRound < 0 ) { + tempMin = tempMin - (tempMin % o.minuteStep); + } else if ( o.minStepRound > 0 ) { + tempMin = tempMin + ( o.minuteStep - ( tempMin % o.minuteStep ) ); + } else { + if ( tempMin % o.minuteStep < o.minuteStep / 2 ) { + tempMin = tempMin - (tempMin % o.minuteStep); + } else { + tempMin = tempMin + ( o.minuteStep - ( tempMin % o.minuteStep ) ); + } + } + w.theDate.setMinutes(tempMin); + } + }, + _offset: function(mode, amount, update) { + // Compute a date/time offset. + // update = false to prevent controls refresh + var w = this, + o = this.options, + ok = false; + + mode = (mode || "").toLowerCase(); + + if ( typeof(update) === "undefined" ) { update = true; } + w.d.input.trigger('datebox', {'method':'offset', 'type':mode, 'amount':amount}); + + if ( mode !== 'a' && ( typeof o.rolloverMode[mode] === 'undefined' || o.rolloverMode[mode] === true )) { + ok = $.inArray(mode, ['y','m','d','h','i','s']); + } else { + switch(mode) { + case 'y': ok = 0; break; + case 'm': + if ( w._btwn(w.theDate.getMonth()+amount,-1,12) ) { ok = 1; } + break; + case 'd': + if ( w._btwn(w.theDate.getDate() + amount,0,(32 - w.theDate.copy([0],[0,0,32,13]).getDate() + 1) )) { ok = 2; } + break; + case 'h': + if ( w._btwn(w.theDate.getHours() + amount,-1,24) ) { ok = 3; } + break; + case 'i': + if ( w._btwn(w.theDate.getMinutes() + amount,-1,60) ) { ok = 4; } + break; + case 's': + if ( w._btwn(w.theDate.getSeconds() + amount,-1,60) ) { ok = 5; } + break; + case 'a': + w._offset('h',((amount>0)?1:-1)*12,false); + break; + } + } + if ( ok !== false ) { w.theDate.adj(ok,amount); } + if ( update === true ) { w.refresh(); } + if ( o.useImmediate ) { w.d.input.trigger('datebox', {'method':'doset'}); } + }, + _startOffset: function(date) { + var o = this.options; + + if ( o.startOffsetYears !== false ) { + date.adj(0, o.startOffsetYears); + } + if ( o.startOffsetMonths !== false ) { + date.adj(1, o.startOffsetMonths); + } + if ( o.startOffsetDays !== false ) { + date.adj(2, o.startOffsetDays); + } + return date; + }, + _create: function() { + // Create the widget, called automatically by widget system + $( document ).trigger( "dateboxcreate" ); + + var w = this, + o = $.extend(this.options, (typeof this.element.jqmData('options') !== 'undefined') ? this.element.jqmData('options') : this._getLongOptions(this.element) ), + thisTheme = ( o.theme === false && typeof($(this).jqmData('theme')) === 'undefined' ) ? + ( ( typeof(this.element.parentsUntil(':jqmData(theme)').parent().jqmData('theme')) === 'undefined' ) ? + o.themeDefault : this.element.parentsUntil(':jqmData(theme)').parent().jqmData('theme') ) + : o.theme, + trans = o.useAnimation ? o.transition : 'none', + d = o.useNewStyle === false ? { + input: this.element, + wrap: this.element.wrap('
      ').parent(), + mainWrap: $("
      ", { "class": 'ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden '+trans+' ui-body-'+thisTheme} ).css('zIndex', o.zindex), + intHTML: false + } : { + input: this.element, + wrap: this.element, + mainWrap: $("
      ", { "class": 'ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden '+trans+' ui-body-'+thisTheme} ).css('zIndex', o.zindex), + intHTML: false + }, + touch = ( typeof window.ontouchstart !== 'undefined' ), + drag = { + eStart : (touch ? 'touchstart' : 'mousedown')+'.datebox', + eMove : (touch ? 'touchmove' : 'mousemove')+'.datebox', + eEnd : (touch ? 'touchend' : 'mouseup')+'.datebox', + eEndA : (touch ? 'mouseup.datebox touchend.datebox touchcancel.datebox touchmove.datebox' : 'mouseup.datebox'), + move : false, + start : false, + end : false, + pos : false, + target : false, + delta : false, + tmp : false + }, + calc = { }, + ns = (typeof $.mobile.ns !== 'undefined')?$.mobile.ns:''; + + $.extend(w, {d: d, ns: ns, drag: drag, touch:touch}); + + if ( o.usePlaceholder !== false ) { + if ( o.usePlaceholder === true && w._grabLabel() !== false ) { w.d.input.attr('placeholder', w._grabLabel()); } + if ( typeof o.usePlaceholder === 'string' ) { w.d.input.attr('placeholder', o.usePlaceholder); } + } + + o.theme = thisTheme; + + w.clearFunc = false; + w.disabled = false; + w.runButton = false; + w._date = window.Date; + w._enhanceDate(); + w.baseID = w.d.input.attr('id'); + + w.initDate = new w._date(); + w.theDate = (o.defaultValue) ? w._makeDate(o.defaultValue) : ( (w.d.input.val() !== "") ? w._makeDate(w.d.input.val()) : new w._date() ); + w.initDone = false; + + if ( o.showInitialValue === true ) { + w.d.input.val(w._formatter(w.__fmt(), w.theDate)); + } + + if ( o.useButton === true && o.useInline === false && o.useNewStyle === false ) { + w.d.open = $(''+this.__('tooltip')+'') + .on(o.clickEvent, function(e) { + e.preventDefault(); + if ( !w.disabled ) { w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.parent().addClass('ui-focus'); w.d.input.parent().removeClass('ui-focus'); } + setTimeout( function() { $(e.target).closest('a').removeClass($.mobile.activeBtnClass); }, 300); + }).appendTo(w.d.wrap).buttonMarkup({icon: 'grid', iconpos: 'notext', corners:true, shadow:true}) + .css({'vertical-align': 'middle', 'display': 'inline-block'}); + } + + w.d.screen = $("
      ", {'class':'ui-datebox-screen ui-datebox-hidden'+((o.useModal)?' ui-datebox-screen-modal':'')}) + .css({'z-index': o.zindex-1}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.trigger('datebox', {'method':'close'}); + }); + + if ( o.enhanceInput === true && navigator.userAgent.match(/Android/i) ){ + w.inputType = 'number'; + } else { + w.inputType = 'text'; + } + + if ( o.hideInput ) { w.d.wrap.parent().hide(); } + + if ( o.mobVer < 140 ) { + $('label[for=\''+w.d.input.attr('id')+'\']').addClass('ui-input-text').css('verticalAlign', 'middle'); + } + + w.d.wrap.on(o.clickEvent, function() { + if ( !w.disabled && ( o.noButtonFocusMode || o.focusMode ) ) { + w.d.input.trigger('datebox', {'method': 'open'}); + w.d.wrap.addClass('ui-focus'); + w.d.input.removeClass('ui-focus'); + } + }); + + w.d.input + .removeClass('ui-corner-all ui-shadow-inset') + .bind(w.touch?'touchend':'click', function(e){ + if ( w.disabled === false && o.useNewStyle === true && o.useFocus === false ) { + if ( ((w.touch ? e.originalEvent.changedTouches[0].pageX : e.pageX) - e.target.offsetLeft) > (e.target.offsetWidth - 20) ) { + w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.parent().addClass('ui-focus'); w.d.input.removeClass('ui-focus'); + //setTimeout(function(){w.d.wrap.addClass('ui-focus');}, 200); + } + } + }) + .focus(function(){ + if ( w.disabled === false && o.useFocus === true ) { + w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.addClass('ui-focus'); w.d.input.removeClass('ui-focus'); + if ( o.useNewStyle === false ) { w.d.input.parent().removeClass('ui-focus'); w.d.wrap.parent().addClass('ui-focus'); } + } + if ( o.useNewStyle === false ) { w.d.input.removeClass('ui-focus'); } + }) + .blur(function(){ + w.d.wrap.removeClass('ui-focus'); + w.d.input.removeClass('ui-focus'); + }) + .change(function() { + w.theDate = w._makeDate(w.d.input.val()); + w.refresh(); + }) + .attr("readonly", o.lockInput) + .on('datebox', w._event); + + if ( o.useNewStyle === true ) { + w.d.input.addClass('ui-corner-all '+((o.useAltIcon===true)?'ui-icon-datebox-alt':'ui-icon-datebox')); + if ( o.overrideStyleClass !== false ) { w.d.input.addClass(o.overrideStyleClass); } + } else { + w.d.input.parent().css('border', 'none').removeClass('ui-shadow-inset'); + } + + w.d.wrap.parent().on(o.clickEvent, function() { + if ( !w.disabled && o.useFocus === true && o.useNewStyle === false ) { + w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.addClass('ui-focus'); w.d.input.removeClass('ui-focus'); + setTimeout(function(){ + w.d.wrap.removeClass('ui-focus'); + w.d.wrap.parent().addClass('ui-focus'); + }, 500); + } + }); + + // Check if mousewheel plugin is loaded + if ( typeof $.event.special.mousewheel !== 'undefined' ) { w.wheelExists = true; } + + // Disable when done if element attribute disabled is true. + if ( w.d.input.is(':disabled') ) { + w.disable(); + } + + if ( o.useInline === true || o.useInlineBlind ) { w.open(); } + + w.applyMinMax(false, false); + + //Throw dateboxinit event + $( document ).trigger( "dateboxaftercreate" ); + }, + applyMinMax: function(refresh, override) { + var w = this, + o = this.options, + calc = {}; + + if ( typeof refresh === 'undefined' ) { refresh = false; } + if ( typeof override === 'undefined' ) { override = true; } + + if ( ( override === true || o.minDays === false ) && typeof(w.d.input.attr('min')) !== 'undefined' ) { + calc.today = new w._date(); + calc.lod = 24 * 60 * 60 * 1000; + calc.todayc = new w._date(calc.today.getFullYear(), calc.today.getMonth(), calc.today.getDate(), 0,0,0,0); + calc.fromel = w.d.input.attr('min').split('-'); + calc.compdt = new w._date(calc.fromel[0],calc.fromel[1]-1,calc.fromel[2],0,0,0,0); + o.minDays = parseInt((((calc.compdt.getTime() - calc.todayc.getTime()) / calc.lod))*-1,10); + } + if ( ( override === true || o.maxDays === false ) && typeof(w.d.input.attr('max')) !== 'undefined' ) { + calc.today = new w._date(); + calc.lod = 24 * 60 * 60 * 1000; + calc.todayc = new w._date(calc.today.getFullYear(), calc.today.getMonth(), calc.today.getDate(), 0,0,0,0); + calc.fromel = w.d.input.attr('max').split('-'); + calc.compdt = new w._date(calc.fromel[0],calc.fromel[1]-1,calc.fromel[2],0,0,0,0); + o.maxDays = parseInt((((calc.compdt.getTime() - calc.todayc.getTime()) / calc.lod)),10); + } + + if ( refresh === true ) { w.refresh(); } + }, + _build: { + 'default': function () { + this.d.headerText = "Error"; + this.d.intHTML = $("

      There is no mode by that name loaded / mode not given

      "); + } + }, + _applyCoords: function(e) { + var w = e.widget, + o = e.widget.options, + fixd = { + h: $.mobile.activePage.find('.ui-header').jqmData('position'), + f: $.mobile.activePage.find('.ui-footer').jqmData('position'), + fh: $.mobile.activePage.find('.ui-footer').outerHeight(), + hh: $.mobile.activePage.find('.ui-header').outerHeight() + }, + iput = { + x: w.d.wrap.offset().left + (w.d.wrap.outerWidth() / 2), + y: w.d.wrap.offset().top + (w.d.wrap.outerHeight() / 2) + }, + size = { + w: w.d.mainWrap.outerWidth(), + h: w.d.mainWrap.outerHeight() + }, + doc = { + t: $(window).scrollTop(), + h: $(window).height(), + w: $.mobile.activePage.width(), + ah: $(document).height() + }, + pos = { + y: (o.centerVert) ? doc.t + ((doc.h / 2) - (size.h / 2)) : iput.y - ( size.h / 2 ), + x: (doc.w < 400 || o.centerHoriz ) ? (doc.w / 2) - (size.w /2) : iput.x - (size.w / 2) + }; + + if ( o.centerVert === false ) { + if ( o.hideFixedToolbars === true && ( typeof fixd.f !== 'undefined' || typeof fixd.h !== 'undefined' )) { + $.mobile.activePage.find(":jqmData(position='fixed')").fixedtoolbar('hide'); + fixd.f = undefined; + fixd.h = undefined; + } + + if ( typeof fixd.f !== 'undefined' ) { + if ( ( pos.y + size.h ) > ( doc.h - fixd.fh - 2 ) ) { + pos.y = doc.h - fixd.fh - 2 - size.h; + } + } else { + if ( ( pos.y + size.h ) > ( doc.ah - fixd.fh - 2 ) ) { + pos.y = doc.ah - fixd.fh - 2 - size.h; + } + if ( ( doc.h + doc.t ) < ( size.h + pos.y + 2 ) ) { + pos.y = doc.h + doc.t - size.h - 2; + } + } + + if ( typeof fixd.h !== 'undefined' ) { + if ( ( doc.t + fixd.hh + 2 ) > pos.y ) { + pos.y = doc.t + fixd.hh + 2; + } + } else { + if ( fixd.hh + 2 > pos.y ) { + pos.y = fixd.hh + 2; + } + if ( pos.y < doc.t + 2 ) { + pos.y = doc.t + 2; + } + } + } + w.d.mainWrap.css({'position': 'absolute', 'top': pos.y, 'left': pos.x}); + }, + _drag: { + 'default': function () { return false; } + }, + open: function () { + var w = this, + o = this.options, + popopts = {}, + basepop = {'history':false}, + qns = 'data-'+this.ns, + trans = o.useAnimation ? o.transition : 'none'; + + if ( o.useFocus === true && w.fastReopen === true ) { w.d.input.blur(); return false; } + if ( w.clearFunc !== false ) { + clearTimeout(w.clearFunc); w.clearFunc = false; + } + + // Call the open callback if provided. Additionally, if this + // returns false then the open/update will stop. + if ( o.openCallback !== false ) { + if ( ! $.isFunction(o.openCallback) ) { + if ( typeof window[o.openCallback] !== 'undefined' ) { + o.openCallback = window[o.openCallback]; + } else { + o.openCallback = new Function(o.openCallback); + } + } + if ( o.openCallback.apply(w, $.merge([w.theDate],o.openCallbackArgs)) === false ) { return false; } + } + + w.theDate = w._makeDate(w.d.input.val()); + if ( w.d.input.val() === "" ) { w._startOffset(w.theDate); } + w.d.input.blur(); + + if ( typeof w._build[o.mode] === 'undefined' ) { + w._build['default'].apply(w,[]); + } else { + w._build[o.mode].apply(w,[]); + } + if ( typeof w._drag[o.mode] !== 'undefined' ) { + w._drag[o.mode].apply(w, []); + } + w.d.input.trigger('datebox', {'method':'refresh'}); + if ( w.__('useArabicIndic') === true ) { w._doIndic(); } + + if ( ( o.useInline === true || o.useInlineBlind === true ) && w.initDone === false ) { + w.d.mainWrap.append(w.d.intHTML); + w.d.input.parent().parent().append(w.d.mainWrap); + w.d.mainWrap.removeClass('ui-datebox-hidden'); + if ( o.useInline === true ) { + w.d.mainWrap.addClass('ui-datebox-inline'); + } else { + w.d.mainWrap.addClass('ui-datebox-inlineblind'); + w.d.mainWrap.hide(); + } + w.initDone = false; + w.d.input.trigger('datebox',{'method':'postrefresh'}); + } + + if ( o.useImmediate ) { w.d.input.trigger('datebox', {'method':'doset'}); } + if ( o.useInline ) { return true; } + if ( o.useInlineBlind ) { + if ( w.initDone ) { w.d.mainWrap.slideDown(); } + else { w.initDone = true; } + return true; + } + if ( w.d.intHTML.is(':visible') ) { return false; } // Ignore if already open + + if ( o.enablePopup === true ) { + w.d.dialogPage = false; + w.d.mainWrap.empty(); + if ( o.useHeader === true ) { + w.d.headHTML = $('
      '); + $("Close").appendTo(w.d.headHTML) + .buttonMarkup({ theme : o.themeHeader, icon : 'delete', iconpos: 'notext', corners: true, shadow : true }) + .on(o.clickEventAlt, function(e) { e.preventDefault(); w.d.input.trigger('datebox', {'method':'close'}); }); + $('

      '+w.d.headerText+'

      ').appendTo(w.d.headHTML); + w.d.mainWrap.append(w.d.headHTML); + } + w.d.mainWrap.append(w.d.intHTML).css('zIndex', o.zindex); + w.d.input.trigger('datebox',{'method':'postrefresh'}); + + if ( o.useAnimation === true ) { + popopts.transition = o.transition; + } else { + popopts.transition = "none"; + } + + if ( o.popupForceX !== false && o.popupForceY !== false ) { + popopts.x = o.popupForceX; + popopts.y = o.popupForceY; + } + + if ( o.popupPosition !== false ) { + popopts.positionTo = o.popupPosition; + } else { + if ( typeof w.baseID !== undefined ) { + popopts.positionTo = '#' + w.baseID; + } else { + popopts.positionTo = 'window'; + } + } + + if ( o.useModal === true ) { basepop.overlayTheme = "a"; } + + w.d.mainWrap.removeClass('ui-datebox-hidden').popup(basepop).popup("open", popopts); + w.refresh(); + } else { + if ( o.dialogForce || ( o.dialogEnable && window.width() < 400 ) ) { + w.d.dialogPage = $("
      " + + "
      " + + "

      "+w.d.headerText+"

      ") + .appendTo( $.mobile.pageContainer ) + .page().css('minHeight', '0px').addClass(trans); + w.d.dialogPage.find('.ui-header').find('a').off('click vclick').on(o.clickEventAlt, function(e) { e.preventDefault(); w.d.input.trigger('datebox', {'method':'close'}); }); + w.d.mainWrap.append(w.d.intHTML).css({'marginLeft':'auto', 'marginRight':'auto'}).removeClass('ui-datebox-hidden'); + w.d.dialogPage.find('.ui-content').append(w.d.mainWrap); + w.d.input.trigger('datebox',{'method':'postrefresh'}); + $.mobile.activePage.off( "pagehide.remove" ); + $.mobile.changePage(w.d.dialogPage, {'transition': trans}); + } else { + w.d.dialogPage = false; + w.d.mainWrap.empty(); + if ( o.useHeader === true ) { + w.d.headHTML = $('
      '); + $("Close").appendTo(w.d.headHTML) + .buttonMarkup({ theme : o.themeHeader, icon : 'delete', iconpos: 'notext', corners: true, shadow : true }) + .on(o.clickEventAlt, function(e) { e.preventDefault(); w.d.input.trigger('datebox', {'method':'close'}); }); + $('

      '+w.d.headerText+'

      ').appendTo(w.d.headHTML); + w.d.mainWrap.append(w.d.headHTML); + } + w.d.mainWrap.append(w.d.intHTML).css('zIndex', o.zindex); + w.d.mainWrap.appendTo($.mobile.activePage); + w.d.screen.appendTo($.mobile.activePage); + w.d.input.trigger('datebox',{'method':'postrefresh'}); + w._applyCoords({widget:w}); + + if ( o.useModal === true ) { + if(o.useAnimation) { + w.d.screen.fadeIn('slow'); + } else { + w.d.screen.show(); + } + } else { + setTimeout(function () { w.d.screen.removeClass('ui-datebox-hidden');}, 500); + } + + w.d.mainWrap.addClass('ui-overlay-shadow in').removeClass('ui-datebox-hidden'); + + $(document).on('orientationchange.datebox', {widget:w}, function(e) { w._applyCoords(e.data); }); + if ( o.resizeListener === true ) { + $(window).on('resize.datebox', {widget:w}, function (e) { w._applyCoords(e.data); }); + } + } + } + }, + close: function() { + var w = this, + o = this.options; + + if ( o.useInlineBlind === true ) { w.d.mainWrap.slideUp(); return true;} + if ( o.useInline === true || w.d.intHTML === false ) { return true; } + + if ( w.d.dialogPage !== false ) { + $(w.d.dialogPage).dialog('close'); + + if ( ! $.mobile.activePage.jqmData('mobile-page').options.domCache ) { + $.mobile.activePage.on('pagehide.remove', function () { $(this).remove(); }); + } + + w.d.intHTML.detach().empty(); + w.d.mainWrap.detach().empty(); + w.d.wrap.removeClass('ui-focus'); + w.clearFunc = setTimeout(function () { w.d.dialogPage.empty().remove(); w.clearFunc = false; }, 1500); + } else { + if ( o.enablePopup === true ) { + w.d.mainWrap.popup('close'); + w.d.wrap.removeClass('ui-focus'); + } else { + if ( o.useModal ) { + if(o.useAnimation) { + w.d.screen.fadeOut('slow'); + } else { + w.d.screen.hide(); + } + } else { + w.d.screen.addClass('ui-datebox-hidden'); + } + w.d.screen.detach(); + w.d.mainWrap.addClass('ui-datebox-hidden').removeAttr('style').removeClass('in ui-overlay-shadow').empty().detach(); + w.d.intHTML.detach(); + w.d.wrap.removeClass('ui-focus'); + + $(document).off('orientationchange.datebox'); + if ( o.resizeListener === true ) { + $(window).off('resize.datebox'); + } + } + } + w.d.wrap.parent().removeClass('ui-focus'); + + $(document).off(w.drag.eMove); + $(document).off(w.drag.eEnd); + $(document).off(w.drag.eEndA); + + if ( o.useFocus ) { + w.fastReopen = true; + setTimeout(function(t) { return function () { t.fastReopen = false; };}(w), 300); + } + + if ( o.closeCallback !== false ) { + if ( ! $.isFunction(o.closeCallback) ) { + if ( typeof window[o.closeCallback] !== 'undefined' ) { + o.closeCallback = window[o.closeCallback]; + } else { + o.closeCallback = new Function(o.closeCallback); + } + } + o.closeCallback.apply(w, $.merge([w.theDate], o.closeCallbackArgs)); + } + }, + refresh: function() { + if ( typeof this._build[this.options.mode] === 'undefined' ) { + this._build['default'].apply(this,[]); + } else { + this._build[this.options.mode].apply(this,[]); + } + if ( this.__('useArabicIndic') === true ) { this._doIndic(); } + this.d.mainWrap.append(this.d.intHTML); + this.d.input.trigger('datebox',{'method':'postrefresh'}); + }, + _check: function() { + var w = this, + td = null, + o = this.options; + + w.dateOK = true; + + if ( o.afterToday !== false ) { + td = new w._date(); + if ( w.theDate < td ) { w.theDate = td; } + } + if ( o.beforeToday !== false ) { + td = new w._date(); + if ( w.theDate > td ) { w.theDate = td; } + } + if ( o.maxDays !== false ) { + td = new w._date(); + td.adj(2, o.maxDays); + if ( w.theDate > td ) { w.theDate = td; } + } + if ( o.minDays !== false ) { + td = new w._date(); + td.adj(2, -1*o.minDays); + if ( w.theDate < td ) { w.theDate = td; } + } + if ( o.minHour !== false ) { + if ( w.theDate.getHours() < o.minHour ) { + w.theDate.setHours(o.minHour); + } + } + if ( o.maxHour !== false ) { + if ( w.theDate.getHours() > o.maxHour ) { + w.theDate.setHours(o.maxHour); + } + } + if ( o.maxYear !== false ) { + td = new w._date(o.maxYear, 0, 1); + td.adj(2, -1); + if ( w.theDate > td ) { w.theDate = td; } + } + if ( o.minYear !== false ) { + td = new w._date(o.minYear, 0, 1); + if ( w.theDate < td ) { w.theDate = td; } + } + + if ( $.inArray(o.mode, ['timebox','durationbox','durationflipbox','timeflipbox']) > -1 ) { + if ( o.mode === 'timeflipbox' && o.validHours !== false ) { + if ( $.inArray(w.theDate.getHours(), o.validHours) < 0 ) { w.dateOK = false; } + } + } else { + if ( o.blackDatesRec !== false ) { + for ( i=0; i -1 ) { w.dateOK = false; } + } + if ( o.blackDays !== false ) { + if ( $.inArray(w.theDate.getDay(), o.blackDays) > -1 ) { w.dateOK = false; } + } + } + }, + _grabLabel: function() { + var w = this, + o = this.options; + + if ( typeof o.overrideDialogLabel === 'undefined' ) { + if ( typeof w.d.input.attr('placeholder') !== 'undefined' ) { return w.d.input.attr('placeholder'); } + if ( typeof w.d.input.attr('title') !== 'undefined' ) { return w.d.input.attr('title'); } + if ( w.d.wrap.parent().find('label[for=\''+w.d.input.attr('id')+'\']').text() !== '' ) { + return w.d.wrap.parent().find('label[for=\''+w.d.input.attr('id')+'\']').text(); + } + return false; + } + return o.overrideDialogLabel; + }, + _makeEl: function(source, parts) { + var part = false, + retty = false; + + retty = source.clone(); + + if ( typeof parts.attr !== 'undefined' ) { + for ( part in parts.attr ) { + if ( parts.attr.hasOwnProperty(part) ) { + retty.jqmData(part, parts.attr[part]); + } + } + } + return retty; + }, + _getLongOptions: function(element) { + var key, retty = {}, prefix, temp; + + if ( $.mobile.ns === "" ) { + prefix = "datebox"; + } else { + prefix = $.mobile.ns.substr(0, $.mobile.ns.length - 1) + 'Datebox'; + } + + for ( key in element.data() ) { + if ( key.substr(0, prefix.length) === prefix && key.length > prefix.length ) { + temp = key.substr(prefix.length); + temp = temp.charAt(0).toLowerCase() + temp.slice(1); + retty[temp] = element.data(key); + } + } + return retty; + }, + disable: function(){ + // Disable the element + this.d.input.attr("disabled",true); + this.d.wrap.addClass("ui-disabled").blur(); + this.disabled = true; + this.d.input.trigger('datebox', {'method':'disable'}); + }, + enable: function(){ + // Enable the element + this.d.input.attr("disabled", false); + this.d.wrap.removeClass("ui-disabled"); + this.disabled = false; + this.d.input.trigger('datebox', {'method':'enable'}); + }, + _setOption: function() { + $.Widget.prototype._setOption.apply( this, arguments ); + this.refresh(); + }, + getTheDate: function() { + return this.theDate; + }, + getLastDur: function() { + return this.lastDuration; + }, + setTheDate: function(newDate) { + this.theDate = newDate; + this.refresh(); + }, + callFormat: function(format, date) { + return this._formatter(format, date); + } + }); + + // Degrade date inputs to text inputs, suppress standard UI functions. + $( document ).on( "pagebeforecreate", function( e ) { + $( ":jqmData(role='datebox')", e.target ).each(function() { + $(this).prop('type', 'text'); + }); + }); + // Automatically bind to data-role='datebox' items. + $( document ).on( "pagecreate create", function( e ){ + $( document ).trigger( "dateboxbeforecreate" ); + $( ":jqmData(role='datebox')", e.target ).each(function() { + var defed = typeof ($(this).data(parseInt($.mobile.version.replace(/\./g,''),10) > 111 ? 'mobile-datebox' : 'datebox')); + if ( defed === "undefined" ) { + $(this).datebox(); + } + }); + }); +})( jQuery ); +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ + /* DurationFlipBox Mode */ + +(function($) { + $.extend( $.mobile.datebox.prototype.options, { + themeDatePick: 'b', + themeDate: 'a', + useSetButton: true, + durationSteppers: {'d': 1, 'h': 1, 'i': 1, 's': 1} + }); + $.extend( $.mobile.datebox.prototype, { + '_durfbox_pos': function () { + var w = this, + ech = null, + top = null, + par = this.d.intHTML.find('.ui-datebox-flipcontent').innerHeight(), + tot = null; + + w.d.intHTML.find('.ui-datebox-flipcenter').each(function() { + ech = $(this); + top = ech.innerHeight(); + ech.css('top', ((par/2)-(top/2)+4)*-1); + }); + w.d.intHTML.find('ul').each(function () { + ech = $(this); + par = ech.parent().innerHeight(); + top = ech.find('li').first(); + tot = ech.find('li').size() * top.outerHeight(); + top.css('marginTop', ((tot/2)-(par/2)+(top.outerHeight()/2))*-1); + }); + }, + '_durfbox_series': function (middle, side, type) { + var w = this, + o = this.options, + ret = [[middle.toString(), middle]], nxt, prv; + + for ( var i = 1; i <= side; i++ ) { + nxt = middle + ( i * o.durationSteppers[type] ); + prv = middle - ( i * o.durationSteppers[type] ); + ret.unshift([nxt.toString(), nxt]); + if ( prv > -1 ) { + ret.push([prv.toString(), prv]); + } else { + ret.push(['',-1]); + } + } + return ret; + } + }); + $.extend( $.mobile.datebox.prototype._build, { + 'durationflipbox': function () { + var w = this, + o = this.options, i, y, tt, hRow, tmp, testDate, + sel = ['d','h','i','s'], + cDur = [0,0,0,0], + cDurS = {}, + ival = {'d': 60*60*24, 'h': 60*60, 'i': 60}, + uid = 'ui-datebox-', + flipBase = $("
        "), + ctrl = $("
        ", {"class":uid+'flipcontent'+' '+uid+'flipcontentd'}); + + if ( typeof w.d.intHTML !== 'boolean' ) { + w.d.intHTML.empty().remove(); + } + + w.d.input.on('datebox', function (e,p) { + if ( p.method === 'postrefresh' ) { w._durfbox_pos(); } + }); + + w.d.headerText = ((w._grabLabel() !== false)?w._grabLabel():w.__('titleDateDialogLabel')); + w.d.intHTML = $(''); + + w.fldOrder = w.__('durationOrder'); + + tmp = $('
        '); + for ( y=0; y'+w.__('durationLabel')[jQuery.inArray(w.fldOrder[y],['d','h','i','s'])]+'
        ').css('textAlign','center').appendTo(tmp); + } + tmp.appendTo(w.d.intHTML); + + w.d.intHTML.append(ctrl); + + i = w.theDate.getEpoch() - w.initDate.getEpoch(); + if ( i<0 ) { i = 0; w.theDate.setTime(w.initDate.getTime()); } + w.lastDuration = i; // Let the number of seconds be sort of public. + + // SPLIT TIME INTO DAYS, HRS, MIN, SEC + cDur[0] = parseInt( i / ival.d, 10); i = i % ival.d; + cDur[1] = parseInt( i / ival.h, 10); i = i % ival.h; + cDur[2] = parseInt( i / ival.i, 10); + cDur[3] = i % ival.i; + + cDurS.d = w._durfbox_series(cDur[0],16,'d'); + cDurS.h = w._durfbox_series(cDur[1],16,'h'); + cDurS.i = w._durfbox_series(cDur[2],20,'i'); + cDurS.s = w._durfbox_series(cDur[3],20,'s'); + + for ( y=0; y", { 'class' : 'ui-body-'+tmp}) + .html(""+cDurS[tt][i][0] +"").appendTo(hRow.find('ul')); + } + hRow.appendTo(ctrl); + } + + $("
        ", {"class":uid+'flipcenter ui-overlay-shadow'}).css('pointerEvents', 'none').appendTo(w.d.intHTML); + + if ( o.useSetButton || o.useClearButton ) { + y = $('
        ', {'class':uid+'controls'}); + + if ( o.useSetButton ) { + $(''+w.__('setDurationButtonLabel')+'') + .appendTo(y).buttonMarkup({theme: o.theme, icon: 'check', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.trigger('datebox', {'method':'set', 'value':w._formatter(w.__fmt(),w.theDate), 'date':w.theDate}); + w.d.input.trigger('datebox', {'method':'close'}); + }); + } + if ( o.useClearButton ) { + $(''+w.__('clearButton')+'') + .appendTo(y).buttonMarkup({theme: o.theme, icon: 'delete', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.val(''); + w.d.input.trigger('datebox',{'method':'clear'}); + w.d.input.trigger('datebox',{'method':'close'}); + }); + } + if ( o.useCollapsedBut ) { + y.addClass('ui-datebox-collapse'); + } + y.appendTo(w.d.intHTML); + } + + if ( w.wheelExists ) { // Mousewheel operation, if plugin is loaded + w.d.intHTML.on('mousewheel', '.ui-overlay-shadow', function(e,d) { + e.preventDefault(); + w._offset($(this).jqmData('field'), ((d<0)?-1:1)*$(this).jqmData('amount')); + }); + } + + w.d.intHTML.on(w.drag.eStart, 'ul', function(e,f) { + if ( !w.drag.move ) { + if ( typeof f !== "undefined" ) { e = f; } + w.drag.move = true; + w.drag.target = $(this).find('li').first(); + w.drag.pos = parseInt(w.drag.target.css('marginTop').replace(/px/i, ''),10); + w.drag.start = w.touch ? e.originalEvent.changedTouches[0].pageY : e.pageY; + w.drag.end = false; + e.stopPropagation(); + e.preventDefault(); + } + }); + + w.d.intHTML.on(w.drag.eStart, '.'+uid+'flipcenter', function(e) { // Used only on old browsers and IE. + if ( !w.drag.move ) { + w.drag.target = w.touch ? e.originalEvent.changedTouches[0].pageX - $(e.currentTarget).offset().left : e.pageX - $(e.currentTarget).offset().left; + w.drag.tmp = w.d.intHTML.find('.'+uid+'flipcenter').innerWidth() / (( $.inArray('a', w.fldOrder) > -1 && w.__('timeFormat') !== 12 )?w.fldOrder.length-1:w.fldOrder.length); + $(w.d.intHTML.find('ul').get(parseInt(w.drag.target / w.drag.tmp,10))).trigger(w.drag.eStart,e); + } + }); + + } + }); + $.extend( $.mobile.datebox.prototype._drag, { + 'durationflipbox': function() { + var w = this, + o = this.options, + g = this.drag; + + $(document).on(g.eMove, function(e) { + if ( g.move && o.mode === 'durationflipbox' ) { + g.end = w.touch ? e.originalEvent.changedTouches[0].pageY : e.pageY; + g.target.css('marginTop', (g.pos + g.end - g.start) + 'px'); + e.preventDefault(); + e.stopPropagation(); + return false; + } + }); + + $(document).on(g.eEnd, function(e) { + if ( g.move && o.mode === 'durationflipbox' ) { + g.move = false; + if ( g.end !== false ) { + e.preventDefault(); + e.stopPropagation(); + g.tmp = g.target.parent().parent(); + w._offset(g.tmp.jqmData('field'), (parseInt((g.start - g.end) / g.target.innerHeight(),10) * g.tmp.jqmData('amount') *-1 )); + } + g.start = false; + g.end = false; + } + }); + } + }); +})( jQuery ); diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.durationflipbox.min.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.durationflipbox.min.js new file mode 100644 index 000000000..a7df21b08 --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.durationflipbox.min.js @@ -0,0 +1,7 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +(function(a){a.widget("mobile.datebox",a.mobile.widget,{options:{version:"2-1.4.0-2013070300",mobVer:parseInt(a.mobile.version.replace(/\./g,"")),theme:false,themeDefault:"a",themeHeader:"a",mode:false,centerHoriz:false,centerVert:false,transition:"pop",useAnimation:true,hideInput:false,hideFixedToolbars:false,lockInput:true,enhanceInput:true,zindex:"500",clickEvent:"vclick",clickEventAlt:"click",resizeListener:true,defaultValue:false,showInitialValue:false,dialogEnable:false,dialogForce:false,enablePopup:false,popupPosition:false,popupForceX:false,popupForceY:false,useModal:false,useInline:false,useInlineBlind:false,useHeader:true,useImmediate:false,useNewStyle:false,useAltIcon:false,overrideStyleClass:false,useButton:true,useFocus:false,useClearButton:false,useCollapsedBut:false,usePlaceholder:false,openCallback:false,openCallbackArgs:[],closeCallback:false,closeCallbackArgs:[],startOffsetYears:false,startOffsetMonths:false,startOffsetDays:false,afterToday:false,beforeToday:false,notToday:false,maxDays:false,minDays:false,maxYear:false,minYear:false,blackDates:false,blackDatesRec:false,blackDays:false,minHour:false,maxHour:false,minuteStep:1,minuteStepRound:0,rolloverMode:{m:true,d:true,h:true,i:true,s:true},useLang:"default",lang:{"default":{setDateButtonLabel:"Set Date",setTimeButtonLabel:"Set Time",setDurationButtonLabel:"Set Duration",calTodayButtonLabel:"Jump to Today",titleDateDialogLabel:"Set Date",titleTimeDialogLabel:"Set Time",daysOfWeek:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],daysOfWeekShort:["Su","Mo","Tu","We","Th","Fr","Sa"],monthsOfYear:["January","February","March","April","May","June","July","August","September","October","November","December"],monthsOfYearShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],durationLabel:["Days","Hours","Minutes","Seconds"],durationDays:["Day","Days"],timeFormat:24,headerFormat:"%A, %B %-d, %Y",tooltip:"Open Date Picker",nextMonth:"Next Month",prevMonth:"Previous Month",dateFieldOrder:["m","d","y"],timeFieldOrder:["h","i","a"],slideFieldOrder:["y","m","d"],dateFormat:"%Y-%m-%d",useArabicIndic:false,isRTL:false,calStartDay:0,clearButton:"Clear",durationOrder:["d","h","i","s"],meridiem:["AM","PM"],timeOutput:"%k:%M",durationFormat:"%Dd %DA, %Dl:%DM:%DS",calDateListLabel:"Other Dates",calHeaderFormat:"%B %Y"}}},_enhanceDate:function(){a.extend(this._date.prototype,{copy:function(c,b){if(typeof c==="undefined"){c=[0,0,0,0,0,0,0]}if(typeof b==="undefined"){b=[0,0,0,0,0,0,0]}while(c.length<7){c.push(0)}while(b.length<7){b.push(0)}return new Date(((b[0]>0)?b[0]:this.getFullYear()+c[0]),((b[1]>0)?b[1]:this.getMonth()+c[1]),((b[2]>0)?b[2]:this.getDate()+c[2]),((b[3]>0)?b[3]:this.getHours()+c[3]),((b[4]>0)?b[4]:this.getMinutes()+c[4]),((b[5]>0)?b[5]:this.getSeconds()+c[5]),((b[6]>0)?b[5]:this.getMilliseconds()+c[6]))},adj:function(c,b){if(typeof b!=="number"){throw new Error("Adjustment value not specified")}if(typeof c!=="number"){throw new Error("Adjustment type not specified")}switch(c){case 0:this.setFullYear(this.getFullYear()+b);break;case 1:this.setMonth(this.getMonth()+b);break;case 2:this.setDate(this.getDate()+b);break;case 3:this.setHours(this.getHours()+b);break;case 4:this.setMinutes(this.getMinutes()+b);break;case 5:this.setSeconds(this.getSeconds()+b);break;case 6:this.setMilliseconds(this.getMilliseconds()+b);break}return this},setD:function(c,b){switch(c){case 0:this.setFullYear(b);break;case 1:this.setMonth(b);break;case 2:this.setDate(b);break;case 3:this.setHours(b);break;case 4:this.setMinutes(b);break;case 5:this.setSeconds(b);break;case 6:this.setMilliseconds(b);break}return this},get:function(b){switch(b){case 0:return this.getFullYear();case 1:return this.getMonth();case 2:return this.getDate();case 3:return this.getHours();case 4:return this.getMinutes();case 5:return this.getSeconds()}return false},iso:function(){return String(this.getFullYear())+"-"+((this.getMonth()<9)?"0":"")+String(this.getMonth()+1)+"-"+((this.getDate()<10)?"0":"")+String(this.getDate())},comp:function(){return parseInt(this.iso().replace(/-/g,""),10)},getEpoch:function(){return(this.getTime()-this.getMilliseconds())/1000},getArray:function(){return[this.getFullYear(),this.getMonth(),this.getDate(),this.getHours(),this.getMinutes(),this.getSeconds()]},setFirstDay:function(b){this.setD(2,1).adj(2,(b-this.getDay()));if(this.get(2)>10){this.adj(2,7)}return this},setDWeek:function(c,b){if(c===4){return this.setD(1,0).setD(2,1).setFirstDay(4).adj(2,-3).adj(2,(b-1)*7)}return this.setD(1,0).setD(2,1).setFirstDay(c).adj(2,(b-1)*7)},getDWeek:function(c){var d,b;switch(c){case 0:d=this.copy([0,-1*this.getMonth()]).setFirstDay(0);return Math.floor((this.getTime()-(d.getTime()+((this.getTimezoneOffset()-d.getTimezoneOffset())*60000)))/604800000)+1;case 1:d=this.copy([0,-1*this.getMonth()]).setFirstDay(1);return Math.floor((this.getTime()-(d.getTime()+((this.getTimezoneOffset()-d.getTimezoneOffset())*60000)))/604800000)+1;case 4:if(this.getMonth()===11&&this.getDate()>28){return 1}d=this.copy([0,-1*this.getMonth()],true).setFirstDay(4).adj(2,-3);b=Math.floor((this.getTime()-(d.getTime()+((this.getTimezoneOffset()-d.getTimezoneOffset())*60000)))/604800000)+1;if(b<1){d=this.copy([-1,-1*this.getMonth()]).setFirstDay(4).adj(2,-3);return Math.floor((this.getTime()-d.getTime())/604800000)+1}return b;default:return 0}}})},_event:function(d,c){var b=a(this).data(parseInt(a.mobile.version.replace(/\./g,""),10)>110?"mobile-datebox":"datebox");if(!d.isPropagationStopped()){switch(c.method){case"close":b.close();break;case"open":b.open();break;case"set":a(this).val(c.value);a(this).trigger("change");break;case"doset":if(a.isFunction(b["_"+b.options.mode+"DoSet"])){b["_"+b.options.mode+"DoSet"].apply(b,[])}else{a(this).trigger("datebox",{method:"set",value:b._formatter(b.__fmt(),b.theDate),date:b.theDate})}break;case"dooffset":if(c.type){b._offset(c.type,c.amount,true)}break;case"dorefresh":b.refresh();break;case"doreset":b.hardreset();break;case"doclear":a(this).val("").trigger("change");break;case"clear":a(this).trigger("change")}}},_hoover:function(b){a(b).toggleClass("ui-btn-up-"+a(b).jqmData("theme")+" ui-btn-down-"+a(b).jqmData("theme"))},_ord:{"default":function(c){var b=c%10;if(c>9&&c<21){return"th"}if(b>3){return"th"}return["th","st","nd","rd"][b]}},__:function(d){var c=this.options,b="override"+d.charAt(0).toUpperCase()+d.slice(1);if(typeof c[b]!=="undefined"){return c[b]}if(typeof c.lang[c.useLang][d]!=="undefined"){return c.lang[c.useLang][d]}if(typeof c[c.mode+"lang"]!=="undefined"&&typeof c[c.mode+"lang"][d]!=="undefined"){return c[c.mode+"lang"][d]}return c.lang["default"][d]},__fmt:function(){var b=this,c=this.options;switch(c.mode){case"timebox":case"timeflipbox":return b.__("timeOutput");case"durationbox":case"durationflipbox":return b.__("durationFormat");default:return b.__("dateFormat")}},_zPad:function(b){return((b<10)?"0"+String(b):String(b))},_dRep:function(j,g){var h=48,b=57,c=1584,d=null,e=null,f="";if(g===-1){h+=c;b+=c;c=-1584}for(d=0;d=h&&e<=b){f=f+String.fromCharCode(e+c)}else{f=f+String.fromCharCode(e)}}return f},_doIndic:function(){var b=this;b.d.intHTML.find("*").each(function(){if(a(this).children().length<1){a(this).text(b._dRep(a(this).text()))}else{if(a(this).hasClass("ui-datebox-slideday")){a(this).html(b._dRep(a(this).html()))}}});b.d.intHTML.find("input").each(function(){a(this).val(b._dRep(a(this).val()))})},_parser:{"default":function(b){return false}},_n:function(c,b){return(c<0)?b:c},_pa:function(b,c){if(typeof c==="boolean"){return new this._date(b[0],b[1],b[2],0,0,0,0)}return new this._date(c.getFullYear(),c.getMonth(),c.getDate(),b[0],b[1],b[2],0)},_makeDate:function(k){k=a.trim(((this.__("useArabicIndic")===true)?this._dRep(k,-1):k));var n=this,c=this.options,e=n.__fmt(),m=null,h=[],l=null,b=null,f=new n._date(),j={year:-1,mont:-1,date:-1,hour:-1,mins:-1,secs:-1,week:false,wtyp:4,wday:false,yday:false,meri:0},g;if(typeof c.mode==="undefined"){return f}if(typeof n._parser[c.mode]!=="undefined"){return n._parser[c.mode].apply(n,[k])}if(c.mode==="durationbox"||c.mode==="durationflipbox"){e=e.replace(/%D([a-z])/gi,function(d,o){switch(o){case"d":case"l":case"M":case"S":return"("+d+"|[0-9]+)";default:return".+?"}});e=new RegExp("^"+e+"$");m=e.exec(k);l=e.exec(n.__fmt());if(m===null||m.length!==l.length){if(typeof c.defaultValue==="number"&&c.defaultValue>0){return new n._date((n.initDate.getEpoch()+parseInt(c.defaultValue,10))*1000)}return new n._date(n.initDate.getTime())}b=n.initDate.getEpoch();for(g=0;g-1){j.mont=b}break;case"B":b=a.inArray(m[g],n.__("monthsOfYear"));if(b>-1){j.mont=b}break}}if(j.meri!==0){if(j.meri===-1&&j.hour===12){j.hour=0}if(j.meri===1&&j.hour!==12){j.hour=j.hour+12}}f=new n._date(n._n(j.year,0),n._n(j.mont,0),n._n(j.date,1),n._n(j.hour,0),n._n(j.mins,0),n._n(j.secs,0),0);if(j.year<100&&j.year!==-1){f.setFullYear(j.year)}if((j.mont>-1&&j.date>-1)||(j.hour>-1&&j.mins>-1&&j.secs>-1)){return f}if(j.week!==false){f.setDWeek(j.wtyp,j.week);if(j.date>-1){f.setDate(j.date)}}if(j.yday!==false){f.setD(1,0).setD(2,1).adj(2,(j.yday-1))}if(j.wday!==false){f.adj(2,(j.wday-f.getDay()))}}return f},_customformat:{"default":function(c,b){return false}},_formatter:function(f,c){var b=this,g=this.options,d,e={part:[0,0,0,0],tp:0};if(g.mode==="durationbox"||g.mode==="durationflipbox"){e.tp=this.theDate.getEpoch()-this.initDate.getEpoch();e.part[0]=parseInt(e.tp/(60*60*24),10);e.tp-=(e.part[0]*60*60*24);e.part[1]=parseInt(e.tp/(60*60),10);e.tp-=(e.part[1]*60*60);e.part[2]=parseInt(e.tp/(60),10);e.tp-=(e.part[2]*60);e.part[3]=e.tp;if(!f.match(/%Dd/)){e.part[1]+=(e.part[0]*24)}if(!f.match(/%Dl/)){e.part[2]+=(e.part[1]*60)}if(!f.match(/%DM/)){e.part[3]+=(e.part[2]*60)}}f=f.replace(/%(D|X|0|-)*([1-9a-zA-Z])/g,function(h,j,k){if(j==="X"){if(typeof b._customformat[g.mode]!=="undefined"){return b._customformat[g.mode](k,c,g)}return h}if(j==="D"){switch(k){case"d":return e.part[0];case"l":return b._zPad(e.part[1]);case"M":return b._zPad(e.part[2]);case"S":return b._zPad(e.part[3]);case"A":return((e.part[0]>1)?b.__("durationDays")[1]:b.__("durationDays")[0]);default:return h}}switch(k){case"%":return"%";case"a":return b.__("daysOfWeekShort")[c.getDay()];case"A":return b.__("daysOfWeek")[c.getDay()];case"b":return b.__("monthsOfYearShort")[c.getMonth()];case"B":return b.__("monthsOfYear")[c.getMonth()];case"C":return c.getFullYear().toString().substr(0,2);case"d":return((j==="-")?c.getDate():b._zPad(c.getDate()));case"H":case"k":return((j==="-")?c.getHours():b._zPad(c.getHours()));case"I":case"l":return((j==="-")?((c.getHours()===0||c.getHours()===12)?12:((c.getHours()<12)?c.getHours():(c.getHours()-12))):b._zPad(((c.getHours()===0||c.getHours()===12)?12:((c.getHours()<12)?c.getHours():c.getHours()-12))));case"m":return((j==="-")?c.getMonth()+1:b._zPad(c.getMonth()+1));case"M":return((j==="-")?c.getMinutes():b._zPad(c.getMinutes()));case"p":return((c.getHours()<12)?b.__("meridiem")[0].toUpperCase():b.__("meridiem")[1].toUpperCase());case"P":return((c.getHours()<12)?b.__("meridiem")[0].toLowerCase():b.__("meridiem")[1].toLowerCase());case"s":return c.getEpoch();case"S":return((j==="-")?c.getSeconds():b._zPad(c.getSeconds()));case"u":return((j==="-")?c.getDay()+1:b._zPad(c.getDay()+1));case"w":return c.getDay();case"y":return c.getFullYear().toString().substr(2,2);case"Y":return c.getFullYear();case"E":return c.getFullYear()+543;case"V":return((j==="-")?c.getDWeek(4):b._zPad(c.getDWeek(4)));case"U":return((j==="-")?c.getDWeek(0):b._zPad(c.getDWeek(0)));case"W":return((j==="-")?c.getDWeek(1):b._zPad(c.getDWeek(1)));case"o":if(typeof b._ord[g.useLang]!=="undefined"){return b._ord[g.useLang](c.getDate())}return b._ord["default"](c.getDate());case"j":d=new Date(c.getFullYear(),0,1);d=Math.ceil((c-d)/86400000)+1;return((d<100)?((d<10)?"00":"0"):"")+String(d);case"G":if(c.getDWeek(4)===1&&c.getMonth()>0){return c.getFullYear()+1}if(c.getDWeek(4)>51&&c.getMonth()<11){return c.getFullYear()-1}return c.getFullYear();case"g":if(c.getDWeek(4)===1&&c.getMonth()>0){return parseInt(c.getFullYear().toString().substr(2,2),10)+1}if(c.getDWeek(4)>51&&c.getMonth()<11){return parseInt(c.getFullYear().toString().substr(2,2),10)-1}return c.getFullYear().toString().substr(2,2);default:return h}});if(b.__("useArabicIndic")===true){f=b._dRep(f)}return f},_btwn:function(d,b,c){return(d>b&&d1&&d%e.minuteStep>0){if(e.minuteStepRound<0){d=d-(d%e.minuteStep)}else{if(e.minStepRound>0){d=d+(e.minuteStep-(d%e.minuteStep))}else{if(d%e.minuteStep0)?1:-1)*12,false);break}}if(c!==false){b.theDate.adj(c,d)}if(g===true){b.refresh()}if(e.useImmediate){b.d.input.trigger("datebox",{method:"doset"})}},_startOffset:function(b){var c=this.options;if(c.startOffsetYears!==false){b.adj(0,c.startOffsetYears)}if(c.startOffsetMonths!==false){b.adj(1,c.startOffsetMonths)}if(c.startOffsetDays!==false){b.adj(2,c.startOffsetDays)}return b},_create:function(){a(document).trigger("dateboxcreate");var j=this,b=a.extend(this.options,(typeof this.element.jqmData("options")!=="undefined")?this.element.jqmData("options"):this._getLongOptions(this.element)),k=(b.theme===false&&typeof(a(this).jqmData("theme"))==="undefined")?((typeof(this.element.parentsUntil(":jqmData(theme)").parent().jqmData("theme"))==="undefined")?b.themeDefault:this.element.parentsUntil(":jqmData(theme)").parent().jqmData("theme")):b.theme,l=b.useAnimation?b.transition:"none",g=b.useNewStyle===false?{input:this.element,wrap:this.element.wrap('
        ').parent(),mainWrap:a("
        ",{"class":"ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden "+l+" ui-body-"+k}).css("zIndex",b.zindex),intHTML:false}:{input:this.element,wrap:this.element,mainWrap:a("
        ",{"class":"ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden "+l+" ui-body-"+k}).css("zIndex",b.zindex),intHTML:false},e=(typeof window.ontouchstart!=="undefined"),f={eStart:(e?"touchstart":"mousedown")+".datebox",eMove:(e?"touchmove":"mousemove")+".datebox",eEnd:(e?"touchend":"mouseup")+".datebox",eEndA:(e?"mouseup.datebox touchend.datebox touchcancel.datebox touchmove.datebox":"mouseup.datebox"),move:false,start:false,end:false,pos:false,target:false,delta:false,tmp:false},c={},h=(typeof a.mobile.ns!=="undefined")?a.mobile.ns:"";a.extend(j,{d:g,ns:h,drag:f,touch:e});if(b.usePlaceholder!==false){if(b.usePlaceholder===true&&j._grabLabel()!==false){j.d.input.attr("placeholder",j._grabLabel())}if(typeof b.usePlaceholder==="string"){j.d.input.attr("placeholder",b.usePlaceholder)}}b.theme=k;j.clearFunc=false;j.disabled=false;j.runButton=false;j._date=window.Date;j._enhanceDate();j.baseID=j.d.input.attr("id");j.initDate=new j._date();j.theDate=(b.defaultValue)?j._makeDate(b.defaultValue):((j.d.input.val()!=="")?j._makeDate(j.d.input.val()):new j._date());j.initDone=false;if(b.showInitialValue===true){j.d.input.val(j._formatter(j.__fmt(),j.theDate))}if(b.useButton===true&&b.useInline===false&&b.useNewStyle===false){j.d.open=a(''+this.__("tooltip")+"").on(b.clickEvent,function(d){d.preventDefault();if(!j.disabled){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.parent().addClass("ui-focus");j.d.input.parent().removeClass("ui-focus")}setTimeout(function(){a(d.target).closest("a").removeClass(a.mobile.activeBtnClass)},300)}).appendTo(j.d.wrap).buttonMarkup({icon:"grid",iconpos:"notext",corners:true,shadow:true}).css({"vertical-align":"middle",display:"inline-block"})}j.d.screen=a("
        ",{"class":"ui-datebox-screen ui-datebox-hidden"+((b.useModal)?" ui-datebox-screen-modal":"")}).css({"z-index":b.zindex-1}).on(b.clickEventAlt,function(d){d.preventDefault();j.d.input.trigger("datebox",{method:"close"})});if(b.enhanceInput===true&&navigator.userAgent.match(/Android/i)){j.inputType="number"}else{j.inputType="text"}if(b.hideInput){j.d.wrap.parent().hide()}if(b.mobVer<140){a("label[for='"+j.d.input.attr("id")+"']").addClass("ui-input-text").css("verticalAlign","middle")}j.d.wrap.on(b.clickEvent,function(){if(!j.disabled&&(b.noButtonFocusMode||b.focusMode)){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.addClass("ui-focus");j.d.input.removeClass("ui-focus")}});j.d.input.removeClass("ui-corner-all ui-shadow-inset").bind(j.touch?"touchend":"click",function(d){if(j.disabled===false&&b.useNewStyle===true&&b.useFocus===false){if(((j.touch?d.originalEvent.changedTouches[0].pageX:d.pageX)-d.target.offsetLeft)>(d.target.offsetWidth-20)){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.parent().addClass("ui-focus");j.d.input.removeClass("ui-focus")}}}).focus(function(){if(j.disabled===false&&b.useFocus===true){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.addClass("ui-focus");j.d.input.removeClass("ui-focus");if(b.useNewStyle===false){j.d.input.parent().removeClass("ui-focus");j.d.wrap.parent().addClass("ui-focus")}}if(b.useNewStyle===false){j.d.input.removeClass("ui-focus")}}).blur(function(){j.d.wrap.removeClass("ui-focus");j.d.input.removeClass("ui-focus")}).change(function(){j.theDate=j._makeDate(j.d.input.val());j.refresh()}).attr("readonly",b.lockInput).on("datebox",j._event);if(b.useNewStyle===true){j.d.input.addClass("ui-corner-all "+((b.useAltIcon===true)?"ui-icon-datebox-alt":"ui-icon-datebox"));if(b.overrideStyleClass!==false){j.d.input.addClass(b.overrideStyleClass)}}else{j.d.input.parent().css("border","none").removeClass("ui-shadow-inset")}j.d.wrap.parent().on(b.clickEvent,function(){if(!j.disabled&&b.useFocus===true&&b.useNewStyle===false){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.addClass("ui-focus");j.d.input.removeClass("ui-focus");setTimeout(function(){j.d.wrap.removeClass("ui-focus");j.d.wrap.parent().addClass("ui-focus")},500)}});if(typeof a.event.special.mousewheel!=="undefined"){j.wheelExists=true}if(j.d.input.is(":disabled")){j.disable()}if(b.useInline===true||b.useInlineBlind){j.open()}j.applyMinMax(false,false);a(document).trigger("dateboxaftercreate")},applyMinMax:function(e,d){var b=this,f=this.options,c={};if(typeof e==="undefined"){e=false}if(typeof d==="undefined"){d=true}if((d===true||f.minDays===false)&&typeof(b.d.input.attr("min"))!=="undefined"){c.today=new b._date();c.lod=24*60*60*1000;c.todayc=new b._date(c.today.getFullYear(),c.today.getMonth(),c.today.getDate(),0,0,0,0);c.fromel=b.d.input.attr("min").split("-");c.compdt=new b._date(c.fromel[0],c.fromel[1]-1,c.fromel[2],0,0,0,0);f.minDays=parseInt((((c.compdt.getTime()-c.todayc.getTime())/c.lod))*-1,10)}if((d===true||f.maxDays===false)&&typeof(b.d.input.attr("max"))!=="undefined"){c.today=new b._date();c.lod=24*60*60*1000;c.todayc=new b._date(c.today.getFullYear(),c.today.getMonth(),c.today.getDate(),0,0,0,0);c.fromel=b.d.input.attr("max").split("-");c.compdt=new b._date(c.fromel[0],c.fromel[1]-1,c.fromel[2],0,0,0,0);f.maxDays=parseInt((((c.compdt.getTime()-c.todayc.getTime())/c.lod)),10)}if(e===true){b.refresh()}},_build:{"default":function(){this.d.headerText="Error";this.d.intHTML=a("

        There is no mode by that name loaded / mode not given

        ")}},_applyCoords:function(h){var b=h.widget,j=h.widget.options,f={h:a.mobile.activePage.find(".ui-header").jqmData("position"),f:a.mobile.activePage.find(".ui-footer").jqmData("position"),fh:a.mobile.activePage.find(".ui-footer").outerHeight(),hh:a.mobile.activePage.find(".ui-header").outerHeight()},c={x:b.d.wrap.offset().left+(b.d.wrap.outerWidth()/2),y:b.d.wrap.offset().top+(b.d.wrap.outerHeight()/2)},d={w:b.d.mainWrap.outerWidth(),h:b.d.mainWrap.outerHeight()},g={t:a(window).scrollTop(),h:a(window).height(),w:a.mobile.activePage.width(),ah:a(document).height()},k={y:(j.centerVert)?g.t+((g.h/2)-(d.h/2)):c.y-(d.h/2),x:(g.w<400||j.centerHoriz)?(g.w/2)-(d.w/2):c.x-(d.w/2)};if(j.centerVert===false){if(j.hideFixedToolbars===true&&(typeof f.f!=="undefined"||typeof f.h!=="undefined")){a.mobile.activePage.find(":jqmData(position='fixed')").fixedtoolbar("hide");f.f=undefined;f.h=undefined}if(typeof f.f!=="undefined"){if((k.y+d.h)>(g.h-f.fh-2)){k.y=g.h-f.fh-2-d.h}}else{if((k.y+d.h)>(g.ah-f.fh-2)){k.y=g.ah-f.fh-2-d.h}if((g.h+g.t)<(d.h+k.y+2)){k.y=g.h+g.t-d.h-2}}if(typeof f.h!=="undefined"){if((g.t+f.hh+2)>k.y){k.y=g.t+f.hh+2}}else{if(f.hh+2>k.y){k.y=f.hh+2}if(k.y
        ');a("Close").appendTo(b.d.headHTML).buttonMarkup({theme:g.themeHeader,icon:"delete",iconpos:"notext",corners:true,shadow:true}).on(g.clickEventAlt,function(h){h.preventDefault();b.d.input.trigger("datebox",{method:"close"})});a('

        '+b.d.headerText+"

        ").appendTo(b.d.headHTML);b.d.mainWrap.append(b.d.headHTML)}b.d.mainWrap.append(b.d.intHTML).css("zIndex",g.zindex);b.d.input.trigger("datebox",{method:"postrefresh"});if(g.useAnimation===true){e.transition=g.transition}else{e.transition="none"}if(g.popupForceX!==false&&g.popupForceY!==false){e.x=g.popupForceX;e.y=g.popupForceY}if(g.popupPosition!==false){e.positionTo=g.popupPosition}else{if(typeof b.baseID!==undefined){e.positionTo="#"+b.baseID}else{e.positionTo="window"}}if(g.useModal===true){f.overlayTheme="a"}b.d.mainWrap.removeClass("ui-datebox-hidden").popup(f).popup("open",e);b.refresh()}else{if(g.dialogForce||(g.dialogEnable&&window.width()<400)){b.d.dialogPage=a("

        "+b.d.headerText+"

        ").appendTo(a.mobile.pageContainer).page().css("minHeight","0px").addClass(c);b.d.dialogPage.find(".ui-header").find("a").off("click vclick").on(g.clickEventAlt,function(h){h.preventDefault();b.d.input.trigger("datebox",{method:"close"})});b.d.mainWrap.append(b.d.intHTML).css({marginLeft:"auto",marginRight:"auto"}).removeClass("ui-datebox-hidden");b.d.dialogPage.find(".ui-content").append(b.d.mainWrap);b.d.input.trigger("datebox",{method:"postrefresh"});a.mobile.activePage.off("pagehide.remove");a.mobile.changePage(b.d.dialogPage,{transition:c})}else{b.d.dialogPage=false;b.d.mainWrap.empty();if(g.useHeader===true){b.d.headHTML=a('
        ');a("Close").appendTo(b.d.headHTML).buttonMarkup({theme:g.themeHeader,icon:"delete",iconpos:"notext",corners:true,shadow:true}).on(g.clickEventAlt,function(h){h.preventDefault();b.d.input.trigger("datebox",{method:"close"})});a('

        '+b.d.headerText+"

        ").appendTo(b.d.headHTML);b.d.mainWrap.append(b.d.headHTML)}b.d.mainWrap.append(b.d.intHTML).css("zIndex",g.zindex);b.d.mainWrap.appendTo(a.mobile.activePage);b.d.screen.appendTo(a.mobile.activePage);b.d.input.trigger("datebox",{method:"postrefresh"});b._applyCoords({widget:b});if(g.useModal===true){if(g.useAnimation){b.d.screen.fadeIn("slow")}else{b.d.screen.show()}}else{setTimeout(function(){b.d.screen.removeClass("ui-datebox-hidden")},500)}b.d.mainWrap.addClass("ui-overlay-shadow in").removeClass("ui-datebox-hidden");a(document).on("orientationchange.datebox",{widget:b},function(h){b._applyCoords(h.data)});if(g.resizeListener===true){a(window).on("resize.datebox",{widget:b},function(h){b._applyCoords(h.data)})}}}},close:function(){var b=this,c=this.options;if(c.useInlineBlind===true){b.d.mainWrap.slideUp();return true}if(c.useInline===true||b.d.intHTML===false){return true}if(b.d.dialogPage!==false){a(b.d.dialogPage).dialog("close");if(!a.mobile.activePage.jqmData("mobile-page").options.domCache){a.mobile.activePage.on("pagehide.remove",function(){a(this).remove()})}b.d.intHTML.detach().empty();b.d.mainWrap.detach().empty();b.d.wrap.removeClass("ui-focus");b.clearFunc=setTimeout(function(){b.d.dialogPage.empty().remove();b.clearFunc=false},1500)}else{if(c.enablePopup===true){b.d.mainWrap.popup("close");b.d.wrap.removeClass("ui-focus")}else{if(c.useModal){if(c.useAnimation){b.d.screen.fadeOut("slow")}else{b.d.screen.hide()}}else{b.d.screen.addClass("ui-datebox-hidden")}b.d.screen.detach();b.d.mainWrap.addClass("ui-datebox-hidden").removeAttr("style").removeClass("in ui-overlay-shadow").empty().detach();b.d.intHTML.detach();b.d.wrap.removeClass("ui-focus");a(document).off("orientationchange.datebox");if(c.resizeListener===true){a(window).off("resize.datebox")}}}b.d.wrap.parent().removeClass("ui-focus");a(document).off(b.drag.eMove);a(document).off(b.drag.eEnd);a(document).off(b.drag.eEndA);if(c.useFocus){b.fastReopen=true;setTimeout(function(d){return function(){d.fastReopen=false}}(b),300)}if(c.closeCallback!==false){if(!a.isFunction(c.closeCallback)){if(typeof window[c.closeCallback]!=="undefined"){c.closeCallback=window[c.closeCallback]}else{c.closeCallback=new Function(c.closeCallback)}}c.closeCallback.apply(b,a.merge([b.theDate],c.closeCallbackArgs))}},refresh:function(){if(typeof this._build[this.options.mode]==="undefined"){this._build["default"].apply(this,[])}else{this._build[this.options.mode].apply(this,[])}if(this.__("useArabicIndic")===true){this._doIndic()}this.d.mainWrap.append(this.d.intHTML);this.d.input.trigger("datebox",{method:"postrefresh"})},_check:function(){var b=this,d=null,c=this.options;b.dateOK=true;if(c.afterToday!==false){d=new b._date();if(b.theDated){b.theDate=d}}if(c.maxDays!==false){d=new b._date();d.adj(2,c.maxDays);if(b.theDate>d){b.theDate=d}}if(c.minDays!==false){d=new b._date();d.adj(2,-1*c.minDays);if(b.theDatec.maxHour){b.theDate.setHours(c.maxHour)}}if(c.maxYear!==false){d=new b._date(c.maxYear,0,1);d.adj(2,-1);if(b.theDate>d){b.theDate=d}}if(c.minYear!==false){d=new b._date(c.minYear,0,1);if(b.theDate-1){if(c.mode==="timeflipbox"&&c.validHours!==false){if(a.inArray(b.theDate.getHours(),c.validHours)<0){b.dateOK=false}}}else{if(c.blackDatesRec!==false){for(i=0;i-1){b.dateOK=false}}if(c.blackDays!==false){if(a.inArray(b.theDate.getDay(),c.blackDays)>-1){b.dateOK=false}}}},_grabLabel:function(){var b=this,c=this.options;if(typeof c.overrideDialogLabel==="undefined"){if(typeof b.d.input.attr("placeholder")!=="undefined"){return b.d.input.attr("placeholder")}if(typeof b.d.input.attr("title")!=="undefined"){return b.d.input.attr("title")}if(b.d.wrap.parent().find("label[for='"+b.d.input.attr("id")+"']").text()!==""){return b.d.wrap.parent().find("label[for='"+b.d.input.attr("id")+"']").text()}return false}return c.overrideDialogLabel},_makeEl:function(d,e){var b=false,c=false;c=d.clone();if(typeof e.attr!=="undefined"){for(b in e.attr){if(e.attr.hasOwnProperty(b)){c.jqmData(b,e.attr[b])}}}return c},_getLongOptions:function(d){var c,e={},f,b;if(a.mobile.ns===""){f="datebox"}else{f=a.mobile.ns.substr(0,a.mobile.ns.length-1)+"Datebox"}for(c in d.data()){if(c.substr(0,f.length)===f&&c.length>f.length){b=c.substr(f.length);b=b.charAt(0).toLowerCase()+b.slice(1);e[b]=d.data(c)}}return e},disable:function(){this.d.input.attr("disabled",true);this.d.wrap.addClass("ui-disabled").blur();this.disabled=true;this.d.input.trigger("datebox",{method:"disable"})},enable:function(){this.d.input.attr("disabled",false);this.d.wrap.removeClass("ui-disabled");this.disabled=false;this.d.input.trigger("datebox",{method:"enable"})},_setOption:function(){a.Widget.prototype._setOption.apply(this,arguments);this.refresh()},getTheDate:function(){return this.theDate},getLastDur:function(){return this.lastDuration},setTheDate:function(b){this.theDate=b;this.refresh()},callFormat:function(c,b){return this._formatter(c,b)}});a(document).on("pagebeforecreate",function(b){a(":jqmData(role='datebox')",b.target).each(function(){a(this).prop("type","text")})});a(document).on("pagecreate create",function(b){a(document).trigger("dateboxbeforecreate");a(":jqmData(role='datebox')",b.target).each(function(){var c=typeof(a(this).data(parseInt(a.mobile.version.replace(/\./g,""),10)>111?"mobile-datebox":"datebox"));if(c==="undefined"){a(this).datebox()}})})})(jQuery);(function(a){a.extend(a.mobile.datebox.prototype.options,{themeDatePick:"b",themeDate:"a",useSetButton:true,durationSteppers:{d:1,h:1,i:1,s:1}});a.extend(a.mobile.datebox.prototype,{_durfbox_pos:function(){var b=this,f=null,e=null,d=this.d.intHTML.find(".ui-datebox-flipcontent").innerHeight(),c=null;b.d.intHTML.find(".ui-datebox-flipcenter").each(function(){f=a(this);e=f.innerHeight();f.css("top",((d/2)-(e/2)+4)*-1)});b.d.intHTML.find("ul").each(function(){f=a(this);d=f.parent().innerHeight();e=f.find("li").first();c=f.find("li").size()*e.outerHeight();e.css("marginTop",((c/2)-(d/2)+(e.outerHeight()/2))*-1)})},_durfbox_series:function(k,g,h){var j=this,c=this.options,f=[[k.toString(),k]],b,e;for(var d=1;d<=g;d++){b=k+(d*c.durationSteppers[h]);e=k-(d*c.durationSteppers[h]);f.unshift([b.toString(),b]);if(e>-1){f.push([e.toString(),e])}else{f.push(["",-1])}}return f}});a.extend(a.mobile.datebox.prototype._build,{durationflipbox:function(){var q=this,e=this.options,g,l,k,r,h,m,d=["d","h","i","s"],f=[0,0,0,0],p={},n={d:60*60*24,h:60*60,i:60},j="ui-datebox-",c=a("
          "),b=a("
          ",{"class":j+"flipcontent "+j+"flipcontentd"});if(typeof q.d.intHTML!=="boolean"){q.d.intHTML.empty().remove()}q.d.input.on("datebox",function(o,i){if(i.method==="postrefresh"){q._durfbox_pos()}});q.d.headerText=((q._grabLabel()!==false)?q._grabLabel():q.__("titleDateDialogLabel"));q.d.intHTML=a("");q.fldOrder=q.__("durationOrder");h=a('
          ');for(l=0;l'+q.__("durationLabel")[jQuery.inArray(q.fldOrder[l],["d","h","i","s"])]+"
          ").css("textAlign","center").appendTo(h)}h.appendTo(q.d.intHTML);q.d.intHTML.append(b);g=q.theDate.getEpoch()-q.initDate.getEpoch();if(g<0){g=0;q.theDate.setTime(q.initDate.getTime())}q.lastDuration=g;f[0]=parseInt(g/n.d,10);g=g%n.d;f[1]=parseInt(g/n.h,10);g=g%n.h;f[2]=parseInt(g/n.i,10);f[3]=g%n.i;p.d=q._durfbox_series(f[0],16,"d");p.h=q._durfbox_series(f[1],16,"h");p.i=q._durfbox_series(f[2],20,"i");p.s=q._durfbox_series(f[3],20,"s");for(l=0;l",{"class":"ui-body-"+h}).html(""+p[k][g][0]+"").appendTo(r.find("ul"))}r.appendTo(b)}a("
          ",{"class":j+"flipcenter ui-overlay-shadow"}).css("pointerEvents","none").appendTo(q.d.intHTML);if(e.useSetButton||e.useClearButton){l=a("
          ",{"class":j+"controls"});if(e.useSetButton){a(''+q.__("setDurationButtonLabel")+"").appendTo(l).buttonMarkup({theme:e.theme,icon:"check",iconpos:"left",corners:true,shadow:true}).on(e.clickEventAlt,function(i){i.preventDefault();q.d.input.trigger("datebox",{method:"set",value:q._formatter(q.__fmt(),q.theDate),date:q.theDate});q.d.input.trigger("datebox",{method:"close"})})}if(e.useClearButton){a(''+q.__("clearButton")+"").appendTo(l).buttonMarkup({theme:e.theme,icon:"delete",iconpos:"left",corners:true,shadow:true}).on(e.clickEventAlt,function(i){i.preventDefault();q.d.input.val("");q.d.input.trigger("datebox",{method:"clear"});q.d.input.trigger("datebox",{method:"close"})})}if(e.useCollapsedBut){l.addClass("ui-datebox-collapse")}l.appendTo(q.d.intHTML)}if(q.wheelExists){q.d.intHTML.on("mousewheel",".ui-overlay-shadow",function(i,o){i.preventDefault();q._offset(a(this).jqmData("field"),((o<0)?-1:1)*a(this).jqmData("amount"))})}q.d.intHTML.on(q.drag.eStart,"ul",function(o,i){if(!q.drag.move){if(typeof i!=="undefined"){o=i}q.drag.move=true;q.drag.target=a(this).find("li").first();q.drag.pos=parseInt(q.drag.target.css("marginTop").replace(/px/i,""),10);q.drag.start=q.touch?o.originalEvent.changedTouches[0].pageY:o.pageY;q.drag.end=false;o.stopPropagation();o.preventDefault()}});q.d.intHTML.on(q.drag.eStart,"."+j+"flipcenter",function(i){if(!q.drag.move){q.drag.target=q.touch?i.originalEvent.changedTouches[0].pageX-a(i.currentTarget).offset().left:i.pageX-a(i.currentTarget).offset().left;q.drag.tmp=q.d.intHTML.find("."+j+"flipcenter").innerWidth()/((a.inArray("a",q.fldOrder)>-1&&q.__("timeFormat")!==12)?q.fldOrder.length-1:q.fldOrder.length);a(q.d.intHTML.find("ul").get(parseInt(q.drag.target/q.drag.tmp,10))).trigger(q.drag.eStart,i)}})}});a.extend(a.mobile.datebox.prototype._drag,{durationflipbox:function(){var b=this,d=this.options,c=this.drag;a(document).on(c.eMove,function(f){if(c.move&&d.mode==="durationflipbox"){c.end=b.touch?f.originalEvent.changedTouches[0].pageY:f.pageY;c.target.css("marginTop",(c.pos+c.end-c.start)+"px");f.preventDefault();f.stopPropagation();return false}});a(document).on(c.eEnd,function(f){if(c.move&&d.mode==="durationflipbox"){c.move=false;if(c.end!==false){f.preventDefault();f.stopPropagation();c.tmp=c.target.parent().parent();b._offset(c.tmp.jqmData("field"),(parseInt((c.start-c.end)/c.target.innerHeight(),10)*c.tmp.jqmData("amount")*-1))}c.start=false;c.end=false}})}})})(jQuery); \ No newline at end of file diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.flipbox.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.flipbox.js new file mode 100644 index 000000000..c10f968ca --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.flipbox.js @@ -0,0 +1,1616 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +/* CORE Functions */ + +(function($) { + $.widget( "mobile.datebox", $.mobile.widget, { + options: { + // All widget options, including some internal runtime details + version: '2-1.4.0-2013070300', // jQMMajor.jQMMinor.DBoxMinor-YrMoDaySerial + mobVer: parseInt($.mobile.version.replace(/\./g,'')), + theme: false, + themeDefault: 'a', + themeHeader: 'a', + mode: false, + + centerHoriz: false, + centerVert: false, + transition: 'pop', + useAnimation: true, + hideInput: false, + hideFixedToolbars: false, + + lockInput: true, + enhanceInput: true, + + zindex: '500', + clickEvent: 'vclick', + clickEventAlt: 'click', + resizeListener: true, + + defaultValue: false, + showInitialValue: false, + + dialogEnable: false, + dialogForce: false, + enablePopup: false, + + popupPosition: false, + popupForceX: false, + popupForceY: false, + + useModal: false, + useInline: false, + useInlineBlind: false, + useHeader: true, + useImmediate: false, + useNewStyle: false, + useAltIcon: false, + overrideStyleClass: false, + + useButton: true, + useFocus: false, + useClearButton: false, + useCollapsedBut: false, + usePlaceholder: false, + + openCallback: false, + openCallbackArgs: [], + closeCallback: false, + closeCallbackArgs: [], + + startOffsetYears: false, + startOffsetMonths: false, + startOffsetDays: false, + afterToday: false, + beforeToday: false, + notToday: false, + maxDays: false, + minDays: false, + maxYear: false, + minYear: false, + blackDates: false, + blackDatesRec: false, + blackDays: false, + minHour: false, + maxHour: false, + minuteStep: 1, + minuteStepRound: 0, + + rolloverMode: { 'm': true, 'd': true, 'h': true, 'i': true, 's': true }, + + useLang: 'default', + lang: { + 'default' : { + setDateButtonLabel: 'Set Date', + setTimeButtonLabel: 'Set Time', + setDurationButtonLabel: 'Set Duration', + calTodayButtonLabel: 'Jump to Today', + titleDateDialogLabel: 'Set Date', + titleTimeDialogLabel: 'Set Time', + daysOfWeek: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], + daysOfWeekShort: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], + monthsOfYear: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], + monthsOfYearShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + durationLabel: ['Days', 'Hours', 'Minutes', 'Seconds'], + durationDays: ['Day', 'Days'], + timeFormat: 24, + headerFormat: '%A, %B %-d, %Y', + tooltip: 'Open Date Picker', + nextMonth: 'Next Month', + prevMonth: 'Previous Month', + dateFieldOrder: ['m', 'd', 'y'], + timeFieldOrder: ['h', 'i', 'a'], + slideFieldOrder: ['y', 'm', 'd'], + dateFormat: '%Y-%m-%d', + useArabicIndic: false, + isRTL: false, + calStartDay: 0, + clearButton: 'Clear', + durationOrder: ['d', 'h', 'i', 's'], + meridiem: ['AM', 'PM'], + timeOutput: '%k:%M', //{ '12': '%l:%M %p', '24': '%k:%M' }, + durationFormat: '%Dd %DA, %Dl:%DM:%DS', + calDateListLabel: 'Other Dates', + calHeaderFormat: '%B %Y' + } + } + }, + _enhanceDate: function() { + $.extend(this._date.prototype, { + copy: function(adjust, override) { + /* Get a modified copy of the date. + * First array - Offset the new date by # (position determines date part) + * Second array - If non-zero, force the new date by # (position determines date part) + */ + if ( typeof adjust === 'undefined' ) { adjust = [0,0,0,0,0,0,0]; } + if ( typeof override === 'undefined' ) { override = [0,0,0,0,0,0,0]; } + while ( adjust.length < 7 ) { adjust.push(0); } + while ( override.length < 7 ) { override.push(0); } + return new Date( + ((override[0] > 0 ) ? override[0] : this.getFullYear() + adjust[0]), + ((override[1] > 0 ) ? override[1] : this.getMonth() + adjust[1]), + ((override[2] > 0 ) ? override[2] : this.getDate() + adjust[2]), + ((override[3] > 0 ) ? override[3] : this.getHours() + adjust[3]), + ((override[4] > 0 ) ? override[4] : this.getMinutes() + adjust[4]), + ((override[5] > 0 ) ? override[5] : this.getSeconds() + adjust[5]), + ((override[6] > 0 ) ? override[5] : this.getMilliseconds() + adjust[6])); + }, + adj: function (type, amount) { + /* Adjust the date. Yes, this is chainable */ + if ( typeof amount !== 'number' ) { + throw new Error("Adjustment value not specified"); + } + if ( typeof type !== 'number' ) { + throw new Error("Adjustment type not specified"); + } + switch ( type ) { + case 0: this.setFullYear(this.getFullYear() + amount); break; + case 1: this.setMonth(this.getMonth() + amount); break; + case 2: this.setDate(this.getDate() + amount); break; + case 3: this.setHours(this.getHours() + amount); break; + case 4: this.setMinutes(this.getMinutes() + amount); break; + case 5: this.setSeconds(this.getSeconds() + amount); break; + case 6: this.setMilliseconds(this.getMilliseconds() + amount); break; + } + return this; + }, + setD: function(type, amount) { + /* A chainable version of setWhatever() */ + switch ( type ) { + case 0: this.setFullYear(amount); break; + case 1: this.setMonth(amount); break; + case 2: this.setDate(amount); break; + case 3: this.setHours(amount); break; + case 4: this.setMinutes(amount); break; + case 5: this.setSeconds(amount); break; + case 6: this.setMilliseconds(amount); break; + } + return this; + }, + get: function(type) { + switch ( type ) { + case 0: return this.getFullYear(); + case 1: return this.getMonth(); + case 2: return this.getDate(); + case 3: return this.getHours(); + case 4: return this.getMinutes(); + case 5: return this.getSeconds(); + } + return false; + }, + iso: function() { + return String(this.getFullYear()) + '-' + (( this.getMonth() < 9 ) ? "0" : "") + String(this.getMonth()+1) + '-' + ((this.getDate() < 10 ) ? "0" : "") + String(this.getDate()); + }, + comp: function () { + return parseInt(this.iso().replace(/-/g,''),10); + }, + getEpoch: function() { + return (this.getTime() - this.getMilliseconds()) / 1000; + }, + getArray: function() { + return [this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds()]; + }, + setFirstDay: function (day) { + this.setD(2,1).adj(2, (day - this.getDay())); + if ( this.get(2) > 10 ) { this.adj(2,7); } + return this; + }, + setDWeek: function (type,num) { + if ( type === 4 ) { + return this.setD(1,0).setD(2,1).setFirstDay(4).adj(2,-3).adj(2,(num-1)*7); + } + return this.setD(1,0).setD(2,1).setFirstDay(type).adj(2,(num-1)*7); + }, + getDWeek: function (type) { + var t1, t2; + + switch ( type ) { + case 0: + t1 = this.copy([0,-1*this.getMonth()]).setFirstDay(0); + return Math.floor((this.getTime() - ( t1.getTime() + (( this.getTimezoneOffset() - t1.getTimezoneOffset()) * 60000))) / 6048e5) + 1; + //return Math.floor((this.getTime() - t1.getTime()) / 6048e5) + 1; + case 1: + t1 = this.copy([0,-1*this.getMonth()]).setFirstDay(1); + return Math.floor((this.getTime() - ( t1.getTime() + (( this.getTimezoneOffset() - t1.getTimezoneOffset()) * 60000))) / 6048e5) + 1; + //return Math.floor((this.getTime() - t1.getTime()) / 6048e5) + 1; + case 4: + // this line is some bullshit. but it does work. + // (trap for dec 29, 30, or 31st being in the new year's week - these are the + // only 3 that can possibly fall like this) + if ( this.getMonth() === 11 && this.getDate() > 28 ) { return 1; } + + t1 = this.copy([0,-1*this.getMonth()],true).setFirstDay(4).adj(2,-3); + t2 = Math.floor((this.getTime() - ( t1.getTime() + (( this.getTimezoneOffset() - t1.getTimezoneOffset()) * 60000))) / 6048e5) + 1; + + if ( t2 < 1 ) { + t1 = this.copy([-1,-1*this.getMonth()]).setFirstDay(4).adj(2,-3); + return Math.floor((this.getTime() - t1.getTime()) / 6048e5) + 1; + } + return t2; + default: + return 0; + } + } + }); + }, + _event: function(e, p) { + var w = $(this).data(parseInt($.mobile.version.replace(/\./g,''),10) > 110 ? 'mobile-datebox' : 'datebox'); + if ( ! e.isPropagationStopped() ) { + switch (p.method) { + case 'close': + w.close(); break; + case 'open': + w.open(); break; + case 'set': + $(this).val(p.value); + $(this).trigger('change'); + break; + case 'doset': + if ( $.isFunction(w['_'+w.options.mode+'DoSet']) ) { + w['_'+w.options.mode+'DoSet'].apply(w,[]); + } else { + $(this).trigger('datebox', {'method':'set', 'value':w._formatter(w.__fmt(), w.theDate), 'date':w.theDate}); + } + break; + case 'dooffset': + if (p.type) { w._offset(p.type, p.amount, true); } break; + case 'dorefresh': + w.refresh(); break; + case 'doreset': + w.hardreset(); break; + case 'doclear': + $(this).val('').trigger('change'); break; + case 'clear': + $(this).trigger('change'); + } + } + }, + _hoover: function(item) { + // Hover toggle class, for calendar + $(item).toggleClass('ui-btn-up-'+$(item).jqmData('theme')+' ui-btn-down-'+$(item).jqmData('theme')); + }, + _ord: { + 'default': function (num) { + // Return an ordinal suffix (1st, 2nd, 3rd, etc) + var ending = num % 10; + if ( num > 9 && num < 21 ) { return 'th'; } + if ( ending > 3 ) { return 'th'; } + return ['th','st','nd','rd'][ending]; + } + }, + __ : function(val) { + var o = this.options, + oride = 'override' + val.charAt(0).toUpperCase() + val.slice(1); + + if ( typeof o[oride] !== 'undefined' ) { return o[oride]; } + if ( typeof o.lang[o.useLang][val] !== 'undefined' ) { return o.lang[o.useLang][val]; } + if ( typeof o[o.mode+'lang'] !== 'undefined' && typeof o[o.mode+'lang'][val] !== 'undefined' ) { return o[o.mode+'lang'][val]; } + return o.lang['default'][val]; + }, + __fmt: function() { + var w = this, + o = this.options; + + switch ( o.mode ) { + case 'timebox': + case 'timeflipbox': + return w.__('timeOutput'); + case 'durationbox': + case 'durationflipbox': + return w.__('durationFormat'); + default: + return w.__('dateFormat'); + } + }, + _zPad: function(number) { + return (( number < 10 ) ? '0' + String(number) : String(number)); + }, + _dRep: function(oper, direction) { + var start = 48, + end = 57, + adder = 1584, + i = null, + ch = null, + newd = ''; + + if ( direction === -1 ) { + start += adder; + end += adder; + adder = -1584; + } + + for ( i=0; i= start && ch <= end ) { + newd = newd + String.fromCharCode(ch+adder); + } else { + newd = newd + String.fromCharCode(ch); + } + } + + return newd; + }, + _doIndic: function() { + var w = this; + + w.d.intHTML.find('*').each(function() { + if ( $(this).children().length < 1 ) { + $(this).text(w._dRep($(this).text())); + } else if ( $(this).hasClass('ui-datebox-slideday') ) { + $(this).html(w._dRep($(this).html())); + } + }); + w.d.intHTML.find('input').each(function() { + $(this).val(w._dRep($(this).val())); + }); + }, + _parser: { + 'default': function (str) { return false; } + }, + _n: function (val,def) { + return ( val < 0 ) ? def : val; + }, + _pa: function (arr,date) { + if ( typeof date === 'boolean' ) { return new this._date(arr[0],arr[1],arr[2],0,0,0,0); } + return new this._date(date.getFullYear(), date.getMonth(), date.getDate(), arr[0], arr[1], arr[2], 0); + }, + _makeDate: function (str) { + // Date Parser + str = $.trim(((this.__('useArabicIndic') === true)?this._dRep(str, -1):str)); + var w = this, + o = this.options, + adv = w.__fmt(), + exp_input = null, + exp_names = [], + exp_format = null, + exp_temp = null, + date = new w._date(), + d = { year: -1, mont: -1, date: -1, hour: -1, mins: -1, secs: -1, week: false, wtyp: 4, wday: false, yday: false, meri: 0 }, + i; + + if ( typeof o.mode === 'undefined' ) { return date; } + if ( typeof w._parser[o.mode] !== 'undefined' ) { return w._parser[o.mode].apply(w,[str]); } + + if ( o.mode === 'durationbox' || o.mode === 'durationflipbox' ) { + adv = adv.replace(/%D([a-z])/gi, function(match, oper) { + switch (oper) { + case 'd': + case 'l': + case 'M': + case 'S': return '(' + match + '|' +'[0-9]+' + ')'; + default: return '.+?'; + } + }); + + adv = new RegExp('^' + adv + '$'); + exp_input = adv.exec(str); + exp_format = adv.exec(w.__fmt()); + + if ( exp_input === null || exp_input.length !== exp_format.length ) { + if ( typeof o.defaultValue === "number" && o.defaultValue > 0 ) { + return new w._date((w.initDate.getEpoch() + parseInt(o.defaultValue,10))*1000); + } + return new w._date(w.initDate.getTime()); + } + + exp_temp = w.initDate.getEpoch(); + for ( i=0; i -1 ) { d.mont = exp_temp; } + break; + case 'B': + exp_temp = $.inArray(exp_input[i], w.__('monthsOfYear')); + if ( exp_temp > -1 ) { d.mont = exp_temp; } + break; + } + } + if ( d.meri !== 0 ) { + if ( d.meri === -1 && d.hour === 12 ) { d.hour = 0; } + if ( d.meri === 1 && d.hour !== 12 ) { d.hour = d.hour + 12; } + } + + date = new w._date(w._n(d.year,0),w._n(d.mont,0),w._n(d.date,1),w._n(d.hour,0),w._n(d.mins,0),w._n(d.secs,0),0); + + if ( d.year < 100 && d.year !== -1 ) { date.setFullYear(d.year); } + + if ( ( d.mont > -1 && d.date > -1 ) || ( d.hour > -1 && d.mins > -1 && d.secs > -1 ) ) { return date; } + + if ( d.week !== false ) { + date.setDWeek(d.wtyp, d.week); + if ( d.date > -1 ) { date.setDate(d.date); } + } + if ( d.yday !== false ) { date.setD(1,0).setD(2,1).adj(2,(d.yday-1)); } + if ( d.wday !== false ) { date.adj(2,(d.wday - date.getDay())); } + } + return date; + }, + _customformat: { + 'default': function(oper, date) { return false; } + }, + _formatter: function(format, date) { + var w = this, + o = this.options, tmp, + dur = { + part: [0,0,0,0], tp: 0 + }; + + if ( o.mode === 'durationbox' || o.mode === 'durationflipbox' ) { + dur.tp = this.theDate.getEpoch() - this.initDate.getEpoch(); + dur.part[0] = parseInt( dur.tp / (60*60*24),10); dur.tp -=(dur.part[0]*60*60*24); // Days + dur.part[1] = parseInt( dur.tp / (60*60),10); dur.tp -= (dur.part[1]*60*60); // Hours + dur.part[2] = parseInt( dur.tp / (60),10); dur.tp -= (dur.part[2]*60); // Minutes + dur.part[3] = dur.tp; // Seconds + + if ( ! format.match(/%Dd/) ) { dur.part[1] += (dur.part[0]*24);} + if ( ! format.match(/%Dl/) ) { dur.part[2] += (dur.part[1]*60);} + if ( ! format.match(/%DM/) ) { dur.part[3] += (dur.part[2]*60);} + } + + format = format.replace(/%(D|X|0|-)*([1-9a-zA-Z])/g, function(match, pad, oper) { + if ( pad === 'X' ) { + if ( typeof w._customformat[o.mode] !== 'undefined' ) { return w._customformat[o.mode](oper, date, o); } + return match; + } + if ( pad === 'D' ) { + switch ( oper ) { + case 'd': return dur.part[0]; + case 'l': return w._zPad(dur.part[1]); + case 'M': return w._zPad(dur.part[2]); + case 'S': return w._zPad(dur.part[3]); + case 'A': return ((dur.part[0] > 1)?w.__('durationDays')[1]:w.__('durationDays')[0]); + default: return match; + } + } + switch ( oper ) { + case '%': // Literal % + return '%'; + case 'a': // Short Day + return w.__('daysOfWeekShort')[date.getDay()]; + case 'A': // Full Day of week + return w.__('daysOfWeek')[date.getDay()]; + case 'b': // Short month + return w.__('monthsOfYearShort')[date.getMonth()]; + case 'B': // Full month + return w.__('monthsOfYear')[date.getMonth()]; + case 'C': // Century + return date.getFullYear().toString().substr(0,2); + case 'd': // Day of month + return (( pad === '-' ) ? date.getDate() : w._zPad(date.getDate())); + case 'H': // Hour (01..23) + case 'k': + return (( pad === '-' ) ? date.getHours() : w._zPad(date.getHours())); + case 'I': // Hour (01..12) + case 'l': + return (( pad === '-' ) ? ((date.getHours() === 0 || date.getHours() === 12)?12:((date.getHours()<12)?date.getHours():(date.getHours()-12))) : w._zPad(((date.getHours() === 0 || date.getHours() === 12)?12:((date.getHours()<12)?date.getHours():date.getHours()-12)))); + case 'm': // Month + return (( pad === '-' ) ? date.getMonth()+1 : w._zPad(date.getMonth()+1)); + case 'M': // Minutes + return (( pad === '-' ) ? date.getMinutes() : w._zPad(date.getMinutes())); + case 'p': // AM/PM (ucase) + return ((date.getHours() < 12)?w.__('meridiem')[0].toUpperCase():w.__('meridiem')[1].toUpperCase()); + case 'P': // AM/PM (lcase) + return ((date.getHours() < 12)?w.__('meridiem')[0].toLowerCase():w.__('meridiem')[1].toLowerCase()); + case 's': // Unix Seconds + return date.getEpoch(); + case 'S': // Seconds + return (( pad === '-' ) ? date.getSeconds() : w._zPad(date.getSeconds())); + case 'u': // Day of week (1-7) + return (( pad === '-' ) ? date.getDay() + 1 : w._zPad(date.getDay() + 1)); + case 'w': // Day of week + return date.getDay(); + case 'y': // Year (2 digit) + return date.getFullYear().toString().substr(2,2); + case 'Y': // Year (4 digit) + return date.getFullYear(); + case 'E': // BE (Buddist Era, 4 Digit) + return date.getFullYear() + 543; + case 'V': + return (( pad === '-' ) ? date.getDWeek(4) : w._zPad(date.getDWeek(4))); + case 'U': + return (( pad === '-' ) ? date.getDWeek(0) : w._zPad(date.getDWeek(0))); + case 'W': + return (( pad === '-' ) ? date.getDWeek(1) : w._zPad(date.getDWeek(1))); + case 'o': // Ordinals + if ( typeof w._ord[o.useLang] !== 'undefined' ) { return w._ord[o.useLang](date.getDate()); } + return w._ord['default'](date.getDate()); + case 'j': + tmp = new Date(date.getFullYear(),0,1); + tmp = Math.ceil((date - tmp) / 86400000)+1; + return (( tmp < 100 ) ? (( tmp < 10 )? '00' : '0') : '' ) + String(tmp); + case 'G': + if ( date.getDWeek(4) === 1 && date.getMonth() > 0 ) { return date.getFullYear() + 1; } + if ( date.getDWeek(4) > 51 && date.getMonth() < 11 ) { return date.getFullYear() - 1; } + return date.getFullYear(); + case 'g': + if ( date.getDWeek(4) === 1 && date.getMonth() > 0 ) { return parseInt(date.getFullYear().toString().substr(2,2),10) + 1; } + if ( date.getDWeek(4) > 51 && date.getMonth() < 11 ) { return parseInt(date.getFullYear().toString().substr(2,2),10) - 1; } + return date.getFullYear().toString().substr(2,2); + default: + return match; + } + }); + + if ( w.__('useArabicIndic') === true ) { + format = w._dRep(format); + } + + return format; + }, + _btwn: function(value, low, high) { + return ( value > low && value < high ); + }, + _minStepFix: function() { + var tempMin = this.theDate.get(4), tmp, + w = this, + o = this.options; + + if ( o.minuteStep > 1 && tempMin % o.minuteStep > 0 ) { + if ( o.minuteStepRound < 0 ) { + tempMin = tempMin - (tempMin % o.minuteStep); + } else if ( o.minStepRound > 0 ) { + tempMin = tempMin + ( o.minuteStep - ( tempMin % o.minuteStep ) ); + } else { + if ( tempMin % o.minuteStep < o.minuteStep / 2 ) { + tempMin = tempMin - (tempMin % o.minuteStep); + } else { + tempMin = tempMin + ( o.minuteStep - ( tempMin % o.minuteStep ) ); + } + } + w.theDate.setMinutes(tempMin); + } + }, + _offset: function(mode, amount, update) { + // Compute a date/time offset. + // update = false to prevent controls refresh + var w = this, + o = this.options, + ok = false; + + mode = (mode || "").toLowerCase(); + + if ( typeof(update) === "undefined" ) { update = true; } + w.d.input.trigger('datebox', {'method':'offset', 'type':mode, 'amount':amount}); + + if ( mode !== 'a' && ( typeof o.rolloverMode[mode] === 'undefined' || o.rolloverMode[mode] === true )) { + ok = $.inArray(mode, ['y','m','d','h','i','s']); + } else { + switch(mode) { + case 'y': ok = 0; break; + case 'm': + if ( w._btwn(w.theDate.getMonth()+amount,-1,12) ) { ok = 1; } + break; + case 'd': + if ( w._btwn(w.theDate.getDate() + amount,0,(32 - w.theDate.copy([0],[0,0,32,13]).getDate() + 1) )) { ok = 2; } + break; + case 'h': + if ( w._btwn(w.theDate.getHours() + amount,-1,24) ) { ok = 3; } + break; + case 'i': + if ( w._btwn(w.theDate.getMinutes() + amount,-1,60) ) { ok = 4; } + break; + case 's': + if ( w._btwn(w.theDate.getSeconds() + amount,-1,60) ) { ok = 5; } + break; + case 'a': + w._offset('h',((amount>0)?1:-1)*12,false); + break; + } + } + if ( ok !== false ) { w.theDate.adj(ok,amount); } + if ( update === true ) { w.refresh(); } + if ( o.useImmediate ) { w.d.input.trigger('datebox', {'method':'doset'}); } + }, + _startOffset: function(date) { + var o = this.options; + + if ( o.startOffsetYears !== false ) { + date.adj(0, o.startOffsetYears); + } + if ( o.startOffsetMonths !== false ) { + date.adj(1, o.startOffsetMonths); + } + if ( o.startOffsetDays !== false ) { + date.adj(2, o.startOffsetDays); + } + return date; + }, + _create: function() { + // Create the widget, called automatically by widget system + $( document ).trigger( "dateboxcreate" ); + + var w = this, + o = $.extend(this.options, (typeof this.element.jqmData('options') !== 'undefined') ? this.element.jqmData('options') : this._getLongOptions(this.element) ), + thisTheme = ( o.theme === false && typeof($(this).jqmData('theme')) === 'undefined' ) ? + ( ( typeof(this.element.parentsUntil(':jqmData(theme)').parent().jqmData('theme')) === 'undefined' ) ? + o.themeDefault : this.element.parentsUntil(':jqmData(theme)').parent().jqmData('theme') ) + : o.theme, + trans = o.useAnimation ? o.transition : 'none', + d = o.useNewStyle === false ? { + input: this.element, + wrap: this.element.wrap('
          ').parent(), + mainWrap: $("
          ", { "class": 'ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden '+trans+' ui-body-'+thisTheme} ).css('zIndex', o.zindex), + intHTML: false + } : { + input: this.element, + wrap: this.element, + mainWrap: $("
          ", { "class": 'ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden '+trans+' ui-body-'+thisTheme} ).css('zIndex', o.zindex), + intHTML: false + }, + touch = ( typeof window.ontouchstart !== 'undefined' ), + drag = { + eStart : (touch ? 'touchstart' : 'mousedown')+'.datebox', + eMove : (touch ? 'touchmove' : 'mousemove')+'.datebox', + eEnd : (touch ? 'touchend' : 'mouseup')+'.datebox', + eEndA : (touch ? 'mouseup.datebox touchend.datebox touchcancel.datebox touchmove.datebox' : 'mouseup.datebox'), + move : false, + start : false, + end : false, + pos : false, + target : false, + delta : false, + tmp : false + }, + calc = { }, + ns = (typeof $.mobile.ns !== 'undefined')?$.mobile.ns:''; + + $.extend(w, {d: d, ns: ns, drag: drag, touch:touch}); + + if ( o.usePlaceholder !== false ) { + if ( o.usePlaceholder === true && w._grabLabel() !== false ) { w.d.input.attr('placeholder', w._grabLabel()); } + if ( typeof o.usePlaceholder === 'string' ) { w.d.input.attr('placeholder', o.usePlaceholder); } + } + + o.theme = thisTheme; + + w.clearFunc = false; + w.disabled = false; + w.runButton = false; + w._date = window.Date; + w._enhanceDate(); + w.baseID = w.d.input.attr('id'); + + w.initDate = new w._date(); + w.theDate = (o.defaultValue) ? w._makeDate(o.defaultValue) : ( (w.d.input.val() !== "") ? w._makeDate(w.d.input.val()) : new w._date() ); + w.initDone = false; + + if ( o.showInitialValue === true ) { + w.d.input.val(w._formatter(w.__fmt(), w.theDate)); + } + + if ( o.useButton === true && o.useInline === false && o.useNewStyle === false ) { + w.d.open = $(''+this.__('tooltip')+'') + .on(o.clickEvent, function(e) { + e.preventDefault(); + if ( !w.disabled ) { w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.parent().addClass('ui-focus'); w.d.input.parent().removeClass('ui-focus'); } + setTimeout( function() { $(e.target).closest('a').removeClass($.mobile.activeBtnClass); }, 300); + }).appendTo(w.d.wrap).buttonMarkup({icon: 'grid', iconpos: 'notext', corners:true, shadow:true}) + .css({'vertical-align': 'middle', 'display': 'inline-block'}); + } + + w.d.screen = $("
          ", {'class':'ui-datebox-screen ui-datebox-hidden'+((o.useModal)?' ui-datebox-screen-modal':'')}) + .css({'z-index': o.zindex-1}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.trigger('datebox', {'method':'close'}); + }); + + if ( o.enhanceInput === true && navigator.userAgent.match(/Android/i) ){ + w.inputType = 'number'; + } else { + w.inputType = 'text'; + } + + if ( o.hideInput ) { w.d.wrap.parent().hide(); } + + if ( o.mobVer < 140 ) { + $('label[for=\''+w.d.input.attr('id')+'\']').addClass('ui-input-text').css('verticalAlign', 'middle'); + } + + w.d.wrap.on(o.clickEvent, function() { + if ( !w.disabled && ( o.noButtonFocusMode || o.focusMode ) ) { + w.d.input.trigger('datebox', {'method': 'open'}); + w.d.wrap.addClass('ui-focus'); + w.d.input.removeClass('ui-focus'); + } + }); + + w.d.input + .removeClass('ui-corner-all ui-shadow-inset') + .bind(w.touch?'touchend':'click', function(e){ + if ( w.disabled === false && o.useNewStyle === true && o.useFocus === false ) { + if ( ((w.touch ? e.originalEvent.changedTouches[0].pageX : e.pageX) - e.target.offsetLeft) > (e.target.offsetWidth - 20) ) { + w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.parent().addClass('ui-focus'); w.d.input.removeClass('ui-focus'); + //setTimeout(function(){w.d.wrap.addClass('ui-focus');}, 200); + } + } + }) + .focus(function(){ + if ( w.disabled === false && o.useFocus === true ) { + w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.addClass('ui-focus'); w.d.input.removeClass('ui-focus'); + if ( o.useNewStyle === false ) { w.d.input.parent().removeClass('ui-focus'); w.d.wrap.parent().addClass('ui-focus'); } + } + if ( o.useNewStyle === false ) { w.d.input.removeClass('ui-focus'); } + }) + .blur(function(){ + w.d.wrap.removeClass('ui-focus'); + w.d.input.removeClass('ui-focus'); + }) + .change(function() { + w.theDate = w._makeDate(w.d.input.val()); + w.refresh(); + }) + .attr("readonly", o.lockInput) + .on('datebox', w._event); + + if ( o.useNewStyle === true ) { + w.d.input.addClass('ui-corner-all '+((o.useAltIcon===true)?'ui-icon-datebox-alt':'ui-icon-datebox')); + if ( o.overrideStyleClass !== false ) { w.d.input.addClass(o.overrideStyleClass); } + } else { + w.d.input.parent().css('border', 'none').removeClass('ui-shadow-inset'); + } + + w.d.wrap.parent().on(o.clickEvent, function() { + if ( !w.disabled && o.useFocus === true && o.useNewStyle === false ) { + w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.addClass('ui-focus'); w.d.input.removeClass('ui-focus'); + setTimeout(function(){ + w.d.wrap.removeClass('ui-focus'); + w.d.wrap.parent().addClass('ui-focus'); + }, 500); + } + }); + + // Check if mousewheel plugin is loaded + if ( typeof $.event.special.mousewheel !== 'undefined' ) { w.wheelExists = true; } + + // Disable when done if element attribute disabled is true. + if ( w.d.input.is(':disabled') ) { + w.disable(); + } + + if ( o.useInline === true || o.useInlineBlind ) { w.open(); } + + w.applyMinMax(false, false); + + //Throw dateboxinit event + $( document ).trigger( "dateboxaftercreate" ); + }, + applyMinMax: function(refresh, override) { + var w = this, + o = this.options, + calc = {}; + + if ( typeof refresh === 'undefined' ) { refresh = false; } + if ( typeof override === 'undefined' ) { override = true; } + + if ( ( override === true || o.minDays === false ) && typeof(w.d.input.attr('min')) !== 'undefined' ) { + calc.today = new w._date(); + calc.lod = 24 * 60 * 60 * 1000; + calc.todayc = new w._date(calc.today.getFullYear(), calc.today.getMonth(), calc.today.getDate(), 0,0,0,0); + calc.fromel = w.d.input.attr('min').split('-'); + calc.compdt = new w._date(calc.fromel[0],calc.fromel[1]-1,calc.fromel[2],0,0,0,0); + o.minDays = parseInt((((calc.compdt.getTime() - calc.todayc.getTime()) / calc.lod))*-1,10); + } + if ( ( override === true || o.maxDays === false ) && typeof(w.d.input.attr('max')) !== 'undefined' ) { + calc.today = new w._date(); + calc.lod = 24 * 60 * 60 * 1000; + calc.todayc = new w._date(calc.today.getFullYear(), calc.today.getMonth(), calc.today.getDate(), 0,0,0,0); + calc.fromel = w.d.input.attr('max').split('-'); + calc.compdt = new w._date(calc.fromel[0],calc.fromel[1]-1,calc.fromel[2],0,0,0,0); + o.maxDays = parseInt((((calc.compdt.getTime() - calc.todayc.getTime()) / calc.lod)),10); + } + + if ( refresh === true ) { w.refresh(); } + }, + _build: { + 'default': function () { + this.d.headerText = "Error"; + this.d.intHTML = $("

          There is no mode by that name loaded / mode not given

          "); + } + }, + _applyCoords: function(e) { + var w = e.widget, + o = e.widget.options, + fixd = { + h: $.mobile.activePage.find('.ui-header').jqmData('position'), + f: $.mobile.activePage.find('.ui-footer').jqmData('position'), + fh: $.mobile.activePage.find('.ui-footer').outerHeight(), + hh: $.mobile.activePage.find('.ui-header').outerHeight() + }, + iput = { + x: w.d.wrap.offset().left + (w.d.wrap.outerWidth() / 2), + y: w.d.wrap.offset().top + (w.d.wrap.outerHeight() / 2) + }, + size = { + w: w.d.mainWrap.outerWidth(), + h: w.d.mainWrap.outerHeight() + }, + doc = { + t: $(window).scrollTop(), + h: $(window).height(), + w: $.mobile.activePage.width(), + ah: $(document).height() + }, + pos = { + y: (o.centerVert) ? doc.t + ((doc.h / 2) - (size.h / 2)) : iput.y - ( size.h / 2 ), + x: (doc.w < 400 || o.centerHoriz ) ? (doc.w / 2) - (size.w /2) : iput.x - (size.w / 2) + }; + + if ( o.centerVert === false ) { + if ( o.hideFixedToolbars === true && ( typeof fixd.f !== 'undefined' || typeof fixd.h !== 'undefined' )) { + $.mobile.activePage.find(":jqmData(position='fixed')").fixedtoolbar('hide'); + fixd.f = undefined; + fixd.h = undefined; + } + + if ( typeof fixd.f !== 'undefined' ) { + if ( ( pos.y + size.h ) > ( doc.h - fixd.fh - 2 ) ) { + pos.y = doc.h - fixd.fh - 2 - size.h; + } + } else { + if ( ( pos.y + size.h ) > ( doc.ah - fixd.fh - 2 ) ) { + pos.y = doc.ah - fixd.fh - 2 - size.h; + } + if ( ( doc.h + doc.t ) < ( size.h + pos.y + 2 ) ) { + pos.y = doc.h + doc.t - size.h - 2; + } + } + + if ( typeof fixd.h !== 'undefined' ) { + if ( ( doc.t + fixd.hh + 2 ) > pos.y ) { + pos.y = doc.t + fixd.hh + 2; + } + } else { + if ( fixd.hh + 2 > pos.y ) { + pos.y = fixd.hh + 2; + } + if ( pos.y < doc.t + 2 ) { + pos.y = doc.t + 2; + } + } + } + w.d.mainWrap.css({'position': 'absolute', 'top': pos.y, 'left': pos.x}); + }, + _drag: { + 'default': function () { return false; } + }, + open: function () { + var w = this, + o = this.options, + popopts = {}, + basepop = {'history':false}, + qns = 'data-'+this.ns, + trans = o.useAnimation ? o.transition : 'none'; + + if ( o.useFocus === true && w.fastReopen === true ) { w.d.input.blur(); return false; } + if ( w.clearFunc !== false ) { + clearTimeout(w.clearFunc); w.clearFunc = false; + } + + // Call the open callback if provided. Additionally, if this + // returns false then the open/update will stop. + if ( o.openCallback !== false ) { + if ( ! $.isFunction(o.openCallback) ) { + if ( typeof window[o.openCallback] !== 'undefined' ) { + o.openCallback = window[o.openCallback]; + } else { + o.openCallback = new Function(o.openCallback); + } + } + if ( o.openCallback.apply(w, $.merge([w.theDate],o.openCallbackArgs)) === false ) { return false; } + } + + w.theDate = w._makeDate(w.d.input.val()); + if ( w.d.input.val() === "" ) { w._startOffset(w.theDate); } + w.d.input.blur(); + + if ( typeof w._build[o.mode] === 'undefined' ) { + w._build['default'].apply(w,[]); + } else { + w._build[o.mode].apply(w,[]); + } + if ( typeof w._drag[o.mode] !== 'undefined' ) { + w._drag[o.mode].apply(w, []); + } + w.d.input.trigger('datebox', {'method':'refresh'}); + if ( w.__('useArabicIndic') === true ) { w._doIndic(); } + + if ( ( o.useInline === true || o.useInlineBlind === true ) && w.initDone === false ) { + w.d.mainWrap.append(w.d.intHTML); + w.d.input.parent().parent().append(w.d.mainWrap); + w.d.mainWrap.removeClass('ui-datebox-hidden'); + if ( o.useInline === true ) { + w.d.mainWrap.addClass('ui-datebox-inline'); + } else { + w.d.mainWrap.addClass('ui-datebox-inlineblind'); + w.d.mainWrap.hide(); + } + w.initDone = false; + w.d.input.trigger('datebox',{'method':'postrefresh'}); + } + + if ( o.useImmediate ) { w.d.input.trigger('datebox', {'method':'doset'}); } + if ( o.useInline ) { return true; } + if ( o.useInlineBlind ) { + if ( w.initDone ) { w.d.mainWrap.slideDown(); } + else { w.initDone = true; } + return true; + } + if ( w.d.intHTML.is(':visible') ) { return false; } // Ignore if already open + + if ( o.enablePopup === true ) { + w.d.dialogPage = false; + w.d.mainWrap.empty(); + if ( o.useHeader === true ) { + w.d.headHTML = $('
          '); + $("Close").appendTo(w.d.headHTML) + .buttonMarkup({ theme : o.themeHeader, icon : 'delete', iconpos: 'notext', corners: true, shadow : true }) + .on(o.clickEventAlt, function(e) { e.preventDefault(); w.d.input.trigger('datebox', {'method':'close'}); }); + $('

          '+w.d.headerText+'

          ').appendTo(w.d.headHTML); + w.d.mainWrap.append(w.d.headHTML); + } + w.d.mainWrap.append(w.d.intHTML).css('zIndex', o.zindex); + w.d.input.trigger('datebox',{'method':'postrefresh'}); + + if ( o.useAnimation === true ) { + popopts.transition = o.transition; + } else { + popopts.transition = "none"; + } + + if ( o.popupForceX !== false && o.popupForceY !== false ) { + popopts.x = o.popupForceX; + popopts.y = o.popupForceY; + } + + if ( o.popupPosition !== false ) { + popopts.positionTo = o.popupPosition; + } else { + if ( typeof w.baseID !== undefined ) { + popopts.positionTo = '#' + w.baseID; + } else { + popopts.positionTo = 'window'; + } + } + + if ( o.useModal === true ) { basepop.overlayTheme = "a"; } + + w.d.mainWrap.removeClass('ui-datebox-hidden').popup(basepop).popup("open", popopts); + w.refresh(); + } else { + if ( o.dialogForce || ( o.dialogEnable && window.width() < 400 ) ) { + w.d.dialogPage = $("
          " + + "
          " + + "

          "+w.d.headerText+"

          ") + .appendTo( $.mobile.pageContainer ) + .page().css('minHeight', '0px').addClass(trans); + w.d.dialogPage.find('.ui-header').find('a').off('click vclick').on(o.clickEventAlt, function(e) { e.preventDefault(); w.d.input.trigger('datebox', {'method':'close'}); }); + w.d.mainWrap.append(w.d.intHTML).css({'marginLeft':'auto', 'marginRight':'auto'}).removeClass('ui-datebox-hidden'); + w.d.dialogPage.find('.ui-content').append(w.d.mainWrap); + w.d.input.trigger('datebox',{'method':'postrefresh'}); + $.mobile.activePage.off( "pagehide.remove" ); + $.mobile.changePage(w.d.dialogPage, {'transition': trans}); + } else { + w.d.dialogPage = false; + w.d.mainWrap.empty(); + if ( o.useHeader === true ) { + w.d.headHTML = $('
          '); + $("Close").appendTo(w.d.headHTML) + .buttonMarkup({ theme : o.themeHeader, icon : 'delete', iconpos: 'notext', corners: true, shadow : true }) + .on(o.clickEventAlt, function(e) { e.preventDefault(); w.d.input.trigger('datebox', {'method':'close'}); }); + $('

          '+w.d.headerText+'

          ').appendTo(w.d.headHTML); + w.d.mainWrap.append(w.d.headHTML); + } + w.d.mainWrap.append(w.d.intHTML).css('zIndex', o.zindex); + w.d.mainWrap.appendTo($.mobile.activePage); + w.d.screen.appendTo($.mobile.activePage); + w.d.input.trigger('datebox',{'method':'postrefresh'}); + w._applyCoords({widget:w}); + + if ( o.useModal === true ) { + if(o.useAnimation) { + w.d.screen.fadeIn('slow'); + } else { + w.d.screen.show(); + } + } else { + setTimeout(function () { w.d.screen.removeClass('ui-datebox-hidden');}, 500); + } + + w.d.mainWrap.addClass('ui-overlay-shadow in').removeClass('ui-datebox-hidden'); + + $(document).on('orientationchange.datebox', {widget:w}, function(e) { w._applyCoords(e.data); }); + if ( o.resizeListener === true ) { + $(window).on('resize.datebox', {widget:w}, function (e) { w._applyCoords(e.data); }); + } + } + } + }, + close: function() { + var w = this, + o = this.options; + + if ( o.useInlineBlind === true ) { w.d.mainWrap.slideUp(); return true;} + if ( o.useInline === true || w.d.intHTML === false ) { return true; } + + if ( w.d.dialogPage !== false ) { + $(w.d.dialogPage).dialog('close'); + + if ( ! $.mobile.activePage.jqmData('mobile-page').options.domCache ) { + $.mobile.activePage.on('pagehide.remove', function () { $(this).remove(); }); + } + + w.d.intHTML.detach().empty(); + w.d.mainWrap.detach().empty(); + w.d.wrap.removeClass('ui-focus'); + w.clearFunc = setTimeout(function () { w.d.dialogPage.empty().remove(); w.clearFunc = false; }, 1500); + } else { + if ( o.enablePopup === true ) { + w.d.mainWrap.popup('close'); + w.d.wrap.removeClass('ui-focus'); + } else { + if ( o.useModal ) { + if(o.useAnimation) { + w.d.screen.fadeOut('slow'); + } else { + w.d.screen.hide(); + } + } else { + w.d.screen.addClass('ui-datebox-hidden'); + } + w.d.screen.detach(); + w.d.mainWrap.addClass('ui-datebox-hidden').removeAttr('style').removeClass('in ui-overlay-shadow').empty().detach(); + w.d.intHTML.detach(); + w.d.wrap.removeClass('ui-focus'); + + $(document).off('orientationchange.datebox'); + if ( o.resizeListener === true ) { + $(window).off('resize.datebox'); + } + } + } + w.d.wrap.parent().removeClass('ui-focus'); + + $(document).off(w.drag.eMove); + $(document).off(w.drag.eEnd); + $(document).off(w.drag.eEndA); + + if ( o.useFocus ) { + w.fastReopen = true; + setTimeout(function(t) { return function () { t.fastReopen = false; };}(w), 300); + } + + if ( o.closeCallback !== false ) { + if ( ! $.isFunction(o.closeCallback) ) { + if ( typeof window[o.closeCallback] !== 'undefined' ) { + o.closeCallback = window[o.closeCallback]; + } else { + o.closeCallback = new Function(o.closeCallback); + } + } + o.closeCallback.apply(w, $.merge([w.theDate], o.closeCallbackArgs)); + } + }, + refresh: function() { + if ( typeof this._build[this.options.mode] === 'undefined' ) { + this._build['default'].apply(this,[]); + } else { + this._build[this.options.mode].apply(this,[]); + } + if ( this.__('useArabicIndic') === true ) { this._doIndic(); } + this.d.mainWrap.append(this.d.intHTML); + this.d.input.trigger('datebox',{'method':'postrefresh'}); + }, + _check: function() { + var w = this, + td = null, + o = this.options; + + w.dateOK = true; + + if ( o.afterToday !== false ) { + td = new w._date(); + if ( w.theDate < td ) { w.theDate = td; } + } + if ( o.beforeToday !== false ) { + td = new w._date(); + if ( w.theDate > td ) { w.theDate = td; } + } + if ( o.maxDays !== false ) { + td = new w._date(); + td.adj(2, o.maxDays); + if ( w.theDate > td ) { w.theDate = td; } + } + if ( o.minDays !== false ) { + td = new w._date(); + td.adj(2, -1*o.minDays); + if ( w.theDate < td ) { w.theDate = td; } + } + if ( o.minHour !== false ) { + if ( w.theDate.getHours() < o.minHour ) { + w.theDate.setHours(o.minHour); + } + } + if ( o.maxHour !== false ) { + if ( w.theDate.getHours() > o.maxHour ) { + w.theDate.setHours(o.maxHour); + } + } + if ( o.maxYear !== false ) { + td = new w._date(o.maxYear, 0, 1); + td.adj(2, -1); + if ( w.theDate > td ) { w.theDate = td; } + } + if ( o.minYear !== false ) { + td = new w._date(o.minYear, 0, 1); + if ( w.theDate < td ) { w.theDate = td; } + } + + if ( $.inArray(o.mode, ['timebox','durationbox','durationflipbox','timeflipbox']) > -1 ) { + if ( o.mode === 'timeflipbox' && o.validHours !== false ) { + if ( $.inArray(w.theDate.getHours(), o.validHours) < 0 ) { w.dateOK = false; } + } + } else { + if ( o.blackDatesRec !== false ) { + for ( i=0; i -1 ) { w.dateOK = false; } + } + if ( o.blackDays !== false ) { + if ( $.inArray(w.theDate.getDay(), o.blackDays) > -1 ) { w.dateOK = false; } + } + } + }, + _grabLabel: function() { + var w = this, + o = this.options; + + if ( typeof o.overrideDialogLabel === 'undefined' ) { + if ( typeof w.d.input.attr('placeholder') !== 'undefined' ) { return w.d.input.attr('placeholder'); } + if ( typeof w.d.input.attr('title') !== 'undefined' ) { return w.d.input.attr('title'); } + if ( w.d.wrap.parent().find('label[for=\''+w.d.input.attr('id')+'\']').text() !== '' ) { + return w.d.wrap.parent().find('label[for=\''+w.d.input.attr('id')+'\']').text(); + } + return false; + } + return o.overrideDialogLabel; + }, + _makeEl: function(source, parts) { + var part = false, + retty = false; + + retty = source.clone(); + + if ( typeof parts.attr !== 'undefined' ) { + for ( part in parts.attr ) { + if ( parts.attr.hasOwnProperty(part) ) { + retty.jqmData(part, parts.attr[part]); + } + } + } + return retty; + }, + _getLongOptions: function(element) { + var key, retty = {}, prefix, temp; + + if ( $.mobile.ns === "" ) { + prefix = "datebox"; + } else { + prefix = $.mobile.ns.substr(0, $.mobile.ns.length - 1) + 'Datebox'; + } + + for ( key in element.data() ) { + if ( key.substr(0, prefix.length) === prefix && key.length > prefix.length ) { + temp = key.substr(prefix.length); + temp = temp.charAt(0).toLowerCase() + temp.slice(1); + retty[temp] = element.data(key); + } + } + return retty; + }, + disable: function(){ + // Disable the element + this.d.input.attr("disabled",true); + this.d.wrap.addClass("ui-disabled").blur(); + this.disabled = true; + this.d.input.trigger('datebox', {'method':'disable'}); + }, + enable: function(){ + // Enable the element + this.d.input.attr("disabled", false); + this.d.wrap.removeClass("ui-disabled"); + this.disabled = false; + this.d.input.trigger('datebox', {'method':'enable'}); + }, + _setOption: function() { + $.Widget.prototype._setOption.apply( this, arguments ); + this.refresh(); + }, + getTheDate: function() { + return this.theDate; + }, + getLastDur: function() { + return this.lastDuration; + }, + setTheDate: function(newDate) { + this.theDate = newDate; + this.refresh(); + }, + callFormat: function(format, date) { + return this._formatter(format, date); + } + }); + + // Degrade date inputs to text inputs, suppress standard UI functions. + $( document ).on( "pagebeforecreate", function( e ) { + $( ":jqmData(role='datebox')", e.target ).each(function() { + $(this).prop('type', 'text'); + }); + }); + // Automatically bind to data-role='datebox' items. + $( document ).on( "pagecreate create", function( e ){ + $( document ).trigger( "dateboxbeforecreate" ); + $( ":jqmData(role='datebox')", e.target ).each(function() { + var defed = typeof ($(this).data(parseInt($.mobile.version.replace(/\./g,''),10) > 111 ? 'mobile-datebox' : 'datebox')); + if ( defed === "undefined" ) { + $(this).datebox(); + } + }); + }); +})( jQuery ); +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +/* FLIPBOX Mode */ + +(function($) { + $.extend( $.mobile.datebox.prototype.options, { + themeDateHigh: 'b', + themeDatePick: 'b', + themeDate: 'a', + useSetButton: true, + validHours: false, + flen: {'y': 15, 'm':12, 'd':15, 'h':12, 'i':15, 'a':3} + }); + $.extend( $.mobile.datebox.prototype, { + '_fbox_pos': function () { + var w = this, + ech = null, + top = null, + par = this.d.intHTML.find('.ui-datebox-flipcontent').innerHeight(), + tot = null; + + w.d.intHTML.find('.ui-datebox-flipcenter').each(function() { + ech = $(this); + top = ech.innerHeight(); + ech.css('top', ((par/2)-(top/2)+4)*-1); + }); + w.d.intHTML.find('ul').each(function () { + ech = $(this); + par = ech.parent().innerHeight(); + top = ech.find('li').first(); + tot = ech.find('li').size() * top.outerHeight(); + top.css('marginTop', ((tot/2)-(par/2)+(top.outerHeight()/2))*-1); + }); + } + }); + $.extend( $.mobile.datebox.prototype._build, { + 'timeflipbox': function() { + this._build.flipbox.apply(this); + }, + 'flipbox': function () { + var w = this, + o = this.options, i, y, hRow, tmp, testDate, + iDate = (w.d.input.val() === "") ? w._startOffset(w._makeDate(w.d.input.val())) : w._makeDate(w.d.input.val()), + uid = 'ui-datebox-', + flipBase = $("
            "), + ctrl = $("
            ", {"class":uid+'flipcontent'}); + + if ( typeof w.d.intHTML !== 'boolean' ) { + w.d.intHTML.empty(); + } + + w.d.input.on('datebox', function (e,p) { + if ( p.method === 'postrefresh' ) { + w._fbox_pos(); + } + }); + + w.d.headerText = ((w._grabLabel() !== false)?w._grabLabel():((o.mode==='flipbox')?w.__('titleDateDialogLabel'):w.__('titleTimeDialogLabel'))); + w.d.intHTML = $('') + + w.fldOrder = ((o.mode==='flipbox')?w.__('dateFieldOrder'):w.__('timeFieldOrder')); + w._check(); + w._minStepFix(); + + if ( o.mode === 'flipbox' ) { $('

            '+w._formatter(w.__('headerFormat'), w.theDate)+'

            ').appendTo(w.d.intHTML); } + + w.d.intHTML.append(ctrl); + + for ( y=0; y', {'class':'ui-body-'+tmp}) + .html(''+(w.theDate.get(0)+i)+'').appendTo(hRow.find('ul')); + } + hRow.appendTo(ctrl); + break; + case 'm': + hRow = w._makeEl(flipBase, {'attr': {'field':'m','amount':1} }); + for ( i=o.flen.m*-1; i<(o.flen.m+1); i++ ) { + testDate = w.theDate.copy([0],[0,0,1]); + testDate.adj(1,i); + tmp = (i!==0)?((iDate.get(1) === testDate.get(1) && iDate.get(0) === testDate.get(0))?o.themeDateHigh:o.themeDate):o.themeDatePick; + $("
          • ", { 'class' : 'ui-body-'+tmp}) + .html(""+w.__('monthsOfYearShort')[testDate.getMonth()]+"").appendTo(hRow.find('ul')); + } + hRow.appendTo(ctrl); + break; + case 'd': + hRow = w._makeEl(flipBase, {'attr': {'field':'d','amount':1} }); + for ( i=o.flen.d*-1; i<(o.flen.d+1); i++ ) { + testDate = w.theDate.copy(); + testDate.adj(2,i); + tmp = (i!==0)?((iDate.comp() === testDate.comp())?o.themeDateHigh:o.themeDate):o.themeDatePick; + if ( ( o.blackDates !== false && $.inArray(testDate.iso(), o.blackDates) > -1 ) || + ( o.blackDays !== false && $.inArray(testDate.getDay(), o.blackDays) > -1 ) ) { + tmp += ' '+uid+'griddate-disable'; + } + $("
          • ", { 'class' : 'ui-body-'+tmp}) + .html(""+testDate.getDate()+"").appendTo(hRow.find('ul')); + } + hRow.appendTo(ctrl); + break; + case 'h': + hRow = w._makeEl(flipBase, {'attr': {'field':'h','amount':1} }); + for ( i=o.flen.h*-1; i<(o.flen.h+1); i++ ) { + testDate = w.theDate.copy(); + testDate.adj(3,i); + tmp = (i!==0)?o.themeDate:o.themeDatePick; + if ( o.validHours !== false && $.inArray(testDate.get(3), o.validHours) < 0 ) { + tmp += ' '+uid+'griddate-disable'; + } + $("
          • ", { 'class' : 'ui-body-'+tmp}) + .html(""+((w.__('timeFormat')===12) ? (( testDate.get(3) === 0 ) ? '12' : (( testDate.get(3) < 13 ) ? testDate.get(3) : (testDate.get(3)-12))) : testDate.get(3))+"").appendTo(hRow.find('ul')); + } + hRow.appendTo(ctrl); + break; + case 'i': + hRow = w._makeEl(flipBase, {'attr': {'field':'i','amount':o.minuteStep} }); + for ( i=o.flen.i*-1; i<(o.flen.i+1); i++ ) { + testDate = w.theDate.copy(); + testDate.adj(4,(i*o.minuteStep)); + tmp = (i!==0)?o.themeDate:o.themeDatePick; + $("
          • ", { 'class' : 'ui-body-'+tmp}) + .html(""+w._zPad(testDate.get(4))+"").appendTo(hRow.find('ul')); + } + hRow.appendTo(ctrl); + break; + case 'a': + if ( w.__('timeFormat') !== 12 ) { break; } + hRow = w._makeEl(flipBase, {'attr': {'field':'a','amount':1} }); + testDate = $("
          • "); + + for ( i=0; i 11) ? [o.themeDate,o.themeDatePick] : [o.themeDatePick,o.themeDate]; + + $("
          • ", { 'class' : 'ui-body-'+tmp[0]}).html(''+w.__('meridiem')[0]+'').appendTo(hRow.find('ul')); + $("
          • ", { 'class' : 'ui-body-'+tmp[1]}).html(''+w.__('meridiem')[1]+'').appendTo(hRow.find('ul')); + + if ( w.theDate.get(3) > 11 ) { testDate.clone().appendTo(hRow.find('ul')); } + for ( i=0; i", {"class":uid+'flipcenter ui-overlay-shadow'}).css('pointerEvents', 'none').appendTo(w.d.intHTML); + + if ( o.useSetButton || o.useClearButton ) { + y = $('
            ', {'class':uid+'controls'}); + + if ( o.useSetButton ) { + $(''+((o.mode==='flipbox')?w.__('setDateButtonLabel'):w.__('setTimeButtonLabel'))+'') + .appendTo(y).buttonMarkup({theme: o.theme, icon: 'check', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + if ( w.dateOK === true ) { + w.d.input.trigger('datebox', {'method':'set', 'value':w._formatter(w.__fmt(),w.theDate), 'date':w.theDate}); + w.d.input.trigger('datebox', {'method':'close'}); + } + }); + } + if ( o.useClearButton ) { + $(''+w.__('clearButton')+'') + .appendTo(y).buttonMarkup({theme: o.theme, icon: 'delete', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.val(''); + w.d.input.trigger('datebox',{'method':'clear'}); + w.d.input.trigger('datebox',{'method':'close'}); + }); + } + if ( o.useCollapsedBut ) { + y.addClass('ui-datebox-collapse'); + } + y.appendTo(w.d.intHTML); + } + + if ( w.wheelExists ) { // Mousewheel operation, if plugin is loaded + w.d.intHTML.on('mousewheel', '.ui-overlay-shadow', function(e,d) { + e.preventDefault(); + w._offset($(this).jqmData('field'), ((d<0)?-1:1)*$(this).jqmData('amount')); + }); + } + + w.d.intHTML.on(w.drag.eStart, 'ul', function(e,f) { + if ( !w.drag.move ) { + if ( typeof f !== "undefined" ) { e = f; } + w.drag.move = true; + w.drag.target = $(this).find('li').first(); + w.drag.pos = parseInt(w.drag.target.css('marginTop').replace(/px/i, ''),10); + w.drag.start = w.touch ? e.originalEvent.changedTouches[0].pageY : e.pageY; + w.drag.end = false; + e.stopPropagation(); + e.preventDefault(); + } + }); + + w.d.intHTML.on(w.drag.eStart, '.'+uid+'flipcenter', function(e) { // Used only on old browsers and IE. + if ( !w.drag.move ) { + w.drag.target = w.touch ? e.originalEvent.changedTouches[0].pageX - $(e.currentTarget).offset().left : e.pageX - $(e.currentTarget).offset().left; + w.drag.tmp = w.d.intHTML.find('.'+uid+'flipcenter').innerWidth() / (( $.inArray('a', w.fldOrder) > -1 && w.__('timeFormat') !== 12 )?w.fldOrder.length-1:w.fldOrder.length); + $(w.d.intHTML.find('ul').get(parseInt(w.drag.target / w.drag.tmp,10))).trigger(w.drag.eStart,e); + } + }); + } + }); + $.extend( $.mobile.datebox.prototype._drag, { + 'timeflipbox': function() { + this._drag.flipbox.apply(this); + }, + 'flipbox': function() { + var w = this, + o = this.options, + g = this.drag; + + $(document).on(g.eMove, function(e) { + if ( g.move && ( o.mode === 'flipbox' || o.mode === 'timeflipbox' )) { + g.end = w.touch ? e.originalEvent.changedTouches[0].pageY : e.pageY; + g.target.css('marginTop', (g.pos + g.end - g.start) + 'px'); + e.preventDefault(); + e.stopPropagation(); + return false; + } + }); + + $(document).on(g.eEnd, function(e) { + if ( g.move && (o.mode === 'flipbox' || o.mode === 'timeflipbox' )) { + g.move = false; + if ( g.end !== false ) { + e.preventDefault(); + e.stopPropagation(); + g.tmp = g.target.parent().parent(); + w._offset(g.tmp.jqmData('field'), (parseInt((g.start - g.end) / g.target.innerHeight(),10) * g.tmp.jqmData('amount'))); + } + g.start = false; + g.end = false; + } + }); + } + }); +})( jQuery ); diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.flipbox.min.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.flipbox.min.js new file mode 100644 index 000000000..80ff2c0f1 --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.flipbox.min.js @@ -0,0 +1,7 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +(function(a){a.widget("mobile.datebox",a.mobile.widget,{options:{version:"2-1.4.0-2013070300",mobVer:parseInt(a.mobile.version.replace(/\./g,"")),theme:false,themeDefault:"a",themeHeader:"a",mode:false,centerHoriz:false,centerVert:false,transition:"pop",useAnimation:true,hideInput:false,hideFixedToolbars:false,lockInput:true,enhanceInput:true,zindex:"500",clickEvent:"vclick",clickEventAlt:"click",resizeListener:true,defaultValue:false,showInitialValue:false,dialogEnable:false,dialogForce:false,enablePopup:false,popupPosition:false,popupForceX:false,popupForceY:false,useModal:false,useInline:false,useInlineBlind:false,useHeader:true,useImmediate:false,useNewStyle:false,useAltIcon:false,overrideStyleClass:false,useButton:true,useFocus:false,useClearButton:false,useCollapsedBut:false,usePlaceholder:false,openCallback:false,openCallbackArgs:[],closeCallback:false,closeCallbackArgs:[],startOffsetYears:false,startOffsetMonths:false,startOffsetDays:false,afterToday:false,beforeToday:false,notToday:false,maxDays:false,minDays:false,maxYear:false,minYear:false,blackDates:false,blackDatesRec:false,blackDays:false,minHour:false,maxHour:false,minuteStep:1,minuteStepRound:0,rolloverMode:{m:true,d:true,h:true,i:true,s:true},useLang:"default",lang:{"default":{setDateButtonLabel:"Set Date",setTimeButtonLabel:"Set Time",setDurationButtonLabel:"Set Duration",calTodayButtonLabel:"Jump to Today",titleDateDialogLabel:"Set Date",titleTimeDialogLabel:"Set Time",daysOfWeek:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],daysOfWeekShort:["Su","Mo","Tu","We","Th","Fr","Sa"],monthsOfYear:["January","February","March","April","May","June","July","August","September","October","November","December"],monthsOfYearShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],durationLabel:["Days","Hours","Minutes","Seconds"],durationDays:["Day","Days"],timeFormat:24,headerFormat:"%A, %B %-d, %Y",tooltip:"Open Date Picker",nextMonth:"Next Month",prevMonth:"Previous Month",dateFieldOrder:["m","d","y"],timeFieldOrder:["h","i","a"],slideFieldOrder:["y","m","d"],dateFormat:"%Y-%m-%d",useArabicIndic:false,isRTL:false,calStartDay:0,clearButton:"Clear",durationOrder:["d","h","i","s"],meridiem:["AM","PM"],timeOutput:"%k:%M",durationFormat:"%Dd %DA, %Dl:%DM:%DS",calDateListLabel:"Other Dates",calHeaderFormat:"%B %Y"}}},_enhanceDate:function(){a.extend(this._date.prototype,{copy:function(c,b){if(typeof c==="undefined"){c=[0,0,0,0,0,0,0]}if(typeof b==="undefined"){b=[0,0,0,0,0,0,0]}while(c.length<7){c.push(0)}while(b.length<7){b.push(0)}return new Date(((b[0]>0)?b[0]:this.getFullYear()+c[0]),((b[1]>0)?b[1]:this.getMonth()+c[1]),((b[2]>0)?b[2]:this.getDate()+c[2]),((b[3]>0)?b[3]:this.getHours()+c[3]),((b[4]>0)?b[4]:this.getMinutes()+c[4]),((b[5]>0)?b[5]:this.getSeconds()+c[5]),((b[6]>0)?b[5]:this.getMilliseconds()+c[6]))},adj:function(c,b){if(typeof b!=="number"){throw new Error("Adjustment value not specified")}if(typeof c!=="number"){throw new Error("Adjustment type not specified")}switch(c){case 0:this.setFullYear(this.getFullYear()+b);break;case 1:this.setMonth(this.getMonth()+b);break;case 2:this.setDate(this.getDate()+b);break;case 3:this.setHours(this.getHours()+b);break;case 4:this.setMinutes(this.getMinutes()+b);break;case 5:this.setSeconds(this.getSeconds()+b);break;case 6:this.setMilliseconds(this.getMilliseconds()+b);break}return this},setD:function(c,b){switch(c){case 0:this.setFullYear(b);break;case 1:this.setMonth(b);break;case 2:this.setDate(b);break;case 3:this.setHours(b);break;case 4:this.setMinutes(b);break;case 5:this.setSeconds(b);break;case 6:this.setMilliseconds(b);break}return this},get:function(b){switch(b){case 0:return this.getFullYear();case 1:return this.getMonth();case 2:return this.getDate();case 3:return this.getHours();case 4:return this.getMinutes();case 5:return this.getSeconds()}return false},iso:function(){return String(this.getFullYear())+"-"+((this.getMonth()<9)?"0":"")+String(this.getMonth()+1)+"-"+((this.getDate()<10)?"0":"")+String(this.getDate())},comp:function(){return parseInt(this.iso().replace(/-/g,""),10)},getEpoch:function(){return(this.getTime()-this.getMilliseconds())/1000},getArray:function(){return[this.getFullYear(),this.getMonth(),this.getDate(),this.getHours(),this.getMinutes(),this.getSeconds()]},setFirstDay:function(b){this.setD(2,1).adj(2,(b-this.getDay()));if(this.get(2)>10){this.adj(2,7)}return this},setDWeek:function(c,b){if(c===4){return this.setD(1,0).setD(2,1).setFirstDay(4).adj(2,-3).adj(2,(b-1)*7)}return this.setD(1,0).setD(2,1).setFirstDay(c).adj(2,(b-1)*7)},getDWeek:function(c){var d,b;switch(c){case 0:d=this.copy([0,-1*this.getMonth()]).setFirstDay(0);return Math.floor((this.getTime()-(d.getTime()+((this.getTimezoneOffset()-d.getTimezoneOffset())*60000)))/604800000)+1;case 1:d=this.copy([0,-1*this.getMonth()]).setFirstDay(1);return Math.floor((this.getTime()-(d.getTime()+((this.getTimezoneOffset()-d.getTimezoneOffset())*60000)))/604800000)+1;case 4:if(this.getMonth()===11&&this.getDate()>28){return 1}d=this.copy([0,-1*this.getMonth()],true).setFirstDay(4).adj(2,-3);b=Math.floor((this.getTime()-(d.getTime()+((this.getTimezoneOffset()-d.getTimezoneOffset())*60000)))/604800000)+1;if(b<1){d=this.copy([-1,-1*this.getMonth()]).setFirstDay(4).adj(2,-3);return Math.floor((this.getTime()-d.getTime())/604800000)+1}return b;default:return 0}}})},_event:function(d,c){var b=a(this).data(parseInt(a.mobile.version.replace(/\./g,""),10)>110?"mobile-datebox":"datebox");if(!d.isPropagationStopped()){switch(c.method){case"close":b.close();break;case"open":b.open();break;case"set":a(this).val(c.value);a(this).trigger("change");break;case"doset":if(a.isFunction(b["_"+b.options.mode+"DoSet"])){b["_"+b.options.mode+"DoSet"].apply(b,[])}else{a(this).trigger("datebox",{method:"set",value:b._formatter(b.__fmt(),b.theDate),date:b.theDate})}break;case"dooffset":if(c.type){b._offset(c.type,c.amount,true)}break;case"dorefresh":b.refresh();break;case"doreset":b.hardreset();break;case"doclear":a(this).val("").trigger("change");break;case"clear":a(this).trigger("change")}}},_hoover:function(b){a(b).toggleClass("ui-btn-up-"+a(b).jqmData("theme")+" ui-btn-down-"+a(b).jqmData("theme"))},_ord:{"default":function(c){var b=c%10;if(c>9&&c<21){return"th"}if(b>3){return"th"}return["th","st","nd","rd"][b]}},__:function(d){var c=this.options,b="override"+d.charAt(0).toUpperCase()+d.slice(1);if(typeof c[b]!=="undefined"){return c[b]}if(typeof c.lang[c.useLang][d]!=="undefined"){return c.lang[c.useLang][d]}if(typeof c[c.mode+"lang"]!=="undefined"&&typeof c[c.mode+"lang"][d]!=="undefined"){return c[c.mode+"lang"][d]}return c.lang["default"][d]},__fmt:function(){var b=this,c=this.options;switch(c.mode){case"timebox":case"timeflipbox":return b.__("timeOutput");case"durationbox":case"durationflipbox":return b.__("durationFormat");default:return b.__("dateFormat")}},_zPad:function(b){return((b<10)?"0"+String(b):String(b))},_dRep:function(j,g){var h=48,b=57,c=1584,d=null,e=null,f="";if(g===-1){h+=c;b+=c;c=-1584}for(d=0;d=h&&e<=b){f=f+String.fromCharCode(e+c)}else{f=f+String.fromCharCode(e)}}return f},_doIndic:function(){var b=this;b.d.intHTML.find("*").each(function(){if(a(this).children().length<1){a(this).text(b._dRep(a(this).text()))}else{if(a(this).hasClass("ui-datebox-slideday")){a(this).html(b._dRep(a(this).html()))}}});b.d.intHTML.find("input").each(function(){a(this).val(b._dRep(a(this).val()))})},_parser:{"default":function(b){return false}},_n:function(c,b){return(c<0)?b:c},_pa:function(b,c){if(typeof c==="boolean"){return new this._date(b[0],b[1],b[2],0,0,0,0)}return new this._date(c.getFullYear(),c.getMonth(),c.getDate(),b[0],b[1],b[2],0)},_makeDate:function(k){k=a.trim(((this.__("useArabicIndic")===true)?this._dRep(k,-1):k));var n=this,c=this.options,e=n.__fmt(),m=null,h=[],l=null,b=null,f=new n._date(),j={year:-1,mont:-1,date:-1,hour:-1,mins:-1,secs:-1,week:false,wtyp:4,wday:false,yday:false,meri:0},g;if(typeof c.mode==="undefined"){return f}if(typeof n._parser[c.mode]!=="undefined"){return n._parser[c.mode].apply(n,[k])}if(c.mode==="durationbox"||c.mode==="durationflipbox"){e=e.replace(/%D([a-z])/gi,function(d,o){switch(o){case"d":case"l":case"M":case"S":return"("+d+"|[0-9]+)";default:return".+?"}});e=new RegExp("^"+e+"$");m=e.exec(k);l=e.exec(n.__fmt());if(m===null||m.length!==l.length){if(typeof c.defaultValue==="number"&&c.defaultValue>0){return new n._date((n.initDate.getEpoch()+parseInt(c.defaultValue,10))*1000)}return new n._date(n.initDate.getTime())}b=n.initDate.getEpoch();for(g=0;g-1){j.mont=b}break;case"B":b=a.inArray(m[g],n.__("monthsOfYear"));if(b>-1){j.mont=b}break}}if(j.meri!==0){if(j.meri===-1&&j.hour===12){j.hour=0}if(j.meri===1&&j.hour!==12){j.hour=j.hour+12}}f=new n._date(n._n(j.year,0),n._n(j.mont,0),n._n(j.date,1),n._n(j.hour,0),n._n(j.mins,0),n._n(j.secs,0),0);if(j.year<100&&j.year!==-1){f.setFullYear(j.year)}if((j.mont>-1&&j.date>-1)||(j.hour>-1&&j.mins>-1&&j.secs>-1)){return f}if(j.week!==false){f.setDWeek(j.wtyp,j.week);if(j.date>-1){f.setDate(j.date)}}if(j.yday!==false){f.setD(1,0).setD(2,1).adj(2,(j.yday-1))}if(j.wday!==false){f.adj(2,(j.wday-f.getDay()))}}return f},_customformat:{"default":function(c,b){return false}},_formatter:function(f,c){var b=this,g=this.options,d,e={part:[0,0,0,0],tp:0};if(g.mode==="durationbox"||g.mode==="durationflipbox"){e.tp=this.theDate.getEpoch()-this.initDate.getEpoch();e.part[0]=parseInt(e.tp/(60*60*24),10);e.tp-=(e.part[0]*60*60*24);e.part[1]=parseInt(e.tp/(60*60),10);e.tp-=(e.part[1]*60*60);e.part[2]=parseInt(e.tp/(60),10);e.tp-=(e.part[2]*60);e.part[3]=e.tp;if(!f.match(/%Dd/)){e.part[1]+=(e.part[0]*24)}if(!f.match(/%Dl/)){e.part[2]+=(e.part[1]*60)}if(!f.match(/%DM/)){e.part[3]+=(e.part[2]*60)}}f=f.replace(/%(D|X|0|-)*([1-9a-zA-Z])/g,function(h,j,k){if(j==="X"){if(typeof b._customformat[g.mode]!=="undefined"){return b._customformat[g.mode](k,c,g)}return h}if(j==="D"){switch(k){case"d":return e.part[0];case"l":return b._zPad(e.part[1]);case"M":return b._zPad(e.part[2]);case"S":return b._zPad(e.part[3]);case"A":return((e.part[0]>1)?b.__("durationDays")[1]:b.__("durationDays")[0]);default:return h}}switch(k){case"%":return"%";case"a":return b.__("daysOfWeekShort")[c.getDay()];case"A":return b.__("daysOfWeek")[c.getDay()];case"b":return b.__("monthsOfYearShort")[c.getMonth()];case"B":return b.__("monthsOfYear")[c.getMonth()];case"C":return c.getFullYear().toString().substr(0,2);case"d":return((j==="-")?c.getDate():b._zPad(c.getDate()));case"H":case"k":return((j==="-")?c.getHours():b._zPad(c.getHours()));case"I":case"l":return((j==="-")?((c.getHours()===0||c.getHours()===12)?12:((c.getHours()<12)?c.getHours():(c.getHours()-12))):b._zPad(((c.getHours()===0||c.getHours()===12)?12:((c.getHours()<12)?c.getHours():c.getHours()-12))));case"m":return((j==="-")?c.getMonth()+1:b._zPad(c.getMonth()+1));case"M":return((j==="-")?c.getMinutes():b._zPad(c.getMinutes()));case"p":return((c.getHours()<12)?b.__("meridiem")[0].toUpperCase():b.__("meridiem")[1].toUpperCase());case"P":return((c.getHours()<12)?b.__("meridiem")[0].toLowerCase():b.__("meridiem")[1].toLowerCase());case"s":return c.getEpoch();case"S":return((j==="-")?c.getSeconds():b._zPad(c.getSeconds()));case"u":return((j==="-")?c.getDay()+1:b._zPad(c.getDay()+1));case"w":return c.getDay();case"y":return c.getFullYear().toString().substr(2,2);case"Y":return c.getFullYear();case"E":return c.getFullYear()+543;case"V":return((j==="-")?c.getDWeek(4):b._zPad(c.getDWeek(4)));case"U":return((j==="-")?c.getDWeek(0):b._zPad(c.getDWeek(0)));case"W":return((j==="-")?c.getDWeek(1):b._zPad(c.getDWeek(1)));case"o":if(typeof b._ord[g.useLang]!=="undefined"){return b._ord[g.useLang](c.getDate())}return b._ord["default"](c.getDate());case"j":d=new Date(c.getFullYear(),0,1);d=Math.ceil((c-d)/86400000)+1;return((d<100)?((d<10)?"00":"0"):"")+String(d);case"G":if(c.getDWeek(4)===1&&c.getMonth()>0){return c.getFullYear()+1}if(c.getDWeek(4)>51&&c.getMonth()<11){return c.getFullYear()-1}return c.getFullYear();case"g":if(c.getDWeek(4)===1&&c.getMonth()>0){return parseInt(c.getFullYear().toString().substr(2,2),10)+1}if(c.getDWeek(4)>51&&c.getMonth()<11){return parseInt(c.getFullYear().toString().substr(2,2),10)-1}return c.getFullYear().toString().substr(2,2);default:return h}});if(b.__("useArabicIndic")===true){f=b._dRep(f)}return f},_btwn:function(d,b,c){return(d>b&&d1&&d%e.minuteStep>0){if(e.minuteStepRound<0){d=d-(d%e.minuteStep)}else{if(e.minStepRound>0){d=d+(e.minuteStep-(d%e.minuteStep))}else{if(d%e.minuteStep0)?1:-1)*12,false);break}}if(c!==false){b.theDate.adj(c,d)}if(g===true){b.refresh()}if(e.useImmediate){b.d.input.trigger("datebox",{method:"doset"})}},_startOffset:function(b){var c=this.options;if(c.startOffsetYears!==false){b.adj(0,c.startOffsetYears)}if(c.startOffsetMonths!==false){b.adj(1,c.startOffsetMonths)}if(c.startOffsetDays!==false){b.adj(2,c.startOffsetDays)}return b},_create:function(){a(document).trigger("dateboxcreate");var j=this,b=a.extend(this.options,(typeof this.element.jqmData("options")!=="undefined")?this.element.jqmData("options"):this._getLongOptions(this.element)),k=(b.theme===false&&typeof(a(this).jqmData("theme"))==="undefined")?((typeof(this.element.parentsUntil(":jqmData(theme)").parent().jqmData("theme"))==="undefined")?b.themeDefault:this.element.parentsUntil(":jqmData(theme)").parent().jqmData("theme")):b.theme,l=b.useAnimation?b.transition:"none",g=b.useNewStyle===false?{input:this.element,wrap:this.element.wrap('
            ').parent(),mainWrap:a("
            ",{"class":"ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden "+l+" ui-body-"+k}).css("zIndex",b.zindex),intHTML:false}:{input:this.element,wrap:this.element,mainWrap:a("
            ",{"class":"ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden "+l+" ui-body-"+k}).css("zIndex",b.zindex),intHTML:false},e=(typeof window.ontouchstart!=="undefined"),f={eStart:(e?"touchstart":"mousedown")+".datebox",eMove:(e?"touchmove":"mousemove")+".datebox",eEnd:(e?"touchend":"mouseup")+".datebox",eEndA:(e?"mouseup.datebox touchend.datebox touchcancel.datebox touchmove.datebox":"mouseup.datebox"),move:false,start:false,end:false,pos:false,target:false,delta:false,tmp:false},c={},h=(typeof a.mobile.ns!=="undefined")?a.mobile.ns:"";a.extend(j,{d:g,ns:h,drag:f,touch:e});if(b.usePlaceholder!==false){if(b.usePlaceholder===true&&j._grabLabel()!==false){j.d.input.attr("placeholder",j._grabLabel())}if(typeof b.usePlaceholder==="string"){j.d.input.attr("placeholder",b.usePlaceholder)}}b.theme=k;j.clearFunc=false;j.disabled=false;j.runButton=false;j._date=window.Date;j._enhanceDate();j.baseID=j.d.input.attr("id");j.initDate=new j._date();j.theDate=(b.defaultValue)?j._makeDate(b.defaultValue):((j.d.input.val()!=="")?j._makeDate(j.d.input.val()):new j._date());j.initDone=false;if(b.showInitialValue===true){j.d.input.val(j._formatter(j.__fmt(),j.theDate))}if(b.useButton===true&&b.useInline===false&&b.useNewStyle===false){j.d.open=a(''+this.__("tooltip")+"").on(b.clickEvent,function(d){d.preventDefault();if(!j.disabled){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.parent().addClass("ui-focus");j.d.input.parent().removeClass("ui-focus")}setTimeout(function(){a(d.target).closest("a").removeClass(a.mobile.activeBtnClass)},300)}).appendTo(j.d.wrap).buttonMarkup({icon:"grid",iconpos:"notext",corners:true,shadow:true}).css({"vertical-align":"middle",display:"inline-block"})}j.d.screen=a("
            ",{"class":"ui-datebox-screen ui-datebox-hidden"+((b.useModal)?" ui-datebox-screen-modal":"")}).css({"z-index":b.zindex-1}).on(b.clickEventAlt,function(d){d.preventDefault();j.d.input.trigger("datebox",{method:"close"})});if(b.enhanceInput===true&&navigator.userAgent.match(/Android/i)){j.inputType="number"}else{j.inputType="text"}if(b.hideInput){j.d.wrap.parent().hide()}if(b.mobVer<140){a("label[for='"+j.d.input.attr("id")+"']").addClass("ui-input-text").css("verticalAlign","middle")}j.d.wrap.on(b.clickEvent,function(){if(!j.disabled&&(b.noButtonFocusMode||b.focusMode)){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.addClass("ui-focus");j.d.input.removeClass("ui-focus")}});j.d.input.removeClass("ui-corner-all ui-shadow-inset").bind(j.touch?"touchend":"click",function(d){if(j.disabled===false&&b.useNewStyle===true&&b.useFocus===false){if(((j.touch?d.originalEvent.changedTouches[0].pageX:d.pageX)-d.target.offsetLeft)>(d.target.offsetWidth-20)){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.parent().addClass("ui-focus");j.d.input.removeClass("ui-focus")}}}).focus(function(){if(j.disabled===false&&b.useFocus===true){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.addClass("ui-focus");j.d.input.removeClass("ui-focus");if(b.useNewStyle===false){j.d.input.parent().removeClass("ui-focus");j.d.wrap.parent().addClass("ui-focus")}}if(b.useNewStyle===false){j.d.input.removeClass("ui-focus")}}).blur(function(){j.d.wrap.removeClass("ui-focus");j.d.input.removeClass("ui-focus")}).change(function(){j.theDate=j._makeDate(j.d.input.val());j.refresh()}).attr("readonly",b.lockInput).on("datebox",j._event);if(b.useNewStyle===true){j.d.input.addClass("ui-corner-all "+((b.useAltIcon===true)?"ui-icon-datebox-alt":"ui-icon-datebox"));if(b.overrideStyleClass!==false){j.d.input.addClass(b.overrideStyleClass)}}else{j.d.input.parent().css("border","none").removeClass("ui-shadow-inset")}j.d.wrap.parent().on(b.clickEvent,function(){if(!j.disabled&&b.useFocus===true&&b.useNewStyle===false){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.addClass("ui-focus");j.d.input.removeClass("ui-focus");setTimeout(function(){j.d.wrap.removeClass("ui-focus");j.d.wrap.parent().addClass("ui-focus")},500)}});if(typeof a.event.special.mousewheel!=="undefined"){j.wheelExists=true}if(j.d.input.is(":disabled")){j.disable()}if(b.useInline===true||b.useInlineBlind){j.open()}j.applyMinMax(false,false);a(document).trigger("dateboxaftercreate")},applyMinMax:function(e,d){var b=this,f=this.options,c={};if(typeof e==="undefined"){e=false}if(typeof d==="undefined"){d=true}if((d===true||f.minDays===false)&&typeof(b.d.input.attr("min"))!=="undefined"){c.today=new b._date();c.lod=24*60*60*1000;c.todayc=new b._date(c.today.getFullYear(),c.today.getMonth(),c.today.getDate(),0,0,0,0);c.fromel=b.d.input.attr("min").split("-");c.compdt=new b._date(c.fromel[0],c.fromel[1]-1,c.fromel[2],0,0,0,0);f.minDays=parseInt((((c.compdt.getTime()-c.todayc.getTime())/c.lod))*-1,10)}if((d===true||f.maxDays===false)&&typeof(b.d.input.attr("max"))!=="undefined"){c.today=new b._date();c.lod=24*60*60*1000;c.todayc=new b._date(c.today.getFullYear(),c.today.getMonth(),c.today.getDate(),0,0,0,0);c.fromel=b.d.input.attr("max").split("-");c.compdt=new b._date(c.fromel[0],c.fromel[1]-1,c.fromel[2],0,0,0,0);f.maxDays=parseInt((((c.compdt.getTime()-c.todayc.getTime())/c.lod)),10)}if(e===true){b.refresh()}},_build:{"default":function(){this.d.headerText="Error";this.d.intHTML=a("

            There is no mode by that name loaded / mode not given

            ")}},_applyCoords:function(h){var b=h.widget,j=h.widget.options,f={h:a.mobile.activePage.find(".ui-header").jqmData("position"),f:a.mobile.activePage.find(".ui-footer").jqmData("position"),fh:a.mobile.activePage.find(".ui-footer").outerHeight(),hh:a.mobile.activePage.find(".ui-header").outerHeight()},c={x:b.d.wrap.offset().left+(b.d.wrap.outerWidth()/2),y:b.d.wrap.offset().top+(b.d.wrap.outerHeight()/2)},d={w:b.d.mainWrap.outerWidth(),h:b.d.mainWrap.outerHeight()},g={t:a(window).scrollTop(),h:a(window).height(),w:a.mobile.activePage.width(),ah:a(document).height()},k={y:(j.centerVert)?g.t+((g.h/2)-(d.h/2)):c.y-(d.h/2),x:(g.w<400||j.centerHoriz)?(g.w/2)-(d.w/2):c.x-(d.w/2)};if(j.centerVert===false){if(j.hideFixedToolbars===true&&(typeof f.f!=="undefined"||typeof f.h!=="undefined")){a.mobile.activePage.find(":jqmData(position='fixed')").fixedtoolbar("hide");f.f=undefined;f.h=undefined}if(typeof f.f!=="undefined"){if((k.y+d.h)>(g.h-f.fh-2)){k.y=g.h-f.fh-2-d.h}}else{if((k.y+d.h)>(g.ah-f.fh-2)){k.y=g.ah-f.fh-2-d.h}if((g.h+g.t)<(d.h+k.y+2)){k.y=g.h+g.t-d.h-2}}if(typeof f.h!=="undefined"){if((g.t+f.hh+2)>k.y){k.y=g.t+f.hh+2}}else{if(f.hh+2>k.y){k.y=f.hh+2}if(k.y
            ');a("Close").appendTo(b.d.headHTML).buttonMarkup({theme:g.themeHeader,icon:"delete",iconpos:"notext",corners:true,shadow:true}).on(g.clickEventAlt,function(h){h.preventDefault();b.d.input.trigger("datebox",{method:"close"})});a('

            '+b.d.headerText+"

            ").appendTo(b.d.headHTML);b.d.mainWrap.append(b.d.headHTML)}b.d.mainWrap.append(b.d.intHTML).css("zIndex",g.zindex);b.d.input.trigger("datebox",{method:"postrefresh"});if(g.useAnimation===true){e.transition=g.transition}else{e.transition="none"}if(g.popupForceX!==false&&g.popupForceY!==false){e.x=g.popupForceX;e.y=g.popupForceY}if(g.popupPosition!==false){e.positionTo=g.popupPosition}else{if(typeof b.baseID!==undefined){e.positionTo="#"+b.baseID}else{e.positionTo="window"}}if(g.useModal===true){f.overlayTheme="a"}b.d.mainWrap.removeClass("ui-datebox-hidden").popup(f).popup("open",e);b.refresh()}else{if(g.dialogForce||(g.dialogEnable&&window.width()<400)){b.d.dialogPage=a("

            "+b.d.headerText+"

            ").appendTo(a.mobile.pageContainer).page().css("minHeight","0px").addClass(c);b.d.dialogPage.find(".ui-header").find("a").off("click vclick").on(g.clickEventAlt,function(h){h.preventDefault();b.d.input.trigger("datebox",{method:"close"})});b.d.mainWrap.append(b.d.intHTML).css({marginLeft:"auto",marginRight:"auto"}).removeClass("ui-datebox-hidden");b.d.dialogPage.find(".ui-content").append(b.d.mainWrap);b.d.input.trigger("datebox",{method:"postrefresh"});a.mobile.activePage.off("pagehide.remove");a.mobile.changePage(b.d.dialogPage,{transition:c})}else{b.d.dialogPage=false;b.d.mainWrap.empty();if(g.useHeader===true){b.d.headHTML=a('
            ');a("Close").appendTo(b.d.headHTML).buttonMarkup({theme:g.themeHeader,icon:"delete",iconpos:"notext",corners:true,shadow:true}).on(g.clickEventAlt,function(h){h.preventDefault();b.d.input.trigger("datebox",{method:"close"})});a('

            '+b.d.headerText+"

            ").appendTo(b.d.headHTML);b.d.mainWrap.append(b.d.headHTML)}b.d.mainWrap.append(b.d.intHTML).css("zIndex",g.zindex);b.d.mainWrap.appendTo(a.mobile.activePage);b.d.screen.appendTo(a.mobile.activePage);b.d.input.trigger("datebox",{method:"postrefresh"});b._applyCoords({widget:b});if(g.useModal===true){if(g.useAnimation){b.d.screen.fadeIn("slow")}else{b.d.screen.show()}}else{setTimeout(function(){b.d.screen.removeClass("ui-datebox-hidden")},500)}b.d.mainWrap.addClass("ui-overlay-shadow in").removeClass("ui-datebox-hidden");a(document).on("orientationchange.datebox",{widget:b},function(h){b._applyCoords(h.data)});if(g.resizeListener===true){a(window).on("resize.datebox",{widget:b},function(h){b._applyCoords(h.data)})}}}},close:function(){var b=this,c=this.options;if(c.useInlineBlind===true){b.d.mainWrap.slideUp();return true}if(c.useInline===true||b.d.intHTML===false){return true}if(b.d.dialogPage!==false){a(b.d.dialogPage).dialog("close");if(!a.mobile.activePage.jqmData("mobile-page").options.domCache){a.mobile.activePage.on("pagehide.remove",function(){a(this).remove()})}b.d.intHTML.detach().empty();b.d.mainWrap.detach().empty();b.d.wrap.removeClass("ui-focus");b.clearFunc=setTimeout(function(){b.d.dialogPage.empty().remove();b.clearFunc=false},1500)}else{if(c.enablePopup===true){b.d.mainWrap.popup("close");b.d.wrap.removeClass("ui-focus")}else{if(c.useModal){if(c.useAnimation){b.d.screen.fadeOut("slow")}else{b.d.screen.hide()}}else{b.d.screen.addClass("ui-datebox-hidden")}b.d.screen.detach();b.d.mainWrap.addClass("ui-datebox-hidden").removeAttr("style").removeClass("in ui-overlay-shadow").empty().detach();b.d.intHTML.detach();b.d.wrap.removeClass("ui-focus");a(document).off("orientationchange.datebox");if(c.resizeListener===true){a(window).off("resize.datebox")}}}b.d.wrap.parent().removeClass("ui-focus");a(document).off(b.drag.eMove);a(document).off(b.drag.eEnd);a(document).off(b.drag.eEndA);if(c.useFocus){b.fastReopen=true;setTimeout(function(d){return function(){d.fastReopen=false}}(b),300)}if(c.closeCallback!==false){if(!a.isFunction(c.closeCallback)){if(typeof window[c.closeCallback]!=="undefined"){c.closeCallback=window[c.closeCallback]}else{c.closeCallback=new Function(c.closeCallback)}}c.closeCallback.apply(b,a.merge([b.theDate],c.closeCallbackArgs))}},refresh:function(){if(typeof this._build[this.options.mode]==="undefined"){this._build["default"].apply(this,[])}else{this._build[this.options.mode].apply(this,[])}if(this.__("useArabicIndic")===true){this._doIndic()}this.d.mainWrap.append(this.d.intHTML);this.d.input.trigger("datebox",{method:"postrefresh"})},_check:function(){var b=this,d=null,c=this.options;b.dateOK=true;if(c.afterToday!==false){d=new b._date();if(b.theDated){b.theDate=d}}if(c.maxDays!==false){d=new b._date();d.adj(2,c.maxDays);if(b.theDate>d){b.theDate=d}}if(c.minDays!==false){d=new b._date();d.adj(2,-1*c.minDays);if(b.theDatec.maxHour){b.theDate.setHours(c.maxHour)}}if(c.maxYear!==false){d=new b._date(c.maxYear,0,1);d.adj(2,-1);if(b.theDate>d){b.theDate=d}}if(c.minYear!==false){d=new b._date(c.minYear,0,1);if(b.theDate-1){if(c.mode==="timeflipbox"&&c.validHours!==false){if(a.inArray(b.theDate.getHours(),c.validHours)<0){b.dateOK=false}}}else{if(c.blackDatesRec!==false){for(i=0;i-1){b.dateOK=false}}if(c.blackDays!==false){if(a.inArray(b.theDate.getDay(),c.blackDays)>-1){b.dateOK=false}}}},_grabLabel:function(){var b=this,c=this.options;if(typeof c.overrideDialogLabel==="undefined"){if(typeof b.d.input.attr("placeholder")!=="undefined"){return b.d.input.attr("placeholder")}if(typeof b.d.input.attr("title")!=="undefined"){return b.d.input.attr("title")}if(b.d.wrap.parent().find("label[for='"+b.d.input.attr("id")+"']").text()!==""){return b.d.wrap.parent().find("label[for='"+b.d.input.attr("id")+"']").text()}return false}return c.overrideDialogLabel},_makeEl:function(d,e){var b=false,c=false;c=d.clone();if(typeof e.attr!=="undefined"){for(b in e.attr){if(e.attr.hasOwnProperty(b)){c.jqmData(b,e.attr[b])}}}return c},_getLongOptions:function(d){var c,e={},f,b;if(a.mobile.ns===""){f="datebox"}else{f=a.mobile.ns.substr(0,a.mobile.ns.length-1)+"Datebox"}for(c in d.data()){if(c.substr(0,f.length)===f&&c.length>f.length){b=c.substr(f.length);b=b.charAt(0).toLowerCase()+b.slice(1);e[b]=d.data(c)}}return e},disable:function(){this.d.input.attr("disabled",true);this.d.wrap.addClass("ui-disabled").blur();this.disabled=true;this.d.input.trigger("datebox",{method:"disable"})},enable:function(){this.d.input.attr("disabled",false);this.d.wrap.removeClass("ui-disabled");this.disabled=false;this.d.input.trigger("datebox",{method:"enable"})},_setOption:function(){a.Widget.prototype._setOption.apply(this,arguments);this.refresh()},getTheDate:function(){return this.theDate},getLastDur:function(){return this.lastDuration},setTheDate:function(b){this.theDate=b;this.refresh()},callFormat:function(c,b){return this._formatter(c,b)}});a(document).on("pagebeforecreate",function(b){a(":jqmData(role='datebox')",b.target).each(function(){a(this).prop("type","text")})});a(document).on("pagecreate create",function(b){a(document).trigger("dateboxbeforecreate");a(":jqmData(role='datebox')",b.target).each(function(){var c=typeof(a(this).data(parseInt(a.mobile.version.replace(/\./g,""),10)>111?"mobile-datebox":"datebox"));if(c==="undefined"){a(this).datebox()}})})})(jQuery);(function(a){a.extend(a.mobile.datebox.prototype.options,{themeDateHigh:"b",themeDatePick:"b",themeDate:"a",useSetButton:true,validHours:false,flen:{y:15,m:12,d:15,h:12,i:15,a:3}});a.extend(a.mobile.datebox.prototype,{_fbox_pos:function(){var b=this,f=null,e=null,d=this.d.intHTML.find(".ui-datebox-flipcontent").innerHeight(),c=null;b.d.intHTML.find(".ui-datebox-flipcenter").each(function(){f=a(this);e=f.innerHeight();f.css("top",((d/2)-(e/2)+4)*-1)});b.d.intHTML.find("ul").each(function(){f=a(this);d=f.parent().innerHeight();e=f.find("li").first();c=f.find("li").size()*e.outerHeight();e.css("marginTop",((c/2)-(d/2)+(e.outerHeight()/2))*-1)})}});a.extend(a.mobile.datebox.prototype._build,{timeflipbox:function(){this._build.flipbox.apply(this)},flipbox:function(){var l=this,d=this.options,e,j,m,f,k,g=(l.d.input.val()==="")?l._startOffset(l._makeDate(l.d.input.val())):l._makeDate(l.d.input.val()),h="ui-datebox-",c=a("
              "),b=a("
              ",{"class":h+"flipcontent"});if(typeof l.d.intHTML!=="boolean"){l.d.intHTML.empty()}l.d.input.on("datebox",function(n,i){if(i.method==="postrefresh"){l._fbox_pos()}});l.d.headerText=((l._grabLabel()!==false)?l._grabLabel():((d.mode==="flipbox")?l.__("titleDateDialogLabel"):l.__("titleTimeDialogLabel")));l.d.intHTML=a("");l.fldOrder=((d.mode==="flipbox")?l.__("dateFieldOrder"):l.__("timeFieldOrder"));l._check();l._minStepFix();if(d.mode==="flipbox"){a('

              '+l._formatter(l.__("headerFormat"),l.theDate)+"

              ").appendTo(l.d.intHTML)}l.d.intHTML.append(b);for(j=0;j",{"class":"ui-body-"+f}).html(""+(l.theDate.get(0)+e)+"").appendTo(m.find("ul"))}m.appendTo(b);break;case"m":m=l._makeEl(c,{attr:{field:"m",amount:1}});for(e=d.flen.m*-1;e<(d.flen.m+1);e++){k=l.theDate.copy([0],[0,0,1]);k.adj(1,e);f=(e!==0)?((g.get(1)===k.get(1)&&g.get(0)===k.get(0))?d.themeDateHigh:d.themeDate):d.themeDatePick;a("
            • ",{"class":"ui-body-"+f}).html(""+l.__("monthsOfYearShort")[k.getMonth()]+"").appendTo(m.find("ul"))}m.appendTo(b);break;case"d":m=l._makeEl(c,{attr:{field:"d",amount:1}});for(e=d.flen.d*-1;e<(d.flen.d+1);e++){k=l.theDate.copy();k.adj(2,e);f=(e!==0)?((g.comp()===k.comp())?d.themeDateHigh:d.themeDate):d.themeDatePick;if((d.blackDates!==false&&a.inArray(k.iso(),d.blackDates)>-1)||(d.blackDays!==false&&a.inArray(k.getDay(),d.blackDays)>-1)){f+=" "+h+"griddate-disable"}a("
            • ",{"class":"ui-body-"+f}).html(""+k.getDate()+"").appendTo(m.find("ul"))}m.appendTo(b);break;case"h":m=l._makeEl(c,{attr:{field:"h",amount:1}});for(e=d.flen.h*-1;e<(d.flen.h+1);e++){k=l.theDate.copy();k.adj(3,e);f=(e!==0)?d.themeDate:d.themeDatePick;if(d.validHours!==false&&a.inArray(k.get(3),d.validHours)<0){f+=" "+h+"griddate-disable"}a("
            • ",{"class":"ui-body-"+f}).html(""+((l.__("timeFormat")===12)?((k.get(3)===0)?"12":((k.get(3)<13)?k.get(3):(k.get(3)-12))):k.get(3))+"").appendTo(m.find("ul"))}m.appendTo(b);break;case"i":m=l._makeEl(c,{attr:{field:"i",amount:d.minuteStep}});for(e=d.flen.i*-1;e<(d.flen.i+1);e++){k=l.theDate.copy();k.adj(4,(e*d.minuteStep));f=(e!==0)?d.themeDate:d.themeDatePick;a("
            • ",{"class":"ui-body-"+f}).html(""+l._zPad(k.get(4))+"").appendTo(m.find("ul"))}m.appendTo(b);break;case"a":if(l.__("timeFormat")!==12){break}m=l._makeEl(c,{attr:{field:"a",amount:1}});k=a("
            • ");for(e=0;e11)?[d.themeDate,d.themeDatePick]:[d.themeDatePick,d.themeDate];a("
            • ",{"class":"ui-body-"+f[0]}).html(""+l.__("meridiem")[0]+"").appendTo(m.find("ul"));a("
            • ",{"class":"ui-body-"+f[1]}).html(""+l.__("meridiem")[1]+"").appendTo(m.find("ul"));if(l.theDate.get(3)>11){k.clone().appendTo(m.find("ul"))}for(e=0;e",{"class":h+"flipcenter ui-overlay-shadow"}).css("pointerEvents","none").appendTo(l.d.intHTML);if(d.useSetButton||d.useClearButton){j=a("
              ",{"class":h+"controls"});if(d.useSetButton){a(''+((d.mode==="flipbox")?l.__("setDateButtonLabel"):l.__("setTimeButtonLabel"))+"").appendTo(j).buttonMarkup({theme:d.theme,icon:"check",iconpos:"left",corners:true,shadow:true}).on(d.clickEventAlt,function(i){i.preventDefault();if(l.dateOK===true){l.d.input.trigger("datebox",{method:"set",value:l._formatter(l.__fmt(),l.theDate),date:l.theDate});l.d.input.trigger("datebox",{method:"close"})}})}if(d.useClearButton){a(''+l.__("clearButton")+"").appendTo(j).buttonMarkup({theme:d.theme,icon:"delete",iconpos:"left",corners:true,shadow:true}).on(d.clickEventAlt,function(i){i.preventDefault();l.d.input.val("");l.d.input.trigger("datebox",{method:"clear"});l.d.input.trigger("datebox",{method:"close"})})}if(d.useCollapsedBut){j.addClass("ui-datebox-collapse")}j.appendTo(l.d.intHTML)}if(l.wheelExists){l.d.intHTML.on("mousewheel",".ui-overlay-shadow",function(i,n){i.preventDefault();l._offset(a(this).jqmData("field"),((n<0)?-1:1)*a(this).jqmData("amount"))})}l.d.intHTML.on(l.drag.eStart,"ul",function(n,i){if(!l.drag.move){if(typeof i!=="undefined"){n=i}l.drag.move=true;l.drag.target=a(this).find("li").first();l.drag.pos=parseInt(l.drag.target.css("marginTop").replace(/px/i,""),10);l.drag.start=l.touch?n.originalEvent.changedTouches[0].pageY:n.pageY;l.drag.end=false;n.stopPropagation();n.preventDefault()}});l.d.intHTML.on(l.drag.eStart,"."+h+"flipcenter",function(i){if(!l.drag.move){l.drag.target=l.touch?i.originalEvent.changedTouches[0].pageX-a(i.currentTarget).offset().left:i.pageX-a(i.currentTarget).offset().left;l.drag.tmp=l.d.intHTML.find("."+h+"flipcenter").innerWidth()/((a.inArray("a",l.fldOrder)>-1&&l.__("timeFormat")!==12)?l.fldOrder.length-1:l.fldOrder.length);a(l.d.intHTML.find("ul").get(parseInt(l.drag.target/l.drag.tmp,10))).trigger(l.drag.eStart,i)}})}});a.extend(a.mobile.datebox.prototype._drag,{timeflipbox:function(){this._drag.flipbox.apply(this)},flipbox:function(){var b=this,d=this.options,c=this.drag;a(document).on(c.eMove,function(f){if(c.move&&(d.mode==="flipbox"||d.mode==="timeflipbox")){c.end=b.touch?f.originalEvent.changedTouches[0].pageY:f.pageY;c.target.css("marginTop",(c.pos+c.end-c.start)+"px");f.preventDefault();f.stopPropagation();return false}});a(document).on(c.eEnd,function(f){if(c.move&&(d.mode==="flipbox"||d.mode==="timeflipbox")){c.move=false;if(c.end!==false){f.preventDefault();f.stopPropagation();c.tmp=c.target.parent().parent();b._offset(c.tmp.jqmData("field"),(parseInt((c.start-c.end)/c.target.innerHeight(),10)*c.tmp.jqmData("amount")))}c.start=false;c.end=false}})}})})(jQuery); \ No newline at end of file diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.slidebox.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.slidebox.js new file mode 100644 index 000000000..308abc22e --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.slidebox.js @@ -0,0 +1,1590 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +/* CORE Functions */ + +(function($) { + $.widget( "mobile.datebox", $.mobile.widget, { + options: { + // All widget options, including some internal runtime details + version: '2-1.4.0-2013070300', // jQMMajor.jQMMinor.DBoxMinor-YrMoDaySerial + mobVer: parseInt($.mobile.version.replace(/\./g,'')), + theme: false, + themeDefault: 'a', + themeHeader: 'a', + mode: false, + + centerHoriz: false, + centerVert: false, + transition: 'pop', + useAnimation: true, + hideInput: false, + hideFixedToolbars: false, + + lockInput: true, + enhanceInput: true, + + zindex: '500', + clickEvent: 'vclick', + clickEventAlt: 'click', + resizeListener: true, + + defaultValue: false, + showInitialValue: false, + + dialogEnable: false, + dialogForce: false, + enablePopup: false, + + popupPosition: false, + popupForceX: false, + popupForceY: false, + + useModal: false, + useInline: false, + useInlineBlind: false, + useHeader: true, + useImmediate: false, + useNewStyle: false, + useAltIcon: false, + overrideStyleClass: false, + + useButton: true, + useFocus: false, + useClearButton: false, + useCollapsedBut: false, + usePlaceholder: false, + + openCallback: false, + openCallbackArgs: [], + closeCallback: false, + closeCallbackArgs: [], + + startOffsetYears: false, + startOffsetMonths: false, + startOffsetDays: false, + afterToday: false, + beforeToday: false, + notToday: false, + maxDays: false, + minDays: false, + maxYear: false, + minYear: false, + blackDates: false, + blackDatesRec: false, + blackDays: false, + minHour: false, + maxHour: false, + minuteStep: 1, + minuteStepRound: 0, + + rolloverMode: { 'm': true, 'd': true, 'h': true, 'i': true, 's': true }, + + useLang: 'default', + lang: { + 'default' : { + setDateButtonLabel: 'Set Date', + setTimeButtonLabel: 'Set Time', + setDurationButtonLabel: 'Set Duration', + calTodayButtonLabel: 'Jump to Today', + titleDateDialogLabel: 'Set Date', + titleTimeDialogLabel: 'Set Time', + daysOfWeek: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], + daysOfWeekShort: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], + monthsOfYear: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], + monthsOfYearShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + durationLabel: ['Days', 'Hours', 'Minutes', 'Seconds'], + durationDays: ['Day', 'Days'], + timeFormat: 24, + headerFormat: '%A, %B %-d, %Y', + tooltip: 'Open Date Picker', + nextMonth: 'Next Month', + prevMonth: 'Previous Month', + dateFieldOrder: ['m', 'd', 'y'], + timeFieldOrder: ['h', 'i', 'a'], + slideFieldOrder: ['y', 'm', 'd'], + dateFormat: '%Y-%m-%d', + useArabicIndic: false, + isRTL: false, + calStartDay: 0, + clearButton: 'Clear', + durationOrder: ['d', 'h', 'i', 's'], + meridiem: ['AM', 'PM'], + timeOutput: '%k:%M', //{ '12': '%l:%M %p', '24': '%k:%M' }, + durationFormat: '%Dd %DA, %Dl:%DM:%DS', + calDateListLabel: 'Other Dates', + calHeaderFormat: '%B %Y' + } + } + }, + _enhanceDate: function() { + $.extend(this._date.prototype, { + copy: function(adjust, override) { + /* Get a modified copy of the date. + * First array - Offset the new date by # (position determines date part) + * Second array - If non-zero, force the new date by # (position determines date part) + */ + if ( typeof adjust === 'undefined' ) { adjust = [0,0,0,0,0,0,0]; } + if ( typeof override === 'undefined' ) { override = [0,0,0,0,0,0,0]; } + while ( adjust.length < 7 ) { adjust.push(0); } + while ( override.length < 7 ) { override.push(0); } + return new Date( + ((override[0] > 0 ) ? override[0] : this.getFullYear() + adjust[0]), + ((override[1] > 0 ) ? override[1] : this.getMonth() + adjust[1]), + ((override[2] > 0 ) ? override[2] : this.getDate() + adjust[2]), + ((override[3] > 0 ) ? override[3] : this.getHours() + adjust[3]), + ((override[4] > 0 ) ? override[4] : this.getMinutes() + adjust[4]), + ((override[5] > 0 ) ? override[5] : this.getSeconds() + adjust[5]), + ((override[6] > 0 ) ? override[5] : this.getMilliseconds() + adjust[6])); + }, + adj: function (type, amount) { + /* Adjust the date. Yes, this is chainable */ + if ( typeof amount !== 'number' ) { + throw new Error("Adjustment value not specified"); + } + if ( typeof type !== 'number' ) { + throw new Error("Adjustment type not specified"); + } + switch ( type ) { + case 0: this.setFullYear(this.getFullYear() + amount); break; + case 1: this.setMonth(this.getMonth() + amount); break; + case 2: this.setDate(this.getDate() + amount); break; + case 3: this.setHours(this.getHours() + amount); break; + case 4: this.setMinutes(this.getMinutes() + amount); break; + case 5: this.setSeconds(this.getSeconds() + amount); break; + case 6: this.setMilliseconds(this.getMilliseconds() + amount); break; + } + return this; + }, + setD: function(type, amount) { + /* A chainable version of setWhatever() */ + switch ( type ) { + case 0: this.setFullYear(amount); break; + case 1: this.setMonth(amount); break; + case 2: this.setDate(amount); break; + case 3: this.setHours(amount); break; + case 4: this.setMinutes(amount); break; + case 5: this.setSeconds(amount); break; + case 6: this.setMilliseconds(amount); break; + } + return this; + }, + get: function(type) { + switch ( type ) { + case 0: return this.getFullYear(); + case 1: return this.getMonth(); + case 2: return this.getDate(); + case 3: return this.getHours(); + case 4: return this.getMinutes(); + case 5: return this.getSeconds(); + } + return false; + }, + iso: function() { + return String(this.getFullYear()) + '-' + (( this.getMonth() < 9 ) ? "0" : "") + String(this.getMonth()+1) + '-' + ((this.getDate() < 10 ) ? "0" : "") + String(this.getDate()); + }, + comp: function () { + return parseInt(this.iso().replace(/-/g,''),10); + }, + getEpoch: function() { + return (this.getTime() - this.getMilliseconds()) / 1000; + }, + getArray: function() { + return [this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds()]; + }, + setFirstDay: function (day) { + this.setD(2,1).adj(2, (day - this.getDay())); + if ( this.get(2) > 10 ) { this.adj(2,7); } + return this; + }, + setDWeek: function (type,num) { + if ( type === 4 ) { + return this.setD(1,0).setD(2,1).setFirstDay(4).adj(2,-3).adj(2,(num-1)*7); + } + return this.setD(1,0).setD(2,1).setFirstDay(type).adj(2,(num-1)*7); + }, + getDWeek: function (type) { + var t1, t2; + + switch ( type ) { + case 0: + t1 = this.copy([0,-1*this.getMonth()]).setFirstDay(0); + return Math.floor((this.getTime() - ( t1.getTime() + (( this.getTimezoneOffset() - t1.getTimezoneOffset()) * 60000))) / 6048e5) + 1; + //return Math.floor((this.getTime() - t1.getTime()) / 6048e5) + 1; + case 1: + t1 = this.copy([0,-1*this.getMonth()]).setFirstDay(1); + return Math.floor((this.getTime() - ( t1.getTime() + (( this.getTimezoneOffset() - t1.getTimezoneOffset()) * 60000))) / 6048e5) + 1; + //return Math.floor((this.getTime() - t1.getTime()) / 6048e5) + 1; + case 4: + // this line is some bullshit. but it does work. + // (trap for dec 29, 30, or 31st being in the new year's week - these are the + // only 3 that can possibly fall like this) + if ( this.getMonth() === 11 && this.getDate() > 28 ) { return 1; } + + t1 = this.copy([0,-1*this.getMonth()],true).setFirstDay(4).adj(2,-3); + t2 = Math.floor((this.getTime() - ( t1.getTime() + (( this.getTimezoneOffset() - t1.getTimezoneOffset()) * 60000))) / 6048e5) + 1; + + if ( t2 < 1 ) { + t1 = this.copy([-1,-1*this.getMonth()]).setFirstDay(4).adj(2,-3); + return Math.floor((this.getTime() - t1.getTime()) / 6048e5) + 1; + } + return t2; + default: + return 0; + } + } + }); + }, + _event: function(e, p) { + var w = $(this).data(parseInt($.mobile.version.replace(/\./g,''),10) > 110 ? 'mobile-datebox' : 'datebox'); + if ( ! e.isPropagationStopped() ) { + switch (p.method) { + case 'close': + w.close(); break; + case 'open': + w.open(); break; + case 'set': + $(this).val(p.value); + $(this).trigger('change'); + break; + case 'doset': + if ( $.isFunction(w['_'+w.options.mode+'DoSet']) ) { + w['_'+w.options.mode+'DoSet'].apply(w,[]); + } else { + $(this).trigger('datebox', {'method':'set', 'value':w._formatter(w.__fmt(), w.theDate), 'date':w.theDate}); + } + break; + case 'dooffset': + if (p.type) { w._offset(p.type, p.amount, true); } break; + case 'dorefresh': + w.refresh(); break; + case 'doreset': + w.hardreset(); break; + case 'doclear': + $(this).val('').trigger('change'); break; + case 'clear': + $(this).trigger('change'); + } + } + }, + _hoover: function(item) { + // Hover toggle class, for calendar + $(item).toggleClass('ui-btn-up-'+$(item).jqmData('theme')+' ui-btn-down-'+$(item).jqmData('theme')); + }, + _ord: { + 'default': function (num) { + // Return an ordinal suffix (1st, 2nd, 3rd, etc) + var ending = num % 10; + if ( num > 9 && num < 21 ) { return 'th'; } + if ( ending > 3 ) { return 'th'; } + return ['th','st','nd','rd'][ending]; + } + }, + __ : function(val) { + var o = this.options, + oride = 'override' + val.charAt(0).toUpperCase() + val.slice(1); + + if ( typeof o[oride] !== 'undefined' ) { return o[oride]; } + if ( typeof o.lang[o.useLang][val] !== 'undefined' ) { return o.lang[o.useLang][val]; } + if ( typeof o[o.mode+'lang'] !== 'undefined' && typeof o[o.mode+'lang'][val] !== 'undefined' ) { return o[o.mode+'lang'][val]; } + return o.lang['default'][val]; + }, + __fmt: function() { + var w = this, + o = this.options; + + switch ( o.mode ) { + case 'timebox': + case 'timeflipbox': + return w.__('timeOutput'); + case 'durationbox': + case 'durationflipbox': + return w.__('durationFormat'); + default: + return w.__('dateFormat'); + } + }, + _zPad: function(number) { + return (( number < 10 ) ? '0' + String(number) : String(number)); + }, + _dRep: function(oper, direction) { + var start = 48, + end = 57, + adder = 1584, + i = null, + ch = null, + newd = ''; + + if ( direction === -1 ) { + start += adder; + end += adder; + adder = -1584; + } + + for ( i=0; i= start && ch <= end ) { + newd = newd + String.fromCharCode(ch+adder); + } else { + newd = newd + String.fromCharCode(ch); + } + } + + return newd; + }, + _doIndic: function() { + var w = this; + + w.d.intHTML.find('*').each(function() { + if ( $(this).children().length < 1 ) { + $(this).text(w._dRep($(this).text())); + } else if ( $(this).hasClass('ui-datebox-slideday') ) { + $(this).html(w._dRep($(this).html())); + } + }); + w.d.intHTML.find('input').each(function() { + $(this).val(w._dRep($(this).val())); + }); + }, + _parser: { + 'default': function (str) { return false; } + }, + _n: function (val,def) { + return ( val < 0 ) ? def : val; + }, + _pa: function (arr,date) { + if ( typeof date === 'boolean' ) { return new this._date(arr[0],arr[1],arr[2],0,0,0,0); } + return new this._date(date.getFullYear(), date.getMonth(), date.getDate(), arr[0], arr[1], arr[2], 0); + }, + _makeDate: function (str) { + // Date Parser + str = $.trim(((this.__('useArabicIndic') === true)?this._dRep(str, -1):str)); + var w = this, + o = this.options, + adv = w.__fmt(), + exp_input = null, + exp_names = [], + exp_format = null, + exp_temp = null, + date = new w._date(), + d = { year: -1, mont: -1, date: -1, hour: -1, mins: -1, secs: -1, week: false, wtyp: 4, wday: false, yday: false, meri: 0 }, + i; + + if ( typeof o.mode === 'undefined' ) { return date; } + if ( typeof w._parser[o.mode] !== 'undefined' ) { return w._parser[o.mode].apply(w,[str]); } + + if ( o.mode === 'durationbox' || o.mode === 'durationflipbox' ) { + adv = adv.replace(/%D([a-z])/gi, function(match, oper) { + switch (oper) { + case 'd': + case 'l': + case 'M': + case 'S': return '(' + match + '|' +'[0-9]+' + ')'; + default: return '.+?'; + } + }); + + adv = new RegExp('^' + adv + '$'); + exp_input = adv.exec(str); + exp_format = adv.exec(w.__fmt()); + + if ( exp_input === null || exp_input.length !== exp_format.length ) { + if ( typeof o.defaultValue === "number" && o.defaultValue > 0 ) { + return new w._date((w.initDate.getEpoch() + parseInt(o.defaultValue,10))*1000); + } + return new w._date(w.initDate.getTime()); + } + + exp_temp = w.initDate.getEpoch(); + for ( i=0; i -1 ) { d.mont = exp_temp; } + break; + case 'B': + exp_temp = $.inArray(exp_input[i], w.__('monthsOfYear')); + if ( exp_temp > -1 ) { d.mont = exp_temp; } + break; + } + } + if ( d.meri !== 0 ) { + if ( d.meri === -1 && d.hour === 12 ) { d.hour = 0; } + if ( d.meri === 1 && d.hour !== 12 ) { d.hour = d.hour + 12; } + } + + date = new w._date(w._n(d.year,0),w._n(d.mont,0),w._n(d.date,1),w._n(d.hour,0),w._n(d.mins,0),w._n(d.secs,0),0); + + if ( d.year < 100 && d.year !== -1 ) { date.setFullYear(d.year); } + + if ( ( d.mont > -1 && d.date > -1 ) || ( d.hour > -1 && d.mins > -1 && d.secs > -1 ) ) { return date; } + + if ( d.week !== false ) { + date.setDWeek(d.wtyp, d.week); + if ( d.date > -1 ) { date.setDate(d.date); } + } + if ( d.yday !== false ) { date.setD(1,0).setD(2,1).adj(2,(d.yday-1)); } + if ( d.wday !== false ) { date.adj(2,(d.wday - date.getDay())); } + } + return date; + }, + _customformat: { + 'default': function(oper, date) { return false; } + }, + _formatter: function(format, date) { + var w = this, + o = this.options, tmp, + dur = { + part: [0,0,0,0], tp: 0 + }; + + if ( o.mode === 'durationbox' || o.mode === 'durationflipbox' ) { + dur.tp = this.theDate.getEpoch() - this.initDate.getEpoch(); + dur.part[0] = parseInt( dur.tp / (60*60*24),10); dur.tp -=(dur.part[0]*60*60*24); // Days + dur.part[1] = parseInt( dur.tp / (60*60),10); dur.tp -= (dur.part[1]*60*60); // Hours + dur.part[2] = parseInt( dur.tp / (60),10); dur.tp -= (dur.part[2]*60); // Minutes + dur.part[3] = dur.tp; // Seconds + + if ( ! format.match(/%Dd/) ) { dur.part[1] += (dur.part[0]*24);} + if ( ! format.match(/%Dl/) ) { dur.part[2] += (dur.part[1]*60);} + if ( ! format.match(/%DM/) ) { dur.part[3] += (dur.part[2]*60);} + } + + format = format.replace(/%(D|X|0|-)*([1-9a-zA-Z])/g, function(match, pad, oper) { + if ( pad === 'X' ) { + if ( typeof w._customformat[o.mode] !== 'undefined' ) { return w._customformat[o.mode](oper, date, o); } + return match; + } + if ( pad === 'D' ) { + switch ( oper ) { + case 'd': return dur.part[0]; + case 'l': return w._zPad(dur.part[1]); + case 'M': return w._zPad(dur.part[2]); + case 'S': return w._zPad(dur.part[3]); + case 'A': return ((dur.part[0] > 1)?w.__('durationDays')[1]:w.__('durationDays')[0]); + default: return match; + } + } + switch ( oper ) { + case '%': // Literal % + return '%'; + case 'a': // Short Day + return w.__('daysOfWeekShort')[date.getDay()]; + case 'A': // Full Day of week + return w.__('daysOfWeek')[date.getDay()]; + case 'b': // Short month + return w.__('monthsOfYearShort')[date.getMonth()]; + case 'B': // Full month + return w.__('monthsOfYear')[date.getMonth()]; + case 'C': // Century + return date.getFullYear().toString().substr(0,2); + case 'd': // Day of month + return (( pad === '-' ) ? date.getDate() : w._zPad(date.getDate())); + case 'H': // Hour (01..23) + case 'k': + return (( pad === '-' ) ? date.getHours() : w._zPad(date.getHours())); + case 'I': // Hour (01..12) + case 'l': + return (( pad === '-' ) ? ((date.getHours() === 0 || date.getHours() === 12)?12:((date.getHours()<12)?date.getHours():(date.getHours()-12))) : w._zPad(((date.getHours() === 0 || date.getHours() === 12)?12:((date.getHours()<12)?date.getHours():date.getHours()-12)))); + case 'm': // Month + return (( pad === '-' ) ? date.getMonth()+1 : w._zPad(date.getMonth()+1)); + case 'M': // Minutes + return (( pad === '-' ) ? date.getMinutes() : w._zPad(date.getMinutes())); + case 'p': // AM/PM (ucase) + return ((date.getHours() < 12)?w.__('meridiem')[0].toUpperCase():w.__('meridiem')[1].toUpperCase()); + case 'P': // AM/PM (lcase) + return ((date.getHours() < 12)?w.__('meridiem')[0].toLowerCase():w.__('meridiem')[1].toLowerCase()); + case 's': // Unix Seconds + return date.getEpoch(); + case 'S': // Seconds + return (( pad === '-' ) ? date.getSeconds() : w._zPad(date.getSeconds())); + case 'u': // Day of week (1-7) + return (( pad === '-' ) ? date.getDay() + 1 : w._zPad(date.getDay() + 1)); + case 'w': // Day of week + return date.getDay(); + case 'y': // Year (2 digit) + return date.getFullYear().toString().substr(2,2); + case 'Y': // Year (4 digit) + return date.getFullYear(); + case 'E': // BE (Buddist Era, 4 Digit) + return date.getFullYear() + 543; + case 'V': + return (( pad === '-' ) ? date.getDWeek(4) : w._zPad(date.getDWeek(4))); + case 'U': + return (( pad === '-' ) ? date.getDWeek(0) : w._zPad(date.getDWeek(0))); + case 'W': + return (( pad === '-' ) ? date.getDWeek(1) : w._zPad(date.getDWeek(1))); + case 'o': // Ordinals + if ( typeof w._ord[o.useLang] !== 'undefined' ) { return w._ord[o.useLang](date.getDate()); } + return w._ord['default'](date.getDate()); + case 'j': + tmp = new Date(date.getFullYear(),0,1); + tmp = Math.ceil((date - tmp) / 86400000)+1; + return (( tmp < 100 ) ? (( tmp < 10 )? '00' : '0') : '' ) + String(tmp); + case 'G': + if ( date.getDWeek(4) === 1 && date.getMonth() > 0 ) { return date.getFullYear() + 1; } + if ( date.getDWeek(4) > 51 && date.getMonth() < 11 ) { return date.getFullYear() - 1; } + return date.getFullYear(); + case 'g': + if ( date.getDWeek(4) === 1 && date.getMonth() > 0 ) { return parseInt(date.getFullYear().toString().substr(2,2),10) + 1; } + if ( date.getDWeek(4) > 51 && date.getMonth() < 11 ) { return parseInt(date.getFullYear().toString().substr(2,2),10) - 1; } + return date.getFullYear().toString().substr(2,2); + default: + return match; + } + }); + + if ( w.__('useArabicIndic') === true ) { + format = w._dRep(format); + } + + return format; + }, + _btwn: function(value, low, high) { + return ( value > low && value < high ); + }, + _minStepFix: function() { + var tempMin = this.theDate.get(4), tmp, + w = this, + o = this.options; + + if ( o.minuteStep > 1 && tempMin % o.minuteStep > 0 ) { + if ( o.minuteStepRound < 0 ) { + tempMin = tempMin - (tempMin % o.minuteStep); + } else if ( o.minStepRound > 0 ) { + tempMin = tempMin + ( o.minuteStep - ( tempMin % o.minuteStep ) ); + } else { + if ( tempMin % o.minuteStep < o.minuteStep / 2 ) { + tempMin = tempMin - (tempMin % o.minuteStep); + } else { + tempMin = tempMin + ( o.minuteStep - ( tempMin % o.minuteStep ) ); + } + } + w.theDate.setMinutes(tempMin); + } + }, + _offset: function(mode, amount, update) { + // Compute a date/time offset. + // update = false to prevent controls refresh + var w = this, + o = this.options, + ok = false; + + mode = (mode || "").toLowerCase(); + + if ( typeof(update) === "undefined" ) { update = true; } + w.d.input.trigger('datebox', {'method':'offset', 'type':mode, 'amount':amount}); + + if ( mode !== 'a' && ( typeof o.rolloverMode[mode] === 'undefined' || o.rolloverMode[mode] === true )) { + ok = $.inArray(mode, ['y','m','d','h','i','s']); + } else { + switch(mode) { + case 'y': ok = 0; break; + case 'm': + if ( w._btwn(w.theDate.getMonth()+amount,-1,12) ) { ok = 1; } + break; + case 'd': + if ( w._btwn(w.theDate.getDate() + amount,0,(32 - w.theDate.copy([0],[0,0,32,13]).getDate() + 1) )) { ok = 2; } + break; + case 'h': + if ( w._btwn(w.theDate.getHours() + amount,-1,24) ) { ok = 3; } + break; + case 'i': + if ( w._btwn(w.theDate.getMinutes() + amount,-1,60) ) { ok = 4; } + break; + case 's': + if ( w._btwn(w.theDate.getSeconds() + amount,-1,60) ) { ok = 5; } + break; + case 'a': + w._offset('h',((amount>0)?1:-1)*12,false); + break; + } + } + if ( ok !== false ) { w.theDate.adj(ok,amount); } + if ( update === true ) { w.refresh(); } + if ( o.useImmediate ) { w.d.input.trigger('datebox', {'method':'doset'}); } + }, + _startOffset: function(date) { + var o = this.options; + + if ( o.startOffsetYears !== false ) { + date.adj(0, o.startOffsetYears); + } + if ( o.startOffsetMonths !== false ) { + date.adj(1, o.startOffsetMonths); + } + if ( o.startOffsetDays !== false ) { + date.adj(2, o.startOffsetDays); + } + return date; + }, + _create: function() { + // Create the widget, called automatically by widget system + $( document ).trigger( "dateboxcreate" ); + + var w = this, + o = $.extend(this.options, (typeof this.element.jqmData('options') !== 'undefined') ? this.element.jqmData('options') : this._getLongOptions(this.element) ), + thisTheme = ( o.theme === false && typeof($(this).jqmData('theme')) === 'undefined' ) ? + ( ( typeof(this.element.parentsUntil(':jqmData(theme)').parent().jqmData('theme')) === 'undefined' ) ? + o.themeDefault : this.element.parentsUntil(':jqmData(theme)').parent().jqmData('theme') ) + : o.theme, + trans = o.useAnimation ? o.transition : 'none', + d = o.useNewStyle === false ? { + input: this.element, + wrap: this.element.wrap('
              ').parent(), + mainWrap: $("
              ", { "class": 'ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden '+trans+' ui-body-'+thisTheme} ).css('zIndex', o.zindex), + intHTML: false + } : { + input: this.element, + wrap: this.element, + mainWrap: $("
              ", { "class": 'ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden '+trans+' ui-body-'+thisTheme} ).css('zIndex', o.zindex), + intHTML: false + }, + touch = ( typeof window.ontouchstart !== 'undefined' ), + drag = { + eStart : (touch ? 'touchstart' : 'mousedown')+'.datebox', + eMove : (touch ? 'touchmove' : 'mousemove')+'.datebox', + eEnd : (touch ? 'touchend' : 'mouseup')+'.datebox', + eEndA : (touch ? 'mouseup.datebox touchend.datebox touchcancel.datebox touchmove.datebox' : 'mouseup.datebox'), + move : false, + start : false, + end : false, + pos : false, + target : false, + delta : false, + tmp : false + }, + calc = { }, + ns = (typeof $.mobile.ns !== 'undefined')?$.mobile.ns:''; + + $.extend(w, {d: d, ns: ns, drag: drag, touch:touch}); + + if ( o.usePlaceholder !== false ) { + if ( o.usePlaceholder === true && w._grabLabel() !== false ) { w.d.input.attr('placeholder', w._grabLabel()); } + if ( typeof o.usePlaceholder === 'string' ) { w.d.input.attr('placeholder', o.usePlaceholder); } + } + + o.theme = thisTheme; + + w.clearFunc = false; + w.disabled = false; + w.runButton = false; + w._date = window.Date; + w._enhanceDate(); + w.baseID = w.d.input.attr('id'); + + w.initDate = new w._date(); + w.theDate = (o.defaultValue) ? w._makeDate(o.defaultValue) : ( (w.d.input.val() !== "") ? w._makeDate(w.d.input.val()) : new w._date() ); + w.initDone = false; + + if ( o.showInitialValue === true ) { + w.d.input.val(w._formatter(w.__fmt(), w.theDate)); + } + + if ( o.useButton === true && o.useInline === false && o.useNewStyle === false ) { + w.d.open = $(''+this.__('tooltip')+'') + .on(o.clickEvent, function(e) { + e.preventDefault(); + if ( !w.disabled ) { w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.parent().addClass('ui-focus'); w.d.input.parent().removeClass('ui-focus'); } + setTimeout( function() { $(e.target).closest('a').removeClass($.mobile.activeBtnClass); }, 300); + }).appendTo(w.d.wrap).buttonMarkup({icon: 'grid', iconpos: 'notext', corners:true, shadow:true}) + .css({'vertical-align': 'middle', 'display': 'inline-block'}); + } + + w.d.screen = $("
              ", {'class':'ui-datebox-screen ui-datebox-hidden'+((o.useModal)?' ui-datebox-screen-modal':'')}) + .css({'z-index': o.zindex-1}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.trigger('datebox', {'method':'close'}); + }); + + if ( o.enhanceInput === true && navigator.userAgent.match(/Android/i) ){ + w.inputType = 'number'; + } else { + w.inputType = 'text'; + } + + if ( o.hideInput ) { w.d.wrap.parent().hide(); } + + if ( o.mobVer < 140 ) { + $('label[for=\''+w.d.input.attr('id')+'\']').addClass('ui-input-text').css('verticalAlign', 'middle'); + } + + w.d.wrap.on(o.clickEvent, function() { + if ( !w.disabled && ( o.noButtonFocusMode || o.focusMode ) ) { + w.d.input.trigger('datebox', {'method': 'open'}); + w.d.wrap.addClass('ui-focus'); + w.d.input.removeClass('ui-focus'); + } + }); + + w.d.input + .removeClass('ui-corner-all ui-shadow-inset') + .bind(w.touch?'touchend':'click', function(e){ + if ( w.disabled === false && o.useNewStyle === true && o.useFocus === false ) { + if ( ((w.touch ? e.originalEvent.changedTouches[0].pageX : e.pageX) - e.target.offsetLeft) > (e.target.offsetWidth - 20) ) { + w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.parent().addClass('ui-focus'); w.d.input.removeClass('ui-focus'); + //setTimeout(function(){w.d.wrap.addClass('ui-focus');}, 200); + } + } + }) + .focus(function(){ + if ( w.disabled === false && o.useFocus === true ) { + w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.addClass('ui-focus'); w.d.input.removeClass('ui-focus'); + if ( o.useNewStyle === false ) { w.d.input.parent().removeClass('ui-focus'); w.d.wrap.parent().addClass('ui-focus'); } + } + if ( o.useNewStyle === false ) { w.d.input.removeClass('ui-focus'); } + }) + .blur(function(){ + w.d.wrap.removeClass('ui-focus'); + w.d.input.removeClass('ui-focus'); + }) + .change(function() { + w.theDate = w._makeDate(w.d.input.val()); + w.refresh(); + }) + .attr("readonly", o.lockInput) + .on('datebox', w._event); + + if ( o.useNewStyle === true ) { + w.d.input.addClass('ui-corner-all '+((o.useAltIcon===true)?'ui-icon-datebox-alt':'ui-icon-datebox')); + if ( o.overrideStyleClass !== false ) { w.d.input.addClass(o.overrideStyleClass); } + } else { + w.d.input.parent().css('border', 'none').removeClass('ui-shadow-inset'); + } + + w.d.wrap.parent().on(o.clickEvent, function() { + if ( !w.disabled && o.useFocus === true && o.useNewStyle === false ) { + w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.addClass('ui-focus'); w.d.input.removeClass('ui-focus'); + setTimeout(function(){ + w.d.wrap.removeClass('ui-focus'); + w.d.wrap.parent().addClass('ui-focus'); + }, 500); + } + }); + + // Check if mousewheel plugin is loaded + if ( typeof $.event.special.mousewheel !== 'undefined' ) { w.wheelExists = true; } + + // Disable when done if element attribute disabled is true. + if ( w.d.input.is(':disabled') ) { + w.disable(); + } + + if ( o.useInline === true || o.useInlineBlind ) { w.open(); } + + w.applyMinMax(false, false); + + //Throw dateboxinit event + $( document ).trigger( "dateboxaftercreate" ); + }, + applyMinMax: function(refresh, override) { + var w = this, + o = this.options, + calc = {}; + + if ( typeof refresh === 'undefined' ) { refresh = false; } + if ( typeof override === 'undefined' ) { override = true; } + + if ( ( override === true || o.minDays === false ) && typeof(w.d.input.attr('min')) !== 'undefined' ) { + calc.today = new w._date(); + calc.lod = 24 * 60 * 60 * 1000; + calc.todayc = new w._date(calc.today.getFullYear(), calc.today.getMonth(), calc.today.getDate(), 0,0,0,0); + calc.fromel = w.d.input.attr('min').split('-'); + calc.compdt = new w._date(calc.fromel[0],calc.fromel[1]-1,calc.fromel[2],0,0,0,0); + o.minDays = parseInt((((calc.compdt.getTime() - calc.todayc.getTime()) / calc.lod))*-1,10); + } + if ( ( override === true || o.maxDays === false ) && typeof(w.d.input.attr('max')) !== 'undefined' ) { + calc.today = new w._date(); + calc.lod = 24 * 60 * 60 * 1000; + calc.todayc = new w._date(calc.today.getFullYear(), calc.today.getMonth(), calc.today.getDate(), 0,0,0,0); + calc.fromel = w.d.input.attr('max').split('-'); + calc.compdt = new w._date(calc.fromel[0],calc.fromel[1]-1,calc.fromel[2],0,0,0,0); + o.maxDays = parseInt((((calc.compdt.getTime() - calc.todayc.getTime()) / calc.lod)),10); + } + + if ( refresh === true ) { w.refresh(); } + }, + _build: { + 'default': function () { + this.d.headerText = "Error"; + this.d.intHTML = $("

              There is no mode by that name loaded / mode not given

              "); + } + }, + _applyCoords: function(e) { + var w = e.widget, + o = e.widget.options, + fixd = { + h: $.mobile.activePage.find('.ui-header').jqmData('position'), + f: $.mobile.activePage.find('.ui-footer').jqmData('position'), + fh: $.mobile.activePage.find('.ui-footer').outerHeight(), + hh: $.mobile.activePage.find('.ui-header').outerHeight() + }, + iput = { + x: w.d.wrap.offset().left + (w.d.wrap.outerWidth() / 2), + y: w.d.wrap.offset().top + (w.d.wrap.outerHeight() / 2) + }, + size = { + w: w.d.mainWrap.outerWidth(), + h: w.d.mainWrap.outerHeight() + }, + doc = { + t: $(window).scrollTop(), + h: $(window).height(), + w: $.mobile.activePage.width(), + ah: $(document).height() + }, + pos = { + y: (o.centerVert) ? doc.t + ((doc.h / 2) - (size.h / 2)) : iput.y - ( size.h / 2 ), + x: (doc.w < 400 || o.centerHoriz ) ? (doc.w / 2) - (size.w /2) : iput.x - (size.w / 2) + }; + + if ( o.centerVert === false ) { + if ( o.hideFixedToolbars === true && ( typeof fixd.f !== 'undefined' || typeof fixd.h !== 'undefined' )) { + $.mobile.activePage.find(":jqmData(position='fixed')").fixedtoolbar('hide'); + fixd.f = undefined; + fixd.h = undefined; + } + + if ( typeof fixd.f !== 'undefined' ) { + if ( ( pos.y + size.h ) > ( doc.h - fixd.fh - 2 ) ) { + pos.y = doc.h - fixd.fh - 2 - size.h; + } + } else { + if ( ( pos.y + size.h ) > ( doc.ah - fixd.fh - 2 ) ) { + pos.y = doc.ah - fixd.fh - 2 - size.h; + } + if ( ( doc.h + doc.t ) < ( size.h + pos.y + 2 ) ) { + pos.y = doc.h + doc.t - size.h - 2; + } + } + + if ( typeof fixd.h !== 'undefined' ) { + if ( ( doc.t + fixd.hh + 2 ) > pos.y ) { + pos.y = doc.t + fixd.hh + 2; + } + } else { + if ( fixd.hh + 2 > pos.y ) { + pos.y = fixd.hh + 2; + } + if ( pos.y < doc.t + 2 ) { + pos.y = doc.t + 2; + } + } + } + w.d.mainWrap.css({'position': 'absolute', 'top': pos.y, 'left': pos.x}); + }, + _drag: { + 'default': function () { return false; } + }, + open: function () { + var w = this, + o = this.options, + popopts = {}, + basepop = {'history':false}, + qns = 'data-'+this.ns, + trans = o.useAnimation ? o.transition : 'none'; + + if ( o.useFocus === true && w.fastReopen === true ) { w.d.input.blur(); return false; } + if ( w.clearFunc !== false ) { + clearTimeout(w.clearFunc); w.clearFunc = false; + } + + // Call the open callback if provided. Additionally, if this + // returns false then the open/update will stop. + if ( o.openCallback !== false ) { + if ( ! $.isFunction(o.openCallback) ) { + if ( typeof window[o.openCallback] !== 'undefined' ) { + o.openCallback = window[o.openCallback]; + } else { + o.openCallback = new Function(o.openCallback); + } + } + if ( o.openCallback.apply(w, $.merge([w.theDate],o.openCallbackArgs)) === false ) { return false; } + } + + w.theDate = w._makeDate(w.d.input.val()); + if ( w.d.input.val() === "" ) { w._startOffset(w.theDate); } + w.d.input.blur(); + + if ( typeof w._build[o.mode] === 'undefined' ) { + w._build['default'].apply(w,[]); + } else { + w._build[o.mode].apply(w,[]); + } + if ( typeof w._drag[o.mode] !== 'undefined' ) { + w._drag[o.mode].apply(w, []); + } + w.d.input.trigger('datebox', {'method':'refresh'}); + if ( w.__('useArabicIndic') === true ) { w._doIndic(); } + + if ( ( o.useInline === true || o.useInlineBlind === true ) && w.initDone === false ) { + w.d.mainWrap.append(w.d.intHTML); + w.d.input.parent().parent().append(w.d.mainWrap); + w.d.mainWrap.removeClass('ui-datebox-hidden'); + if ( o.useInline === true ) { + w.d.mainWrap.addClass('ui-datebox-inline'); + } else { + w.d.mainWrap.addClass('ui-datebox-inlineblind'); + w.d.mainWrap.hide(); + } + w.initDone = false; + w.d.input.trigger('datebox',{'method':'postrefresh'}); + } + + if ( o.useImmediate ) { w.d.input.trigger('datebox', {'method':'doset'}); } + if ( o.useInline ) { return true; } + if ( o.useInlineBlind ) { + if ( w.initDone ) { w.d.mainWrap.slideDown(); } + else { w.initDone = true; } + return true; + } + if ( w.d.intHTML.is(':visible') ) { return false; } // Ignore if already open + + if ( o.enablePopup === true ) { + w.d.dialogPage = false; + w.d.mainWrap.empty(); + if ( o.useHeader === true ) { + w.d.headHTML = $('
              '); + $("Close").appendTo(w.d.headHTML) + .buttonMarkup({ theme : o.themeHeader, icon : 'delete', iconpos: 'notext', corners: true, shadow : true }) + .on(o.clickEventAlt, function(e) { e.preventDefault(); w.d.input.trigger('datebox', {'method':'close'}); }); + $('

              '+w.d.headerText+'

              ').appendTo(w.d.headHTML); + w.d.mainWrap.append(w.d.headHTML); + } + w.d.mainWrap.append(w.d.intHTML).css('zIndex', o.zindex); + w.d.input.trigger('datebox',{'method':'postrefresh'}); + + if ( o.useAnimation === true ) { + popopts.transition = o.transition; + } else { + popopts.transition = "none"; + } + + if ( o.popupForceX !== false && o.popupForceY !== false ) { + popopts.x = o.popupForceX; + popopts.y = o.popupForceY; + } + + if ( o.popupPosition !== false ) { + popopts.positionTo = o.popupPosition; + } else { + if ( typeof w.baseID !== undefined ) { + popopts.positionTo = '#' + w.baseID; + } else { + popopts.positionTo = 'window'; + } + } + + if ( o.useModal === true ) { basepop.overlayTheme = "a"; } + + w.d.mainWrap.removeClass('ui-datebox-hidden').popup(basepop).popup("open", popopts); + w.refresh(); + } else { + if ( o.dialogForce || ( o.dialogEnable && window.width() < 400 ) ) { + w.d.dialogPage = $("
              " + + "
              " + + "

              "+w.d.headerText+"

              ") + .appendTo( $.mobile.pageContainer ) + .page().css('minHeight', '0px').addClass(trans); + w.d.dialogPage.find('.ui-header').find('a').off('click vclick').on(o.clickEventAlt, function(e) { e.preventDefault(); w.d.input.trigger('datebox', {'method':'close'}); }); + w.d.mainWrap.append(w.d.intHTML).css({'marginLeft':'auto', 'marginRight':'auto'}).removeClass('ui-datebox-hidden'); + w.d.dialogPage.find('.ui-content').append(w.d.mainWrap); + w.d.input.trigger('datebox',{'method':'postrefresh'}); + $.mobile.activePage.off( "pagehide.remove" ); + $.mobile.changePage(w.d.dialogPage, {'transition': trans}); + } else { + w.d.dialogPage = false; + w.d.mainWrap.empty(); + if ( o.useHeader === true ) { + w.d.headHTML = $('
              '); + $("Close").appendTo(w.d.headHTML) + .buttonMarkup({ theme : o.themeHeader, icon : 'delete', iconpos: 'notext', corners: true, shadow : true }) + .on(o.clickEventAlt, function(e) { e.preventDefault(); w.d.input.trigger('datebox', {'method':'close'}); }); + $('

              '+w.d.headerText+'

              ').appendTo(w.d.headHTML); + w.d.mainWrap.append(w.d.headHTML); + } + w.d.mainWrap.append(w.d.intHTML).css('zIndex', o.zindex); + w.d.mainWrap.appendTo($.mobile.activePage); + w.d.screen.appendTo($.mobile.activePage); + w.d.input.trigger('datebox',{'method':'postrefresh'}); + w._applyCoords({widget:w}); + + if ( o.useModal === true ) { + if(o.useAnimation) { + w.d.screen.fadeIn('slow'); + } else { + w.d.screen.show(); + } + } else { + setTimeout(function () { w.d.screen.removeClass('ui-datebox-hidden');}, 500); + } + + w.d.mainWrap.addClass('ui-overlay-shadow in').removeClass('ui-datebox-hidden'); + + $(document).on('orientationchange.datebox', {widget:w}, function(e) { w._applyCoords(e.data); }); + if ( o.resizeListener === true ) { + $(window).on('resize.datebox', {widget:w}, function (e) { w._applyCoords(e.data); }); + } + } + } + }, + close: function() { + var w = this, + o = this.options; + + if ( o.useInlineBlind === true ) { w.d.mainWrap.slideUp(); return true;} + if ( o.useInline === true || w.d.intHTML === false ) { return true; } + + if ( w.d.dialogPage !== false ) { + $(w.d.dialogPage).dialog('close'); + + if ( ! $.mobile.activePage.jqmData('mobile-page').options.domCache ) { + $.mobile.activePage.on('pagehide.remove', function () { $(this).remove(); }); + } + + w.d.intHTML.detach().empty(); + w.d.mainWrap.detach().empty(); + w.d.wrap.removeClass('ui-focus'); + w.clearFunc = setTimeout(function () { w.d.dialogPage.empty().remove(); w.clearFunc = false; }, 1500); + } else { + if ( o.enablePopup === true ) { + w.d.mainWrap.popup('close'); + w.d.wrap.removeClass('ui-focus'); + } else { + if ( o.useModal ) { + if(o.useAnimation) { + w.d.screen.fadeOut('slow'); + } else { + w.d.screen.hide(); + } + } else { + w.d.screen.addClass('ui-datebox-hidden'); + } + w.d.screen.detach(); + w.d.mainWrap.addClass('ui-datebox-hidden').removeAttr('style').removeClass('in ui-overlay-shadow').empty().detach(); + w.d.intHTML.detach(); + w.d.wrap.removeClass('ui-focus'); + + $(document).off('orientationchange.datebox'); + if ( o.resizeListener === true ) { + $(window).off('resize.datebox'); + } + } + } + w.d.wrap.parent().removeClass('ui-focus'); + + $(document).off(w.drag.eMove); + $(document).off(w.drag.eEnd); + $(document).off(w.drag.eEndA); + + if ( o.useFocus ) { + w.fastReopen = true; + setTimeout(function(t) { return function () { t.fastReopen = false; };}(w), 300); + } + + if ( o.closeCallback !== false ) { + if ( ! $.isFunction(o.closeCallback) ) { + if ( typeof window[o.closeCallback] !== 'undefined' ) { + o.closeCallback = window[o.closeCallback]; + } else { + o.closeCallback = new Function(o.closeCallback); + } + } + o.closeCallback.apply(w, $.merge([w.theDate], o.closeCallbackArgs)); + } + }, + refresh: function() { + if ( typeof this._build[this.options.mode] === 'undefined' ) { + this._build['default'].apply(this,[]); + } else { + this._build[this.options.mode].apply(this,[]); + } + if ( this.__('useArabicIndic') === true ) { this._doIndic(); } + this.d.mainWrap.append(this.d.intHTML); + this.d.input.trigger('datebox',{'method':'postrefresh'}); + }, + _check: function() { + var w = this, + td = null, + o = this.options; + + w.dateOK = true; + + if ( o.afterToday !== false ) { + td = new w._date(); + if ( w.theDate < td ) { w.theDate = td; } + } + if ( o.beforeToday !== false ) { + td = new w._date(); + if ( w.theDate > td ) { w.theDate = td; } + } + if ( o.maxDays !== false ) { + td = new w._date(); + td.adj(2, o.maxDays); + if ( w.theDate > td ) { w.theDate = td; } + } + if ( o.minDays !== false ) { + td = new w._date(); + td.adj(2, -1*o.minDays); + if ( w.theDate < td ) { w.theDate = td; } + } + if ( o.minHour !== false ) { + if ( w.theDate.getHours() < o.minHour ) { + w.theDate.setHours(o.minHour); + } + } + if ( o.maxHour !== false ) { + if ( w.theDate.getHours() > o.maxHour ) { + w.theDate.setHours(o.maxHour); + } + } + if ( o.maxYear !== false ) { + td = new w._date(o.maxYear, 0, 1); + td.adj(2, -1); + if ( w.theDate > td ) { w.theDate = td; } + } + if ( o.minYear !== false ) { + td = new w._date(o.minYear, 0, 1); + if ( w.theDate < td ) { w.theDate = td; } + } + + if ( $.inArray(o.mode, ['timebox','durationbox','durationflipbox','timeflipbox']) > -1 ) { + if ( o.mode === 'timeflipbox' && o.validHours !== false ) { + if ( $.inArray(w.theDate.getHours(), o.validHours) < 0 ) { w.dateOK = false; } + } + } else { + if ( o.blackDatesRec !== false ) { + for ( i=0; i -1 ) { w.dateOK = false; } + } + if ( o.blackDays !== false ) { + if ( $.inArray(w.theDate.getDay(), o.blackDays) > -1 ) { w.dateOK = false; } + } + } + }, + _grabLabel: function() { + var w = this, + o = this.options; + + if ( typeof o.overrideDialogLabel === 'undefined' ) { + if ( typeof w.d.input.attr('placeholder') !== 'undefined' ) { return w.d.input.attr('placeholder'); } + if ( typeof w.d.input.attr('title') !== 'undefined' ) { return w.d.input.attr('title'); } + if ( w.d.wrap.parent().find('label[for=\''+w.d.input.attr('id')+'\']').text() !== '' ) { + return w.d.wrap.parent().find('label[for=\''+w.d.input.attr('id')+'\']').text(); + } + return false; + } + return o.overrideDialogLabel; + }, + _makeEl: function(source, parts) { + var part = false, + retty = false; + + retty = source.clone(); + + if ( typeof parts.attr !== 'undefined' ) { + for ( part in parts.attr ) { + if ( parts.attr.hasOwnProperty(part) ) { + retty.jqmData(part, parts.attr[part]); + } + } + } + return retty; + }, + _getLongOptions: function(element) { + var key, retty = {}, prefix, temp; + + if ( $.mobile.ns === "" ) { + prefix = "datebox"; + } else { + prefix = $.mobile.ns.substr(0, $.mobile.ns.length - 1) + 'Datebox'; + } + + for ( key in element.data() ) { + if ( key.substr(0, prefix.length) === prefix && key.length > prefix.length ) { + temp = key.substr(prefix.length); + temp = temp.charAt(0).toLowerCase() + temp.slice(1); + retty[temp] = element.data(key); + } + } + return retty; + }, + disable: function(){ + // Disable the element + this.d.input.attr("disabled",true); + this.d.wrap.addClass("ui-disabled").blur(); + this.disabled = true; + this.d.input.trigger('datebox', {'method':'disable'}); + }, + enable: function(){ + // Enable the element + this.d.input.attr("disabled", false); + this.d.wrap.removeClass("ui-disabled"); + this.disabled = false; + this.d.input.trigger('datebox', {'method':'enable'}); + }, + _setOption: function() { + $.Widget.prototype._setOption.apply( this, arguments ); + this.refresh(); + }, + getTheDate: function() { + return this.theDate; + }, + getLastDur: function() { + return this.lastDuration; + }, + setTheDate: function(newDate) { + this.theDate = newDate; + this.refresh(); + }, + callFormat: function(format, date) { + return this._formatter(format, date); + } + }); + + // Degrade date inputs to text inputs, suppress standard UI functions. + $( document ).on( "pagebeforecreate", function( e ) { + $( ":jqmData(role='datebox')", e.target ).each(function() { + $(this).prop('type', 'text'); + }); + }); + // Automatically bind to data-role='datebox' items. + $( document ).on( "pagecreate create", function( e ){ + $( document ).trigger( "dateboxbeforecreate" ); + $( ":jqmData(role='datebox')", e.target ).each(function() { + var defed = typeof ($(this).data(parseInt($.mobile.version.replace(/\./g,''),10) > 111 ? 'mobile-datebox' : 'datebox')); + if ( defed === "undefined" ) { + $(this).datebox(); + } + }); + }); +})( jQuery ); +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +/* SLIDEBOX Mode */ + +(function($) { + $.extend( $.mobile.datebox.prototype.options, { + themeDateHigh: 'b', + themeDatePick: 'b', + themeDate: 'a', + useSetButton: true, + validHours: false, + slen: {'y': 5, 'm':6, 'd':15, 'h':12, 'i':30} + }); + $.extend( $.mobile.datebox.prototype, { + '_sbox_pos': function () { + var w = this, + ech, top, par, tot; + + w.d.intHTML.find('div.ui-datebox-sliderow-int').each(function () { + ech = $(this); + par = ech.parent().innerWidth(); + if ( w.__('isRTL') ) { + top = ech.find('div').last(); + } else { + top = ech.find('div').first(); + } + tot = ech.find('div').size() * top.outerWidth(); + top.css('marginLeft', ((tot/2)-(par/2))*-1); + }); + } + }); + $.extend( $.mobile.datebox.prototype._build, { + 'slidebox': function () { + var w = this, + o = this.options, i, y, hRow, phRow, tmp, testDate, + iDate = (w.d.input.val() === "") ? w._startOffset(w._makeDate(w.d.input.val())) : w._makeDate(w.d.input.val()), + uid = 'ui-datebox-', + thMod = (( this.options.mobVer < 140 ) ? 'up-' : ''), + slideBase = $("
              "), + phBase = $('
              '), + ctrl = $("
              ", {"class":uid+'slide'}); + + if ( typeof w.d.intHTML !== 'boolean' ) { + w.d.intHTML.empty().remove() + } + + w.d.input.on('datebox', function (e,p) { + if ( p.method === 'postrefresh' ) { w._sbox_pos(); } + }); + + w.d.headerText = ((w._grabLabel() !== false)?w._grabLabel():w.__('titleDateDialogLabel')); + w.d.intHTML = $('') + + w.fldOrder = w.__('slideFieldOrder'); + w._check(); + w._minStepFix(); + + $('

              '+w._formatter(w.__('headerFormat'), w.theDate)+'

              ').appendTo(w.d.intHTML); + + w.d.intHTML.append(ctrl); + + for ( y=0; y', {'class':uid+'slideyear ui-corner-all ui-btn ui-btn-'+thMod+tmp}) + .html(w.theDate.get(0)+i).jqmData('offset', i).jqmData('theme', tmp).appendTo(hRow); + } + break; + case 'm': + phRow.addClass(uid+'sliderow-ym'); + for ( i=o.slen.m*-1; i<(o.slen.m+1); i++ ) { + testDate = w.theDate.copy([0],[0,0,1]); + testDate.adj(1,i); + tmp = (i!==0)?((iDate.get(1) === testDate.get(1) && iDate.get(0) === testDate.get(0))?o.themeDateHigh:o.themeDate):o.themeDatePick; + $('
              ', {'class':uid+'slidemonth ui-corner-all ui-btn ui-btn-'+thMod+tmp}) + .html(String(w.__('monthsOfYearShort')[testDate.get(1)])) + .jqmData('offset', i) + .jqmData('theme', tmp).appendTo(hRow); + } + break; + + case 'd': + phRow.addClass(uid+'sliderow-d'); + for ( i=o.slen.d*-1; i<(o.slen.d+1); i++ ) { + testDate = w.theDate.copy(); + testDate.adj(2,i); + tmp = (i!==0)?((iDate.comp() === testDate.comp())?o.themeDateHigh:o.themeDate):o.themeDatePick; + if ( ( o.blackDates !== false && $.inArray(testDate.iso(), o.blackDates) > -1 ) || + ( o.blackDays !== false && $.inArray(testDate.getDay(), o.blackDays) > -1 ) ) { + tmp += ' '+uid+'griddate-disable'; + } + $('
              ', {'class':uid+'slideday ui-corner-all ui-btn ui-btn-'+thMod+tmp}) + .html(testDate.get(2) + '
              ' + w.__('daysOfWeekShort')[testDate.getDay()] + '') + .jqmData('offset', i).jqmData('theme', tmp).appendTo(hRow); + } + break; + case 'h': + phRow.addClass(uid+'sliderow-hi'); + for ( i=o.slen.h*-1; i<(o.slen.h+1); i++ ) { + testDate = w.theDate.copy(); + testDate.adj(3,i); + tmp = (i!==0)?o.themeDate:o.themeDatePick; + if ( o.validHours !== false && $.inArray(testDate.get(3), o.validHours) < 0 ) { + tmp += ' '+uid+'griddate-disable'; + } + $('
              ', {'class':uid+'slidehour ui-corner-all ui-btn ui-btn-'+thMod+tmp}) + .html( w.__('timeFormat') === 12 ? w._formatter('%I%p', testDate) : testDate.get(3) ) + .jqmData('offset', i).jqmData('theme', tmp).appendTo(hRow); + } + break; + case 'i': + phRow.addClass(uid+'sliderow-hi'); + for ( i=o.slen.i*-1; i<(o.slen.i+1); i++ ) { + testDate = w.theDate.copy(); + testDate.adj(4,(i*o.minuteStep)); + tmp = (i!==0)?o.themeDate:o.themeDatePick; + $('
              ', {'class':uid+'slidemins ui-corner-all ui-btn ui-btn-'+thMod+tmp}) + .html(w._zPad(testDate.get(4))).jqmData('offset', i*o.minuteStep).jqmData('theme', tmp).appendTo(hRow); + } + break; + } + phRow.appendTo(ctrl); + } + + if ( o.useSetButton || o.useClearButton ) { + y = $('
              ', {'class':uid+'controls'}); + + if ( o.useSetButton ) { + $(''+w.__('setDateButtonLabel')+'') + .appendTo(y).buttonMarkup({theme: o.theme, icon: 'check', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + if ( w.dateOK === true ) { + w.d.input.trigger('datebox', {'method':'set', 'value':w._formatter(w.__fmt(),w.theDate), 'date':w.theDate}); + w.d.input.trigger('datebox', {'method':'close'}); + } + }); + } + if ( o.useClearButton ) { + $(''+w.__('clearButton')+'') + .appendTo(y).buttonMarkup({theme: o.theme, icon: 'delete', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.val(''); + w.d.input.trigger('datebox',{'method':'clear'}); + w.d.input.trigger('datebox',{'method':'close'}); + }); + } + if ( o.useCollapsedBut ) { + y.addClass('ui-datebox-collapse'); + } + y.appendTo(w.d.intHTML); + } + + if ( w.wheelExists ) { // Mousewheel operation, if plugin is loaded + w.d.intHTML.on('mousewheel', '.ui-datebox-sliderow-int', function(e,d) { + e.preventDefault(); + w._offset($(this).jqmData('rowtype'), ((d<0)?-1:1)*($(this).jqmData('rowtype')==='i'?o.minuteStep:1)); + }); + } + + w.d.intHTML.on(o.clickEvent, '.ui-datebox-sliderow-int>div', function(e) { + e.preventDefault(); + w._offset($(this).parent().jqmData('rowtype'), parseInt($(this).jqmData('offset'),10)); + }); + w.d.intHTML.on('vmouseover vmouseout', '.ui-datebox-sliderow-int>div', function() { + w._hoover(this); + }); + + w.d.intHTML.on(w.drag.eStart, '.ui-datebox-sliderow-int', function(e) { + if ( !w.drag.move ) { + w.drag.move = true; + w.drag.target = $(this); + w.drag.pos = parseInt(w.drag.target.css('marginLeft').replace(/px/i, ''),10); + w.drag.start = w.touch ? e.originalEvent.changedTouches[0].pageX : e.pageX; + w.drag.end = false; + e.stopPropagation(); + e.preventDefault(); + } + }); + } + }); + $.extend( $.mobile.datebox.prototype._drag, { + 'slidebox': function() { + var w = this, + o = this.options, + g = this.drag; + + $(document).on(g.eMove, function(e) { + if ( g.move && o.mode === 'slidebox') { + g.end = w.touch ? e.originalEvent.changedTouches[0].pageX : e.pageX; + g.target.css('marginLeft', (g.pos + g.end - g.start) + 'px'); + e.preventDefault(); + e.stopPropagation(); + return false; + } + }); + + $(document).on(g.eEnd, function(e) { + if ( g.move && o.mode === 'slidebox' ) { + g.move = false; + if ( g.end !== false ) { + e.preventDefault(); + e.stopPropagation(); + g.tmp = g.target.find('div').first(); + w._offset(g.target.jqmData('rowtype'), ( w.__('isRTL') ? -1 : 1 )*(parseInt((g.start - g.end) / g.tmp.innerWidth(),10))*(g.target.jqmData('rowtype')==='i'?o.minuteStep:1)); + } + g.start = false; + g.end = false; + } + }); + } + }); +})( jQuery ); diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.slidebox.min.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.slidebox.min.js new file mode 100644 index 000000000..80d233809 --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.comp.slidebox.min.js @@ -0,0 +1,7 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +(function(a){a.widget("mobile.datebox",a.mobile.widget,{options:{version:"2-1.4.0-2013070300",mobVer:parseInt(a.mobile.version.replace(/\./g,"")),theme:false,themeDefault:"a",themeHeader:"a",mode:false,centerHoriz:false,centerVert:false,transition:"pop",useAnimation:true,hideInput:false,hideFixedToolbars:false,lockInput:true,enhanceInput:true,zindex:"500",clickEvent:"vclick",clickEventAlt:"click",resizeListener:true,defaultValue:false,showInitialValue:false,dialogEnable:false,dialogForce:false,enablePopup:false,popupPosition:false,popupForceX:false,popupForceY:false,useModal:false,useInline:false,useInlineBlind:false,useHeader:true,useImmediate:false,useNewStyle:false,useAltIcon:false,overrideStyleClass:false,useButton:true,useFocus:false,useClearButton:false,useCollapsedBut:false,usePlaceholder:false,openCallback:false,openCallbackArgs:[],closeCallback:false,closeCallbackArgs:[],startOffsetYears:false,startOffsetMonths:false,startOffsetDays:false,afterToday:false,beforeToday:false,notToday:false,maxDays:false,minDays:false,maxYear:false,minYear:false,blackDates:false,blackDatesRec:false,blackDays:false,minHour:false,maxHour:false,minuteStep:1,minuteStepRound:0,rolloverMode:{m:true,d:true,h:true,i:true,s:true},useLang:"default",lang:{"default":{setDateButtonLabel:"Set Date",setTimeButtonLabel:"Set Time",setDurationButtonLabel:"Set Duration",calTodayButtonLabel:"Jump to Today",titleDateDialogLabel:"Set Date",titleTimeDialogLabel:"Set Time",daysOfWeek:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],daysOfWeekShort:["Su","Mo","Tu","We","Th","Fr","Sa"],monthsOfYear:["January","February","March","April","May","June","July","August","September","October","November","December"],monthsOfYearShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],durationLabel:["Days","Hours","Minutes","Seconds"],durationDays:["Day","Days"],timeFormat:24,headerFormat:"%A, %B %-d, %Y",tooltip:"Open Date Picker",nextMonth:"Next Month",prevMonth:"Previous Month",dateFieldOrder:["m","d","y"],timeFieldOrder:["h","i","a"],slideFieldOrder:["y","m","d"],dateFormat:"%Y-%m-%d",useArabicIndic:false,isRTL:false,calStartDay:0,clearButton:"Clear",durationOrder:["d","h","i","s"],meridiem:["AM","PM"],timeOutput:"%k:%M",durationFormat:"%Dd %DA, %Dl:%DM:%DS",calDateListLabel:"Other Dates",calHeaderFormat:"%B %Y"}}},_enhanceDate:function(){a.extend(this._date.prototype,{copy:function(c,b){if(typeof c==="undefined"){c=[0,0,0,0,0,0,0]}if(typeof b==="undefined"){b=[0,0,0,0,0,0,0]}while(c.length<7){c.push(0)}while(b.length<7){b.push(0)}return new Date(((b[0]>0)?b[0]:this.getFullYear()+c[0]),((b[1]>0)?b[1]:this.getMonth()+c[1]),((b[2]>0)?b[2]:this.getDate()+c[2]),((b[3]>0)?b[3]:this.getHours()+c[3]),((b[4]>0)?b[4]:this.getMinutes()+c[4]),((b[5]>0)?b[5]:this.getSeconds()+c[5]),((b[6]>0)?b[5]:this.getMilliseconds()+c[6]))},adj:function(c,b){if(typeof b!=="number"){throw new Error("Adjustment value not specified")}if(typeof c!=="number"){throw new Error("Adjustment type not specified")}switch(c){case 0:this.setFullYear(this.getFullYear()+b);break;case 1:this.setMonth(this.getMonth()+b);break;case 2:this.setDate(this.getDate()+b);break;case 3:this.setHours(this.getHours()+b);break;case 4:this.setMinutes(this.getMinutes()+b);break;case 5:this.setSeconds(this.getSeconds()+b);break;case 6:this.setMilliseconds(this.getMilliseconds()+b);break}return this},setD:function(c,b){switch(c){case 0:this.setFullYear(b);break;case 1:this.setMonth(b);break;case 2:this.setDate(b);break;case 3:this.setHours(b);break;case 4:this.setMinutes(b);break;case 5:this.setSeconds(b);break;case 6:this.setMilliseconds(b);break}return this},get:function(b){switch(b){case 0:return this.getFullYear();case 1:return this.getMonth();case 2:return this.getDate();case 3:return this.getHours();case 4:return this.getMinutes();case 5:return this.getSeconds()}return false},iso:function(){return String(this.getFullYear())+"-"+((this.getMonth()<9)?"0":"")+String(this.getMonth()+1)+"-"+((this.getDate()<10)?"0":"")+String(this.getDate())},comp:function(){return parseInt(this.iso().replace(/-/g,""),10)},getEpoch:function(){return(this.getTime()-this.getMilliseconds())/1000},getArray:function(){return[this.getFullYear(),this.getMonth(),this.getDate(),this.getHours(),this.getMinutes(),this.getSeconds()]},setFirstDay:function(b){this.setD(2,1).adj(2,(b-this.getDay()));if(this.get(2)>10){this.adj(2,7)}return this},setDWeek:function(c,b){if(c===4){return this.setD(1,0).setD(2,1).setFirstDay(4).adj(2,-3).adj(2,(b-1)*7)}return this.setD(1,0).setD(2,1).setFirstDay(c).adj(2,(b-1)*7)},getDWeek:function(c){var d,b;switch(c){case 0:d=this.copy([0,-1*this.getMonth()]).setFirstDay(0);return Math.floor((this.getTime()-(d.getTime()+((this.getTimezoneOffset()-d.getTimezoneOffset())*60000)))/604800000)+1;case 1:d=this.copy([0,-1*this.getMonth()]).setFirstDay(1);return Math.floor((this.getTime()-(d.getTime()+((this.getTimezoneOffset()-d.getTimezoneOffset())*60000)))/604800000)+1;case 4:if(this.getMonth()===11&&this.getDate()>28){return 1}d=this.copy([0,-1*this.getMonth()],true).setFirstDay(4).adj(2,-3);b=Math.floor((this.getTime()-(d.getTime()+((this.getTimezoneOffset()-d.getTimezoneOffset())*60000)))/604800000)+1;if(b<1){d=this.copy([-1,-1*this.getMonth()]).setFirstDay(4).adj(2,-3);return Math.floor((this.getTime()-d.getTime())/604800000)+1}return b;default:return 0}}})},_event:function(d,c){var b=a(this).data(parseInt(a.mobile.version.replace(/\./g,""),10)>110?"mobile-datebox":"datebox");if(!d.isPropagationStopped()){switch(c.method){case"close":b.close();break;case"open":b.open();break;case"set":a(this).val(c.value);a(this).trigger("change");break;case"doset":if(a.isFunction(b["_"+b.options.mode+"DoSet"])){b["_"+b.options.mode+"DoSet"].apply(b,[])}else{a(this).trigger("datebox",{method:"set",value:b._formatter(b.__fmt(),b.theDate),date:b.theDate})}break;case"dooffset":if(c.type){b._offset(c.type,c.amount,true)}break;case"dorefresh":b.refresh();break;case"doreset":b.hardreset();break;case"doclear":a(this).val("").trigger("change");break;case"clear":a(this).trigger("change")}}},_hoover:function(b){a(b).toggleClass("ui-btn-up-"+a(b).jqmData("theme")+" ui-btn-down-"+a(b).jqmData("theme"))},_ord:{"default":function(c){var b=c%10;if(c>9&&c<21){return"th"}if(b>3){return"th"}return["th","st","nd","rd"][b]}},__:function(d){var c=this.options,b="override"+d.charAt(0).toUpperCase()+d.slice(1);if(typeof c[b]!=="undefined"){return c[b]}if(typeof c.lang[c.useLang][d]!=="undefined"){return c.lang[c.useLang][d]}if(typeof c[c.mode+"lang"]!=="undefined"&&typeof c[c.mode+"lang"][d]!=="undefined"){return c[c.mode+"lang"][d]}return c.lang["default"][d]},__fmt:function(){var b=this,c=this.options;switch(c.mode){case"timebox":case"timeflipbox":return b.__("timeOutput");case"durationbox":case"durationflipbox":return b.__("durationFormat");default:return b.__("dateFormat")}},_zPad:function(b){return((b<10)?"0"+String(b):String(b))},_dRep:function(j,g){var h=48,b=57,c=1584,d=null,e=null,f="";if(g===-1){h+=c;b+=c;c=-1584}for(d=0;d=h&&e<=b){f=f+String.fromCharCode(e+c)}else{f=f+String.fromCharCode(e)}}return f},_doIndic:function(){var b=this;b.d.intHTML.find("*").each(function(){if(a(this).children().length<1){a(this).text(b._dRep(a(this).text()))}else{if(a(this).hasClass("ui-datebox-slideday")){a(this).html(b._dRep(a(this).html()))}}});b.d.intHTML.find("input").each(function(){a(this).val(b._dRep(a(this).val()))})},_parser:{"default":function(b){return false}},_n:function(c,b){return(c<0)?b:c},_pa:function(b,c){if(typeof c==="boolean"){return new this._date(b[0],b[1],b[2],0,0,0,0)}return new this._date(c.getFullYear(),c.getMonth(),c.getDate(),b[0],b[1],b[2],0)},_makeDate:function(k){k=a.trim(((this.__("useArabicIndic")===true)?this._dRep(k,-1):k));var n=this,c=this.options,e=n.__fmt(),m=null,h=[],l=null,b=null,f=new n._date(),j={year:-1,mont:-1,date:-1,hour:-1,mins:-1,secs:-1,week:false,wtyp:4,wday:false,yday:false,meri:0},g;if(typeof c.mode==="undefined"){return f}if(typeof n._parser[c.mode]!=="undefined"){return n._parser[c.mode].apply(n,[k])}if(c.mode==="durationbox"||c.mode==="durationflipbox"){e=e.replace(/%D([a-z])/gi,function(d,o){switch(o){case"d":case"l":case"M":case"S":return"("+d+"|[0-9]+)";default:return".+?"}});e=new RegExp("^"+e+"$");m=e.exec(k);l=e.exec(n.__fmt());if(m===null||m.length!==l.length){if(typeof c.defaultValue==="number"&&c.defaultValue>0){return new n._date((n.initDate.getEpoch()+parseInt(c.defaultValue,10))*1000)}return new n._date(n.initDate.getTime())}b=n.initDate.getEpoch();for(g=0;g-1){j.mont=b}break;case"B":b=a.inArray(m[g],n.__("monthsOfYear"));if(b>-1){j.mont=b}break}}if(j.meri!==0){if(j.meri===-1&&j.hour===12){j.hour=0}if(j.meri===1&&j.hour!==12){j.hour=j.hour+12}}f=new n._date(n._n(j.year,0),n._n(j.mont,0),n._n(j.date,1),n._n(j.hour,0),n._n(j.mins,0),n._n(j.secs,0),0);if(j.year<100&&j.year!==-1){f.setFullYear(j.year)}if((j.mont>-1&&j.date>-1)||(j.hour>-1&&j.mins>-1&&j.secs>-1)){return f}if(j.week!==false){f.setDWeek(j.wtyp,j.week);if(j.date>-1){f.setDate(j.date)}}if(j.yday!==false){f.setD(1,0).setD(2,1).adj(2,(j.yday-1))}if(j.wday!==false){f.adj(2,(j.wday-f.getDay()))}}return f},_customformat:{"default":function(c,b){return false}},_formatter:function(f,c){var b=this,g=this.options,d,e={part:[0,0,0,0],tp:0};if(g.mode==="durationbox"||g.mode==="durationflipbox"){e.tp=this.theDate.getEpoch()-this.initDate.getEpoch();e.part[0]=parseInt(e.tp/(60*60*24),10);e.tp-=(e.part[0]*60*60*24);e.part[1]=parseInt(e.tp/(60*60),10);e.tp-=(e.part[1]*60*60);e.part[2]=parseInt(e.tp/(60),10);e.tp-=(e.part[2]*60);e.part[3]=e.tp;if(!f.match(/%Dd/)){e.part[1]+=(e.part[0]*24)}if(!f.match(/%Dl/)){e.part[2]+=(e.part[1]*60)}if(!f.match(/%DM/)){e.part[3]+=(e.part[2]*60)}}f=f.replace(/%(D|X|0|-)*([1-9a-zA-Z])/g,function(h,j,k){if(j==="X"){if(typeof b._customformat[g.mode]!=="undefined"){return b._customformat[g.mode](k,c,g)}return h}if(j==="D"){switch(k){case"d":return e.part[0];case"l":return b._zPad(e.part[1]);case"M":return b._zPad(e.part[2]);case"S":return b._zPad(e.part[3]);case"A":return((e.part[0]>1)?b.__("durationDays")[1]:b.__("durationDays")[0]);default:return h}}switch(k){case"%":return"%";case"a":return b.__("daysOfWeekShort")[c.getDay()];case"A":return b.__("daysOfWeek")[c.getDay()];case"b":return b.__("monthsOfYearShort")[c.getMonth()];case"B":return b.__("monthsOfYear")[c.getMonth()];case"C":return c.getFullYear().toString().substr(0,2);case"d":return((j==="-")?c.getDate():b._zPad(c.getDate()));case"H":case"k":return((j==="-")?c.getHours():b._zPad(c.getHours()));case"I":case"l":return((j==="-")?((c.getHours()===0||c.getHours()===12)?12:((c.getHours()<12)?c.getHours():(c.getHours()-12))):b._zPad(((c.getHours()===0||c.getHours()===12)?12:((c.getHours()<12)?c.getHours():c.getHours()-12))));case"m":return((j==="-")?c.getMonth()+1:b._zPad(c.getMonth()+1));case"M":return((j==="-")?c.getMinutes():b._zPad(c.getMinutes()));case"p":return((c.getHours()<12)?b.__("meridiem")[0].toUpperCase():b.__("meridiem")[1].toUpperCase());case"P":return((c.getHours()<12)?b.__("meridiem")[0].toLowerCase():b.__("meridiem")[1].toLowerCase());case"s":return c.getEpoch();case"S":return((j==="-")?c.getSeconds():b._zPad(c.getSeconds()));case"u":return((j==="-")?c.getDay()+1:b._zPad(c.getDay()+1));case"w":return c.getDay();case"y":return c.getFullYear().toString().substr(2,2);case"Y":return c.getFullYear();case"E":return c.getFullYear()+543;case"V":return((j==="-")?c.getDWeek(4):b._zPad(c.getDWeek(4)));case"U":return((j==="-")?c.getDWeek(0):b._zPad(c.getDWeek(0)));case"W":return((j==="-")?c.getDWeek(1):b._zPad(c.getDWeek(1)));case"o":if(typeof b._ord[g.useLang]!=="undefined"){return b._ord[g.useLang](c.getDate())}return b._ord["default"](c.getDate());case"j":d=new Date(c.getFullYear(),0,1);d=Math.ceil((c-d)/86400000)+1;return((d<100)?((d<10)?"00":"0"):"")+String(d);case"G":if(c.getDWeek(4)===1&&c.getMonth()>0){return c.getFullYear()+1}if(c.getDWeek(4)>51&&c.getMonth()<11){return c.getFullYear()-1}return c.getFullYear();case"g":if(c.getDWeek(4)===1&&c.getMonth()>0){return parseInt(c.getFullYear().toString().substr(2,2),10)+1}if(c.getDWeek(4)>51&&c.getMonth()<11){return parseInt(c.getFullYear().toString().substr(2,2),10)-1}return c.getFullYear().toString().substr(2,2);default:return h}});if(b.__("useArabicIndic")===true){f=b._dRep(f)}return f},_btwn:function(d,b,c){return(d>b&&d1&&d%e.minuteStep>0){if(e.minuteStepRound<0){d=d-(d%e.minuteStep)}else{if(e.minStepRound>0){d=d+(e.minuteStep-(d%e.minuteStep))}else{if(d%e.minuteStep0)?1:-1)*12,false);break}}if(c!==false){b.theDate.adj(c,d)}if(g===true){b.refresh()}if(e.useImmediate){b.d.input.trigger("datebox",{method:"doset"})}},_startOffset:function(b){var c=this.options;if(c.startOffsetYears!==false){b.adj(0,c.startOffsetYears)}if(c.startOffsetMonths!==false){b.adj(1,c.startOffsetMonths)}if(c.startOffsetDays!==false){b.adj(2,c.startOffsetDays)}return b},_create:function(){a(document).trigger("dateboxcreate");var j=this,b=a.extend(this.options,(typeof this.element.jqmData("options")!=="undefined")?this.element.jqmData("options"):this._getLongOptions(this.element)),k=(b.theme===false&&typeof(a(this).jqmData("theme"))==="undefined")?((typeof(this.element.parentsUntil(":jqmData(theme)").parent().jqmData("theme"))==="undefined")?b.themeDefault:this.element.parentsUntil(":jqmData(theme)").parent().jqmData("theme")):b.theme,l=b.useAnimation?b.transition:"none",g=b.useNewStyle===false?{input:this.element,wrap:this.element.wrap('
              ').parent(),mainWrap:a("
              ",{"class":"ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden "+l+" ui-body-"+k}).css("zIndex",b.zindex),intHTML:false}:{input:this.element,wrap:this.element,mainWrap:a("
              ",{"class":"ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden "+l+" ui-body-"+k}).css("zIndex",b.zindex),intHTML:false},e=(typeof window.ontouchstart!=="undefined"),f={eStart:(e?"touchstart":"mousedown")+".datebox",eMove:(e?"touchmove":"mousemove")+".datebox",eEnd:(e?"touchend":"mouseup")+".datebox",eEndA:(e?"mouseup.datebox touchend.datebox touchcancel.datebox touchmove.datebox":"mouseup.datebox"),move:false,start:false,end:false,pos:false,target:false,delta:false,tmp:false},c={},h=(typeof a.mobile.ns!=="undefined")?a.mobile.ns:"";a.extend(j,{d:g,ns:h,drag:f,touch:e});if(b.usePlaceholder!==false){if(b.usePlaceholder===true&&j._grabLabel()!==false){j.d.input.attr("placeholder",j._grabLabel())}if(typeof b.usePlaceholder==="string"){j.d.input.attr("placeholder",b.usePlaceholder)}}b.theme=k;j.clearFunc=false;j.disabled=false;j.runButton=false;j._date=window.Date;j._enhanceDate();j.baseID=j.d.input.attr("id");j.initDate=new j._date();j.theDate=(b.defaultValue)?j._makeDate(b.defaultValue):((j.d.input.val()!=="")?j._makeDate(j.d.input.val()):new j._date());j.initDone=false;if(b.showInitialValue===true){j.d.input.val(j._formatter(j.__fmt(),j.theDate))}if(b.useButton===true&&b.useInline===false&&b.useNewStyle===false){j.d.open=a(''+this.__("tooltip")+"").on(b.clickEvent,function(d){d.preventDefault();if(!j.disabled){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.parent().addClass("ui-focus");j.d.input.parent().removeClass("ui-focus")}setTimeout(function(){a(d.target).closest("a").removeClass(a.mobile.activeBtnClass)},300)}).appendTo(j.d.wrap).buttonMarkup({icon:"grid",iconpos:"notext",corners:true,shadow:true}).css({"vertical-align":"middle",display:"inline-block"})}j.d.screen=a("
              ",{"class":"ui-datebox-screen ui-datebox-hidden"+((b.useModal)?" ui-datebox-screen-modal":"")}).css({"z-index":b.zindex-1}).on(b.clickEventAlt,function(d){d.preventDefault();j.d.input.trigger("datebox",{method:"close"})});if(b.enhanceInput===true&&navigator.userAgent.match(/Android/i)){j.inputType="number"}else{j.inputType="text"}if(b.hideInput){j.d.wrap.parent().hide()}if(b.mobVer<140){a("label[for='"+j.d.input.attr("id")+"']").addClass("ui-input-text").css("verticalAlign","middle")}j.d.wrap.on(b.clickEvent,function(){if(!j.disabled&&(b.noButtonFocusMode||b.focusMode)){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.addClass("ui-focus");j.d.input.removeClass("ui-focus")}});j.d.input.removeClass("ui-corner-all ui-shadow-inset").bind(j.touch?"touchend":"click",function(d){if(j.disabled===false&&b.useNewStyle===true&&b.useFocus===false){if(((j.touch?d.originalEvent.changedTouches[0].pageX:d.pageX)-d.target.offsetLeft)>(d.target.offsetWidth-20)){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.parent().addClass("ui-focus");j.d.input.removeClass("ui-focus")}}}).focus(function(){if(j.disabled===false&&b.useFocus===true){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.addClass("ui-focus");j.d.input.removeClass("ui-focus");if(b.useNewStyle===false){j.d.input.parent().removeClass("ui-focus");j.d.wrap.parent().addClass("ui-focus")}}if(b.useNewStyle===false){j.d.input.removeClass("ui-focus")}}).blur(function(){j.d.wrap.removeClass("ui-focus");j.d.input.removeClass("ui-focus")}).change(function(){j.theDate=j._makeDate(j.d.input.val());j.refresh()}).attr("readonly",b.lockInput).on("datebox",j._event);if(b.useNewStyle===true){j.d.input.addClass("ui-corner-all "+((b.useAltIcon===true)?"ui-icon-datebox-alt":"ui-icon-datebox"));if(b.overrideStyleClass!==false){j.d.input.addClass(b.overrideStyleClass)}}else{j.d.input.parent().css("border","none").removeClass("ui-shadow-inset")}j.d.wrap.parent().on(b.clickEvent,function(){if(!j.disabled&&b.useFocus===true&&b.useNewStyle===false){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.addClass("ui-focus");j.d.input.removeClass("ui-focus");setTimeout(function(){j.d.wrap.removeClass("ui-focus");j.d.wrap.parent().addClass("ui-focus")},500)}});if(typeof a.event.special.mousewheel!=="undefined"){j.wheelExists=true}if(j.d.input.is(":disabled")){j.disable()}if(b.useInline===true||b.useInlineBlind){j.open()}j.applyMinMax(false,false);a(document).trigger("dateboxaftercreate")},applyMinMax:function(e,d){var b=this,f=this.options,c={};if(typeof e==="undefined"){e=false}if(typeof d==="undefined"){d=true}if((d===true||f.minDays===false)&&typeof(b.d.input.attr("min"))!=="undefined"){c.today=new b._date();c.lod=24*60*60*1000;c.todayc=new b._date(c.today.getFullYear(),c.today.getMonth(),c.today.getDate(),0,0,0,0);c.fromel=b.d.input.attr("min").split("-");c.compdt=new b._date(c.fromel[0],c.fromel[1]-1,c.fromel[2],0,0,0,0);f.minDays=parseInt((((c.compdt.getTime()-c.todayc.getTime())/c.lod))*-1,10)}if((d===true||f.maxDays===false)&&typeof(b.d.input.attr("max"))!=="undefined"){c.today=new b._date();c.lod=24*60*60*1000;c.todayc=new b._date(c.today.getFullYear(),c.today.getMonth(),c.today.getDate(),0,0,0,0);c.fromel=b.d.input.attr("max").split("-");c.compdt=new b._date(c.fromel[0],c.fromel[1]-1,c.fromel[2],0,0,0,0);f.maxDays=parseInt((((c.compdt.getTime()-c.todayc.getTime())/c.lod)),10)}if(e===true){b.refresh()}},_build:{"default":function(){this.d.headerText="Error";this.d.intHTML=a("

              There is no mode by that name loaded / mode not given

              ")}},_applyCoords:function(h){var b=h.widget,j=h.widget.options,f={h:a.mobile.activePage.find(".ui-header").jqmData("position"),f:a.mobile.activePage.find(".ui-footer").jqmData("position"),fh:a.mobile.activePage.find(".ui-footer").outerHeight(),hh:a.mobile.activePage.find(".ui-header").outerHeight()},c={x:b.d.wrap.offset().left+(b.d.wrap.outerWidth()/2),y:b.d.wrap.offset().top+(b.d.wrap.outerHeight()/2)},d={w:b.d.mainWrap.outerWidth(),h:b.d.mainWrap.outerHeight()},g={t:a(window).scrollTop(),h:a(window).height(),w:a.mobile.activePage.width(),ah:a(document).height()},k={y:(j.centerVert)?g.t+((g.h/2)-(d.h/2)):c.y-(d.h/2),x:(g.w<400||j.centerHoriz)?(g.w/2)-(d.w/2):c.x-(d.w/2)};if(j.centerVert===false){if(j.hideFixedToolbars===true&&(typeof f.f!=="undefined"||typeof f.h!=="undefined")){a.mobile.activePage.find(":jqmData(position='fixed')").fixedtoolbar("hide");f.f=undefined;f.h=undefined}if(typeof f.f!=="undefined"){if((k.y+d.h)>(g.h-f.fh-2)){k.y=g.h-f.fh-2-d.h}}else{if((k.y+d.h)>(g.ah-f.fh-2)){k.y=g.ah-f.fh-2-d.h}if((g.h+g.t)<(d.h+k.y+2)){k.y=g.h+g.t-d.h-2}}if(typeof f.h!=="undefined"){if((g.t+f.hh+2)>k.y){k.y=g.t+f.hh+2}}else{if(f.hh+2>k.y){k.y=f.hh+2}if(k.y
              ');a("Close").appendTo(b.d.headHTML).buttonMarkup({theme:g.themeHeader,icon:"delete",iconpos:"notext",corners:true,shadow:true}).on(g.clickEventAlt,function(h){h.preventDefault();b.d.input.trigger("datebox",{method:"close"})});a('

              '+b.d.headerText+"

              ").appendTo(b.d.headHTML);b.d.mainWrap.append(b.d.headHTML)}b.d.mainWrap.append(b.d.intHTML).css("zIndex",g.zindex);b.d.input.trigger("datebox",{method:"postrefresh"});if(g.useAnimation===true){e.transition=g.transition}else{e.transition="none"}if(g.popupForceX!==false&&g.popupForceY!==false){e.x=g.popupForceX;e.y=g.popupForceY}if(g.popupPosition!==false){e.positionTo=g.popupPosition}else{if(typeof b.baseID!==undefined){e.positionTo="#"+b.baseID}else{e.positionTo="window"}}if(g.useModal===true){f.overlayTheme="a"}b.d.mainWrap.removeClass("ui-datebox-hidden").popup(f).popup("open",e);b.refresh()}else{if(g.dialogForce||(g.dialogEnable&&window.width()<400)){b.d.dialogPage=a("

              "+b.d.headerText+"

              ").appendTo(a.mobile.pageContainer).page().css("minHeight","0px").addClass(c);b.d.dialogPage.find(".ui-header").find("a").off("click vclick").on(g.clickEventAlt,function(h){h.preventDefault();b.d.input.trigger("datebox",{method:"close"})});b.d.mainWrap.append(b.d.intHTML).css({marginLeft:"auto",marginRight:"auto"}).removeClass("ui-datebox-hidden");b.d.dialogPage.find(".ui-content").append(b.d.mainWrap);b.d.input.trigger("datebox",{method:"postrefresh"});a.mobile.activePage.off("pagehide.remove");a.mobile.changePage(b.d.dialogPage,{transition:c})}else{b.d.dialogPage=false;b.d.mainWrap.empty();if(g.useHeader===true){b.d.headHTML=a('
              ');a("Close").appendTo(b.d.headHTML).buttonMarkup({theme:g.themeHeader,icon:"delete",iconpos:"notext",corners:true,shadow:true}).on(g.clickEventAlt,function(h){h.preventDefault();b.d.input.trigger("datebox",{method:"close"})});a('

              '+b.d.headerText+"

              ").appendTo(b.d.headHTML);b.d.mainWrap.append(b.d.headHTML)}b.d.mainWrap.append(b.d.intHTML).css("zIndex",g.zindex);b.d.mainWrap.appendTo(a.mobile.activePage);b.d.screen.appendTo(a.mobile.activePage);b.d.input.trigger("datebox",{method:"postrefresh"});b._applyCoords({widget:b});if(g.useModal===true){if(g.useAnimation){b.d.screen.fadeIn("slow")}else{b.d.screen.show()}}else{setTimeout(function(){b.d.screen.removeClass("ui-datebox-hidden")},500)}b.d.mainWrap.addClass("ui-overlay-shadow in").removeClass("ui-datebox-hidden");a(document).on("orientationchange.datebox",{widget:b},function(h){b._applyCoords(h.data)});if(g.resizeListener===true){a(window).on("resize.datebox",{widget:b},function(h){b._applyCoords(h.data)})}}}},close:function(){var b=this,c=this.options;if(c.useInlineBlind===true){b.d.mainWrap.slideUp();return true}if(c.useInline===true||b.d.intHTML===false){return true}if(b.d.dialogPage!==false){a(b.d.dialogPage).dialog("close");if(!a.mobile.activePage.jqmData("mobile-page").options.domCache){a.mobile.activePage.on("pagehide.remove",function(){a(this).remove()})}b.d.intHTML.detach().empty();b.d.mainWrap.detach().empty();b.d.wrap.removeClass("ui-focus");b.clearFunc=setTimeout(function(){b.d.dialogPage.empty().remove();b.clearFunc=false},1500)}else{if(c.enablePopup===true){b.d.mainWrap.popup("close");b.d.wrap.removeClass("ui-focus")}else{if(c.useModal){if(c.useAnimation){b.d.screen.fadeOut("slow")}else{b.d.screen.hide()}}else{b.d.screen.addClass("ui-datebox-hidden")}b.d.screen.detach();b.d.mainWrap.addClass("ui-datebox-hidden").removeAttr("style").removeClass("in ui-overlay-shadow").empty().detach();b.d.intHTML.detach();b.d.wrap.removeClass("ui-focus");a(document).off("orientationchange.datebox");if(c.resizeListener===true){a(window).off("resize.datebox")}}}b.d.wrap.parent().removeClass("ui-focus");a(document).off(b.drag.eMove);a(document).off(b.drag.eEnd);a(document).off(b.drag.eEndA);if(c.useFocus){b.fastReopen=true;setTimeout(function(d){return function(){d.fastReopen=false}}(b),300)}if(c.closeCallback!==false){if(!a.isFunction(c.closeCallback)){if(typeof window[c.closeCallback]!=="undefined"){c.closeCallback=window[c.closeCallback]}else{c.closeCallback=new Function(c.closeCallback)}}c.closeCallback.apply(b,a.merge([b.theDate],c.closeCallbackArgs))}},refresh:function(){if(typeof this._build[this.options.mode]==="undefined"){this._build["default"].apply(this,[])}else{this._build[this.options.mode].apply(this,[])}if(this.__("useArabicIndic")===true){this._doIndic()}this.d.mainWrap.append(this.d.intHTML);this.d.input.trigger("datebox",{method:"postrefresh"})},_check:function(){var b=this,d=null,c=this.options;b.dateOK=true;if(c.afterToday!==false){d=new b._date();if(b.theDated){b.theDate=d}}if(c.maxDays!==false){d=new b._date();d.adj(2,c.maxDays);if(b.theDate>d){b.theDate=d}}if(c.minDays!==false){d=new b._date();d.adj(2,-1*c.minDays);if(b.theDatec.maxHour){b.theDate.setHours(c.maxHour)}}if(c.maxYear!==false){d=new b._date(c.maxYear,0,1);d.adj(2,-1);if(b.theDate>d){b.theDate=d}}if(c.minYear!==false){d=new b._date(c.minYear,0,1);if(b.theDate-1){if(c.mode==="timeflipbox"&&c.validHours!==false){if(a.inArray(b.theDate.getHours(),c.validHours)<0){b.dateOK=false}}}else{if(c.blackDatesRec!==false){for(i=0;i-1){b.dateOK=false}}if(c.blackDays!==false){if(a.inArray(b.theDate.getDay(),c.blackDays)>-1){b.dateOK=false}}}},_grabLabel:function(){var b=this,c=this.options;if(typeof c.overrideDialogLabel==="undefined"){if(typeof b.d.input.attr("placeholder")!=="undefined"){return b.d.input.attr("placeholder")}if(typeof b.d.input.attr("title")!=="undefined"){return b.d.input.attr("title")}if(b.d.wrap.parent().find("label[for='"+b.d.input.attr("id")+"']").text()!==""){return b.d.wrap.parent().find("label[for='"+b.d.input.attr("id")+"']").text()}return false}return c.overrideDialogLabel},_makeEl:function(d,e){var b=false,c=false;c=d.clone();if(typeof e.attr!=="undefined"){for(b in e.attr){if(e.attr.hasOwnProperty(b)){c.jqmData(b,e.attr[b])}}}return c},_getLongOptions:function(d){var c,e={},f,b;if(a.mobile.ns===""){f="datebox"}else{f=a.mobile.ns.substr(0,a.mobile.ns.length-1)+"Datebox"}for(c in d.data()){if(c.substr(0,f.length)===f&&c.length>f.length){b=c.substr(f.length);b=b.charAt(0).toLowerCase()+b.slice(1);e[b]=d.data(c)}}return e},disable:function(){this.d.input.attr("disabled",true);this.d.wrap.addClass("ui-disabled").blur();this.disabled=true;this.d.input.trigger("datebox",{method:"disable"})},enable:function(){this.d.input.attr("disabled",false);this.d.wrap.removeClass("ui-disabled");this.disabled=false;this.d.input.trigger("datebox",{method:"enable"})},_setOption:function(){a.Widget.prototype._setOption.apply(this,arguments);this.refresh()},getTheDate:function(){return this.theDate},getLastDur:function(){return this.lastDuration},setTheDate:function(b){this.theDate=b;this.refresh()},callFormat:function(c,b){return this._formatter(c,b)}});a(document).on("pagebeforecreate",function(b){a(":jqmData(role='datebox')",b.target).each(function(){a(this).prop("type","text")})});a(document).on("pagecreate create",function(b){a(document).trigger("dateboxbeforecreate");a(":jqmData(role='datebox')",b.target).each(function(){var c=typeof(a(this).data(parseInt(a.mobile.version.replace(/\./g,""),10)>111?"mobile-datebox":"datebox"));if(c==="undefined"){a(this).datebox()}})})})(jQuery);(function(a){a.extend(a.mobile.datebox.prototype.options,{themeDateHigh:"b",themeDatePick:"b",themeDate:"a",useSetButton:true,validHours:false,slen:{y:5,m:6,d:15,h:12,i:30}});a.extend(a.mobile.datebox.prototype,{_sbox_pos:function(){var b=this,f,e,d,c;b.d.intHTML.find("div.ui-datebox-sliderow-int").each(function(){f=a(this);d=f.parent().innerWidth();if(b.__("isRTL")){e=f.find("div").last()}else{e=f.find("div").first()}c=f.find("div").size()*e.outerWidth();e.css("marginLeft",((c/2)-(d/2))*-1)})}});a.extend(a.mobile.datebox.prototype._build,{slidebox:function(){var p=this,c=this.options,e,l,q,d,f,n,g=(p.d.input.val()==="")?p._startOffset(p._makeDate(p.d.input.val())):p._makeDate(p.d.input.val()),j="ui-datebox-",h=((this.options.mobVer<140)?"up-":""),k=a("
              "),m=a("
              "),b=a("
              ",{"class":j+"slide"});if(typeof p.d.intHTML!=="boolean"){p.d.intHTML.empty().remove()}p.d.input.on("datebox",function(o,i){if(i.method==="postrefresh"){p._sbox_pos()}});p.d.headerText=((p._grabLabel()!==false)?p._grabLabel():p.__("titleDateDialogLabel"));p.d.intHTML=a("");p.fldOrder=p.__("slideFieldOrder");p._check();p._minStepFix();a('

              '+p._formatter(p.__("headerFormat"),p.theDate)+"

              ").appendTo(p.d.intHTML);p.d.intHTML.append(b);for(l=0;l",{"class":j+"slideyear ui-corner-all ui-btn ui-btn-"+h+f}).html(p.theDate.get(0)+e).jqmData("offset",e).jqmData("theme",f).appendTo(q)}break;case"m":d.addClass(j+"sliderow-ym");for(e=c.slen.m*-1;e<(c.slen.m+1);e++){n=p.theDate.copy([0],[0,0,1]);n.adj(1,e);f=(e!==0)?((g.get(1)===n.get(1)&&g.get(0)===n.get(0))?c.themeDateHigh:c.themeDate):c.themeDatePick;a("
              ",{"class":j+"slidemonth ui-corner-all ui-btn ui-btn-"+h+f}).html(String(p.__("monthsOfYearShort")[n.get(1)])).jqmData("offset",e).jqmData("theme",f).appendTo(q)}break;case"d":d.addClass(j+"sliderow-d");for(e=c.slen.d*-1;e<(c.slen.d+1);e++){n=p.theDate.copy();n.adj(2,e);f=(e!==0)?((g.comp()===n.comp())?c.themeDateHigh:c.themeDate):c.themeDatePick;if((c.blackDates!==false&&a.inArray(n.iso(),c.blackDates)>-1)||(c.blackDays!==false&&a.inArray(n.getDay(),c.blackDays)>-1)){f+=" "+j+"griddate-disable"}a("
              ",{"class":j+"slideday ui-corner-all ui-btn ui-btn-"+h+f}).html(n.get(2)+'
              '+p.__("daysOfWeekShort")[n.getDay()]+"").jqmData("offset",e).jqmData("theme",f).appendTo(q)}break;case"h":d.addClass(j+"sliderow-hi");for(e=c.slen.h*-1;e<(c.slen.h+1);e++){n=p.theDate.copy();n.adj(3,e);f=(e!==0)?c.themeDate:c.themeDatePick;if(c.validHours!==false&&a.inArray(n.get(3),c.validHours)<0){f+=" "+j+"griddate-disable"}a("
              ",{"class":j+"slidehour ui-corner-all ui-btn ui-btn-"+h+f}).html(p.__("timeFormat")===12?p._formatter('%I%p',n):n.get(3)).jqmData("offset",e).jqmData("theme",f).appendTo(q)}break;case"i":d.addClass(j+"sliderow-hi");for(e=c.slen.i*-1;e<(c.slen.i+1);e++){n=p.theDate.copy();n.adj(4,(e*c.minuteStep));f=(e!==0)?c.themeDate:c.themeDatePick;a("
              ",{"class":j+"slidemins ui-corner-all ui-btn ui-btn-"+h+f}).html(p._zPad(n.get(4))).jqmData("offset",e*c.minuteStep).jqmData("theme",f).appendTo(q)}break}d.appendTo(b)}if(c.useSetButton||c.useClearButton){l=a("
              ",{"class":j+"controls"});if(c.useSetButton){a(''+p.__("setDateButtonLabel")+"").appendTo(l).buttonMarkup({theme:c.theme,icon:"check",iconpos:"left",corners:true,shadow:true}).on(c.clickEventAlt,function(i){i.preventDefault();if(p.dateOK===true){p.d.input.trigger("datebox",{method:"set",value:p._formatter(p.__fmt(),p.theDate),date:p.theDate});p.d.input.trigger("datebox",{method:"close"})}})}if(c.useClearButton){a(''+p.__("clearButton")+"").appendTo(l).buttonMarkup({theme:c.theme,icon:"delete",iconpos:"left",corners:true,shadow:true}).on(c.clickEventAlt,function(i){i.preventDefault();p.d.input.val("");p.d.input.trigger("datebox",{method:"clear"});p.d.input.trigger("datebox",{method:"close"})})}if(c.useCollapsedBut){l.addClass("ui-datebox-collapse")}l.appendTo(p.d.intHTML)}if(p.wheelExists){p.d.intHTML.on("mousewheel",".ui-datebox-sliderow-int",function(i,o){i.preventDefault();p._offset(a(this).jqmData("rowtype"),((o<0)?-1:1)*(a(this).jqmData("rowtype")==="i"?c.minuteStep:1))})}p.d.intHTML.on(c.clickEvent,".ui-datebox-sliderow-int>div",function(i){i.preventDefault();p._offset(a(this).parent().jqmData("rowtype"),parseInt(a(this).jqmData("offset"),10))});p.d.intHTML.on("vmouseover vmouseout",".ui-datebox-sliderow-int>div",function(){p._hoover(this)});p.d.intHTML.on(p.drag.eStart,".ui-datebox-sliderow-int",function(i){if(!p.drag.move){p.drag.move=true;p.drag.target=a(this);p.drag.pos=parseInt(p.drag.target.css("marginLeft").replace(/px/i,""),10);p.drag.start=p.touch?i.originalEvent.changedTouches[0].pageX:i.pageX;p.drag.end=false;i.stopPropagation();i.preventDefault()}})}});a.extend(a.mobile.datebox.prototype._drag,{slidebox:function(){var b=this,d=this.options,c=this.drag;a(document).on(c.eMove,function(f){if(c.move&&d.mode==="slidebox"){c.end=b.touch?f.originalEvent.changedTouches[0].pageX:f.pageX;c.target.css("marginLeft",(c.pos+c.end-c.start)+"px");f.preventDefault();f.stopPropagation();return false}});a(document).on(c.eEnd,function(f){if(c.move&&d.mode==="slidebox"){c.move=false;if(c.end!==false){f.preventDefault();f.stopPropagation();c.tmp=c.target.find("div").first();b._offset(c.target.jqmData("rowtype"),(b.__("isRTL")?-1:1)*(parseInt((c.start-c.end)/c.tmp.innerWidth(),10))*(c.target.jqmData("rowtype")==="i"?d.minuteStep:1))}c.start=false;c.end=false}})}})})(jQuery); \ No newline at end of file diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.core.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.core.js new file mode 100644 index 000000000..d98616dd3 --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.core.js @@ -0,0 +1,1365 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +/* CORE Functions */ + +(function($) { + $.widget( "mobile.datebox", $.mobile.widget, { + options: { + // All widget options, including some internal runtime details + version: '2-1.4.0-2013070300', // jQMMajor.jQMMinor.DBoxMinor-YrMoDaySerial + mobVer: parseInt($.mobile.version.replace(/\./g,'')), + theme: false, + themeDefault: 'a', + themeHeader: 'a', + mode: false, + + centerHoriz: false, + centerVert: false, + transition: 'pop', + useAnimation: true, + hideInput: false, + hideFixedToolbars: false, + + lockInput: true, + enhanceInput: true, + + zindex: '500', + clickEvent: 'vclick', + clickEventAlt: 'click', + resizeListener: true, + + defaultValue: false, + showInitialValue: false, + + dialogEnable: false, + dialogForce: false, + enablePopup: false, + + popupPosition: false, + popupForceX: false, + popupForceY: false, + + useModal: false, + useInline: false, + useInlineBlind: false, + useHeader: true, + useImmediate: false, + useNewStyle: false, + useAltIcon: false, + overrideStyleClass: false, + + useButton: true, + useFocus: false, + useClearButton: false, + useCollapsedBut: false, + usePlaceholder: false, + + openCallback: false, + openCallbackArgs: [], + closeCallback: false, + closeCallbackArgs: [], + + startOffsetYears: false, + startOffsetMonths: false, + startOffsetDays: false, + afterToday: false, + beforeToday: false, + notToday: false, + maxDays: false, + minDays: false, + maxYear: false, + minYear: false, + blackDates: false, + blackDatesRec: false, + blackDays: false, + minHour: false, + maxHour: false, + minuteStep: 1, + minuteStepRound: 0, + + rolloverMode: { 'm': true, 'd': true, 'h': true, 'i': true, 's': true }, + + useLang: 'default', + lang: { + 'default' : { + setDateButtonLabel: 'Set Date', + setTimeButtonLabel: 'Set Time', + setDurationButtonLabel: 'Set Duration', + calTodayButtonLabel: 'Jump to Today', + titleDateDialogLabel: 'Set Date', + titleTimeDialogLabel: 'Set Time', + daysOfWeek: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], + daysOfWeekShort: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], + monthsOfYear: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], + monthsOfYearShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], + durationLabel: ['Days', 'Hours', 'Minutes', 'Seconds'], + durationDays: ['Day', 'Days'], + timeFormat: 24, + headerFormat: '%A, %B %-d, %Y', + tooltip: 'Open Date Picker', + nextMonth: 'Next Month', + prevMonth: 'Previous Month', + dateFieldOrder: ['m', 'd', 'y'], + timeFieldOrder: ['h', 'i', 'a'], + slideFieldOrder: ['y', 'm', 'd'], + dateFormat: '%Y-%m-%d', + useArabicIndic: false, + isRTL: false, + calStartDay: 0, + clearButton: 'Clear', + durationOrder: ['d', 'h', 'i', 's'], + meridiem: ['AM', 'PM'], + timeOutput: '%k:%M', //{ '12': '%l:%M %p', '24': '%k:%M' }, + durationFormat: '%Dd %DA, %Dl:%DM:%DS', + calDateListLabel: 'Other Dates', + calHeaderFormat: '%B %Y' + } + } + }, + _enhanceDate: function() { + $.extend(this._date.prototype, { + copy: function(adjust, override) { + /* Get a modified copy of the date. + * First array - Offset the new date by # (position determines date part) + * Second array - If non-zero, force the new date by # (position determines date part) + */ + if ( typeof adjust === 'undefined' ) { adjust = [0,0,0,0,0,0,0]; } + if ( typeof override === 'undefined' ) { override = [0,0,0,0,0,0,0]; } + while ( adjust.length < 7 ) { adjust.push(0); } + while ( override.length < 7 ) { override.push(0); } + return new Date( + ((override[0] > 0 ) ? override[0] : this.getFullYear() + adjust[0]), + ((override[1] > 0 ) ? override[1] : this.getMonth() + adjust[1]), + ((override[2] > 0 ) ? override[2] : this.getDate() + adjust[2]), + ((override[3] > 0 ) ? override[3] : this.getHours() + adjust[3]), + ((override[4] > 0 ) ? override[4] : this.getMinutes() + adjust[4]), + ((override[5] > 0 ) ? override[5] : this.getSeconds() + adjust[5]), + ((override[6] > 0 ) ? override[5] : this.getMilliseconds() + adjust[6])); + }, + adj: function (type, amount) { + /* Adjust the date. Yes, this is chainable */ + if ( typeof amount !== 'number' ) { + throw new Error("Adjustment value not specified"); + } + if ( typeof type !== 'number' ) { + throw new Error("Adjustment type not specified"); + } + switch ( type ) { + case 0: this.setFullYear(this.getFullYear() + amount); break; + case 1: this.setMonth(this.getMonth() + amount); break; + case 2: this.setDate(this.getDate() + amount); break; + case 3: this.setHours(this.getHours() + amount); break; + case 4: this.setMinutes(this.getMinutes() + amount); break; + case 5: this.setSeconds(this.getSeconds() + amount); break; + case 6: this.setMilliseconds(this.getMilliseconds() + amount); break; + } + return this; + }, + setD: function(type, amount) { + /* A chainable version of setWhatever() */ + switch ( type ) { + case 0: this.setFullYear(amount); break; + case 1: this.setMonth(amount); break; + case 2: this.setDate(amount); break; + case 3: this.setHours(amount); break; + case 4: this.setMinutes(amount); break; + case 5: this.setSeconds(amount); break; + case 6: this.setMilliseconds(amount); break; + } + return this; + }, + get: function(type) { + switch ( type ) { + case 0: return this.getFullYear(); + case 1: return this.getMonth(); + case 2: return this.getDate(); + case 3: return this.getHours(); + case 4: return this.getMinutes(); + case 5: return this.getSeconds(); + } + return false; + }, + iso: function() { + return String(this.getFullYear()) + '-' + (( this.getMonth() < 9 ) ? "0" : "") + String(this.getMonth()+1) + '-' + ((this.getDate() < 10 ) ? "0" : "") + String(this.getDate()); + }, + comp: function () { + return parseInt(this.iso().replace(/-/g,''),10); + }, + getEpoch: function() { + return (this.getTime() - this.getMilliseconds()) / 1000; + }, + getArray: function() { + return [this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds()]; + }, + setFirstDay: function (day) { + this.setD(2,1).adj(2, (day - this.getDay())); + if ( this.get(2) > 10 ) { this.adj(2,7); } + return this; + }, + setDWeek: function (type,num) { + if ( type === 4 ) { + return this.setD(1,0).setD(2,1).setFirstDay(4).adj(2,-3).adj(2,(num-1)*7); + } + return this.setD(1,0).setD(2,1).setFirstDay(type).adj(2,(num-1)*7); + }, + getDWeek: function (type) { + var t1, t2; + + switch ( type ) { + case 0: + t1 = this.copy([0,-1*this.getMonth()]).setFirstDay(0); + return Math.floor((this.getTime() - ( t1.getTime() + (( this.getTimezoneOffset() - t1.getTimezoneOffset()) * 60000))) / 6048e5) + 1; + //return Math.floor((this.getTime() - t1.getTime()) / 6048e5) + 1; + case 1: + t1 = this.copy([0,-1*this.getMonth()]).setFirstDay(1); + return Math.floor((this.getTime() - ( t1.getTime() + (( this.getTimezoneOffset() - t1.getTimezoneOffset()) * 60000))) / 6048e5) + 1; + //return Math.floor((this.getTime() - t1.getTime()) / 6048e5) + 1; + case 4: + // this line is some bullshit. but it does work. + // (trap for dec 29, 30, or 31st being in the new year's week - these are the + // only 3 that can possibly fall like this) + if ( this.getMonth() === 11 && this.getDate() > 28 ) { return 1; } + + t1 = this.copy([0,-1*this.getMonth()],true).setFirstDay(4).adj(2,-3); + t2 = Math.floor((this.getTime() - ( t1.getTime() + (( this.getTimezoneOffset() - t1.getTimezoneOffset()) * 60000))) / 6048e5) + 1; + + if ( t2 < 1 ) { + t1 = this.copy([-1,-1*this.getMonth()]).setFirstDay(4).adj(2,-3); + return Math.floor((this.getTime() - t1.getTime()) / 6048e5) + 1; + } + return t2; + default: + return 0; + } + } + }); + }, + _event: function(e, p) { + var w = $(this).data(parseInt($.mobile.version.replace(/\./g,''),10) > 110 ? 'mobile-datebox' : 'datebox'); + if ( ! e.isPropagationStopped() ) { + switch (p.method) { + case 'close': + w.close(); break; + case 'open': + w.open(); break; + case 'set': + $(this).val(p.value); + $(this).trigger('change'); + break; + case 'doset': + if ( $.isFunction(w['_'+w.options.mode+'DoSet']) ) { + w['_'+w.options.mode+'DoSet'].apply(w,[]); + } else { + $(this).trigger('datebox', {'method':'set', 'value':w._formatter(w.__fmt(), w.theDate), 'date':w.theDate}); + } + break; + case 'dooffset': + if (p.type) { w._offset(p.type, p.amount, true); } break; + case 'dorefresh': + w.refresh(); break; + case 'doreset': + w.hardreset(); break; + case 'doclear': + $(this).val('').trigger('change'); break; + case 'clear': + $(this).trigger('change'); + } + } + }, + _hoover: function(item) { + // Hover toggle class, for calendar + $(item).toggleClass('ui-btn-up-'+$(item).jqmData('theme')+' ui-btn-down-'+$(item).jqmData('theme')); + }, + _ord: { + 'default': function (num) { + // Return an ordinal suffix (1st, 2nd, 3rd, etc) + var ending = num % 10; + if ( num > 9 && num < 21 ) { return 'th'; } + if ( ending > 3 ) { return 'th'; } + return ['th','st','nd','rd'][ending]; + } + }, + __ : function(val) { + var o = this.options, + oride = 'override' + val.charAt(0).toUpperCase() + val.slice(1); + + if ( typeof o[oride] !== 'undefined' ) { return o[oride]; } + if ( typeof o.lang[o.useLang][val] !== 'undefined' ) { return o.lang[o.useLang][val]; } + if ( typeof o[o.mode+'lang'] !== 'undefined' && typeof o[o.mode+'lang'][val] !== 'undefined' ) { return o[o.mode+'lang'][val]; } + return o.lang['default'][val]; + }, + __fmt: function() { + var w = this, + o = this.options; + + switch ( o.mode ) { + case 'timebox': + case 'timeflipbox': + return w.__('timeOutput'); + case 'durationbox': + case 'durationflipbox': + return w.__('durationFormat'); + default: + return w.__('dateFormat'); + } + }, + _zPad: function(number) { + return (( number < 10 ) ? '0' + String(number) : String(number)); + }, + _dRep: function(oper, direction) { + var start = 48, + end = 57, + adder = 1584, + i = null, + ch = null, + newd = ''; + + if ( direction === -1 ) { + start += adder; + end += adder; + adder = -1584; + } + + for ( i=0; i= start && ch <= end ) { + newd = newd + String.fromCharCode(ch+adder); + } else { + newd = newd + String.fromCharCode(ch); + } + } + + return newd; + }, + _doIndic: function() { + var w = this; + + w.d.intHTML.find('*').each(function() { + if ( $(this).children().length < 1 ) { + $(this).text(w._dRep($(this).text())); + } else if ( $(this).hasClass('ui-datebox-slideday') ) { + $(this).html(w._dRep($(this).html())); + } + }); + w.d.intHTML.find('input').each(function() { + $(this).val(w._dRep($(this).val())); + }); + }, + _parser: { + 'default': function (str) { return false; } + }, + _n: function (val,def) { + return ( val < 0 ) ? def : val; + }, + _pa: function (arr,date) { + if ( typeof date === 'boolean' ) { return new this._date(arr[0],arr[1],arr[2],0,0,0,0); } + return new this._date(date.getFullYear(), date.getMonth(), date.getDate(), arr[0], arr[1], arr[2], 0); + }, + _makeDate: function (str) { + // Date Parser + str = $.trim(((this.__('useArabicIndic') === true)?this._dRep(str, -1):str)); + var w = this, + o = this.options, + adv = w.__fmt(), + exp_input = null, + exp_names = [], + exp_format = null, + exp_temp = null, + date = new w._date(), + d = { year: -1, mont: -1, date: -1, hour: -1, mins: -1, secs: -1, week: false, wtyp: 4, wday: false, yday: false, meri: 0 }, + i; + + if ( typeof o.mode === 'undefined' ) { return date; } + if ( typeof w._parser[o.mode] !== 'undefined' ) { return w._parser[o.mode].apply(w,[str]); } + + if ( o.mode === 'durationbox' || o.mode === 'durationflipbox' ) { + adv = adv.replace(/%D([a-z])/gi, function(match, oper) { + switch (oper) { + case 'd': + case 'l': + case 'M': + case 'S': return '(' + match + '|' +'[0-9]+' + ')'; + default: return '.+?'; + } + }); + + adv = new RegExp('^' + adv + '$'); + exp_input = adv.exec(str); + exp_format = adv.exec(w.__fmt()); + + if ( exp_input === null || exp_input.length !== exp_format.length ) { + if ( typeof o.defaultValue === "number" && o.defaultValue > 0 ) { + return new w._date((w.initDate.getEpoch() + parseInt(o.defaultValue,10))*1000); + } + return new w._date(w.initDate.getTime()); + } + + exp_temp = w.initDate.getEpoch(); + for ( i=0; i -1 ) { d.mont = exp_temp; } + break; + case 'B': + exp_temp = $.inArray(exp_input[i], w.__('monthsOfYear')); + if ( exp_temp > -1 ) { d.mont = exp_temp; } + break; + } + } + if ( d.meri !== 0 ) { + if ( d.meri === -1 && d.hour === 12 ) { d.hour = 0; } + if ( d.meri === 1 && d.hour !== 12 ) { d.hour = d.hour + 12; } + } + + date = new w._date(w._n(d.year,0),w._n(d.mont,0),w._n(d.date,1),w._n(d.hour,0),w._n(d.mins,0),w._n(d.secs,0),0); + + if ( d.year < 100 && d.year !== -1 ) { date.setFullYear(d.year); } + + if ( ( d.mont > -1 && d.date > -1 ) || ( d.hour > -1 && d.mins > -1 && d.secs > -1 ) ) { return date; } + + if ( d.week !== false ) { + date.setDWeek(d.wtyp, d.week); + if ( d.date > -1 ) { date.setDate(d.date); } + } + if ( d.yday !== false ) { date.setD(1,0).setD(2,1).adj(2,(d.yday-1)); } + if ( d.wday !== false ) { date.adj(2,(d.wday - date.getDay())); } + } + return date; + }, + _customformat: { + 'default': function(oper, date) { return false; } + }, + _formatter: function(format, date) { + var w = this, + o = this.options, tmp, + dur = { + part: [0,0,0,0], tp: 0 + }; + + if ( o.mode === 'durationbox' || o.mode === 'durationflipbox' ) { + dur.tp = this.theDate.getEpoch() - this.initDate.getEpoch(); + dur.part[0] = parseInt( dur.tp / (60*60*24),10); dur.tp -=(dur.part[0]*60*60*24); // Days + dur.part[1] = parseInt( dur.tp / (60*60),10); dur.tp -= (dur.part[1]*60*60); // Hours + dur.part[2] = parseInt( dur.tp / (60),10); dur.tp -= (dur.part[2]*60); // Minutes + dur.part[3] = dur.tp; // Seconds + + if ( ! format.match(/%Dd/) ) { dur.part[1] += (dur.part[0]*24);} + if ( ! format.match(/%Dl/) ) { dur.part[2] += (dur.part[1]*60);} + if ( ! format.match(/%DM/) ) { dur.part[3] += (dur.part[2]*60);} + } + + format = format.replace(/%(D|X|0|-)*([1-9a-zA-Z])/g, function(match, pad, oper) { + if ( pad === 'X' ) { + if ( typeof w._customformat[o.mode] !== 'undefined' ) { return w._customformat[o.mode](oper, date, o); } + return match; + } + if ( pad === 'D' ) { + switch ( oper ) { + case 'd': return dur.part[0]; + case 'l': return w._zPad(dur.part[1]); + case 'M': return w._zPad(dur.part[2]); + case 'S': return w._zPad(dur.part[3]); + case 'A': return ((dur.part[0] > 1)?w.__('durationDays')[1]:w.__('durationDays')[0]); + default: return match; + } + } + switch ( oper ) { + case '%': // Literal % + return '%'; + case 'a': // Short Day + return w.__('daysOfWeekShort')[date.getDay()]; + case 'A': // Full Day of week + return w.__('daysOfWeek')[date.getDay()]; + case 'b': // Short month + return w.__('monthsOfYearShort')[date.getMonth()]; + case 'B': // Full month + return w.__('monthsOfYear')[date.getMonth()]; + case 'C': // Century + return date.getFullYear().toString().substr(0,2); + case 'd': // Day of month + return (( pad === '-' ) ? date.getDate() : w._zPad(date.getDate())); + case 'H': // Hour (01..23) + case 'k': + return (( pad === '-' ) ? date.getHours() : w._zPad(date.getHours())); + case 'I': // Hour (01..12) + case 'l': + return (( pad === '-' ) ? ((date.getHours() === 0 || date.getHours() === 12)?12:((date.getHours()<12)?date.getHours():(date.getHours()-12))) : w._zPad(((date.getHours() === 0 || date.getHours() === 12)?12:((date.getHours()<12)?date.getHours():date.getHours()-12)))); + case 'm': // Month + return (( pad === '-' ) ? date.getMonth()+1 : w._zPad(date.getMonth()+1)); + case 'M': // Minutes + return (( pad === '-' ) ? date.getMinutes() : w._zPad(date.getMinutes())); + case 'p': // AM/PM (ucase) + return ((date.getHours() < 12)?w.__('meridiem')[0].toUpperCase():w.__('meridiem')[1].toUpperCase()); + case 'P': // AM/PM (lcase) + return ((date.getHours() < 12)?w.__('meridiem')[0].toLowerCase():w.__('meridiem')[1].toLowerCase()); + case 's': // Unix Seconds + return date.getEpoch(); + case 'S': // Seconds + return (( pad === '-' ) ? date.getSeconds() : w._zPad(date.getSeconds())); + case 'u': // Day of week (1-7) + return (( pad === '-' ) ? date.getDay() + 1 : w._zPad(date.getDay() + 1)); + case 'w': // Day of week + return date.getDay(); + case 'y': // Year (2 digit) + return date.getFullYear().toString().substr(2,2); + case 'Y': // Year (4 digit) + return date.getFullYear(); + case 'E': // BE (Buddist Era, 4 Digit) + return date.getFullYear() + 543; + case 'V': + return (( pad === '-' ) ? date.getDWeek(4) : w._zPad(date.getDWeek(4))); + case 'U': + return (( pad === '-' ) ? date.getDWeek(0) : w._zPad(date.getDWeek(0))); + case 'W': + return (( pad === '-' ) ? date.getDWeek(1) : w._zPad(date.getDWeek(1))); + case 'o': // Ordinals + if ( typeof w._ord[o.useLang] !== 'undefined' ) { return w._ord[o.useLang](date.getDate()); } + return w._ord['default'](date.getDate()); + case 'j': + tmp = new Date(date.getFullYear(),0,1); + tmp = Math.ceil((date - tmp) / 86400000)+1; + return (( tmp < 100 ) ? (( tmp < 10 )? '00' : '0') : '' ) + String(tmp); + case 'G': + if ( date.getDWeek(4) === 1 && date.getMonth() > 0 ) { return date.getFullYear() + 1; } + if ( date.getDWeek(4) > 51 && date.getMonth() < 11 ) { return date.getFullYear() - 1; } + return date.getFullYear(); + case 'g': + if ( date.getDWeek(4) === 1 && date.getMonth() > 0 ) { return parseInt(date.getFullYear().toString().substr(2,2),10) + 1; } + if ( date.getDWeek(4) > 51 && date.getMonth() < 11 ) { return parseInt(date.getFullYear().toString().substr(2,2),10) - 1; } + return date.getFullYear().toString().substr(2,2); + default: + return match; + } + }); + + if ( w.__('useArabicIndic') === true ) { + format = w._dRep(format); + } + + return format; + }, + _btwn: function(value, low, high) { + return ( value > low && value < high ); + }, + _minStepFix: function() { + var tempMin = this.theDate.get(4), tmp, + w = this, + o = this.options; + + if ( o.minuteStep > 1 && tempMin % o.minuteStep > 0 ) { + if ( o.minuteStepRound < 0 ) { + tempMin = tempMin - (tempMin % o.minuteStep); + } else if ( o.minStepRound > 0 ) { + tempMin = tempMin + ( o.minuteStep - ( tempMin % o.minuteStep ) ); + } else { + if ( tempMin % o.minuteStep < o.minuteStep / 2 ) { + tempMin = tempMin - (tempMin % o.minuteStep); + } else { + tempMin = tempMin + ( o.minuteStep - ( tempMin % o.minuteStep ) ); + } + } + w.theDate.setMinutes(tempMin); + } + }, + _offset: function(mode, amount, update) { + // Compute a date/time offset. + // update = false to prevent controls refresh + var w = this, + o = this.options, + ok = false; + + mode = (mode || "").toLowerCase(); + + if ( typeof(update) === "undefined" ) { update = true; } + w.d.input.trigger('datebox', {'method':'offset', 'type':mode, 'amount':amount}); + + if ( mode !== 'a' && ( typeof o.rolloverMode[mode] === 'undefined' || o.rolloverMode[mode] === true )) { + ok = $.inArray(mode, ['y','m','d','h','i','s']); + } else { + switch(mode) { + case 'y': ok = 0; break; + case 'm': + if ( w._btwn(w.theDate.getMonth()+amount,-1,12) ) { ok = 1; } + break; + case 'd': + if ( w._btwn(w.theDate.getDate() + amount,0,(32 - w.theDate.copy([0],[0,0,32,13]).getDate() + 1) )) { ok = 2; } + break; + case 'h': + if ( w._btwn(w.theDate.getHours() + amount,-1,24) ) { ok = 3; } + break; + case 'i': + if ( w._btwn(w.theDate.getMinutes() + amount,-1,60) ) { ok = 4; } + break; + case 's': + if ( w._btwn(w.theDate.getSeconds() + amount,-1,60) ) { ok = 5; } + break; + case 'a': + w._offset('h',((amount>0)?1:-1)*12,false); + break; + } + } + if ( ok !== false ) { w.theDate.adj(ok,amount); } + if ( update === true ) { w.refresh(); } + if ( o.useImmediate ) { w.d.input.trigger('datebox', {'method':'doset'}); } + }, + _startOffset: function(date) { + var o = this.options; + + if ( o.startOffsetYears !== false ) { + date.adj(0, o.startOffsetYears); + } + if ( o.startOffsetMonths !== false ) { + date.adj(1, o.startOffsetMonths); + } + if ( o.startOffsetDays !== false ) { + date.adj(2, o.startOffsetDays); + } + return date; + }, + _create: function() { + // Create the widget, called automatically by widget system + $( document ).trigger( "dateboxcreate" ); + + var w = this, + o = $.extend(this.options, (typeof this.element.jqmData('options') !== 'undefined') ? this.element.jqmData('options') : this._getLongOptions(this.element) ), + thisTheme = ( o.theme === false && typeof($(this).jqmData('theme')) === 'undefined' ) ? + ( ( typeof(this.element.parentsUntil(':jqmData(theme)').parent().jqmData('theme')) === 'undefined' ) ? + o.themeDefault : this.element.parentsUntil(':jqmData(theme)').parent().jqmData('theme') ) + : o.theme, + trans = o.useAnimation ? o.transition : 'none', + d = o.useNewStyle === false ? { + input: this.element, + wrap: this.element.wrap('
              ').parent(), + mainWrap: $("
              ", { "class": 'ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden '+trans+' ui-body-'+thisTheme} ).css('zIndex', o.zindex), + intHTML: false + } : { + input: this.element, + wrap: this.element, + mainWrap: $("
              ", { "class": 'ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden '+trans+' ui-body-'+thisTheme} ).css('zIndex', o.zindex), + intHTML: false + }, + touch = ( typeof window.ontouchstart !== 'undefined' ), + drag = { + eStart : (touch ? 'touchstart' : 'mousedown')+'.datebox', + eMove : (touch ? 'touchmove' : 'mousemove')+'.datebox', + eEnd : (touch ? 'touchend' : 'mouseup')+'.datebox', + eEndA : (touch ? 'mouseup.datebox touchend.datebox touchcancel.datebox touchmove.datebox' : 'mouseup.datebox'), + move : false, + start : false, + end : false, + pos : false, + target : false, + delta : false, + tmp : false + }, + calc = { }, + ns = (typeof $.mobile.ns !== 'undefined')?$.mobile.ns:''; + + $.extend(w, {d: d, ns: ns, drag: drag, touch:touch}); + + if ( o.usePlaceholder !== false ) { + if ( o.usePlaceholder === true && w._grabLabel() !== false ) { w.d.input.attr('placeholder', w._grabLabel()); } + if ( typeof o.usePlaceholder === 'string' ) { w.d.input.attr('placeholder', o.usePlaceholder); } + } + + o.theme = thisTheme; + + w.clearFunc = false; + w.disabled = false; + w.runButton = false; + w._date = window.Date; + w._enhanceDate(); + w.baseID = w.d.input.attr('id'); + + w.initDate = new w._date(); + w.theDate = (o.defaultValue) ? w._makeDate(o.defaultValue) : ( (w.d.input.val() !== "") ? w._makeDate(w.d.input.val()) : new w._date() ); + w.initDone = false; + + if ( o.showInitialValue === true ) { + w.d.input.val(w._formatter(w.__fmt(), w.theDate)); + } + + if ( o.useButton === true && o.useInline === false && o.useNewStyle === false ) { + w.d.open = $(''+this.__('tooltip')+'') + .on(o.clickEvent, function(e) { + e.preventDefault(); + if ( !w.disabled ) { w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.parent().addClass('ui-focus'); w.d.input.parent().removeClass('ui-focus'); } + setTimeout( function() { $(e.target).closest('a').removeClass($.mobile.activeBtnClass); }, 300); + }).appendTo(w.d.wrap).buttonMarkup({icon: 'grid', iconpos: 'notext', corners:true, shadow:true}) + .css({'vertical-align': 'middle', 'display': 'inline-block'}); + } + + w.d.screen = $("
              ", {'class':'ui-datebox-screen ui-datebox-hidden'+((o.useModal)?' ui-datebox-screen-modal':'')}) + .css({'z-index': o.zindex-1}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.trigger('datebox', {'method':'close'}); + }); + + if ( o.enhanceInput === true && navigator.userAgent.match(/Android/i) ){ + w.inputType = 'number'; + } else { + w.inputType = 'text'; + } + + if ( o.hideInput ) { w.d.wrap.parent().hide(); } + + if ( o.mobVer < 140 ) { + $('label[for=\''+w.d.input.attr('id')+'\']').addClass('ui-input-text').css('verticalAlign', 'middle'); + } + + w.d.wrap.on(o.clickEvent, function() { + if ( !w.disabled && ( o.noButtonFocusMode || o.focusMode ) ) { + w.d.input.trigger('datebox', {'method': 'open'}); + w.d.wrap.addClass('ui-focus'); + w.d.input.removeClass('ui-focus'); + } + }); + + w.d.input + .removeClass('ui-corner-all ui-shadow-inset') + .bind(w.touch?'touchend':'click', function(e){ + if ( w.disabled === false && o.useNewStyle === true && o.useFocus === false ) { + if ( ((w.touch ? e.originalEvent.changedTouches[0].pageX : e.pageX) - e.target.offsetLeft) > (e.target.offsetWidth - 20) ) { + w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.parent().addClass('ui-focus'); w.d.input.removeClass('ui-focus'); + //setTimeout(function(){w.d.wrap.addClass('ui-focus');}, 200); + } + } + }) + .focus(function(){ + if ( w.disabled === false && o.useFocus === true ) { + w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.addClass('ui-focus'); w.d.input.removeClass('ui-focus'); + if ( o.useNewStyle === false ) { w.d.input.parent().removeClass('ui-focus'); w.d.wrap.parent().addClass('ui-focus'); } + } + if ( o.useNewStyle === false ) { w.d.input.removeClass('ui-focus'); } + }) + .blur(function(){ + w.d.wrap.removeClass('ui-focus'); + w.d.input.removeClass('ui-focus'); + }) + .change(function() { + w.theDate = w._makeDate(w.d.input.val()); + w.refresh(); + }) + .attr("readonly", o.lockInput) + .on('datebox', w._event); + + if ( o.useNewStyle === true ) { + w.d.input.addClass('ui-corner-all '+((o.useAltIcon===true)?'ui-icon-datebox-alt':'ui-icon-datebox')); + if ( o.overrideStyleClass !== false ) { w.d.input.addClass(o.overrideStyleClass); } + } else { + w.d.input.parent().css('border', 'none').removeClass('ui-shadow-inset'); + } + + w.d.wrap.parent().on(o.clickEvent, function() { + if ( !w.disabled && o.useFocus === true && o.useNewStyle === false ) { + w.d.input.trigger('datebox', {'method': 'open'}); w.d.wrap.addClass('ui-focus'); w.d.input.removeClass('ui-focus'); + setTimeout(function(){ + w.d.wrap.removeClass('ui-focus'); + w.d.wrap.parent().addClass('ui-focus'); + }, 500); + } + }); + + // Check if mousewheel plugin is loaded + if ( typeof $.event.special.mousewheel !== 'undefined' ) { w.wheelExists = true; } + + // Disable when done if element attribute disabled is true. + if ( w.d.input.is(':disabled') ) { + w.disable(); + } + + if ( o.useInline === true || o.useInlineBlind ) { w.open(); } + + w.applyMinMax(false, false); + + //Throw dateboxinit event + $( document ).trigger( "dateboxaftercreate" ); + }, + applyMinMax: function(refresh, override) { + var w = this, + o = this.options, + calc = {}; + + if ( typeof refresh === 'undefined' ) { refresh = false; } + if ( typeof override === 'undefined' ) { override = true; } + + if ( ( override === true || o.minDays === false ) && typeof(w.d.input.attr('min')) !== 'undefined' ) { + calc.today = new w._date(); + calc.lod = 24 * 60 * 60 * 1000; + calc.todayc = new w._date(calc.today.getFullYear(), calc.today.getMonth(), calc.today.getDate(), 0,0,0,0); + calc.fromel = w.d.input.attr('min').split('-'); + calc.compdt = new w._date(calc.fromel[0],calc.fromel[1]-1,calc.fromel[2],0,0,0,0); + o.minDays = parseInt((((calc.compdt.getTime() - calc.todayc.getTime()) / calc.lod))*-1,10); + } + if ( ( override === true || o.maxDays === false ) && typeof(w.d.input.attr('max')) !== 'undefined' ) { + calc.today = new w._date(); + calc.lod = 24 * 60 * 60 * 1000; + calc.todayc = new w._date(calc.today.getFullYear(), calc.today.getMonth(), calc.today.getDate(), 0,0,0,0); + calc.fromel = w.d.input.attr('max').split('-'); + calc.compdt = new w._date(calc.fromel[0],calc.fromel[1]-1,calc.fromel[2],0,0,0,0); + o.maxDays = parseInt((((calc.compdt.getTime() - calc.todayc.getTime()) / calc.lod)),10); + } + + if ( refresh === true ) { w.refresh(); } + }, + _build: { + 'default': function () { + this.d.headerText = "Error"; + this.d.intHTML = $("

              There is no mode by that name loaded / mode not given

              "); + } + }, + _applyCoords: function(e) { + var w = e.widget, + o = e.widget.options, + fixd = { + h: $.mobile.activePage.find('.ui-header').jqmData('position'), + f: $.mobile.activePage.find('.ui-footer').jqmData('position'), + fh: $.mobile.activePage.find('.ui-footer').outerHeight(), + hh: $.mobile.activePage.find('.ui-header').outerHeight() + }, + iput = { + x: w.d.wrap.offset().left + (w.d.wrap.outerWidth() / 2), + y: w.d.wrap.offset().top + (w.d.wrap.outerHeight() / 2) + }, + size = { + w: w.d.mainWrap.outerWidth(), + h: w.d.mainWrap.outerHeight() + }, + doc = { + t: $(window).scrollTop(), + h: $(window).height(), + w: $.mobile.activePage.width(), + ah: $(document).height() + }, + pos = { + y: (o.centerVert) ? doc.t + ((doc.h / 2) - (size.h / 2)) : iput.y - ( size.h / 2 ), + x: (doc.w < 400 || o.centerHoriz ) ? (doc.w / 2) - (size.w /2) : iput.x - (size.w / 2) + }; + + if ( o.centerVert === false ) { + if ( o.hideFixedToolbars === true && ( typeof fixd.f !== 'undefined' || typeof fixd.h !== 'undefined' )) { + $.mobile.activePage.find(":jqmData(position='fixed')").fixedtoolbar('hide'); + fixd.f = undefined; + fixd.h = undefined; + } + + if ( typeof fixd.f !== 'undefined' ) { + if ( ( pos.y + size.h ) > ( doc.h - fixd.fh - 2 ) ) { + pos.y = doc.h - fixd.fh - 2 - size.h; + } + } else { + if ( ( pos.y + size.h ) > ( doc.ah - fixd.fh - 2 ) ) { + pos.y = doc.ah - fixd.fh - 2 - size.h; + } + if ( ( doc.h + doc.t ) < ( size.h + pos.y + 2 ) ) { + pos.y = doc.h + doc.t - size.h - 2; + } + } + + if ( typeof fixd.h !== 'undefined' ) { + if ( ( doc.t + fixd.hh + 2 ) > pos.y ) { + pos.y = doc.t + fixd.hh + 2; + } + } else { + if ( fixd.hh + 2 > pos.y ) { + pos.y = fixd.hh + 2; + } + if ( pos.y < doc.t + 2 ) { + pos.y = doc.t + 2; + } + } + } + w.d.mainWrap.css({'position': 'absolute', 'top': pos.y, 'left': pos.x}); + }, + _drag: { + 'default': function () { return false; } + }, + open: function () { + var w = this, + o = this.options, + popopts = {}, + basepop = {'history':false}, + qns = 'data-'+this.ns, + trans = o.useAnimation ? o.transition : 'none'; + + if ( o.useFocus === true && w.fastReopen === true ) { w.d.input.blur(); return false; } + if ( w.clearFunc !== false ) { + clearTimeout(w.clearFunc); w.clearFunc = false; + } + + // Call the open callback if provided. Additionally, if this + // returns false then the open/update will stop. + if ( o.openCallback !== false ) { + if ( ! $.isFunction(o.openCallback) ) { + if ( typeof window[o.openCallback] !== 'undefined' ) { + o.openCallback = window[o.openCallback]; + } else { + o.openCallback = new Function(o.openCallback); + } + } + if ( o.openCallback.apply(w, $.merge([w.theDate],o.openCallbackArgs)) === false ) { return false; } + } + + w.theDate = w._makeDate(w.d.input.val()); + if ( w.d.input.val() === "" ) { w._startOffset(w.theDate); } + w.d.input.blur(); + + if ( typeof w._build[o.mode] === 'undefined' ) { + w._build['default'].apply(w,[]); + } else { + w._build[o.mode].apply(w,[]); + } + if ( typeof w._drag[o.mode] !== 'undefined' ) { + w._drag[o.mode].apply(w, []); + } + w.d.input.trigger('datebox', {'method':'refresh'}); + if ( w.__('useArabicIndic') === true ) { w._doIndic(); } + + if ( ( o.useInline === true || o.useInlineBlind === true ) && w.initDone === false ) { + w.d.mainWrap.append(w.d.intHTML); + w.d.input.parent().parent().append(w.d.mainWrap); + w.d.mainWrap.removeClass('ui-datebox-hidden'); + if ( o.useInline === true ) { + w.d.mainWrap.addClass('ui-datebox-inline'); + } else { + w.d.mainWrap.addClass('ui-datebox-inlineblind'); + w.d.mainWrap.hide(); + } + w.initDone = false; + w.d.input.trigger('datebox',{'method':'postrefresh'}); + } + + if ( o.useImmediate ) { w.d.input.trigger('datebox', {'method':'doset'}); } + if ( o.useInline ) { return true; } + if ( o.useInlineBlind ) { + if ( w.initDone ) { w.d.mainWrap.slideDown(); } + else { w.initDone = true; } + return true; + } + if ( w.d.intHTML.is(':visible') ) { return false; } // Ignore if already open + + if ( o.enablePopup === true ) { + w.d.dialogPage = false; + w.d.mainWrap.empty(); + if ( o.useHeader === true ) { + w.d.headHTML = $('
              '); + $("Close").appendTo(w.d.headHTML) + .buttonMarkup({ theme : o.themeHeader, icon : 'delete', iconpos: 'notext', corners: true, shadow : true }) + .on(o.clickEventAlt, function(e) { e.preventDefault(); w.d.input.trigger('datebox', {'method':'close'}); }); + $('

              '+w.d.headerText+'

              ').appendTo(w.d.headHTML); + w.d.mainWrap.append(w.d.headHTML); + } + w.d.mainWrap.append(w.d.intHTML).css('zIndex', o.zindex); + w.d.input.trigger('datebox',{'method':'postrefresh'}); + + if ( o.useAnimation === true ) { + popopts.transition = o.transition; + } else { + popopts.transition = "none"; + } + + if ( o.popupForceX !== false && o.popupForceY !== false ) { + popopts.x = o.popupForceX; + popopts.y = o.popupForceY; + } + + if ( o.popupPosition !== false ) { + popopts.positionTo = o.popupPosition; + } else { + if ( typeof w.baseID !== undefined ) { + popopts.positionTo = '#' + w.baseID; + } else { + popopts.positionTo = 'window'; + } + } + + if ( o.useModal === true ) { basepop.overlayTheme = "a"; } + + w.d.mainWrap.removeClass('ui-datebox-hidden').popup(basepop).popup("open", popopts); + w.refresh(); + } else { + if ( o.dialogForce || ( o.dialogEnable && window.width() < 400 ) ) { + w.d.dialogPage = $("
              " + + "
              " + + "

              "+w.d.headerText+"

              ") + .appendTo( $.mobile.pageContainer ) + .page().css('minHeight', '0px').addClass(trans); + w.d.dialogPage.find('.ui-header').find('a').off('click vclick').on(o.clickEventAlt, function(e) { e.preventDefault(); w.d.input.trigger('datebox', {'method':'close'}); }); + w.d.mainWrap.append(w.d.intHTML).css({'marginLeft':'auto', 'marginRight':'auto'}).removeClass('ui-datebox-hidden'); + w.d.dialogPage.find('.ui-content').append(w.d.mainWrap); + w.d.input.trigger('datebox',{'method':'postrefresh'}); + $.mobile.activePage.off( "pagehide.remove" ); + $.mobile.changePage(w.d.dialogPage, {'transition': trans}); + } else { + w.d.dialogPage = false; + w.d.mainWrap.empty(); + if ( o.useHeader === true ) { + w.d.headHTML = $('
              '); + $("Close").appendTo(w.d.headHTML) + .buttonMarkup({ theme : o.themeHeader, icon : 'delete', iconpos: 'notext', corners: true, shadow : true }) + .on(o.clickEventAlt, function(e) { e.preventDefault(); w.d.input.trigger('datebox', {'method':'close'}); }); + $('

              '+w.d.headerText+'

              ').appendTo(w.d.headHTML); + w.d.mainWrap.append(w.d.headHTML); + } + w.d.mainWrap.append(w.d.intHTML).css('zIndex', o.zindex); + w.d.mainWrap.appendTo($.mobile.activePage); + w.d.screen.appendTo($.mobile.activePage); + w.d.input.trigger('datebox',{'method':'postrefresh'}); + w._applyCoords({widget:w}); + + if ( o.useModal === true ) { + if(o.useAnimation) { + w.d.screen.fadeIn('slow'); + } else { + w.d.screen.show(); + } + } else { + setTimeout(function () { w.d.screen.removeClass('ui-datebox-hidden');}, 500); + } + + w.d.mainWrap.addClass('ui-overlay-shadow in').removeClass('ui-datebox-hidden'); + + $(document).on('orientationchange.datebox', {widget:w}, function(e) { w._applyCoords(e.data); }); + if ( o.resizeListener === true ) { + $(window).on('resize.datebox', {widget:w}, function (e) { w._applyCoords(e.data); }); + } + } + } + }, + close: function() { + var w = this, + o = this.options; + + if ( o.useInlineBlind === true ) { w.d.mainWrap.slideUp(); return true;} + if ( o.useInline === true || w.d.intHTML === false ) { return true; } + + if ( w.d.dialogPage !== false ) { + $(w.d.dialogPage).dialog('close'); + + if ( ! $.mobile.activePage.jqmData('mobile-page').options.domCache ) { + $.mobile.activePage.on('pagehide.remove', function () { $(this).remove(); }); + } + + w.d.intHTML.detach().empty(); + w.d.mainWrap.detach().empty(); + w.d.wrap.removeClass('ui-focus'); + w.clearFunc = setTimeout(function () { w.d.dialogPage.empty().remove(); w.clearFunc = false; }, 1500); + } else { + if ( o.enablePopup === true ) { + w.d.mainWrap.popup('close'); + w.d.wrap.removeClass('ui-focus'); + } else { + if ( o.useModal ) { + if(o.useAnimation) { + w.d.screen.fadeOut('slow'); + } else { + w.d.screen.hide(); + } + } else { + w.d.screen.addClass('ui-datebox-hidden'); + } + w.d.screen.detach(); + w.d.mainWrap.addClass('ui-datebox-hidden').removeAttr('style').removeClass('in ui-overlay-shadow').empty().detach(); + w.d.intHTML.detach(); + w.d.wrap.removeClass('ui-focus'); + + $(document).off('orientationchange.datebox'); + if ( o.resizeListener === true ) { + $(window).off('resize.datebox'); + } + } + } + w.d.wrap.parent().removeClass('ui-focus'); + + $(document).off(w.drag.eMove); + $(document).off(w.drag.eEnd); + $(document).off(w.drag.eEndA); + + if ( o.useFocus ) { + w.fastReopen = true; + setTimeout(function(t) { return function () { t.fastReopen = false; };}(w), 300); + } + + if ( o.closeCallback !== false ) { + if ( ! $.isFunction(o.closeCallback) ) { + if ( typeof window[o.closeCallback] !== 'undefined' ) { + o.closeCallback = window[o.closeCallback]; + } else { + o.closeCallback = new Function(o.closeCallback); + } + } + o.closeCallback.apply(w, $.merge([w.theDate], o.closeCallbackArgs)); + } + }, + refresh: function() { + if ( typeof this._build[this.options.mode] === 'undefined' ) { + this._build['default'].apply(this,[]); + } else { + this._build[this.options.mode].apply(this,[]); + } + if ( this.__('useArabicIndic') === true ) { this._doIndic(); } + this.d.mainWrap.append(this.d.intHTML); + this.d.input.trigger('datebox',{'method':'postrefresh'}); + }, + _check: function() { + var w = this, + td = null, + o = this.options; + + w.dateOK = true; + + if ( o.afterToday !== false ) { + td = new w._date(); + if ( w.theDate < td ) { w.theDate = td; } + } + if ( o.beforeToday !== false ) { + td = new w._date(); + if ( w.theDate > td ) { w.theDate = td; } + } + if ( o.maxDays !== false ) { + td = new w._date(); + td.adj(2, o.maxDays); + if ( w.theDate > td ) { w.theDate = td; } + } + if ( o.minDays !== false ) { + td = new w._date(); + td.adj(2, -1*o.minDays); + if ( w.theDate < td ) { w.theDate = td; } + } + if ( o.minHour !== false ) { + if ( w.theDate.getHours() < o.minHour ) { + w.theDate.setHours(o.minHour); + } + } + if ( o.maxHour !== false ) { + if ( w.theDate.getHours() > o.maxHour ) { + w.theDate.setHours(o.maxHour); + } + } + if ( o.maxYear !== false ) { + td = new w._date(o.maxYear, 0, 1); + td.adj(2, -1); + if ( w.theDate > td ) { w.theDate = td; } + } + if ( o.minYear !== false ) { + td = new w._date(o.minYear, 0, 1); + if ( w.theDate < td ) { w.theDate = td; } + } + + if ( $.inArray(o.mode, ['timebox','durationbox','durationflipbox','timeflipbox']) > -1 ) { + if ( o.mode === 'timeflipbox' && o.validHours !== false ) { + if ( $.inArray(w.theDate.getHours(), o.validHours) < 0 ) { w.dateOK = false; } + } + } else { + if ( o.blackDatesRec !== false ) { + for ( i=0; i -1 ) { w.dateOK = false; } + } + if ( o.blackDays !== false ) { + if ( $.inArray(w.theDate.getDay(), o.blackDays) > -1 ) { w.dateOK = false; } + } + } + }, + _grabLabel: function() { + var w = this, + o = this.options; + + if ( typeof o.overrideDialogLabel === 'undefined' ) { + if ( typeof w.d.input.attr('placeholder') !== 'undefined' ) { return w.d.input.attr('placeholder'); } + if ( typeof w.d.input.attr('title') !== 'undefined' ) { return w.d.input.attr('title'); } + if ( w.d.wrap.parent().find('label[for=\''+w.d.input.attr('id')+'\']').text() !== '' ) { + return w.d.wrap.parent().find('label[for=\''+w.d.input.attr('id')+'\']').text(); + } + return false; + } + return o.overrideDialogLabel; + }, + _makeEl: function(source, parts) { + var part = false, + retty = false; + + retty = source.clone(); + + if ( typeof parts.attr !== 'undefined' ) { + for ( part in parts.attr ) { + if ( parts.attr.hasOwnProperty(part) ) { + retty.jqmData(part, parts.attr[part]); + } + } + } + return retty; + }, + _getLongOptions: function(element) { + var key, retty = {}, prefix, temp; + + if ( $.mobile.ns === "" ) { + prefix = "datebox"; + } else { + prefix = $.mobile.ns.substr(0, $.mobile.ns.length - 1) + 'Datebox'; + } + + for ( key in element.data() ) { + if ( key.substr(0, prefix.length) === prefix && key.length > prefix.length ) { + temp = key.substr(prefix.length); + temp = temp.charAt(0).toLowerCase() + temp.slice(1); + retty[temp] = element.data(key); + } + } + return retty; + }, + disable: function(){ + // Disable the element + this.d.input.attr("disabled",true); + this.d.wrap.addClass("ui-disabled").blur(); + this.disabled = true; + this.d.input.trigger('datebox', {'method':'disable'}); + }, + enable: function(){ + // Enable the element + this.d.input.attr("disabled", false); + this.d.wrap.removeClass("ui-disabled"); + this.disabled = false; + this.d.input.trigger('datebox', {'method':'enable'}); + }, + _setOption: function() { + $.Widget.prototype._setOption.apply( this, arguments ); + this.refresh(); + }, + getTheDate: function() { + return this.theDate; + }, + getLastDur: function() { + return this.lastDuration; + }, + setTheDate: function(newDate) { + this.theDate = newDate; + this.refresh(); + }, + callFormat: function(format, date) { + return this._formatter(format, date); + } + }); + + // Degrade date inputs to text inputs, suppress standard UI functions. + $( document ).on( "pagebeforecreate", function( e ) { + $( ":jqmData(role='datebox')", e.target ).each(function() { + $(this).prop('type', 'text'); + }); + }); + // Automatically bind to data-role='datebox' items. + $( document ).on( "pagecreate create", function( e ){ + $( document ).trigger( "dateboxbeforecreate" ); + $( ":jqmData(role='datebox')", e.target ).each(function() { + var defed = typeof ($(this).data(parseInt($.mobile.version.replace(/\./g,''),10) > 111 ? 'mobile-datebox' : 'datebox')); + if ( defed === "undefined" ) { + $(this).datebox(); + } + }); + }); +})( jQuery ); diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.core.min.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.core.min.js new file mode 100644 index 000000000..ce7ea9bd6 --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.core.min.js @@ -0,0 +1,7 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +(function(a){a.widget("mobile.datebox",a.mobile.widget,{options:{version:"2-1.4.0-2013070300",mobVer:parseInt(a.mobile.version.replace(/\./g,"")),theme:false,themeDefault:"a",themeHeader:"a",mode:false,centerHoriz:false,centerVert:false,transition:"pop",useAnimation:true,hideInput:false,hideFixedToolbars:false,lockInput:true,enhanceInput:true,zindex:"500",clickEvent:"vclick",clickEventAlt:"click",resizeListener:true,defaultValue:false,showInitialValue:false,dialogEnable:false,dialogForce:false,enablePopup:false,popupPosition:false,popupForceX:false,popupForceY:false,useModal:false,useInline:false,useInlineBlind:false,useHeader:true,useImmediate:false,useNewStyle:false,useAltIcon:false,overrideStyleClass:false,useButton:true,useFocus:false,useClearButton:false,useCollapsedBut:false,usePlaceholder:false,openCallback:false,openCallbackArgs:[],closeCallback:false,closeCallbackArgs:[],startOffsetYears:false,startOffsetMonths:false,startOffsetDays:false,afterToday:false,beforeToday:false,notToday:false,maxDays:false,minDays:false,maxYear:false,minYear:false,blackDates:false,blackDatesRec:false,blackDays:false,minHour:false,maxHour:false,minuteStep:1,minuteStepRound:0,rolloverMode:{m:true,d:true,h:true,i:true,s:true},useLang:"default",lang:{"default":{setDateButtonLabel:"Set Date",setTimeButtonLabel:"Set Time",setDurationButtonLabel:"Set Duration",calTodayButtonLabel:"Jump to Today",titleDateDialogLabel:"Set Date",titleTimeDialogLabel:"Set Time",daysOfWeek:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],daysOfWeekShort:["Su","Mo","Tu","We","Th","Fr","Sa"],monthsOfYear:["January","February","March","April","May","June","July","August","September","October","November","December"],monthsOfYearShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],durationLabel:["Days","Hours","Minutes","Seconds"],durationDays:["Day","Days"],timeFormat:24,headerFormat:"%A, %B %-d, %Y",tooltip:"Open Date Picker",nextMonth:"Next Month",prevMonth:"Previous Month",dateFieldOrder:["m","d","y"],timeFieldOrder:["h","i","a"],slideFieldOrder:["y","m","d"],dateFormat:"%Y-%m-%d",useArabicIndic:false,isRTL:false,calStartDay:0,clearButton:"Clear",durationOrder:["d","h","i","s"],meridiem:["AM","PM"],timeOutput:"%k:%M",durationFormat:"%Dd %DA, %Dl:%DM:%DS",calDateListLabel:"Other Dates",calHeaderFormat:"%B %Y"}}},_enhanceDate:function(){a.extend(this._date.prototype,{copy:function(c,b){if(typeof c==="undefined"){c=[0,0,0,0,0,0,0]}if(typeof b==="undefined"){b=[0,0,0,0,0,0,0]}while(c.length<7){c.push(0)}while(b.length<7){b.push(0)}return new Date(((b[0]>0)?b[0]:this.getFullYear()+c[0]),((b[1]>0)?b[1]:this.getMonth()+c[1]),((b[2]>0)?b[2]:this.getDate()+c[2]),((b[3]>0)?b[3]:this.getHours()+c[3]),((b[4]>0)?b[4]:this.getMinutes()+c[4]),((b[5]>0)?b[5]:this.getSeconds()+c[5]),((b[6]>0)?b[5]:this.getMilliseconds()+c[6]))},adj:function(c,b){if(typeof b!=="number"){throw new Error("Adjustment value not specified")}if(typeof c!=="number"){throw new Error("Adjustment type not specified")}switch(c){case 0:this.setFullYear(this.getFullYear()+b);break;case 1:this.setMonth(this.getMonth()+b);break;case 2:this.setDate(this.getDate()+b);break;case 3:this.setHours(this.getHours()+b);break;case 4:this.setMinutes(this.getMinutes()+b);break;case 5:this.setSeconds(this.getSeconds()+b);break;case 6:this.setMilliseconds(this.getMilliseconds()+b);break}return this},setD:function(c,b){switch(c){case 0:this.setFullYear(b);break;case 1:this.setMonth(b);break;case 2:this.setDate(b);break;case 3:this.setHours(b);break;case 4:this.setMinutes(b);break;case 5:this.setSeconds(b);break;case 6:this.setMilliseconds(b);break}return this},get:function(b){switch(b){case 0:return this.getFullYear();case 1:return this.getMonth();case 2:return this.getDate();case 3:return this.getHours();case 4:return this.getMinutes();case 5:return this.getSeconds()}return false},iso:function(){return String(this.getFullYear())+"-"+((this.getMonth()<9)?"0":"")+String(this.getMonth()+1)+"-"+((this.getDate()<10)?"0":"")+String(this.getDate())},comp:function(){return parseInt(this.iso().replace(/-/g,""),10)},getEpoch:function(){return(this.getTime()-this.getMilliseconds())/1000},getArray:function(){return[this.getFullYear(),this.getMonth(),this.getDate(),this.getHours(),this.getMinutes(),this.getSeconds()]},setFirstDay:function(b){this.setD(2,1).adj(2,(b-this.getDay()));if(this.get(2)>10){this.adj(2,7)}return this},setDWeek:function(c,b){if(c===4){return this.setD(1,0).setD(2,1).setFirstDay(4).adj(2,-3).adj(2,(b-1)*7)}return this.setD(1,0).setD(2,1).setFirstDay(c).adj(2,(b-1)*7)},getDWeek:function(c){var d,b;switch(c){case 0:d=this.copy([0,-1*this.getMonth()]).setFirstDay(0);return Math.floor((this.getTime()-(d.getTime()+((this.getTimezoneOffset()-d.getTimezoneOffset())*60000)))/604800000)+1;case 1:d=this.copy([0,-1*this.getMonth()]).setFirstDay(1);return Math.floor((this.getTime()-(d.getTime()+((this.getTimezoneOffset()-d.getTimezoneOffset())*60000)))/604800000)+1;case 4:if(this.getMonth()===11&&this.getDate()>28){return 1}d=this.copy([0,-1*this.getMonth()],true).setFirstDay(4).adj(2,-3);b=Math.floor((this.getTime()-(d.getTime()+((this.getTimezoneOffset()-d.getTimezoneOffset())*60000)))/604800000)+1;if(b<1){d=this.copy([-1,-1*this.getMonth()]).setFirstDay(4).adj(2,-3);return Math.floor((this.getTime()-d.getTime())/604800000)+1}return b;default:return 0}}})},_event:function(d,c){var b=a(this).data(parseInt(a.mobile.version.replace(/\./g,""),10)>110?"mobile-datebox":"datebox");if(!d.isPropagationStopped()){switch(c.method){case"close":b.close();break;case"open":b.open();break;case"set":a(this).val(c.value);a(this).trigger("change");break;case"doset":if(a.isFunction(b["_"+b.options.mode+"DoSet"])){b["_"+b.options.mode+"DoSet"].apply(b,[])}else{a(this).trigger("datebox",{method:"set",value:b._formatter(b.__fmt(),b.theDate),date:b.theDate})}break;case"dooffset":if(c.type){b._offset(c.type,c.amount,true)}break;case"dorefresh":b.refresh();break;case"doreset":b.hardreset();break;case"doclear":a(this).val("").trigger("change");break;case"clear":a(this).trigger("change")}}},_hoover:function(b){a(b).toggleClass("ui-btn-up-"+a(b).jqmData("theme")+" ui-btn-down-"+a(b).jqmData("theme"))},_ord:{"default":function(c){var b=c%10;if(c>9&&c<21){return"th"}if(b>3){return"th"}return["th","st","nd","rd"][b]}},__:function(d){var c=this.options,b="override"+d.charAt(0).toUpperCase()+d.slice(1);if(typeof c[b]!=="undefined"){return c[b]}if(typeof c.lang[c.useLang][d]!=="undefined"){return c.lang[c.useLang][d]}if(typeof c[c.mode+"lang"]!=="undefined"&&typeof c[c.mode+"lang"][d]!=="undefined"){return c[c.mode+"lang"][d]}return c.lang["default"][d]},__fmt:function(){var b=this,c=this.options;switch(c.mode){case"timebox":case"timeflipbox":return b.__("timeOutput");case"durationbox":case"durationflipbox":return b.__("durationFormat");default:return b.__("dateFormat")}},_zPad:function(b){return((b<10)?"0"+String(b):String(b))},_dRep:function(j,g){var h=48,b=57,c=1584,d=null,e=null,f="";if(g===-1){h+=c;b+=c;c=-1584}for(d=0;d=h&&e<=b){f=f+String.fromCharCode(e+c)}else{f=f+String.fromCharCode(e)}}return f},_doIndic:function(){var b=this;b.d.intHTML.find("*").each(function(){if(a(this).children().length<1){a(this).text(b._dRep(a(this).text()))}else{if(a(this).hasClass("ui-datebox-slideday")){a(this).html(b._dRep(a(this).html()))}}});b.d.intHTML.find("input").each(function(){a(this).val(b._dRep(a(this).val()))})},_parser:{"default":function(b){return false}},_n:function(c,b){return(c<0)?b:c},_pa:function(b,c){if(typeof c==="boolean"){return new this._date(b[0],b[1],b[2],0,0,0,0)}return new this._date(c.getFullYear(),c.getMonth(),c.getDate(),b[0],b[1],b[2],0)},_makeDate:function(k){k=a.trim(((this.__("useArabicIndic")===true)?this._dRep(k,-1):k));var n=this,c=this.options,e=n.__fmt(),m=null,h=[],l=null,b=null,f=new n._date(),j={year:-1,mont:-1,date:-1,hour:-1,mins:-1,secs:-1,week:false,wtyp:4,wday:false,yday:false,meri:0},g;if(typeof c.mode==="undefined"){return f}if(typeof n._parser[c.mode]!=="undefined"){return n._parser[c.mode].apply(n,[k])}if(c.mode==="durationbox"||c.mode==="durationflipbox"){e=e.replace(/%D([a-z])/gi,function(d,o){switch(o){case"d":case"l":case"M":case"S":return"("+d+"|[0-9]+)";default:return".+?"}});e=new RegExp("^"+e+"$");m=e.exec(k);l=e.exec(n.__fmt());if(m===null||m.length!==l.length){if(typeof c.defaultValue==="number"&&c.defaultValue>0){return new n._date((n.initDate.getEpoch()+parseInt(c.defaultValue,10))*1000)}return new n._date(n.initDate.getTime())}b=n.initDate.getEpoch();for(g=0;g-1){j.mont=b}break;case"B":b=a.inArray(m[g],n.__("monthsOfYear"));if(b>-1){j.mont=b}break}}if(j.meri!==0){if(j.meri===-1&&j.hour===12){j.hour=0}if(j.meri===1&&j.hour!==12){j.hour=j.hour+12}}f=new n._date(n._n(j.year,0),n._n(j.mont,0),n._n(j.date,1),n._n(j.hour,0),n._n(j.mins,0),n._n(j.secs,0),0);if(j.year<100&&j.year!==-1){f.setFullYear(j.year)}if((j.mont>-1&&j.date>-1)||(j.hour>-1&&j.mins>-1&&j.secs>-1)){return f}if(j.week!==false){f.setDWeek(j.wtyp,j.week);if(j.date>-1){f.setDate(j.date)}}if(j.yday!==false){f.setD(1,0).setD(2,1).adj(2,(j.yday-1))}if(j.wday!==false){f.adj(2,(j.wday-f.getDay()))}}return f},_customformat:{"default":function(c,b){return false}},_formatter:function(f,c){var b=this,g=this.options,d,e={part:[0,0,0,0],tp:0};if(g.mode==="durationbox"||g.mode==="durationflipbox"){e.tp=this.theDate.getEpoch()-this.initDate.getEpoch();e.part[0]=parseInt(e.tp/(60*60*24),10);e.tp-=(e.part[0]*60*60*24);e.part[1]=parseInt(e.tp/(60*60),10);e.tp-=(e.part[1]*60*60);e.part[2]=parseInt(e.tp/(60),10);e.tp-=(e.part[2]*60);e.part[3]=e.tp;if(!f.match(/%Dd/)){e.part[1]+=(e.part[0]*24)}if(!f.match(/%Dl/)){e.part[2]+=(e.part[1]*60)}if(!f.match(/%DM/)){e.part[3]+=(e.part[2]*60)}}f=f.replace(/%(D|X|0|-)*([1-9a-zA-Z])/g,function(h,j,k){if(j==="X"){if(typeof b._customformat[g.mode]!=="undefined"){return b._customformat[g.mode](k,c,g)}return h}if(j==="D"){switch(k){case"d":return e.part[0];case"l":return b._zPad(e.part[1]);case"M":return b._zPad(e.part[2]);case"S":return b._zPad(e.part[3]);case"A":return((e.part[0]>1)?b.__("durationDays")[1]:b.__("durationDays")[0]);default:return h}}switch(k){case"%":return"%";case"a":return b.__("daysOfWeekShort")[c.getDay()];case"A":return b.__("daysOfWeek")[c.getDay()];case"b":return b.__("monthsOfYearShort")[c.getMonth()];case"B":return b.__("monthsOfYear")[c.getMonth()];case"C":return c.getFullYear().toString().substr(0,2);case"d":return((j==="-")?c.getDate():b._zPad(c.getDate()));case"H":case"k":return((j==="-")?c.getHours():b._zPad(c.getHours()));case"I":case"l":return((j==="-")?((c.getHours()===0||c.getHours()===12)?12:((c.getHours()<12)?c.getHours():(c.getHours()-12))):b._zPad(((c.getHours()===0||c.getHours()===12)?12:((c.getHours()<12)?c.getHours():c.getHours()-12))));case"m":return((j==="-")?c.getMonth()+1:b._zPad(c.getMonth()+1));case"M":return((j==="-")?c.getMinutes():b._zPad(c.getMinutes()));case"p":return((c.getHours()<12)?b.__("meridiem")[0].toUpperCase():b.__("meridiem")[1].toUpperCase());case"P":return((c.getHours()<12)?b.__("meridiem")[0].toLowerCase():b.__("meridiem")[1].toLowerCase());case"s":return c.getEpoch();case"S":return((j==="-")?c.getSeconds():b._zPad(c.getSeconds()));case"u":return((j==="-")?c.getDay()+1:b._zPad(c.getDay()+1));case"w":return c.getDay();case"y":return c.getFullYear().toString().substr(2,2);case"Y":return c.getFullYear();case"E":return c.getFullYear()+543;case"V":return((j==="-")?c.getDWeek(4):b._zPad(c.getDWeek(4)));case"U":return((j==="-")?c.getDWeek(0):b._zPad(c.getDWeek(0)));case"W":return((j==="-")?c.getDWeek(1):b._zPad(c.getDWeek(1)));case"o":if(typeof b._ord[g.useLang]!=="undefined"){return b._ord[g.useLang](c.getDate())}return b._ord["default"](c.getDate());case"j":d=new Date(c.getFullYear(),0,1);d=Math.ceil((c-d)/86400000)+1;return((d<100)?((d<10)?"00":"0"):"")+String(d);case"G":if(c.getDWeek(4)===1&&c.getMonth()>0){return c.getFullYear()+1}if(c.getDWeek(4)>51&&c.getMonth()<11){return c.getFullYear()-1}return c.getFullYear();case"g":if(c.getDWeek(4)===1&&c.getMonth()>0){return parseInt(c.getFullYear().toString().substr(2,2),10)+1}if(c.getDWeek(4)>51&&c.getMonth()<11){return parseInt(c.getFullYear().toString().substr(2,2),10)-1}return c.getFullYear().toString().substr(2,2);default:return h}});if(b.__("useArabicIndic")===true){f=b._dRep(f)}return f},_btwn:function(d,b,c){return(d>b&&d1&&d%e.minuteStep>0){if(e.minuteStepRound<0){d=d-(d%e.minuteStep)}else{if(e.minStepRound>0){d=d+(e.minuteStep-(d%e.minuteStep))}else{if(d%e.minuteStep0)?1:-1)*12,false);break}}if(c!==false){b.theDate.adj(c,d)}if(g===true){b.refresh()}if(e.useImmediate){b.d.input.trigger("datebox",{method:"doset"})}},_startOffset:function(b){var c=this.options;if(c.startOffsetYears!==false){b.adj(0,c.startOffsetYears)}if(c.startOffsetMonths!==false){b.adj(1,c.startOffsetMonths)}if(c.startOffsetDays!==false){b.adj(2,c.startOffsetDays)}return b},_create:function(){a(document).trigger("dateboxcreate");var j=this,b=a.extend(this.options,(typeof this.element.jqmData("options")!=="undefined")?this.element.jqmData("options"):this._getLongOptions(this.element)),k=(b.theme===false&&typeof(a(this).jqmData("theme"))==="undefined")?((typeof(this.element.parentsUntil(":jqmData(theme)").parent().jqmData("theme"))==="undefined")?b.themeDefault:this.element.parentsUntil(":jqmData(theme)").parent().jqmData("theme")):b.theme,l=b.useAnimation?b.transition:"none",g=b.useNewStyle===false?{input:this.element,wrap:this.element.wrap('
              ').parent(),mainWrap:a("
              ",{"class":"ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden "+l+" ui-body-"+k}).css("zIndex",b.zindex),intHTML:false}:{input:this.element,wrap:this.element,mainWrap:a("
              ",{"class":"ui-datebox-container ui-overlay-shadow ui-corner-all ui-datebox-hidden "+l+" ui-body-"+k}).css("zIndex",b.zindex),intHTML:false},e=(typeof window.ontouchstart!=="undefined"),f={eStart:(e?"touchstart":"mousedown")+".datebox",eMove:(e?"touchmove":"mousemove")+".datebox",eEnd:(e?"touchend":"mouseup")+".datebox",eEndA:(e?"mouseup.datebox touchend.datebox touchcancel.datebox touchmove.datebox":"mouseup.datebox"),move:false,start:false,end:false,pos:false,target:false,delta:false,tmp:false},c={},h=(typeof a.mobile.ns!=="undefined")?a.mobile.ns:"";a.extend(j,{d:g,ns:h,drag:f,touch:e});if(b.usePlaceholder!==false){if(b.usePlaceholder===true&&j._grabLabel()!==false){j.d.input.attr("placeholder",j._grabLabel())}if(typeof b.usePlaceholder==="string"){j.d.input.attr("placeholder",b.usePlaceholder)}}b.theme=k;j.clearFunc=false;j.disabled=false;j.runButton=false;j._date=window.Date;j._enhanceDate();j.baseID=j.d.input.attr("id");j.initDate=new j._date();j.theDate=(b.defaultValue)?j._makeDate(b.defaultValue):((j.d.input.val()!=="")?j._makeDate(j.d.input.val()):new j._date());j.initDone=false;if(b.showInitialValue===true){j.d.input.val(j._formatter(j.__fmt(),j.theDate))}if(b.useButton===true&&b.useInline===false&&b.useNewStyle===false){j.d.open=a(''+this.__("tooltip")+"").on(b.clickEvent,function(d){d.preventDefault();if(!j.disabled){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.parent().addClass("ui-focus");j.d.input.parent().removeClass("ui-focus")}setTimeout(function(){a(d.target).closest("a").removeClass(a.mobile.activeBtnClass)},300)}).appendTo(j.d.wrap).buttonMarkup({icon:"grid",iconpos:"notext",corners:true,shadow:true}).css({"vertical-align":"middle",display:"inline-block"})}j.d.screen=a("
              ",{"class":"ui-datebox-screen ui-datebox-hidden"+((b.useModal)?" ui-datebox-screen-modal":"")}).css({"z-index":b.zindex-1}).on(b.clickEventAlt,function(d){d.preventDefault();j.d.input.trigger("datebox",{method:"close"})});if(b.enhanceInput===true&&navigator.userAgent.match(/Android/i)){j.inputType="number"}else{j.inputType="text"}if(b.hideInput){j.d.wrap.parent().hide()}if(b.mobVer<140){a("label[for='"+j.d.input.attr("id")+"']").addClass("ui-input-text").css("verticalAlign","middle")}j.d.wrap.on(b.clickEvent,function(){if(!j.disabled&&(b.noButtonFocusMode||b.focusMode)){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.addClass("ui-focus");j.d.input.removeClass("ui-focus")}});j.d.input.removeClass("ui-corner-all ui-shadow-inset").bind(j.touch?"touchend":"click",function(d){if(j.disabled===false&&b.useNewStyle===true&&b.useFocus===false){if(((j.touch?d.originalEvent.changedTouches[0].pageX:d.pageX)-d.target.offsetLeft)>(d.target.offsetWidth-20)){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.parent().addClass("ui-focus");j.d.input.removeClass("ui-focus")}}}).focus(function(){if(j.disabled===false&&b.useFocus===true){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.addClass("ui-focus");j.d.input.removeClass("ui-focus");if(b.useNewStyle===false){j.d.input.parent().removeClass("ui-focus");j.d.wrap.parent().addClass("ui-focus")}}if(b.useNewStyle===false){j.d.input.removeClass("ui-focus")}}).blur(function(){j.d.wrap.removeClass("ui-focus");j.d.input.removeClass("ui-focus")}).change(function(){j.theDate=j._makeDate(j.d.input.val());j.refresh()}).attr("readonly",b.lockInput).on("datebox",j._event);if(b.useNewStyle===true){j.d.input.addClass("ui-corner-all "+((b.useAltIcon===true)?"ui-icon-datebox-alt":"ui-icon-datebox"));if(b.overrideStyleClass!==false){j.d.input.addClass(b.overrideStyleClass)}}else{j.d.input.parent().css("border","none").removeClass("ui-shadow-inset")}j.d.wrap.parent().on(b.clickEvent,function(){if(!j.disabled&&b.useFocus===true&&b.useNewStyle===false){j.d.input.trigger("datebox",{method:"open"});j.d.wrap.addClass("ui-focus");j.d.input.removeClass("ui-focus");setTimeout(function(){j.d.wrap.removeClass("ui-focus");j.d.wrap.parent().addClass("ui-focus")},500)}});if(typeof a.event.special.mousewheel!=="undefined"){j.wheelExists=true}if(j.d.input.is(":disabled")){j.disable()}if(b.useInline===true||b.useInlineBlind){j.open()}j.applyMinMax(false,false);a(document).trigger("dateboxaftercreate")},applyMinMax:function(e,d){var b=this,f=this.options,c={};if(typeof e==="undefined"){e=false}if(typeof d==="undefined"){d=true}if((d===true||f.minDays===false)&&typeof(b.d.input.attr("min"))!=="undefined"){c.today=new b._date();c.lod=24*60*60*1000;c.todayc=new b._date(c.today.getFullYear(),c.today.getMonth(),c.today.getDate(),0,0,0,0);c.fromel=b.d.input.attr("min").split("-");c.compdt=new b._date(c.fromel[0],c.fromel[1]-1,c.fromel[2],0,0,0,0);f.minDays=parseInt((((c.compdt.getTime()-c.todayc.getTime())/c.lod))*-1,10)}if((d===true||f.maxDays===false)&&typeof(b.d.input.attr("max"))!=="undefined"){c.today=new b._date();c.lod=24*60*60*1000;c.todayc=new b._date(c.today.getFullYear(),c.today.getMonth(),c.today.getDate(),0,0,0,0);c.fromel=b.d.input.attr("max").split("-");c.compdt=new b._date(c.fromel[0],c.fromel[1]-1,c.fromel[2],0,0,0,0);f.maxDays=parseInt((((c.compdt.getTime()-c.todayc.getTime())/c.lod)),10)}if(e===true){b.refresh()}},_build:{"default":function(){this.d.headerText="Error";this.d.intHTML=a("

              There is no mode by that name loaded / mode not given

              ")}},_applyCoords:function(h){var b=h.widget,j=h.widget.options,f={h:a.mobile.activePage.find(".ui-header").jqmData("position"),f:a.mobile.activePage.find(".ui-footer").jqmData("position"),fh:a.mobile.activePage.find(".ui-footer").outerHeight(),hh:a.mobile.activePage.find(".ui-header").outerHeight()},c={x:b.d.wrap.offset().left+(b.d.wrap.outerWidth()/2),y:b.d.wrap.offset().top+(b.d.wrap.outerHeight()/2)},d={w:b.d.mainWrap.outerWidth(),h:b.d.mainWrap.outerHeight()},g={t:a(window).scrollTop(),h:a(window).height(),w:a.mobile.activePage.width(),ah:a(document).height()},k={y:(j.centerVert)?g.t+((g.h/2)-(d.h/2)):c.y-(d.h/2),x:(g.w<400||j.centerHoriz)?(g.w/2)-(d.w/2):c.x-(d.w/2)};if(j.centerVert===false){if(j.hideFixedToolbars===true&&(typeof f.f!=="undefined"||typeof f.h!=="undefined")){a.mobile.activePage.find(":jqmData(position='fixed')").fixedtoolbar("hide");f.f=undefined;f.h=undefined}if(typeof f.f!=="undefined"){if((k.y+d.h)>(g.h-f.fh-2)){k.y=g.h-f.fh-2-d.h}}else{if((k.y+d.h)>(g.ah-f.fh-2)){k.y=g.ah-f.fh-2-d.h}if((g.h+g.t)<(d.h+k.y+2)){k.y=g.h+g.t-d.h-2}}if(typeof f.h!=="undefined"){if((g.t+f.hh+2)>k.y){k.y=g.t+f.hh+2}}else{if(f.hh+2>k.y){k.y=f.hh+2}if(k.y
              ');a("Close").appendTo(b.d.headHTML).buttonMarkup({theme:g.themeHeader,icon:"delete",iconpos:"notext",corners:true,shadow:true}).on(g.clickEventAlt,function(h){h.preventDefault();b.d.input.trigger("datebox",{method:"close"})});a('

              '+b.d.headerText+"

              ").appendTo(b.d.headHTML);b.d.mainWrap.append(b.d.headHTML)}b.d.mainWrap.append(b.d.intHTML).css("zIndex",g.zindex);b.d.input.trigger("datebox",{method:"postrefresh"});if(g.useAnimation===true){e.transition=g.transition}else{e.transition="none"}if(g.popupForceX!==false&&g.popupForceY!==false){e.x=g.popupForceX;e.y=g.popupForceY}if(g.popupPosition!==false){e.positionTo=g.popupPosition}else{if(typeof b.baseID!==undefined){e.positionTo="#"+b.baseID}else{e.positionTo="window"}}if(g.useModal===true){f.overlayTheme="a"}b.d.mainWrap.removeClass("ui-datebox-hidden").popup(f).popup("open",e);b.refresh()}else{if(g.dialogForce||(g.dialogEnable&&window.width()<400)){b.d.dialogPage=a("

              "+b.d.headerText+"

              ").appendTo(a.mobile.pageContainer).page().css("minHeight","0px").addClass(c);b.d.dialogPage.find(".ui-header").find("a").off("click vclick").on(g.clickEventAlt,function(h){h.preventDefault();b.d.input.trigger("datebox",{method:"close"})});b.d.mainWrap.append(b.d.intHTML).css({marginLeft:"auto",marginRight:"auto"}).removeClass("ui-datebox-hidden");b.d.dialogPage.find(".ui-content").append(b.d.mainWrap);b.d.input.trigger("datebox",{method:"postrefresh"});a.mobile.activePage.off("pagehide.remove");a.mobile.changePage(b.d.dialogPage,{transition:c})}else{b.d.dialogPage=false;b.d.mainWrap.empty();if(g.useHeader===true){b.d.headHTML=a('
              ');a("Close").appendTo(b.d.headHTML).buttonMarkup({theme:g.themeHeader,icon:"delete",iconpos:"notext",corners:true,shadow:true}).on(g.clickEventAlt,function(h){h.preventDefault();b.d.input.trigger("datebox",{method:"close"})});a('

              '+b.d.headerText+"

              ").appendTo(b.d.headHTML);b.d.mainWrap.append(b.d.headHTML)}b.d.mainWrap.append(b.d.intHTML).css("zIndex",g.zindex);b.d.mainWrap.appendTo(a.mobile.activePage);b.d.screen.appendTo(a.mobile.activePage);b.d.input.trigger("datebox",{method:"postrefresh"});b._applyCoords({widget:b});if(g.useModal===true){if(g.useAnimation){b.d.screen.fadeIn("slow")}else{b.d.screen.show()}}else{setTimeout(function(){b.d.screen.removeClass("ui-datebox-hidden")},500)}b.d.mainWrap.addClass("ui-overlay-shadow in").removeClass("ui-datebox-hidden");a(document).on("orientationchange.datebox",{widget:b},function(h){b._applyCoords(h.data)});if(g.resizeListener===true){a(window).on("resize.datebox",{widget:b},function(h){b._applyCoords(h.data)})}}}},close:function(){var b=this,c=this.options;if(c.useInlineBlind===true){b.d.mainWrap.slideUp();return true}if(c.useInline===true||b.d.intHTML===false){return true}if(b.d.dialogPage!==false){a(b.d.dialogPage).dialog("close");if(!a.mobile.activePage.jqmData("mobile-page").options.domCache){a.mobile.activePage.on("pagehide.remove",function(){a(this).remove()})}b.d.intHTML.detach().empty();b.d.mainWrap.detach().empty();b.d.wrap.removeClass("ui-focus");b.clearFunc=setTimeout(function(){b.d.dialogPage.empty().remove();b.clearFunc=false},1500)}else{if(c.enablePopup===true){b.d.mainWrap.popup("close");b.d.wrap.removeClass("ui-focus")}else{if(c.useModal){if(c.useAnimation){b.d.screen.fadeOut("slow")}else{b.d.screen.hide()}}else{b.d.screen.addClass("ui-datebox-hidden")}b.d.screen.detach();b.d.mainWrap.addClass("ui-datebox-hidden").removeAttr("style").removeClass("in ui-overlay-shadow").empty().detach();b.d.intHTML.detach();b.d.wrap.removeClass("ui-focus");a(document).off("orientationchange.datebox");if(c.resizeListener===true){a(window).off("resize.datebox")}}}b.d.wrap.parent().removeClass("ui-focus");a(document).off(b.drag.eMove);a(document).off(b.drag.eEnd);a(document).off(b.drag.eEndA);if(c.useFocus){b.fastReopen=true;setTimeout(function(d){return function(){d.fastReopen=false}}(b),300)}if(c.closeCallback!==false){if(!a.isFunction(c.closeCallback)){if(typeof window[c.closeCallback]!=="undefined"){c.closeCallback=window[c.closeCallback]}else{c.closeCallback=new Function(c.closeCallback)}}c.closeCallback.apply(b,a.merge([b.theDate],c.closeCallbackArgs))}},refresh:function(){if(typeof this._build[this.options.mode]==="undefined"){this._build["default"].apply(this,[])}else{this._build[this.options.mode].apply(this,[])}if(this.__("useArabicIndic")===true){this._doIndic()}this.d.mainWrap.append(this.d.intHTML);this.d.input.trigger("datebox",{method:"postrefresh"})},_check:function(){var b=this,d=null,c=this.options;b.dateOK=true;if(c.afterToday!==false){d=new b._date();if(b.theDated){b.theDate=d}}if(c.maxDays!==false){d=new b._date();d.adj(2,c.maxDays);if(b.theDate>d){b.theDate=d}}if(c.minDays!==false){d=new b._date();d.adj(2,-1*c.minDays);if(b.theDatec.maxHour){b.theDate.setHours(c.maxHour)}}if(c.maxYear!==false){d=new b._date(c.maxYear,0,1);d.adj(2,-1);if(b.theDate>d){b.theDate=d}}if(c.minYear!==false){d=new b._date(c.minYear,0,1);if(b.theDate-1){if(c.mode==="timeflipbox"&&c.validHours!==false){if(a.inArray(b.theDate.getHours(),c.validHours)<0){b.dateOK=false}}}else{if(c.blackDatesRec!==false){for(i=0;i-1){b.dateOK=false}}if(c.blackDays!==false){if(a.inArray(b.theDate.getDay(),c.blackDays)>-1){b.dateOK=false}}}},_grabLabel:function(){var b=this,c=this.options;if(typeof c.overrideDialogLabel==="undefined"){if(typeof b.d.input.attr("placeholder")!=="undefined"){return b.d.input.attr("placeholder")}if(typeof b.d.input.attr("title")!=="undefined"){return b.d.input.attr("title")}if(b.d.wrap.parent().find("label[for='"+b.d.input.attr("id")+"']").text()!==""){return b.d.wrap.parent().find("label[for='"+b.d.input.attr("id")+"']").text()}return false}return c.overrideDialogLabel},_makeEl:function(d,e){var b=false,c=false;c=d.clone();if(typeof e.attr!=="undefined"){for(b in e.attr){if(e.attr.hasOwnProperty(b)){c.jqmData(b,e.attr[b])}}}return c},_getLongOptions:function(d){var c,e={},f,b;if(a.mobile.ns===""){f="datebox"}else{f=a.mobile.ns.substr(0,a.mobile.ns.length-1)+"Datebox"}for(c in d.data()){if(c.substr(0,f.length)===f&&c.length>f.length){b=c.substr(f.length);b=b.charAt(0).toLowerCase()+b.slice(1);e[b]=d.data(c)}}return e},disable:function(){this.d.input.attr("disabled",true);this.d.wrap.addClass("ui-disabled").blur();this.disabled=true;this.d.input.trigger("datebox",{method:"disable"})},enable:function(){this.d.input.attr("disabled",false);this.d.wrap.removeClass("ui-disabled");this.disabled=false;this.d.input.trigger("datebox",{method:"enable"})},_setOption:function(){a.Widget.prototype._setOption.apply(this,arguments);this.refresh()},getTheDate:function(){return this.theDate},getLastDur:function(){return this.lastDuration},setTheDate:function(b){this.theDate=b;this.refresh()},callFormat:function(c,b){return this._formatter(c,b)}});a(document).on("pagebeforecreate",function(b){a(":jqmData(role='datebox')",b.target).each(function(){a(this).prop("type","text")})});a(document).on("pagecreate create",function(b){a(document).trigger("dateboxbeforecreate");a(":jqmData(role='datebox')",b.target).each(function(){var c=typeof(a(this).data(parseInt(a.mobile.version.replace(/\./g,""),10)>111?"mobile-datebox":"datebox"));if(c==="undefined"){a(this).datebox()}})})})(jQuery); \ No newline at end of file diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.css b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.css new file mode 100644 index 000000000..d45fa7164 --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.css @@ -0,0 +1,112 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ + +/* Base input element Styles */ + +.ui-input-datebox { width: 97%; background-image: none; padding: .4em; line-height: 1.4; font-size: 16px; display: block; padding-top: 0px; padding-bottom: 0px; background-color: transparent; } +.ui-input-datebox { min-height: 38px; } /* Fix for IE8 */ +.ui-datebox-container > .ui-header:first-child { -webkit-border-top-left-radius: 3px; border-top-left-radius: 3px; -webkit-border-top-right-radius: 3px; border-top-right-radius: 3px; } +/*.ui-input-datebox .ui-btn-icon-notext { margin-top: 5px !important; margin-bottom: 5px !important; }*/ +.ui-input-datebox input { width: 100% !important; padding: 0 !important; margin-top: 5px !important; margin-right: -40px !important; border: 1px solid transparent !important; vertical-align: middle; display: inline-block !important; background-color: transparent; zoom: 1; *display: inline; } +.ui-input-datebox input:focus { outline: none;} +.ui-input-datebox .ui-btn-text {display: none;} +.ui-input-datebox.ui-mini { min-height: 20px; font-size: 14px; } +/*.ui-input-datebox.ui-mini .ui-btn-icon-notext { margin-top: 2px !important; margin-bottom: 2px !important; }*/ +.ui-icon-datebox { background-image: url('image/datebox.png') !important; background-repeat: no-repeat !important; background-position: 99% 8px !important; } +.ui-icon-datebox-alt { background-image: url('image/datebox.png') !important; background-repeat: no-repeat !important; background-position: 99% -28px !important; } +.ui-mini.ui-icon-datebox { background-position: 99% 6px; } +.ui-mini.ui-icon-datebox-alt { background-position: 99% -30px; } + +@media all and (min-width: 450px){ + .ui-field-contain .ui-input-datebox { width: 74.7%; display: inline-block; } + .ui-hide-label .ui-input-datebox { width: 100%; } +} + +/* Full width if in a grid, ignore the media query */ +.ui-grid-a .ui-input-datebox { width: 97%; } +.ui-grid-b .ui-input-datebox { width: 97%; } +.ui-grid-c .ui-input-datebox { width: 97%; } +.ui-grid-d .ui-input-datebox { width: 97%; } +.ui-grid-e .ui-input-datebox { width: 97%; } + +/* Define a grid, just in case. */ +/* grid d: 16.65/16.65/16.65/16.65/16.65/16.65 */ +.ui-grid-e .ui-block-a, .ui-grid-e .ui-block-b, .ui-grid-e .ui-block-c, .ui-grid-e .ui-block-d, .ui-grid-e .ui-block-e, .ui-grid-e .ui-block-f { width: 16.65%; } +.ui-grid-e > :nth-child(n) { width: 16.65%; } +.ui-grid-e .ui-block-a { clear: left; } + +.ui-grid-e { overflow: hidden; } +.ui-block-f { margin: 0; padding: 0; border: 0; float: left; min-height: 1px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; -ms-box-sizing: border-box; box-sizing: border-box; } + +/* Calendar Mode Styles */ + +.ui-datebox-gridheader { text-align: center; } +.ui-datebox-gridheader h4 { text-align: center; display: inline-block; margin-top: 10px; margin-bottom: 10px; zoom:1; *display: inline;} +.ui-datebox-gridplus { float: right; } +.ui-datebox-gridminus { float: left; } +.ui-datebox-gridplus-rtl { float: left; } +.ui-datebox-gridminus-rtl { float: right; } +.ui-datebox-gridrow { margin-left: 5px; margin-right: 5px; margin-bottom: -7px; } +.ui-datebox-grid { clear: both; margin-bottom: 5px; } +.ui-datebox-griddate { width: 36px; height: 30px; padding: 0px; display: inline-block; vertical-align: middle; text-align: center; line-height: 30px; font-weight: bold; font-size: 12px; zoom:1; *display: inline;} +.ui-datebox-griddate-week { width: 31px; height: 30px; display: inline-block; vertical-align: middle; text-align: center; line-height: 30px; font-weight: bold; font-size: 12px; zoom:1; *display: inline;} +.ui-datebox-griddate-empty { border: 1px solid transparent; color: #888; } +.ui-datebox-griddate-label { height: 15px !important; line-height: 15px !important; color: black;} +.ui-datebox-griddate-disable { color: #888; } + +/* Android Mode Styles */ + +.ui-datebox-header h4 { margin-top: 5px; margin-bottom: 5px; text-align: center; } +.ui-datebox-container fieldset div { margin: 0px !important; } +.ui-datebox-dboxin input { padding: .4em 0 !important; text-align: center; width:95%; } +.ui-datebox-dboxin label { width: 100%; text-align: center; display: block; margin-top: 5px; margin-bottom: -8px; } +.ui-datebox-controls { text-align: center; } +.ui-datebox-controls div { width: 77px; text-align: center; display: inline-block; zoom: 1; *display: inline;} +.ui-datebox-scontrols { text-align: center; } +.ui-datebox-scontrols div { width: 55px; text-align: center; display: inline-block; zoom: 1; *display: inline;} +.ui-datebox-scontrols .ui-datebox-sinput { width: 68px; } +.ui-datebox-scontrols .ui-datebox-sinput input { width: 48px; text-align: center; margin-left: 3px; } +.ui-datebox-input { width: 74px !important; margin-left: 1px; margin-right: 1px; text-align: center !important; display: inline-block !important; zoom:1; *display: inline; } + +/* Slide Mode Styles */ + +.ui-datebox-slide { width: 280px; margin-left: auto; margin-right: auto;} +.ui-datebox-sliderow-d { margin-bottom: 5px; text-align: center; height: 40px; width: 280px; overflow: hidden;} +.ui-datebox-sliderow-ym { margin-bottom: 5px; text-align: center; height: 32px; width: 280px; overflow: hidden;} +.ui-datebox-sliderow-hi { text-align: center; height: 32px; width: 280px; overflow: hidden;} +.ui-datebox-sliderow-int { display: inline-block; white-space: nowrap;} +.ui-datebox-slide .ui-btn { margin: 0px; padding: 0px 1em; } + +.ui-datebox-slideyear { text-align: center; display: inline-block; zoom:1; *display:inline; width: 84px; vertical-align: middle; line-height: 30px; height: 30px; font-size: 14px; font-weight: bold; } +.ui-datebox-slidemonth { text-align: center; display: inline-block; zoom:1; *display:inline; width: 51px; vertical-align: middle; line-height: 30px; height: 30px; font-size: 12px; font-weight: bold; } +.ui-datebox-slideday { text-align: center; display: inline-block; zoom:1; *display:inline; width: 32px; vertical-align: middle; line-height: 20px; height: 38px; font-size: 14px; font-weight: bold; } +.ui-datebox-slidehour { text-align: center; display: inline-block; zoom:1; *display:inline; width: 32px; vertical-align: middle; line-height: 22px; height: 24px; font-size: 14px; font-weight: bold; } +.ui-datebox-slidemins { text-align: center; display: inline-block; zoom:1; *display:inline; width: 32px; vertical-align: middle; line-height: 22px; height: 24px; font-size: 14px; font-weight: bold; } +.ui-datebox-slidearrow { text-align: center; display: inline-block; zoom:1; *display:inline; width: 10px; vertical-align: middle; line-height: 38px; height: 38px; font-size: 10px; font-weight: bold; } +.ui-datebox-slidewday { font-size: 10px; font-weight: normal; } + +/* Flip Mode Styles */ +.ui-datebox-flipcontent { text-align: center; height: 125px; margin-bottom: -40px;} +.ui-datebox-flipcontent div { margin-left: 3px; margin-right: 3px; width: 77px; height: 120px; display: inline-block; text-align: center; zoom: 1; *display: inline; overflow: hidden;} +.ui-datebox-flipcontentd div { width: 60px; } +.ui-datebox-flipcenter { border: 1px solid #eee; height: 40px; margin-left: 10px; width: 260px; margin-right: auto; margin-left: auto; position: relative; top: -45px;} +.ui-datebox-flipcontent ul { list-style-type: none; display: inline; } +.ui-datebox-flipcontent li { height: 30px; } +.ui-datebox-flipcontent li span { margin-top: 7px; display: block; } +/* Shared Styles */ + +.ui-datebox-container { border: 5px solid #111 !important; width: 280px; -webkit-transform:translate3d(0,0,0); } +.ui-datebox-screen { position: absolute; top: 0px; left: 0px; width: 100%; height: 100%; } +.ui-datebox-screen-modal { background-color: black; -moz-opacity: 0.8; opacity:.80; filter: alpha(opacity=80); } +.ui-datebox-hidden { display: none; } +.ui-dialog .ui-datebox-container { border: none !important; } +.ui-popup-container .ui-datebox-container { border: none !important; } +.ui-popup-container .ui-datebox-gridrow { margin-left: 0px; margin-right: 0px; } +.ui-datebox-collapse a { display: inline-block; width: 45% } + +.ui-datebox-inline { margin-top: 5px; border: 5px solid #111111 !important; margin-left: auto; margin-right: auto; text-align: center; } +.ui-datebox-inlineblind { margin-top: 5px; border: 5px solid #111111 !important; margin-left: auto; margin-right: auto; text-align: center; } diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.min.css b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.min.css new file mode 100644 index 000000000..786bb0e34 --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.min.css @@ -0,0 +1,7 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +.ui-input-datebox{width:97%;background-image:none;padding:.4em;line-height:1.4;font-size:16px;display:block;padding-top:0;padding-bottom:0;background-color:transparent}.ui-input-datebox{min-height:38px}.ui-datebox-container>.ui-header:first-child{-webkit-border-top-left-radius:3px;border-top-left-radius:3px;-webkit-border-top-right-radius:3px;border-top-right-radius:3px}.ui-input-datebox input{width:100%!important;padding:0!important;margin-top:5px!important;margin-right:-40px!important;border:1px solid transparent!important;vertical-align:middle;display:inline-block!important;background-color:transparent;zoom:1;*display:inline}.ui-input-datebox input:focus{outline:0}.ui-input-datebox .ui-btn-text{display:none}.ui-input-datebox.ui-mini{min-height:20px;font-size:14px}.ui-icon-datebox{background-image:url('image/datebox.png')!important;background-repeat:no-repeat!important;background-position:99% 8px!important}.ui-icon-datebox-alt{background-image:url('image/datebox.png')!important;background-repeat:no-repeat!important;background-position:99% -28px!important}.ui-mini.ui-icon-datebox{background-position:99% 6px}.ui-mini.ui-icon-datebox-alt{background-position:99% -30px}@media all and (min-width:450px){.ui-field-contain .ui-input-datebox{width:74.7%;display:inline-block}.ui-hide-label .ui-input-datebox{width:100%}}.ui-grid-a .ui-input-datebox{width:97%}.ui-grid-b .ui-input-datebox{width:97%}.ui-grid-c .ui-input-datebox{width:97%}.ui-grid-d .ui-input-datebox{width:97%}.ui-grid-e .ui-input-datebox{width:97%}.ui-grid-e .ui-block-a,.ui-grid-e .ui-block-b,.ui-grid-e .ui-block-c,.ui-grid-e .ui-block-d,.ui-grid-e .ui-block-e,.ui-grid-e .ui-block-f{width:16.65%}.ui-grid-e>:nth-child(n){width:16.65%}.ui-grid-e .ui-block-a{clear:left}.ui-grid-e{overflow:hidden}.ui-block-f{margin:0;padding:0;border:0;float:left;min-height:1px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;-ms-box-sizing:border-box;box-sizing:border-box}.ui-datebox-gridheader{text-align:center}.ui-datebox-gridheader h4{text-align:center;display:inline-block;margin-top:10px;margin-bottom:10px;zoom:1;*display:inline}.ui-datebox-gridplus{float:right}.ui-datebox-gridminus{float:left}.ui-datebox-gridplus-rtl{float:left}.ui-datebox-gridminus-rtl{float:right}.ui-datebox-gridrow{margin-left:5px;margin-right:5px;margin-bottom:-7px}.ui-datebox-grid{clear:both;margin-bottom:5px}.ui-datebox-griddate{width:36px;height:30px;padding:0;display:inline-block;vertical-align:middle;text-align:center;line-height:30px;font-weight:bold;font-size:12px;zoom:1;*display:inline}.ui-datebox-griddate-week{width:31px;height:30px;display:inline-block;vertical-align:middle;text-align:center;line-height:30px;font-weight:bold;font-size:12px;zoom:1;*display:inline}.ui-datebox-griddate-empty{border:1px solid transparent;color:#888}.ui-datebox-griddate-label{height:15px!important;line-height:15px!important;color:black}.ui-datebox-griddate-disable{color:#888}.ui-datebox-header h4{margin-top:5px;margin-bottom:5px;text-align:center}.ui-datebox-container fieldset div{margin:0!important}.ui-datebox-dboxin input{padding:.4em 0!important;text-align:center;width:95%}.ui-datebox-dboxin label{width:100%;text-align:center;display:block;margin-top:5px;margin-bottom:-8px}.ui-datebox-controls{text-align:center}.ui-datebox-controls div{width:77px;text-align:center;display:inline-block;zoom:1;*display:inline}.ui-datebox-scontrols{text-align:center}.ui-datebox-scontrols div{width:55px;text-align:center;display:inline-block;zoom:1;*display:inline}.ui-datebox-scontrols .ui-datebox-sinput{width:68px}.ui-datebox-scontrols .ui-datebox-sinput input{width:48px;text-align:center;margin-left:3px}.ui-datebox-input{width:74px!important;margin-left:1px;margin-right:1px;text-align:center!important;display:inline-block!important;zoom:1;*display:inline}.ui-datebox-slide{width:280px;margin-left:auto;margin-right:auto}.ui-datebox-sliderow-d{margin-bottom:5px;text-align:center;height:40px;width:280px;overflow:hidden}.ui-datebox-sliderow-ym{margin-bottom:5px;text-align:center;height:32px;width:280px;overflow:hidden}.ui-datebox-sliderow-hi{text-align:center;height:32px;width:280px;overflow:hidden}.ui-datebox-sliderow-int{display:inline-block;white-space:nowrap}.ui-datebox-slide .ui-btn{margin:0;padding:0 1em}.ui-datebox-slideyear{text-align:center;display:inline-block;zoom:1;*display:inline;width:84px;vertical-align:middle;line-height:30px;height:30px;font-size:14px;font-weight:bold}.ui-datebox-slidemonth{text-align:center;display:inline-block;zoom:1;*display:inline;width:51px;vertical-align:middle;line-height:30px;height:30px;font-size:12px;font-weight:bold}.ui-datebox-slideday{text-align:center;display:inline-block;zoom:1;*display:inline;width:32px;vertical-align:middle;line-height:20px;height:38px;font-size:14px;font-weight:bold}.ui-datebox-slidehour{text-align:center;display:inline-block;zoom:1;*display:inline;width:32px;vertical-align:middle;line-height:22px;height:24px;font-size:14px;font-weight:bold}.ui-datebox-slidemins{text-align:center;display:inline-block;zoom:1;*display:inline;width:32px;vertical-align:middle;line-height:22px;height:24px;font-size:14px;font-weight:bold}.ui-datebox-slidearrow{text-align:center;display:inline-block;zoom:1;*display:inline;width:10px;vertical-align:middle;line-height:38px;height:38px;font-size:10px;font-weight:bold}.ui-datebox-slidewday{font-size:10px;font-weight:normal}.ui-datebox-flipcontent{text-align:center;height:125px;margin-bottom:-40px}.ui-datebox-flipcontent div{margin-left:3px;margin-right:3px;width:77px;height:120px;display:inline-block;text-align:center;zoom:1;*display:inline;overflow:hidden}.ui-datebox-flipcontentd div{width:60px}.ui-datebox-flipcenter{border:1px solid #eee;height:40px;margin-left:10px;width:260px;margin-right:auto;margin-left:auto;position:relative;top:-45px}.ui-datebox-flipcontent ul{list-style-type:none;display:inline}.ui-datebox-flipcontent li{height:30px}.ui-datebox-flipcontent li span{margin-top:7px;display:block}.ui-datebox-container{border:5px solid #111!important;width:280px;-webkit-transform:translate3d(0,0,0)}.ui-datebox-screen{position:absolute;top:0;left:0;width:100%;height:100%}.ui-datebox-screen-modal{background-color:black;-moz-opacity:.8;opacity:.80;filter:alpha(opacity=80)}.ui-datebox-hidden{display:none}.ui-dialog .ui-datebox-container{border:none!important}.ui-popup-container .ui-datebox-container{border:none!important}.ui-popup-container .ui-datebox-gridrow{margin-left:0;margin-right:0}.ui-datebox-collapse a{display:inline-block;width:45%}.ui-datebox-inline{margin-top:5px;border:5px solid #111!important;margin-left:auto;margin-right:auto;text-align:center}.ui-datebox-inlineblind{margin-top:5px;border:5px solid #111!important;margin-left:auto;margin-right:auto;text-align:center} \ No newline at end of file diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.calbox.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.calbox.js new file mode 100644 index 000000000..33d0d02c0 --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.calbox.js @@ -0,0 +1,375 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +/* CALBOX Mode */ +// Version Notes: <140 :: New button theme method, still use _hoover + +(function($) { + $.extend( $.mobile.datebox.prototype.options, { + themeDateToday: 'b', + themeDayHigh: 'b', + themeDatePick: 'b', + themeDateHigh: 'b', + themeDateHighAlt: 'b', + themeDateHighRec: 'b', + themeDate: 'a', + + calHighToday: true, + calHighPick: true, + + calShowDays: true, + calOnlyMonth: false, + calWeekMode: false, + calWeekModeDay: 1, + calWeekHigh: false, + calControlGroup: false, + calShowWeek: false, + calUsePickers: false, + calNoHeader: false, + + useTodayButton: false, + useCollapsedBut: false, + + highDays: false, + highDates: false, + highDatesRec: false, + highDatesAlt: false, + enableDates: false, + calDateList: false, + calShowDateList: false, + }); + $.extend( $.mobile.datebox.prototype, { + _cal_gen: function (start,prev,last,other,month) { + var rc = 0, cc = 0, day = 1, + next = 1, cal = [], row = [], stop = false; + + for ( rc = 0; rc <= 5; rc++ ) { + if ( stop === false ) { + row = []; + for ( cc = 0; cc <= 6; cc++ ) { + if ( rc === 0 && cc < start ) { + if ( other === true ) { + row.push([prev + (cc - start) + 1,month-1]); + } else { + row.push(false); + } + } else if ( rc > 3 && day > last ) { + if ( other === true ) { + row.push([next,month+1]); next++; + } else { + row.push(false); + } + stop = true; + } else { + row.push([day,month]); day++; + if ( day > last ) { stop = true; } + } + } + cal.push(row); + } + } + return cal; + }, + _cal_check : function (cal, year, month, date) { + var w = this, i, + o = this.options, + ret = {}, + day = new this._date(year,month,date,0,0,0,0).getDay(); + + ret.ok = true; + ret.iso = year + '-' + w._zPad(month+1) + '-' + w._zPad(date); + ret.comp = parseInt(ret.iso.replace(/-/g, ''),10); + ret.theme = o.themeDate; + ret.recok = true; + ret.rectheme = false; + + if ( o.blackDatesRec !== false ) { + for ( i=0; i ret.comp ) || + ( o.beforeToday === true && cal.thisDate.comp() < ret.comp ) || + ( o.notToday === true && cal.thisDate.comp() === ret.comp ) || + ( o.maxDays !== false && cal.maxDate.comp() < ret.comp ) || + ( o.minDays !== false && cal.minDate.comp() > ret.comp ) || + ( $.isArray(o.blackDays) && $.inArray(day, o.blackDays) > -1 ) || + ( $.isArray(o.blackDates) && $.inArray(ret.iso, o.blackDates) > -1 ) + ) { + ret.ok = false; + } + } + if ( ret.ok ) { + if ( o.highDatesRec !== false ) { + for ( i=0; i -1) ) { + ret.theme = o.themeDateHighAlt; + } else if ( $.isArray(o.highDates) && ($.inArray(ret.iso, o.highDates) > -1) ) { + ret.theme = o.themeDateHigh; + } else if ( $.isArray(o.highDays) && ($.inArray(day, o.highDays) > -1) ) { + ret.theme = o.themeDayHigh; + } else if ( $.isArray(o.highDatesRec) && ret.rectheme === true ) { + ret.theme = o.themeDateHighRec; + } + } + return ret; + } + }); + $.extend( $.mobile.datebox.prototype._build, { + 'calbox': function () { + var w = this, + o = this.options, i, + cal = false, + uid = 'ui-datebox-', + temp = false, row = false, col = false, hRow = false, checked = false; + + if ( typeof w.d.intHTML !== 'boolean' ) { + w.d.intHTML.remove(); + } + + w.d.headerText = ((w._grabLabel() !== false)?w._grabLabel():w.__('titleDateDialogLabel')); + w.d.intHTML = $(''); + + $('

              ' + + w._formatter(w.__('calHeaderFormat'), w.theDate) + + '

              ').appendTo(w.d.intHTML); + + // Previous and next month buttons, define booleans to decide if they should do anything + $("") + .prependTo(w.d.intHTML.find('.'+uid+'gridheader')) + .buttonMarkup({theme: o.themeDate, icon: 'arrow-r', inline: true, iconpos: 'notext', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + if ( w.calNext ) { + if ( w.theDate.getDate() > 28 ) { w.theDate.setDate(1); } + w._offset('m',1); + } + }); + $("") + .prependTo(w.d.intHTML.find('.'+uid+'gridheader')) + .buttonMarkup({theme: o.themeDate, icon: 'arrow-l', inline: true, iconpos: 'notext', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + if ( w.calPrev ) { + if ( w.theDate.getDate() > 28 ) { w.theDate.setDate(1); } + w._offset('m',-1); + } + }); + + if ( o.calNoHeader === true ) { w.d.intHTML.find('.'+uid+'gridheader').remove(); } + + cal = {'today': -1, 'highlightDay': -1, 'presetDay': -1, 'startDay': w.__('calStartDay'), + 'thisDate': new w._date(), 'maxDate': w.initDate.copy(), 'minDate': w.initDate.copy(), + 'currentMonth': false, 'weekMode': 0, 'weekDays': null }; + cal.start = (w.theDate.copy([0],[0,0,1]).getDay() - w.__('calStartDay') + 7) % 7; + cal.thisMonth = w.theDate.getMonth(); + cal.thisYear = w.theDate.getFullYear(); + cal.wk = w.theDate.copy([0],[0,0,1]).adj(2,(-1*cal.start)+(w.__('calStartDay')===0?1:0)).getDWeek(4); + cal.end = 32 - w.theDate.copy([0],[0,0,32,13]).getDate(); + cal.lastend = 32 - w.theDate.copy([0,-1],[0,0,32,13]).getDate(); + cal.presetDate = (w.d.input.val() === "") ? w._startOffset(w._makeDate(w.d.input.val())) : w._makeDate(w.d.input.val()); + cal.thisDateArr = cal.thisDate.getArray(); + cal.theDateArr = w.theDate.getArray(); + cal.checkDates = ( $.inArray(false, [o.afterToday, o.beforeToday, o.notToday, o.maxDays, o.minDays, o.blackDates, o.blackDays]) > -1 ); + + w.calNext = true; + w.calPrev = true; + + if ( cal.thisDateArr[0] === cal.theDateArr[0] && cal.thisDateArr[1] === cal.theDateArr[1] ) { cal.currentMonth = true; } + if ( cal.presetDate.comp() === w.theDate.comp() ) { cal.presetDay = cal.presetDate.getDate(); } + + if ( o.afterToday === true && + ( cal.currentMonth === true || ( cal.thisDateArr[1] >= cal.theDateArr[1] && cal.theDateArr[0] === cal.thisDateArr[0] ) ) ) { + w.calPrev = false; } + if ( o.beforeToday === true && + ( cal.currentMonth === true || ( cal.thisDateArr[1] <= cal.theDateArr[1] && cal.theDateArr[0] === cal.thisDateArr[0] ) ) ) { + w.calNext = false; } + + if ( o.minDays !== false ) { + cal.minDate.adj(2, -1*o.minDays); + if ( cal.theDateArr[0] === cal.minDate.getFullYear() && cal.theDateArr[1] <= cal.minDate.getMonth() ) { w.calPrev = false;} + } + if ( o.maxDays !== false ) { + cal.maxDate.adj(2, o.maxDays); + if ( cal.theDateArr[0] === cal.maxDate.getFullYear() && cal.theDateArr[1] >= cal.maxDate.getMonth() ) { w.calNext = false;} + } + + if ( o.calUsePickers === true ) { + cal.picker = $('
              ', {'class': 'ui-grid-a ui-datebox-grid','style':'padding-top: 5px; padding-bottom: 5px;'}); + + cal.picker1 = $('
              ').appendTo(cal.picker).find('select'); + cal.picker2 = $('
              ').appendTo(cal.picker).find('select'); + + for ( i=0; i<=11; i++ ) { + cal.picker1.append($('')); + } + for ( i=(cal.thisYear-6); i<=cal.thisYear+6; i++ ) { + cal.picker2.append($('')); + } + + cal.picker1.on('change', function () { w.theDate.setMonth($(this).val()); w.refresh(); }); + cal.picker2.on('change', function () { w.theDate.setFullYear($(this).val()); w.refresh(); }); + + cal.picker.find('select').selectmenu({mini:true, nativeMenu: true}); + cal.picker.appendTo(w.d.intHTML); + } + + temp = $('
              ').appendTo(w.d.intHTML); + + if ( o.calShowDays ) { + w._cal_days = w.__('daysOfWeekShort').concat(w.__('daysOfWeekShort')); + cal.weekDays = $("
              ", {'class':uid+'gridrow'}).appendTo(temp); + if ( w.__('isRTL') === true ) { cal.weekDays.css('direction', 'rtl'); } + if ( o.calShowWeek ) { + $("
              ").addClass(uid+'griddate '+uid+'griddate-empty '+uid+'griddate-label').appendTo(cal.weekDays); + } + for ( i=0; i<=6;i++ ) { + $("
              "+w._cal_days[(i+cal.startDay)%7]+"
              ").addClass(uid+'griddate '+uid+'griddate-empty '+uid+'griddate-label').appendTo(cal.weekDays); + } + } + + cal.gen = w._cal_gen(cal.start, cal.lastend, cal.end, !o.calOnlyMonth, w.theDate.getMonth()); + for ( var row=0, rows=cal.gen.length; row < rows; row++ ) { + hRow = $('
              ', {'class': uid+'gridrow'}); + if ( w.__('isRTL') ) { hRow.css('direction', 'rtl'); } + if ( o.calShowWeek ) { + $('
              ', {'class':uid+'griddate '+uid+'griddate-empty'}).text('W'+cal.wk).appendTo(hRow); + cal.wk++; + if ( cal.wk > 52 && typeof cal.gen[parseInt(row,10)+1] !== 'undefined' ) { cal.wk = new Date(cal.theDateArr[0],cal.theDateArr[1],((w.__('calStartDay')===0)?cal.gen[parseInt(row,10)+1][1][0]:cal.gen[parseInt(row,10)+1][0][0])).getDWeek(4); } + } + for ( var col=0, cols=cal.gen[row].length; col', {'class':uid+'griddate '+uid+'griddate-empty'}).appendTo(hRow); + } else { + checked = w._cal_check(cal, cal.theDateArr[0], cal.gen[row][col][1], cal.gen[row][col][0]); + if (cal.gen[row][col][0]) { + $("
              "+String(cal.gen[row][col][0])+"
              ") + .addClass( cal.thisMonth === cal.gen[row][col][1] ? + (uid+'griddate ui-corner-all ui-btn ui-btn-'+(o.mobVer<140?'up-':'')+checked.theme + (checked.ok?'':' '+uid+'griddate-disable')): + (uid+'griddate '+uid+'griddate-empty') + ) + .jqmData('date', ((o.calWeekMode)?cal.weekMode:cal.gen[row][col][0])) + .jqmData('theme', cal.thisMonth === cal.gen[row][col][1] ? checked.theme : '-') + .jqmData('enabled', checked.ok) + .jqmData('month', cal.gen[row][((o.calWeekMode)?o.calWeekModeDay:col)][1]) + .appendTo(hRow); + } + } + } + if ( o.calControlGroup === true ) { + hRow.find('.ui-corner-all').removeClass('ui-corner-all').eq(0).addClass('ui-corner-left').end().last().addClass('ui-corner-right').addClass('ui-controlgroup-last'); + } + hRow.appendTo(temp); + } + if ( o.calShowWeek ) { temp.find('.'+uid+'griddate').addClass(uid+'griddate-week'); } + + if ( o.calShowDateList === true && o.calDateList !== false ) { + cal.datelist = $('
              '); + cal.datelistpick = $('').appendTo(cal.datelist); + + cal.datelistpick.append(''); + for ( i=0; i'+o.calDateList[i][1]+'')); + } + + cal.datelistpick.on('change', function() { + cal.datelistdate = $(this).val().split('-'); + w.theDate = new w._date(cal.datelistdate[0], cal.datelistdate[1]-1, cal.datelistdate[2], 0,0,0,0); + w.d.input.trigger('datebox',{'method':'doset'}); + }); + + cal.datelist.find('select').selectmenu({mini:true, nativeMenu:true}); + cal.datelist.appendTo(w.d.intHTML); + } + + if ( o.useTodayButton || o.useClearButton ) { + hRow = $('
              ', {'class':uid+'controls'}); + + if ( o.useTodayButton ) { + $(''+w.__('calTodayButtonLabel')+'') + .appendTo(hRow).buttonMarkup({theme: o.theme, icon: 'check', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEvent, function(e) { + e.preventDefault(); + w.theDate = new w._date(); + w.theDate = new w._date(w.theDate.getFullYear(), w.theDate.getMonth(), w.theDate.getDate(),0,0,0,0); + w.d.input.trigger('datebox',{'method':'doset'}); + }); + } + if ( o.useClearButton ) { + $(''+w.__('clearButton')+'') + .appendTo(hRow).buttonMarkup({theme: o.theme, icon: 'delete', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.val(''); + w.d.input.trigger('datebox',{'method':'clear'}); + w.d.input.trigger('datebox',{'method':'close'}); + }); + } + if ( o.useCollapsedBut ) { + hRow.addClass('ui-datebox-collapse'); + } + hRow.appendTo(temp); + } + + w.d.intHTML.on(o.clickEventAlt+' vmouseover vmouseout', 'div.'+uid+'griddate', function(e) { + if ( e.type === o.clickEventAlt ) { + e.preventDefault(); + if ( $(this).jqmData('enabled') ) { + w.theDate.setD(2,1).setD(1,$(this).jqmData('month')).setD(2,$(this).jqmData('date')); + w.d.input.trigger('datebox', {'method':'set', 'value':w._formatter(w.__fmt(),w.theDate), 'date':w.theDate}); + w.d.input.trigger('datebox', {'method':'close'}); + } + } else { + if ( $(this).jqmData('enabled') && typeof $(this).jqmData('theme') !== 'undefined' && o.mobVer < 140 ) { + if ( o.calWeekMode !== false && o.calWeekHigh === true ) { + $(this).parent().find('div').each(function() { w._hoover(this); }); + } else { w._hoover(this); } + } + } + }); + w.d.intHTML + .on('swipeleft', function() { if ( w.calNext ) { w._offset('m', 1); } }) + .on('swiperight', function() { if ( w.calPrev ) { w._offset('m', -1); } }); + + if ( w.wheelExists) { // Mousewheel operations, if plugin is loaded + w.d.intHTML.on('mousewheel', function(e,d) { + e.preventDefault(); + if ( d > 0 && w.calNext ) { + w.theDate.setD(2,1); + w._offset('m', 1); + } + if ( d < 0 && w.calPrev ) { + w.theDate.setD(2,1); + w._offset('m', -1); + } + }); + } + } + }); +})( jQuery ); diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.calbox.min.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.calbox.min.js new file mode 100644 index 000000000..9cbfa7d2d --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.calbox.min.js @@ -0,0 +1,7 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +(function(a){a.extend(a.mobile.datebox.prototype.options,{themeDateToday:"b",themeDayHigh:"b",themeDatePick:"b",themeDateHigh:"b",themeDateHighAlt:"b",themeDateHighRec:"b",themeDate:"a",calHighToday:true,calHighPick:true,calShowDays:true,calOnlyMonth:false,calWeekMode:false,calWeekModeDay:1,calWeekHigh:false,calControlGroup:false,calShowWeek:false,calUsePickers:false,calNoHeader:false,useTodayButton:false,useCollapsedBut:false,highDays:false,highDates:false,highDatesRec:false,highDatesAlt:false,enableDates:false,calDateList:false,calShowDateList:false,});a.extend(a.mobile.datebox.prototype,{_cal_gen:function(d,f,l,i,h){var b=0,e=0,k=1,g=1,c=[],m=[],j=false;for(b=0;b<=5;b++){if(j===false){m=[];for(e=0;e<=6;e++){if(b===0&&e3&&k>l){if(i===true){m.push([g,h+1]);g++}else{m.push(false)}j=true}else{m.push([k,h]);k++;if(k>l){j=true}}}}c.push(m)}}return c},_cal_check:function(b,h,f,d){var k=this,e,c=this.options,g={},j=new this._date(h,f,d,0,0,0,0).getDay();g.ok=true;g.iso=h+"-"+k._zPad(f+1)+"-"+k._zPad(d);g.comp=parseInt(g.iso.replace(/-/g,""),10);g.theme=c.themeDate;g.recok=true;g.rectheme=false;if(c.blackDatesRec!==false){for(e=0;eg.comp)||(c.beforeToday===true&&b.thisDate.comp()g.comp)||(a.isArray(c.blackDays)&&a.inArray(j,c.blackDays)>-1)||(a.isArray(c.blackDates)&&a.inArray(g.iso,c.blackDates)>-1)){g.ok=false}}}if(g.ok){if(c.highDatesRec!==false){for(e=0;e-1)){g.theme=c.themeDateHighAlt}else{if(a.isArray(c.highDates)&&(a.inArray(g.iso,c.highDates)>-1)){g.theme=c.themeDateHigh}else{if(a.isArray(c.highDays)&&(a.inArray(j,c.highDays)>-1)){g.theme=c.themeDayHigh}else{if(a.isArray(c.highDatesRec)&&g.rectheme===true){g.theme=c.themeDateHighRec}}}}}}}return g}});a.extend(a.mobile.datebox.prototype._build,{calbox:function(){var j=this,c=this.options,e,b=false,f="ui-datebox-",l=false,n=false,d=false,k=false,h=false;if(typeof j.d.intHTML!=="boolean"){j.d.intHTML.remove()}j.d.headerText=((j._grabLabel()!==false)?j._grabLabel():j.__("titleDateDialogLabel"));j.d.intHTML=a("");a('

              '+j._formatter(j.__("calHeaderFormat"),j.theDate)+"

              ").appendTo(j.d.intHTML);a("").prependTo(j.d.intHTML.find("."+f+"gridheader")).buttonMarkup({theme:c.themeDate,icon:"arrow-r",inline:true,iconpos:"notext",corners:true,shadow:true}).on(c.clickEventAlt,function(i){i.preventDefault();if(j.calNext){if(j.theDate.getDate()>28){j.theDate.setDate(1)}j._offset("m",1)}});a("").prependTo(j.d.intHTML.find("."+f+"gridheader")).buttonMarkup({theme:c.themeDate,icon:"arrow-l",inline:true,iconpos:"notext",corners:true,shadow:true}).on(c.clickEventAlt,function(i){i.preventDefault();if(j.calPrev){if(j.theDate.getDate()>28){j.theDate.setDate(1)}j._offset("m",-1)}});if(c.calNoHeader===true){j.d.intHTML.find("."+f+"gridheader").remove()}b={today:-1,highlightDay:-1,presetDay:-1,startDay:j.__("calStartDay"),thisDate:new j._date(),maxDate:j.initDate.copy(),minDate:j.initDate.copy(),currentMonth:false,weekMode:0,weekDays:null};b.start=(j.theDate.copy([0],[0,0,1]).getDay()-j.__("calStartDay")+7)%7;b.thisMonth=j.theDate.getMonth();b.thisYear=j.theDate.getFullYear();b.wk=j.theDate.copy([0],[0,0,1]).adj(2,(-1*b.start)+(j.__("calStartDay")===0?1:0)).getDWeek(4);b.end=32-j.theDate.copy([0],[0,0,32,13]).getDate();b.lastend=32-j.theDate.copy([0,-1],[0,0,32,13]).getDate();b.presetDate=(j.d.input.val()==="")?j._startOffset(j._makeDate(j.d.input.val())):j._makeDate(j.d.input.val());b.thisDateArr=b.thisDate.getArray();b.theDateArr=j.theDate.getArray();b.checkDates=(a.inArray(false,[c.afterToday,c.beforeToday,c.notToday,c.maxDays,c.minDays,c.blackDates,c.blackDays])>-1);j.calNext=true;j.calPrev=true;if(b.thisDateArr[0]===b.theDateArr[0]&&b.thisDateArr[1]===b.theDateArr[1]){b.currentMonth=true}if(b.presetDate.comp()===j.theDate.comp()){b.presetDay=b.presetDate.getDate()}if(c.afterToday===true&&(b.currentMonth===true||(b.thisDateArr[1]>=b.theDateArr[1]&&b.theDateArr[0]===b.thisDateArr[0]))){j.calPrev=false}if(c.beforeToday===true&&(b.currentMonth===true||(b.thisDateArr[1]<=b.theDateArr[1]&&b.theDateArr[0]===b.thisDateArr[0]))){j.calNext=false}if(c.minDays!==false){b.minDate.adj(2,-1*c.minDays);if(b.theDateArr[0]===b.minDate.getFullYear()&&b.theDateArr[1]<=b.minDate.getMonth()){j.calPrev=false}}if(c.maxDays!==false){b.maxDate.adj(2,c.maxDays);if(b.theDateArr[0]===b.maxDate.getFullYear()&&b.theDateArr[1]>=b.maxDate.getMonth()){j.calNext=false}}if(c.calUsePickers===true){b.picker=a("
              ",{"class":"ui-grid-a ui-datebox-grid",style:"padding-top: 5px; padding-bottom: 5px;"});b.picker1=a('
              ').appendTo(b.picker).find("select");b.picker2=a('
              ').appendTo(b.picker).find("select");for(e=0;e<=11;e++){b.picker1.append(a('"))}for(e=(b.thisYear-6);e<=b.thisYear+6;e++){b.picker2.append(a('"))}b.picker1.on("change",function(){j.theDate.setMonth(a(this).val());j.refresh()});b.picker2.on("change",function(){j.theDate.setFullYear(a(this).val());j.refresh()});b.picker.find("select").selectmenu({mini:true,nativeMenu:true});b.picker.appendTo(j.d.intHTML)}l=a('
              ').appendTo(j.d.intHTML);if(c.calShowDays){j._cal_days=j.__("daysOfWeekShort").concat(j.__("daysOfWeekShort"));b.weekDays=a("
              ",{"class":f+"gridrow"}).appendTo(l);if(j.__("isRTL")===true){b.weekDays.css("direction","rtl")}if(c.calShowWeek){a("
              ").addClass(f+"griddate "+f+"griddate-empty "+f+"griddate-label").appendTo(b.weekDays)}for(e=0;e<=6;e++){a("
              "+j._cal_days[(e+b.startDay)%7]+"
              ").addClass(f+"griddate "+f+"griddate-empty "+f+"griddate-label").appendTo(b.weekDays)}}b.gen=j._cal_gen(b.start,b.lastend,b.end,!c.calOnlyMonth,j.theDate.getMonth());for(var n=0,m=b.gen.length;n",{"class":f+"gridrow"});if(j.__("isRTL")){k.css("direction","rtl")}if(c.calShowWeek){a("
              ",{"class":f+"griddate "+f+"griddate-empty"}).text("W"+b.wk).appendTo(k);b.wk++;if(b.wk>52&&typeof b.gen[parseInt(n,10)+1]!=="undefined"){b.wk=new Date(b.theDateArr[0],b.theDateArr[1],((j.__("calStartDay")===0)?b.gen[parseInt(n,10)+1][1][0]:b.gen[parseInt(n,10)+1][0][0])).getDWeek(4)}}for(var d=0,g=b.gen[n].length;d",{"class":f+"griddate "+f+"griddate-empty"}).appendTo(k)}else{h=j._cal_check(b,b.theDateArr[0],b.gen[n][d][1],b.gen[n][d][0]);if(b.gen[n][d][0]){a("
              "+String(b.gen[n][d][0])+"
              ").addClass(b.thisMonth===b.gen[n][d][1]?(f+"griddate ui-corner-all ui-btn ui-btn-"+(c.mobVer<140?"up-":"")+h.theme+(h.ok?"":" "+f+"griddate-disable")):(f+"griddate "+f+"griddate-empty")).jqmData("date",((c.calWeekMode)?b.weekMode:b.gen[n][d][0])).jqmData("theme",b.thisMonth===b.gen[n][d][1]?h.theme:"-").jqmData("enabled",h.ok).jqmData("month",b.gen[n][((c.calWeekMode)?c.calWeekModeDay:d)][1]).appendTo(k)}}}if(c.calControlGroup===true){k.find(".ui-corner-all").removeClass("ui-corner-all").eq(0).addClass("ui-corner-left").end().last().addClass("ui-corner-right").addClass("ui-controlgroup-last")}k.appendTo(l)}if(c.calShowWeek){l.find("."+f+"griddate").addClass(f+"griddate-week")}if(c.calShowDateList===true&&c.calDateList!==false){b.datelist=a("
              ");b.datelistpick=a('').appendTo(b.datelist);b.datelistpick.append('");for(e=0;e'+c.calDateList[e][1]+""))}b.datelistpick.on("change",function(){b.datelistdate=a(this).val().split("-");j.theDate=new j._date(b.datelistdate[0],b.datelistdate[1]-1,b.datelistdate[2],0,0,0,0);j.d.input.trigger("datebox",{method:"doset"})});b.datelist.find("select").selectmenu({mini:true,nativeMenu:true});b.datelist.appendTo(j.d.intHTML)}if(c.useTodayButton||c.useClearButton){k=a("
              ",{"class":f+"controls"});if(c.useTodayButton){a(''+j.__("calTodayButtonLabel")+"").appendTo(k).buttonMarkup({theme:c.theme,icon:"check",iconpos:"left",corners:true,shadow:true}).on(c.clickEvent,function(i){i.preventDefault();j.theDate=new j._date();j.theDate=new j._date(j.theDate.getFullYear(),j.theDate.getMonth(),j.theDate.getDate(),0,0,0,0);j.d.input.trigger("datebox",{method:"doset"})})}if(c.useClearButton){a(''+j.__("clearButton")+"").appendTo(k).buttonMarkup({theme:c.theme,icon:"delete",iconpos:"left",corners:true,shadow:true}).on(c.clickEventAlt,function(i){i.preventDefault();j.d.input.val("");j.d.input.trigger("datebox",{method:"clear"});j.d.input.trigger("datebox",{method:"close"})})}if(c.useCollapsedBut){k.addClass("ui-datebox-collapse")}k.appendTo(l)}j.d.intHTML.on(c.clickEventAlt+" vmouseover vmouseout","div."+f+"griddate",function(i){if(i.type===c.clickEventAlt){i.preventDefault();if(a(this).jqmData("enabled")){j.theDate.setD(2,1).setD(1,a(this).jqmData("month")).setD(2,a(this).jqmData("date"));j.d.input.trigger("datebox",{method:"set",value:j._formatter(j.__fmt(),j.theDate),date:j.theDate});j.d.input.trigger("datebox",{method:"close"})}}else{if(a(this).jqmData("enabled")&&typeof a(this).jqmData("theme")!=="undefined"&&c.mobVer<140){if(c.calWeekMode!==false&&c.calWeekHigh===true){a(this).parent().find("div").each(function(){j._hoover(this)})}else{j._hoover(this)}}}});j.d.intHTML.on("swipeleft",function(){if(j.calNext){j._offset("m",1)}}).on("swiperight",function(){if(j.calPrev){j._offset("m",-1)}});if(j.wheelExists){j.d.intHTML.on("mousewheel",function(i,o){i.preventDefault();if(o>0&&j.calNext){j.theDate.setD(2,1);j._offset("m",1)}if(o<0&&j.calPrev){j.theDate.setD(2,1);j._offset("m",-1)}})}}})})(jQuery); \ No newline at end of file diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.custombox.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.custombox.js new file mode 100644 index 000000000..2f8cfe9e2 --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.custombox.js @@ -0,0 +1,157 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ + +(function($) { + $.extend( $.mobile.datebox.prototype.options, { + themeButton: 'a', + themeInput: 'a', + useSetButton: true, + customData: [ + {'input': true, 'name':'Letter', 'data':['a','b','c','d','e']}, + {'input': true, 'name':'Text', 'data':['some','bull','shtuff','here']}, + {'input': false, 'name':'Image', 'data':['','','','']} + ], + customDefault: [0,0,0], + customFormat: false, + customboxlang: { + // This structure interfaces with __() -> if it exists, strings are looked up here after i8n fails, + // and before going to 'default' - the name syntax is lang + 'customSet':'Looks Good' + } + + }); + $.extend( $.mobile.datebox.prototype, { + _cbox_offset: function (fld,amount) { + // This is *not* an automatic override, used below specificly. + var w = this, x, + o = this.options; + + tmp = (w.customCurrent[fld] + amount) % o.customData[fld]['data'].length; + if ( tmp < 0 ) { tmp = o.customData[fld]['data'].length + tmp; } + + w.customCurrent[fld] = tmp; + if ( o.useImmediate ) { w.d.input.trigger('datebox', {'method':'set', 'value':w._formatter(o.customFormat,w.customCurrent), 'date':w.customCurrent}); } + w.refresh(); + } + }); + $.extend( $.mobile.datebox.prototype._parser, { + // If this stucture exists, it is called instead of the usual date input parser. + // The name of the structure is the same as the mode name - it recieves a string + // as the input, which is the current value of the input element, pre-sanitized + 'custombox' : function ( str ) { + return ( str.length < 1 || ! str.match(/,/) ) ? this.options.customDefault : str.split(","); + } + }); + $.extend( $.mobile.datebox.prototype._customformat, { + // If this stucture exists, the formatter will call it when it encounters a special string + // %X - it recieves the single letter operater, and the current "date" value + 'custombox' : function ( oper, val ) { + return val[oper-1]; + } + }); + $.extend( $.mobile.datebox.prototype._build, { + 'custombox': function () { + var w = this, + o = this.options, i, y, tmp, cnt = -2, + uid = 'ui-datebox-', + divBase = $("
              "), + divPlus = $('
              '), + divIn = divBase.clone(), + divMinus = divPlus.clone(), + customCurrent = this._makeDate(this.d.input.val()), + inBase = $("").addClass('ui-input-text ui-corner-all ui-shadow-inset ui-body-'+o.themeInput), + inDiv = $("
              ").addClass('ui-input-text ui-corner-all ui-shadow-inset ui-body-'+o.themeInput).css({'padding':'.4em','margin':'.5em 0','text-align':'center'}), + butBase = $("
              "), + butPTheme = {theme: o.themeButton, icon: 'plus', iconpos: 'bottom', corners:true, shadow:true}, + butMTheme = $.extend({}, butPTheme, {icon: 'minus', iconpos: 'top'}); + + if ( typeof w.customCurrent === "undefined" ) { w.customCurrent = customCurrent; } + + if ( o.customFormat === false ) { + tmp = []; + for ( i = 0; i'); + + + for(i=0; i').append(inBase.clone().attr('value', o.customData[i]['data'][w.customCurrent[i]])).addClass('ui-block-'+tmp).appendTo(divIn); + } else { + $('
              ').append(inDiv.clone().html(o.customData[i]['data'][w.customCurrent[i]])).addClass('ui-block-'+tmp).appendTo(divIn); + } + w._makeEl(butBase, {'attr': {'field':i, 'amount':1}}).addClass('ui-block-'+tmp).buttonMarkup(butPTheme).appendTo(divPlus); + w._makeEl(butBase, {'attr': {'field':i, 'amount':1}}).addClass('ui-block-'+tmp).buttonMarkup(butMTheme).appendTo(divMinus); + cnt++; + } + + divPlus.addClass('ui-grid-'+['a','b','c','d','e'][cnt]).appendTo(w.d.intHTML); + divIn.addClass('ui-datebox-dboxin').addClass('ui-grid-'+['a','b','c','d','e'][cnt]).appendTo(w.d.intHTML); + divMinus.addClass('ui-grid-'+['a','b','c','d','e'][cnt]).appendTo(w.d.intHTML); + + if (o.mobVer >= 140) { + divMinus.find('div').css({'min-height': '2.3em'}); + divPlus.find('div').css({'min-height': '2.3em'}); + } + + if (o.mobVer >= 140) { + divMinus.find('div').css({'min-height': '2.3em'}); + divPlus.find('div').css({'min-height': '2.3em'}); + } + + if ( o.useSetButton || o.useClearButton ) { + y = $('
              ', {'class':uid+'controls'}); + + if ( o.useSetButton ) { + $(''+w.__('customSet')+'') + .appendTo(y).buttonMarkup({theme: o.theme, icon: 'check', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.trigger('datebox', {'method':'set', 'value':w._formatter(o.customFormat,w.customCurrent), 'date':w.customCurrent}); + w.d.input.trigger('datebox', {'method':'close'}); + }); + } + if ( o.useClearButton ) { + $(''+w.__('clearButton')+'') + .appendTo(y).buttonMarkup({theme: o.theme, icon: 'delete', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.val(''); + w.d.input.trigger('datebox',{'method':'clear'}); + w.d.input.trigger('datebox',{'method':'close'}); + }); + } + if ( o.useCollapsedBut ) { + y.addClass('ui-datebox-collapse'); + } + y.appendTo(w.d.intHTML); + } + + divIn.on('change', 'input', function() { w.refresh(); }); + + divPlus.on(o.clickEvent, 'div', function(e) { + e.preventDefault(); + w._cbox_offset($(this).jqmData('field'), $(this).jqmData('amount')); + }); + divMinus.on(o.clickEvent, 'div', function(e) { + e.preventDefault(); + w._cbox_offset($(this).jqmData('field'), $(this).jqmData('amount')*-1); + }); + + } + }); +})( jQuery ); diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.custombox.min.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.custombox.min.js new file mode 100644 index 000000000..6ed323197 --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.custombox.min.js @@ -0,0 +1,7 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +(function(a){a.extend(a.mobile.datebox.prototype.options,{themeButton:"a",themeInput:"a",useSetButton:true,customData:[{input:true,name:"Letter",data:["a","b","c","d","e"]},{input:true,name:"Text",data:["some","bull","shtuff","here"]},{input:false,name:"Image",data:['','','','']}],customDefault:[0,0,0],customFormat:false,customboxlang:{customSet:"Looks Good"}});a.extend(a.mobile.datebox.prototype,{_cbox_offset:function(e,d){var c=this,b,f=this.options;tmp=(c.customCurrent[e]+d)%f.customData[e]["data"].length;if(tmp<0){tmp=f.customData[e]["data"].length+tmp}c.customCurrent[e]=tmp;if(f.useImmediate){c.d.input.trigger("datebox",{method:"set",value:c._formatter(f.customFormat,c.customCurrent),date:c.customCurrent})}c.refresh()}});a.extend(a.mobile.datebox.prototype._parser,{custombox:function(b){return(b.length<1||!b.match(/,/))?this.options.customDefault:b.split(",")}});a.extend(a.mobile.datebox.prototype._customformat,{custombox:function(c,b){return b[c-1]}});a.extend(a.mobile.datebox.prototype._build,{custombox:function(){var t=this,f=this.options,l,s,m,g=-2,q="ui-datebox-",r=a("
              "),c=a("
              "),j=r.clone(),k=c.clone(),n=this._makeDate(this.d.input.val()),e=a("").addClass("ui-input-text ui-corner-all ui-shadow-inset ui-body-"+f.themeInput),h=a("
              ").addClass("ui-input-text ui-corner-all ui-shadow-inset ui-body-"+f.themeInput).css({padding:".4em",margin:".5em 0","text-align":"center"}),p=a("
              "),b={theme:f.themeButton,icon:"plus",iconpos:"bottom",corners:true,shadow:true},d=a.extend({},b,{icon:"minus",iconpos:"top"});if(typeof t.customCurrent==="undefined"){t.customCurrent=n}if(f.customFormat===false){m=[];for(l=0;l");for(l=0;l").append(e.clone().attr("value",f.customData[l]["data"][t.customCurrent[l]])).addClass("ui-block-"+m).appendTo(j)}else{a("
              ").append(h.clone().html(f.customData[l]["data"][t.customCurrent[l]])).addClass("ui-block-"+m).appendTo(j)}t._makeEl(p,{attr:{field:l,amount:1}}).addClass("ui-block-"+m).buttonMarkup(b).appendTo(c);t._makeEl(p,{attr:{field:l,amount:1}}).addClass("ui-block-"+m).buttonMarkup(d).appendTo(k);g++}c.addClass("ui-grid-"+["a","b","c","d","e"][g]).appendTo(t.d.intHTML);j.addClass("ui-datebox-dboxin").addClass("ui-grid-"+["a","b","c","d","e"][g]).appendTo(t.d.intHTML);k.addClass("ui-grid-"+["a","b","c","d","e"][g]).appendTo(t.d.intHTML);if(f.mobVer>=140){k.find("div").css({"min-height":"2.3em"});c.find("div").css({"min-height":"2.3em"})}if(f.mobVer>=140){k.find("div").css({"min-height":"2.3em"});c.find("div").css({"min-height":"2.3em"})}if(f.useSetButton||f.useClearButton){s=a("
              ",{"class":q+"controls"});if(f.useSetButton){a(''+t.__("customSet")+"").appendTo(s).buttonMarkup({theme:f.theme,icon:"check",iconpos:"left",corners:true,shadow:true}).on(f.clickEventAlt,function(i){i.preventDefault();t.d.input.trigger("datebox",{method:"set",value:t._formatter(f.customFormat,t.customCurrent),date:t.customCurrent});t.d.input.trigger("datebox",{method:"close"})})}if(f.useClearButton){a(''+t.__("clearButton")+"").appendTo(s).buttonMarkup({theme:f.theme,icon:"delete",iconpos:"left",corners:true,shadow:true}).on(f.clickEventAlt,function(i){i.preventDefault();t.d.input.val("");t.d.input.trigger("datebox",{method:"clear"});t.d.input.trigger("datebox",{method:"close"})})}if(f.useCollapsedBut){s.addClass("ui-datebox-collapse")}s.appendTo(t.d.intHTML)}j.on("change","input",function(){t.refresh()});c.on(f.clickEvent,"div",function(i){i.preventDefault();t._cbox_offset(a(this).jqmData("field"),a(this).jqmData("amount"))});k.on(f.clickEvent,"div",function(i){i.preventDefault();t._cbox_offset(a(this).jqmData("field"),a(this).jqmData("amount")*-1)})}})})(jQuery); \ No newline at end of file diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.customflip.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.customflip.js new file mode 100644 index 000000000..b59800ad9 --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.customflip.js @@ -0,0 +1,294 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +/* CUSTOMFLIP Mode */ + +(function($) { + $.extend( $.mobile.datebox.prototype.options, { + themeOptPick: 'b', + themeOpt: 'a', + useSetButton: true, + customData: [ + {'input': true, 'name':'Letter', 'data':['a','b','c','d','e']}, + {'input': true, 'name':'Text', 'data':['some','bull','shtuff','here']}, + {'input': false, 'name':'Image', 'data':['','','','']} + ], + customDefault: [0,0,0], + customFormat: false, + customfliplang: { + // This structure interfaces with __() -> if it exists, strings are looked up here after i8n fails, + // and before going to 'default' - the name syntax is lang + 'customSet':'Looks Good' + } + }); + $.extend( $.mobile.datebox.prototype, { + '_customflipDoSet': function () { + // If this function exists, it overrides the 'doset' method of the 'datebox' event. + // The name syntax is _DoSet + var w = this, o = this.options; + if ( typeof w.customCurrent === 'undefined' ) { w.customCurrent = this._makeDate(this.d.input.val()); } + w.d.input.trigger('datebox', {'method':'set', 'value':w._formatter(o.customFormat,w.customCurrent), 'date':w.customCurrent}); + }, + '_cubox_offset': function (fld, amount) { + // This is *not* an automatic override, used below specificly. + var w = this, x, + o = this.options; + + tmp = (w.customCurrent[fld] + amount) % o.customData[fld]['data'].length; + if ( tmp < 0 ) { tmp = o.customData[fld]['data'].length + tmp; } + + w.customCurrent[fld] = tmp; + if ( o.useImmediate ) { w.d.input.trigger('datebox', {'method':'set', 'value':w._formatter(o.customFormat,w.customCurrent), 'date':w.customCurrent}); } + w.refresh(); + }, + '_cubox_arr': function (data, choice) { + var base = data, x, + before = data.slice(0,choice), + after = data.slice(choice+1); + + while ( before.length < 10 ) { + for ( x = base.length; x > 0; x-- ) { + before.unshift(base[x-1]); + } + } + while ( before.length > 10 ) { + before.shift(); + } + + while ( after.length < 10 ) { + for ( x = 0; x < base.length; x++ ) { + after.push(base[x]); + } + } + after.length = 10; + + before.push(data[choice]); + + return $.merge($.merge([], before), after); + }, + '_cubox_pos': function () { + var w = this, + ech = null, + top = null, + par = this.d.intHTML.find('.ui-datebox-flipcontent').innerHeight(), + tot = null; + + w.d.intHTML.find('.ui-datebox-flipcenter').each(function() { + ech = $(this); + top = ech.innerHeight(); + ech.css('top', ((par/2)-(top/2)+4)*-1); + }); + w.d.intHTML.find('ul').each(function () { + ech = $(this); + par = ech.parent().innerHeight(); + top = ech.find('li').first(); + tot = ech.find('li').size() * top.outerHeight(); + top.css('marginTop', ((tot/2)-(par/2)+(top.outerHeight()/2))*-1); + }); + } + }); + $.extend( $.mobile.datebox.prototype._parser, { + // If this stucture exists, it is called instead of the usual date input parser. + // The name of the structure is the same as the mode name - it recieves a string + // as the input, which is the current value of the input element, pre-sanitized + 'customflip' : function ( str ) { + var w = this, + o = this.options, + adv = o.customFormat, + exp_input, exp_format, tmp, tmp2, retty_val=[0,0,0,0,0,0]; + + if ( typeof(adv) !== 'string' ) { adv = ''; } + + adv = adv.replace(/%X([0-9a-f])/gi, function(match, oper) { + switch (oper) { + case 'a': + case 'b': + case 'c': + case 'd': + case 'e': + case 'f': + return '(' + match + '|' + '.+?' + ')'; break; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + return '(' + match + '|' + '[0-9]+' + ')'; break; + default: + return '.+?'; + } + }); + + adv = new RegExp('^' + adv + '$'); + exp_input = adv.exec(str); + exp_format = adv.exec(o.customFormat); + + if ( exp_input !== null ) { + for ( var x = 1; x - it recieves the single letter operater, and the current "date" value + 'customflip' : function ( oper, val, o ) { + var per = parseInt(oper), tmp; + + if ( typeof(per) === 'number' && !isNaN(per) ) { + return val[oper-1]; + } else { + tmp = $.inArray(oper, ['a','b','c','d','e','f']); + return o.customData[tmp].data[val[tmp]]; + } + } + }); + $.extend( $.mobile.datebox.prototype._build, { + // This builds the actual interface, and is called on *every* refresh. (after each "movement") + 'customflip': function () { + var w = this, + o = this.options, i, y, hRow, tmp, lineArr, + uid = 'ui-datebox-', + customCurrent = this._makeDate(this.d.input.val()), + flipBase = $("
                "), + ctrl = $("
                ", {"class":uid+'flipcontent'}); + + if ( typeof w.customCurrent === "undefined" ) { w.customCurrent = customCurrent; } + + if ( o.customFormat === false ) { + tmp = []; + for ( i = 0; i'); + + w.fldOrder = o.tireFieldOrder; + + tmp = $('
                '); + for ( y=0; y'+o.customData[y]['name']+'
                ').css('textAlign','center').appendTo(tmp); + } + tmp.appendTo(w.d.intHTML); + + w.d.intHTML.append(ctrl); + + for ( y=0; y', {'class':'ui-body-'+tmp}) + .html(''+lineArr[i]+'').appendTo(hRow.find('ul')); + } + hRow.appendTo(ctrl); + } + + $("
                ", {"class":uid+'flipcenter ui-overlay-shadow'}).css('pointerEvents', 'none').appendTo(w.d.intHTML); + + if ( o.useSetButton ) { + y = $('
                ', {'class':uid+'controls'}); + + if ( o.useSetButton ) { + $(''+w.__('customSet')+'') + .appendTo(y).buttonMarkup({theme: o.theme, icon: 'check', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.trigger('datebox', {'method':'set', 'value':w._formatter(o.customFormat,w.customCurrent), 'date':w.tireChoice}); + w.d.input.trigger('datebox', {'method':'close'}); + }); + } + y.appendTo(w.d.intHTML); + } + + if ( w.wheelExists ) { // Mousewheel operation, if plugin is loaded + w.d.intHTML.on('mousewheel', '.ui-overlay-shadow', function(e,d) { + e.preventDefault(); + w._cubox_offset($(this).jqmData('field'), ((d<0)?1:-1)*$(this).jqmData('amount')); + }); + } + + w.d.intHTML.on(w.drag.eStart, 'ul', function(e,f) { + if ( !w.drag.move ) { + if ( typeof f !== "undefined" ) { e = f; } + w.drag.move = true; + w.drag.target = $(this).find('li').first(); + w.drag.pos = parseInt(w.drag.target.css('marginTop').replace(/px/i, ''),10); + w.drag.start = w.touch ? e.originalEvent.changedTouches[0].pageY : e.pageY; + w.drag.end = false; + e.stopPropagation(); + e.preventDefault(); + } + }); + + w.d.intHTML.on(w.drag.eStart, '.'+uid+'flipcenter', function(e) { // Used only on old browsers and IE. + if ( !w.drag.move ) { + w.drag.target = w.touch ? e.originalEvent.changedTouches[0].pageX - $(e.currentTarget).offset().left : e.pageX - $(e.currentTarget).offset().left; + w.drag.tmp = w.d.intHTML.find('.'+uid+'flipcenter').innerWidth() / (( $.inArray('a', w.fldOrder) > -1 && w.__('timeFormat') !== 12 )?w.fldOrder.length-1:w.fldOrder.length); + $(w.d.intHTML.find('ul').get(parseInt(w.drag.target / w.drag.tmp,10))).trigger(w.drag.eStart,e); + } + }); + } + }); + $.extend( $.mobile.datebox.prototype._drag, { + // This contains the code that the drag and drop (or touch move) code uses + 'customflip': function() { + var w = this, + o = this.options, + g = this.drag; + + $(document).on(g.eMove, function(e) { + if ( g.move && o.mode === 'customflip' ) { + g.end = w.touch ? e.originalEvent.changedTouches[0].pageY : e.pageY; + g.target.css('marginTop', (g.pos + g.end - g.start) + 'px'); + e.preventDefault(); + e.stopPropagation(); + return false; + } + }); + + $(document).on(g.eEnd, function(e) { + if ( g.move && o.mode === 'customflip' ) { + g.move = false; + if ( g.end !== false ) { + e.preventDefault(); + e.stopPropagation(); + g.tmp = g.target.parent().parent(); + w._cubox_offset(g.tmp.jqmData('field'), (parseInt((g.start - g.end) / g.target.innerHeight(),10) * g.tmp.jqmData('amount'))); + } + g.start = false; + g.end = false; + } + }); + } + }); +})( jQuery ); diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.customflip.min.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.customflip.min.js new file mode 100644 index 000000000..f66d72e9e --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.customflip.min.js @@ -0,0 +1,7 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +(function(a){a.extend(a.mobile.datebox.prototype.options,{themeOptPick:"b",themeOpt:"a",useSetButton:true,customData:[{input:true,name:"Letter",data:["a","b","c","d","e"]},{input:true,name:"Text",data:["some","bull","shtuff","here"]},{input:false,name:"Image",data:['','','','']}],customDefault:[0,0,0],customFormat:false,customfliplang:{customSet:"Looks Good"}});a.extend(a.mobile.datebox.prototype,{_customflipDoSet:function(){var b=this,c=this.options;if(typeof b.customCurrent==="undefined"){b.customCurrent=this._makeDate(this.d.input.val())}b.d.input.trigger("datebox",{method:"set",value:b._formatter(c.customFormat,b.customCurrent),date:b.customCurrent})},_cubox_offset:function(e,d){var c=this,b,f=this.options;tmp=(c.customCurrent[e]+d)%f.customData[e]["data"].length;if(tmp<0){tmp=f.customData[e]["data"].length+tmp}c.customCurrent[e]=tmp;if(f.useImmediate){c.d.input.trigger("datebox",{method:"set",value:c._formatter(f.customFormat,c.customCurrent),date:c.customCurrent})}c.refresh()},_cubox_arr:function(f,c){var e=f,b,d=f.slice(0,c),g=f.slice(c+1);while(d.length<10){for(b=e.length;b>0;b--){d.unshift(e[b-1])}}while(d.length>10){d.shift()}while(g.length<10){for(b=0;b
                  "),b=a("
                  ",{"class":j+"flipcontent"});if(typeof l.customCurrent==="undefined"){l.customCurrent=g}if(d.customFormat===false){f=[];for(e=0;e");l.fldOrder=d.tireFieldOrder;f=a('
                  ');for(k=0;k'+d.customData[k]["name"]+"
                  ").css("textAlign","center").appendTo(f)}f.appendTo(l.d.intHTML);l.d.intHTML.append(b);for(k=0;k",{"class":"ui-body-"+f}).html(""+h[e]+"").appendTo(m.find("ul"))}m.appendTo(b)}a("
                  ",{"class":j+"flipcenter ui-overlay-shadow"}).css("pointerEvents","none").appendTo(l.d.intHTML);if(d.useSetButton){k=a("
                  ",{"class":j+"controls"});if(d.useSetButton){a(''+l.__("customSet")+"").appendTo(k).buttonMarkup({theme:d.theme,icon:"check",iconpos:"left",corners:true,shadow:true}).on(d.clickEventAlt,function(i){i.preventDefault();l.d.input.trigger("datebox",{method:"set",value:l._formatter(d.customFormat,l.customCurrent),date:l.tireChoice});l.d.input.trigger("datebox",{method:"close"})})}k.appendTo(l.d.intHTML)}if(l.wheelExists){l.d.intHTML.on("mousewheel",".ui-overlay-shadow",function(i,n){i.preventDefault();l._cubox_offset(a(this).jqmData("field"),((n<0)?1:-1)*a(this).jqmData("amount"))})}l.d.intHTML.on(l.drag.eStart,"ul",function(n,i){if(!l.drag.move){if(typeof i!=="undefined"){n=i}l.drag.move=true;l.drag.target=a(this).find("li").first();l.drag.pos=parseInt(l.drag.target.css("marginTop").replace(/px/i,""),10);l.drag.start=l.touch?n.originalEvent.changedTouches[0].pageY:n.pageY;l.drag.end=false;n.stopPropagation();n.preventDefault()}});l.d.intHTML.on(l.drag.eStart,"."+j+"flipcenter",function(i){if(!l.drag.move){l.drag.target=l.touch?i.originalEvent.changedTouches[0].pageX-a(i.currentTarget).offset().left:i.pageX-a(i.currentTarget).offset().left;l.drag.tmp=l.d.intHTML.find("."+j+"flipcenter").innerWidth()/((a.inArray("a",l.fldOrder)>-1&&l.__("timeFormat")!==12)?l.fldOrder.length-1:l.fldOrder.length);a(l.d.intHTML.find("ul").get(parseInt(l.drag.target/l.drag.tmp,10))).trigger(l.drag.eStart,i)}})}});a.extend(a.mobile.datebox.prototype._drag,{customflip:function(){var b=this,d=this.options,c=this.drag;a(document).on(c.eMove,function(f){if(c.move&&d.mode==="customflip"){c.end=b.touch?f.originalEvent.changedTouches[0].pageY:f.pageY;c.target.css("marginTop",(c.pos+c.end-c.start)+"px");f.preventDefault();f.stopPropagation();return false}});a(document).on(c.eEnd,function(f){if(c.move&&d.mode==="customflip"){c.move=false;if(c.end!==false){f.preventDefault();f.stopPropagation();c.tmp=c.target.parent().parent();b._cubox_offset(c.tmp.jqmData("field"),(parseInt((c.start-c.end)/c.target.innerHeight(),10)*c.tmp.jqmData("amount")))}c.start=false;c.end=false}})}})})(jQuery); \ No newline at end of file diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.datebox.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.datebox.js new file mode 100644 index 000000000..0a3131486 --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.datebox.js @@ -0,0 +1,319 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ + +(function($) { + $.extend( $.mobile.datebox.prototype.options, { + themeButton: 'a', + themeInput: 'a', + useSetButton: true, + validHours: false, + repButton: true + + }); + $.extend( $.mobile.datebox.prototype, { + _dbox_run: function() { + var w = this; + w.drag.didRun = true; + w._offset(w.drag.target[0], w.drag.target[1], false); + w._dbox_run_update(); + w.runButton = setTimeout(function() {w._dbox_run();}, 150); + }, + _dbox_run_update: function() { + var w = this, + o = this.options; + + if ( o.mode === 'datebox' ) { + w.d.intHTML.find('.ui-datebox-header').find('h4').text(w._formatter(w.__('headerFormat'), w.theDate)); + } + + w.d.divIn.find('input').each(function () { + switch ( $(this).jqmData('field') ) { + case 'y': + $(this).val(w.theDate.getFullYear()); break; + case 'm': + $(this).val(w.theDate.getMonth() + 1); break; + case 'd': + $(this).val(w.theDate.getDate()); break; + case 'h': + if ( w.__('timeFormat') === 12 ) { + if ( w.theDate.getHours() > 12 ) { + $(this).val(w.theDate.getHours()-12); break; + } else if ( w.theDate.getHours() === 0 ) { + $(this).val(12); break; + } + } + $(this).val(w.theDate.getHours()); break; + case 'i': + $(this).val(w._zPad(w.theDate.getMinutes())); break; + case 'M': + $(this).val(w.__('monthsOfYearShort')[w.theDate.getMonth()]); break; + case 'a': + $(this).val((w.theDate.getHours() > 11)?w.__('meridiem')[1]:w.__('meridiem')[0]); + break; + } + }); + }, + _dbox_vhour: function (delta) { + var w = this, + o = this.options, tmp, + closeya = [25,0], + closenay = [25,0]; + + if ( o.validHours === false ) { return true; } + if ( $.inArray(w.theDate.getHours(), o.validHours) > -1 ) { return true; } + + tmp = w.theDate.getHours(); + $.each(o.validHours, function(){ + if ( ((tmp < this)?1:-1) === delta ) { + if ( closeya[0] > Math.abs(this-tmp) ) { + closeya = [Math.abs(this-tmp),parseInt(this,10)]; + } + } else { + if ( closenay[0] > Math.abs(this-tmp) ) { + closenay = [Math.abs(this-tmp),parseInt(this,10)]; + } + } + }); + if ( closeya[1] !== 0 ) { w.theDate.setHours(closeya[1]); } + else { w.theDate.setHours(closenay[1]); } + }, + _dbox_enter: function (item) { + var w = this; + + if ( item.jqmData('field') === 'M' && $.inArray(item.val(), w.__('monthsOfYearShort')) > -1 ) { + w.theDate.setMonth($.inArray(item.val(), w.__('monthsOfYearShort'))); + } + + if ( item.val() !== '' && item.val().toString().search(/^[0-9]+$/) === 0 ) { + switch ( item.jqmData('field') ) { + case 'y': + w.theDate.setFullYear(parseInt(item.val(),10)); break; + case 'm': + w.theDate.setMonth(parseInt(item.val(),10)-1); break; + case 'd': + w.theDate.setDate(parseInt(item.val(),10)); break; + case 'h': + w.theDate.setHours(parseInt(item.val(),10)); break; + case 'i': + w.theDate.setMinutes(parseInt(item.val(),10)); break; + } + } + w.refresh(); + } + }); + $.extend( $.mobile.datebox.prototype._build, { + 'timebox': function () { + this._build.datebox.apply(this,[]); + }, + 'datebox': function () { + var w = this, + g = this.drag, + o = this.options, i, y, tmp, cnt = -2, + uid = 'ui-datebox-', + divBase = $("
                  "), + divPlus = $('
                  '), + divIn = divBase.clone(), + divMinus = divPlus.clone(), + inBase = $("").addClass('ui-input-text ui-corner-all ui-shadow-inset ui-body-'+o.themeInput), + inBaseT = $("").addClass('ui-input-text ui-corner-all ui-shadow-inset ui-body-'+o.themeInput), + butBase = $("
                  "), + butPTheme = {theme: o.themeButton, icon: 'plus', iconpos: 'bottom', corners:true, shadow:true, inline:true}, + butMTheme = $.extend({}, butPTheme, {icon: 'minus', iconpos: 'top'}); + + if ( typeof w.d.intHTML !== 'boolean' ) { + w.d.intHTML.empty().remove(); + } + + w.d.headerText = ((w._grabLabel() !== false)?w._grabLabel():((o.mode==='datebox')?w.__('titleDateDialogLabel'):w.__('titleTimeDialogLabel'))); + w.d.intHTML = $(''); + + if ( w.inputType !== 'number' ) { inBase.attr('pattern', '[0-9]*'); } + + w.fldOrder = ((o.mode==='datebox')?w.__('dateFieldOrder'):w.__('timeFieldOrder')); + w._check(); + w._minStepFix(); + w._dbox_vhour(typeof w._dbox_delta !== 'undefined'?w._dbox_delta:1); + + if ( o.mode === 'datebox' ) { $('

                  '+w._formatter(w.__('headerFormat'), w.theDate)+'

                  ').appendTo(w.d.intHTML); } + + for(i=0; i<=w.fldOrder.length; i++) { + tmp = ['a','b','c','d','e','f'][i]; + switch (w.fldOrder[i]) { + case 'y': + case 'm': + case 'd': + case 'h': + $('
                  ').append(w._makeEl(inBase, {'attr': {'field':w.fldOrder[i], 'amount':1}})).addClass('ui-block-'+tmp).appendTo(divIn); + w._makeEl(butBase, {'attr': {'field':w.fldOrder[i], 'amount':1}}).addClass('ui-block-'+tmp).buttonMarkup(butPTheme).appendTo(divPlus); + w._makeEl(butBase, {'attr': {'field':w.fldOrder[i], 'amount':1}}).addClass('ui-block-'+tmp).buttonMarkup(butMTheme).appendTo(divMinus); + cnt++; + break; + case 'a': + if ( w.__('timeFormat') === 12 ) { + $('
                  ').append(w._makeEl(inBaseT, {'attr': {'field':w.fldOrder[i], 'amount':1}})).addClass('ui-block-'+tmp).appendTo(divIn); + w._makeEl(butBase, {'attr': {'field':w.fldOrder[i], 'amount':1}}).addClass('ui-block-'+tmp).buttonMarkup(butPTheme).appendTo(divPlus); + w._makeEl(butBase, {'attr': {'field':w.fldOrder[i], 'amount':1}}).addClass('ui-block-'+tmp).buttonMarkup(butMTheme).appendTo(divMinus); + cnt++; + } + break; + case 'M': + $('
                  ').append(w._makeEl(inBaseT, {'attr': {'field':w.fldOrder[i], 'amount':1}})).addClass('ui-block-'+tmp).appendTo(divIn); + w._makeEl(butBase, {'attr': {'field':w.fldOrder[i], 'amount':1}}).addClass('ui-block-'+tmp).buttonMarkup(butPTheme).appendTo(divPlus); + w._makeEl(butBase, {'attr': {'field':w.fldOrder[i], 'amount':1}}).addClass('ui-block-'+tmp).buttonMarkup(butMTheme).appendTo(divMinus); + cnt++; + break; + case 'i': + $('
                  ').append(w._makeEl(inBase, {'attr': {'field':w.fldOrder[i], 'amount':o.minuteStep}})).addClass('ui-block-'+tmp).appendTo(divIn); + w._makeEl(butBase, {'attr': {'field':w.fldOrder[i], 'amount':o.minuteStep}}).addClass('ui-block-'+tmp).buttonMarkup(butPTheme).appendTo(divPlus); + w._makeEl(butBase, {'attr': {'field':w.fldOrder[i], 'amount':o.minuteStep}}).addClass('ui-block-'+tmp).buttonMarkup(butMTheme).appendTo(divMinus); + cnt++; + break; + } + } + + divPlus.addClass('ui-grid-'+['a','b','c','d','e'][cnt]).appendTo(w.d.intHTML); + divIn.addClass('ui-datebox-dboxin').addClass('ui-grid-'+['a','b','c','d','e'][cnt]).appendTo(w.d.intHTML); + divMinus.addClass('ui-grid-'+['a','b','c','d','e'][cnt]).appendTo(w.d.intHTML); + + if ( o.mobVer >= 140 ) { + divMinus.find('div').css({'min-height':'2.3em'}); + divPlus.find('div').css({'min-height':'2.3em'}); + } + + divIn.find('input').each(function () { + switch ( $(this).jqmData('field') ) { + case 'y': + $(this).val(w.theDate.getFullYear()); break; + case 'm': + $(this).val(w.theDate.getMonth() + 1); break; + case 'd': + $(this).val(w.theDate.getDate()); break; + case 'h': + if ( w.__('timeFormat') === 12 ) { + if ( w.theDate.getHours() > 12 ) { + $(this).val(w.theDate.getHours()-12); break; + } else if ( w.theDate.getHours() === 0 ) { + $(this).val(12); break; + } + } + $(this).val(w.theDate.getHours()); break; + case 'i': + $(this).val(w._zPad(w.theDate.getMinutes())); break; + case 'M': + $(this).val(w.__('monthsOfYearShort')[w.theDate.getMonth()]); break; + case 'a': + $(this).val((w.theDate.getHours() > 11)?w.__('meridiem')[1]:w.__('meridiem')[0]); + break; + } + }); + + w.d.divIn = divIn; + + if ( w.dateOK !== true ) { + divIn.find('input').addClass(uid+'griddate-disable'); + } else { + divIn.find('.'+uid+'griddate-disable').removeClass(uid+'griddate-disable'); + } + + if ( o.useSetButton || o.useClearButton ) { + y = $('
                  ', {'class':uid+'controls'}); + + if ( o.useSetButton ) { + $(''+((o.mode==='datebox')?w.__('setDateButtonLabel'):w.__('setTimeButtonLabel'))+'') + .appendTo(y).buttonMarkup({theme: o.theme, icon: 'check', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + if ( w.dateOK === true ) { + w.d.input.trigger('datebox', {'method':'set', 'value':w._formatter(w.__fmt(),w.theDate), 'date':w.theDate}); + w.d.input.trigger('datebox', {'method':'close'}); + } + }); + } + if ( o.useClearButton ) { + $(''+w.__('clearButton')+'') + .appendTo(y).buttonMarkup({theme: o.theme, icon: 'delete', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.val(''); + w.d.input.trigger('datebox',{'method':'clear'}); + w.d.input.trigger('datebox',{'method':'close'}); + }); + } + if ( o.useCollapsedBut ) { + y.addClass('ui-datebox-collapse'); + } + y.appendTo(w.d.intHTML); + } + + if ( o.repButton === false ) { + divPlus.on(o.clickEvent, 'div', function(e) { + e.preventDefault(); + w._dbox_delta = 1; + w._offset($(this).jqmData('field'), $(this).jqmData('amount')); + }); + divMinus.on(o.clickEvent, 'div', function(e) { + e.preventDefault(); + w._dbox_delta = -1; + w._offset($(this).jqmData('field'), $(this).jqmData('amount')*-1); + }); + } + + divIn.on('change', 'input', function() { w._dbox_enter($(this)); }); + + if ( w.wheelExists ) { // Mousewheel operation, if plugin is loaded + divIn.on('mousewheel', 'input', function(e,d) { + e.preventDefault(); + w._dbox_delta = d<0?-1:1; + w._offset($(this).jqmData('field'), ((d<0)?-1:1)*$(this).jqmData('amount')); + }); + } + + if ( o.repButton === true ) { + divPlus.on(w.drag.eStart, 'div', function(e) { + tmp = [$(this).jqmData('field'), $(this).jqmData('amount')]; + w.drag.move = true; + w._dbox_delta = 1; + w._offset(tmp[0], tmp[1], false); + w._dbox_run_update(); + if ( !w.runButton ) { + w.drag.target = tmp; + w.runButton = setTimeout(function() {w._dbox_run();}, 500); + } + }); + + divMinus.on(w.drag.eStart, 'div', function(e) { + tmp = [$(this).jqmData('field'), $(this).jqmData('amount')*-1]; + w.drag.move = true; + w._dbox_delta = -1; + w._offset(tmp[0], tmp[1], false); + w._dbox_run_update(); + if ( !w.runButton ) { + w.drag.target = tmp; + w.runButton = setTimeout(function() {w._dbox_run();}, 500); + } + }); + + divPlus.on(g.eEndA, function(e) { + if ( g.move ) { + e.preventDefault(); + clearTimeout(w.runButton); + w.runButton = false; + g.move = false; + } + }); + divMinus.on(g.eEndA, function(e) { + if ( g.move ) { + e.preventDefault(); + clearTimeout(w.runButton); + w.runButton = false; + g.move = false; + } + }); + } + } + }); +})( jQuery ); diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.datebox.min.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.datebox.min.js new file mode 100644 index 000000000..8752fd2ec --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.datebox.min.js @@ -0,0 +1,7 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +(function(a){a.extend(a.mobile.datebox.prototype.options,{themeButton:"a",themeInput:"a",useSetButton:true,validHours:false,repButton:true});a.extend(a.mobile.datebox.prototype,{_dbox_run:function(){var b=this;b.drag.didRun=true;b._offset(b.drag.target[0],b.drag.target[1],false);b._dbox_run_update();b.runButton=setTimeout(function(){b._dbox_run()},150)},_dbox_run_update:function(){var b=this,c=this.options;if(c.mode==="datebox"){b.d.intHTML.find(".ui-datebox-header").find("h4").text(b._formatter(b.__("headerFormat"),b.theDate))}b.d.divIn.find("input").each(function(){switch(a(this).jqmData("field")){case"y":a(this).val(b.theDate.getFullYear());break;case"m":a(this).val(b.theDate.getMonth()+1);break;case"d":a(this).val(b.theDate.getDate());break;case"h":if(b.__("timeFormat")===12){if(b.theDate.getHours()>12){a(this).val(b.theDate.getHours()-12);break}else{if(b.theDate.getHours()===0){a(this).val(12);break}}}a(this).val(b.theDate.getHours());break;case"i":a(this).val(b._zPad(b.theDate.getMinutes()));break;case"M":a(this).val(b.__("monthsOfYearShort")[b.theDate.getMonth()]);break;case"a":a(this).val((b.theDate.getHours()>11)?b.__("meridiem")[1]:b.__("meridiem")[0]);break}})},_dbox_vhour:function(g){var b=this,f=this.options,e,d=[25,0],c=[25,0];if(f.validHours===false){return true}if(a.inArray(b.theDate.getHours(),f.validHours)>-1){return true}e=b.theDate.getHours();a.each(f.validHours,function(){if(((eMath.abs(this-e)){d=[Math.abs(this-e),parseInt(this,10)]}}else{if(c[0]>Math.abs(this-e)){c=[Math.abs(this-e),parseInt(this,10)]}}});if(d[1]!==0){b.theDate.setHours(d[1])}else{b.theDate.setHours(c[1])}},_dbox_enter:function(c){var b=this;if(c.jqmData("field")==="M"&&a.inArray(c.val(),b.__("monthsOfYearShort"))>-1){b.theDate.setMonth(a.inArray(c.val(),b.__("monthsOfYearShort")))}if(c.val()!==""&&c.val().toString().search(/^[0-9]+$/)===0){switch(c.jqmData("field")){case"y":b.theDate.setFullYear(parseInt(c.val(),10));break;case"m":b.theDate.setMonth(parseInt(c.val(),10)-1);break;case"d":b.theDate.setDate(parseInt(c.val(),10));break;case"h":b.theDate.setHours(parseInt(c.val(),10));break;case"i":b.theDate.setMinutes(parseInt(c.val(),10));break}}b.refresh()}});a.extend(a.mobile.datebox.prototype._build,{timebox:function(){this._build.datebox.apply(this,[])},datebox:function(){var u=this,n=this.drag,f=this.options,l,s,m,h=-2,q="ui-datebox-",r=a("
                  "),c=a("
                  "),j=r.clone(),k=c.clone(),e=a("").addClass("ui-input-text ui-corner-all ui-shadow-inset ui-body-"+f.themeInput),t=a("").addClass("ui-input-text ui-corner-all ui-shadow-inset ui-body-"+f.themeInput),p=a("
                  "),b={theme:f.themeButton,icon:"plus",iconpos:"bottom",corners:true,shadow:true,inline:true},d=a.extend({},b,{icon:"minus",iconpos:"top"});if(typeof u.d.intHTML!=="boolean"){u.d.intHTML.empty().remove()}u.d.headerText=((u._grabLabel()!==false)?u._grabLabel():((f.mode==="datebox")?u.__("titleDateDialogLabel"):u.__("titleTimeDialogLabel")));u.d.intHTML=a("");if(u.inputType!=="number"){e.attr("pattern","[0-9]*")}u.fldOrder=((f.mode==="datebox")?u.__("dateFieldOrder"):u.__("timeFieldOrder"));u._check();u._minStepFix();u._dbox_vhour(typeof u._dbox_delta!=="undefined"?u._dbox_delta:1);if(f.mode==="datebox"){a('

                  '+u._formatter(u.__("headerFormat"),u.theDate)+"

                  ").appendTo(u.d.intHTML)}for(l=0;l<=u.fldOrder.length;l++){m=["a","b","c","d","e","f"][l];switch(u.fldOrder[l]){case"y":case"m":case"d":case"h":a("
                  ").append(u._makeEl(e,{attr:{field:u.fldOrder[l],amount:1}})).addClass("ui-block-"+m).appendTo(j);u._makeEl(p,{attr:{field:u.fldOrder[l],amount:1}}).addClass("ui-block-"+m).buttonMarkup(b).appendTo(c);u._makeEl(p,{attr:{field:u.fldOrder[l],amount:1}}).addClass("ui-block-"+m).buttonMarkup(d).appendTo(k);h++;break;case"a":if(u.__("timeFormat")===12){a("
                  ").append(u._makeEl(t,{attr:{field:u.fldOrder[l],amount:1}})).addClass("ui-block-"+m).appendTo(j);u._makeEl(p,{attr:{field:u.fldOrder[l],amount:1}}).addClass("ui-block-"+m).buttonMarkup(b).appendTo(c);u._makeEl(p,{attr:{field:u.fldOrder[l],amount:1}}).addClass("ui-block-"+m).buttonMarkup(d).appendTo(k);h++}break;case"M":a("
                  ").append(u._makeEl(t,{attr:{field:u.fldOrder[l],amount:1}})).addClass("ui-block-"+m).appendTo(j);u._makeEl(p,{attr:{field:u.fldOrder[l],amount:1}}).addClass("ui-block-"+m).buttonMarkup(b).appendTo(c);u._makeEl(p,{attr:{field:u.fldOrder[l],amount:1}}).addClass("ui-block-"+m).buttonMarkup(d).appendTo(k);h++;break;case"i":a("
                  ").append(u._makeEl(e,{attr:{field:u.fldOrder[l],amount:f.minuteStep}})).addClass("ui-block-"+m).appendTo(j);u._makeEl(p,{attr:{field:u.fldOrder[l],amount:f.minuteStep}}).addClass("ui-block-"+m).buttonMarkup(b).appendTo(c);u._makeEl(p,{attr:{field:u.fldOrder[l],amount:f.minuteStep}}).addClass("ui-block-"+m).buttonMarkup(d).appendTo(k);h++;break}}c.addClass("ui-grid-"+["a","b","c","d","e"][h]).appendTo(u.d.intHTML);j.addClass("ui-datebox-dboxin").addClass("ui-grid-"+["a","b","c","d","e"][h]).appendTo(u.d.intHTML);k.addClass("ui-grid-"+["a","b","c","d","e"][h]).appendTo(u.d.intHTML);if(f.mobVer>=140){k.find("div").css({"min-height":"2.3em"});c.find("div").css({"min-height":"2.3em"})}j.find("input").each(function(){switch(a(this).jqmData("field")){case"y":a(this).val(u.theDate.getFullYear());break;case"m":a(this).val(u.theDate.getMonth()+1);break;case"d":a(this).val(u.theDate.getDate());break;case"h":if(u.__("timeFormat")===12){if(u.theDate.getHours()>12){a(this).val(u.theDate.getHours()-12);break}else{if(u.theDate.getHours()===0){a(this).val(12);break}}}a(this).val(u.theDate.getHours());break;case"i":a(this).val(u._zPad(u.theDate.getMinutes()));break;case"M":a(this).val(u.__("monthsOfYearShort")[u.theDate.getMonth()]);break;case"a":a(this).val((u.theDate.getHours()>11)?u.__("meridiem")[1]:u.__("meridiem")[0]);break}});u.d.divIn=j;if(u.dateOK!==true){j.find("input").addClass(q+"griddate-disable")}else{j.find("."+q+"griddate-disable").removeClass(q+"griddate-disable")}if(f.useSetButton||f.useClearButton){s=a("
                  ",{"class":q+"controls"});if(f.useSetButton){a(''+((f.mode==="datebox")?u.__("setDateButtonLabel"):u.__("setTimeButtonLabel"))+"").appendTo(s).buttonMarkup({theme:f.theme,icon:"check",iconpos:"left",corners:true,shadow:true}).on(f.clickEventAlt,function(g){g.preventDefault();if(u.dateOK===true){u.d.input.trigger("datebox",{method:"set",value:u._formatter(u.__fmt(),u.theDate),date:u.theDate});u.d.input.trigger("datebox",{method:"close"})}})}if(f.useClearButton){a(''+u.__("clearButton")+"").appendTo(s).buttonMarkup({theme:f.theme,icon:"delete",iconpos:"left",corners:true,shadow:true}).on(f.clickEventAlt,function(g){g.preventDefault();u.d.input.val("");u.d.input.trigger("datebox",{method:"clear"});u.d.input.trigger("datebox",{method:"close"})})}if(f.useCollapsedBut){s.addClass("ui-datebox-collapse")}s.appendTo(u.d.intHTML)}if(f.repButton===false){c.on(f.clickEvent,"div",function(g){g.preventDefault();u._dbox_delta=1;u._offset(a(this).jqmData("field"),a(this).jqmData("amount"))});k.on(f.clickEvent,"div",function(g){g.preventDefault();u._dbox_delta=-1;u._offset(a(this).jqmData("field"),a(this).jqmData("amount")*-1)})}j.on("change","input",function(){u._dbox_enter(a(this))});if(u.wheelExists){j.on("mousewheel","input",function(g,i){g.preventDefault();u._dbox_delta=i<0?-1:1;u._offset(a(this).jqmData("field"),((i<0)?-1:1)*a(this).jqmData("amount"))})}if(f.repButton===true){c.on(u.drag.eStart,"div",function(g){m=[a(this).jqmData("field"),a(this).jqmData("amount")];u.drag.move=true;u._dbox_delta=1;u._offset(m[0],m[1],false);u._dbox_run_update();if(!u.runButton){u.drag.target=m;u.runButton=setTimeout(function(){u._dbox_run()},500)}});k.on(u.drag.eStart,"div",function(g){m=[a(this).jqmData("field"),a(this).jqmData("amount")*-1];u.drag.move=true;u._dbox_delta=-1;u._offset(m[0],m[1],false);u._dbox_run_update();if(!u.runButton){u.drag.target=m;u.runButton=setTimeout(function(){u._dbox_run()},500)}});c.on(n.eEndA,function(g){if(n.move){g.preventDefault();clearTimeout(u.runButton);u.runButton=false;n.move=false}});k.on(n.eEndA,function(g){if(n.move){g.preventDefault();clearTimeout(u.runButton);u.runButton=false;n.move=false}})}}})})(jQuery); \ No newline at end of file diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.durationbox.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.durationbox.js new file mode 100644 index 000000000..ee92fba16 --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.durationbox.js @@ -0,0 +1,247 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ + /* DurationBox Mode */ + +(function($) { + $.extend( $.mobile.datebox.prototype.options, { + themeButton: 'a', + themeInput: 'a', + useSetButton: true, + repButton: true, + durationSteppers: {'d': 1, 'h': 1, 'i': 1, 's': 1} + }); + $.extend( $.mobile.datebox.prototype, { + _durbox_run: function() { + var w = this; + w.drag.didRun = true; + w._offset(w.drag.target[0], w.drag.target[1], false); + w._durbox_run_update(); + w.runButton = setTimeout(function() {w._durbox_run();}, 100); + }, + _durbox_run_update: function () { + var w = this, i, cDur = [], + ival = {'d': 60*60*24, 'h': 60*60, 'i': 60}; + + i = w.theDate.getEpoch() - w.initDate.getEpoch(); + if ( i<0 ) { i = 0; w.theDate.setTime(w.initDate.getTime()); } + w.lastDuration = i; // Let the number of seconds be sort of public. + + // DAYS + cDur[0] = parseInt( i / ival.d,10); i = i % ival.d; + // HOURS + cDur[1] = parseInt( i / ival.h, 10); i = i % ival.h; + // MINS AND SECS + cDur[2] = parseInt( i / ival.i, 10); + cDur[3] = i % ival.i; + + w.d.divIn.find('input').each(function () { + switch ( $(this).parent().jqmData('field') ) { + case 'd': + $(this).val(cDur[0]); break; + case 'h': + $(this).val(cDur[1]); break; + case 'i': + $(this).val(cDur[2]); break; + case 's': + $(this).val(cDur[3]); break; + } + }); + }, + _durbox_valid: function (num) { + if ( num.toString().search(/^[0-9]+$/) === 0 ) { return parseInt(num,10); } + return 0; + }, + _durbox_enter: function (item) { + var w = this, + t = w.initDate.getEpoch(); + + w.d.intHTML.find('input').each( function() { + switch ( $(this).parent().jqmData('field') ) { + case 'd': + t += (60*60*24) * w._durbox_valid($(this).val()); break; + case 'h': + t += (60*60) * w._durbox_valid($(this).val()); break; + case 'i': + t += (60) * w._durbox_valid($(this).val()); break; + case 's': + t += w._durbox_valid($(this).val()); break; + } + }); + w.theDate.setTime( t * 1000 ); + w.refresh(); + } + }); + $.extend( $.mobile.datebox.prototype._build, { + 'durationbox': function () { + var w = this, + g = this.drag, + o = this.options, i, y, cDur = [0,0,0,0], tmp, + ival = {'d': 60*60*24, 'h': 60*60, 'i': 60}, + uid = 'ui-datebox-', + divBase = $("
                  "), + divPlus = $('
                  '), + divIn = divBase.clone().addClass('ui-datebox-dboxin'), + divMinus = divPlus.clone(), + inBase = $("").addClass('ui-input-text ui-corner-all ui-shadow-inset ui-body-'+o.themeInput), + butBase = $(""), + butPTheme = {theme: o.themeButton, icon: 'plus', iconpos: 'bottom', corners:true, shadow:true}, + butMTheme = $.extend({}, butPTheme, {icon: 'minus', iconpos: 'top'}); + + if ( typeof w.d.intHTML !== 'boolean' ) { + w.d.intHTML.empty().remove(); + } + + w.d.headerText = ((w._grabLabel() !== false)?w._grabLabel():w.__('titleDateDialogLabel')); + w.d.intHTML = $(''); + + if ( w.inputType !== 'number' ) { inBase.attr('pattern', '[0-9]*'); } + + w.fldOrder = w.__('durationOrder'); + + for(i=0; i<=w.fldOrder.length; i++) { + switch (w.fldOrder[i]) { + case 'd': + case 'h': + case 'i': + case 's': + y = $.inArray(w.fldOrder[i], ['d','h','i','s']); + $('
                  ').jqmData('field', w.fldOrder[i]).addClass('ui-block-'+['a','b','c','d'][i]).append(inBase.clone()).appendTo(divIn).prepend(''); + w._makeEl(butBase, {'attr': {'field':w.fldOrder[i]}}).addClass('ui-block-'+['a','b','c','d'][i]).buttonMarkup(butPTheme).appendTo(divPlus); + w._makeEl(butBase, {'attr': {'field':w.fldOrder[i]}}).addClass('ui-block-'+['a','b','c','d'][i]).buttonMarkup(butMTheme).appendTo(divMinus); + break; + } + } + + i = w.theDate.getEpoch() - w.initDate.getEpoch(); + if ( i<0 ) { i = 0; w.theDate.setTime(w.initDate.getTime()); } + w.lastDuration = i; // Let the number of seconds be sort of public. + + // DAYS + cDur[0] = parseInt( i / ival.d,10); i = i % ival.d; + // HOURS + cDur[1] = parseInt( i / ival.h, 10); i = i % ival.h; + // MINS AND SECS + cDur[2] = parseInt( i / ival.i, 10); + cDur[3] = i % ival.i; + + divIn.find('input').each(function () { + switch ( $(this).parent().jqmData('field') ) { + case 'd': + $(this).val(cDur[0]); break; + case 'h': + $(this).val(cDur[1]); break; + case 'i': + $(this).val(cDur[2]); break; + case 's': + $(this).val(cDur[3]); break; + } + }); + + w.d.divIn = divIn; + + divPlus.addClass('ui-grid-'+['a','b','c'][w.fldOrder.length-2]).appendTo(w.d.intHTML); + divIn.addClass('ui-grid-'+['a','b','c'][w.fldOrder.length-2]).appendTo(w.d.intHTML); + divMinus.addClass('ui-grid-'+['a','b','c'][w.fldOrder.length-2]).appendTo(w.d.intHTML); + + if (o.mobVer >= 140) { + divMinus.find('div').css({'min-height': '2.3em'}); + divPlus.find('div').css({'min-height': '2.3em'}); + } + + if ( o.useSetButton || o.useClearButton ) { + y = $('
                  ', {'class':uid+'controls'}); + + if ( o.useSetButton ) { + $(''+w.__('setDurationButtonLabel')+'') + .appendTo(y).buttonMarkup({theme: o.theme, icon: 'check', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.trigger('datebox', {'method':'set', 'value':w._formatter(w.__fmt(),w.theDate), 'date':w.theDate}); + w.d.input.trigger('datebox', {'method':'close'}); + }); + } + if ( o.useClearButton ) { + $(''+w.__('clearButton')+'') + .appendTo(y).buttonMarkup({theme: o.theme, icon: 'delete', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.val(''); + w.d.input.trigger('datebox',{'method':'clear'}); + w.d.input.trigger('datebox',{'method':'close'}); + }); + } + if ( o.useCollapsedBut ) { + y.addClass('ui-datebox-collapse'); + } + y.appendTo(w.d.intHTML); + } + + if ( o.repButton === false ) { + divPlus.on(o.clickEvent, 'div', function(e) { + e.preventDefault(); + w._offset($(this).jqmData('field'), o.durationSteppers[$(this).jqmData('field')]); + }); + divMinus.on(o.clickEvent, 'div', function(e) { + e.preventDefault(); + w._offset($(this).jqmData('field'), o.durationSteppers[$(this).jqmData('field')]*-1); + }); + } + + divIn.on('change', 'input', function() { w._durbox_enter($(this)); }); + + if ( w.wheelExists ) { // Mousewheel operation, if plugin is loaded + divIn.on('mousewheel', 'input', function(e,d) { + e.preventDefault(); + w._offset($(this).parent().jqmData('field'), ((d<0)?-1:1)*o.durationSteppers[$(this).parent().jqmData('field')]); + }); + } + + if ( o.repButton === true ) { + divPlus.on(w.drag.eStart, 'div', function(e) { + tmp = [$(this).jqmData('field'), o.durationSteppers[$(this).jqmData('field')]]; + w.drag.move = true; + w._dbox_delta = 1; + w._offset(tmp[0], tmp[1], false); + w._durbox_run_update(); + if ( !w.runButton ) { + w.drag.target = tmp; + w.runButton = setTimeout(function() {w._durbox_run();}, 500); + } + }); + + divMinus.on(w.drag.eStart, 'div', function(e) { + tmp = [$(this).jqmData('field'), o.durationSteppers[$(this).jqmData('field')]*-1]; + w.drag.move = true; + w._dbox_delta = -1; + w._offset(tmp[0], tmp[1], false); + w._durbox_run_update(); + if ( !w.runButton ) { + w.drag.target = tmp; + w.runButton = setTimeout(function() {w._durbox_run();}, 500); + } + }); + + divPlus.on(g.eEndA, function(e) { + if ( g.move ) { + e.preventDefault(); + clearTimeout(w.runButton); + w.runButton = false; + g.move = false; + } + }); + divMinus.on(g.eEndA, function(e) { + if ( g.move ) { + e.preventDefault(); + clearTimeout(w.runButton); + w.runButton = false; + g.move = false; + } + }); + } + } + }); +})( jQuery ); diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.durationbox.min.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.durationbox.min.js new file mode 100644 index 000000000..98ccc89c1 --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.durationbox.min.js @@ -0,0 +1,7 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +(function(a){a.extend(a.mobile.datebox.prototype.options,{themeButton:"a",themeInput:"a",useSetButton:true,repButton:true,durationSteppers:{d:1,h:1,i:1,s:1}});a.extend(a.mobile.datebox.prototype,{_durbox_run:function(){var b=this;b.drag.didRun=true;b._offset(b.drag.target[0],b.drag.target[1],false);b._durbox_run_update();b.runButton=setTimeout(function(){b._durbox_run()},100)},_durbox_run_update:function(){var c=this,e,b=[],d={d:60*60*24,h:60*60,i:60};e=c.theDate.getEpoch()-c.initDate.getEpoch();if(e<0){e=0;c.theDate.setTime(c.initDate.getTime())}c.lastDuration=e;b[0]=parseInt(e/d.d,10);e=e%d.d;b[1]=parseInt(e/d.h,10);e=e%d.h;b[2]=parseInt(e/d.i,10);b[3]=e%d.i;c.d.divIn.find("input").each(function(){switch(a(this).parent().jqmData("field")){case"d":a(this).val(b[0]);break;case"h":a(this).val(b[1]);break;case"i":a(this).val(b[2]);break;case"s":a(this).val(b[3]);break}})},_durbox_valid:function(b){if(b.toString().search(/^[0-9]+$/)===0){return parseInt(b,10)}return 0},_durbox_enter:function(d){var b=this,c=b.initDate.getEpoch();b.d.intHTML.find("input").each(function(){switch(a(this).parent().jqmData("field")){case"d":c+=(60*60*24)*b._durbox_valid(a(this).val());break;case"h":c+=(60*60)*b._durbox_valid(a(this).val());break;case"i":c+=(60)*b._durbox_valid(a(this).val());break;case"s":c+=b._durbox_valid(a(this).val());break}});b.theDate.setTime(c*1000);b.refresh()}});a.extend(a.mobile.datebox.prototype._build,{durationbox:function(){var u=this,n=this.drag,f=this.options,l,s,h=[0,0,0,0],m,t={d:60*60*24,h:60*60,i:60},q="ui-datebox-",r=a("
                  "),c=a("
                  "),j=r.clone().addClass("ui-datebox-dboxin"),k=c.clone(),e=a("").addClass("ui-input-text ui-corner-all ui-shadow-inset ui-body-"+f.themeInput),p=a(""),b={theme:f.themeButton,icon:"plus",iconpos:"bottom",corners:true,shadow:true},d=a.extend({},b,{icon:"minus",iconpos:"top"});if(typeof u.d.intHTML!=="boolean"){u.d.intHTML.empty().remove()}u.d.headerText=((u._grabLabel()!==false)?u._grabLabel():u.__("titleDateDialogLabel"));u.d.intHTML=a("");if(u.inputType!=="number"){e.attr("pattern","[0-9]*")}u.fldOrder=u.__("durationOrder");for(l=0;l<=u.fldOrder.length;l++){switch(u.fldOrder[l]){case"d":case"h":case"i":case"s":s=a.inArray(u.fldOrder[l],["d","h","i","s"]);a("
                  ").jqmData("field",u.fldOrder[l]).addClass("ui-block-"+["a","b","c","d"][l]).append(e.clone()).appendTo(j).prepend("");u._makeEl(p,{attr:{field:u.fldOrder[l]}}).addClass("ui-block-"+["a","b","c","d"][l]).buttonMarkup(b).appendTo(c);u._makeEl(p,{attr:{field:u.fldOrder[l]}}).addClass("ui-block-"+["a","b","c","d"][l]).buttonMarkup(d).appendTo(k);break}}l=u.theDate.getEpoch()-u.initDate.getEpoch();if(l<0){l=0;u.theDate.setTime(u.initDate.getTime())}u.lastDuration=l;h[0]=parseInt(l/t.d,10);l=l%t.d;h[1]=parseInt(l/t.h,10);l=l%t.h;h[2]=parseInt(l/t.i,10);h[3]=l%t.i;j.find("input").each(function(){switch(a(this).parent().jqmData("field")){case"d":a(this).val(h[0]);break;case"h":a(this).val(h[1]);break;case"i":a(this).val(h[2]);break;case"s":a(this).val(h[3]);break}});u.d.divIn=j;c.addClass("ui-grid-"+["a","b","c"][u.fldOrder.length-2]).appendTo(u.d.intHTML);j.addClass("ui-grid-"+["a","b","c"][u.fldOrder.length-2]).appendTo(u.d.intHTML);k.addClass("ui-grid-"+["a","b","c"][u.fldOrder.length-2]).appendTo(u.d.intHTML);if(f.mobVer>=140){k.find("div").css({"min-height":"2.3em"});c.find("div").css({"min-height":"2.3em"})}if(f.useSetButton||f.useClearButton){s=a("
                  ",{"class":q+"controls"});if(f.useSetButton){a(''+u.__("setDurationButtonLabel")+"").appendTo(s).buttonMarkup({theme:f.theme,icon:"check",iconpos:"left",corners:true,shadow:true}).on(f.clickEventAlt,function(g){g.preventDefault();u.d.input.trigger("datebox",{method:"set",value:u._formatter(u.__fmt(),u.theDate),date:u.theDate});u.d.input.trigger("datebox",{method:"close"})})}if(f.useClearButton){a(''+u.__("clearButton")+"").appendTo(s).buttonMarkup({theme:f.theme,icon:"delete",iconpos:"left",corners:true,shadow:true}).on(f.clickEventAlt,function(g){g.preventDefault();u.d.input.val("");u.d.input.trigger("datebox",{method:"clear"});u.d.input.trigger("datebox",{method:"close"})})}if(f.useCollapsedBut){s.addClass("ui-datebox-collapse")}s.appendTo(u.d.intHTML)}if(f.repButton===false){c.on(f.clickEvent,"div",function(g){g.preventDefault();u._offset(a(this).jqmData("field"),f.durationSteppers[a(this).jqmData("field")])});k.on(f.clickEvent,"div",function(g){g.preventDefault();u._offset(a(this).jqmData("field"),f.durationSteppers[a(this).jqmData("field")]*-1)})}j.on("change","input",function(){u._durbox_enter(a(this))});if(u.wheelExists){j.on("mousewheel","input",function(g,i){g.preventDefault();u._offset(a(this).parent().jqmData("field"),((i<0)?-1:1)*f.durationSteppers[a(this).parent().jqmData("field")])})}if(f.repButton===true){c.on(u.drag.eStart,"div",function(g){m=[a(this).jqmData("field"),f.durationSteppers[a(this).jqmData("field")]];u.drag.move=true;u._dbox_delta=1;u._offset(m[0],m[1],false);u._durbox_run_update();if(!u.runButton){u.drag.target=m;u.runButton=setTimeout(function(){u._durbox_run()},500)}});k.on(u.drag.eStart,"div",function(g){m=[a(this).jqmData("field"),f.durationSteppers[a(this).jqmData("field")]*-1];u.drag.move=true;u._dbox_delta=-1;u._offset(m[0],m[1],false);u._durbox_run_update();if(!u.runButton){u.drag.target=m;u.runButton=setTimeout(function(){u._durbox_run()},500)}});c.on(n.eEndA,function(g){if(n.move){g.preventDefault();clearTimeout(u.runButton);u.runButton=false;n.move=false}});k.on(n.eEndA,function(g){if(n.move){g.preventDefault();clearTimeout(u.runButton);u.runButton=false;n.move=false}})}}})})(jQuery); \ No newline at end of file diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.durationflipbox.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.durationflipbox.js new file mode 100644 index 000000000..e401c5ad3 --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.durationflipbox.js @@ -0,0 +1,206 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ + /* DurationFlipBox Mode */ + +(function($) { + $.extend( $.mobile.datebox.prototype.options, { + themeDatePick: 'b', + themeDate: 'a', + useSetButton: true, + durationSteppers: {'d': 1, 'h': 1, 'i': 1, 's': 1} + }); + $.extend( $.mobile.datebox.prototype, { + '_durfbox_pos': function () { + var w = this, + ech = null, + top = null, + par = this.d.intHTML.find('.ui-datebox-flipcontent').innerHeight(), + tot = null; + + w.d.intHTML.find('.ui-datebox-flipcenter').each(function() { + ech = $(this); + top = ech.innerHeight(); + ech.css('top', ((par/2)-(top/2)+4)*-1); + }); + w.d.intHTML.find('ul').each(function () { + ech = $(this); + par = ech.parent().innerHeight(); + top = ech.find('li').first(); + tot = ech.find('li').size() * top.outerHeight(); + top.css('marginTop', ((tot/2)-(par/2)+(top.outerHeight()/2))*-1); + }); + }, + '_durfbox_series': function (middle, side, type) { + var w = this, + o = this.options, + ret = [[middle.toString(), middle]], nxt, prv; + + for ( var i = 1; i <= side; i++ ) { + nxt = middle + ( i * o.durationSteppers[type] ); + prv = middle - ( i * o.durationSteppers[type] ); + ret.unshift([nxt.toString(), nxt]); + if ( prv > -1 ) { + ret.push([prv.toString(), prv]); + } else { + ret.push(['',-1]); + } + } + return ret; + } + }); + $.extend( $.mobile.datebox.prototype._build, { + 'durationflipbox': function () { + var w = this, + o = this.options, i, y, tt, hRow, tmp, testDate, + sel = ['d','h','i','s'], + cDur = [0,0,0,0], + cDurS = {}, + ival = {'d': 60*60*24, 'h': 60*60, 'i': 60}, + uid = 'ui-datebox-', + flipBase = $("
                    "), + ctrl = $("
                    ", {"class":uid+'flipcontent'+' '+uid+'flipcontentd'}); + + if ( typeof w.d.intHTML !== 'boolean' ) { + w.d.intHTML.empty().remove(); + } + + w.d.input.on('datebox', function (e,p) { + if ( p.method === 'postrefresh' ) { w._durfbox_pos(); } + }); + + w.d.headerText = ((w._grabLabel() !== false)?w._grabLabel():w.__('titleDateDialogLabel')); + w.d.intHTML = $(''); + + w.fldOrder = w.__('durationOrder'); + + tmp = $('
                    '); + for ( y=0; y'+w.__('durationLabel')[jQuery.inArray(w.fldOrder[y],['d','h','i','s'])]+'
                    ').css('textAlign','center').appendTo(tmp); + } + tmp.appendTo(w.d.intHTML); + + w.d.intHTML.append(ctrl); + + i = w.theDate.getEpoch() - w.initDate.getEpoch(); + if ( i<0 ) { i = 0; w.theDate.setTime(w.initDate.getTime()); } + w.lastDuration = i; // Let the number of seconds be sort of public. + + // SPLIT TIME INTO DAYS, HRS, MIN, SEC + cDur[0] = parseInt( i / ival.d, 10); i = i % ival.d; + cDur[1] = parseInt( i / ival.h, 10); i = i % ival.h; + cDur[2] = parseInt( i / ival.i, 10); + cDur[3] = i % ival.i; + + cDurS.d = w._durfbox_series(cDur[0],16,'d'); + cDurS.h = w._durfbox_series(cDur[1],16,'h'); + cDurS.i = w._durfbox_series(cDur[2],20,'i'); + cDurS.s = w._durfbox_series(cDur[3],20,'s'); + + for ( y=0; y", { 'class' : 'ui-body-'+tmp}) + .html(""+cDurS[tt][i][0] +"").appendTo(hRow.find('ul')); + } + hRow.appendTo(ctrl); + } + + $("
                    ", {"class":uid+'flipcenter ui-overlay-shadow'}).css('pointerEvents', 'none').appendTo(w.d.intHTML); + + if ( o.useSetButton || o.useClearButton ) { + y = $('
                    ', {'class':uid+'controls'}); + + if ( o.useSetButton ) { + $(''+w.__('setDurationButtonLabel')+'') + .appendTo(y).buttonMarkup({theme: o.theme, icon: 'check', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.trigger('datebox', {'method':'set', 'value':w._formatter(w.__fmt(),w.theDate), 'date':w.theDate}); + w.d.input.trigger('datebox', {'method':'close'}); + }); + } + if ( o.useClearButton ) { + $(''+w.__('clearButton')+'') + .appendTo(y).buttonMarkup({theme: o.theme, icon: 'delete', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.val(''); + w.d.input.trigger('datebox',{'method':'clear'}); + w.d.input.trigger('datebox',{'method':'close'}); + }); + } + if ( o.useCollapsedBut ) { + y.addClass('ui-datebox-collapse'); + } + y.appendTo(w.d.intHTML); + } + + if ( w.wheelExists ) { // Mousewheel operation, if plugin is loaded + w.d.intHTML.on('mousewheel', '.ui-overlay-shadow', function(e,d) { + e.preventDefault(); + w._offset($(this).jqmData('field'), ((d<0)?-1:1)*$(this).jqmData('amount')); + }); + } + + w.d.intHTML.on(w.drag.eStart, 'ul', function(e,f) { + if ( !w.drag.move ) { + if ( typeof f !== "undefined" ) { e = f; } + w.drag.move = true; + w.drag.target = $(this).find('li').first(); + w.drag.pos = parseInt(w.drag.target.css('marginTop').replace(/px/i, ''),10); + w.drag.start = w.touch ? e.originalEvent.changedTouches[0].pageY : e.pageY; + w.drag.end = false; + e.stopPropagation(); + e.preventDefault(); + } + }); + + w.d.intHTML.on(w.drag.eStart, '.'+uid+'flipcenter', function(e) { // Used only on old browsers and IE. + if ( !w.drag.move ) { + w.drag.target = w.touch ? e.originalEvent.changedTouches[0].pageX - $(e.currentTarget).offset().left : e.pageX - $(e.currentTarget).offset().left; + w.drag.tmp = w.d.intHTML.find('.'+uid+'flipcenter').innerWidth() / (( $.inArray('a', w.fldOrder) > -1 && w.__('timeFormat') !== 12 )?w.fldOrder.length-1:w.fldOrder.length); + $(w.d.intHTML.find('ul').get(parseInt(w.drag.target / w.drag.tmp,10))).trigger(w.drag.eStart,e); + } + }); + + } + }); + $.extend( $.mobile.datebox.prototype._drag, { + 'durationflipbox': function() { + var w = this, + o = this.options, + g = this.drag; + + $(document).on(g.eMove, function(e) { + if ( g.move && o.mode === 'durationflipbox' ) { + g.end = w.touch ? e.originalEvent.changedTouches[0].pageY : e.pageY; + g.target.css('marginTop', (g.pos + g.end - g.start) + 'px'); + e.preventDefault(); + e.stopPropagation(); + return false; + } + }); + + $(document).on(g.eEnd, function(e) { + if ( g.move && o.mode === 'durationflipbox' ) { + g.move = false; + if ( g.end !== false ) { + e.preventDefault(); + e.stopPropagation(); + g.tmp = g.target.parent().parent(); + w._offset(g.tmp.jqmData('field'), (parseInt((g.start - g.end) / g.target.innerHeight(),10) * g.tmp.jqmData('amount') *-1 )); + } + g.start = false; + g.end = false; + } + }); + } + }); +})( jQuery ); diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.durationflipbox.min.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.durationflipbox.min.js new file mode 100644 index 000000000..caec95515 --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.durationflipbox.min.js @@ -0,0 +1,7 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +(function(a){a.extend(a.mobile.datebox.prototype.options,{themeDatePick:"b",themeDate:"a",useSetButton:true,durationSteppers:{d:1,h:1,i:1,s:1}});a.extend(a.mobile.datebox.prototype,{_durfbox_pos:function(){var b=this,f=null,e=null,d=this.d.intHTML.find(".ui-datebox-flipcontent").innerHeight(),c=null;b.d.intHTML.find(".ui-datebox-flipcenter").each(function(){f=a(this);e=f.innerHeight();f.css("top",((d/2)-(e/2)+4)*-1)});b.d.intHTML.find("ul").each(function(){f=a(this);d=f.parent().innerHeight();e=f.find("li").first();c=f.find("li").size()*e.outerHeight();e.css("marginTop",((c/2)-(d/2)+(e.outerHeight()/2))*-1)})},_durfbox_series:function(k,g,h){var j=this,c=this.options,f=[[k.toString(),k]],b,e;for(var d=1;d<=g;d++){b=k+(d*c.durationSteppers[h]);e=k-(d*c.durationSteppers[h]);f.unshift([b.toString(),b]);if(e>-1){f.push([e.toString(),e])}else{f.push(["",-1])}}return f}});a.extend(a.mobile.datebox.prototype._build,{durationflipbox:function(){var q=this,e=this.options,g,l,k,r,h,m,d=["d","h","i","s"],f=[0,0,0,0],p={},n={d:60*60*24,h:60*60,i:60},j="ui-datebox-",c=a("
                      "),b=a("
                      ",{"class":j+"flipcontent "+j+"flipcontentd"});if(typeof q.d.intHTML!=="boolean"){q.d.intHTML.empty().remove()}q.d.input.on("datebox",function(o,i){if(i.method==="postrefresh"){q._durfbox_pos()}});q.d.headerText=((q._grabLabel()!==false)?q._grabLabel():q.__("titleDateDialogLabel"));q.d.intHTML=a("");q.fldOrder=q.__("durationOrder");h=a('
                      ');for(l=0;l'+q.__("durationLabel")[jQuery.inArray(q.fldOrder[l],["d","h","i","s"])]+"
                      ").css("textAlign","center").appendTo(h)}h.appendTo(q.d.intHTML);q.d.intHTML.append(b);g=q.theDate.getEpoch()-q.initDate.getEpoch();if(g<0){g=0;q.theDate.setTime(q.initDate.getTime())}q.lastDuration=g;f[0]=parseInt(g/n.d,10);g=g%n.d;f[1]=parseInt(g/n.h,10);g=g%n.h;f[2]=parseInt(g/n.i,10);f[3]=g%n.i;p.d=q._durfbox_series(f[0],16,"d");p.h=q._durfbox_series(f[1],16,"h");p.i=q._durfbox_series(f[2],20,"i");p.s=q._durfbox_series(f[3],20,"s");for(l=0;l",{"class":"ui-body-"+h}).html(""+p[k][g][0]+"").appendTo(r.find("ul"))}r.appendTo(b)}a("
                      ",{"class":j+"flipcenter ui-overlay-shadow"}).css("pointerEvents","none").appendTo(q.d.intHTML);if(e.useSetButton||e.useClearButton){l=a("
                      ",{"class":j+"controls"});if(e.useSetButton){a(''+q.__("setDurationButtonLabel")+"").appendTo(l).buttonMarkup({theme:e.theme,icon:"check",iconpos:"left",corners:true,shadow:true}).on(e.clickEventAlt,function(i){i.preventDefault();q.d.input.trigger("datebox",{method:"set",value:q._formatter(q.__fmt(),q.theDate),date:q.theDate});q.d.input.trigger("datebox",{method:"close"})})}if(e.useClearButton){a(''+q.__("clearButton")+"").appendTo(l).buttonMarkup({theme:e.theme,icon:"delete",iconpos:"left",corners:true,shadow:true}).on(e.clickEventAlt,function(i){i.preventDefault();q.d.input.val("");q.d.input.trigger("datebox",{method:"clear"});q.d.input.trigger("datebox",{method:"close"})})}if(e.useCollapsedBut){l.addClass("ui-datebox-collapse")}l.appendTo(q.d.intHTML)}if(q.wheelExists){q.d.intHTML.on("mousewheel",".ui-overlay-shadow",function(i,o){i.preventDefault();q._offset(a(this).jqmData("field"),((o<0)?-1:1)*a(this).jqmData("amount"))})}q.d.intHTML.on(q.drag.eStart,"ul",function(o,i){if(!q.drag.move){if(typeof i!=="undefined"){o=i}q.drag.move=true;q.drag.target=a(this).find("li").first();q.drag.pos=parseInt(q.drag.target.css("marginTop").replace(/px/i,""),10);q.drag.start=q.touch?o.originalEvent.changedTouches[0].pageY:o.pageY;q.drag.end=false;o.stopPropagation();o.preventDefault()}});q.d.intHTML.on(q.drag.eStart,"."+j+"flipcenter",function(i){if(!q.drag.move){q.drag.target=q.touch?i.originalEvent.changedTouches[0].pageX-a(i.currentTarget).offset().left:i.pageX-a(i.currentTarget).offset().left;q.drag.tmp=q.d.intHTML.find("."+j+"flipcenter").innerWidth()/((a.inArray("a",q.fldOrder)>-1&&q.__("timeFormat")!==12)?q.fldOrder.length-1:q.fldOrder.length);a(q.d.intHTML.find("ul").get(parseInt(q.drag.target/q.drag.tmp,10))).trigger(q.drag.eStart,i)}})}});a.extend(a.mobile.datebox.prototype._drag,{durationflipbox:function(){var b=this,d=this.options,c=this.drag;a(document).on(c.eMove,function(f){if(c.move&&d.mode==="durationflipbox"){c.end=b.touch?f.originalEvent.changedTouches[0].pageY:f.pageY;c.target.css("marginTop",(c.pos+c.end-c.start)+"px");f.preventDefault();f.stopPropagation();return false}});a(document).on(c.eEnd,function(f){if(c.move&&d.mode==="durationflipbox"){c.move=false;if(c.end!==false){f.preventDefault();f.stopPropagation();c.tmp=c.target.parent().parent();b._offset(c.tmp.jqmData("field"),(parseInt((c.start-c.end)/c.target.innerHeight(),10)*c.tmp.jqmData("amount")*-1))}c.start=false;c.end=false}})}})})(jQuery); \ No newline at end of file diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.flipbox.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.flipbox.js new file mode 100644 index 000000000..0f8b886dc --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.flipbox.js @@ -0,0 +1,251 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +/* FLIPBOX Mode */ + +(function($) { + $.extend( $.mobile.datebox.prototype.options, { + themeDateHigh: 'b', + themeDatePick: 'b', + themeDate: 'a', + useSetButton: true, + validHours: false, + flen: {'y': 15, 'm':12, 'd':15, 'h':12, 'i':15, 'a':3} + }); + $.extend( $.mobile.datebox.prototype, { + '_fbox_pos': function () { + var w = this, + ech = null, + top = null, + par = this.d.intHTML.find('.ui-datebox-flipcontent').innerHeight(), + tot = null; + + w.d.intHTML.find('.ui-datebox-flipcenter').each(function() { + ech = $(this); + top = ech.innerHeight(); + ech.css('top', ((par/2)-(top/2)+4)*-1); + }); + w.d.intHTML.find('ul').each(function () { + ech = $(this); + par = ech.parent().innerHeight(); + top = ech.find('li').first(); + tot = ech.find('li').size() * top.outerHeight(); + top.css('marginTop', ((tot/2)-(par/2)+(top.outerHeight()/2))*-1); + }); + } + }); + $.extend( $.mobile.datebox.prototype._build, { + 'timeflipbox': function() { + this._build.flipbox.apply(this); + }, + 'flipbox': function () { + var w = this, + o = this.options, i, y, hRow, tmp, testDate, + iDate = (w.d.input.val() === "") ? w._startOffset(w._makeDate(w.d.input.val())) : w._makeDate(w.d.input.val()), + uid = 'ui-datebox-', + flipBase = $("
                        "), + ctrl = $("
                        ", {"class":uid+'flipcontent'}); + + if ( typeof w.d.intHTML !== 'boolean' ) { + w.d.intHTML.empty(); + } + + w.d.input.on('datebox', function (e,p) { + if ( p.method === 'postrefresh' ) { + w._fbox_pos(); + } + }); + + w.d.headerText = ((w._grabLabel() !== false)?w._grabLabel():((o.mode==='flipbox')?w.__('titleDateDialogLabel'):w.__('titleTimeDialogLabel'))); + w.d.intHTML = $('') + + w.fldOrder = ((o.mode==='flipbox')?w.__('dateFieldOrder'):w.__('timeFieldOrder')); + w._check(); + w._minStepFix(); + + if ( o.mode === 'flipbox' ) { $('

                        '+w._formatter(w.__('headerFormat'), w.theDate)+'

                        ').appendTo(w.d.intHTML); } + + w.d.intHTML.append(ctrl); + + for ( y=0; y', {'class':'ui-body-'+tmp}) + .html(''+(w.theDate.get(0)+i)+'').appendTo(hRow.find('ul')); + } + hRow.appendTo(ctrl); + break; + case 'm': + hRow = w._makeEl(flipBase, {'attr': {'field':'m','amount':1} }); + for ( i=o.flen.m*-1; i<(o.flen.m+1); i++ ) { + testDate = w.theDate.copy([0],[0,0,1]); + testDate.adj(1,i); + tmp = (i!==0)?((iDate.get(1) === testDate.get(1) && iDate.get(0) === testDate.get(0))?o.themeDateHigh:o.themeDate):o.themeDatePick; + $("
                      • ", { 'class' : 'ui-body-'+tmp}) + .html(""+w.__('monthsOfYearShort')[testDate.getMonth()]+"").appendTo(hRow.find('ul')); + } + hRow.appendTo(ctrl); + break; + case 'd': + hRow = w._makeEl(flipBase, {'attr': {'field':'d','amount':1} }); + for ( i=o.flen.d*-1; i<(o.flen.d+1); i++ ) { + testDate = w.theDate.copy(); + testDate.adj(2,i); + tmp = (i!==0)?((iDate.comp() === testDate.comp())?o.themeDateHigh:o.themeDate):o.themeDatePick; + if ( ( o.blackDates !== false && $.inArray(testDate.iso(), o.blackDates) > -1 ) || + ( o.blackDays !== false && $.inArray(testDate.getDay(), o.blackDays) > -1 ) ) { + tmp += ' '+uid+'griddate-disable'; + } + $("
                      • ", { 'class' : 'ui-body-'+tmp}) + .html(""+testDate.getDate()+"").appendTo(hRow.find('ul')); + } + hRow.appendTo(ctrl); + break; + case 'h': + hRow = w._makeEl(flipBase, {'attr': {'field':'h','amount':1} }); + for ( i=o.flen.h*-1; i<(o.flen.h+1); i++ ) { + testDate = w.theDate.copy(); + testDate.adj(3,i); + tmp = (i!==0)?o.themeDate:o.themeDatePick; + if ( o.validHours !== false && $.inArray(testDate.get(3), o.validHours) < 0 ) { + tmp += ' '+uid+'griddate-disable'; + } + $("
                      • ", { 'class' : 'ui-body-'+tmp}) + .html(""+((w.__('timeFormat')===12) ? (( testDate.get(3) === 0 ) ? '12' : (( testDate.get(3) < 13 ) ? testDate.get(3) : (testDate.get(3)-12))) : testDate.get(3))+"").appendTo(hRow.find('ul')); + } + hRow.appendTo(ctrl); + break; + case 'i': + hRow = w._makeEl(flipBase, {'attr': {'field':'i','amount':o.minuteStep} }); + for ( i=o.flen.i*-1; i<(o.flen.i+1); i++ ) { + testDate = w.theDate.copy(); + testDate.adj(4,(i*o.minuteStep)); + tmp = (i!==0)?o.themeDate:o.themeDatePick; + $("
                      • ", { 'class' : 'ui-body-'+tmp}) + .html(""+w._zPad(testDate.get(4))+"").appendTo(hRow.find('ul')); + } + hRow.appendTo(ctrl); + break; + case 'a': + if ( w.__('timeFormat') !== 12 ) { break; } + hRow = w._makeEl(flipBase, {'attr': {'field':'a','amount':1} }); + testDate = $("
                      • "); + + for ( i=0; i 11) ? [o.themeDate,o.themeDatePick] : [o.themeDatePick,o.themeDate]; + + $("
                      • ", { 'class' : 'ui-body-'+tmp[0]}).html(''+w.__('meridiem')[0]+'').appendTo(hRow.find('ul')); + $("
                      • ", { 'class' : 'ui-body-'+tmp[1]}).html(''+w.__('meridiem')[1]+'').appendTo(hRow.find('ul')); + + if ( w.theDate.get(3) > 11 ) { testDate.clone().appendTo(hRow.find('ul')); } + for ( i=0; i", {"class":uid+'flipcenter ui-overlay-shadow'}).css('pointerEvents', 'none').appendTo(w.d.intHTML); + + if ( o.useSetButton || o.useClearButton ) { + y = $('
                        ', {'class':uid+'controls'}); + + if ( o.useSetButton ) { + $(''+((o.mode==='flipbox')?w.__('setDateButtonLabel'):w.__('setTimeButtonLabel'))+'') + .appendTo(y).buttonMarkup({theme: o.theme, icon: 'check', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + if ( w.dateOK === true ) { + w.d.input.trigger('datebox', {'method':'set', 'value':w._formatter(w.__fmt(),w.theDate), 'date':w.theDate}); + w.d.input.trigger('datebox', {'method':'close'}); + } + }); + } + if ( o.useClearButton ) { + $(''+w.__('clearButton')+'') + .appendTo(y).buttonMarkup({theme: o.theme, icon: 'delete', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.val(''); + w.d.input.trigger('datebox',{'method':'clear'}); + w.d.input.trigger('datebox',{'method':'close'}); + }); + } + if ( o.useCollapsedBut ) { + y.addClass('ui-datebox-collapse'); + } + y.appendTo(w.d.intHTML); + } + + if ( w.wheelExists ) { // Mousewheel operation, if plugin is loaded + w.d.intHTML.on('mousewheel', '.ui-overlay-shadow', function(e,d) { + e.preventDefault(); + w._offset($(this).jqmData('field'), ((d<0)?-1:1)*$(this).jqmData('amount')); + }); + } + + w.d.intHTML.on(w.drag.eStart, 'ul', function(e,f) { + if ( !w.drag.move ) { + if ( typeof f !== "undefined" ) { e = f; } + w.drag.move = true; + w.drag.target = $(this).find('li').first(); + w.drag.pos = parseInt(w.drag.target.css('marginTop').replace(/px/i, ''),10); + w.drag.start = w.touch ? e.originalEvent.changedTouches[0].pageY : e.pageY; + w.drag.end = false; + e.stopPropagation(); + e.preventDefault(); + } + }); + + w.d.intHTML.on(w.drag.eStart, '.'+uid+'flipcenter', function(e) { // Used only on old browsers and IE. + if ( !w.drag.move ) { + w.drag.target = w.touch ? e.originalEvent.changedTouches[0].pageX - $(e.currentTarget).offset().left : e.pageX - $(e.currentTarget).offset().left; + w.drag.tmp = w.d.intHTML.find('.'+uid+'flipcenter').innerWidth() / (( $.inArray('a', w.fldOrder) > -1 && w.__('timeFormat') !== 12 )?w.fldOrder.length-1:w.fldOrder.length); + $(w.d.intHTML.find('ul').get(parseInt(w.drag.target / w.drag.tmp,10))).trigger(w.drag.eStart,e); + } + }); + } + }); + $.extend( $.mobile.datebox.prototype._drag, { + 'timeflipbox': function() { + this._drag.flipbox.apply(this); + }, + 'flipbox': function() { + var w = this, + o = this.options, + g = this.drag; + + $(document).on(g.eMove, function(e) { + if ( g.move && ( o.mode === 'flipbox' || o.mode === 'timeflipbox' )) { + g.end = w.touch ? e.originalEvent.changedTouches[0].pageY : e.pageY; + g.target.css('marginTop', (g.pos + g.end - g.start) + 'px'); + e.preventDefault(); + e.stopPropagation(); + return false; + } + }); + + $(document).on(g.eEnd, function(e) { + if ( g.move && (o.mode === 'flipbox' || o.mode === 'timeflipbox' )) { + g.move = false; + if ( g.end !== false ) { + e.preventDefault(); + e.stopPropagation(); + g.tmp = g.target.parent().parent(); + w._offset(g.tmp.jqmData('field'), (parseInt((g.start - g.end) / g.target.innerHeight(),10) * g.tmp.jqmData('amount'))); + } + g.start = false; + g.end = false; + } + }); + } + }); +})( jQuery ); diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.flipbox.min.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.flipbox.min.js new file mode 100644 index 000000000..53403172b --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.flipbox.min.js @@ -0,0 +1,7 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +(function(a){a.extend(a.mobile.datebox.prototype.options,{themeDateHigh:"b",themeDatePick:"b",themeDate:"a",useSetButton:true,validHours:false,flen:{y:15,m:12,d:15,h:12,i:15,a:3}});a.extend(a.mobile.datebox.prototype,{_fbox_pos:function(){var b=this,f=null,e=null,d=this.d.intHTML.find(".ui-datebox-flipcontent").innerHeight(),c=null;b.d.intHTML.find(".ui-datebox-flipcenter").each(function(){f=a(this);e=f.innerHeight();f.css("top",((d/2)-(e/2)+4)*-1)});b.d.intHTML.find("ul").each(function(){f=a(this);d=f.parent().innerHeight();e=f.find("li").first();c=f.find("li").size()*e.outerHeight();e.css("marginTop",((c/2)-(d/2)+(e.outerHeight()/2))*-1)})}});a.extend(a.mobile.datebox.prototype._build,{timeflipbox:function(){this._build.flipbox.apply(this)},flipbox:function(){var l=this,d=this.options,e,j,m,f,k,g=(l.d.input.val()==="")?l._startOffset(l._makeDate(l.d.input.val())):l._makeDate(l.d.input.val()),h="ui-datebox-",c=a("
                          "),b=a("
                          ",{"class":h+"flipcontent"});if(typeof l.d.intHTML!=="boolean"){l.d.intHTML.empty()}l.d.input.on("datebox",function(n,i){if(i.method==="postrefresh"){l._fbox_pos()}});l.d.headerText=((l._grabLabel()!==false)?l._grabLabel():((d.mode==="flipbox")?l.__("titleDateDialogLabel"):l.__("titleTimeDialogLabel")));l.d.intHTML=a("");l.fldOrder=((d.mode==="flipbox")?l.__("dateFieldOrder"):l.__("timeFieldOrder"));l._check();l._minStepFix();if(d.mode==="flipbox"){a('

                          '+l._formatter(l.__("headerFormat"),l.theDate)+"

                          ").appendTo(l.d.intHTML)}l.d.intHTML.append(b);for(j=0;j",{"class":"ui-body-"+f}).html(""+(l.theDate.get(0)+e)+"").appendTo(m.find("ul"))}m.appendTo(b);break;case"m":m=l._makeEl(c,{attr:{field:"m",amount:1}});for(e=d.flen.m*-1;e<(d.flen.m+1);e++){k=l.theDate.copy([0],[0,0,1]);k.adj(1,e);f=(e!==0)?((g.get(1)===k.get(1)&&g.get(0)===k.get(0))?d.themeDateHigh:d.themeDate):d.themeDatePick;a("
                        • ",{"class":"ui-body-"+f}).html(""+l.__("monthsOfYearShort")[k.getMonth()]+"").appendTo(m.find("ul"))}m.appendTo(b);break;case"d":m=l._makeEl(c,{attr:{field:"d",amount:1}});for(e=d.flen.d*-1;e<(d.flen.d+1);e++){k=l.theDate.copy();k.adj(2,e);f=(e!==0)?((g.comp()===k.comp())?d.themeDateHigh:d.themeDate):d.themeDatePick;if((d.blackDates!==false&&a.inArray(k.iso(),d.blackDates)>-1)||(d.blackDays!==false&&a.inArray(k.getDay(),d.blackDays)>-1)){f+=" "+h+"griddate-disable"}a("
                        • ",{"class":"ui-body-"+f}).html(""+k.getDate()+"").appendTo(m.find("ul"))}m.appendTo(b);break;case"h":m=l._makeEl(c,{attr:{field:"h",amount:1}});for(e=d.flen.h*-1;e<(d.flen.h+1);e++){k=l.theDate.copy();k.adj(3,e);f=(e!==0)?d.themeDate:d.themeDatePick;if(d.validHours!==false&&a.inArray(k.get(3),d.validHours)<0){f+=" "+h+"griddate-disable"}a("
                        • ",{"class":"ui-body-"+f}).html(""+((l.__("timeFormat")===12)?((k.get(3)===0)?"12":((k.get(3)<13)?k.get(3):(k.get(3)-12))):k.get(3))+"").appendTo(m.find("ul"))}m.appendTo(b);break;case"i":m=l._makeEl(c,{attr:{field:"i",amount:d.minuteStep}});for(e=d.flen.i*-1;e<(d.flen.i+1);e++){k=l.theDate.copy();k.adj(4,(e*d.minuteStep));f=(e!==0)?d.themeDate:d.themeDatePick;a("
                        • ",{"class":"ui-body-"+f}).html(""+l._zPad(k.get(4))+"").appendTo(m.find("ul"))}m.appendTo(b);break;case"a":if(l.__("timeFormat")!==12){break}m=l._makeEl(c,{attr:{field:"a",amount:1}});k=a("
                        • ");for(e=0;e11)?[d.themeDate,d.themeDatePick]:[d.themeDatePick,d.themeDate];a("
                        • ",{"class":"ui-body-"+f[0]}).html(""+l.__("meridiem")[0]+"").appendTo(m.find("ul"));a("
                        • ",{"class":"ui-body-"+f[1]}).html(""+l.__("meridiem")[1]+"").appendTo(m.find("ul"));if(l.theDate.get(3)>11){k.clone().appendTo(m.find("ul"))}for(e=0;e",{"class":h+"flipcenter ui-overlay-shadow"}).css("pointerEvents","none").appendTo(l.d.intHTML);if(d.useSetButton||d.useClearButton){j=a("
                          ",{"class":h+"controls"});if(d.useSetButton){a(''+((d.mode==="flipbox")?l.__("setDateButtonLabel"):l.__("setTimeButtonLabel"))+"").appendTo(j).buttonMarkup({theme:d.theme,icon:"check",iconpos:"left",corners:true,shadow:true}).on(d.clickEventAlt,function(i){i.preventDefault();if(l.dateOK===true){l.d.input.trigger("datebox",{method:"set",value:l._formatter(l.__fmt(),l.theDate),date:l.theDate});l.d.input.trigger("datebox",{method:"close"})}})}if(d.useClearButton){a(''+l.__("clearButton")+"").appendTo(j).buttonMarkup({theme:d.theme,icon:"delete",iconpos:"left",corners:true,shadow:true}).on(d.clickEventAlt,function(i){i.preventDefault();l.d.input.val("");l.d.input.trigger("datebox",{method:"clear"});l.d.input.trigger("datebox",{method:"close"})})}if(d.useCollapsedBut){j.addClass("ui-datebox-collapse")}j.appendTo(l.d.intHTML)}if(l.wheelExists){l.d.intHTML.on("mousewheel",".ui-overlay-shadow",function(i,n){i.preventDefault();l._offset(a(this).jqmData("field"),((n<0)?-1:1)*a(this).jqmData("amount"))})}l.d.intHTML.on(l.drag.eStart,"ul",function(n,i){if(!l.drag.move){if(typeof i!=="undefined"){n=i}l.drag.move=true;l.drag.target=a(this).find("li").first();l.drag.pos=parseInt(l.drag.target.css("marginTop").replace(/px/i,""),10);l.drag.start=l.touch?n.originalEvent.changedTouches[0].pageY:n.pageY;l.drag.end=false;n.stopPropagation();n.preventDefault()}});l.d.intHTML.on(l.drag.eStart,"."+h+"flipcenter",function(i){if(!l.drag.move){l.drag.target=l.touch?i.originalEvent.changedTouches[0].pageX-a(i.currentTarget).offset().left:i.pageX-a(i.currentTarget).offset().left;l.drag.tmp=l.d.intHTML.find("."+h+"flipcenter").innerWidth()/((a.inArray("a",l.fldOrder)>-1&&l.__("timeFormat")!==12)?l.fldOrder.length-1:l.fldOrder.length);a(l.d.intHTML.find("ul").get(parseInt(l.drag.target/l.drag.tmp,10))).trigger(l.drag.eStart,i)}})}});a.extend(a.mobile.datebox.prototype._drag,{timeflipbox:function(){this._drag.flipbox.apply(this)},flipbox:function(){var b=this,d=this.options,c=this.drag;a(document).on(c.eMove,function(f){if(c.move&&(d.mode==="flipbox"||d.mode==="timeflipbox")){c.end=b.touch?f.originalEvent.changedTouches[0].pageY:f.pageY;c.target.css("marginTop",(c.pos+c.end-c.start)+"px");f.preventDefault();f.stopPropagation();return false}});a(document).on(c.eEnd,function(f){if(c.move&&(d.mode==="flipbox"||d.mode==="timeflipbox")){c.move=false;if(c.end!==false){f.preventDefault();f.stopPropagation();c.tmp=c.target.parent().parent();b._offset(c.tmp.jqmData("field"),(parseInt((c.start-c.end)/c.target.innerHeight(),10)*c.tmp.jqmData("amount")))}c.start=false;c.end=false}})}})})(jQuery); \ No newline at end of file diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.slidebox.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.slidebox.js new file mode 100644 index 000000000..981025f68 --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.slidebox.js @@ -0,0 +1,225 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +/* SLIDEBOX Mode */ + +(function($) { + $.extend( $.mobile.datebox.prototype.options, { + themeDateHigh: 'b', + themeDatePick: 'b', + themeDate: 'a', + useSetButton: true, + validHours: false, + slen: {'y': 5, 'm':6, 'd':15, 'h':12, 'i':30} + }); + $.extend( $.mobile.datebox.prototype, { + '_sbox_pos': function () { + var w = this, + ech, top, par, tot; + + w.d.intHTML.find('div.ui-datebox-sliderow-int').each(function () { + ech = $(this); + par = ech.parent().innerWidth(); + if ( w.__('isRTL') ) { + top = ech.find('div').last(); + } else { + top = ech.find('div').first(); + } + tot = ech.find('div').size() * top.outerWidth(); + top.css('marginLeft', ((tot/2)-(par/2))*-1); + }); + } + }); + $.extend( $.mobile.datebox.prototype._build, { + 'slidebox': function () { + var w = this, + o = this.options, i, y, hRow, phRow, tmp, testDate, + iDate = (w.d.input.val() === "") ? w._startOffset(w._makeDate(w.d.input.val())) : w._makeDate(w.d.input.val()), + uid = 'ui-datebox-', + thMod = (( this.options.mobVer < 140 ) ? 'up-' : ''), + slideBase = $("
                          "), + phBase = $('
                          '), + ctrl = $("
                          ", {"class":uid+'slide'}); + + if ( typeof w.d.intHTML !== 'boolean' ) { + w.d.intHTML.empty().remove() + } + + w.d.input.on('datebox', function (e,p) { + if ( p.method === 'postrefresh' ) { w._sbox_pos(); } + }); + + w.d.headerText = ((w._grabLabel() !== false)?w._grabLabel():w.__('titleDateDialogLabel')); + w.d.intHTML = $('') + + w.fldOrder = w.__('slideFieldOrder'); + w._check(); + w._minStepFix(); + + $('

                          '+w._formatter(w.__('headerFormat'), w.theDate)+'

                          ').appendTo(w.d.intHTML); + + w.d.intHTML.append(ctrl); + + for ( y=0; y', {'class':uid+'slideyear ui-corner-all ui-btn ui-btn-'+thMod+tmp}) + .html(w.theDate.get(0)+i).jqmData('offset', i).jqmData('theme', tmp).appendTo(hRow); + } + break; + case 'm': + phRow.addClass(uid+'sliderow-ym'); + for ( i=o.slen.m*-1; i<(o.slen.m+1); i++ ) { + testDate = w.theDate.copy([0],[0,0,1]); + testDate.adj(1,i); + tmp = (i!==0)?((iDate.get(1) === testDate.get(1) && iDate.get(0) === testDate.get(0))?o.themeDateHigh:o.themeDate):o.themeDatePick; + $('
                          ', {'class':uid+'slidemonth ui-corner-all ui-btn ui-btn-'+thMod+tmp}) + .html(String(w.__('monthsOfYearShort')[testDate.get(1)])) + .jqmData('offset', i) + .jqmData('theme', tmp).appendTo(hRow); + } + break; + + case 'd': + phRow.addClass(uid+'sliderow-d'); + for ( i=o.slen.d*-1; i<(o.slen.d+1); i++ ) { + testDate = w.theDate.copy(); + testDate.adj(2,i); + tmp = (i!==0)?((iDate.comp() === testDate.comp())?o.themeDateHigh:o.themeDate):o.themeDatePick; + if ( ( o.blackDates !== false && $.inArray(testDate.iso(), o.blackDates) > -1 ) || + ( o.blackDays !== false && $.inArray(testDate.getDay(), o.blackDays) > -1 ) ) { + tmp += ' '+uid+'griddate-disable'; + } + $('
                          ', {'class':uid+'slideday ui-corner-all ui-btn ui-btn-'+thMod+tmp}) + .html(testDate.get(2) + '
                          ' + w.__('daysOfWeekShort')[testDate.getDay()] + '') + .jqmData('offset', i).jqmData('theme', tmp).appendTo(hRow); + } + break; + case 'h': + phRow.addClass(uid+'sliderow-hi'); + for ( i=o.slen.h*-1; i<(o.slen.h+1); i++ ) { + testDate = w.theDate.copy(); + testDate.adj(3,i); + tmp = (i!==0)?o.themeDate:o.themeDatePick; + if ( o.validHours !== false && $.inArray(testDate.get(3), o.validHours) < 0 ) { + tmp += ' '+uid+'griddate-disable'; + } + $('
                          ', {'class':uid+'slidehour ui-corner-all ui-btn ui-btn-'+thMod+tmp}) + .html( w.__('timeFormat') === 12 ? w._formatter('%I%p', testDate) : testDate.get(3) ) + .jqmData('offset', i).jqmData('theme', tmp).appendTo(hRow); + } + break; + case 'i': + phRow.addClass(uid+'sliderow-hi'); + for ( i=o.slen.i*-1; i<(o.slen.i+1); i++ ) { + testDate = w.theDate.copy(); + testDate.adj(4,(i*o.minuteStep)); + tmp = (i!==0)?o.themeDate:o.themeDatePick; + $('
                          ', {'class':uid+'slidemins ui-corner-all ui-btn ui-btn-'+thMod+tmp}) + .html(w._zPad(testDate.get(4))).jqmData('offset', i*o.minuteStep).jqmData('theme', tmp).appendTo(hRow); + } + break; + } + phRow.appendTo(ctrl); + } + + if ( o.useSetButton || o.useClearButton ) { + y = $('
                          ', {'class':uid+'controls'}); + + if ( o.useSetButton ) { + $(''+w.__('setDateButtonLabel')+'') + .appendTo(y).buttonMarkup({theme: o.theme, icon: 'check', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + if ( w.dateOK === true ) { + w.d.input.trigger('datebox', {'method':'set', 'value':w._formatter(w.__fmt(),w.theDate), 'date':w.theDate}); + w.d.input.trigger('datebox', {'method':'close'}); + } + }); + } + if ( o.useClearButton ) { + $(''+w.__('clearButton')+'') + .appendTo(y).buttonMarkup({theme: o.theme, icon: 'delete', iconpos: 'left', corners:true, shadow:true}) + .on(o.clickEventAlt, function(e) { + e.preventDefault(); + w.d.input.val(''); + w.d.input.trigger('datebox',{'method':'clear'}); + w.d.input.trigger('datebox',{'method':'close'}); + }); + } + if ( o.useCollapsedBut ) { + y.addClass('ui-datebox-collapse'); + } + y.appendTo(w.d.intHTML); + } + + if ( w.wheelExists ) { // Mousewheel operation, if plugin is loaded + w.d.intHTML.on('mousewheel', '.ui-datebox-sliderow-int', function(e,d) { + e.preventDefault(); + w._offset($(this).jqmData('rowtype'), ((d<0)?-1:1)*($(this).jqmData('rowtype')==='i'?o.minuteStep:1)); + }); + } + + w.d.intHTML.on(o.clickEvent, '.ui-datebox-sliderow-int>div', function(e) { + e.preventDefault(); + w._offset($(this).parent().jqmData('rowtype'), parseInt($(this).jqmData('offset'),10)); + }); + w.d.intHTML.on('vmouseover vmouseout', '.ui-datebox-sliderow-int>div', function() { + w._hoover(this); + }); + + w.d.intHTML.on(w.drag.eStart, '.ui-datebox-sliderow-int', function(e) { + if ( !w.drag.move ) { + w.drag.move = true; + w.drag.target = $(this); + w.drag.pos = parseInt(w.drag.target.css('marginLeft').replace(/px/i, ''),10); + w.drag.start = w.touch ? e.originalEvent.changedTouches[0].pageX : e.pageX; + w.drag.end = false; + e.stopPropagation(); + e.preventDefault(); + } + }); + } + }); + $.extend( $.mobile.datebox.prototype._drag, { + 'slidebox': function() { + var w = this, + o = this.options, + g = this.drag; + + $(document).on(g.eMove, function(e) { + if ( g.move && o.mode === 'slidebox') { + g.end = w.touch ? e.originalEvent.changedTouches[0].pageX : e.pageX; + g.target.css('marginLeft', (g.pos + g.end - g.start) + 'px'); + e.preventDefault(); + e.stopPropagation(); + return false; + } + }); + + $(document).on(g.eEnd, function(e) { + if ( g.move && o.mode === 'slidebox' ) { + g.move = false; + if ( g.end !== false ) { + e.preventDefault(); + e.stopPropagation(); + g.tmp = g.target.find('div').first(); + w._offset(g.target.jqmData('rowtype'), ( w.__('isRTL') ? -1 : 1 )*(parseInt((g.start - g.end) / g.tmp.innerWidth(),10))*(g.target.jqmData('rowtype')==='i'?o.minuteStep:1)); + } + g.start = false; + g.end = false; + } + }); + } + }); +})( jQuery ); diff --git a/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.slidebox.min.js b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.slidebox.min.js new file mode 100644 index 000000000..13802b0db --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/1.1.1/jqm-datebox.mode.slidebox.min.js @@ -0,0 +1,7 @@ +/* + * jQuery Mobile Framework : plugin to provide a date and time picker. + * Copyright (c) JTSage + * CC 3.0 Attribution. May be relicensed without permission/notification. + * https://github.com/jtsage/jquery-mobile-datebox + */ +(function(a){a.extend(a.mobile.datebox.prototype.options,{themeDateHigh:"b",themeDatePick:"b",themeDate:"a",useSetButton:true,validHours:false,slen:{y:5,m:6,d:15,h:12,i:30}});a.extend(a.mobile.datebox.prototype,{_sbox_pos:function(){var b=this,f,e,d,c;b.d.intHTML.find("div.ui-datebox-sliderow-int").each(function(){f=a(this);d=f.parent().innerWidth();if(b.__("isRTL")){e=f.find("div").last()}else{e=f.find("div").first()}c=f.find("div").size()*e.outerWidth();e.css("marginLeft",((c/2)-(d/2))*-1)})}});a.extend(a.mobile.datebox.prototype._build,{slidebox:function(){var p=this,c=this.options,e,l,q,d,f,n,g=(p.d.input.val()==="")?p._startOffset(p._makeDate(p.d.input.val())):p._makeDate(p.d.input.val()),j="ui-datebox-",h=((this.options.mobVer<140)?"up-":""),k=a("
                          "),m=a("
                          "),b=a("
                          ",{"class":j+"slide"});if(typeof p.d.intHTML!=="boolean"){p.d.intHTML.empty().remove()}p.d.input.on("datebox",function(o,i){if(i.method==="postrefresh"){p._sbox_pos()}});p.d.headerText=((p._grabLabel()!==false)?p._grabLabel():p.__("titleDateDialogLabel"));p.d.intHTML=a("");p.fldOrder=p.__("slideFieldOrder");p._check();p._minStepFix();a('

                          '+p._formatter(p.__("headerFormat"),p.theDate)+"

                          ").appendTo(p.d.intHTML);p.d.intHTML.append(b);for(l=0;l",{"class":j+"slideyear ui-corner-all ui-btn ui-btn-"+h+f}).html(p.theDate.get(0)+e).jqmData("offset",e).jqmData("theme",f).appendTo(q)}break;case"m":d.addClass(j+"sliderow-ym");for(e=c.slen.m*-1;e<(c.slen.m+1);e++){n=p.theDate.copy([0],[0,0,1]);n.adj(1,e);f=(e!==0)?((g.get(1)===n.get(1)&&g.get(0)===n.get(0))?c.themeDateHigh:c.themeDate):c.themeDatePick;a("
                          ",{"class":j+"slidemonth ui-corner-all ui-btn ui-btn-"+h+f}).html(String(p.__("monthsOfYearShort")[n.get(1)])).jqmData("offset",e).jqmData("theme",f).appendTo(q)}break;case"d":d.addClass(j+"sliderow-d");for(e=c.slen.d*-1;e<(c.slen.d+1);e++){n=p.theDate.copy();n.adj(2,e);f=(e!==0)?((g.comp()===n.comp())?c.themeDateHigh:c.themeDate):c.themeDatePick;if((c.blackDates!==false&&a.inArray(n.iso(),c.blackDates)>-1)||(c.blackDays!==false&&a.inArray(n.getDay(),c.blackDays)>-1)){f+=" "+j+"griddate-disable"}a("
                          ",{"class":j+"slideday ui-corner-all ui-btn ui-btn-"+h+f}).html(n.get(2)+'
                          '+p.__("daysOfWeekShort")[n.getDay()]+"").jqmData("offset",e).jqmData("theme",f).appendTo(q)}break;case"h":d.addClass(j+"sliderow-hi");for(e=c.slen.h*-1;e<(c.slen.h+1);e++){n=p.theDate.copy();n.adj(3,e);f=(e!==0)?c.themeDate:c.themeDatePick;if(c.validHours!==false&&a.inArray(n.get(3),c.validHours)<0){f+=" "+j+"griddate-disable"}a("
                          ",{"class":j+"slidehour ui-corner-all ui-btn ui-btn-"+h+f}).html(p.__("timeFormat")===12?p._formatter('%I%p',n):n.get(3)).jqmData("offset",e).jqmData("theme",f).appendTo(q)}break;case"i":d.addClass(j+"sliderow-hi");for(e=c.slen.i*-1;e<(c.slen.i+1);e++){n=p.theDate.copy();n.adj(4,(e*c.minuteStep));f=(e!==0)?c.themeDate:c.themeDatePick;a("
                          ",{"class":j+"slidemins ui-corner-all ui-btn ui-btn-"+h+f}).html(p._zPad(n.get(4))).jqmData("offset",e*c.minuteStep).jqmData("theme",f).appendTo(q)}break}d.appendTo(b)}if(c.useSetButton||c.useClearButton){l=a("
                          ",{"class":j+"controls"});if(c.useSetButton){a(''+p.__("setDateButtonLabel")+"").appendTo(l).buttonMarkup({theme:c.theme,icon:"check",iconpos:"left",corners:true,shadow:true}).on(c.clickEventAlt,function(i){i.preventDefault();if(p.dateOK===true){p.d.input.trigger("datebox",{method:"set",value:p._formatter(p.__fmt(),p.theDate),date:p.theDate});p.d.input.trigger("datebox",{method:"close"})}})}if(c.useClearButton){a(''+p.__("clearButton")+"").appendTo(l).buttonMarkup({theme:c.theme,icon:"delete",iconpos:"left",corners:true,shadow:true}).on(c.clickEventAlt,function(i){i.preventDefault();p.d.input.val("");p.d.input.trigger("datebox",{method:"clear"});p.d.input.trigger("datebox",{method:"close"})})}if(c.useCollapsedBut){l.addClass("ui-datebox-collapse")}l.appendTo(p.d.intHTML)}if(p.wheelExists){p.d.intHTML.on("mousewheel",".ui-datebox-sliderow-int",function(i,o){i.preventDefault();p._offset(a(this).jqmData("rowtype"),((o<0)?-1:1)*(a(this).jqmData("rowtype")==="i"?c.minuteStep:1))})}p.d.intHTML.on(c.clickEvent,".ui-datebox-sliderow-int>div",function(i){i.preventDefault();p._offset(a(this).parent().jqmData("rowtype"),parseInt(a(this).jqmData("offset"),10))});p.d.intHTML.on("vmouseover vmouseout",".ui-datebox-sliderow-int>div",function(){p._hoover(this)});p.d.intHTML.on(p.drag.eStart,".ui-datebox-sliderow-int",function(i){if(!p.drag.move){p.drag.move=true;p.drag.target=a(this);p.drag.pos=parseInt(p.drag.target.css("marginLeft").replace(/px/i,""),10);p.drag.start=p.touch?i.originalEvent.changedTouches[0].pageX:i.pageX;p.drag.end=false;i.stopPropagation();i.preventDefault()}})}});a.extend(a.mobile.datebox.prototype._drag,{slidebox:function(){var b=this,d=this.options,c=this.drag;a(document).on(c.eMove,function(f){if(c.move&&d.mode==="slidebox"){c.end=b.touch?f.originalEvent.changedTouches[0].pageX:f.pageX;c.target.css("marginLeft",(c.pos+c.end-c.start)+"px");f.preventDefault();f.stopPropagation();return false}});a(document).on(c.eEnd,function(f){if(c.move&&d.mode==="slidebox"){c.move=false;if(c.end!==false){f.preventDefault();f.stopPropagation();c.tmp=c.target.find("div").first();b._offset(c.target.jqmData("rowtype"),(b.__("isRTL")?-1:1)*(parseInt((c.start-c.end)/c.tmp.innerWidth(),10))*(c.target.jqmData("rowtype")==="i"?d.minuteStep:1))}c.start=false;c.end=false}})}})})(jQuery); \ No newline at end of file diff --git a/ajax/libs/jquery-mobile-datebox/package.json b/ajax/libs/jquery-mobile-datebox/package.json new file mode 100644 index 000000000..6285391a6 --- /dev/null +++ b/ajax/libs/jquery-mobile-datebox/package.json @@ -0,0 +1,10 @@ +{ + "name": "jquery-mobile-datebox", + "description": "A multi-mode date and time picker for jQueryMobile", + "version": "1.1.1", + "homepage": "http://dev.jtsage.com/forums/", + "repositories": [{ + "type": "git", + "url": "git@github.com:jtsage/jquery-mobile-datebox.git" + }] +} \ No newline at end of file From 20c888b66df859bdca4af715a3908e07fa1bad88 Mon Sep 17 00:00:00 2001 From: "marcos@paliari.com.br" Date: Wed, 11 Sep 2013 11:29:00 -0300 Subject: [PATCH 02/26] ajax/libs/jquery-mobile-datebox/package.json valid --- ajax/libs/jquery-mobile-datebox/package.json | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/ajax/libs/jquery-mobile-datebox/package.json b/ajax/libs/jquery-mobile-datebox/package.json index 6285391a6..3e440ee50 100644 --- a/ajax/libs/jquery-mobile-datebox/package.json +++ b/ajax/libs/jquery-mobile-datebox/package.json @@ -1,10 +1,11 @@ { - "name": "jquery-mobile-datebox", - "description": "A multi-mode date and time picker for jQueryMobile", - "version": "1.1.1", - "homepage": "http://dev.jtsage.com/forums/", - "repositories": [{ - "type": "git", - "url": "git@github.com:jtsage/jquery-mobile-datebox.git" - }] + "name": "jquery-mobile-datebox", + "filename": "jqm-datebox.core.min.js", + "description": "A multi-mode date and time picker for jQueryMobile", + "version": "1.1.1", + "homepage": "http://dev.jtsage.com/forums/", + "repositories": [{ + "type": "git", + "url": "git@github.com:jtsage/jquery-mobile-datebox.git" + }] } \ No newline at end of file From 07ef41734a16109263eda0b0a13272b302513615 Mon Sep 17 00:00:00 2001 From: Eric Betts Date: Mon, 30 Sep 2013 19:08:35 -0700 Subject: [PATCH 03/26] Adding skycons.js --- ajax/libs/skycons/0/skycons.min.js | 1 + ajax/libs/skycons/package.json | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+) create mode 100644 ajax/libs/skycons/0/skycons.min.js create mode 100644 ajax/libs/skycons/package.json diff --git a/ajax/libs/skycons/0/skycons.min.js b/ajax/libs/skycons/0/skycons.min.js new file mode 100644 index 000000000..f06d3100e --- /dev/null +++ b/ajax/libs/skycons/0/skycons.min.js @@ -0,0 +1 @@ +var Skycons;(function(global){"use strict";var requestInterval,cancelInterval;(function(){var raf=global.requestAnimationFrame||global.webkitRequestAnimationFrame||global.mozRequestAnimationFrame||global.oRequestAnimationFrame||global.msRequestAnimationFrame,caf=global.cancelAnimationFrame||global.webkitCancelAnimationFrame||global.mozCancelAnimationFrame||global.oCancelAnimationFrame||global.msCancelAnimationFrame;if(raf&&caf){requestInterval=function(fn,delay){var handle={value:null};function loop(){handle.value=raf(loop);fn()}loop();return handle};cancelInterval=function(handle){caf(handle.value)}}else{requestInterval=setInterval;cancelInterval=clearInterval}})();var KEYFRAME=500,STROKE=.08,TWO_PI=2*Math.PI,TWO_OVER_SQRT_2=2/Math.sqrt(2);function circle(ctx,x,y,r){ctx.beginPath();ctx.arc(x,y,r,0,TWO_PI,false);ctx.fill()}function line(ctx,ax,ay,bx,by){ctx.beginPath();ctx.moveTo(ax,ay);ctx.lineTo(bx,by);ctx.stroke()}function puff(ctx,t,cx,cy,rx,ry,rmin,rmax){var c=Math.cos(t*TWO_PI),s=Math.sin(t*TWO_PI);rmax-=rmin;circle(ctx,cx-s*rx,cy+c*ry+rmax*.5,rmin+(1-c*.5)*rmax)}function puffs(ctx,t,cx,cy,rx,ry,rmin,rmax){var i;for(i=5;i--;)puff(ctx,t+i/5,cx,cy,rx,ry,rmin,rmax)}function cloud(ctx,t,cx,cy,cw,s,color){t/=3e4;var a=cw*.21,b=cw*.12,c=cw*.24,d=cw*.28;ctx.fillStyle=color;puffs(ctx,t,cx,cy,a,b,c,d);ctx.globalCompositeOperation="destination-out";puffs(ctx,t,cx,cy,a,b,c-s,d-s);ctx.globalCompositeOperation="source-over"}function sun(ctx,t,cx,cy,cw,s,color){t/=12e4;var a=cw*.25-s*.5,b=cw*.32+s*.5,c=cw*.5-s*.5,i,p,cos,sin;ctx.strokeStyle=color;ctx.lineWidth=s;ctx.lineCap="round";ctx.lineJoin="round";ctx.beginPath();ctx.arc(cx,cy,a,0,TWO_PI,false);ctx.stroke();for(i=8;i--;){p=(t+i/8)*TWO_PI;cos=Math.cos(p);sin=Math.sin(p);line(ctx,cx+cos*b,cy+sin*b,cx+cos*c,cy+sin*c)}}function moon(ctx,t,cx,cy,cw,s,color){t/=15e3;var a=cw*.29-s*.5,b=cw*.05,c=Math.cos(t*TWO_PI),p=c*TWO_PI/-16;ctx.strokeStyle=color;ctx.lineWidth=s;ctx.lineCap="round";ctx.lineJoin="round";cx+=c*b;ctx.beginPath();ctx.arc(cx,cy,a,p+TWO_PI/8,p+TWO_PI*7/8,false);ctx.arc(cx+Math.cos(p)*a*TWO_OVER_SQRT_2,cy+Math.sin(p)*a*TWO_OVER_SQRT_2,a,p+TWO_PI*5/8,p+TWO_PI*3/8,true);ctx.closePath();ctx.stroke()}function rain(ctx,t,cx,cy,cw,s,color){t/=1350;var a=cw*.16,b=TWO_PI*11/12,c=TWO_PI*7/12,i,p,x,y;ctx.fillStyle=color;for(i=4;i--;){p=(t+i/4)%1;x=cx+(i-1.5)/1.5*(i===1||i===2?-1:1)*a;y=cy+p*p*cw;ctx.beginPath();ctx.moveTo(x,y-s*1.5);ctx.arc(x,y,s*.75,b,c,false);ctx.fill()}}function sleet(ctx,t,cx,cy,cw,s,color){t/=750;var a=cw*.1875,b=TWO_PI*11/12,c=TWO_PI*7/12,i,p,x,y;ctx.strokeStyle=color;ctx.lineWidth=s*.5;ctx.lineCap="round";ctx.lineJoin="round";for(i=4;i--;){p=(t+i/4)%1;x=Math.floor(cx+(i-1.5)/1.5*(i===1||i===2?-1:1)*a)+.5;y=cy+p*cw;line(ctx,x,y-s*1.5,x,y+s*1.5)}}function snow(ctx,t,cx,cy,cw,s,color){t/=3e3;var a=cw*.16,b=s*.75,u=t*TWO_PI*.7,ux=Math.cos(u)*b,uy=Math.sin(u)*b,v=u+TWO_PI/3,vx=Math.cos(v)*b,vy=Math.sin(v)*b,w=u+TWO_PI*2/3,wx=Math.cos(w)*b,wy=Math.sin(w)*b,i,p,x,y;ctx.strokeStyle=color;ctx.lineWidth=s*.5;ctx.lineCap="round";ctx.lineJoin="round";for(i=4;i--;){p=(t+i/4)%1;x=cx+Math.sin((p+i/4)*TWO_PI)*a;y=cy+p*cw;line(ctx,x-ux,y-uy,x+ux,y+uy);line(ctx,x-vx,y-vy,x+vx,y+vy);line(ctx,x-wx,y-wy,x+wx,y+wy)}}function fogbank(ctx,t,cx,cy,cw,s,color){t/=3e4;var a=cw*.21,b=cw*.06,c=cw*.21,d=cw*.28;ctx.fillStyle=color;puffs(ctx,t,cx,cy,a,b,c,d);ctx.globalCompositeOperation="destination-out";puffs(ctx,t,cx,cy,a,b,c-s,d-s);ctx.globalCompositeOperation="source-over"}var WIND_PATHS=[[-.75,-.18,-.7219,-.1527,-.6971,-.1225,-.6739,-.091,-.6516,-.0588,-.6298,-.0262,-.6083,.0065,-.5868,.0396,-.5643,.0731,-.5372,.1041,-.5033,.1259,-.4662,.1406,-.4275,.1493,-.3881,.153,-.3487,.1526,-.3095,.1488,-.2708,.1421,-.2319,.1342,-.1943,.1217,-.16,.1025,-.129,.0785,-.1012,.0509,-.0764,.0206,-.0547,-.012,-.0378,-.0472,-.0324,-.0857,-.0389,-.1241,-.0546,-.1599,-.0814,-.1876,-.1193,-.1964,-.1582,-.1935,-.1931,-.1769,-.2157,-.1453,-.229,-.1085,-.2327,-.0697,-.224,-.0317,-.2064,.0033,-.1853,.0362,-.1613,.0672,-.135,.0961,-.1051,.1213,-.0706,.1397,-.0332,.1512,.0053,.158,.0442,.1624,.0833,.1636,.1224,.1615,.1613,.1565,.1999,.15,.2378,.1402,.2749,.1279,.3118,.1147,.3487,.1015,.3858,.0892,.4236,.0787,.4621,.0715,.5012,.0702,.5398,.0766,.5768,.089,.6123,.1055,.6466,.1244,.6805,.144,.7147,.163,.75,.18],[-.75,0,-.7033,.0195,-.6569,.0399,-.6104,.06,-.5634,.0789,-.5155,.0954,-.4667,.1089,-.4174,.1206,-.3676,.1299,-.3174,.1365,-.2669,.1398,-.2162,.1391,-.1658,.1347,-.1157,.1271,-.0661,.1169,-.017,.1046,.0316,.0903,.0791,.0728,.1259,.0534,.1723,.0331,.2188,.0129,.2656,-.0064,.3122,-.0263,.3586,-.0466,.4052,-.0665,.4525,-.0847,.5007,-.1002,.5497,-.113,.5991,-.124,.6491,-.1325,.6994,-.138,.75,-.14]],WIND_OFFSETS=[{start:.36,end:.11},{start:.56,end:.16}];function leaf(ctx,t,x,y,cw,s,color){var a=cw/8,b=a/3,c=2*b,d=t%1*TWO_PI,e=Math.cos(d),f=Math.sin(d);ctx.fillStyle=color;ctx.strokeStyle=color;ctx.lineWidth=s;ctx.lineCap="round";ctx.lineJoin="round";ctx.beginPath();ctx.arc(x,y,a,d,d+Math.PI,false);ctx.arc(x-b*e,y-b*f,c,d+Math.PI,d,false);ctx.arc(x+c*e,y+c*f,b,d+Math.PI,d,true);ctx.globalCompositeOperation="destination-out";ctx.fill();ctx.globalCompositeOperation="source-over";ctx.stroke()}function swoosh(ctx,t,cx,cy,cw,s,index,total,color){t/=2500;var path=WIND_PATHS[index],a=(t+index-WIND_OFFSETS[index].start)%total,c=(t+index-WIND_OFFSETS[index].end)%total,e=(t+index)%total,b,d,f,i;ctx.strokeStyle=color;ctx.lineWidth=s;ctx.lineCap="round";ctx.lineJoin="round";if(a<1){ctx.beginPath();a*=path.length/2-1;b=Math.floor(a);a-=b;b*=2;b+=2;ctx.moveTo(cx+(path[b-2]*(1-a)+path[b]*a)*cw,cy+(path[b-1]*(1-a)+path[b+1]*a)*cw);if(c<1){c*=path.length/2-1;d=Math.floor(c);c-=d;d*=2;d+=2;for(i=b;i!==d;i+=2)ctx.lineTo(cx+path[i]*cw,cy+path[i+1]*cw);ctx.lineTo(cx+(path[d-2]*(1-c)+path[d]*c)*cw,cy+(path[d-1]*(1-c)+path[d+1]*c)*cw)}else for(i=b;i!==path.length;i+=2)ctx.lineTo(cx+path[i]*cw,cy+path[i+1]*cw);ctx.stroke()}else if(c<1){ctx.beginPath();c*=path.length/2-1;d=Math.floor(c);c-=d;d*=2;d+=2;ctx.moveTo(cx+path[0]*cw,cy+path[1]*cw);for(i=2;i!==d;i+=2)ctx.lineTo(cx+path[i]*cw,cy+path[i+1]*cw);ctx.lineTo(cx+(path[d-2]*(1-c)+path[d]*c)*cw,cy+(path[d-1]*(1-c)+path[d+1]*c)*cw);ctx.stroke()}if(e<1){e*=path.length/2-1;f=Math.floor(e);e-=f;f*=2;f+=2;leaf(ctx,t,cx+(path[f-2]*(1-e)+path[f]*e)*cw,cy+(path[f-1]*(1-e)+path[f+1]*e)*cw,cw,s,color)}}Skycons=function(opts){this.list=[];this.interval=null;this.color=opts&&opts.color?opts.color:"black";this.resizeClear=!!(opts&&opts.resizeClear)};Skycons.CLEAR_DAY=function(ctx,t,color){var w=ctx.canvas.width,h=ctx.canvas.height,s=Math.min(w,h);sun(ctx,t,w*.5,h*.5,s,s*STROKE,color)};Skycons.CLEAR_NIGHT=function(ctx,t,color){var w=ctx.canvas.width,h=ctx.canvas.height,s=Math.min(w,h);moon(ctx,t,w*.5,h*.5,s,s*STROKE,color)};Skycons.PARTLY_CLOUDY_DAY=function(ctx,t,color){var w=ctx.canvas.width,h=ctx.canvas.height,s=Math.min(w,h);sun(ctx,t,w*.625,h*.375,s*.75,s*STROKE,color);cloud(ctx,t,w*.375,h*.625,s*.75,s*STROKE,color)};Skycons.PARTLY_CLOUDY_NIGHT=function(ctx,t,color){var w=ctx.canvas.width,h=ctx.canvas.height,s=Math.min(w,h);moon(ctx,t,w*.667,h*.375,s*.75,s*STROKE,color);cloud(ctx,t,w*.375,h*.625,s*.75,s*STROKE,color)};Skycons.CLOUDY=function(ctx,t,color){var w=ctx.canvas.width,h=ctx.canvas.height,s=Math.min(w,h);cloud(ctx,t,w*.5,h*.5,s,s*STROKE,color)};Skycons.RAIN=function(ctx,t,color){var w=ctx.canvas.width,h=ctx.canvas.height,s=Math.min(w,h);rain(ctx,t,w*.5,h*.37,s*.9,s*STROKE,color);cloud(ctx,t,w*.5,h*.37,s*.9,s*STROKE,color)};Skycons.SLEET=function(ctx,t,color){var w=ctx.canvas.width,h=ctx.canvas.height,s=Math.min(w,h);sleet(ctx,t,w*.5,h*.37,s*.9,s*STROKE,color);cloud(ctx,t,w*.5,h*.37,s*.9,s*STROKE,color)};Skycons.SNOW=function(ctx,t,color){var w=ctx.canvas.width,h=ctx.canvas.height,s=Math.min(w,h);snow(ctx,t,w*.5,h*.37,s*.9,s*STROKE,color);cloud(ctx,t,w*.5,h*.37,s*.9,s*STROKE,color)};Skycons.WIND=function(ctx,t,color){var w=ctx.canvas.width,h=ctx.canvas.height,s=Math.min(w,h);swoosh(ctx,t,w*.5,h*.5,s,s*STROKE,0,2,color);swoosh(ctx,t,w*.5,h*.5,s,s*STROKE,1,2,color)};Skycons.FOG=function(ctx,t,color){var w=ctx.canvas.width,h=ctx.canvas.height,s=Math.min(w,h),k=s*STROKE;fogbank(ctx,t,w*.5,h*.32,s*.75,k,color);t/=5e3;var a=Math.cos(t*TWO_PI)*s*.02,b=Math.cos((t+.25)*TWO_PI)*s*.02,c=Math.cos((t+.5)*TWO_PI)*s*.02,d=Math.cos((t+.75)*TWO_PI)*s*.02,n=h*.936,e=Math.floor(n-k*.5)+.5,f=Math.floor(n-k*2.5)+.5;ctx.strokeStyle=color;ctx.lineWidth=k;ctx.lineCap="round";ctx.lineJoin="round";line(ctx,a+w*.2+k*.5,e,b+w*.8-k*.5,e);line(ctx,c+w*.2+k*.5,f,d+w*.8-k*.5,f)};Skycons.prototype={add:function(el,draw){var obj;if(typeof el==="string")el=document.getElementById(el);obj={element:el,context:el.getContext("2d"),drawing:draw};this.list.push(obj);this.draw(obj,KEYFRAME)},set:function(el,draw){var i;if(typeof el==="string")el=document.getElementById(el);for(i=this.list.length;i--;)if(this.list[i].element===el){this.list[i].drawing=draw;this.draw(this.list[i],KEYFRAME);return}this.add(el,draw)},remove:function(el){var i;if(typeof el==="string")el=document.getElementById(el);for(i=this.list.length;i--;)if(this.list[i].element===el){this.list.splice(i,1);return}},draw:function(obj,time){var canvas=obj.context.canvas;if(this.resizeClear)canvas.width=canvas.width;else obj.context.clearRect(0,0,canvas.width,canvas.height);obj.drawing(obj.context,time,this.color)},play:function(){var self=this;this.pause();this.interval=requestInterval(function(){var now=Date.now(),i;for(i=self.list.length;i--;)self.draw(self.list[i],now)},1e3/60)},pause:function(){var i;if(this.interval){cancelInterval(this.interval);this.interval=null}}}})(this); \ No newline at end of file diff --git a/ajax/libs/skycons/package.json b/ajax/libs/skycons/package.json new file mode 100644 index 000000000..998e44484 --- /dev/null +++ b/ajax/libs/skycons/package.json @@ -0,0 +1,22 @@ +{ + "name": "skycons", + "filename": "skycons.min.js", + "version": "0", + "description": "A public domain library of animated weather icons rendered using javascript", + "keywords": [ + "weather", + "forecast", + "animation", + "canvas" + ], + "homepage": "http://darkskyapp.github.io/skycons/", + "author": { + "name": "The Dark Sky Company, LLC", + "email": "support@forecast.io", + "url": "http://forecast.io/" + }, + "repository": { + "type": "git", + "url": "http://github.com/darkskyapp/skycons.git" + } +} From 24305adf333ce3ceb3fcd2ad01b3b0cb651aed05 Mon Sep 17 00:00:00 2001 From: Salvatore Garbesi Date: Thu, 10 Oct 2013 04:10:23 -0400 Subject: [PATCH 04/26] Adding Fallback library. --- ajax/libs/fallback/1.0.5/fallback.js | 265 +++++++++++++++++++++++ ajax/libs/fallback/1.0.5/fallback.min.js | 6 + ajax/libs/fallback/package.json | 31 +++ 3 files changed, 302 insertions(+) create mode 100644 ajax/libs/fallback/1.0.5/fallback.js create mode 100644 ajax/libs/fallback/1.0.5/fallback.min.js create mode 100644 ajax/libs/fallback/package.json diff --git a/ajax/libs/fallback/1.0.5/fallback.js b/ajax/libs/fallback/1.0.5/fallback.js new file mode 100644 index 000000000..916b0c617 --- /dev/null +++ b/ajax/libs/fallback/1.0.5/fallback.js @@ -0,0 +1,265 @@ +/* fallback.js v1.0.5 | https://github.com/dolox/fallback/ | Salvatore Garbesi | (c) 2013 Dolox Inc. */ + +(function(window) { + 'use strict'; + + var fallback = { + callback: null, + callbacks: [], + + head: document.getElementsByTagName('head')[0], + + libraries: {}, + libraries_count: 0, + + loaded: {}, + loaded_count: 0, + + fail: {}, + fail_count: 0, + + shim: {} + }; + + fallback.is_array = function(variable) { + if (variable instanceof Array) { + return true; + } + + return false; + }; + + fallback.is_defined = function(variable) { + /* jslint evil: true */ + if (eval('window.' + variable)) { + return true; + } + + return false; + }; + + fallback.is_function = function(variable) { + if (({}).toString.call(variable) === '[object Function]') { + return true; + } + + return false; + }; + + fallback.is_object = function(variable) { + if (typeof variable === 'object') { + return true; + } + + return false; + }; + + fallback.index_of = function(object, value) { + var index; + + for (index in object) { + if (object[index] === value) { + return index; + } + } + + return -1; + }; + + fallback.initialize = function() { + var library, urls; + + for (library in this.libraries) { + if (this.libraries[library]) { + urls = this.libraries[library]; + + if (!this.is_array(urls)) { + this.libraries[library] = urls = [urls]; + } + + this.libraries_count++; + + if (!this.shim[library]) { + this.spawn(library, urls[0], 0); + } + } + } + }; + + fallback.completed = function() { + this.ready_invocation(); + + if (this.libraries_count === this.loaded_count + this.fail_count) { + if (this.is_function(this.callback)) { + this.callback(this.loaded, this.fail); + } + + this.callback = null; + } + }; + + fallback.error = function(library, index) { + index = parseInt(index,0); + + if (!this.fail[library]) { + this.fail[library] = []; + } + + this.fail[library][this.fail[library].length] = this.libraries[library][index]; + + if (index < this.libraries[library].length - 1) { + this.spawn(library, this.libraries[library][index + 1], index + 1); + } else { + this.fail_count++; + } + + this.completed(); + }; + + fallback.load = function(libraries, options, callback) { + if (this.is_function(options)) { + callback = options; + options = {}; + } + + if (!this.is_object(options)) { + options = {}; + } + + if (options.shim) { + this.shim = options.shim; + } + + if (!this.is_function(callback)) { + callback = function() {}; + } + + this.callback = callback; + this.libraries = libraries; + this.initialize(); + }; + + fallback.ready = function(libraries, callback) { + var options = { + callback: callback, + libraries: libraries + }; + + if (!this.is_array(libraries)) { + options.callback = libraries; + options.libraries = []; + } + + this.callbacks[this.callbacks.length] = options; + this.ready_invocation(); + }; + + fallback.ready_invocation = function() { + var index, options, count, library, wipe; + + for (index in this.callbacks) { + if (this.is_object(this.callbacks[index])) { + options = this.callbacks[index]; + wipe = false; + + if (options.libraries.length > 0) { + count = 0; + + for (library in this.loaded) { + if (this.index_of(options.libraries, library) >= 0) { + count++; + } + } + + if (count === options.libraries.length) { + options.callback(); + wipe = true; + } + } else if (this.libraries_count === this.loaded_count + this.fail_count) { + options.callback(this.loaded, this.fail); + wipe = true; + } + + if (wipe) { + delete this.callbacks[index]; + } + } + } + }; + + fallback.spawn = function(library, url, index) { + var element; + + if (this.is_defined(library)) { + return fallback.success(library, index); + } + + if (url.indexOf('.css') > -1) { + element = document.createElement('link'); + element.rel = 'stylesheet'; + element.href = url; + } else { + element = document.createElement('script'); + element.src = url; + } + + element.onload = function() { + fallback.success(library, index); + }; + + element.onreadystatechange = function() { + if (!this.readyState || this.readyState === 'loaded' || this.readyState === 'complete') { + this.onreadystatechange = null; + + if (!fallback.is_defined(library)) { + fallback.error(library, index); + } else { + fallback.success(library, index); + } + } + }; + + element.onerror = function() { + fallback.error(library, index); + }; + + this.head.appendChild(element); + }; + + fallback.success = function(library, index) { + this.loaded[library] = this.libraries[library][index]; + this.loaded_count++; + + if (this.shim) { + this.shim_invocation(library); + } + + this.completed(); + }; + + fallback.shim_invocation = function() { + var count, index, shim, shimming; + + for (shim in this.shim) { + if (this.shim[shim]) { + shimming = this.shim[shim]; + count = 0; + + if (!this.loaded[shim]) { + for (index in shimming) { + if (this.loaded[shimming[index]]) { + count++; + } + } + + if (count === shimming.length) { + this.spawn(shim, this.libraries[shim][0], 0); + delete this.shim[shim]; + } + } + } + } + }; + + window.fallback = fallback; +})(window); \ No newline at end of file diff --git a/ajax/libs/fallback/1.0.5/fallback.min.js b/ajax/libs/fallback/1.0.5/fallback.min.js new file mode 100644 index 000000000..65b39ad2c --- /dev/null +++ b/ajax/libs/fallback/1.0.5/fallback.min.js @@ -0,0 +1,6 @@ +/* fallback.js v1.0.5 | https://github.com/dolox/fallback/ | Salvatore Garbesi | (c) 2013 Dolox Inc. */ +(function(f){var e={b:null,c:[],head:document.getElementsByTagName("head")[0],a:{},g:0,loaded:{},h:0,d:{},e:0,shim:{},l:function(a){return a instanceof Array?!0:!1},m:function(a){return eval("window."+a)?!0:!1},f:function(a){return"[object Function]"==={}.toString.call(a)?!0:!1},n:function(a){return"object"===typeof a?!0:!1},p:function(a,b){for(var c in a)if(a[c]===b)return c;return-1},q:function(){var a,b;for(a in this.a)this.a[a]&&(b=this.a[a],this.l(b)||(this.a[a]=b=[b]),this.g++,this.shim[a]|| +this.i(a,b[0],0))},k:function(){this.o();this.g===this.h+this.e&&(this.f(this.b)&&this.b(this.loaded,this.d),this.b=null)},error:function(a,b){b=parseInt(b,0);this.d[a]||(this.d[a]=[]);this.d[a][this.d[a].length]=this.a[a][b];b Date: Thu, 10 Oct 2013 11:54:21 -0400 Subject: [PATCH 05/26] Update stacktrace.js to 0.5.3 --- ajax/libs/stacktrace.js/0.5.3/stacktrace.js | 450 ++++++++++++++++++ .../stacktrace.js/0.5.3/stacktrace.min.js | 11 + 2 files changed, 461 insertions(+) create mode 100644 ajax/libs/stacktrace.js/0.5.3/stacktrace.js create mode 100644 ajax/libs/stacktrace.js/0.5.3/stacktrace.min.js diff --git a/ajax/libs/stacktrace.js/0.5.3/stacktrace.js b/ajax/libs/stacktrace.js/0.5.3/stacktrace.js new file mode 100644 index 000000000..8cacb4b69 --- /dev/null +++ b/ajax/libs/stacktrace.js/0.5.3/stacktrace.js @@ -0,0 +1,450 @@ +// Domain Public by Eric Wendelin http://eriwen.com/ (2008) +// Luke Smith http://lucassmith.name/ (2008) +// Loic Dachary (2008) +// Johan Euphrosine (2008) +// Oyvind Sean Kinsey http://kinsey.no/blog (2010) +// Victor Homyakov (2010) + +/** + * Main function giving a function stack trace with a forced or passed in Error + * + * @cfg {Error} e The error to create a stacktrace from (optional) + * @cfg {Boolean} guess If we should try to resolve the names of anonymous functions + * @return {Array} of Strings with functions, lines, files, and arguments where possible + */ +function printStackTrace(options) { + options = options || {guess: true}; + var ex = options.e || null, guess = !!options.guess; + var p = new printStackTrace.implementation(), result = p.run(ex); + return (guess) ? p.guessAnonymousFunctions(result) : result; +} + +if (typeof module !== "undefined" && module.exports) { + module.exports = printStackTrace; +} + +printStackTrace.implementation = function() { +}; + +printStackTrace.implementation.prototype = { + /** + * @param {Error} ex The error to create a stacktrace from (optional) + * @param {String} mode Forced mode (optional, mostly for unit tests) + */ + run: function(ex, mode) { + ex = ex || this.createException(); + // examine exception properties w/o debugger + //for (var prop in ex) {alert("Ex['" + prop + "']=" + ex[prop]);} + mode = mode || this.mode(ex); + if (mode === 'other') { + return this.other(arguments.callee); + } else { + return this[mode](ex); + } + }, + + createException: function() { + try { + this.undef(); + } catch (e) { + return e; + } + }, + + /** + * Mode could differ for different exception, e.g. + * exceptions in Chrome may or may not have arguments or stack. + * + * @return {String} mode of operation for the exception + */ + mode: function(e) { + if (e['arguments'] && e.stack) { + return 'chrome'; + } else if (e.stack && e.sourceURL) { + return 'safari'; + } else if (e.stack && e.number) { + return 'ie'; + } else if (typeof e.message === 'string' && typeof window !== 'undefined' && window.opera) { + // e.message.indexOf("Backtrace:") > -1 -> opera + // !e.stacktrace -> opera + if (!e.stacktrace) { + return 'opera9'; // use e.message + } + // 'opera#sourceloc' in e -> opera9, opera10a + if (e.message.indexOf('\n') > -1 && e.message.split('\n').length > e.stacktrace.split('\n').length) { + return 'opera9'; // use e.message + } + // e.stacktrace && !e.stack -> opera10a + if (!e.stack) { + return 'opera10a'; // use e.stacktrace + } + // e.stacktrace && e.stack -> opera10b + if (e.stacktrace.indexOf("called from line") < 0) { + return 'opera10b'; // use e.stacktrace, format differs from 'opera10a' + } + // e.stacktrace && e.stack -> opera11 + return 'opera11'; // use e.stacktrace, format differs from 'opera10a', 'opera10b' + } else if (e.stack && !e.fileName) { + // Chrome 27 does not have e.arguments as earlier versions, + // but still does not have e.fileName as Firefox + return 'chrome'; + } else if (e.stack) { + return 'firefox'; + } + return 'other'; + }, + + /** + * Given a context, function name, and callback function, overwrite it so that it calls + * printStackTrace() first with a callback and then runs the rest of the body. + * + * @param {Object} context of execution (e.g. window) + * @param {String} functionName to instrument + * @param {Function} callback function to call with a stack trace on invocation + */ + instrumentFunction: function(context, functionName, callback) { + context = context || window; + var original = context[functionName]; + context[functionName] = function instrumented() { + callback.call(this, printStackTrace().slice(4)); + return context[functionName]._instrumented.apply(this, arguments); + }; + context[functionName]._instrumented = original; + }, + + /** + * Given a context and function name of a function that has been + * instrumented, revert the function to it's original (non-instrumented) + * state. + * + * @param {Object} context of execution (e.g. window) + * @param {String} functionName to de-instrument + */ + deinstrumentFunction: function(context, functionName) { + if (context[functionName].constructor === Function && + context[functionName]._instrumented && + context[functionName]._instrumented.constructor === Function) { + context[functionName] = context[functionName]._instrumented; + } + }, + + /** + * Given an Error object, return a formatted Array based on Chrome's stack string. + * + * @param e - Error object to inspect + * @return Array of function calls, files and line numbers + */ + chrome: function(e) { + var stack = (e.stack + '\n').replace(/^\S[^\(]+?[\n$]/gm, ''). + replace(/^\s+(at eval )?at\s+/gm, ''). + replace(/^([^\(]+?)([\n$])/gm, '{anonymous}()@$1$2'). + replace(/^Object.\s*\(([^\)]+)\)/gm, '{anonymous}()@$1').split('\n'); + stack.pop(); + return stack; + }, + + /** + * Given an Error object, return a formatted Array based on Safari's stack string. + * + * @param e - Error object to inspect + * @return Array of function calls, files and line numbers + */ + safari: function(e) { + return e.stack.replace(/\[native code\]\n/m, '') + .replace(/^(?=\w+Error\:).*$\n/m, '') + .replace(/^@/gm, '{anonymous}()@') + .split('\n'); + }, + + /** + * Given an Error object, return a formatted Array based on IE's stack string. + * + * @param e - Error object to inspect + * @return Array of function calls, files and line numbers + */ + ie: function(e) { + var lineRE = /^.*at (\w+) \(([^\)]+)\)$/gm; + return e.stack.replace(/at Anonymous function /gm, '{anonymous}()@') + .replace(/^(?=\w+Error\:).*$\n/m, '') + .replace(lineRE, '$1@$2') + .split('\n'); + }, + + /** + * Given an Error object, return a formatted Array based on Firefox's stack string. + * + * @param e - Error object to inspect + * @return Array of function calls, files and line numbers + */ + firefox: function(e) { + return e.stack.replace(/(?:\n@:0)?\s+$/m, '').replace(/^[\(@]/gm, '{anonymous}()@').split('\n'); + }, + + opera11: function(e) { + var ANON = '{anonymous}', lineRE = /^.*line (\d+), column (\d+)(?: in (.+))? in (\S+):$/; + var lines = e.stacktrace.split('\n'), result = []; + + for (var i = 0, len = lines.length; i < len; i += 2) { + var match = lineRE.exec(lines[i]); + if (match) { + var location = match[4] + ':' + match[1] + ':' + match[2]; + var fnName = match[3] || "global code"; + fnName = fnName.replace(//, "$1").replace(//, ANON); + result.push(fnName + '@' + location + ' -- ' + lines[i + 1].replace(/^\s+/, '')); + } + } + + return result; + }, + + opera10b: function(e) { + // "([arguments not available])@file://localhost/G:/js/stacktrace.js:27\n" + + // "printStackTrace([arguments not available])@file://localhost/G:/js/stacktrace.js:18\n" + + // "@file://localhost/G:/js/test/functional/testcase1.html:15" + var lineRE = /^(.*)@(.+):(\d+)$/; + var lines = e.stacktrace.split('\n'), result = []; + + for (var i = 0, len = lines.length; i < len; i++) { + var match = lineRE.exec(lines[i]); + if (match) { + var fnName = match[1]? (match[1] + '()') : "global code"; + result.push(fnName + '@' + match[2] + ':' + match[3]); + } + } + + return result; + }, + + /** + * Given an Error object, return a formatted Array based on Opera 10's stacktrace string. + * + * @param e - Error object to inspect + * @return Array of function calls, files and line numbers + */ + opera10a: function(e) { + // " Line 27 of linked script file://localhost/G:/js/stacktrace.js\n" + // " Line 11 of inline#1 script in file://localhost/G:/js/test/functional/testcase1.html: In function foo\n" + var ANON = '{anonymous}', lineRE = /Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i; + var lines = e.stacktrace.split('\n'), result = []; + + for (var i = 0, len = lines.length; i < len; i += 2) { + var match = lineRE.exec(lines[i]); + if (match) { + var fnName = match[3] || ANON; + result.push(fnName + '()@' + match[2] + ':' + match[1] + ' -- ' + lines[i + 1].replace(/^\s+/, '')); + } + } + + return result; + }, + + // Opera 7.x-9.2x only! + opera9: function(e) { + // " Line 43 of linked script file://localhost/G:/js/stacktrace.js\n" + // " Line 7 of inline#1 script in file://localhost/G:/js/test/functional/testcase1.html\n" + var ANON = '{anonymous}', lineRE = /Line (\d+).*script (?:in )?(\S+)/i; + var lines = e.message.split('\n'), result = []; + + for (var i = 2, len = lines.length; i < len; i += 2) { + var match = lineRE.exec(lines[i]); + if (match) { + result.push(ANON + '()@' + match[2] + ':' + match[1] + ' -- ' + lines[i + 1].replace(/^\s+/, '')); + } + } + + return result; + }, + + // Safari 5-, IE 9-, and others + other: function(curr) { + var ANON = '{anonymous}', fnRE = /function\s*([\w\-$]+)?\s*\(/i, stack = [], fn, args, maxStackSize = 10; + while (curr && curr['arguments'] && stack.length < maxStackSize) { + fn = fnRE.test(curr.toString()) ? RegExp.$1 || ANON : ANON; + args = Array.prototype.slice.call(curr['arguments'] || []); + stack[stack.length] = fn + '(' + this.stringifyArguments(args) + ')'; + curr = curr.caller; + } + return stack; + }, + + /** + * Given arguments array as a String, substituting type names for non-string types. + * + * @param {Arguments,Array} args + * @return {String} stringified arguments + */ + stringifyArguments: function(args) { + var result = []; + var slice = Array.prototype.slice; + for (var i = 0; i < args.length; ++i) { + var arg = args[i]; + if (arg === undefined) { + result[i] = 'undefined'; + } else if (arg === null) { + result[i] = 'null'; + } else if (arg.constructor) { + if (arg.constructor === Array) { + if (arg.length < 3) { + result[i] = '[' + this.stringifyArguments(arg) + ']'; + } else { + result[i] = '[' + this.stringifyArguments(slice.call(arg, 0, 1)) + '...' + this.stringifyArguments(slice.call(arg, -1)) + ']'; + } + } else if (arg.constructor === Object) { + result[i] = '#object'; + } else if (arg.constructor === Function) { + result[i] = '#function'; + } else if (arg.constructor === String) { + result[i] = '"' + arg + '"'; + } else if (arg.constructor === Number) { + result[i] = arg; + } + } + } + return result.join(','); + }, + + sourceCache: {}, + + /** + * @return the text from a given URL + */ + ajax: function(url) { + var req = this.createXMLHTTPObject(); + if (req) { + try { + req.open('GET', url, false); + //req.overrideMimeType('text/plain'); + //req.overrideMimeType('text/javascript'); + req.send(null); + //return req.status == 200 ? req.responseText : ''; + return req.responseText; + } catch (e) { + } + } + return ''; + }, + + /** + * Try XHR methods in order and store XHR factory. + * + * @return XHR function or equivalent + */ + createXMLHTTPObject: function() { + var xmlhttp, XMLHttpFactories = [ + function() { + return new XMLHttpRequest(); + }, function() { + return new ActiveXObject('Msxml2.XMLHTTP'); + }, function() { + return new ActiveXObject('Msxml3.XMLHTTP'); + }, function() { + return new ActiveXObject('Microsoft.XMLHTTP'); + } + ]; + for (var i = 0; i < XMLHttpFactories.length; i++) { + try { + xmlhttp = XMLHttpFactories[i](); + // Use memoization to cache the factory + this.createXMLHTTPObject = XMLHttpFactories[i]; + return xmlhttp; + } catch (e) { + } + } + }, + + /** + * Given a URL, check if it is in the same domain (so we can get the source + * via Ajax). + * + * @param url source url + * @return False if we need a cross-domain request + */ + isSameDomain: function(url) { + return typeof location !== "undefined" && url.indexOf(location.hostname) !== -1; // location may not be defined, e.g. when running from nodejs. + }, + + /** + * Get source code from given URL if in the same domain. + * + * @param url JS source URL + * @return Array of source code lines + */ + getSource: function(url) { + // TODO reuse source from script tags? + if (!(url in this.sourceCache)) { + this.sourceCache[url] = this.ajax(url).split('\n'); + } + return this.sourceCache[url]; + }, + + guessAnonymousFunctions: function(stack) { + for (var i = 0; i < stack.length; ++i) { + var reStack = /\{anonymous\}\(.*\)@(.*)/, + reRef = /^(.*?)(?::(\d+))(?::(\d+))?(?: -- .+)?$/, + frame = stack[i], ref = reStack.exec(frame); + + if (ref) { + var m = reRef.exec(ref[1]); + if (m) { // If falsey, we did not get any file/line information + var file = m[1], lineno = m[2], charno = m[3] || 0; + if (file && this.isSameDomain(file) && lineno) { + var functionName = this.guessAnonymousFunction(file, lineno, charno); + stack[i] = frame.replace('{anonymous}', functionName); + } + } + } + } + return stack; + }, + + guessAnonymousFunction: function(url, lineNo, charNo) { + var ret; + try { + ret = this.findFunctionName(this.getSource(url), lineNo); + } catch (e) { + ret = 'getSource failed with url: ' + url + ', exception: ' + e.toString(); + } + return ret; + }, + + findFunctionName: function(source, lineNo) { + // FIXME findFunctionName fails for compressed source + // (more than one function on the same line) + // function {name}({args}) m[1]=name m[2]=args + var reFunctionDeclaration = /function\s+([^(]*?)\s*\(([^)]*)\)/; + // {name} = function ({args}) TODO args capture + // /['"]?([0-9A-Za-z_]+)['"]?\s*[:=]\s*function(?:[^(]*)/ + var reFunctionExpression = /['"]?([$_A-Za-z][$_A-Za-z0-9]*)['"]?\s*[:=]\s*function\b/; + // {name} = eval() + var reFunctionEvaluation = /['"]?([$_A-Za-z][$_A-Za-z0-9]*)['"]?\s*[:=]\s*(?:eval|new Function)\b/; + // Walk backwards in the source lines until we find + // the line which matches one of the patterns above + var code = "", line, maxLines = Math.min(lineNo, 20), m, commentPos; + for (var i = 0; i < maxLines; ++i) { + // lineNo is 1-based, source[] is 0-based + line = source[lineNo - i - 1]; + commentPos = line.indexOf('//'); + if (commentPos >= 0) { + line = line.substr(0, commentPos); + } + // TODO check other types of comments? Commented code may lead to false positive + if (line) { + code = line + code; + m = reFunctionExpression.exec(code); + if (m && m[1]) { + return m[1]; + } + m = reFunctionDeclaration.exec(code); + if (m && m[1]) { + //return m[1] + "(" + (m[2] || "") + ")"; + return m[1]; + } + m = reFunctionEvaluation.exec(code); + if (m && m[1]) { + return m[1]; + } + } + } + return '(?)'; + } +}; diff --git a/ajax/libs/stacktrace.js/0.5.3/stacktrace.min.js b/ajax/libs/stacktrace.js/0.5.3/stacktrace.min.js new file mode 100644 index 000000000..c54783a67 --- /dev/null +++ b/ajax/libs/stacktrace.js/0.5.3/stacktrace.min.js @@ -0,0 +1,11 @@ +function printStackTrace(a){var a=a||{guess:!0},b=a.e||null,a=!!a.guess,d=new printStackTrace.implementation,b=d.run(b);return a?d.guessAnonymousFunctions(b):b}"undefined"!==typeof module&&module.exports&&(module.exports=printStackTrace);printStackTrace.implementation=function(){}; +printStackTrace.implementation.prototype={run:function(a,b){a=a||this.createException();b=b||this.mode(a);return b==="other"?this.other(arguments.callee):this[b](a)},createException:function(){try{this.undef()}catch(a){return a}},mode:function(a){return a.arguments&&a.stack?"chrome":a.stack&&a.sourceURL?"safari":a.stack&&a.number?"ie":typeof a.message==="string"&&typeof window!=="undefined"&&window.opera?!a.stacktrace||a.message.indexOf("\n")>-1&&a.message.split("\n").length>a.stacktrace.split("\n").length? +"opera9":!a.stack?"opera10a":a.stacktrace.indexOf("called from line")<0?"opera10b":"opera11":a.stack&&!a.fileName?"chrome":a.stack?"firefox":"other"},instrumentFunction:function(a,b,d){var a=a||window,c=a[b];a[b]=function(){d.call(this,printStackTrace().slice(4));return a[b]._instrumented.apply(this,arguments)};a[b]._instrumented=c},deinstrumentFunction:function(a,b){if(a[b].constructor===Function&&a[b]._instrumented&&a[b]._instrumented.constructor===Function)a[b]=a[b]._instrumented},chrome:function(a){a= +(a.stack+"\n").replace(/^\S[^\(]+?[\n$]/gm,"").replace(/^\s+(at eval )?at\s+/gm,"").replace(/^([^\(]+?)([\n$])/gm,"{anonymous}()@$1$2").replace(/^Object.\s*\(([^\)]+)\)/gm,"{anonymous}()@$1").split("\n");a.pop();return a},safari:function(a){return a.stack.replace(/\[native code\]\n/m,"").replace(/^(?=\w+Error\:).*$\n/m,"").replace(/^@/gm,"{anonymous}()@").split("\n")},ie:function(a){return a.stack.replace(/at Anonymous function /gm,"{anonymous}()@").replace(/^(?=\w+Error\:).*$\n/m,"").replace(/^.*at (\w+) \(([^\)]+)\)$/gm, +"$1@$2").split("\n")},firefox:function(a){return a.stack.replace(/(?:\n@:0)?\s+$/m,"").replace(/^[\(@]/gm,"{anonymous}()@").split("\n")},opera11:function(a){for(var b=/^.*line (\d+), column (\d+)(?: in (.+))? in (\S+):$/,a=a.stacktrace.split("\n"),d=[],c=0,f=a.length;c/,"$1").replace(//,"{anonymous}");d.push(e+"@"+g+" -- "+a[c+1].replace(/^\s+/,""))}}return d}, +opera10b:function(a){for(var b=/^(.*)@(.+):(\d+)$/,a=a.stacktrace.split("\n"),d=[],c=0,f=a.length;c=0&&(g=g.substr(0,h));if(g){e=g+e;if((g=c.exec(e))&&g[1])return g[1];if((g=d.exec(e))&&g[1])return g[1];if((g=f.exec(e))&&g[1])return g[1]}}return"(?)"}}; \ No newline at end of file From 1da8a7f8add5ae5fcaf4ba643d696831ef6f7db0 Mon Sep 17 00:00:00 2001 From: Dean Malmgren Date: Thu, 10 Oct 2013 16:55:00 -0500 Subject: [PATCH 06/26] added kinetic.js 4.6.0 --- ajax/libs/kineticjs/4.6.0/kinetic.min.js | 4 ++++ ajax/libs/kineticjs/package.json | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) create mode 100644 ajax/libs/kineticjs/4.6.0/kinetic.min.js diff --git a/ajax/libs/kineticjs/4.6.0/kinetic.min.js b/ajax/libs/kineticjs/4.6.0/kinetic.min.js new file mode 100644 index 000000000..25ed7addf --- /dev/null +++ b/ajax/libs/kineticjs/4.6.0/kinetic.min.js @@ -0,0 +1,4 @@ +/*! KineticJS v4.6.0 2013-08-12 http://www.kineticjs.com by Eric Rowell @ericdrowell - MIT License https://github.com/ericdrowell/KineticJS/wiki/License*/ +var Kinetic={};!function(){Kinetic.version="4.6.0",Kinetic.Filters={},Kinetic.Node=function(a){this._init(a)},Kinetic.Shape=function(a){this.__init(a)},Kinetic.Container=function(a){this.__init(a)},Kinetic.Stage=function(a){this.___init(a)},Kinetic.Layer=function(a){this.___init(a)},Kinetic.Group=function(a){this.___init(a)},Kinetic.Global={stages:[],idCounter:0,ids:{},names:{},shapes:{},listenClickTap:!1,inDblClickWindow:!1,dblClickWindow:400,isDragging:function(){var a=Kinetic.DD;return a?a.isDragging:!1},isDragReady:function(){var a=Kinetic.DD;return a?!!a.node:!1},_addId:function(a,b){void 0!==b&&(this.ids[b]=a)},_removeId:function(a){void 0!==a&&delete this.ids[a]},_addName:function(a,b){void 0!==b&&(void 0===this.names[b]&&(this.names[b]=[]),this.names[b].push(a))},_removeName:function(a,b){if(void 0!==a){var c=this.names[a];if(void 0!==c){for(var d=0;dc;c++)this[c]=a[c];return this},Kinetic.Collection.prototype=[],Kinetic.Collection.prototype.each=function(a){for(var b=0;ba;a++)b.push(this[a]);return b},Kinetic.Collection.toCollection=function(a){var b,c=new Kinetic.Collection,d=a.length;for(b=0;d>b;b++)c.push(a[b]);return c},Kinetic.Collection.mapMethods=function(a){var b,c=a.length;for(b=0;c>b;b++)!function(b){var c=a[b];Kinetic.Collection.prototype[c]=function(){var a,b=this.length;for(args=[].slice.call(arguments),a=0;b>a;a++)this[a][c].apply(this[a],args)}}(b)}}(),function(){Kinetic.Transform=function(){this.m=[1,0,0,1,0,0]},Kinetic.Transform.prototype={translate:function(a,b){this.m[4]+=this.m[0]*a+this.m[2]*b,this.m[5]+=this.m[1]*a+this.m[3]*b},scale:function(a,b){this.m[0]*=a,this.m[1]*=a,this.m[2]*=b,this.m[3]*=b},rotate:function(a){var b=Math.cos(a),c=Math.sin(a),d=this.m[0]*b+this.m[2]*c,e=this.m[1]*b+this.m[3]*c,f=this.m[0]*-c+this.m[2]*b,g=this.m[1]*-c+this.m[3]*b;this.m[0]=d,this.m[1]=e,this.m[2]=f,this.m[3]=g},getTranslation:function(){return{x:this.m[4],y:this.m[5]}},skew:function(a,b){var c=this.m[0]+this.m[2]*b,d=this.m[1]+this.m[3]*b,e=this.m[2]+this.m[0]*a,f=this.m[3]+this.m[1]*a;this.m[0]=c,this.m[1]=d,this.m[2]=e,this.m[3]=f},multiply:function(a){var b=this.m[0]*a.m[0]+this.m[2]*a.m[1],c=this.m[1]*a.m[0]+this.m[3]*a.m[1],d=this.m[0]*a.m[2]+this.m[2]*a.m[3],e=this.m[1]*a.m[2]+this.m[3]*a.m[3],f=this.m[0]*a.m[4]+this.m[2]*a.m[5]+this.m[4],g=this.m[1]*a.m[4]+this.m[3]*a.m[5]+this.m[5];this.m[0]=b,this.m[1]=c,this.m[2]=d,this.m[3]=e,this.m[4]=f,this.m[5]=g},invert:function(){var a=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),b=this.m[3]*a,c=-this.m[1]*a,d=-this.m[2]*a,e=this.m[0]*a,f=a*(this.m[2]*this.m[5]-this.m[3]*this.m[4]),g=a*(this.m[1]*this.m[4]-this.m[0]*this.m[5]);this.m[0]=b,this.m[1]=c,this.m[2]=d,this.m[3]=e,this.m[4]=f,this.m[5]=g},getMatrix:function(){return this.m},setAbsolutePosition:function(a,b){var c=this.m[0],d=this.m[1],e=this.m[2],f=this.m[3],g=this.m[4],h=this.m[5],i=(c*(b-h)-d*(a-g))/(c*f-d*e),j=(a-g-e*i)/c;this.translate(j,i)}}}(),function(){var a="canvas",b="2d",c="[object Array]",d="[object Number]",e="[object String]",f=Math.PI/180,g=180/Math.PI,h="#",i="",j="0",k="Kinetic warning: ",l="Kinetic error: ",m="rgb(",n={aqua:[0,255,255],lime:[0,255,0],silver:[192,192,192],black:[0,0,0],maroon:[128,0,0],teal:[0,128,128],blue:[0,0,255],navy:[0,0,128],white:[255,255,255],fuchsia:[255,0,255],olive:[128,128,0],yellow:[255,255,0],orange:[255,165,0],gray:[128,128,128],purple:[128,0,128],green:[0,128,0],red:[255,0,0],pink:[255,192,203],cyan:[0,255,255],transparent:[255,255,255,0]},o=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;Kinetic.Util={_isElement:function(a){return!(!a||1!=a.nodeType)},_isFunction:function(a){return!!(a&&a.constructor&&a.call&&a.apply)},_isObject:function(a){return!!a&&a.constructor==Object},_isArray:function(a){return Object.prototype.toString.call(a)==c},_isNumber:function(a){return Object.prototype.toString.call(a)==d},_isString:function(a){return Object.prototype.toString.call(a)==e},_hasMethods:function(a){var b,c=[];for(b in a)this._isFunction(a[b])&&c.push(b);return c.length>0},_isInDocument:function(a){for(;a=a.parentNode;)if(a==document)return!0;return!1},_getXY:function(a){if(this._isNumber(a))return{x:a,y:a};if(this._isArray(a)){if(1===a.length){var b=a[0];if(this._isNumber(b))return{x:b,y:b};if(this._isArray(b))return{x:b[0],y:b[1]};if(this._isObject(b))return b}else if(a.length>=2)return{x:a[0],y:a[1]}}else if(this._isObject(a))return a;return null},_getSize:function(a){if(this._isNumber(a))return{width:a,height:a};if(this._isArray(a))if(1===a.length){var b=a[0];if(this._isNumber(b))return{width:b,height:b};if(this._isArray(b)){if(b.length>=4)return{width:b[2],height:b[3]};if(b.length>=2)return{width:b[0],height:b[1]}}else if(this._isObject(b))return b}else{if(a.length>=4)return{width:a[2],height:a[3]};if(a.length>=2)return{width:a[0],height:a[1]}}else if(this._isObject(a))return a;return null},_getPoints:function(a){var b,c,d=[];if(void 0===a)return[];if(c=a.length,this._isArray(a[0])){for(b=0;c>b;b++)d.push({x:a[b][0],y:a[b][1]});return d}if(this._isObject(a[0]))return a;for(b=0;c>b;b+=2)d.push({x:a[b],y:a[b+1]});return d},_getImage:function(c,d){var e,f,g,h;c?this._isElement(c)?d(c):this._isString(c)?(e=new Image,e.onload=function(){d(e)},e.src=c):c.data?(f=document.createElement(a),f.width=c.width,f.height=c.height,g=f.getContext(b),g.putImageData(c,0,0),h=f.toDataURL(),e=new Image,e.onload=function(){d(e)},e.src=h):d(null):d(null)},_rgbToHex:function(a,b,c){return((1<<24)+(a<<16)+(b<<8)+c).toString(16).slice(1)},_hexToRgb:function(a){a=a.replace(h,i);var b=parseInt(a,16);return{r:255&b>>16,g:255&b>>8,b:255&b}},getRandomColor:function(){for(var a=(16777215*Math.random()<<0).toString(16);a.length<6;)a=j+a;return h+a},getRGB:function(a){var b;return a in n?(b=n[a],{r:b[0],g:b[1],b:b[2]}):a[0]===h?this._hexToRgb(a.substring(1)):a.substr(0,4)===m?(b=o.exec(a.replace(/ /g,"")),{r:parseInt(b[1],10),g:parseInt(b[2],10),b:parseInt(b[3],10)}):{r:0,g:0,b:0}},_merge:function(a,b){var c=this._clone(b);for(var d in a)c[d]=this._isObject(a[d])?this._merge(a[d],c[d]):a[d];return c},_clone:function(a){var b={};for(var c in a)b[c]=this._isObject(a[c])?this._clone(a[c]):a[c];return b},_degToRad:function(a){return a*f},_radToDeg:function(a){return a*g},_capitalize:function(a){return a.charAt(0).toUpperCase()+a.slice(1)},error:function(a){throw new Error(l+a)},warn:function(a){window.console&&console.warn&&console.warn(k+a)},extend:function(a,b){for(var c in b.prototype)c in a.prototype||(a.prototype[c]=b.prototype[c])},addMethods:function(a,b){var c;for(c in b)a.prototype[c]=b[c]},_getControlPoints:function(a,b,c,d){var e=a.x,f=a.y,g=b.x,h=b.y,i=c.x,j=c.y,k=Math.sqrt(Math.pow(g-e,2)+Math.pow(h-f,2)),l=Math.sqrt(Math.pow(i-g,2)+Math.pow(j-h,2)),m=d*k/(k+l),n=d*l/(k+l),o=g-m*(i-e),p=h-m*(j-f),q=g+n*(i-e),r=h+n*(j-f);return[{x:o,y:p},{x:q,y:r}]},_expandPoints:function(a,b){var c,d,e=a.length,f=[];for(c=1;e-1>c;c++)d=Kinetic.Util._getControlPoints(a[c-1],a[c],a[c+1],b),f.push(d[0]),f.push(a[c]),f.push(d[1]);return f},_removeLastLetter:function(a){return a.substring(0,a.length-1)}}}(),function(){var a=document.createElement("canvas"),b=a.getContext("2d"),c=window.devicePixelRatio||1,d=b.webkitBackingStorePixelRatio||b.mozBackingStorePixelRatio||b.msBackingStorePixelRatio||b.oBackingStorePixelRatio||b.backingStorePixelRatio||1,e=c/d;Kinetic.Canvas=function(a){this.init(a)},Kinetic.Canvas.prototype={init:function(a){a=a||{};var b=a.width||0,c=a.height||0,d=a.pixelRatio||e,f=a.contextType||"2d";this.pixelRatio=d,this.element=document.createElement("canvas"),this.element.style.padding=0,this.element.style.margin=0,this.element.style.border=0,this.element.style.background="transparent",this.element.style.position="absolute",this.element.style.top=0,this.element.style.left=0,this.context=this.element.getContext(f),this.setSize(b,c)},getElement:function(){return this.element},getContext:function(){return this.context},setWidth:function(a){this.width=this.element.width=a*this.pixelRatio,this.element.style.width=a+"px"},setHeight:function(a){this.height=this.element.height=a*this.pixelRatio,this.element.style.height=a+"px"},getWidth:function(){return this.width},getHeight:function(){return this.height},setSize:function(a,b){this.setWidth(a),this.setHeight(b)},clear:function(a){var b,c,d=this.getContext();a?(b=Kinetic.Util._getXY(a),c=Kinetic.Util._getSize(a),d.clearRect(b.x||0,b.y||0,c.width,c.height)):d.clearRect(0,0,this.getWidth(),this.getHeight())},toDataURL:function(a,b){try{return this.element.toDataURL(a,b)}catch(c){try{return this.element.toDataURL()}catch(d){return Kinetic.Util.warn("Unable to get data URL. "+d.message),""}}},fill:function(a){a.getFillEnabled()&&this._fill(a)},stroke:function(a){a.getStrokeEnabled()&&this._stroke(a)},fillStroke:function(a){var b=a.getFillEnabled();b&&this._fill(a),a.getStrokeEnabled()&&this._stroke(a,a.hasShadow()&&a.hasFill()&&b)},applyShadow:function(a,b){var c=this.context;c.save(),this._applyShadow(a),b(),c.restore(),b()},_applyLineCap:function(a){var b=a.getLineCap();b&&(this.context.lineCap=b)},_applyOpacity:function(a){var b=a.getAbsoluteOpacity();1!==b&&(this.context.globalAlpha=b)},_applyLineJoin:function(a){var b=a.getLineJoin();b&&(this.context.lineJoin=b)},_applyAncestorTransforms:function(a){var b=a.getAbsoluteTransform().getMatrix();this.context.transform(b[0],b[1],b[2],b[3],b[4],b[5])},_clip:function(a){var b=this.getContext(),c=a.getClipX()||0,d=a.getClipY()||0,e=a.getClipWidth(),f=a.getClipHeight();b.save(),this._applyAncestorTransforms(a),b.beginPath(),b.rect(c,d,e,f),b.clip(),b.setTransform(1,0,0,1,0,0)}},Kinetic.SceneCanvas=function(a){Kinetic.Canvas.call(this,a)},Kinetic.SceneCanvas.prototype={setWidth:function(a){var b=this.pixelRatio;Kinetic.Canvas.prototype.setWidth.call(this,a),this.context.scale(b,b)},setHeight:function(a){var b=this.pixelRatio;Kinetic.Canvas.prototype.setHeight.call(this,a),this.context.scale(b,b)},_fillColor:function(a){var b=this.context,c=a.getFill();b.fillStyle=c,a._fillFunc(b)},_fillPattern:function(a){var b=this.context,c=a.getFillPatternImage(),d=a.getFillPatternX(),e=a.getFillPatternY(),f=a.getFillPatternScale(),g=a.getFillPatternRotation(),h=a.getFillPatternOffset(),i=a.getFillPatternRepeat();(d||e)&&b.translate(d||0,e||0),g&&b.rotate(g),f&&b.scale(f.x,f.y),h&&b.translate(-1*h.x,-1*h.y),b.fillStyle=b.createPattern(c,i||"repeat"),b.fill()},_fillLinearGradient:function(a){var b=this.context,c=a.getFillLinearGradientStartPoint(),d=a.getFillLinearGradientEndPoint(),e=a.getFillLinearGradientColorStops(),f=b.createLinearGradient(c.x,c.y,d.x,d.y);if(e){for(var g=0;gc;c++)d=j[c],e=d.split(f),h=e[0],i=e[1]||g,this.eventListeners[h]||(this.eventListeners[h]=[]),this.eventListeners[h].push({name:i,handler:b});return this},off:function(a){var b,c,d,e,g,h=a.split(q),i=h.length;for(b=0;i>b;b++)if(c=h[b],d=c.split(f),e=d[0],g=d[1],e)this.eventListeners[e]&&this._off(e,g);else for(t in this.eventListeners)this._off(t,g);return this},remove:function(){var c=this.getParent();return c&&c.children&&(c.children.splice(this.index,1),c._setChildrenIndices(),delete this.parent),this._clearSelfAndChildrenCache(r),this._clearSelfAndChildrenCache(b),this._clearSelfAndChildrenCache(v),this._clearSelfAndChildrenCache(k),this._clearSelfAndChildrenCache(a),this},destroy:function(){var a=Kinetic.Global;a._removeId(this.getId()),a._removeName(this.getName(),this._id),this.remove()},getAttr:function(a){var b=h+Kinetic.Util._capitalize(a);return Kinetic.Util._isFunction(this[b])?this[b]():this.attrs[a]},getAncestors:function(){for(var a=this.getParent(),b=new Kinetic.Collection;a;)b.push(a),a=a.getParent();return b},setAttr:function(){var a=Array.prototype.slice.call(arguments),b=a[0],c=o+Kinetic.Util._capitalize(b),d=this[c];return a.shift(),Kinetic.Util._isFunction(d)?d.apply(this,a):this.attrs[b]=a[0],this},getAttrs:function(){return this.attrs||{}},setAttrs:function(a){var b,c;if(a)for(b in a)b===e||(c=o+Kinetic.Util._capitalize(b),Kinetic.Util._isFunction(this[c])?this[c](a[b]):this._setAttr(b,a[b]));return this},isListening:function(){return this._getCache(k,this._isListening)},_isListening:function(){var a=this.getListening(),b=this.getParent();return a&&b&&!b.isListening()?!1:a},isVisible:function(){return this._getCache(v,this._isVisible)},_isVisible:function(){var a=this.getVisible(),b=this.getParent();return a&&b&&!b.isVisible()?!1:a},show:function(){return this.setVisible(!0),this},hide:function(){return this.setVisible(!1),this},getZIndex:function(){return this.index||0},getAbsoluteZIndex:function(){function a(i){for(b=[],c=i.length,d=0;c>d;d++)e=i[d],h++,e.nodeType!==p&&(b=b.concat(e.getChildren().toArray())),e._id===g._id&&(d=c);b.length>0&&b[0].getLevel()<=f&&a(b)}var b,c,d,e,f=this.getLevel(),g=this,h=0;return g.nodeType!==u&&a(g.getStage().getChildren()),h},getLevel:function(){for(var a=0,b=this.parent;b;)a++,b=b.parent;return a},setPosition:function(){var a=Kinetic.Util._getXY([].slice.call(arguments));return this.setX(a.x),this.setY(a.y),this},getPosition:function(){return{x:this.getX(),y:this.getY()}},getAbsolutePosition:function(){var a=this.getAbsoluteTransform(),b=this.getOffset();return a.translate(b.x,b.y),a.getTranslation()},setAbsolutePosition:function(){var a,b=Kinetic.Util._getXY([].slice.call(arguments)),c=this._clearTransform();return this.attrs.x=c.x,this.attrs.y=c.y,delete c.x,delete c.y,a=this.getAbsoluteTransform(),a.invert(),a.translate(b.x,b.y),b={x:this.attrs.x+a.getTranslation().x,y:this.attrs.y+a.getTranslation().y},this.setPosition(b.x,b.y),this._setTransform(c),this},_setTransform:function(a){var c;for(c in a)this.attrs[c]=a[c];this._clearCache(s),this._clearSelfAndChildrenCache(b)},_clearTransform:function(){var a={x:this.getX(),y:this.getY(),rotation:this.getRotation(),scaleX:this.getScaleX(),scaleY:this.getScaleY(),offsetX:this.getOffsetX(),offsetY:this.getOffsetY(),skewX:this.getSkewX(),skewY:this.getSkewY()};return this.attrs.x=0,this.attrs.y=0,this.attrs.rotation=0,this.attrs.scaleX=1,this.attrs.scaleY=1,this.attrs.offsetX=0,this.attrs.offsetY=0,this.attrs.skewX=0,this.attrs.skewY=0,this._clearCache(s),this._clearSelfAndChildrenCache(b),a},move:function(){var a=Kinetic.Util._getXY([].slice.call(arguments)),b=this.getX(),c=this.getY();return void 0!==a.x&&(b+=a.x),void 0!==a.y&&(c+=a.y),this.setPosition(b,c),this},_eachAncestorReverse:function(a,b){var c,d,e=[],f=this.getParent();for(b&&e.unshift(this);f;)e.unshift(f),f=f.parent;for(c=e.length,d=0;c>d;d++)a(e[d])},rotate:function(a){return this.setRotation(this.getRotation()+a),this},rotateDeg:function(a){return this.setRotation(this.getRotation()+Kinetic.Util._degToRad(a)),this},moveToTop:function(){var a=this.index;return this.parent.children.splice(a,1),this.parent.children.push(this),this.parent._setChildrenIndices(),!0},moveUp:function(){var a=this.index,b=this.parent.getChildren().length;return b-1>a?(this.parent.children.splice(a,1),this.parent.children.splice(a+1,0,this),this.parent._setChildrenIndices(),!0):!1},moveDown:function(){var a=this.index;return a>0?(this.parent.children.splice(a,1),this.parent.children.splice(a-1,0,this),this.parent._setChildrenIndices(),!0):!1},moveToBottom:function(){var a=this.index;return a>0?(this.parent.children.splice(a,1),this.parent.children.unshift(this),this.parent._setChildrenIndices(),!0):!1},setZIndex:function(a){var b=this.index;return this.parent.children.splice(b,1),this.parent.children.splice(a,0,this),this.parent._setChildrenIndices(),this},getAbsoluteOpacity:function(){return this._getCache(a,this._getAbsoluteOpacity)},_getAbsoluteOpacity:function(){var a=this.getOpacity();return this.getParent()&&(a*=this.getParent().getAbsoluteOpacity()),a},moveTo:function(a){return Kinetic.Node.prototype.remove.call(this),a.add(this),this},toObject:function(){var a,b,c=Kinetic.Util,d={},e=this.getAttrs();d.attrs={};for(a in e)b=e[a],c._isFunction(b)||c._isElement(b)||c._isObject(b)&&c._hasMethods(b)||(d.attrs[a]=b);return d.className=this.getClassName(),d},toJSON:function(){return JSON.stringify(this.toObject())},getParent:function(){return this.parent},getLayer:function(){return this.getParent().getLayer()},getStage:function(){return this._getCache(r,this._getStage)},_getStage:function(){var a=this.getParent();return a?a.getStage():void 0},fire:function(a,b,c){return c?this._fireAndBubble(a,b||{}):this._fire(a,b||{}),this},getAbsoluteTransform:function(){return this._getCache(b,this._getAbsoluteTransform)},_getAbsoluteTransform:function(){var a,b=new Kinetic.Transform;return this._eachAncestorReverse(function(c){a=c.getTransform(),b.multiply(a)},!0),b},_getTransform:function(){var a=new Kinetic.Transform,b=this.getX(),c=this.getY(),d=this.getRotation(),e=this.getScaleX(),f=this.getScaleY(),g=this.getSkewX(),h=this.getSkewY(),i=this.getOffsetX(),j=this.getOffsetY();return(0!==b||0!==c)&&a.translate(b,c),0!==d&&a.rotate(d),(0!==g||0!==h)&&a.skew(g,h),(1!==e||1!==f)&&a.scale(e,f),(0!==i||0!==j)&&a.translate(-1*i,-1*j),a},clone:function(a){var b,c,d,e,f,g=this.getClassName(),h=new Kinetic[g](this.attrs);for(b in this.eventListeners)for(c=this.eventListeners[b],d=c.length,e=0;d>e;e++)f=c[e],f.name.indexOf(j)<0&&(h.eventListeners[b]||(h.eventListeners[b]=[]),h.eventListeners[b].push(f));return h.setAttrs(a),h},toDataURL:function(a){a=a||{};var b=a.mimeType||null,c=a.quality||null,d=this.getStage(),e=a.x||0,f=a.y||0,g=new Kinetic.SceneCanvas({width:a.width||d.getWidth(),height:a.height||d.getHeight(),pixelRatio:1}),h=g.getContext();return h.save(),(e||f)&&h.translate(-1*e,-1*f),this.drawScene(g),h.restore(),g.toDataURL(b,c)},toImage:function(a){Kinetic.Util._getImage(this.toDataURL(a),function(b){a.callback(b)})},setSize:function(){var a=Kinetic.Util._getSize(Array.prototype.slice.call(arguments));return this.setWidth(a.width),this.setHeight(a.height),this},getSize:function(){return{width:this.getWidth(),height:this.getHeight()}},getWidth:function(){return this.attrs.width||0},getHeight:function(){return this.attrs.height||0},getClassName:function(){return this.className||this.nodeType},getType:function(){return this.nodeType},_get:function(a){return this.nodeType===a?[this]:[]},_off:function(a,b){var c,d,e=this.eventListeners[a];for(c=0;cd;d++)e[d].handler.call(this,b)},draw:function(){return this.drawScene(),this.drawHit(),this},shouldDrawHit:function(){return this.isListening()&&this.isVisible()&&!Kinetic.Global.isDragging()},isDraggable:function(){return!1},getTransform:function(){return this._getCache(s,this._getTransform)}}),Kinetic.Node.create=function(a,b){return this._createNode(JSON.parse(a),b)},Kinetic.Node._createNode=function(a,b){var c,d,e,f=Kinetic.Node.prototype.getClassName.call(a),g=a.children;if(b&&(a.attrs.container=b),c=new Kinetic[f](a.attrs),g)for(d=g.length,e=0;d>e;e++)c.add(this._createNode(g[e]));return c},Kinetic.Factory.addGetterSetter(Kinetic.Node,"x",0),Kinetic.Factory.addGetterSetter(Kinetic.Node,"y",0),Kinetic.Factory.addGetterSetter(Kinetic.Node,"opacity",1),Kinetic.Factory.addGetter(Kinetic.Node,"name"),Kinetic.Factory.addGetter(Kinetic.Node,"id"),Kinetic.Factory.addRotationGetterSetter(Kinetic.Node,"rotation",0),Kinetic.Factory.addPointGetterSetter(Kinetic.Node,"scale",1),Kinetic.Factory.addPointGetterSetter(Kinetic.Node,"skew",0),Kinetic.Factory.addPointGetterSetter(Kinetic.Node,"offset",0),Kinetic.Factory.addSetter(Kinetic.Node,"width"),Kinetic.Factory.addSetter(Kinetic.Node,"height"),Kinetic.Factory.addGetterSetter(Kinetic.Node,"listening",!0),Kinetic.Factory.addGetterSetter(Kinetic.Node,"visible",!0),Kinetic.Collection.mapMethods(["on","off","remove","destroy","show","hide","move","rotate","moveToTop","moveUp","moveDown","moveToBottom","moveTo","fire","draw"])}(),function(){function a(a){window.setTimeout(a,1e3/60)}var b=500;Kinetic.Animation=function(a,b){this.func=a,this.setLayers(b),this.id=Kinetic.Animation.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:(new Date).getTime()}},Kinetic.Animation.prototype={setLayers:function(a){var b=[];b=a?a.length>0?a:[a]:[],this.layers=b},getLayers:function(){return this.layers},addLayer:function(a){var b,c,d=this.layers;if(d){for(b=d.length,c=0;b>c;c++)if(d[c]._id===a._id)return!1}else this.layers=[];return this.layers.push(a),!0},isRunning:function(){for(var a=Kinetic.Animation,b=a.animations,c=0;ce;e++)if(c[e].id===b){this.animations.splice(e,1);break}},Kinetic.Animation._runFrames=function(){var a,b,c,d,e,f,g,h,i={},j=this.animations;for(d=0;de;e++)g=b[e],void 0!==g._id&&(i[g._id]=g);c&&c.call(a,a.frame)}for(h in i)i[h].draw()},Kinetic.Animation._animationLoop=function(){var a=this;this.animations.length>0?(this._runFrames(),Kinetic.Animation.requestAnimFrame(function(){a._animationLoop()})):this.animRunning=!1},Kinetic.Animation._handleAnimation=function(){var a=this;this.animRunning||(this.animRunning=!0,a._animationLoop())},RAF=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||a}(),Kinetic.Animation.requestAnimFrame=function(b){var c=Kinetic.DD&&Kinetic.DD.isDragging?a:RAF;c(b)};var c=Kinetic.Node.prototype.moveTo;Kinetic.Node.prototype.moveTo=function(a){c.call(this,a)},Kinetic.Layer.prototype.batchDraw=function(){var a=this;this.batchAnim||(this.batchAnim=new Kinetic.Animation(function(){a.lastBatchDrawTime&&(new Date).getTime()-a.lastBatchDrawTime>b&&a.batchAnim.stop()},this)),this.lastBatchDrawTime=(new Date).getTime(),this.batchAnim.isRunning()||(this.draw(),this.batchAnim.start())},Kinetic.Stage.prototype.batchDraw=function(){this.getChildren().each(function(a){a.batchDraw()})}}(),function(){var a={node:1,duration:1,easing:1,onFinish:1,yoyo:1},b=1,c=2,d=3,e=0;Kinetic.Tween=function(b){var c,d=this,g=b.node,h=g._id,i=b.duration||1,j=b.easing||Kinetic.Easings.Linear,k=!!b.yoyo; +this.node=g,this._id=e++,this.anim=new Kinetic.Animation(function(){d.tween.onEnterFrame()},g.getLayer()||g.getLayers()),this.tween=new f(c,function(a){d._tweenFunc(a)},j,0,1,1e3*i,k),this._addListeners(),Kinetic.Tween.attrs[h]||(Kinetic.Tween.attrs[h]={}),Kinetic.Tween.attrs[h][this._id]||(Kinetic.Tween.attrs[h][this._id]={}),Kinetic.Tween.tweens[h]||(Kinetic.Tween.tweens[h]={});for(c in b)void 0===a[c]&&this._addAttr(c,b[c]);this.reset(),this.onFinish=b.onFinish,this.onReset=b.onReset},Kinetic.Tween.attrs={},Kinetic.Tween.tweens={},Kinetic.Tween.prototype={_addAttr:function(a,b){var c,d,e,f,g,h,i,j=this.node,k=j._id;if(e=Kinetic.Tween.tweens[k][a],e&&delete Kinetic.Tween.attrs[k][e][a],c=j.getAttr(a),Kinetic.Util._isArray(b))for(b=Kinetic.Util._getPoints(b),d=[],g=b.length,f=0;g>f;f++)h=c[f],i=b[f],d.push({x:i.x-h.x,y:i.y-h.y});else d=b-c;Kinetic.Tween.attrs[k][this._id][a]={start:c,diff:d},Kinetic.Tween.tweens[k][a]=this._id},_tweenFunc:function(a){var b,c,d,e,f,g,h,i,j,k=this.node,l=Kinetic.Tween.attrs[k._id][this._id];for(b in l){if(c=l[b],d=c.start,e=c.diff,Kinetic.Util._isArray(d))for(f=[],h=d.length,g=0;h>g;g++)i=d[g],j=e[g],f.push({x:i.x+j.x*a,y:i.y+j.y*a});else f=d+e*a;k.setAttr(b,f)}},_addListeners:function(){var a=this;this.tween.onPlay=function(){a.anim.start()},this.tween.onReverse=function(){a.anim.start()},this.tween.onPause=function(){a.anim.stop()},this.tween.onFinish=function(){a.onFinish&&a.onFinish()},this.tween.onReset=function(){a.onReset&&a.onReset()}},play:function(){return this.tween.play(),this},reverse:function(){return this.tween.reverse(),this},reset:function(){var a=this.node;return this.tween.reset(),(a.getLayer()||a.getLayers()).draw(),this},seek:function(a){var b=this.node;return this.tween.seek(1e3*a),(b.getLayer()||b.getLayers()).draw(),this},pause:function(){return this.tween.pause(),this},finish:function(){var a=this.node;return this.tween.finish(),(a.getLayer()||a.getLayers()).draw(),this},destroy:function(){var a,b=this.node._id,c=this._id,d=Kinetic.Tween.tweens[b];this.pause();for(a in d)delete Kinetic.Tween.tweens[b][a];delete Kinetic.Tween.attrs[b][c]}};var f=function(a,b,c,d,e,f,g){this.prop=a,this.propFunc=b,this.begin=d,this._pos=d,this.duration=f,this._change=0,this.prevPos=0,this.yoyo=g,this._time=0,this._position=0,this._startTime=0,this._finish=0,this.func=c,this._change=e-this.begin,this.pause()};f.prototype={fire:function(a){var b=this[a];b&&b()},setTime:function(a){a>this.duration?this.yoyo?(this._time=this.duration,this.reverse()):this.finish():0>a?this.yoyo?(this._time=0,this.play()):this.reset():(this._time=a,this.update())},getTime:function(){return this._time},setPosition:function(a){this.prevPos=this._pos,this.propFunc(a),this._pos=a},getPosition:function(a){return void 0===a&&(a=this._time),this.func(a,this.begin,this._change,this.duration)},play:function(){this.state=c,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")},reverse:function(){this.state=d,this._time=this.duration-this._time,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onReverse")},seek:function(a){this.pause(),this._time=a,this.update(),this.fire("onSeek")},reset:function(){this.pause(),this._time=0,this.update(),this.fire("onReset")},finish:function(){this.pause(),this._time=this.duration,this.update(),this.fire("onFinish")},update:function(){this.setPosition(this.getPosition(this._time))},onEnterFrame:function(){var a=this.getTimer()-this._startTime;this.state===c?this.setTime(a):this.state===d&&this.setTime(this.duration-a)},pause:function(){this.state=b,this.fire("onPause")},getTimer:function(){return(new Date).getTime()}},Kinetic.Easings={BackEaseIn:function(a,b,c,d){var e=1.70158;return c*(a/=d)*a*((e+1)*a-e)+b},BackEaseOut:function(a,b,c,d){var e=1.70158;return c*((a=a/d-1)*a*((e+1)*a+e)+1)+b},BackEaseInOut:function(a,b,c,d){var e=1.70158;return(a/=d/2)<1?c/2*a*a*(((e*=1.525)+1)*a-e)+b:c/2*((a-=2)*a*(((e*=1.525)+1)*a+e)+2)+b},ElasticEaseIn:function(a,b,c,d,e,f){var g=0;return 0===a?b:1==(a/=d)?b+c:(f||(f=.3*d),!e||ea?-.5*e*Math.pow(2,10*(a-=1))*Math.sin((a*d-g)*2*Math.PI/f)+b:.5*e*Math.pow(2,-10*(a-=1))*Math.sin((a*d-g)*2*Math.PI/f)+c+b)},BounceEaseOut:function(a,b,c,d){return(a/=d)<1/2.75?c*7.5625*a*a+b:2/2.75>a?c*(7.5625*(a-=1.5/2.75)*a+.75)+b:2.5/2.75>a?c*(7.5625*(a-=2.25/2.75)*a+.9375)+b:c*(7.5625*(a-=2.625/2.75)*a+.984375)+b},BounceEaseIn:function(a,b,c,d){return c-Kinetic.Easings.BounceEaseOut(d-a,0,c,d)+b},BounceEaseInOut:function(a,b,c,d){return d/2>a?.5*Kinetic.Easings.BounceEaseIn(2*a,0,c,d)+b:.5*Kinetic.Easings.BounceEaseOut(2*a-d,0,c,d)+.5*c+b},EaseIn:function(a,b,c,d){return c*(a/=d)*a+b},EaseOut:function(a,b,c,d){return-c*(a/=d)*(a-2)+b},EaseInOut:function(a,b,c,d){return(a/=d/2)<1?c/2*a*a+b:-c/2*(--a*(a-2)-1)+b},StrongEaseIn:function(a,b,c,d){return c*(a/=d)*a*a*a*a+b},StrongEaseOut:function(a,b,c,d){return c*((a=a/d-1)*a*a*a*a+1)+b},StrongEaseInOut:function(a,b,c,d){return(a/=d/2)<1?c/2*a*a*a*a*a+b:c/2*((a-=2)*a*a*a*a+2)+b},Linear:function(a,b,c,d){return c*a/d+b}}}(),function(){Kinetic.DD={anim:new Kinetic.Animation,isDragging:!1,offset:{x:0,y:0},node:null,_drag:function(a){var b=Kinetic.DD,c=b.node;c&&(c._setDragPosition(a),b.isDragging||(b.isDragging=!0,c.fire("dragstart",a,!0)),c.fire("dragmove",a,!0))},_endDragBefore:function(a){var b,c,d=Kinetic.DD,e=Kinetic.Global,f=d.node;f&&(b=f.nodeType,c=f.getLayer(),d.anim.stop(),d.isDragging&&(d.isDragging=!1,e.listenClickTap=!1,a&&(a.dragEndNode=f)),delete d.node,(c||f).draw())},_endDragAfter:function(a){a=a||{};var b=a.dragEndNode;a&&b&&b.fire("dragend",a,!0)}},Kinetic.Node.prototype.startDrag=function(){var a=Kinetic.DD,b=this.getStage(),c=this.getLayer(),d=b.getPointerPosition(),e=this.getAbsolutePosition();d&&(a.node&&a.node.stopDrag(),a.node=this,a.offset.x=d.x-e.x,a.offset.y=d.y-e.y,a.anim.setLayers(c||this.getLayers()),a.anim.start(),this._setDragPosition())},Kinetic.Node.prototype._setDragPosition=function(a){var b=Kinetic.DD;pos=this.getStage().getPointerPosition(),dbf=this.getDragBoundFunc(),newNodePos={x:pos.x-b.offset.x,y:pos.y-b.offset.y},void 0!==dbf&&(newNodePos=dbf.call(this,newNodePos,a)),this.setAbsolutePosition(newNodePos)},Kinetic.Node.prototype.stopDrag=function(){var a=Kinetic.DD,b={};a._endDragBefore(b),a._endDragAfter(b)},Kinetic.Node.prototype.setDraggable=function(a){this._setAttr("draggable",a),this._dragChange()};var a=Kinetic.Node.prototype.destroy;Kinetic.Node.prototype.destroy=function(){var b=Kinetic.DD;b.node&&b.node._id===this._id&&this.stopDrag(),a.call(this)},Kinetic.Node.prototype.isDragging=function(){var a=Kinetic.DD;return a.node&&a.node._id===this._id&&a.isDragging},Kinetic.Node.prototype._listenDrag=function(){this._dragCleanup();var a=this;this.on("mousedown.kinetic touchstart.kinetic",function(b){Kinetic.DD.node||a.startDrag(b)})},Kinetic.Node.prototype._dragChange=function(){if(this.attrs.draggable)this._listenDrag();else{this._dragCleanup();var a=this.getStage(),b=Kinetic.DD;a&&b.node&&b.node._id===this._id&&b.node.stopDrag()}},Kinetic.Node.prototype._dragCleanup=function(){this.off("mousedown.kinetic"),this.off("touchstart.kinetic")},Kinetic.Factory.addGetterSetter(Kinetic.Node,"dragBoundFunc"),Kinetic.Factory.addGetter(Kinetic.Node,"draggable",!1),Kinetic.Node.prototype.isDraggable=Kinetic.Node.prototype.getDraggable;var b=document.getElementsByTagName("html")[0];b.addEventListener("mouseup",Kinetic.DD._endDragBefore,!0),b.addEventListener("touchend",Kinetic.DD._endDragBefore,!0),b.addEventListener("mouseup",Kinetic.DD._endDragAfter,!1),b.addEventListener("touchend",Kinetic.DD._endDragAfter,!1)}(),function(){Kinetic.Util.addMethods(Kinetic.Container,{__init:function(a){this.children=new Kinetic.Collection,Kinetic.Node.call(this,a)},getChildren:function(){return this.children},hasChildren:function(){return this.getChildren().length>0},removeChildren:function(){for(var a,b=this.children;b.length>0;)a=b[0],a.hasChildren()&&a.removeChildren(),a.remove();return this},destroyChildren:function(){for(var a=this.children;a.length>0;)a[0].destroy();return this},add:function(a){var b=(Kinetic.Global,this.children);return this._validateAdd(a),a.index=b.length,a.parent=this,b.push(a),this._fire("add",{child:a}),this},destroy:function(){this.hasChildren()&&this.destroyChildren(),Kinetic.Node.prototype.destroy.call(this)},get:function(a){var b,c,d,e,f,g,h,i=[],j=a.replace(/ /g,"").split(","),k=j.length;for(b=0;k>b;b++)if(d=j[b],"#"===d.charAt(0))f=this._getNodeById(d.slice(1)),f&&i.push(f);else if("."===d.charAt(0))e=this._getNodesByName(d.slice(1)),i=i.concat(e);else for(g=this.getChildren(),h=g.length,c=0;h>c;c++)i=i.concat(g[c]._get(d));return Kinetic.Collection.toCollection(i)},_getNodeById:function(a){var b=Kinetic.Global,c=b.ids[a];return void 0!==c&&this.isAncestorOf(c)?c:null},_getNodesByName:function(a){var b=Kinetic.Global,c=b.names[a]||[];return this._getDescendants(c)},_get:function(a){for(var b=Kinetic.Node.prototype._get.call(this,a),c=this.getChildren(),d=c.length,e=0;d>e;e++)b=b.concat(c[e]._get(a));return b},toObject:function(){var a=Kinetic.Node.prototype.toObject.call(this);a.children=[];for(var b=this.getChildren(),c=b.length,d=0;c>d;d++){var e=b[d];a.children.push(e.toObject())}return a},_getDescendants:function(a){for(var b=[],c=a.length,d=0;c>d;d++){var e=a[d];this.isAncestorOf(e)&&b.push(e)}return b},isAncestorOf:function(a){for(var b=a.getParent();b;){if(b._id===this._id)return!0;b=b.getParent()}return!1},clone:function(a){var b=Kinetic.Node.prototype.clone.call(this,a);return this.getChildren().each(function(a){b.add(a.clone())}),b},getAllIntersections:function(){for(var a=Kinetic.Util._getXY(Array.prototype.slice.call(arguments)),b=[],c=this.get("Shape"),d=c.length,e=0;d>e;e++){var f=c[e];f.isVisible()&&f.intersects(a)&&b.push(f)}return b},_setChildrenIndices:function(){for(var a=this.children,b=a.length,c=0;b>c;c++)a[c].index=c},drawScene:function(a){var b,c,d,e=this.getLayer(),f=this.getClipWidth()&&this.getClipHeight();if(!a&&e&&(a=e.getCanvas()),this.isVisible()){for(f&&a._clip(this),b=this.children,d=b.length,c=0;d>c;c++)b[c].drawScene(a);f&&a.getContext().restore()}return this},drawHit:function(){var a,b=this.getClipWidth()&&this.getClipHeight()&&"Stage"!==this.nodeType,c=0,d=0,e=[];if(this.shouldDrawHit()){for(b&&(a=this.getLayer().hitCanvas,a._clip(this)),e=this.children,d=e.length,c=0;d>c;c++)e[c].drawHit();b&&a.getContext().restore()}return this}}),Kinetic.Util.extend(Kinetic.Container,Kinetic.Node),Kinetic.Factory.addBoxGetterSetter(Kinetic.Container,"clip")}(),function(){function a(a){a.fill()}function b(a){a.stroke()}function c(a){a.fill()}function d(a){a.stroke()}function e(){this._clearCache(f)}var f="hasShadow";Kinetic.Util.addMethods(Kinetic.Shape,{__init:function(f){this.nodeType="Shape",this._fillFunc=a,this._strokeFunc=b,this._fillFuncHit=c,this._strokeFuncHit=d;for(var g,h=Kinetic.Global.shapes;;)if(g=Kinetic.Util.getRandomColor(),g&&!(g in h))break;this.colorKey=g,h[g]=this,Kinetic.Node.call(this,f),this._setDrawFuncs(),this.on("shadowColorChange.kinetic shadowBlurChange.kinetic shadowOffsetChange.kinetic shadowOpacityChange.kinetic",e)},hasChildren:function(){return!1},getChildren:function(){return[]},getContext:function(){return this.getLayer().getContext()},getCanvas:function(){return this.getLayer().getCanvas()},hasShadow:function(){return this._getCache(f,this._hasShadow)},_hasShadow:function(){return 0!==this.getShadowOpacity()&&!!(this.getShadowColor()||this.getShadowBlur()||this.getShadowOffsetX()||this.getShadowOffsetY())},hasFill:function(){return!!(this.getFill()||this.getFillPatternImage()||this.getFillLinearGradientColorStops()||this.getFillRadialGradientColorStops())},_get:function(a){return this.className===a||this.nodeType===a?[this]:[]},intersects:function(){var a=Kinetic.Util._getXY(Array.prototype.slice.call(arguments)),b=this.getStage(),c=b.hitCanvas;c.clear(),this.drawScene(c);var d=c.context.getImageData(0|a.x,0|a.y,1,1).data;return d[3]>0},enableFill:function(){return this._setAttr("fillEnabled",!0),this},disableFill:function(){return this._setAttr("fillEnabled",!1),this},enableStroke:function(){return this._setAttr("strokeEnabled",!0),this},disableStroke:function(){return this._setAttr("strokeEnabled",!1),this},enableStrokeScale:function(){return this._setAttr("strokeScaleEnabled",!0),this},disableStrokeScale:function(){return this._setAttr("strokeScaleEnabled",!1),this},enableShadow:function(){return this._setAttr("shadowEnabled",!0),this},disableShadow:function(){return this._setAttr("shadowEnabled",!1),this},enableDashArray:function(){return this._setAttr("dashArrayEnabled",!0),this},disableDashArray:function(){return this._setAttr("dashArrayEnabled",!1),this},destroy:function(){return Kinetic.Node.prototype.destroy.call(this),delete Kinetic.Global.shapes[this.colorKey],this},drawScene:function(a){a=a||this.getLayer().getCanvas();var b=this.getDrawFunc(),c=a.getContext();return b&&this.isVisible()&&(c.save(),a._applyOpacity(this),a._applyLineJoin(this),a._applyAncestorTransforms(this),b.call(this,a),c.restore()),this},drawHit:function(){var a=this.getAttrs(),b=a.drawHitFunc||a.drawFunc,c=this.getLayer().hitCanvas,d=c.getContext();return b&&this.shouldDrawHit()&&(d.save(),c._applyLineJoin(this),c._applyAncestorTransforms(this),b.call(this,c),d.restore()),this},_setDrawFuncs:function(){!this.attrs.drawFunc&&this.drawFunc&&this.setDrawFunc(this.drawFunc),!this.attrs.drawHitFunc&&this.drawHitFunc&&this.setDrawHitFunc(this.drawHitFunc)}}),Kinetic.Util.extend(Kinetic.Shape,Kinetic.Node),Kinetic.Factory.addColorGetterSetter(Kinetic.Shape,"stroke"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"lineJoin"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"lineCap"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"strokeWidth"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"drawFunc"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"drawHitFunc"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"dashArray"),Kinetic.Factory.addColorGetterSetter(Kinetic.Shape,"shadowColor"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"shadowBlur"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"shadowOpacity"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"fillPatternImage"),Kinetic.Factory.addColorGetterSetter(Kinetic.Shape,"fill"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"fillPatternX"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"fillPatternY"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"fillLinearGradientColorStops"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"fillRadialGradientStartRadius"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"fillRadialGradientEndRadius"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"fillRadialGradientColorStops"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"fillPatternRepeat"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"fillEnabled",!0),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"strokeEnabled",!0),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"shadowEnabled",!0),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"dashArrayEnabled",!0),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"fillPriority","color"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"strokeScaleEnabled",!0),Kinetic.Factory.addPointGetterSetter(Kinetic.Shape,"fillPatternOffset",0),Kinetic.Factory.addPointGetterSetter(Kinetic.Shape,"fillPatternScale",1),Kinetic.Factory.addPointGetterSetter(Kinetic.Shape,"fillLinearGradientStartPoint",0),Kinetic.Factory.addPointGetterSetter(Kinetic.Shape,"fillLinearGradientEndPoint",0),Kinetic.Factory.addPointGetterSetter(Kinetic.Shape,"fillRadialGradientStartPoint",0),Kinetic.Factory.addPointGetterSetter(Kinetic.Shape,"fillRadialGradientEndPoint",0),Kinetic.Factory.addPointGetterSetter(Kinetic.Shape,"shadowOffset",0),Kinetic.Factory.addRotationGetterSetter(Kinetic.Shape,"fillPatternRotation",0)}(),function(){function a(a,b){a.content.addEventListener(b,function(c){a[x+b](c)},!1)}var b="Stage",c="string",d="px",e="mouseout",f="mouseleave",g="mouseover",h="mouseenter",i="mousemove",j="mousedown",k="mouseup",l="click",m="dblclick",n="touchstart",o="touchend",p="tap",q="dbltap",r="touchmove",s="div",t="relative",u="inline-block",v="kineticjs-content",w=" ",x="_",y="container",z="",A=[j,i,k,e,n,r,o,g],B=A.length;Kinetic.Util.addMethods(Kinetic.Stage,{___init:function(a){Kinetic.Container.call(this,a),this.nodeType=b,this._id=Kinetic.Global.idCounter++,this._buildDOM(),this._bindContentEvents(),Kinetic.Global.stages.push(this)},_validateAdd:function(a){"Layer"!==a.getType()&&Kinetic.Util.error("You may only add layers to the stage.")},setContainer:function(a){return typeof a===c&&(a=document.getElementById(a)),this._setAttr(y,a),this},draw:function(){return Kinetic.Node.prototype.draw.call(this),this},setHeight:function(a){return Kinetic.Node.prototype.setHeight.call(this,a),this._resizeDOM(),this},setWidth:function(a){return Kinetic.Node.prototype.setWidth.call(this,a),this._resizeDOM(),this},clear:function(){var a,b=this.children,c=b.length;for(a=0;c>a;a++)b[a].clear();return this},destroy:function(){var a=this.content;Kinetic.Container.prototype.destroy.call(this),a&&Kinetic.Util._isInDocument(a)&&this.getContainer().removeChild(a)},getMousePosition:function(){return this.mousePos},getTouchPosition:function(){return this.touchPos},getPointerPosition:function(){return this.getTouchPosition()||this.getMousePosition()},getStage:function(){return this},getContent:function(){return this.content},toDataURL:function(a){function b(e){var f=i[e],j=f.toDataURL(),k=new Image;k.onload=function(){h.drawImage(k,0,0),e=0;a--)if(b=d[a].getIntersection(c))return b;return null},_resizeDOM:function(){if(this.content){var a,b,c=this.getWidth(),e=this.getHeight(),f=this.getChildren(),g=f.length;for(this.content.style.width=c+d,this.content.style.height=e+d,this.bufferCanvas.setSize(c,e,1),this.hitCanvas.setSize(c,e),a=0;g>a;a++)b=f[a],b.getCanvas().setSize(c,e),b.hitCanvas.setSize(c,e),b.draw()}},add:function(a){return Kinetic.Container.prototype.add.call(this,a),a.canvas.setSize(this.attrs.width,this.attrs.height),a.hitCanvas.setSize(this.attrs.width,this.attrs.height),a.draw(),this.content.appendChild(a.canvas.element),this},getParent:function(){return null},getLayer:function(){return null},getLayers:function(){return this.getChildren()},_setPointerPosition:function(a){a||(a=window.event),this._setMousePosition(a),this._setTouchPosition(a)},_bindContentEvents:function(){var b;for(b=0;B>b;b++)a(this,A[b])},_mouseover:function(a){this._fire(g,a)},_mouseout:function(a){this._setPointerPosition(a);var b=Kinetic.Global,c=this.targetShape;c&&!b.isDragging()&&(c._fireAndBubble(e,a),c._fireAndBubble(f,a),this.targetShape=null),this.mousePos=void 0,this._fire(e,a)},_mousemove:function(a){this._setPointerPosition(a);var b,c=Kinetic.Global,d=Kinetic.DD,j=this.getIntersection(this.getPointerPosition());j?(b=j.shape,b&&(c.isDragging()||255!==j.pixel[3]||this.targetShape&&this.targetShape._id===b._id?b._fireAndBubble(i,a):(b._fireAndBubble(g,a,this.targetShape),b._fireAndBubble(h,a,this.targetShape),this.targetShape&&(this.targetShape._fireAndBubble(e,a,b),this.targetShape._fireAndBubble(f,a,b)),this.targetShape=b))):(this._fire(i,a),this.targetShape&&!c.isDragging()&&(this.targetShape._fireAndBubble(e,a),this.targetShape._fireAndBubble(f,a),this.targetShape=null)),d&&d._drag(a),a.preventDefault&&a.preventDefault()},_mousedown:function(a){this._setPointerPosition(a);var b=Kinetic.Global,c=this.getIntersection(this.getPointerPosition()),d=c&&c.shape?c.shape:this;b.listenClickTap=!0,this.clickStartShape=d,d._fireAndBubble(j,a),a.preventDefault&&a.preventDefault()},_mouseup:function(a){this._setPointerPosition(a);var b=Kinetic.Global,c=this.getIntersection(this.getPointerPosition()),d=c&&c.shape?c.shape:this;d._fireAndBubble(k,a),b.listenClickTap&&d._id===this.clickStartShape._id&&(d._fireAndBubble(l,a),b.inDblClickWindow?(d._fireAndBubble(m,a),b.inDblClickWindow=!1):b.inDblClickWindow=!0,setTimeout(function(){b.inDblClickWindow=!1},b.dblClickWindow)),b.listenClickTap=!1,a.preventDefault&&a.preventDefault()},_touchstart:function(a){this._setPointerPosition(a);var b=Kinetic.Global,c=this.getIntersection(this.getPointerPosition()),d=c&&c.shape?c.shape:this;b.listenClickTap=!0,this.tapStartShape=d,d._fireAndBubble(n,a),d.isListening()&&a.preventDefault&&a.preventDefault()},_touchend:function(a){this._setPointerPosition(a);var b=Kinetic.Global,c=this.getIntersection(this.getPointerPosition()),d=c&&c.shape?c.shape:this;d._fireAndBubble(o,a),b.listenClickTap&&d._id===this.tapStartShape._id&&(d._fireAndBubble(p,a),b.inDblClickWindow?(d._fireAndBubble(q,a),b.inDblClickWindow=!1):b.inDblClickWindow=!0,setTimeout(function(){b.inDblClickWindow=!1},b.dblClickWindow)),b.listenClickTap=!1,d.isListening()&&a.preventDefault&&a.preventDefault()},_touchmove:function(a){this._setPointerPosition(a);var b=Kinetic.DD,c=this.getIntersection(this.getPointerPosition()),d=c&&c.shape?c.shape:this;d._fireAndBubble(r,a),b&&b._drag(a),d.isListening()&&a.preventDefault&&a.preventDefault()},_setMousePosition:function(a){var b=a.clientX-this._getContentPosition().left,c=a.clientY-this._getContentPosition().top;this.mousePos={x:b,y:c}},_setTouchPosition:function(a){var b,c,d;void 0!==a.touches&&1===a.touches.length&&(b=a.touches[0],c=b.clientX-this._getContentPosition().left,d=b.clientY-this._getContentPosition().top,this.touchPos={x:c,y:d})},_getContentPosition:function(){var a=this.content.getBoundingClientRect();return{top:a.top,left:a.left}},_buildDOM:function(){var a=this.getContainer();a.innerHTML=z,this.content=document.createElement(s),this.content.style.position=t,this.content.style.display=u,this.content.className=v,a.appendChild(this.content),this.bufferCanvas=new Kinetic.SceneCanvas,this.hitCanvas=new Kinetic.HitCanvas,this._resizeDOM()},_onContent:function(a,b){var c,d,e=a.split(w),f=e.length;for(c=0;f>c;c++)d=e[c],this.content.addEventListener(d,b,!1)}}),Kinetic.Util.extend(Kinetic.Stage,Kinetic.Container),Kinetic.Factory.addGetter(Kinetic.Stage,"container")}(),function(){var a="#",b="beforeDraw",c="draw";Kinetic.Util.addMethods(Kinetic.Layer,{___init:function(a){this.nodeType="Layer",this.canvas=new Kinetic.SceneCanvas,this.hitCanvas=new Kinetic.HitCanvas,Kinetic.Container.call(this,a)},_validateAdd:function(a){var b=a.getType();"Group"!==b&&"Shape"!==b&&Kinetic.Util.error("You may only add groups and shapes to a layer.")},getIntersection:function(){var b,c,d,e=Kinetic.Util._getXY(Array.prototype.slice.call(arguments));if(this.isVisible()&&this.isListening()){if(b=this.hitCanvas.context.getImageData(0|e.x,0|e.y,1,1).data,255===b[3])return c=Kinetic.Util._rgbToHex(b[0],b[1],b[2]),d=Kinetic.Global.shapes[a+c],{shape:d,pixel:b};if(b[0]>0||b[1]>0||b[2]>0||b[3]>0)return{pixel:b}}return null},drawScene:function(a){return a=a||this.getCanvas(),this._fire(b,{node:this}),this.getClearBeforeDraw()&&a.clear(),Kinetic.Container.prototype.drawScene.call(this,a),this._fire(c,{node:this}),this},drawHit:function(){var a=this.getLayer();return a&&a.getClearBeforeDraw()&&a.getHitCanvas().clear(),Kinetic.Container.prototype.drawHit.call(this),this},getCanvas:function(){return this.canvas},getHitCanvas:function(){return this.hitCanvas},getContext:function(){return this.getCanvas().getContext()},clear:function(a){return this.getCanvas().clear(a),this},setVisible:function(a){return Kinetic.Node.prototype.setVisible.call(this,a),a?(this.getCanvas().element.style.display="block",this.hitCanvas.element.style.display="block"):(this.getCanvas().element.style.display="none",this.hitCanvas.element.style.display="none"),this},setZIndex:function(a){Kinetic.Node.prototype.setZIndex.call(this,a);var b=this.getStage();return b&&(b.content.removeChild(this.getCanvas().element),ae;e+=4)c[e+3]>0&&(c[e]=d.r,c[e+1]=d.g,c[e+2]=d.b);Kinetic.Util._getImage(b,function(b){g.imageHitRegion=b,a&&a()})}catch(m){Kinetic.Util.warn("Unable to create image hit region. "+m.message)}},clearImageHitRegion:function(){delete this.imageHitRegion},getWidth:function(){var a=this.getImage();return this.attrs.width||(a?a.width:0)},getHeight:function(){var a=this.getImage();return this.attrs.height||(a?a.height:0)},_drawImage:function(a,b){5===b.length?a.drawImage(b[0],b[1],b[2],b[3],b[4]):9===b.length&&a.drawImage(b[0],b[1],b[2],b[3],b[4],b[5],b[6],b[7],b[8])}},Kinetic.Util.extend(Kinetic.Image,Kinetic.Shape),Kinetic.Factory.addFilterGetterSetter=function(a,b,c){this.addGetter(a,b,c),this.addFilterSetter(a,b)},Kinetic.Factory.addFilterSetter=function(a,c){var d=b+Kinetic.Util._capitalize(c);a.prototype[d]=function(a){this._setAttr(c,a),this._applyFilter=!0 +}},Kinetic.Factory.addGetterSetter(Kinetic.Image,"image"),Kinetic.Factory.addBoxGetterSetter(Kinetic.Image,"crop"),Kinetic.Factory.addFilterGetterSetter(Kinetic.Image,"filter")}(),function(){Kinetic.Polygon=function(a){this.___init(a)},Kinetic.Polygon.prototype={___init:function(a){Kinetic.Shape.call(this,a),this.className="Polygon"},drawFunc:function(a){var b=a.getContext(),c=this.getPoints(),d=c.length;b.beginPath(),b.moveTo(c[0].x,c[0].y);for(var e=1;d>e;e++)b.lineTo(c[e].x,c[e].y);b.closePath(),a.fillStroke(this)}},Kinetic.Util.extend(Kinetic.Polygon,Kinetic.Shape),Kinetic.Factory.addPointsGetterSetter(Kinetic.Polygon,"points")}(),function(){function a(a){a.fillText(this.partialText,0,0)}function b(a){a.strokeText(this.partialText,0,0)}var c="auto",d="Calibri",e="canvas",f="center",g="Change.kinetic",h="2d",i="-",j="",k="left",l="text",m="Text",n="middle",o="normal",p="px ",q=" ",r="right",s="word",t="char",u="none",v=["fontFamily","fontSize","fontStyle","padding","align","lineHeight","text","width","height","wrap"],w=v.length,x=document.createElement(e).getContext(h);Kinetic.Text=function(a){this.___init(a)},Kinetic.Text.prototype={___init:function(d){var e=this;void 0===d.width&&(d.width=c),void 0===d.height&&(d.height=c),Kinetic.Shape.call(this,d),this._fillFunc=a,this._strokeFunc=b,this.className=m;for(var f=0;w>f;f++)this.on(v[f]+g,e._setTextData);this._setTextData()},drawFunc:function(a){var b=a.getContext(),c=this.getPadding(),d=(this.getFontStyle(),this.getFontSize(),this.getFontFamily(),this.getTextHeight()),e=this.getLineHeight()*d,g=this.textArr,h=g.length,i=this.getWidth();b.font=this._getContextFont(),b.textBaseline=n,b.textAlign=k,b.save(),b.translate(c,0),b.translate(0,c+d/2);for(var j=0;h>j;j++){var l=g[j],m=l.text,o=l.width;b.save(),this.getAlign()===r?b.translate(i-o-2*c,0):this.getAlign()===f&&b.translate((i-o-2*c)/2,0),this.partialText=m,a.fillStroke(this),b.restore(),b.translate(0,e)}b.restore()},drawHitFunc:function(a){var b=a.getContext(),c=this.getWidth(),d=this.getHeight();b.beginPath(),b.rect(0,0,c,d),b.closePath(),a.fillStroke(this)},setText:function(a){var b=Kinetic.Util._isString(a)?a:a.toString();this._setAttr(l,b)},getWidth:function(){return this.attrs.width===c?this.getTextWidth()+2*this.getPadding():this.attrs.width},getHeight:function(){return this.attrs.height===c?this.getTextHeight()*this.textArr.length*this.getLineHeight()+2*this.getPadding():this.attrs.height},getTextWidth:function(){return this.textWidth},getTextHeight:function(){return this.textHeight},_getTextSize:function(a){var b,c=x,d=this.getFontSize();return c.save(),c.font=this._getContextFont(),b=c.measureText(a),c.restore(),{width:b.width,height:parseInt(d,10)}},_getContextFont:function(){return this.getFontStyle()+q+this.getFontSize()+p+this.getFontFamily()},_addTextLine:function(a,b){return this.textArr.push({text:a,width:b})},_getTextWidth:function(a){return x.measureText(a).width},_setTextData:function(){var a=this.getText().split("\n"),b=+this.getFontSize(),d=0,e=this.getLineHeight()*b,f=this.attrs.width,g=this.attrs.height,h=f!==c,j=g!==c,k=this.getPadding(),l=f-2*k,m=g-2*k,n=0,o=this.getWrap(),r=o!==u,s=o!==t&&r;this.textArr=[],x.save(),x.font=this.getFontStyle()+q+b+p+this.getFontFamily();for(var v=0,w=a.length;w>v;++v){var y=a[v],z=this._getTextWidth(y);if(h&&z>l)for(;y.length>0;){for(var A=0,B=y.length,C="",D=0;B>A;){var E=A+B>>>1,F=y.slice(0,E+1),G=this._getTextWidth(F);l>=G?(A=E+1,C=F,D=G):B=E}if(!C)break;if(s){var H=Math.max(C.lastIndexOf(q),C.lastIndexOf(i))+1;H>0&&(A=H,C=C.slice(0,A),D=this._getTextWidth(C))}if(this._addTextLine(C,D),n+=e,!r||j&&n+e>m)break;if(y=y.slice(A),y.length>0&&(z=this._getTextWidth(y),l>=z)){this._addTextLine(y,z),n+=e;break}}else this._addTextLine(y,z),n+=e,d=Math.max(d,z);if(j&&n+e>m)break}x.restore(),this.textHeight=b,this.textWidth=d}},Kinetic.Util.extend(Kinetic.Text,Kinetic.Shape),Kinetic.Factory.addGetterSetter(Kinetic.Text,"fontFamily",d),Kinetic.Factory.addGetterSetter(Kinetic.Text,"fontSize",12),Kinetic.Factory.addGetterSetter(Kinetic.Text,"fontStyle",o),Kinetic.Factory.addGetterSetter(Kinetic.Text,"padding",0),Kinetic.Factory.addGetterSetter(Kinetic.Text,"align",k),Kinetic.Factory.addGetterSetter(Kinetic.Text,"lineHeight",1),Kinetic.Factory.addGetterSetter(Kinetic.Text,"wrap",s),Kinetic.Factory.addGetter(Kinetic.Text,l,j),Kinetic.Factory.addSetter(Kinetic.Text,"width"),Kinetic.Factory.addSetter(Kinetic.Text,"height")}(),function(){Kinetic.Line=function(a){this.___init(a)},Kinetic.Line.prototype={___init:function(a){Kinetic.Shape.call(this,a),this.className="Line"},drawFunc:function(a){var b,c,d=this.getPoints(),e=d.length,f=a.getContext();for(f.beginPath(),f.moveTo(d[0].x,d[0].y),b=1;e>b;b++)c=d[b],f.lineTo(c.x,c.y);a.stroke(this)}},Kinetic.Util.extend(Kinetic.Line,Kinetic.Shape),Kinetic.Factory.addPointsGetterSetter(Kinetic.Line,"points")}(),function(){Kinetic.Spline=function(a){this.___init(a)},Kinetic.Spline.prototype={___init:function(a){var b=this;Kinetic.Shape.call(this,a),this.className="Spline",this.on("pointsChange.kinetic tensionChange.kinetic",function(){b._setAllPoints()}),this._setAllPoints()},drawFunc:function(a){var b,c,d,e,f=this.getPoints(),g=f.length,h=a.getContext(),i=this.getTension();if(h.beginPath(),h.moveTo(f[0].x,f[0].y),0!==i&&g>2){for(b=this.allPoints,c=b.length,d=2,h.quadraticCurveTo(b[0].x,b[0].y,b[1].x,b[1].y);c-1>d;)h.bezierCurveTo(b[d].x,b[d++].y,b[d].x,b[d++].y,b[d].x,b[d++].y);h.quadraticCurveTo(b[c-1].x,b[c-1].y,f[g-1].x,f[g-1].y)}else for(d=1;g>d;d++)e=f[d],h.lineTo(e.x,e.y);a.stroke(this)},_setAllPoints:function(){this.allPoints=Kinetic.Util._expandPoints(this.getPoints(),this.getTension())}},Kinetic.Util.extend(Kinetic.Spline,Kinetic.Shape),Kinetic.Factory.addGetterSetter(Kinetic.Spline,"tension",1),Kinetic.Factory.addPointsGetterSetter(Kinetic.Spline,"points")}(),function(){Kinetic.Blob=function(a){this.___init(a)},Kinetic.Blob.prototype={___init:function(a){var b=this;Kinetic.Shape.call(this,a),this.className="Blob",this.on("pointsChange.kinetic tensionChange.kinetic",function(){b._setAllPoints()}),this._setAllPoints()},drawFunc:function(a){var b,c,d,e,f=this.getPoints(),g=f.length,h=a.getContext(),i=this.getTension();if(h.beginPath(),h.moveTo(f[0].x,f[0].y),0!==i&&g>2)for(b=this.allPoints,c=b.length,d=0;c-1>d;)h.bezierCurveTo(b[d].x,b[d++].y,b[d].x,b[d++].y,b[d].x,b[d++].y);else for(d=1;g>d;d++)e=f[d],h.lineTo(e.x,e.y);h.closePath(),a.fillStroke(this)},_setAllPoints:function(){var a=this.getPoints(),b=a.length,c=this.getTension(),d=Kinetic.Util,e=d._getControlPoints(a[b-1],a[0],a[1],c),f=d._getControlPoints(a[b-2],a[b-1],a[0],c);this.allPoints=Kinetic.Util._expandPoints(this.getPoints(),this.getTension()),this.allPoints.unshift(e[1]),this.allPoints.push(f[0]),this.allPoints.push(a[b-1]),this.allPoints.push(f[1]),this.allPoints.push(e[0]),this.allPoints.push(a[0])}},Kinetic.Util.extend(Kinetic.Blob,Kinetic.Shape),Kinetic.Factory.addGetterSetter(Kinetic.Blob,"tension",1),Kinetic.Factory.addPointsGetterSetter(Kinetic.Blob,"points")}(),function(){Kinetic.Sprite=function(a){this.___init(a)},Kinetic.Sprite.prototype={___init:function(a){Kinetic.Shape.call(this,a),this.className="Sprite",this.anim=new Kinetic.Animation;var b=this;this.on("animationChange.kinetic",function(){b.setIndex(0)})},drawFunc:function(a){var b=this.getAnimation(),c=this.getIndex(),d=this.getAnimations()[b][c],e=a.getContext(),f=this.getImage();f&&e.drawImage(f,d.x,d.y,d.width,d.height,0,0,d.width,d.height)},drawHitFunc:function(a){var b=this.getAnimation(),c=this.getIndex(),d=this.getAnimations()[b][c],e=a.getContext();e.beginPath(),e.rect(0,0,d.width,d.height),e.closePath(),a.fill(this)},start:function(){var a=this,b=this.getLayer();this.anim.setLayers(b),this.interval=setInterval(function(){var b=a.getIndex();a._updateIndex(),a.afterFrameFunc&&b===a.afterFrameIndex&&(a.afterFrameFunc(),delete a.afterFrameFunc,delete a.afterFrameIndex)},1e3/this.getFrameRate()),this.anim.start()},stop:function(){this.anim.stop(),clearInterval(this.interval)},afterFrame:function(a,b){this.afterFrameIndex=a,this.afterFrameFunc=b},_updateIndex:function(){var a=this.getIndex(),b=this.getAnimation(),c=this.getAnimations(),d=c[b],e=d.length;e-1>a?this.setIndex(a+1):this.setIndex(0)}},Kinetic.Util.extend(Kinetic.Sprite,Kinetic.Shape),Kinetic.Factory.addGetterSetter(Kinetic.Sprite,"animation"),Kinetic.Factory.addGetterSetter(Kinetic.Sprite,"animations"),Kinetic.Factory.addGetterSetter(Kinetic.Sprite,"image"),Kinetic.Factory.addGetterSetter(Kinetic.Sprite,"index",0),Kinetic.Factory.addGetterSetter(Kinetic.Sprite,"frameRate",17)}(),function(){Kinetic.Path=function(a){this.___init(a)},Kinetic.Path.prototype={___init:function(a){this.dataArray=[];var b=this;Kinetic.Shape.call(this,a),this.className="Path",this.dataArray=Kinetic.Path.parsePathData(this.getData()),this.on("dataChange.kinetic",function(){b.dataArray=Kinetic.Path.parsePathData(this.getData())})},drawFunc:function(a){var b=this.dataArray,c=a.getContext();c.beginPath();for(var d=0;dj?i:j,p=i>j?1:i/j,q=i>j?j/i:1;c.translate(g,h),c.rotate(m),c.scale(p,q),c.arc(0,0,o,k,k+l,1-n),c.scale(1/p,1/q),c.rotate(-m),c.translate(-g,-h);break;case"z":c.closePath()}}a.fillStroke(this)}},Kinetic.Util.extend(Kinetic.Path,Kinetic.Shape),Kinetic.Path.getLineLength=function(a,b,c,d){return Math.sqrt((c-a)*(c-a)+(d-b)*(d-b))},Kinetic.Path.getPointOnLine=function(a,b,c,d,e,f,g){void 0===f&&(f=b),void 0===g&&(g=c);var h=(e-c)/(d-b+1e-8),i=Math.sqrt(a*a/(1+h*h));b>d&&(i*=-1);var j,k=h*i;if((g-c)/(f-b+1e-8)===h)j={x:f+i,y:g+k};else{var l,m,n=this.getLineLength(b,c,d,e);if(1e-8>n)return void 0;var o=(f-b)*(d-b)+(g-c)*(e-c);o/=n*n,l=b+o*(d-b),m=c+o*(e-c);var p=this.getLineLength(f,g,l,m),q=Math.sqrt(a*a-p*p);i=Math.sqrt(q*q/(1+h*h)),b>d&&(i*=-1),k=h*i,j={x:l+i,y:m+k}}return j},Kinetic.Path.getPointOnCubicBezier=function(a,b,c,d,e,f,g,h,i){function j(a){return a*a*a}function k(a){return 3*a*a*(1-a)}function l(a){return 3*a*(1-a)*(1-a)}function m(a){return(1-a)*(1-a)*(1-a)}var n=h*j(a)+f*k(a)+d*l(a)+b*m(a),o=i*j(a)+g*k(a)+e*l(a)+c*m(a);return{x:n,y:o}},Kinetic.Path.getPointOnQuadraticBezier=function(a,b,c,d,e,f,g){function h(a){return a*a}function i(a){return 2*a*(1-a)}function j(a){return(1-a)*(1-a)}var k=f*h(a)+d*i(a)+b*j(a),l=g*h(a)+e*i(a)+c*j(a);return{x:k,y:l}},Kinetic.Path.getPointOnEllipticalArc=function(a,b,c,d,e,f){var g=Math.cos(f),h=Math.sin(f),i={x:c*Math.cos(e),y:d*Math.sin(e)};return{x:a+(i.x*g-i.y*h),y:b+(i.x*h+i.y*g)}},Kinetic.Path.parsePathData=function(a){if(!a)return[];var b=a,c=["m","M","l","L","v","V","h","H","z","Z","c","C","q","Q","t","T","s","S","a","A"];b=b.replace(new RegExp(" ","g"),",");for(var d=0;d0&&""===k[0]&&k.shift();for(var l=0;l0&&!isNaN(k[0]);){var m,n,o,p,q,r,s,t,u,v,w=null,x=[],y=g,z=h;switch(j){case"l":g+=k.shift(),h+=k.shift(),w="L",x.push(g,h);break;case"L":g=k.shift(),h=k.shift(),x.push(g,h);break;case"m":g+=k.shift(),h+=k.shift(),w="M",x.push(g,h),j="l";break;case"M":g=k.shift(),h=k.shift(),w="M",x.push(g,h),j="L";break;case"h":g+=k.shift(),w="L",x.push(g,h);break;case"H":g=k.shift(),w="L",x.push(g,h);break;case"v":h+=k.shift(),w="L",x.push(g,h);break;case"V":h=k.shift(),w="L",x.push(g,h);break;case"C":x.push(k.shift(),k.shift(),k.shift(),k.shift()),g=k.shift(),h=k.shift(),x.push(g,h);break;case"c":x.push(g+k.shift(),h+k.shift(),g+k.shift(),h+k.shift()),g+=k.shift(),h+=k.shift(),w="C",x.push(g,h);break;case"S":n=g,o=h,m=f[f.length-1],"C"===m.command&&(n=g+(g-m.points[2]),o=h+(h-m.points[3])),x.push(n,o,k.shift(),k.shift()),g=k.shift(),h=k.shift(),w="C",x.push(g,h);break;case"s":n=g,o=h,m=f[f.length-1],"C"===m.command&&(n=g+(g-m.points[2]),o=h+(h-m.points[3])),x.push(n,o,g+k.shift(),h+k.shift()),g+=k.shift(),h+=k.shift(),w="C",x.push(g,h);break;case"Q":x.push(k.shift(),k.shift()),g=k.shift(),h=k.shift(),x.push(g,h);break;case"q":x.push(g+k.shift(),h+k.shift()),g+=k.shift(),h+=k.shift(),w="Q",x.push(g,h);break;case"T":n=g,o=h,m=f[f.length-1],"Q"===m.command&&(n=g+(g-m.points[0]),o=h+(h-m.points[1])),g=k.shift(),h=k.shift(),w="Q",x.push(n,o,g,h);break;case"t":n=g,o=h,m=f[f.length-1],"Q"===m.command&&(n=g+(g-m.points[0]),o=h+(h-m.points[1])),g+=k.shift(),h+=k.shift(),w="Q",x.push(n,o,g,h);break;case"A":p=k.shift(),q=k.shift(),r=k.shift(),s=k.shift(),t=k.shift(),u=g,v=h,g=k.shift(),h=k.shift(),w="A",x=this.convertEndpointToCenterParameterization(u,v,g,h,s,t,p,q,r);break;case"a":p=k.shift(),q=k.shift(),r=k.shift(),s=k.shift(),t=k.shift(),u=g,v=h,g+=k.shift(),h+=k.shift(),w="A",x=this.convertEndpointToCenterParameterization(u,v,g,h,s,t,p,q,r)}f.push({command:w||j,points:x,start:{x:y,y:z},pathLength:this.calcLength(y,z,w||j,x)})}("z"===j||"Z"===j)&&f.push({command:"z",points:[],start:void 0,pathLength:0})}return f},Kinetic.Path.calcLength=function(a,b,c,d){var e,f,g,h=Kinetic.Path;switch(c){case"L":return h.getLineLength(a,b,d[0],d[1]);case"C":for(e=0,f=h.getPointOnCubicBezier(0,a,b,d[0],d[1],d[2],d[3],d[4],d[5]),t=.01;1>=t;t+=.01)g=h.getPointOnCubicBezier(t,a,b,d[0],d[1],d[2],d[3],d[4],d[5]),e+=h.getLineLength(f.x,f.y,g.x,g.y),f=g;return e;case"Q":for(e=0,f=h.getPointOnQuadraticBezier(0,a,b,d[0],d[1],d[2],d[3]),t=.01;1>=t;t+=.01)g=h.getPointOnQuadraticBezier(t,a,b,d[0],d[1],d[2],d[3]),e+=h.getLineLength(f.x,f.y,g.x,g.y),f=g;return e;case"A":e=0;var i=d[4],j=d[5],k=d[4]+j,l=Math.PI/180;if(Math.abs(i-k)j)for(t=i-l;t>k;t-=l)g=h.getPointOnEllipticalArc(d[0],d[1],d[2],d[3],t,0),e+=h.getLineLength(f.x,f.y,g.x,g.y),f=g;else for(t=i+l;k>t;t+=l)g=h.getPointOnEllipticalArc(d[0],d[1],d[2],d[3],t,0),e+=h.getLineLength(f.x,f.y,g.x,g.y),f=g;return g=h.getPointOnEllipticalArc(d[0],d[1],d[2],d[3],k,0),e+=h.getLineLength(f.x,f.y,g.x,g.y)}return 0},Kinetic.Path.convertEndpointToCenterParameterization=function(a,b,c,d,e,f,g,h,i){var j=i*(Math.PI/180),k=Math.cos(j)*(a-c)/2+Math.sin(j)*(b-d)/2,l=-1*Math.sin(j)*(a-c)/2+Math.cos(j)*(b-d)/2,m=k*k/(g*g)+l*l/(h*h);m>1&&(g*=Math.sqrt(m),h*=Math.sqrt(m));var n=Math.sqrt((g*g*h*h-g*g*l*l-h*h*k*k)/(g*g*l*l+h*h*k*k));e==f&&(n*=-1),isNaN(n)&&(n=0);var o=n*g*l/h,p=n*-h*k/g,q=(a+c)/2+Math.cos(j)*o-Math.sin(j)*p,r=(b+d)/2+Math.sin(j)*o+Math.cos(j)*p,s=function(a){return Math.sqrt(a[0]*a[0]+a[1]*a[1])},t=function(a,b){return(a[0]*b[0]+a[1]*b[1])/(s(a)*s(b))},u=function(a,b){return(a[0]*b[1]=1&&(y=0),0===f&&y>0&&(y-=2*Math.PI),1==f&&0>y&&(y+=2*Math.PI),[q,r,g,h,v,y,j,f]},Kinetic.Factory.addGetterSetter(Kinetic.Path,"data")}(),function(){function a(a){a.fillText(this.partialText,0,0)}function b(a){a.strokeText(this.partialText,0,0)}var c="",d="Calibri",e="normal";Kinetic.TextPath=function(a){this.___init(a)},Kinetic.TextPath.prototype={___init:function(c){var d=this;this.dummyCanvas=document.createElement("canvas"),this.dataArray=[],Kinetic.Shape.call(this,c),this._fillFunc=a,this._strokeFunc=b,this.className="TextPath",this.dataArray=Kinetic.Path.parsePathData(this.attrs.data),this.on("dataChange.kinetic",function(){d.dataArray=Kinetic.Path.parsePathData(this.attrs.data)}),this.on("textChange.kinetic textStroke.kinetic textStrokeWidth.kinetic",d._setTextData),d._setTextData()},drawFunc:function(a){var b=(this.charArr,a.getContext());b.font=this._getContextFont(),b.textBaseline="middle",b.textAlign="left",b.save();for(var c=this.glyphInfo,d=0;d0)return g=d,b[d];"M"==b[d].command&&(c={x:b[d].points[0],y:b[d].points[1]})}return{}},j=function(b){var f=a._getTextSize(b).width,g=0,j=0;for(d=void 0;Math.abs(f-g)/f>.01&&25>j;){j++;for(var k=g;void 0===e;)e=i(),e&&k+e.pathLengthf?d=Kinetic.Path.getPointOnLine(f,c.x,c.y,e.points[0],e.points[1],c.x,c.y):e=void 0;break;case"A":var m=e.points[4],n=e.points[5],o=e.points[4]+n;0===h?h=m+1e-8:f>g?h+=Math.PI/180*n/Math.abs(n):h-=Math.PI/360*n/Math.abs(n),Math.abs(h)>Math.abs(o)&&(h=o,l=!0),d=Kinetic.Path.getPointOnEllipticalArc(e.points[0],e.points[1],e.points[2],e.points[3],h,e.points[6]);break;case"C":0===h?h=f>e.pathLength?1e-8:f/e.pathLength:f>g?h+=(f-g)/e.pathLength:h-=(g-f)/e.pathLength,h>1&&(h=1,l=!0),d=Kinetic.Path.getPointOnCubicBezier(h,e.start.x,e.start.y,e.points[0],e.points[1],e.points[2],e.points[3],e.points[4],e.points[5]);break;case"Q":0===h?h=f/e.pathLength:f>g?h+=(f-g)/e.pathLength:h-=(g-f)/e.pathLength,h>1&&(h=1,l=!0),d=Kinetic.Path.getPointOnQuadraticBezier(h,e.start.x,e.start.y,e.points[0],e.points[1],e.points[2],e.points[3])}void 0!==d&&(g=Kinetic.Path.getLineLength(c.x,c.y,d.x,d.y)),l&&(l=!1,e=void 0)}},k=0;kb;b++)c=g*Math.sin(2*b*Math.PI/f),d=-1*g*Math.cos(2*b*Math.PI/f),e.lineTo(c,d);e.closePath(),a.fillStroke(this)}},Kinetic.Util.extend(Kinetic.RegularPolygon,Kinetic.Shape),Kinetic.Factory.addGetterSetter(Kinetic.RegularPolygon,"radius",0),Kinetic.Factory.addGetterSetter(Kinetic.RegularPolygon,"sides",0)}(),function(){Kinetic.Star=function(a){this.___init(a)},Kinetic.Star.prototype={___init:function(a){Kinetic.Shape.call(this,a),this.className="Star"},drawFunc:function(a){var b=a.getContext(),c=this.attrs.innerRadius,d=this.attrs.outerRadius,e=this.attrs.numPoints;b.beginPath(),b.moveTo(0,0-this.attrs.outerRadius);for(var f=1;2*e>f;f++){var g=0===f%2?d:c,h=g*Math.sin(f*Math.PI/e),i=-1*g*Math.cos(f*Math.PI/e);b.lineTo(h,i)}b.closePath(),a.fillStroke(this)}},Kinetic.Util.extend(Kinetic.Star,Kinetic.Shape),Kinetic.Factory.addGetterSetter(Kinetic.Star,"numPoints",0),Kinetic.Factory.addGetterSetter(Kinetic.Star,"innerRadius",0),Kinetic.Factory.addGetterSetter(Kinetic.Star,"outerRadius",0)}(),function(){var a=["fontFamily","fontSize","fontStyle","padding","lineHeight","text"],b="Change.kinetic",c="none",d="up",e="right",f="down",g="left",h="Label",i=a.length;Kinetic.Label=function(a){this.____init(a)},Kinetic.Label.prototype={____init:function(a){var b=this;this.className=h,Kinetic.Group.call(this,a),this.on("add.kinetic",function(a){b._addListeners(a.child),b._sync()})},getText:function(){return this.get("Text")[0]},getTag:function(){return this.get("Tag")[0]},_addListeners:function(c){var d,e=this,f=function(){e._sync()};for(d=0;i>d;d++)c.on(a[d]+b,f)},getWidth:function(){return this.getText().getWidth()},getHeight:function(){return this.getText().getHeight()},_sync:function(){var a,b,c,h,i,j,k=this.getText(),l=this.getTag();if(k&&l){switch(a=k.getWidth(),b=k.getHeight(),c=l.getPointerDirection(),h=l.getPointerWidth(),pointerHeight=l.getPointerHeight(),i=0,j=0,c){case d:i=a/2,j=-1*pointerHeight;break;case e:i=a+h,j=b/2;break;case f:i=a/2,j=b+pointerHeight;break;case g:i=-1*h,j=b/2}l.setAttrs({x:-1*i,y:-1*j,width:a,height:b}),k.setAttrs({x:-1*i,y:-1*j})}}},Kinetic.Util.extend(Kinetic.Label,Kinetic.Group),Kinetic.Tag=function(a){this.___init(a)},Kinetic.Tag.prototype={___init:function(a){Kinetic.Shape.call(this,a),this.className="Tag"},drawFunc:function(a){var b=a.getContext(),c=this.getWidth(),h=this.getHeight(),i=this.getPointerDirection(),j=this.getPointerWidth(),k=this.getPointerHeight();this.getCornerRadius(),b.beginPath(),b.moveTo(0,0),i===d&&(b.lineTo((c-j)/2,0),b.lineTo(c/2,-1*k),b.lineTo((c+j)/2,0)),b.lineTo(c,0),i===e&&(b.lineTo(c,(h-k)/2),b.lineTo(c+j,h/2),b.lineTo(c,(h+k)/2)),b.lineTo(c,h),i===f&&(b.lineTo((c+j)/2,h),b.lineTo(c/2,h+k),b.lineTo((c-j)/2,h)),b.lineTo(0,h),i===g&&(b.lineTo(0,(h+k)/2),b.lineTo(-1*j,h/2),b.lineTo(0,(h-k)/2)),b.closePath(),a.fillStroke(this)}},Kinetic.Util.extend(Kinetic.Tag,Kinetic.Shape),Kinetic.Factory.addGetterSetter(Kinetic.Tag,"pointerDirection",c),Kinetic.Factory.addGetterSetter(Kinetic.Tag,"pointerWidth",0),Kinetic.Factory.addGetterSetter(Kinetic.Tag,"pointerHeight",0),Kinetic.Factory.addGetterSetter(Kinetic.Tag,"cornerRadius",0)}(),function(){Kinetic.Filters.Grayscale=function(a){for(var b=a.data,c=0;ch;h++)N=N.next=new a,h==J&&(M=N);for(N.next=L,l=k=0,g=0;F>g;g++){for(u=v=w=x=m=n=o=p=0,q=J*(y=D[k]),r=J*(z=D[k+1]),s=J*(A=D[k+2]),t=J*(B=D[k+3]),m+=K*y,n+=K*z,o+=K*A,p+=K*B,N=L,h=0;J>h;h++)N.r=y,N.g=z,N.b=A,N.a=B,N=N.next;for(h=1;J>h;h++)i=k+((h>H?H:h)<<2),m+=(N.r=y=D[i])*(C=J-h),n+=(N.g=z=D[i+1])*C,o+=(N.b=A=D[i+2])*C,p+=(N.a=B=D[i+3])*C,u+=y,v+=z,w+=A,x+=B,N=N.next;for(O=L,P=M,f=0;E>f;f++)D[k+3]=B=p*Q>>R,0!==B?(B=255/B,D[k]=(m*Q>>R)*B,D[k+1]=(n*Q>>R)*B,D[k+2]=(o*Q>>R)*B):D[k]=D[k+1]=D[k+2]=0,m-=q,n-=r,o-=s,p-=t,q-=O.r,r-=O.g,s-=O.b,t-=O.a,i=l+((i=f+e+1)f;f++){for(v=w=x=u=n=o=p=m=0,k=f<<2,q=J*(y=D[k]),r=J*(z=D[k+1]),s=J*(A=D[k+2]),t=J*(B=D[k+3]),m+=K*y,n+=K*z,o+=K*A,p+=K*B,N=L,h=0;J>h;h++)N.r=y,N.g=z,N.b=A,N.a=B,N=N.next;for(j=E,h=1;e>=h;h++)k=j+f<<2,m+=(N.r=y=D[k])*(C=J-h),n+=(N.g=z=D[k+1])*C,o+=(N.b=A=D[k+2])*C,p+=(N.a=B=D[k+3])*C,u+=y,v+=z,w+=A,x+=B,N=N.next,I>h&&(j+=E);for(k=f,O=L,P=M,g=0;F>g;g++)i=k<<2,D[i+3]=B=p*Q>>R,B>0?(B=255/B,D[i]=(m*Q>>R)*B,D[i+1]=(n*Q>>R)*B,D[i+2]=(o*Q>>R)*B):D[i]=D[i+1]=D[i+2]=0,m-=q,n-=r,o-=s,p-=t,q-=O.r,r-=O.g,s-=O.b,t-=O.a,i=f+((i=g+J)0&&b(a,c)},Kinetic.Factory.addFilterGetterSetter(Kinetic.Image,"filterRadius",0)}(),function(){function a(a,b,c){var d=4*(c*a.width+b),e=[];return e.push(a.data[d++],a.data[d++],a.data[d++],a.data[d++]),e}function b(a,b){return Math.sqrt(Math.pow(a[0]-b[0],2)+Math.pow(a[1]-b[1],2)+Math.pow(a[2]-b[2],2))}function c(a){for(var b=[0,0,0],c=0;cn?0:255}return l}}function e(a,b){for(var c=0;ch;h++)for(var i=0;b>i;i++){for(var j=h*b+i,k=0,l=0;e>l;l++)for(var m=0;e>m;m++){var n=h+l-f,o=i+m-f;if(n>=0&&c>n&&o>=0&&b>o){var p=n*b+o,q=d[l*e+m];k+=a[p]*q}}g[j]=2040===k?255:0}return g}function g(a,b,c){for(var d=[1,1,1,1,1,1,1,1,1],e=Math.round(Math.sqrt(d.length)),f=Math.floor(e/2),g=[],h=0;c>h;h++)for(var i=0;b>i;i++){for(var j=h*b+i,k=0,l=0;e>l;l++)for(var m=0;e>m;m++){var n=h+l-f,o=i+m-f;if(n>=0&&c>n&&o>=0&&b>o){var p=n*b+o,q=d[l*e+m];k+=a[p]*q}}g[j]=k>=1020?255:0}return g}function h(a,b,c){for(var d=[1/9,1/9,1/9,1/9,1/9,1/9,1/9,1/9,1/9],e=Math.round(Math.sqrt(d.length)),f=Math.floor(e/2),g=[],h=0;c>h;h++)for(var i=0;b>i;i++){for(var j=h*b+i,k=0,l=0;e>l;l++)for(var m=0;e>m;m++){var n=h+l-f,o=i+m-f;if(n>=0&&c>n&&o>=0&&b>o){var p=n*b+o,q=d[l*e+m];k+=a[p]*q}}g[j]=k}return g}Kinetic.Filters.Mask=function(a){var b=this.getFilterThreshold(),c=d(a,b);return c&&(c=f(c,a.width,a.height),c=g(c,a.width,a.height),c=h(c,a.width,a.height),e(a,c)),a},Kinetic.Factory.addFilterGetterSetter(Kinetic.Image,"filterThreshold",0)}(),function(){var a=function(a,b,c){a/=255,b/=255,c/=255;var d=Math.max(a,b,c),e=Math.min(a,b,c),f=d-e,g=f/2,h=f/(1-Math.abs(2*g-1)),i=0;return d==a?i=(b-c)/f%6:d==b?i=(c-a)/f+2:d==c&&(i=(a-b)/f+4),[(60*i+360)%360,h,g]},b=function(a,b,c,d){a/=255,b/=255,c/=255;var e=Math.max(a,b,c),f=Math.min(a,b,c),g=e-f,h=g/2,i=(g/(1-Math.abs(2*h-1)),0);e==a?i=(b-c)/g%6:e==b?i=(c-a)/g+2:e==c&&(i=(a-b)/g+4),i*=60,i%=360,i+=d,i%=360,i/=60;var j=0,k=0,l=0,m=g*(1-Math.abs(i%2-1)),n=h-g/2;return i>=0&&1>i?(j=g,k=m):i>=1&&2>i?(k=g,j=m):i>=2&&3>i?(k=g,l=m):i>=3&&4>i?(l=g,k=m):i>=4&&5>i?(l=g,j=m):i>=5&&6>i&&(j=g,l=m),j+=n,k+=n,l+=n,j=255*j,k=255*k,l=255*l,[j,k,l]},c=function(a,c){for(var d,e=a.data,f=0;fm;m+=1)for(l=0;d>l;l+=1){for(h=0,i=0,j=0,k=0,q=0;s>q;q+=1)for(r=0;t>r;r+=1)n=(l+q-u)%d,n=n>0?n:-n,o=(m+q-v)%e,o=o>0?o:-o,p=4*(o*d+n),h+=b[r][q]*c[p+0],i+=b[r][q]*c[p+1],j+=b[r][q]*c[p+2];p=4*(m*d+l),g[p+0]=h,g[p+1]=i,g[p+2]=j}var w=4*f;for(p=0;w>p;p+=4)c[p+0]=g[p+0],c[p+1]=g[p+1],c[p+2]=g[p+2]},b=function(a,b,c){var d=a-b;return Math.pow(Math.E,-d*d/(2*c*c))},c=function(a,c,d){0===a%2&&(a+=1);var e,f,g,h=[];for(e=0;a>e;e+=1){for(g=[],f=0;a>f;f+=1)g.push(c*b(e,a/2,d)*b(f,a/2,d));h.push(g)}return h},d=function(a,b){var d=c(a,b,1),e=Math.floor(a/2);return d[e][e]+=1-b,d},e=function(a,b){var d=c(a,-b,1),e=Math.floor(a/2);return d[e][e]+=1+b,d};Kinetic.Factory.addFilterGetterSetter(Kinetic.Image,"filterAmount",50),Kinetic.Filters.UnsharpMask=function(b){a(b,e(5,this.getFilterAmount()/100))},Kinetic.Filters.SoftBlur=function(b){a(b,d(5,this.getFilterAmount()/100))},Kinetic.Filters.Edge=function(b){var c=this.getFilterAmount()/100;0!==c&&a(b,[[0,-1*c,0],[-1*c,1-c+4*c,-1*c],[0,-1*c,0]])},Kinetic.Filters.Emboss=function(b){var c=this.getFilterAmount()/100;0!==c&&a(b,[[-1*c,-.5*c,0],[-.5*c,1+.5*c,.5*c],[0,.5*c,1*c]])}}(); \ No newline at end of file diff --git a/ajax/libs/kineticjs/package.json b/ajax/libs/kineticjs/package.json index 99af86d86..9efbf651a 100644 --- a/ajax/libs/kineticjs/package.json +++ b/ajax/libs/kineticjs/package.json @@ -1,7 +1,7 @@ { "name": "kineticjs", "filename": "kinetic.min.js", - "version": "4.3.1", + "version": "4.6.0", "description": "KineticJS is an HTML5 Canvas JavaScript framework that enables high performance animations, transitions, node nesting, layering, filtering, caching, event handling for desktop and mobile applications, and much more.", "homepage": "http://kineticjs.com/", "keywords": [ From 311c7099ef59c6f642ad34dc3bb31e00d1ec4050 Mon Sep 17 00:00:00 2001 From: Dean Malmgren Date: Thu, 10 Oct 2013 16:56:53 -0500 Subject: [PATCH 07/26] added kinetic.js 4.7.2 --- ajax/libs/kineticjs/4.7.2/kinetic.min.js | 5 +++++ ajax/libs/kineticjs/package.json | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) create mode 100644 ajax/libs/kineticjs/4.7.2/kinetic.min.js diff --git a/ajax/libs/kineticjs/4.7.2/kinetic.min.js b/ajax/libs/kineticjs/4.7.2/kinetic.min.js new file mode 100644 index 000000000..6b1a303d4 --- /dev/null +++ b/ajax/libs/kineticjs/4.7.2/kinetic.min.js @@ -0,0 +1,5 @@ +/*! KineticJS v4.7.2 2013-09-29 http://www.kineticjs.com by Eric Rowell @ericdrowell - MIT License https://github.com/ericdrowell/KineticJS/wiki/License*/ +var Kinetic={};!function(){Kinetic={version:"4.7.2",stages:[],idCounter:0,ids:{},names:{},shapes:{},listenClickTap:!1,inDblClickWindow:!1,enableTrace:!1,traceArrMax:100,dblClickWindow:400,pixelRatio:void 0,UA:function(){var a=navigator.userAgent.toLowerCase(),b=/(chrome)[ \/]([\w.]+)/.exec(a)||/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||a.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}}(),Filters:{},Node:function(a){this._init(a)},Shape:function(a){this.__init(a)},Container:function(a){this.__init(a)},Stage:function(a){this.___init(a)},Layer:function(a){this.___init(a)},Group:function(a){this.___init(a)},isDragging:function(){var a=Kinetic.DD;return a?a.isDragging:!1},isDragReady:function(){var a=Kinetic.DD;return a?!!a.node:!1},_addId:function(a,b){void 0!==b&&(this.ids[b]=a)},_removeId:function(a){void 0!==a&&delete this.ids[a]},_addName:function(a,b){void 0!==b&&(void 0===this.names[b]&&(this.names[b]=[]),this.names[b].push(a))},_removeName:function(a,b){if(void 0!==a){var c=this.names[a];if(void 0!==c){for(var d=0;dc;c++)this[c]=a[c];return this},Kinetic.Collection.prototype=[],Kinetic.Collection.prototype.each=function(a){for(var b=0;ba;a++)b.push(this[a]);return b},Kinetic.Collection.toCollection=function(a){var b,c=new Kinetic.Collection,d=a.length;for(b=0;d>b;b++)c.push(a[b]);return c},Kinetic.Collection.mapMethods=function(a){var b,c=a.length;for(b=0;c>b;b++)!function(b){var c=a[b];Kinetic.Collection.prototype[c]=function(){var a,b=this.length;for(args=[].slice.call(arguments),a=0;b>a;a++)this[a][c].apply(this[a],args)}}(b)},Kinetic.Transform=function(){this.m=[1,0,0,1,0,0]},Kinetic.Transform.prototype={translate:function(a,b){this.m[4]+=this.m[0]*a+this.m[2]*b,this.m[5]+=this.m[1]*a+this.m[3]*b},scale:function(a,b){this.m[0]*=a,this.m[1]*=a,this.m[2]*=b,this.m[3]*=b},rotate:function(a){var b=Math.cos(a),c=Math.sin(a),d=this.m[0]*b+this.m[2]*c,e=this.m[1]*b+this.m[3]*c,f=this.m[0]*-c+this.m[2]*b,g=this.m[1]*-c+this.m[3]*b;this.m[0]=d,this.m[1]=e,this.m[2]=f,this.m[3]=g},getTranslation:function(){return{x:this.m[4],y:this.m[5]}},skew:function(a,b){var c=this.m[0]+this.m[2]*b,d=this.m[1]+this.m[3]*b,e=this.m[2]+this.m[0]*a,f=this.m[3]+this.m[1]*a;this.m[0]=c,this.m[1]=d,this.m[2]=e,this.m[3]=f},multiply:function(a){var b=this.m[0]*a.m[0]+this.m[2]*a.m[1],c=this.m[1]*a.m[0]+this.m[3]*a.m[1],d=this.m[0]*a.m[2]+this.m[2]*a.m[3],e=this.m[1]*a.m[2]+this.m[3]*a.m[3],f=this.m[0]*a.m[4]+this.m[2]*a.m[5]+this.m[4],g=this.m[1]*a.m[4]+this.m[3]*a.m[5]+this.m[5];this.m[0]=b,this.m[1]=c,this.m[2]=d,this.m[3]=e,this.m[4]=f,this.m[5]=g},invert:function(){var a=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),b=this.m[3]*a,c=-this.m[1]*a,d=-this.m[2]*a,e=this.m[0]*a,f=a*(this.m[2]*this.m[5]-this.m[3]*this.m[4]),g=a*(this.m[1]*this.m[4]-this.m[0]*this.m[5]);this.m[0]=b,this.m[1]=c,this.m[2]=d,this.m[3]=e,this.m[4]=f,this.m[5]=g},getMatrix:function(){return this.m},setAbsolutePosition:function(a,b){var c=this.m[0],d=this.m[1],e=this.m[2],f=this.m[3],g=this.m[4],h=this.m[5],i=(c*(b-h)-d*(a-g))/(c*f-d*e),j=(a-g-e*i)/c;this.translate(j,i)}};var a="canvas",b="2d",c="[object Array]",d="[object Number]",e="[object String]",f=Math.PI/180,g=180/Math.PI,h="#",i="",j="0",k="Kinetic warning: ",l="Kinetic error: ",m="rgb(",n={aqua:[0,255,255],lime:[0,255,0],silver:[192,192,192],black:[0,0,0],maroon:[128,0,0],teal:[0,128,128],blue:[0,0,255],navy:[0,0,128],white:[255,255,255],fuchsia:[255,0,255],olive:[128,128,0],yellow:[255,255,0],orange:[255,165,0],gray:[128,128,128],purple:[128,0,128],green:[0,128,0],red:[255,0,0],pink:[255,192,203],cyan:[0,255,255],transparent:[255,255,255,0]},o=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;Kinetic.Util={_isElement:function(a){return!(!a||1!=a.nodeType)},_isFunction:function(a){return!!(a&&a.constructor&&a.call&&a.apply)},_isObject:function(a){return!!a&&a.constructor==Object},_isArray:function(a){return Object.prototype.toString.call(a)==c},_isNumber:function(a){return Object.prototype.toString.call(a)==d},_isString:function(a){return Object.prototype.toString.call(a)==e},_hasMethods:function(a){var b,c=[];for(b in a)this._isFunction(a[b])&&c.push(b);return c.length>0},_isInDocument:function(a){for(;a=a.parentNode;)if(a==document)return!0;return!1},_simplifyArray:function(a){var b,c,d=[],e=a.length,f=Kinetic.Util;for(b=0;e>b;b++)c=a[b],f._isNumber(c)?c=Math.round(1e3*c)/1e3:f._isString(c)||(c=c.toString()),d.push(c);return d},_getXY:function(a){if(this._isNumber(a))return{x:a,y:a};if(this._isArray(a)){if(1===a.length){var b=a[0];if(this._isNumber(b))return{x:b,y:b};if(this._isArray(b))return{x:b[0],y:b[1]};if(this._isObject(b))return b}else if(a.length>=2)return{x:a[0],y:a[1]}}else if(this._isObject(a))return a;return null},_getSize:function(a){if(this._isNumber(a))return{width:a,height:a};if(this._isArray(a))if(1===a.length){var b=a[0];if(this._isNumber(b))return{width:b,height:b};if(this._isArray(b)){if(b.length>=4)return{width:b[2],height:b[3]};if(b.length>=2)return{width:b[0],height:b[1]}}else if(this._isObject(b))return b}else{if(a.length>=4)return{width:a[2],height:a[3]};if(a.length>=2)return{width:a[0],height:a[1]}}else if(this._isObject(a))return a;return null},_getPoints:function(a){var b,c,d=[];if(void 0===a)return[];if(c=a.length,this._isArray(a[0])){for(b=0;c>b;b++)d.push({x:a[b][0],y:a[b][1]});return d}if(this._isObject(a[0]))return a;for(b=0;c>b;b+=2)d.push({x:a[b],y:a[b+1]});return d},_getImage:function(c,d){var e,f,g;c?this._isElement(c)?d(c):this._isString(c)?(e=new Image,e.onload=function(){d(e)},e.src=c):c.data?(f=document.createElement(a),f.width=c.width,f.height=c.height,_context=f.getContext(b),_context.putImageData(c,0,0),g=f.toDataURL(),e=new Image,e.onload=function(){d(e)},e.src=g):d(null):d(null)},_rgbToHex:function(a,b,c){return((1<<24)+(a<<16)+(b<<8)+c).toString(16).slice(1)},_hexToRgb:function(a){a=a.replace(h,i);var b=parseInt(a,16);return{r:255&b>>16,g:255&b>>8,b:255&b}},getRandomColor:function(){for(var a=(16777215*Math.random()<<0).toString(16);a.length<6;)a=j+a;return h+a},get:function(a,b){return void 0===a?b:a},getRGB:function(a){var b;return a in n?(b=n[a],{r:b[0],g:b[1],b:b[2]}):a[0]===h?this._hexToRgb(a.substring(1)):a.substr(0,4)===m?(b=o.exec(a.replace(/ /g,"")),{r:parseInt(b[1],10),g:parseInt(b[2],10),b:parseInt(b[3],10)}):{r:0,g:0,b:0}},_merge:function(a,b){var c=this._clone(b);for(var d in a)c[d]=this._isObject(a[d])?this._merge(a[d],c[d]):a[d];return c},_clone:function(a){var b={};for(var c in a)b[c]=this._isObject(a[c])?this._clone(a[c]):a[c];return b},_degToRad:function(a){return a*f},_radToDeg:function(a){return a*g},_capitalize:function(a){return a.charAt(0).toUpperCase()+a.slice(1)},error:function(a){throw new Error(l+a)},warn:function(a){window.console&&console.warn&&console.warn(k+a)},extend:function(a,b){for(var c in b.prototype)c in a.prototype||(a.prototype[c]=b.prototype[c])},addMethods:function(a,b){var c;for(c in b)a.prototype[c]=b[c]},_getControlPoints:function(a,b,c,d){var e=a.x,f=a.y,g=b.x,h=b.y,i=c.x,j=c.y,k=Math.sqrt(Math.pow(g-e,2)+Math.pow(h-f,2)),l=Math.sqrt(Math.pow(i-g,2)+Math.pow(j-h,2)),m=d*k/(k+l),n=d*l/(k+l),o=g-m*(i-e),p=h-m*(j-f),q=g+n*(i-e),r=h+n*(j-f);return[{x:o,y:p},{x:q,y:r}]},_expandPoints:function(a,b){var c,d,e=a.length,f=[];for(c=1;e-1>c;c++)d=Kinetic.Util._getControlPoints(a[c-1],a[c],a[c+1],b),f.push(d[0]),f.push(a[c]),f.push(d[1]);return f},_removeLastLetter:function(a){return a.substring(0,a.length-1)}}}(),function(){var a=document.createElement("canvas"),b=a.getContext("2d"),c=window.devicePixelRatio||1,d=b.webkitBackingStorePixelRatio||b.mozBackingStorePixelRatio||b.msBackingStorePixelRatio||b.oBackingStorePixelRatio||b.backingStorePixelRatio||1,e=c/d;Kinetic.Canvas=function(a){this.init(a)},Kinetic.Canvas.prototype={init:function(a){a=a||{};var b=a.pixelRatio||Kinetic.pixelRatio||e;this.pixelRatio=b,this._canvas=document.createElement("canvas"),this._canvas.style.padding=0,this._canvas.style.margin=0,this._canvas.style.border=0,this._canvas.style.background="transparent",this._canvas.style.position="absolute",this._canvas.style.top=0,this._canvas.style.left=0},getContext:function(){return this.context},getPixelRatio:function(){return this.pixelRatio},setPixelRatio:function(a){this.pixelRatio=a,this.setSize(this.getWidth(),this.getHeight())},setWidth:function(a){this.width=this._canvas.width=a*this.pixelRatio,this._canvas.style.width=a+"px"},setHeight:function(a){this.height=this._canvas.height=a*this.pixelRatio,this._canvas.style.height=a+"px"},getWidth:function(){return this.width},getHeight:function(){return this.height},setSize:function(a,b){this.setWidth(a),this.setHeight(b)},toDataURL:function(a,b){try{return this._canvas.toDataURL(a,b)}catch(c){try{return this._canvas.toDataURL()}catch(d){return Kinetic.Util.warn("Unable to get data URL. "+d.message),""}}}},Kinetic.SceneCanvas=function(a){a=a||{};var b=a.width||0,c=a.height||0;Kinetic.Canvas.call(this,a),this.context=new Kinetic.SceneContext(this),this.setSize(b,c)},Kinetic.SceneCanvas.prototype={setWidth:function(a){var b=this.pixelRatio,c=this.getContext()._context;Kinetic.Canvas.prototype.setWidth.call(this,a),c.scale(b,b)},setHeight:function(a){var b=this.pixelRatio,c=this.getContext()._context;Kinetic.Canvas.prototype.setHeight.call(this,a),c.scale(b,b)}},Kinetic.Util.extend(Kinetic.SceneCanvas,Kinetic.Canvas),Kinetic.HitCanvas=function(a){a=a||{};var b=a.width||0,c=a.height||0;Kinetic.Canvas.call(this,a),this.context=new Kinetic.HitContext(this),this.setSize(b,c)},Kinetic.Util.extend(Kinetic.HitCanvas,Kinetic.Canvas)}(),function(){var a=",",b="(",c=")",d="([",e="])",f=";",g="()",h="=",i=["arc","arcTo","beginPath","bezierCurveTo","clearRect","clip","closePath","createLinearGradient","createPattern","createRadialGradient","drawImage","fill","fillText","getImageData","lineTo","moveTo","putImageData","quadraticCurveTo","rect","restore","rotate","save","scale","setLineDash","setTransform","stroke","strokeText","transform","translate"];Kinetic.Context=function(a){this.init(a)},Kinetic.Context.prototype={init:function(a){this.canvas=a,this._context=a._canvas.getContext("2d"),Kinetic.enableTrace&&(this.traceArr=[],this._enableTrace())},fillShape:function(a){a.getFillEnabled()&&this._fill(a)},strokeShape:function(a){a.getStrokeEnabled()&&this._stroke(a)},fillStrokeShape:function(a){var b=a.getFillEnabled();b&&this._fill(a),a.getStrokeEnabled()&&this._stroke(a)},getTrace:function(i){var j,k,l,m,n=this.traceArr,o=n.length,p="";for(j=0;o>j;j++)k=n[j],l=k.method,l?(m=k.args,p+=l,p+=i?g:Kinetic.Util._isArray(m[0])?d+m.join(a)+e:b+m.join(a)+c):(p+=k.property,i||(p+=h+k.val)),p+=f;return p},clearTrace:function(){this.traceArr=[]},_trace:function(a){var b,c=this.traceArr;c.push(a),b=c.length,b>=Kinetic.traceArrMax&&c.shift()},reset:function(){var a=this.getCanvas().getPixelRatio();this.setTransform(1*a,0,0,1*a,0,0)},getCanvas:function(){return this.canvas},clear:function(){var a,b,c=[].slice.call(arguments),d=this.getCanvas();c.length?(a=Kinetic.Util._getXY(c),b=Kinetic.Util._getSize(c),this.clearRect(a.x||0,a.y||0,b.width,b.height)):this.clearRect(0,0,d.getWidth(),d.getHeight())},_applyLineCap:function(a){var b=a.getLineCap();b&&this.setAttr("lineCap",b)},_applyOpacity:function(a){var b=a.getAbsoluteOpacity();1!==b&&this.setAttr("globalAlpha",b)},_applyLineJoin:function(a){var b=a.getLineJoin();b&&this.setAttr("lineJoin",b)},_applyAncestorTransforms:function(a){var b=a.getAbsoluteTransform().getMatrix();this.transform(b[0],b[1],b[2],b[3],b[4],b[5])},_clip:function(a){var b=a.getClipX()||0,c=a.getClipY()||0,d=a.getClipWidth(),e=a.getClipHeight();this.save(),this._applyAncestorTransforms(a),this.beginPath(),this.rect(b,c,d,e),this.clip(),this.reset(),a._drawChildren(this.getCanvas()),this.restore()},setAttr:function(a,b){this._context[a]=b},arc:function(){var a=arguments;this._context.arc(a[0],a[1],a[2],a[3],a[4],a[5])},beginPath:function(){this._context.beginPath()},bezierCurveTo:function(){var a=arguments;this._context.bezierCurveTo(a[0],a[1],a[2],a[3],a[4],a[5])},clearRect:function(){var a=arguments;this._context.clearRect(a[0],a[1],a[2],a[3])},clip:function(){this._context.clip()},closePath:function(){this._context.closePath()},createLinearGradient:function(){var a=arguments;return this._context.createLinearGradient(a[0],a[1],a[2],a[3])},createPattern:function(){var a=arguments;return this._context.createPattern(a[0],a[1])},createRadialGradient:function(){var a=arguments;return this._context.createRadialGradient(a[0],a[1],a[2],a[3],a[4],a[5])},drawImage:function(){var a=arguments,b=this._context;3===a.length?b.drawImage(a[0],a[1],a[2]):5===a.length?b.drawImage(a[0],a[1],a[2],a[3],a[4]):9===a.length&&b.drawImage(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8])},fill:function(){this._context.fill()},fillText:function(){var a=arguments;this._context.fillText(a[0],a[1],a[2])},getImageData:function(){var a=arguments;return this._context.getImageData(a[0],a[1],a[2],a[3])},lineTo:function(){var a=arguments;this._context.lineTo(a[0],a[1])},moveTo:function(){var a=arguments;this._context.moveTo(a[0],a[1])},rect:function(){var a=arguments;this._context.rect(a[0],a[1],a[2],a[3])},putImageData:function(){var a=arguments;this._context.putImageData(a[0],a[1],a[2])},quadraticCurveTo:function(){var a=arguments;this._context.quadraticCurveTo(a[0],a[1],a[2],a[3])},restore:function(){this._context.restore()},rotate:function(){var a=arguments;this._context.rotate(a[0])},save:function(){this._context.save()},scale:function(){var a=arguments;this._context.scale(a[0],a[1])},setLineDash:function(){var a=arguments,b=this._context;this._context.setLineDash?b.setLineDash(a[0]):"mozDash"in b?b.mozDash=a[0]:"webkitLineDash"in b&&(b.webkitLineDash=a[0])},setTransform:function(){var a=arguments;this._context.setTransform(a[0],a[1],a[2],a[3],a[4],a[5])},stroke:function(){this._context.stroke()},strokeText:function(){var a=arguments;this._context.strokeText(a[0],a[1],a[2])},transform:function(){var a=arguments;this._context.transform(a[0],a[1],a[2],a[3],a[4],a[5])},translate:function(){var a=arguments;this._context.translate(a[0],a[1])},_enableTrace:function(){var a,b,c=this,d=i.length,e=Kinetic.Util._simplifyArray,f=this.setAttr;for(a=0;d>a;a++)!function(a){var d,f=c[a];c[a]=function(){return b=e(Array.prototype.slice.call(arguments,0)),d=f.apply(c,arguments),c._trace({method:a,args:b}),d}}(i[a]);c.setAttr=function(){f.apply(c,arguments),c._trace({property:arguments[0],val:arguments[1]})}}},Kinetic.SceneContext=function(a){Kinetic.Context.call(this,a)},Kinetic.SceneContext.prototype={_fillColor:function(a){var b=a.getFill();this.setAttr("fillStyle",b),a._fillFunc(this)},_fillPattern:function(a){var b=a.getFillPatternImage(),c=a.getFillPatternX(),d=a.getFillPatternY(),e=a.getFillPatternScale(),f=a.getFillPatternRotation(),g=a.getFillPatternOffset(),h=a.getFillPatternRepeat();(c||d)&&this.translate(c||0,d||0),f&&this.rotate(f),e&&this.scale(e.x,e.y),g&&this.translate(-1*g.x,-1*g.y),this.setAttr("fillStyle",this.createPattern(b,h||"repeat")),this.fill()},_fillLinearGradient:function(a){var b=a.getFillLinearGradientStartPoint(),c=a.getFillLinearGradientEndPoint(),d=a.getFillLinearGradientColorStops(),e=this.createLinearGradient(b.x,b.y,c.x,c.y);if(d){for(var f=0;fc;c++)d=j[c],e=d.split(f),h=e[0],i=e[1]||g,this.eventListeners[h]||(this.eventListeners[h]=[]),this.eventListeners[h].push({name:i,handler:b});return this},off:function(a){var b,c,d,e,g,h,i=a.split(q),j=i.length;for(b=0;j>b;b++)if(d=i[b],e=d.split(f),g=e[0],h=e[1],g)this.eventListeners[g]&&this._off(g,h);else for(c in this.eventListeners)this._off(c,h);return this},remove:function(){var c=this.getParent();return c&&c.children&&(c.children.splice(this.index,1),c._setChildrenIndices(),delete this.parent),this._clearSelfAndChildrenCache(r),this._clearSelfAndChildrenCache(b),this._clearSelfAndChildrenCache(u),this._clearSelfAndChildrenCache(k),this._clearSelfAndChildrenCache(a),this},destroy:function(){Kinetic._removeId(this.getId()),Kinetic._removeName(this.getName(),this._id),this.remove()},getAttr:function(a){var b=h+Kinetic.Util._capitalize(a);return Kinetic.Util._isFunction(this[b])?this[b]():this.attrs[a]},getAncestors:function(){for(var a=this.getParent(),b=new Kinetic.Collection;a;)b.push(a),a=a.getParent();return b},setAttr:function(){var a=Array.prototype.slice.call(arguments),b=a[0],c=o+Kinetic.Util._capitalize(b),d=this[c];return a.shift(),Kinetic.Util._isFunction(d)?d.apply(this,a):this.attrs[b]=a[0],this},getAttrs:function(){return this.attrs||{}},setAttrs:function(a){var b,c;if(a)for(b in a)b===e||(c=o+Kinetic.Util._capitalize(b),Kinetic.Util._isFunction(this[c])?this[c](a[b]):this._setAttr(b,a[b]));return this},isListening:function(){return this._getCache(k,this._isListening)},_isListening:function(){var a=this.getListening(),b=this.getParent();return a&&b&&!b.isListening()?!1:a},isVisible:function(){return this._getCache(u,this._isVisible)},_isVisible:function(){var a=this.getVisible(),b=this.getParent();return a&&b&&!b.isVisible()?!1:a},show:function(){return this.setVisible(!0),this},hide:function(){return this.setVisible(!1),this},getZIndex:function(){return this.index||0},getAbsoluteZIndex:function(){function a(i){for(b=[],c=i.length,d=0;c>d;d++)e=i[d],h++,e.nodeType!==p&&(b=b.concat(e.getChildren().toArray())),e._id===g._id&&(d=c);b.length>0&&b[0].getLevel()<=f&&a(b)}var b,c,d,e,f=this.getLevel(),g=this,h=0;return g.nodeType!==t&&a(g.getStage().getChildren()),h},getLevel:function(){for(var a=0,b=this.parent;b;)a++,b=b.parent;return a},setPosition:function(){var a=Kinetic.Util._getXY([].slice.call(arguments));return this.setX(a.x),this.setY(a.y),this},getPosition:function(){return{x:this.getX(),y:this.getY()}},getAbsolutePosition:function(){var a=this.getAbsoluteTransform().getMatrix(),b=new Kinetic.Transform,c=this.getOffset();return b.m=a.slice(),b.translate(c.x,c.y),b.getTranslation()},setAbsolutePosition:function(){var a,b=Kinetic.Util._getXY([].slice.call(arguments)),c=this._clearTransform();return this.attrs.x=c.x,this.attrs.y=c.y,delete c.x,delete c.y,a=this.getAbsoluteTransform(),a.invert(),a.translate(b.x,b.y),b={x:this.attrs.x+a.getTranslation().x,y:this.attrs.y+a.getTranslation().y},this.setPosition(b.x,b.y),this._setTransform(c),this},_setTransform:function(a){var c;for(c in a)this.attrs[c]=a[c];this._clearCache(s),this._clearSelfAndChildrenCache(b)},_clearTransform:function(){var a={x:this.getX(),y:this.getY(),rotation:this.getRotation(),scaleX:this.getScaleX(),scaleY:this.getScaleY(),offsetX:this.getOffsetX(),offsetY:this.getOffsetY(),skewX:this.getSkewX(),skewY:this.getSkewY()};return this.attrs.x=0,this.attrs.y=0,this.attrs.rotation=0,this.attrs.scaleX=1,this.attrs.scaleY=1,this.attrs.offsetX=0,this.attrs.offsetY=0,this.attrs.skewX=0,this.attrs.skewY=0,this._clearCache(s),this._clearSelfAndChildrenCache(b),a},move:function(){var a=Kinetic.Util._getXY([].slice.call(arguments)),b=this.getX(),c=this.getY();return void 0!==a.x&&(b+=a.x),void 0!==a.y&&(c+=a.y),this.setPosition(b,c),this},_eachAncestorReverse:function(a,b){var c,d,e=[],f=this.getParent();for(b&&e.unshift(this);f;)e.unshift(f),f=f.parent;for(c=e.length,d=0;c>d;d++)a(e[d])},rotate:function(a){return this.setRotation(this.getRotation()+a),this},rotateDeg:function(a){return this.setRotation(this.getRotation()+Kinetic.Util._degToRad(a)),this},moveToTop:function(){var a=this.index;return this.parent.children.splice(a,1),this.parent.children.push(this),this.parent._setChildrenIndices(),!0},moveUp:function(){var a=this.index,b=this.parent.getChildren().length;return b-1>a?(this.parent.children.splice(a,1),this.parent.children.splice(a+1,0,this),this.parent._setChildrenIndices(),!0):!1},moveDown:function(){var a=this.index;return a>0?(this.parent.children.splice(a,1),this.parent.children.splice(a-1,0,this),this.parent._setChildrenIndices(),!0):!1},moveToBottom:function(){var a=this.index;return a>0?(this.parent.children.splice(a,1),this.parent.children.unshift(this),this.parent._setChildrenIndices(),!0):!1},setZIndex:function(a){var b=this.index;return this.parent.children.splice(b,1),this.parent.children.splice(a,0,this),this.parent._setChildrenIndices(),this},getAbsoluteOpacity:function(){return this._getCache(a,this._getAbsoluteOpacity)},_getAbsoluteOpacity:function(){var a=this.getOpacity();return this.getParent()&&(a*=this.getParent().getAbsoluteOpacity()),a},moveTo:function(a){return Kinetic.Node.prototype.remove.call(this),a.add(this),this},toObject:function(){var a,b,c=Kinetic.Util,d={},e=this.getAttrs();d.attrs={};for(a in e)b=e[a],c._isFunction(b)||c._isElement(b)||c._isObject(b)&&c._hasMethods(b)||(d.attrs[a]=b);return d.className=this.getClassName(),d},toJSON:function(){return JSON.stringify(this.toObject())},getParent:function(){return this.parent},getLayer:function(){return this.getParent().getLayer()},getStage:function(){return this._getCache(r,this._getStage)},_getStage:function(){var a=this.getParent();return a?a.getStage():void 0},fire:function(a,b,c){return c?this._fireAndBubble(a,b||{}):this._fire(a,b||{}),this},getAbsoluteTransform:function(){return this._getCache(b,this._getAbsoluteTransform)},_getAbsoluteTransform:function(){var a,b=new Kinetic.Transform;return this._eachAncestorReverse(function(c){a=c.getTransform(),b.multiply(a)},!0),b},_getTransform:function(){var a=new Kinetic.Transform,b=this.getX(),c=this.getY(),d=this.getRotation(),e=this.getScaleX(),f=this.getScaleY(),g=this.getSkewX(),h=this.getSkewY(),i=this.getOffsetX(),j=this.getOffsetY();return(0!==b||0!==c)&&a.translate(b,c),0!==d&&a.rotate(d),(0!==g||0!==h)&&a.skew(g,h),(1!==e||1!==f)&&a.scale(e,f),(0!==i||0!==j)&&a.translate(-1*i,-1*j),a},clone:function(a){var b,c,d,e,f,g=this.getClassName(),h=new Kinetic[g](this.attrs);for(b in this.eventListeners)for(c=this.eventListeners[b],d=c.length,e=0;d>e;e++)f=c[e],f.name.indexOf(j)<0&&(h.eventListeners[b]||(h.eventListeners[b]=[]),h.eventListeners[b].push(f));return h.setAttrs(a),h},toDataURL:function(a){a=a||{};var b=a.mimeType||null,c=a.quality||null,d=this.getStage(),e=a.x||0,f=a.y||0,g=new Kinetic.SceneCanvas({width:a.width||d.getWidth(),height:a.height||d.getHeight(),pixelRatio:1}),h=g.getContext();return h.save(),(e||f)&&h.translate(-1*e,-1*f),this.drawScene(g),h.restore(),g.toDataURL(b,c)},toImage:function(a){Kinetic.Util._getImage(this.toDataURL(a),function(b){a.callback(b)})},setSize:function(){var a=Kinetic.Util._getSize(Array.prototype.slice.call(arguments));return this.setWidth(a.width),this.setHeight(a.height),this},getSize:function(){return{width:this.getWidth(),height:this.getHeight()}},getWidth:function(){return this.attrs.width||0},getHeight:function(){return this.attrs.height||0},getClassName:function(){return this.className||this.nodeType},getType:function(){return this.nodeType},_get:function(a){return this.nodeType===a?[this]:[]},_off:function(a,b){var c,d,e=this.eventListeners[a];for(c=0;cd;d++)e[d].handler.call(this,b)},draw:function(){return this.drawScene(),this.drawHit(),this},shouldDrawHit:function(){return this.isListening()&&this.isVisible()&&!Kinetic.isDragging()},isDraggable:function(){return!1},getTransform:function(){return this._getCache(s,this._getTransform)}}),Kinetic.Node.create=function(a,b){return this._createNode(JSON.parse(a),b)},Kinetic.Node._createNode=function(a,b){var c,d,e,f=Kinetic.Node.prototype.getClassName.call(a),g=a.children;if(b&&(a.attrs.container=b),c=new Kinetic[f](a.attrs),g)for(d=g.length,e=0;d>e;e++)c.add(this._createNode(g[e]));return c},Kinetic.Factory.addGetterSetter(Kinetic.Node,"x",0),Kinetic.Factory.addGetterSetter(Kinetic.Node,"y",0),Kinetic.Factory.addGetterSetter(Kinetic.Node,"opacity",1),Kinetic.Factory.addGetter(Kinetic.Node,"name"),Kinetic.Factory.addGetter(Kinetic.Node,"id"),Kinetic.Factory.addRotationGetterSetter(Kinetic.Node,"rotation",0),Kinetic.Factory.addPointGetterSetter(Kinetic.Node,"scale",1),Kinetic.Factory.addPointGetterSetter(Kinetic.Node,"skew",0),Kinetic.Factory.addPointGetterSetter(Kinetic.Node,"offset",0),Kinetic.Factory.addSetter(Kinetic.Node,"width"),Kinetic.Factory.addSetter(Kinetic.Node,"height"),Kinetic.Factory.addGetterSetter(Kinetic.Node,"listening",!0),Kinetic.Factory.addGetterSetter(Kinetic.Node,"visible",!0),Kinetic.Collection.mapMethods(["on","off","remove","destroy","show","hide","move","rotate","moveToTop","moveUp","moveDown","moveToBottom","moveTo","fire","draw"])}(),function(){function a(a){window.setTimeout(a,1e3/60)}var b=500;Kinetic.Animation=function(a,b){this.func=a,this.setLayers(b),this.id=Kinetic.Animation.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:(new Date).getTime()}},Kinetic.Animation.prototype={setLayers:function(a){var b=[];b=a?a.length>0?a:[a]:[],this.layers=b},getLayers:function(){return this.layers},addLayer:function(a){var b,c,d=this.layers;if(d){for(b=d.length,c=0;b>c;c++)if(d[c]._id===a._id)return!1}else this.layers=[];return this.layers.push(a),!0},isRunning:function(){for(var a=Kinetic.Animation,b=a.animations,c=0;ce;e++)if(c[e].id===b){this.animations.splice(e,1);break}},Kinetic.Animation._runFrames=function(){var a,b,c,d,e,f,g,h,i={},j=this.animations;for(d=0;de;e++)g=b[e],void 0!==g._id&&(i[g._id]=g);c&&c.call(a,a.frame)}for(h in i)i[h].draw()},Kinetic.Animation._animationLoop=function(){var a=this;this.animations.length>0?(this._runFrames(),Kinetic.Animation.requestAnimFrame(function(){a._animationLoop()})):this.animRunning=!1},Kinetic.Animation._handleAnimation=function(){var a=this;this.animRunning||(this.animRunning=!0,a._animationLoop())},RAF=function(){return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||a}(),Kinetic.Animation.requestAnimFrame=function(b){var c=Kinetic.DD&&Kinetic.DD.isDragging?a:RAF;c(b)};var c=Kinetic.Node.prototype.moveTo;Kinetic.Node.prototype.moveTo=function(a){c.call(this,a)},Kinetic.Layer.prototype.batchDraw=function(){var a=this;this.batchAnim||(this.batchAnim=new Kinetic.Animation(function(){a.lastBatchDrawTime&&(new Date).getTime()-a.lastBatchDrawTime>b&&a.batchAnim.stop()},this)),this.lastBatchDrawTime=(new Date).getTime(),this.batchAnim.isRunning()||(this.draw(),this.batchAnim.start())},Kinetic.Stage.prototype.batchDraw=function(){this.getChildren().each(function(a){a.batchDraw()})}}(),function(){var a={node:1,duration:1,easing:1,onFinish:1,yoyo:1},b=1,c=2,d=3,e=0;Kinetic.Tween=function(b){var c,d=this,g=b.node,h=g._id,i=b.duration||1,j=b.easing||Kinetic.Easings.Linear,k=!!b.yoyo;this.node=g,this._id=e++,this.anim=new Kinetic.Animation(function(){d.tween.onEnterFrame()},g.getLayer()||g.getLayers()),this.tween=new f(c,function(a){d._tweenFunc(a)},j,0,1,1e3*i,k),this._addListeners(),Kinetic.Tween.attrs[h]||(Kinetic.Tween.attrs[h]={}),Kinetic.Tween.attrs[h][this._id]||(Kinetic.Tween.attrs[h][this._id]={}),Kinetic.Tween.tweens[h]||(Kinetic.Tween.tweens[h]={});for(c in b)void 0===a[c]&&this._addAttr(c,b[c]);this.reset(),this.onFinish=b.onFinish,this.onReset=b.onReset},Kinetic.Tween.attrs={},Kinetic.Tween.tweens={},Kinetic.Tween.prototype={_addAttr:function(a,b){var c,d,e,f,g,h,i,j=this.node,k=j._id;if(e=Kinetic.Tween.tweens[k][a],e&&delete Kinetic.Tween.attrs[k][e][a],c=j.getAttr(a),Kinetic.Util._isArray(b))for(b=Kinetic.Util._getPoints(b),d=[],g=b.length,f=0;g>f;f++)h=c[f],i=b[f],d.push({x:i.x-h.x,y:i.y-h.y});else d=b-c;Kinetic.Tween.attrs[k][this._id][a]={start:c,diff:d},Kinetic.Tween.tweens[k][a]=this._id},_tweenFunc:function(a){var b,c,d,e,f,g,h,i,j,k=this.node,l=Kinetic.Tween.attrs[k._id][this._id];for(b in l){if(c=l[b],d=c.start,e=c.diff,Kinetic.Util._isArray(d))for(f=[],h=d.length,g=0;h>g;g++)i=d[g],j=e[g],f.push({x:i.x+j.x*a,y:i.y+j.y*a});else f=d+e*a;k.setAttr(b,f)}},_addListeners:function(){var a=this;this.tween.onPlay=function(){a.anim.start()},this.tween.onReverse=function(){a.anim.start()},this.tween.onPause=function(){a.anim.stop()},this.tween.onFinish=function(){a.onFinish&&a.onFinish()},this.tween.onReset=function(){a.onReset&&a.onReset()}},play:function(){return this.tween.play(),this},reverse:function(){return this.tween.reverse(),this},reset:function(){var a=this.node;return this.tween.reset(),(a.getLayer()||a.getLayers()).draw(),this},seek:function(a){var b=this.node;return this.tween.seek(1e3*a),(b.getLayer()||b.getLayers()).draw(),this},pause:function(){return this.tween.pause(),this},finish:function(){var a=this.node;return this.tween.finish(),(a.getLayer()||a.getLayers()).draw(),this},destroy:function(){var a,b=this.node._id,c=this._id,d=Kinetic.Tween.tweens[b];this.pause();for(a in d)delete Kinetic.Tween.tweens[b][a];delete Kinetic.Tween.attrs[b][c]}};var f=function(a,b,c,d,e,f,g){this.prop=a,this.propFunc=b,this.begin=d,this._pos=d,this.duration=f,this._change=0,this.prevPos=0,this.yoyo=g,this._time=0,this._position=0,this._startTime=0,this._finish=0,this.func=c,this._change=e-this.begin,this.pause()};f.prototype={fire:function(a){var b=this[a];b&&b()},setTime:function(a){a>this.duration?this.yoyo?(this._time=this.duration,this.reverse()):this.finish():0>a?this.yoyo?(this._time=0,this.play()):this.reset():(this._time=a,this.update())},getTime:function(){return this._time},setPosition:function(a){this.prevPos=this._pos,this.propFunc(a),this._pos=a},getPosition:function(a){return void 0===a&&(a=this._time),this.func(a,this.begin,this._change,this.duration)},play:function(){this.state=c,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")},reverse:function(){this.state=d,this._time=this.duration-this._time,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onReverse")},seek:function(a){this.pause(),this._time=a,this.update(),this.fire("onSeek")},reset:function(){this.pause(),this._time=0,this.update(),this.fire("onReset")},finish:function(){this.pause(),this._time=this.duration,this.update(),this.fire("onFinish")},update:function(){this.setPosition(this.getPosition(this._time))},onEnterFrame:function(){var a=this.getTimer()-this._startTime;this.state===c?this.setTime(a):this.state===d&&this.setTime(this.duration-a)},pause:function(){this.state=b,this.fire("onPause")},getTimer:function(){return(new Date).getTime()}},Kinetic.Easings={BackEaseIn:function(a,b,c,d){var e=1.70158;return c*(a/=d)*a*((e+1)*a-e)+b},BackEaseOut:function(a,b,c,d){var e=1.70158;return c*((a=a/d-1)*a*((e+1)*a+e)+1)+b},BackEaseInOut:function(a,b,c,d){var e=1.70158;return(a/=d/2)<1?c/2*a*a*(((e*=1.525)+1)*a-e)+b:c/2*((a-=2)*a*(((e*=1.525)+1)*a+e)+2)+b},ElasticEaseIn:function(a,b,c,d,e,f){var g=0;return 0===a?b:1==(a/=d)?b+c:(f||(f=.3*d),!e||ea?-.5*e*Math.pow(2,10*(a-=1))*Math.sin((a*d-g)*2*Math.PI/f)+b:.5*e*Math.pow(2,-10*(a-=1))*Math.sin((a*d-g)*2*Math.PI/f)+c+b)},BounceEaseOut:function(a,b,c,d){return(a/=d)<1/2.75?c*7.5625*a*a+b:2/2.75>a?c*(7.5625*(a-=1.5/2.75)*a+.75)+b:2.5/2.75>a?c*(7.5625*(a-=2.25/2.75)*a+.9375)+b:c*(7.5625*(a-=2.625/2.75)*a+.984375)+b},BounceEaseIn:function(a,b,c,d){return c-Kinetic.Easings.BounceEaseOut(d-a,0,c,d)+b},BounceEaseInOut:function(a,b,c,d){return d/2>a?.5*Kinetic.Easings.BounceEaseIn(2*a,0,c,d)+b:.5*Kinetic.Easings.BounceEaseOut(2*a-d,0,c,d)+.5*c+b},EaseIn:function(a,b,c,d){return c*(a/=d)*a+b},EaseOut:function(a,b,c,d){return-c*(a/=d)*(a-2)+b},EaseInOut:function(a,b,c,d){return(a/=d/2)<1?c/2*a*a+b:-c/2*(--a*(a-2)-1)+b},StrongEaseIn:function(a,b,c,d){return c*(a/=d)*a*a*a*a+b},StrongEaseOut:function(a,b,c,d){return c*((a=a/d-1)*a*a*a*a+1)+b},StrongEaseInOut:function(a,b,c,d){return(a/=d/2)<1?c/2*a*a*a*a*a+b:c/2*((a-=2)*a*a*a*a+2)+b},Linear:function(a,b,c,d){return c*a/d+b}}}(),function(){Kinetic.DD={anim:new Kinetic.Animation,isDragging:!1,offset:{x:0,y:0},node:null,_drag:function(a){var b=Kinetic.DD,c=b.node;c&&(c._setDragPosition(a),b.isDragging||(b.isDragging=!0,c.fire("dragstart",a,!0)),c.fire("dragmove",a,!0))},_endDragBefore:function(a){var b,c,d=Kinetic.DD,e=d.node;e&&(b=e.nodeType,c=e.getLayer(),d.anim.stop(),d.isDragging&&(d.isDragging=!1,Kinetic.listenClickTap=!1,a&&(a.dragEndNode=e)),delete d.node,(c||e).draw())},_endDragAfter:function(a){a=a||{};var b=a.dragEndNode;a&&b&&b.fire("dragend",a,!0)}},Kinetic.Node.prototype.startDrag=function(){var a=Kinetic.DD,b=this.getStage(),c=this.getLayer(),d=b.getPointerPosition(),e=this.getAbsolutePosition();d&&(a.node&&a.node.stopDrag(),a.node=this,a.offset.x=d.x-e.x,a.offset.y=d.y-e.y,a.anim.setLayers(c||this.getLayers()),a.anim.start(),this._setDragPosition())},Kinetic.Node.prototype._setDragPosition=function(a){var b=Kinetic.DD,c=this.getStage().getPointerPosition(),d=this.getDragBoundFunc(),e={x:c.x-b.offset.x,y:c.y-b.offset.y};void 0!==d&&(e=d.call(this,e,a)),this.setAbsolutePosition(e)},Kinetic.Node.prototype.stopDrag=function(){var a=Kinetic.DD,b={};a._endDragBefore(b),a._endDragAfter(b)},Kinetic.Node.prototype.setDraggable=function(a){this._setAttr("draggable",a),this._dragChange()};var a=Kinetic.Node.prototype.destroy;Kinetic.Node.prototype.destroy=function(){var b=Kinetic.DD;b.node&&b.node._id===this._id&&this.stopDrag(),a.call(this)},Kinetic.Node.prototype.isDragging=function(){var a=Kinetic.DD;return a.node&&a.node._id===this._id&&a.isDragging},Kinetic.Node.prototype._listenDrag=function(){var a=this;this._dragCleanup(),"Stage"===this.getClassName()?this.on("contentMousedown.kinetic contentTouchstart.kinetic",function(b){Kinetic.DD.node||a.startDrag(b)}):this.on("mousedown.kinetic touchstart.kinetic",function(b){Kinetic.DD.node||a.startDrag(b)})},Kinetic.Node.prototype._dragChange=function(){if(this.attrs.draggable)this._listenDrag();else{this._dragCleanup();var a=this.getStage(),b=Kinetic.DD;a&&b.node&&b.node._id===this._id&&b.node.stopDrag()}},Kinetic.Node.prototype._dragCleanup=function(){this.off("mousedown.kinetic"),this.off("touchstart.kinetic")},Kinetic.Factory.addGetterSetter(Kinetic.Node,"dragBoundFunc"),Kinetic.Factory.addGetter(Kinetic.Node,"draggable",!1),Kinetic.Node.prototype.isDraggable=Kinetic.Node.prototype.getDraggable;var b=document.getElementsByTagName("html")[0];b.addEventListener("mouseup",Kinetic.DD._endDragBefore,!0),b.addEventListener("touchend",Kinetic.DD._endDragBefore,!0),b.addEventListener("mouseup",Kinetic.DD._endDragAfter,!1),b.addEventListener("touchend",Kinetic.DD._endDragAfter,!1)}(),function(){Kinetic.Util.addMethods(Kinetic.Container,{__init:function(a){this.children=new Kinetic.Collection,Kinetic.Node.call(this,a)},getChildren:function(){return this.children},hasChildren:function(){return this.getChildren().length>0},removeChildren:function(){for(var a,b=this.children;b.length>0;)a=b[0],a.hasChildren()&&a.removeChildren(),a.remove();return this},destroyChildren:function(){for(var a=this.children;a.length>0;)a[0].destroy();return this},add:function(a){var b=this.children;return this._validateAdd(a),a.index=b.length,a.parent=this,b.push(a),this._fire("add",{child:a}),this},destroy:function(){this.hasChildren()&&this.destroyChildren(),Kinetic.Node.prototype.destroy.call(this)},find:function(a){var b,c,d,e,f,g,h,i=[],j=a.replace(/ /g,"").split(","),k=j.length;for(b=0;k>b;b++)if(d=j[b],"#"===d.charAt(0))f=this._getNodeById(d.slice(1)),f&&i.push(f);else if("."===d.charAt(0))e=this._getNodesByName(d.slice(1)),i=i.concat(e);else for(g=this.getChildren(),h=g.length,c=0;h>c;c++)i=i.concat(g[c]._get(d));return Kinetic.Collection.toCollection(i)},_getNodeById:function(a){var b=Kinetic.ids[a];return void 0!==b&&this.isAncestorOf(b)?b:null},_getNodesByName:function(a){var b=Kinetic.names[a]||[];return this._getDescendants(b)},_get:function(a){for(var b=Kinetic.Node.prototype._get.call(this,a),c=this.getChildren(),d=c.length,e=0;d>e;e++)b=b.concat(c[e]._get(a));return b},toObject:function(){var a=Kinetic.Node.prototype.toObject.call(this);a.children=[];for(var b=this.getChildren(),c=b.length,d=0;c>d;d++){var e=b[d];a.children.push(e.toObject())}return a},_getDescendants:function(a){for(var b=[],c=a.length,d=0;c>d;d++){var e=a[d];this.isAncestorOf(e)&&b.push(e)}return b},isAncestorOf:function(a){for(var b=a.getParent();b;){if(b._id===this._id)return!0;b=b.getParent()}return!1},clone:function(a){var b=Kinetic.Node.prototype.clone.call(this,a);return this.getChildren().each(function(a){b.add(a.clone())}),b},getAllIntersections:function(){for(var a=Kinetic.Util._getXY(Array.prototype.slice.call(arguments)),b=[],c=this.find("Shape"),d=c.length,e=0;d>e;e++){var f=c[e];f.isVisible()&&f.intersects(a)&&b.push(f)}return b},_setChildrenIndices:function(){this.children.each(function(a,b){a.index=b})},drawScene:function(a){var b=this.getLayer(),c=this.getClipWidth()&&this.getClipHeight();return!a&&b&&(a=b.getCanvas()),this.isVisible()&&(c?a.getContext()._clip(this):this._drawChildren(a)),this},_drawChildren:function(a){this.children.each(function(b){b.drawScene(a)})},drawHit:function(){var a,b=this.getClipWidth()&&this.getClipHeight()&&"Stage"!==this.nodeType,c=0,d=0,e=[];if(this.shouldDrawHit()){for(b&&(a=this.getLayer().hitCanvas,a.getContext()._clip(this)),e=this.children,d=e.length,c=0;d>c;c++)e[c].drawHit();b&&a.getContext()._context.restore()}return this}}),Kinetic.Util.extend(Kinetic.Container,Kinetic.Node),Kinetic.Container.prototype.get=Kinetic.Container.prototype.find,Kinetic.Factory.addBoxGetterSetter(Kinetic.Container,"clip")}(),function(){function a(a){a.fill()}function b(a){a.stroke()}function c(a){a.fill()}function d(a){a.stroke()}function e(){this._clearCache(f)}var f="hasShadow";Kinetic.Util.addMethods(Kinetic.Shape,{__init:function(f){this.nodeType="Shape",this._fillFunc=a,this._strokeFunc=b,this._fillFuncHit=c,this._strokeFuncHit=d;for(var g,h=Kinetic.shapes;;)if(g=Kinetic.Util.getRandomColor(),g&&!(g in h))break;this.colorKey=g,h[g]=this,Kinetic.Node.call(this,f),this._setDrawFuncs(),this.on("shadowColorChange.kinetic shadowBlurChange.kinetic shadowOffsetChange.kinetic shadowOpacityChange.kinetic",e)},hasChildren:function(){return!1},getChildren:function(){return[]},getContext:function(){return this.getLayer().getContext()},getCanvas:function(){return this.getLayer().getCanvas()},hasShadow:function(){return this._getCache(f,this._hasShadow)},_hasShadow:function(){return this.getShadowEnabled()&&0!==this.getShadowOpacity()&&!!(this.getShadowColor()||this.getShadowBlur()||this.getShadowOffsetX()||this.getShadowOffsetY())},hasFill:function(){return!!(this.getFill()||this.getFillPatternImage()||this.getFillLinearGradientColorStops()||this.getFillRadialGradientColorStops())},hasStroke:function(){return!(!this.getStroke()&&!this.getStrokeWidth())},_get:function(a){return this.className===a||this.nodeType===a?[this]:[]},intersects:function(){var a,b=Kinetic.Util._getXY(Array.prototype.slice.call(arguments)),c=this.getStage(),d=c.bufferHitCanvas;return d.getContext().clear(),this.drawScene(d),a=d.context.getImageData(0|b.x,0|b.y,1,1).data,a[3]>0},enableFill:function(){return this._setAttr("fillEnabled",!0),this},disableFill:function(){return this._setAttr("fillEnabled",!1),this},enableStroke:function(){return this._setAttr("strokeEnabled",!0),this},disableStroke:function(){return this._setAttr("strokeEnabled",!1),this},enableStrokeScale:function(){return this._setAttr("strokeScaleEnabled",!0),this},disableStrokeScale:function(){return this._setAttr("strokeScaleEnabled",!1),this},enableShadow:function(){return this._setAttr("shadowEnabled",!0),this},disableShadow:function(){return this._setAttr("shadowEnabled",!1),this},enableDashArray:function(){return this._setAttr("dashArrayEnabled",!0),this},disableDashArray:function(){return this._setAttr("dashArrayEnabled",!1),this},destroy:function(){return Kinetic.Node.prototype.destroy.call(this),delete Kinetic.shapes[this.colorKey],this},_useBufferCanvas:function(){return(this.hasShadow()||1!==this.getAbsoluteOpacity())&&this.hasFill()&&this.hasStroke()},drawScene:function(a){var b,c,d,e=a||this.getLayer().getCanvas(),f=e.getContext(),g=this.getDrawFunc(),h=this.hasShadow();return g&&this.isVisible()&&(this._useBufferCanvas()?(b=this.getStage(),c=b.bufferCanvas,d=c.getContext(),d.clear(),d.save(),d._applyLineJoin(this),d._applyAncestorTransforms(this),g.call(this,d),d.restore(),f.save(),h&&(f.save(),f._applyShadow(this),f.drawImage(c._canvas,0,0),f.restore()),f._applyOpacity(this),f.drawImage(c._canvas,0,0),f.restore()):(f.save(),f._applyLineJoin(this),f._applyAncestorTransforms(this),h&&(f.save(),f._applyShadow(this),g.call(this,f),f.restore()),f._applyOpacity(this),g.call(this,f),f.restore())),this},drawHit:function(){var a=this.getAttrs(),b=a.drawHitFunc||a.drawFunc,c=this.getLayer().hitCanvas,d=c.getContext();return b&&this.shouldDrawHit()&&(d.save(),d._applyLineJoin(this),d._applyAncestorTransforms(this),b.call(this,d),d.restore()),this},_setDrawFuncs:function(){!this.attrs.drawFunc&&this.drawFunc&&this.setDrawFunc(this.drawFunc),!this.attrs.drawHitFunc&&this.drawHitFunc&&this.setDrawHitFunc(this.drawHitFunc)}}),Kinetic.Util.extend(Kinetic.Shape,Kinetic.Node),Kinetic.Factory.addColorGetterSetter(Kinetic.Shape,"stroke"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"lineJoin"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"lineCap"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"strokeWidth"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"drawFunc"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"drawHitFunc"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"dashArray"),Kinetic.Factory.addColorGetterSetter(Kinetic.Shape,"shadowColor"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"shadowBlur"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"shadowOpacity"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"fillPatternImage"),Kinetic.Factory.addColorGetterSetter(Kinetic.Shape,"fill"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"fillPatternX"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"fillPatternY"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"fillLinearGradientColorStops"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"fillRadialGradientStartRadius"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"fillRadialGradientEndRadius"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"fillRadialGradientColorStops"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"fillPatternRepeat"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"fillEnabled",!0),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"strokeEnabled",!0),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"shadowEnabled",!0),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"dashArrayEnabled",!0),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"fillPriority","color"),Kinetic.Factory.addGetterSetter(Kinetic.Shape,"strokeScaleEnabled",!0),Kinetic.Factory.addPointGetterSetter(Kinetic.Shape,"fillPatternOffset",0),Kinetic.Factory.addPointGetterSetter(Kinetic.Shape,"fillPatternScale",1),Kinetic.Factory.addPointGetterSetter(Kinetic.Shape,"fillLinearGradientStartPoint",0),Kinetic.Factory.addPointGetterSetter(Kinetic.Shape,"fillLinearGradientEndPoint",0),Kinetic.Factory.addPointGetterSetter(Kinetic.Shape,"fillRadialGradientStartPoint",0),Kinetic.Factory.addPointGetterSetter(Kinetic.Shape,"fillRadialGradientEndPoint",0),Kinetic.Factory.addPointGetterSetter(Kinetic.Shape,"shadowOffset",0),Kinetic.Factory.addRotationGetterSetter(Kinetic.Shape,"fillPatternRotation",0)}(),function(){function a(a,b){a.content.addEventListener(b,function(c){a[I+b](c)},!1)}var b="Stage",c="string",d="px",e="mouseout",f="mouseleave",g="mouseover",h="mouseenter",i="mousemove",j="mousedown",k="mouseup",l="click",m="dblclick",n="touchstart",o="touchend",p="tap",q="dbltap",r="touchmove",s="contentMouseout",t="contentMouseover",u="contentMousemove",v="contentMousedown",w="contentMouseup",x="contentClick",y="contentDblclick",z="contentTouchstart",A="contentTouchend",B="contentDbltap",C="contentTouchmove",D="div",E="relative",F="inline-block",G="kineticjs-content",H=" ",I="_",J="container",K="",L=[j,i,k,e,n,r,o,g],M=L.length;Kinetic.Util.addMethods(Kinetic.Stage,{___init:function(a){this.nodeType=b,Kinetic.Container.call(this,a),this._id=Kinetic.idCounter++,this._buildDOM(),this._bindContentEvents(),Kinetic.stages.push(this)},_validateAdd:function(a){"Layer"!==a.getType()&&Kinetic.Util.error("You may only add layers to the stage.")},setContainer:function(a){return typeof a===c&&(a=document.getElementById(a)),this._setAttr(J,a),this},draw:function(){return Kinetic.Node.prototype.draw.call(this),this},setHeight:function(a){return Kinetic.Node.prototype.setHeight.call(this,a),this._resizeDOM(),this},setWidth:function(a){return Kinetic.Node.prototype.setWidth.call(this,a),this._resizeDOM(),this},clear:function(){var a,b=this.children,c=b.length;for(a=0;c>a;a++)b[a].clear();return this},destroy:function(){var a=this.content;Kinetic.Container.prototype.destroy.call(this),a&&Kinetic.Util._isInDocument(a)&&this.getContainer().removeChild(a)},getMousePosition:function(){return this.mousePos},getTouchPosition:function(){return this.touchPos},getPointerPosition:function(){return this.getTouchPosition()||this.getMousePosition()},getStage:function(){return this},getContent:function(){return this.content},toDataURL:function(a){function b(e){var f=i[e],j=f.toDataURL(),k=new Image;k.onload=function(){h.drawImage(k,0,0),e=0;a--)if(b=d[a].getIntersection(c))return b;return null},_resizeDOM:function(){if(this.content){var a,b,c=this.getWidth(),e=this.getHeight(),f=this.getChildren(),g=f.length;for(this.content.style.width=c+d,this.content.style.height=e+d,this.bufferCanvas.setSize(c,e),this.bufferHitCanvas.setSize(c,e),a=0;g>a;a++)b=f[a],b.getCanvas().setSize(c,e),b.hitCanvas.setSize(c,e),b.draw()}},add:function(a){return Kinetic.Container.prototype.add.call(this,a),a.canvas.setSize(this.attrs.width,this.attrs.height),a.hitCanvas.setSize(this.attrs.width,this.attrs.height),a.draw(),this.content.appendChild(a.canvas._canvas),this},getParent:function(){return null},getLayer:function(){return null},getLayers:function(){return this.getChildren()},_setPointerPosition:function(a){a||(a=window.event),this._setMousePosition(a),this._setTouchPosition(a)},_bindContentEvents:function(){var b;for(b=0;M>b;b++)a(this,L[b])},_mouseover:function(a){this._fire(t,a)},_mouseout:function(a){this._setPointerPosition(a);var b=this.targetShape;b&&!Kinetic.isDragging()&&(b._fireAndBubble(e,a),b._fireAndBubble(f,a),this.targetShape=null),this.mousePos=void 0,this._fire(s,a)},_mousemove:function(a){this._setPointerPosition(a);var b=Kinetic.DD,c=this.getIntersection(this.getPointerPosition()),d=c&&c.shape?c.shape:void 0;d?Kinetic.isDragging()||255!==c.pixel[3]||this.targetShape&&this.targetShape._id===d._id?d._fireAndBubble(i,a):(this.targetShape&&(this.targetShape._fireAndBubble(e,a,d),this.targetShape._fireAndBubble(f,a,d)),d._fireAndBubble(g,a,this.targetShape),d._fireAndBubble(h,a,this.targetShape),this.targetShape=d):this.targetShape&&!Kinetic.isDragging()&&(this.targetShape._fireAndBubble(e,a),this.targetShape._fireAndBubble(f,a),this.targetShape=null),this._fire(u,a),b&&b._drag(a),a.preventDefault&&a.preventDefault()},_mousedown:function(a){this._setPointerPosition(a);var b=this.getIntersection(this.getPointerPosition()),c=b&&b.shape?b.shape:void 0;Kinetic.listenClickTap=!0,c&&(this.clickStartShape=c,c._fireAndBubble(j,a)),this._fire(v),a.preventDefault&&a.preventDefault()},_mouseup:function(a){this._setPointerPosition(a);var b=this.getIntersection(this.getPointerPosition()),c=b&&b.shape?b.shape:void 0,d=!1;Kinetic.inDblClickWindow?(d=!0,Kinetic.inDblClickWindow=!1):Kinetic.inDblClickWindow=!0,setTimeout(function(){Kinetic.inDblClickWindow=!1},Kinetic.dblClickWindow),c&&(c._fireAndBubble(k,a),Kinetic.listenClickTap&&c._id===this.clickStartShape._id&&(c._fireAndBubble(l,a),d&&c._fireAndBubble(m,a))),this._fire(w),Kinetic.listenClickTap&&(this._fire(x,a),d&&this._fire(y,a)),Kinetic.listenClickTap=!1,a.preventDefault&&a.preventDefault()},_touchstart:function(a){this._setPointerPosition(a);var b=this.getIntersection(this.getPointerPosition()),c=b&&b.shape?b.shape:void 0;Kinetic.listenClickTap=!0,c&&(this.tapStartShape=c,c._fireAndBubble(n,a),c.isListening()&&a.preventDefault&&a.preventDefault()),this._fire(z,a)},_touchend:function(a){this._setPointerPosition(a);var b=this.getIntersection(this.getPointerPosition()),c=b&&b.shape?b.shape:void 0,d=!1;Kinetic.inDblClickWindow?(d=!0,Kinetic.inDblClickWindow=!1):Kinetic.inDblClickWindow=!0,setTimeout(function(){Kinetic.inDblClickWindow=!1},Kinetic.dblClickWindow),c&&(c._fireAndBubble(o,a),Kinetic.listenClickTap&&c._id===this.tapStartShape._id&&(c._fireAndBubble(p,a),d&&c._fireAndBubble(q,a)),c.isListening()&&a.preventDefault&&a.preventDefault()),Kinetic.listenClickTap&&(this._fire(A,a),d&&this._fire(B,a)),Kinetic.listenClickTap=!1},_touchmove:function(a){this._setPointerPosition(a);var b=Kinetic.DD,c=this.getIntersection(this.getPointerPosition()),d=c&&c.shape?c.shape:void 0;d&&(d._fireAndBubble(r,a),d.isListening()&&a.preventDefault&&a.preventDefault()),this._fire(C,a),b&&b._drag(a)},_setMousePosition:function(a){var b=this._getContentPosition(),c=a.offsetX,d=a.clientX,e=0,f=0;void 0!==c?(e=c,f=a.offsetY):"mozilla"===Kinetic.UA.browser?(e=a.layerX,f=a.layerY):void 0!==d&&b&&(e=d-b.left,f=a.clientY-b.top),this.mousePos={x:e,y:f}},_setTouchPosition:function(a){var b,c,d,e=this._getContentPosition();void 0!==a.touches&&1===a.touches.length&&(b=a.touches[0],c=b.clientX-e.left,d=b.clientY-e.top,this.touchPos={x:c,y:d})},_getContentPosition:function(){var a=this.content.getBoundingClientRect();return{top:a.top,left:a.left}},_buildDOM:function(){var a=this.getContainer();a.innerHTML=K,this.content=document.createElement(D),this.content.style.position=E,this.content.style.display=F,this.content.className=G,a.appendChild(this.content),this.bufferCanvas=new Kinetic.SceneCanvas,this.bufferHitCanvas=new Kinetic.HitCanvas,this._resizeDOM()},_onContent:function(a,b){var c,d,e=a.split(H),f=e.length;for(c=0;f>c;c++)d=e[c],this.content.addEventListener(d,b,!1)}}),Kinetic.Util.extend(Kinetic.Stage,Kinetic.Container),Kinetic.Factory.addGetter(Kinetic.Stage,"container")}(),function(){var a="#",b="beforeDraw",c="draw";Kinetic.Util.addMethods(Kinetic.Layer,{___init:function(a){this.nodeType="Layer",this.canvas=new Kinetic.SceneCanvas,this.hitCanvas=new Kinetic.HitCanvas,Kinetic.Container.call(this,a)},_validateAdd:function(a){var b=a.getType();"Group"!==b&&"Shape"!==b&&Kinetic.Util.error("You may only add groups and shapes to a layer.")},getIntersection:function(){var b,c,d,e=Kinetic.Util._getXY(Array.prototype.slice.call(arguments));if(this.isVisible()&&this.isListening()){if(b=this.hitCanvas.context._context.getImageData(0|e.x,0|e.y,1,1).data,255===b[3])return c=Kinetic.Util._rgbToHex(b[0],b[1],b[2]),d=Kinetic.shapes[a+c],{shape:d,pixel:b};if(b[0]>0||b[1]>0||b[2]>0||b[3]>0)return{pixel:b}}return null},drawScene:function(a){return a=a||this.getCanvas(),this._fire(b,{node:this}),this.getClearBeforeDraw()&&a.getContext().clear(),Kinetic.Container.prototype.drawScene.call(this,a),this._fire(c,{node:this}),this},drawHit:function(){var a=this.getLayer();return a&&a.getClearBeforeDraw()&&a.getHitCanvas().getContext().clear(),Kinetic.Container.prototype.drawHit.call(this),this},getCanvas:function(){return this.canvas},getHitCanvas:function(){return this.hitCanvas},getContext:function(){return this.getCanvas().getContext()},clear:function(){var a=this.getContext(),b=this.getHitCanvas().getContext();return a.clear.apply(a,arguments),b.clear.apply(b,arguments),this},setVisible:function(a){return Kinetic.Node.prototype.setVisible.call(this,a),a?(this.getCanvas()._canvas.style.display="block",this.hitCanvas._canvas.style.display="block"):(this.getCanvas()._canvas.style.display="none",this.hitCanvas._canvas.style.display="none"),this},setZIndex:function(a){Kinetic.Node.prototype.setZIndex.call(this,a);var b=this.getStage();return b&&(b.content.removeChild(this.getCanvas()._canvas),ae;e+=4)c[e+3]>0&&(c[e]=d.r,c[e+1]=d.g,c[e+2]=d.b);Kinetic.Util._getImage(b,function(b){g.imageHitRegion=b,a&&a()})}catch(m){Kinetic.Util.warn("Unable to create image hit region. "+m.message)}},clearImageHitRegion:function(){delete this.imageHitRegion},getWidth:function(){var a=this.getImage();return this.attrs.width||(a?a.width:0)},getHeight:function(){var a=this.getImage();return this.attrs.height||(a?a.height:0)}},Kinetic.Util.extend(Kinetic.Image,Kinetic.Shape),Kinetic.Factory.addFilterGetterSetter=function(a,b,c){this.addGetter(a,b,c),this.addFilterSetter(a,b)},Kinetic.Factory.addFilterSetter=function(a,c){var d=b+Kinetic.Util._capitalize(c);a.prototype[d]=function(a){this._setAttr(c,a),this._applyFilter=!0}},Kinetic.Factory.addGetterSetter(Kinetic.Image,"image"),Kinetic.Factory.addBoxGetterSetter(Kinetic.Image,"crop"),Kinetic.Factory.addFilterGetterSetter(Kinetic.Image,"filter")}(),function(){Kinetic.Polygon=function(a){this.___init(a)},Kinetic.Polygon.prototype={___init:function(a){Kinetic.Shape.call(this,a),this.className="Polygon"},drawFunc:function(a){var b=this.getPoints(),c=b.length;a.beginPath(),a.moveTo(b[0].x,b[0].y);for(var d=1;c>d;d++)a.lineTo(b[d].x,b[d].y);a.closePath(),a.fillStrokeShape(this)}},Kinetic.Util.extend(Kinetic.Polygon,Kinetic.Shape),Kinetic.Factory.addPointsGetterSetter(Kinetic.Polygon,"points")}(),function(){function a(a){a.fillText(this.partialText,0,0)}function b(a){a.strokeText(this.partialText,0,0)}var c="auto",d="Calibri",e="canvas",f="center",g="Change.kinetic",h="2d",i="-",j="",k="left",l="text",m="Text",n="middle",o="normal",p="px ",q=" ",r="right",s="word",t="char",u="none",v=["fontFamily","fontSize","fontStyle","padding","align","lineHeight","text","width","height","wrap"],w=v.length,x=document.createElement(e).getContext(h);Kinetic.Text=function(a){this.___init(a)},Kinetic.Text.prototype={___init:function(d){var e=this;void 0===d.width&&(d.width=c),void 0===d.height&&(d.height=c),Kinetic.Shape.call(this,d),this._fillFunc=a,this._strokeFunc=b,this.className=m;for(var f=0;w>f;f++)this.on(v[f]+g,e._setTextData);this._setTextData()},drawFunc:function(a){var b=this.getPadding(),c=(this.getFontStyle(),this.getFontSize(),this.getFontFamily(),this.getTextHeight()),d=this.getLineHeight()*c,e=this.textArr,g=e.length,h=this.getWidth();a.setAttr("font",this._getContextFont()),a.setAttr("textBaseline",n),a.setAttr("textAlign",k),a.save(),a.translate(b,0),a.translate(0,b+c/2);for(var i=0;g>i;i++){var j=e[i],l=j.text,m=j.width;a.save(),this.getAlign()===r?a.translate(h-m-2*b,0):this.getAlign()===f&&a.translate((h-m-2*b)/2,0),this.partialText=l,a.fillStrokeShape(this),a.restore(),a.translate(0,d)}a.restore()},drawHitFunc:function(a){var b=this.getWidth(),c=this.getHeight();a.beginPath(),a.rect(0,0,b,c),a.closePath(),a.fillStrokeShape(this)},setText:function(a){var b=Kinetic.Util._isString(a)?a:a.toString();this._setAttr(l,b)},getWidth:function(){return this.attrs.width===c?this.getTextWidth()+2*this.getPadding():this.attrs.width},getHeight:function(){return this.attrs.height===c?this.getTextHeight()*this.textArr.length*this.getLineHeight()+2*this.getPadding():this.attrs.height},getTextWidth:function(){return this.textWidth},getTextHeight:function(){return this.textHeight},_getTextSize:function(a){var b,c=x,d=this.getFontSize();return c.save(),c.font=this._getContextFont(),b=c.measureText(a),c.restore(),{width:b.width,height:parseInt(d,10)}},_getContextFont:function(){return this.getFontStyle()+q+this.getFontSize()+p+this.getFontFamily()},_addTextLine:function(a,b){return this.textArr.push({text:a,width:b})},_getTextWidth:function(a){return x.measureText(a).width},_setTextData:function(){var a=this.getText().split("\n"),b=+this.getFontSize(),d=0,e=this.getLineHeight()*b,f=this.attrs.width,g=this.attrs.height,h=f!==c,j=g!==c,k=this.getPadding(),l=f-2*k,m=g-2*k,n=0,o=this.getWrap(),r=o!==u,s=o!==t&&r;this.textArr=[],x.save(),x.font=this.getFontStyle()+q+b+p+this.getFontFamily();for(var v=0,w=a.length;w>v;++v){var y=a[v],z=this._getTextWidth(y);if(h&&z>l)for(;y.length>0;){for(var A=0,B=y.length,C="",D=0;B>A;){var E=A+B>>>1,F=y.slice(0,E+1),G=this._getTextWidth(F);l>=G?(A=E+1,C=F,D=G):B=E}if(!C)break;if(s){var H=Math.max(C.lastIndexOf(q),C.lastIndexOf(i))+1;H>0&&(A=H,C=C.slice(0,A),D=this._getTextWidth(C))}if(this._addTextLine(C,D),n+=e,!r||j&&n+e>m)break;if(y=y.slice(A),y.length>0&&(z=this._getTextWidth(y),l>=z)){this._addTextLine(y,z),n+=e;break}}else this._addTextLine(y,z),n+=e,d=Math.max(d,z);if(j&&n+e>m)break}x.restore(),this.textHeight=b,this.textWidth=d}},Kinetic.Util.extend(Kinetic.Text,Kinetic.Shape),Kinetic.Factory.addGetterSetter(Kinetic.Text,"fontFamily",d),Kinetic.Factory.addGetterSetter(Kinetic.Text,"fontSize",12),Kinetic.Factory.addGetterSetter(Kinetic.Text,"fontStyle",o),Kinetic.Factory.addGetterSetter(Kinetic.Text,"padding",0),Kinetic.Factory.addGetterSetter(Kinetic.Text,"align",k),Kinetic.Factory.addGetterSetter(Kinetic.Text,"lineHeight",1),Kinetic.Factory.addGetterSetter(Kinetic.Text,"wrap",s),Kinetic.Factory.addGetter(Kinetic.Text,l,j),Kinetic.Factory.addSetter(Kinetic.Text,"width"),Kinetic.Factory.addSetter(Kinetic.Text,"height")}(),function(){Kinetic.Line=function(a){this.___init(a)},Kinetic.Line.prototype={___init:function(a){Kinetic.Shape.call(this,a),this.className="Line"},drawFunc:function(a){var b,c,d=this.getPoints(),e=d.length;for(a.beginPath(),a.moveTo(d[0].x,d[0].y),b=1;e>b;b++)c=d[b],a.lineTo(c.x,c.y);a.strokeShape(this)}},Kinetic.Util.extend(Kinetic.Line,Kinetic.Shape),Kinetic.Factory.addPointsGetterSetter(Kinetic.Line,"points")}(),function(){Kinetic.Spline=function(a){this.___init(a)},Kinetic.Spline.prototype={___init:function(a){var b=this;Kinetic.Shape.call(this,a),this.className="Spline",this.on("pointsChange.kinetic tensionChange.kinetic",function(){b._setAllPoints()}),this._setAllPoints()},drawFunc:function(a){var b,c,d,e,f=this.getPoints(),g=f.length,h=this.getTension();if(a.beginPath(),a.moveTo(f[0].x,f[0].y),0!==h&&g>2){for(b=this.allPoints,c=b.length,d=2,a.quadraticCurveTo(b[0].x,b[0].y,b[1].x,b[1].y);c-1>d;)a.bezierCurveTo(b[d].x,b[d++].y,b[d].x,b[d++].y,b[d].x,b[d++].y);a.quadraticCurveTo(b[c-1].x,b[c-1].y,f[g-1].x,f[g-1].y)}else for(d=1;g>d;d++)e=f[d],a.lineTo(e.x,e.y);a.strokeShape(this)},_setAllPoints:function(){this.allPoints=Kinetic.Util._expandPoints(this.getPoints(),this.getTension())}},Kinetic.Util.extend(Kinetic.Spline,Kinetic.Shape),Kinetic.Factory.addGetterSetter(Kinetic.Spline,"tension",1),Kinetic.Factory.addPointsGetterSetter(Kinetic.Spline,"points")}(),function(){Kinetic.Blob=function(a){this.___init(a)},Kinetic.Blob.prototype={___init:function(a){var b=this;Kinetic.Shape.call(this,a),this.className="Blob",this.on("pointsChange.kinetic tensionChange.kinetic",function(){b._setAllPoints()}),this._setAllPoints()},drawFunc:function(a){var b,c,d,e,f=this.getPoints(),g=f.length,h=this.getTension();if(a.beginPath(),a.moveTo(f[0].x,f[0].y),0!==h&&g>2)for(b=this.allPoints,c=b.length,d=0;c-1>d;)a.bezierCurveTo(b[d].x,b[d++].y,b[d].x,b[d++].y,b[d].x,b[d++].y);else for(d=1;g>d;d++)e=f[d],a.lineTo(e.x,e.y);a.closePath(),a.fillStrokeShape(this)},_setAllPoints:function(){var a=this.getPoints(),b=a.length,c=this.getTension(),d=Kinetic.Util,e=d._getControlPoints(a[b-1],a[0],a[1],c),f=d._getControlPoints(a[b-2],a[b-1],a[0],c);this.allPoints=Kinetic.Util._expandPoints(this.getPoints(),this.getTension()),this.allPoints.unshift(e[1]),this.allPoints.push(f[0]),this.allPoints.push(a[b-1]),this.allPoints.push(f[1]),this.allPoints.push(e[0]),this.allPoints.push(a[0])}},Kinetic.Util.extend(Kinetic.Blob,Kinetic.Shape),Kinetic.Factory.addGetterSetter(Kinetic.Blob,"tension",1),Kinetic.Factory.addPointsGetterSetter(Kinetic.Blob,"points")}(),function(){Kinetic.Sprite=function(a){this.___init(a)},Kinetic.Sprite.prototype={___init:function(a){Kinetic.Shape.call(this,a),this.className="Sprite",this.anim=new Kinetic.Animation;var b=this;this.on("animationChange.kinetic",function(){b.setIndex(0)})},drawFunc:function(a){var b=this.getAnimation(),c=this.getIndex(),d=this.getAnimations()[b][c],e=this.getImage();e&&a.drawImage(e,d.x,d.y,d.width,d.height,0,0,d.width,d.height)},drawHitFunc:function(a){var b=this.getAnimation(),c=this.getIndex(),d=this.getAnimations()[b][c];a.beginPath(),a.rect(0,0,d.width,d.height),a.closePath(),a.fillShape(this)},_useBufferCanvas:function(){return(this.hasShadow()||1!==this.getAbsoluteOpacity())&&this.hasStroke()},start:function(){var a=this,b=this.getLayer();this.anim.setLayers(b),this.interval=setInterval(function(){var b=a.getIndex();a._updateIndex(),a.afterFrameFunc&&b===a.afterFrameIndex&&(a.afterFrameFunc(),delete a.afterFrameFunc,delete a.afterFrameIndex)},1e3/this.getFrameRate()),this.anim.start()},stop:function(){this.anim.stop(),clearInterval(this.interval)},afterFrame:function(a,b){this.afterFrameIndex=a,this.afterFrameFunc=b},_updateIndex:function(){var a=this.getIndex(),b=this.getAnimation(),c=this.getAnimations(),d=c[b],e=d.length;e-1>a?this.setIndex(a+1):this.setIndex(0)}},Kinetic.Util.extend(Kinetic.Sprite,Kinetic.Shape),Kinetic.Factory.addGetterSetter(Kinetic.Sprite,"animation"),Kinetic.Factory.addGetterSetter(Kinetic.Sprite,"animations"),Kinetic.Factory.addGetterSetter(Kinetic.Sprite,"image"),Kinetic.Factory.addGetterSetter(Kinetic.Sprite,"index",0),Kinetic.Factory.addGetterSetter(Kinetic.Sprite,"frameRate",17)}(),function(){Kinetic.Path=function(a){this.___init(a)},Kinetic.Path.prototype={___init:function(a){this.dataArray=[];var b=this;Kinetic.Shape.call(this,a),this.className="Path",this.dataArray=Kinetic.Path.parsePathData(this.getData()),this.on("dataChange.kinetic",function(){b.dataArray=Kinetic.Path.parsePathData(this.getData())})},drawFunc:function(a){var b=this.dataArray,c=!1;a.beginPath();for(var d=0;dj?i:j,p=i>j?1:i/j,q=i>j?j/i:1;a.translate(g,h),a.rotate(m),a.scale(p,q),a.arc(0,0,o,k,k+l,1-n),a.scale(1/p,1/q),a.rotate(-m),a.translate(-g,-h);break;case"z":a.closePath(),c=!0}}c?a.fillStrokeShape(this):a.strokeShape(this)}},Kinetic.Util.extend(Kinetic.Path,Kinetic.Shape),Kinetic.Path.getLineLength=function(a,b,c,d){return Math.sqrt((c-a)*(c-a)+(d-b)*(d-b))},Kinetic.Path.getPointOnLine=function(a,b,c,d,e,f,g){void 0===f&&(f=b),void 0===g&&(g=c);var h=(e-c)/(d-b+1e-8),i=Math.sqrt(a*a/(1+h*h));b>d&&(i*=-1);var j,k=h*i;if(d===b)j={x:f,y:g+k};else if((g-c)/(f-b+1e-8)===h)j={x:f+i,y:g+k};else{var l,m,n=this.getLineLength(b,c,d,e);if(1e-8>n)return void 0;var o=(f-b)*(d-b)+(g-c)*(e-c);o/=n*n,l=b+o*(d-b),m=c+o*(e-c);var p=this.getLineLength(f,g,l,m),q=Math.sqrt(a*a-p*p);i=Math.sqrt(q*q/(1+h*h)),b>d&&(i*=-1),k=h*i,j={x:l+i,y:m+k}}return j},Kinetic.Path.getPointOnCubicBezier=function(a,b,c,d,e,f,g,h,i){function j(a){return a*a*a}function k(a){return 3*a*a*(1-a)}function l(a){return 3*a*(1-a)*(1-a)}function m(a){return(1-a)*(1-a)*(1-a)}var n=h*j(a)+f*k(a)+d*l(a)+b*m(a),o=i*j(a)+g*k(a)+e*l(a)+c*m(a);return{x:n,y:o}},Kinetic.Path.getPointOnQuadraticBezier=function(a,b,c,d,e,f,g){function h(a){return a*a}function i(a){return 2*a*(1-a)}function j(a){return(1-a)*(1-a)}var k=f*h(a)+d*i(a)+b*j(a),l=g*h(a)+e*i(a)+c*j(a);return{x:k,y:l}},Kinetic.Path.getPointOnEllipticalArc=function(a,b,c,d,e,f){var g=Math.cos(f),h=Math.sin(f),i={x:c*Math.cos(e),y:d*Math.sin(e)};return{x:a+(i.x*g-i.y*h),y:b+(i.x*h+i.y*g)}},Kinetic.Path.parsePathData=function(a){if(!a)return[];var b=a,c=["m","M","l","L","v","V","h","H","z","Z","c","C","q","Q","t","T","s","S","a","A"];b=b.replace(new RegExp(" ","g"),",");for(var d=0;d0&&""===k[0]&&k.shift();for(var l=0;l0&&!isNaN(k[0]);){var m,n,o,p,q,r,s,t,u,v,w=null,x=[],y=g,z=h;switch(j){case"l":g+=k.shift(),h+=k.shift(),w="L",x.push(g,h);break;case"L":g=k.shift(),h=k.shift(),x.push(g,h);break;case"m":g+=k.shift(),h+=k.shift(),w="M",x.push(g,h),j="l";break;case"M":g=k.shift(),h=k.shift(),w="M",x.push(g,h),j="L";break;case"h":g+=k.shift(),w="L",x.push(g,h);break;case"H":g=k.shift(),w="L",x.push(g,h);break;case"v":h+=k.shift(),w="L",x.push(g,h);break;case"V":h=k.shift(),w="L",x.push(g,h);break;case"C":x.push(k.shift(),k.shift(),k.shift(),k.shift()),g=k.shift(),h=k.shift(),x.push(g,h);break;case"c":x.push(g+k.shift(),h+k.shift(),g+k.shift(),h+k.shift()),g+=k.shift(),h+=k.shift(),w="C",x.push(g,h);break;case"S":n=g,o=h,m=f[f.length-1],"C"===m.command&&(n=g+(g-m.points[2]),o=h+(h-m.points[3])),x.push(n,o,k.shift(),k.shift()),g=k.shift(),h=k.shift(),w="C",x.push(g,h);break;case"s":n=g,o=h,m=f[f.length-1],"C"===m.command&&(n=g+(g-m.points[2]),o=h+(h-m.points[3])),x.push(n,o,g+k.shift(),h+k.shift()),g+=k.shift(),h+=k.shift(),w="C",x.push(g,h);break;case"Q":x.push(k.shift(),k.shift()),g=k.shift(),h=k.shift(),x.push(g,h);break;case"q":x.push(g+k.shift(),h+k.shift()),g+=k.shift(),h+=k.shift(),w="Q",x.push(g,h);break;case"T":n=g,o=h,m=f[f.length-1],"Q"===m.command&&(n=g+(g-m.points[0]),o=h+(h-m.points[1])),g=k.shift(),h=k.shift(),w="Q",x.push(n,o,g,h);break;case"t":n=g,o=h,m=f[f.length-1],"Q"===m.command&&(n=g+(g-m.points[0]),o=h+(h-m.points[1])),g+=k.shift(),h+=k.shift(),w="Q",x.push(n,o,g,h);break;case"A":p=k.shift(),q=k.shift(),r=k.shift(),s=k.shift(),t=k.shift(),u=g,v=h,g=k.shift(),h=k.shift(),w="A",x=this.convertEndpointToCenterParameterization(u,v,g,h,s,t,p,q,r);break;case"a":p=k.shift(),q=k.shift(),r=k.shift(),s=k.shift(),t=k.shift(),u=g,v=h,g+=k.shift(),h+=k.shift(),w="A",x=this.convertEndpointToCenterParameterization(u,v,g,h,s,t,p,q,r)}f.push({command:w||j,points:x,start:{x:y,y:z},pathLength:this.calcLength(y,z,w||j,x)})}("z"===j||"Z"===j)&&f.push({command:"z",points:[],start:void 0,pathLength:0})}return f},Kinetic.Path.calcLength=function(a,b,c,d){var e,f,g,h=Kinetic.Path;switch(c){case"L":return h.getLineLength(a,b,d[0],d[1]);case"C":for(e=0,f=h.getPointOnCubicBezier(0,a,b,d[0],d[1],d[2],d[3],d[4],d[5]),t=.01;1>=t;t+=.01)g=h.getPointOnCubicBezier(t,a,b,d[0],d[1],d[2],d[3],d[4],d[5]),e+=h.getLineLength(f.x,f.y,g.x,g.y),f=g;return e;case"Q":for(e=0,f=h.getPointOnQuadraticBezier(0,a,b,d[0],d[1],d[2],d[3]),t=.01;1>=t;t+=.01)g=h.getPointOnQuadraticBezier(t,a,b,d[0],d[1],d[2],d[3]),e+=h.getLineLength(f.x,f.y,g.x,g.y),f=g;return e;case"A":e=0;var i=d[4],j=d[5],k=d[4]+j,l=Math.PI/180;if(Math.abs(i-k)j)for(t=i-l;t>k;t-=l)g=h.getPointOnEllipticalArc(d[0],d[1],d[2],d[3],t,0),e+=h.getLineLength(f.x,f.y,g.x,g.y),f=g;else for(t=i+l;k>t;t+=l)g=h.getPointOnEllipticalArc(d[0],d[1],d[2],d[3],t,0),e+=h.getLineLength(f.x,f.y,g.x,g.y),f=g;return g=h.getPointOnEllipticalArc(d[0],d[1],d[2],d[3],k,0),e+=h.getLineLength(f.x,f.y,g.x,g.y)}return 0},Kinetic.Path.convertEndpointToCenterParameterization=function(a,b,c,d,e,f,g,h,i){var j=i*(Math.PI/180),k=Math.cos(j)*(a-c)/2+Math.sin(j)*(b-d)/2,l=-1*Math.sin(j)*(a-c)/2+Math.cos(j)*(b-d)/2,m=k*k/(g*g)+l*l/(h*h);m>1&&(g*=Math.sqrt(m),h*=Math.sqrt(m));var n=Math.sqrt((g*g*h*h-g*g*l*l-h*h*k*k)/(g*g*l*l+h*h*k*k));e==f&&(n*=-1),isNaN(n)&&(n=0);var o=n*g*l/h,p=n*-h*k/g,q=(a+c)/2+Math.cos(j)*o-Math.sin(j)*p,r=(b+d)/2+Math.sin(j)*o+Math.cos(j)*p,s=function(a){return Math.sqrt(a[0]*a[0]+a[1]*a[1])},t=function(a,b){return(a[0]*b[0]+a[1]*b[1])/(s(a)*s(b))},u=function(a,b){return(a[0]*b[1]=1&&(y=0),0===f&&y>0&&(y-=2*Math.PI),1==f&&0>y&&(y+=2*Math.PI),[q,r,g,h,v,y,j,f]},Kinetic.Factory.addGetterSetter(Kinetic.Path,"data")}(),function(){function a(a){a.fillText(this.partialText,0,0)}function b(a){a.strokeText(this.partialText,0,0)}var c="",d="Calibri",e="normal";Kinetic.TextPath=function(a){this.___init(a)},Kinetic.TextPath.prototype={___init:function(c){var d=this;this.dummyCanvas=document.createElement("canvas"),this.dataArray=[],Kinetic.Shape.call(this,c),this._fillFunc=a,this._strokeFunc=b,this.className="TextPath",this.dataArray=Kinetic.Path.parsePathData(this.attrs.data),this.on("dataChange.kinetic",function(){d.dataArray=Kinetic.Path.parsePathData(this.attrs.data)}),this.on("textChange.kinetic textStroke.kinetic textStrokeWidth.kinetic",d._setTextData),d._setTextData()},drawFunc:function(a){this.charArr,a.setAttr("font",this._getContextFont()),a.setAttr("textBaseline","middle"),a.setAttr("textAlign","left"),a.save();for(var b=this.glyphInfo,c=0;c0)return g=d,b[d];"M"==b[d].command&&(c={x:b[d].points[0],y:b[d].points[1]})}return{}},j=function(b){var f=a._getTextSize(b).width,g=0,j=0;for(d=void 0;Math.abs(f-g)/f>.01&&25>j;){j++;for(var k=g;void 0===e;)e=i(),e&&k+e.pathLengthf?d=Kinetic.Path.getPointOnLine(f,c.x,c.y,e.points[0],e.points[1],c.x,c.y):e=void 0;break;case"A":var m=e.points[4],n=e.points[5],o=e.points[4]+n;0===h?h=m+1e-8:f>g?h+=Math.PI/180*n/Math.abs(n):h-=Math.PI/360*n/Math.abs(n),(0>n&&o>h||n>=0&&h>o)&&(h=o,l=!0),d=Kinetic.Path.getPointOnEllipticalArc(e.points[0],e.points[1],e.points[2],e.points[3],h,e.points[6]);break;case"C":0===h?h=f>e.pathLength?1e-8:f/e.pathLength:f>g?h+=(f-g)/e.pathLength:h-=(g-f)/e.pathLength,h>1&&(h=1,l=!0),d=Kinetic.Path.getPointOnCubicBezier(h,e.start.x,e.start.y,e.points[0],e.points[1],e.points[2],e.points[3],e.points[4],e.points[5]);break;case"Q":0===h?h=f/e.pathLength:f>g?h+=(f-g)/e.pathLength:h-=(g-f)/e.pathLength,h>1&&(h=1,l=!0),d=Kinetic.Path.getPointOnQuadraticBezier(h,e.start.x,e.start.y,e.points[0],e.points[1],e.points[2],e.points[3])}void 0!==d&&(g=Kinetic.Path.getLineLength(c.x,c.y,d.x,d.y)),l&&(l=!1,e=void 0)}},k=0;kb;b++)c=f*Math.sin(2*b*Math.PI/e),d=-1*f*Math.cos(2*b*Math.PI/e),a.lineTo(c,d);a.closePath(),a.fillStrokeShape(this)}},Kinetic.Util.extend(Kinetic.RegularPolygon,Kinetic.Shape),Kinetic.Factory.addGetterSetter(Kinetic.RegularPolygon,"radius",0),Kinetic.Factory.addGetterSetter(Kinetic.RegularPolygon,"sides",0)}(),function(){Kinetic.Star=function(a){this.___init(a)},Kinetic.Star.prototype={___init:function(a){Kinetic.Shape.call(this,a),this.className="Star"},drawFunc:function(a){var b=a._context,c=this.attrs.innerRadius,d=this.attrs.outerRadius,e=this.attrs.numPoints;b.beginPath(),b.moveTo(0,0-this.attrs.outerRadius);for(var f=1;2*e>f;f++){var g=0===f%2?d:c,h=g*Math.sin(f*Math.PI/e),i=-1*g*Math.cos(f*Math.PI/e);b.lineTo(h,i)}b.closePath(),a.fillStrokeShape(this)}},Kinetic.Util.extend(Kinetic.Star,Kinetic.Shape),Kinetic.Factory.addGetterSetter(Kinetic.Star,"numPoints",0),Kinetic.Factory.addGetterSetter(Kinetic.Star,"innerRadius",0),Kinetic.Factory.addGetterSetter(Kinetic.Star,"outerRadius",0)}(),function(){var a=["fontFamily","fontSize","fontStyle","padding","lineHeight","text"],b="Change.kinetic",c="none",d="up",e="right",f="down",g="left",h="Label",i=a.length;Kinetic.Label=function(a){this.____init(a)},Kinetic.Label.prototype={____init:function(a){var b=this;this.className=h,Kinetic.Group.call(this,a),this.on("add.kinetic",function(a){b._addListeners(a.child),b._sync()})},getText:function(){return this.find("Text")[0]},getTag:function(){return this.find("Tag")[0]},_addListeners:function(c){var d,e=this,f=function(){e._sync()};for(d=0;i>d;d++)c.on(a[d]+b,f)},getWidth:function(){return this.getText().getWidth()},getHeight:function(){return this.getText().getHeight()},_sync:function(){var a,b,c,h,i,j,k=this.getText(),l=this.getTag();if(k&&l){switch(a=k.getWidth(),b=k.getHeight(),c=l.getPointerDirection(),h=l.getPointerWidth(),pointerHeight=l.getPointerHeight(),i=0,j=0,c){case d:i=a/2,j=-1*pointerHeight;break;case e:i=a+h,j=b/2;break;case f:i=a/2,j=b+pointerHeight;break;case g:i=-1*h,j=b/2}l.setAttrs({x:-1*i,y:-1*j,width:a,height:b}),k.setAttrs({x:-1*i,y:-1*j})}}},Kinetic.Util.extend(Kinetic.Label,Kinetic.Group),Kinetic.Tag=function(a){this.___init(a)},Kinetic.Tag.prototype={___init:function(a){Kinetic.Shape.call(this,a),this.className="Tag"},drawFunc:function(a){var b=this.getWidth(),c=this.getHeight(),h=this.getPointerDirection(),i=this.getPointerWidth(),j=this.getPointerHeight();this.getCornerRadius(),a.beginPath(),a.moveTo(0,0),h===d&&(a.lineTo((b-i)/2,0),a.lineTo(b/2,-1*j),a.lineTo((b+i)/2,0)),a.lineTo(b,0),h===e&&(a.lineTo(b,(c-j)/2),a.lineTo(b+i,c/2),a.lineTo(b,(c+j)/2)),a.lineTo(b,c),h===f&&(a.lineTo((b+i)/2,c),a.lineTo(b/2,c+j),a.lineTo((b-i)/2,c)),a.lineTo(0,c),h===g&&(a.lineTo(0,(c+j)/2),a.lineTo(-1*i,c/2),a.lineTo(0,(c-j)/2)),a.closePath(),a.fillStrokeShape(this)}},Kinetic.Util.extend(Kinetic.Tag,Kinetic.Shape),Kinetic.Factory.addGetterSetter(Kinetic.Tag,"pointerDirection",c),Kinetic.Factory.addGetterSetter(Kinetic.Tag,"pointerWidth",0),Kinetic.Factory.addGetterSetter(Kinetic.Tag,"pointerHeight",0),Kinetic.Factory.addGetterSetter(Kinetic.Tag,"cornerRadius",0)}(),function(){Kinetic.Filters.Grayscale=function(a){for(var b=a.data,c=0;ch;h++)N=N.next=new a,h==J&&(M=N);for(N.next=L,l=k=0,g=0;F>g;g++){for(u=v=w=x=m=n=o=p=0,q=J*(y=D[k]),r=J*(z=D[k+1]),s=J*(A=D[k+2]),t=J*(B=D[k+3]),m+=K*y,n+=K*z,o+=K*A,p+=K*B,N=L,h=0;J>h;h++)N.r=y,N.g=z,N.b=A,N.a=B,N=N.next;for(h=1;J>h;h++)i=k+((h>H?H:h)<<2),m+=(N.r=y=D[i])*(C=J-h),n+=(N.g=z=D[i+1])*C,o+=(N.b=A=D[i+2])*C,p+=(N.a=B=D[i+3])*C,u+=y,v+=z,w+=A,x+=B,N=N.next;for(O=L,P=M,f=0;E>f;f++)D[k+3]=B=p*Q>>R,0!==B?(B=255/B,D[k]=(m*Q>>R)*B,D[k+1]=(n*Q>>R)*B,D[k+2]=(o*Q>>R)*B):D[k]=D[k+1]=D[k+2]=0,m-=q,n-=r,o-=s,p-=t,q-=O.r,r-=O.g,s-=O.b,t-=O.a,i=l+((i=f+e+1)f;f++){for(v=w=x=u=n=o=p=m=0,k=f<<2,q=J*(y=D[k]),r=J*(z=D[k+1]),s=J*(A=D[k+2]),t=J*(B=D[k+3]),m+=K*y,n+=K*z,o+=K*A,p+=K*B,N=L,h=0;J>h;h++)N.r=y,N.g=z,N.b=A,N.a=B,N=N.next;for(j=E,h=1;e>=h;h++)k=j+f<<2,m+=(N.r=y=D[k])*(C=J-h),n+=(N.g=z=D[k+1])*C,o+=(N.b=A=D[k+2])*C,p+=(N.a=B=D[k+3])*C,u+=y,v+=z,w+=A,x+=B,N=N.next,I>h&&(j+=E);for(k=f,O=L,P=M,g=0;F>g;g++)i=k<<2,D[i+3]=B=p*Q>>R,B>0?(B=255/B,D[i]=(m*Q>>R)*B,D[i+1]=(n*Q>>R)*B,D[i+2]=(o*Q>>R)*B):D[i]=D[i+1]=D[i+2]=0,m-=q,n-=r,o-=s,p-=t,q-=O.r,r-=O.g,s-=O.b,t-=O.a,i=f+((i=g+J)0&&b(a,c)},Kinetic.Factory.addFilterGetterSetter(Kinetic.Image,"filterRadius",0)}(),function(){function a(a,b,c){var d=4*(c*a.width+b),e=[];return e.push(a.data[d++],a.data[d++],a.data[d++],a.data[d++]),e}function b(a,b){return Math.sqrt(Math.pow(a[0]-b[0],2)+Math.pow(a[1]-b[1],2)+Math.pow(a[2]-b[2],2))}function c(a){for(var b=[0,0,0],c=0;cn?0:255}return l}}function e(a,b){for(var c=0;ch;h++)for(var i=0;b>i;i++){for(var j=h*b+i,k=0,l=0;e>l;l++)for(var m=0;e>m;m++){var n=h+l-f,o=i+m-f;if(n>=0&&c>n&&o>=0&&b>o){var p=n*b+o,q=d[l*e+m];k+=a[p]*q}}g[j]=2040===k?255:0}return g}function g(a,b,c){for(var d=[1,1,1,1,1,1,1,1,1],e=Math.round(Math.sqrt(d.length)),f=Math.floor(e/2),g=[],h=0;c>h;h++)for(var i=0;b>i;i++){for(var j=h*b+i,k=0,l=0;e>l;l++)for(var m=0;e>m;m++){var n=h+l-f,o=i+m-f;if(n>=0&&c>n&&o>=0&&b>o){var p=n*b+o,q=d[l*e+m];k+=a[p]*q}}g[j]=k>=1020?255:0}return g}function h(a,b,c){for(var d=[1/9,1/9,1/9,1/9,1/9,1/9,1/9,1/9,1/9],e=Math.round(Math.sqrt(d.length)),f=Math.floor(e/2),g=[],h=0;c>h;h++)for(var i=0;b>i;i++){for(var j=h*b+i,k=0,l=0;e>l;l++)for(var m=0;e>m;m++){var n=h+l-f,o=i+m-f;if(n>=0&&c>n&&o>=0&&b>o){var p=n*b+o,q=d[l*e+m];k+=a[p]*q}}g[j]=k}return g}Kinetic.Filters.Mask=function(a){var b=this.getFilterThreshold(),c=d(a,b);return c&&(c=f(c,a.width,a.height),c=g(c,a.width,a.height),c=h(c,a.width,a.height),e(a,c)),a},Kinetic.Factory.addFilterGetterSetter(Kinetic.Image,"filterThreshold",0)}(),function(){var a=function(a,b,c){a/=255,b/=255,c/=255;var d=Math.max(a,b,c),e=Math.min(a,b,c),f=d-e,g=f/2,h=f/(1-Math.abs(2*g-1)),i=0;return d==a?i=(b-c)/f%6:d==b?i=(c-a)/f+2:d==c&&(i=(a-b)/f+4),[(60*i+360)%360,h,g]},b=function(a,b,c,d){a/=255,b/=255,c/=255;var e=Math.max(a,b,c),f=Math.min(a,b,c),g=e-f,h=g/2,i=(g/(1-Math.abs(2*h-1)),0);e==a?i=(b-c)/g%6:e==b?i=(c-a)/g+2:e==c&&(i=(a-b)/g+4),i*=60,i%=360,i+=d,i%=360,i/=60;var j=0,k=0,l=0,m=g*(1-Math.abs(i%2-1)),n=h-g/2;return i>=0&&1>i?(j=g,k=m):i>=1&&2>i?(k=g,j=m):i>=2&&3>i?(k=g,l=m):i>=3&&4>i?(l=g,k=m):i>=4&&5>i?(l=g,j=m):i>=5&&6>i&&(j=g,l=m),j+=n,k+=n,l+=n,j=255*j,k=255*k,l=255*l,[j,k,l]},c=function(a,c){for(var d,e=a.data,f=0;fm;m+=1)for(l=0;d>l;l+=1){for(h=0,i=0,j=0,k=0,q=0;s>q;q+=1)for(r=0;t>r;r+=1)n=(l+q-u)%d,n=n>0?n:-n,o=(m+q-v)%e,o=o>0?o:-o,p=4*(o*d+n),h+=b[r][q]*c[p+0],i+=b[r][q]*c[p+1],j+=b[r][q]*c[p+2];p=4*(m*d+l),g[p+0]=h,g[p+1]=i,g[p+2]=j}var w=4*f;for(p=0;w>p;p+=4)c[p+0]=g[p+0],c[p+1]=g[p+1],c[p+2]=g[p+2]},b=function(a,b,c){var d=a-b;return Math.pow(Math.E,-d*d/(2*c*c))},c=function(a,c,d){0===a%2&&(a+=1);var e,f,g,h=[];for(e=0;a>e;e+=1){for(g=[],f=0;a>f;f+=1)g.push(c*b(e,a/2,d)*b(f,a/2,d));h.push(g)}return h},d=function(a,b){var d=c(a,b,1),e=Math.floor(a/2);return d[e][e]+=1-b,d},e=function(a,b){var d=c(a,-b,1),e=Math.floor(a/2);return d[e][e]+=1+b,d};Kinetic.Factory.addFilterGetterSetter(Kinetic.Image,"filterAmount",50),Kinetic.Filters.UnsharpMask=function(b){a(b,e(5,this.getFilterAmount()/100))},Kinetic.Filters.SoftBlur=function(b){a(b,d(5,this.getFilterAmount()/100))},Kinetic.Filters.Edge=function(b){var c=this.getFilterAmount()/100;0!==c&&a(b,[[0,-1*c,0],[-1*c,1-c+4*c,-1*c],[0,-1*c,0]])},Kinetic.Filters.Emboss=function(b){var c=this.getFilterAmount()/100;0!==c&&a(b,[[-1*c,-.5*c,0],[-.5*c,1+.5*c,.5*c],[0,.5*c,1*c]])}}(); diff --git a/ajax/libs/kineticjs/package.json b/ajax/libs/kineticjs/package.json index 99af86d86..27cc3f5d3 100644 --- a/ajax/libs/kineticjs/package.json +++ b/ajax/libs/kineticjs/package.json @@ -1,7 +1,7 @@ { "name": "kineticjs", "filename": "kinetic.min.js", - "version": "4.3.1", + "version": "4.7.2", "description": "KineticJS is an HTML5 Canvas JavaScript framework that enables high performance animations, transitions, node nesting, layering, filtering, caching, event handling for desktop and mobile applications, and much more.", "homepage": "http://kineticjs.com/", "keywords": [ From 3f0d4a350f5b29666401123339ce0be14dadd645 Mon Sep 17 00:00:00 2001 From: Dean Malmgren Date: Thu, 10 Oct 2013 17:07:54 -0500 Subject: [PATCH 08/26] added seedrandom 2.2 --- ajax/libs/seedrandom/2.2/seedrandom.min.js | 1 + ajax/libs/seedrandom/package.json | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+) create mode 100644 ajax/libs/seedrandom/2.2/seedrandom.min.js create mode 100644 ajax/libs/seedrandom/package.json diff --git a/ajax/libs/seedrandom/2.2/seedrandom.min.js b/ajax/libs/seedrandom/2.2/seedrandom.min.js new file mode 100644 index 000000000..bafa00a17 --- /dev/null +++ b/ajax/libs/seedrandom/2.2/seedrandom.min.js @@ -0,0 +1 @@ +(function(a,b,c,d,e,f){function k(a){var b,c=a.length,e=this,f=0,g=e.i=e.j=0,h=e.S=[];for(c||(a=[c++]);d>f;)h[f]=f++;for(f=0;d>f;f++)h[f]=h[g=j&g+a[f%c]+(b=h[f])],h[g]=b;(e.g=function(a){for(var b,c=0,f=e.i,g=e.j,h=e.S;a--;)b=h[f=j&f+1],c=c*d+h[j&(h[f]=h[g=j&g+b])+(h[g]=b)];return e.i=f,e.j=g,c})(d)}function l(a,b){var e,c=[],d=(typeof a)[0];if(b&&"o"==d)for(e in a)try{c.push(l(a[e],b-1))}catch(f){}return c.length?c:"s"==d?a:a+"\0"}function m(a,b){for(var d,c=a+"",e=0;c.length>e;)b[j&e]=j&(d^=19*b[j&e])+c.charCodeAt(e++);return o(b)}function n(c){try{return a.crypto.getRandomValues(c=new Uint8Array(d)),o(c)}catch(e){return[+new Date,a,a.navigator.plugins,a.screen,o(b)]}}function o(a){return String.fromCharCode.apply(0,a)}var g=c.pow(d,e),h=c.pow(2,f),i=2*h,j=d-1;c.seedrandom=function(a,f){var j=[],p=m(l(f?[a,o(b)]:0 in arguments?a:n(),3),j),q=new k(j);return m(o(q.S),b),c.random=function(){for(var a=q.g(e),b=g,c=0;h>a;)a=(a+c)*d,b*=d,c=q.g(1);for(;a>=i;)a/=2,b/=2,c>>>=1;return(a+c)/b},p},m(c.random(),b)})(this,[],Math,256,6,52); diff --git a/ajax/libs/seedrandom/package.json b/ajax/libs/seedrandom/package.json new file mode 100644 index 000000000..b00a6ecbf --- /dev/null +++ b/ajax/libs/seedrandom/package.json @@ -0,0 +1,22 @@ +{ + "name": "seedrandom", + "filename": "seedrandom.min.js", + "version": "2.2", + "description": "seeded random number generator for Javascript", + "homepage": "https://github.com/davidbau/seedrandom", + "keywords": [ + "random number", + "seed" + ], + "maintainers": [ + { + "name": "David Bau" + } + ], + "repositories": [ + { + "type": "git", + "url": "https://github.com/davidbau/seedrandom.git" + } + ] +} From 89b28f9c089a1f58bf721386a5b40f785793566a Mon Sep 17 00:00:00 2001 From: Ellis Berner Date: Thu, 10 Oct 2013 17:04:17 -0700 Subject: [PATCH 09/26] Create morris.css --- ajax/libs/morris.js/0.4.3/morris.css | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 ajax/libs/morris.js/0.4.3/morris.css diff --git a/ajax/libs/morris.js/0.4.3/morris.css b/ajax/libs/morris.js/0.4.3/morris.css new file mode 100644 index 000000000..bc687242e --- /dev/null +++ b/ajax/libs/morris.js/0.4.3/morris.css @@ -0,0 +1,2 @@ +.morris-hover{position:absolute;z-index:1000;}.morris-hover.morris-default-style{border-radius:10px;padding:6px;color:#666;background:rgba(255, 255, 255, 0.8);border:solid 2px rgba(230, 230, 230, 0.8);font-family:sans-serif;font-size:12px;text-align:center;}.morris-hover.morris-default-style .morris-hover-row-label{font-weight:bold;margin:0.25em 0;} +.morris-hover.morris-default-style .morris-hover-point{white-space:nowrap;margin:0.1em 0;} From 8fa71ea427b6197cdf7be91b5e6e44616c864f7c Mon Sep 17 00:00:00 2001 From: Ellis Berner Date: Thu, 10 Oct 2013 17:04:59 -0700 Subject: [PATCH 10/26] Create morris.js --- ajax/libs/morris.js/0.4.3/morris.js | 1767 +++++++++++++++++++++++++++ 1 file changed, 1767 insertions(+) create mode 100644 ajax/libs/morris.js/0.4.3/morris.js diff --git a/ajax/libs/morris.js/0.4.3/morris.js b/ajax/libs/morris.js/0.4.3/morris.js new file mode 100644 index 000000000..b91f075de --- /dev/null +++ b/ajax/libs/morris.js/0.4.3/morris.js @@ -0,0 +1,1767 @@ +(function() { + var $, Morris, minutesSpecHelper, secondsSpecHelper, + __slice = [].slice, + __hasProp = {}.hasOwnProperty, + __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, + __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; + + Morris = window.Morris = {}; + + $ = jQuery; + + Morris.EventEmitter = (function() { + + function EventEmitter() {} + + EventEmitter.prototype.on = function(name, handler) { + if (this.handlers == null) { + this.handlers = {}; + } + if (this.handlers[name] == null) { + this.handlers[name] = []; + } + this.handlers[name].push(handler); + return this; + }; + + EventEmitter.prototype.fire = function() { + var args, handler, name, _i, _len, _ref, _results; + name = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; + if ((this.handlers != null) && (this.handlers[name] != null)) { + _ref = this.handlers[name]; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + handler = _ref[_i]; + _results.push(handler.apply(null, args)); + } + return _results; + } + }; + + return EventEmitter; + + })(); + + Morris.commas = function(num) { + var absnum, intnum, ret, strabsnum; + if (num != null) { + ret = num < 0 ? "-" : ""; + absnum = Math.abs(num); + intnum = Math.floor(absnum).toFixed(0); + ret += intnum.replace(/(?=(?:\d{3})+$)(?!^)/g, ','); + strabsnum = absnum.toString(); + if (strabsnum.length > intnum.length) { + ret += strabsnum.slice(intnum.length); + } + return ret; + } else { + return '-'; + } + }; + + Morris.pad2 = function(number) { + return (number < 10 ? '0' : '') + number; + }; + + Morris.Grid = (function(_super) { + + __extends(Grid, _super); + + function Grid(options) { + var _this = this; + if (typeof options.element === 'string') { + this.el = $(document.getElementById(options.element)); + } else { + this.el = $(options.element); + } + if (!(this.el != null) || this.el.length === 0) { + throw new Error("Graph container element not found"); + } + if (this.el.css('position') === 'static') { + this.el.css('position', 'relative'); + } + this.options = $.extend({}, this.gridDefaults, this.defaults || {}, options); + if (typeof this.options.units === 'string') { + this.options.postUnits = options.units; + } + this.raphael = new Raphael(this.el[0]); + this.elementWidth = null; + this.elementHeight = null; + this.dirty = false; + if (this.init) { + this.init(); + } + this.setData(this.options.data); + this.el.bind('mousemove', function(evt) { + var offset; + offset = _this.el.offset(); + return _this.fire('hovermove', evt.pageX - offset.left, evt.pageY - offset.top); + }); + this.el.bind('mouseout', function(evt) { + return _this.fire('hoverout'); + }); + this.el.bind('touchstart touchmove touchend', function(evt) { + var offset, touch; + touch = evt.originalEvent.touches[0] || evt.originalEvent.changedTouches[0]; + offset = _this.el.offset(); + _this.fire('hover', touch.pageX - offset.left, touch.pageY - offset.top); + return touch; + }); + this.el.bind('click', function(evt) { + var offset; + offset = _this.el.offset(); + return _this.fire('gridclick', evt.pageX - offset.left, evt.pageY - offset.top); + }); + if (this.postInit) { + this.postInit(); + } + } + + Grid.prototype.gridDefaults = { + dateFormat: null, + axes: true, + grid: true, + gridLineColor: '#aaa', + gridStrokeWidth: 0.5, + gridTextColor: '#888', + gridTextSize: 12, + gridTextFamily: 'sans-serif', + gridTextWeight: 'normal', + hideHover: false, + yLabelFormat: null, + xLabelAngle: 0, + numLines: 5, + padding: 25, + parseTime: true, + postUnits: '', + preUnits: '', + ymax: 'auto', + ymin: 'auto 0', + goals: [], + goalStrokeWidth: 1.0, + goalLineColors: ['#666633', '#999966', '#cc6666', '#663333'], + events: [], + eventStrokeWidth: 1.0, + eventLineColors: ['#005a04', '#ccffbb', '#3a5f0b', '#005502'] + }; + + Grid.prototype.setData = function(data, redraw) { + var e, idx, index, maxGoal, minGoal, ret, row, step, total, y, ykey, ymax, ymin, yval; + if (redraw == null) { + redraw = true; + } + this.options.data = data; + if (!(data != null) || data.length === 0) { + this.data = []; + this.raphael.clear(); + if (this.hover != null) { + this.hover.hide(); + } + return; + } + ymax = this.cumulative ? 0 : null; + ymin = this.cumulative ? 0 : null; + if (this.options.goals.length > 0) { + minGoal = Math.min.apply(null, this.options.goals); + maxGoal = Math.max.apply(null, this.options.goals); + ymin = ymin != null ? Math.min(ymin, minGoal) : minGoal; + ymax = ymax != null ? Math.max(ymax, maxGoal) : maxGoal; + } + this.data = (function() { + var _i, _len, _results; + _results = []; + for (index = _i = 0, _len = data.length; _i < _len; index = ++_i) { + row = data[index]; + ret = {}; + ret.label = row[this.options.xkey]; + if (this.options.parseTime) { + ret.x = Morris.parseDate(ret.label); + if (this.options.dateFormat) { + ret.label = this.options.dateFormat(ret.x); + } else if (typeof ret.label === 'number') { + ret.label = new Date(ret.label).toString(); + } + } else { + ret.x = index; + if (this.options.xLabelFormat) { + ret.label = this.options.xLabelFormat(ret); + } + } + total = 0; + ret.y = (function() { + var _j, _len1, _ref, _results1; + _ref = this.options.ykeys; + _results1 = []; + for (idx = _j = 0, _len1 = _ref.length; _j < _len1; idx = ++_j) { + ykey = _ref[idx]; + yval = row[ykey]; + if (typeof yval === 'string') { + yval = parseFloat(yval); + } + if ((yval != null) && typeof yval !== 'number') { + yval = null; + } + if (yval != null) { + if (this.cumulative) { + total += yval; + } else { + if (ymax != null) { + ymax = Math.max(yval, ymax); + ymin = Math.min(yval, ymin); + } else { + ymax = ymin = yval; + } + } + } + if (this.cumulative && (total != null)) { + ymax = Math.max(total, ymax); + ymin = Math.min(total, ymin); + } + _results1.push(yval); + } + return _results1; + }).call(this); + _results.push(ret); + } + return _results; + }).call(this); + if (this.options.parseTime) { + this.data = this.data.sort(function(a, b) { + return (a.x > b.x) - (b.x > a.x); + }); + } + this.xmin = this.data[0].x; + this.xmax = this.data[this.data.length - 1].x; + this.events = []; + if (this.options.parseTime && this.options.events.length > 0) { + this.events = (function() { + var _i, _len, _ref, _results; + _ref = this.options.events; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + e = _ref[_i]; + _results.push(Morris.parseDate(e)); + } + return _results; + }).call(this); + this.xmax = Math.max(this.xmax, Math.max.apply(null, this.events)); + this.xmin = Math.min(this.xmin, Math.min.apply(null, this.events)); + } + if (this.xmin === this.xmax) { + this.xmin -= 1; + this.xmax += 1; + } + this.ymin = this.yboundary('min', ymin); + this.ymax = this.yboundary('max', ymax); + if (this.ymin === this.ymax) { + if (ymin) { + this.ymin -= 1; + } + this.ymax += 1; + } + if (this.options.axes === true || this.options.grid === true) { + if (this.options.ymax === this.gridDefaults.ymax && this.options.ymin === this.gridDefaults.ymin) { + this.grid = this.autoGridLines(this.ymin, this.ymax, this.options.numLines); + this.ymin = Math.min(this.ymin, this.grid[0]); + this.ymax = Math.max(this.ymax, this.grid[this.grid.length - 1]); + } else { + step = (this.ymax - this.ymin) / (this.options.numLines - 1); + this.grid = (function() { + var _i, _ref, _ref1, _results; + _results = []; + for (y = _i = _ref = this.ymin, _ref1 = this.ymax; _ref <= _ref1 ? _i <= _ref1 : _i >= _ref1; y = _i += step) { + _results.push(y); + } + return _results; + }).call(this); + } + } + this.dirty = true; + if (redraw) { + return this.redraw(); + } + }; + + Grid.prototype.yboundary = function(boundaryType, currentValue) { + var boundaryOption, suggestedValue; + boundaryOption = this.options["y" + boundaryType]; + if (typeof boundaryOption === 'string') { + if (boundaryOption.slice(0, 4) === 'auto') { + if (boundaryOption.length > 5) { + suggestedValue = parseInt(boundaryOption.slice(5), 10); + if (currentValue == null) { + return suggestedValue; + } + return Math[boundaryType](currentValue, suggestedValue); + } else { + if (currentValue != null) { + return currentValue; + } else { + return 0; + } + } + } else { + return parseInt(boundaryOption, 10); + } + } else { + return boundaryOption; + } + }; + + Grid.prototype.autoGridLines = function(ymin, ymax, nlines) { + var gmax, gmin, grid, smag, span, step, unit, y, ymag; + span = ymax - ymin; + ymag = Math.floor(Math.log(span) / Math.log(10)); + unit = Math.pow(10, ymag); + gmin = Math.floor(ymin / unit) * unit; + gmax = Math.ceil(ymax / unit) * unit; + step = (gmax - gmin) / (nlines - 1); + if (unit === 1 && step > 1 && Math.ceil(step) !== step) { + step = Math.ceil(step); + gmax = gmin + step * (nlines - 1); + } + if (gmin < 0 && gmax > 0) { + gmin = Math.floor(ymin / step) * step; + gmax = Math.ceil(ymax / step) * step; + } + if (step < 1) { + smag = Math.floor(Math.log(step) / Math.log(10)); + grid = (function() { + var _i, _results; + _results = []; + for (y = _i = gmin; gmin <= gmax ? _i <= gmax : _i >= gmax; y = _i += step) { + _results.push(parseFloat(y.toFixed(1 - smag))); + } + return _results; + })(); + } else { + grid = (function() { + var _i, _results; + _results = []; + for (y = _i = gmin; gmin <= gmax ? _i <= gmax : _i >= gmax; y = _i += step) { + _results.push(y); + } + return _results; + })(); + } + return grid; + }; + + Grid.prototype._calc = function() { + var bottomOffsets, gridLine, h, i, w, yLabelWidths; + w = this.el.width(); + h = this.el.height(); + if (this.elementWidth !== w || this.elementHeight !== h || this.dirty) { + this.elementWidth = w; + this.elementHeight = h; + this.dirty = false; + this.left = this.options.padding; + this.right = this.elementWidth - this.options.padding; + this.top = this.options.padding; + this.bottom = this.elementHeight - this.options.padding; + if (this.options.axes) { + yLabelWidths = (function() { + var _i, _len, _ref, _results; + _ref = this.grid; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + gridLine = _ref[_i]; + _results.push(this.measureText(this.yAxisFormat(gridLine)).width); + } + return _results; + }).call(this); + this.left += Math.max.apply(Math, yLabelWidths); + bottomOffsets = (function() { + var _i, _ref, _results; + _results = []; + for (i = _i = 0, _ref = this.data.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { + _results.push(this.measureText(this.data[i].text, -this.options.xLabelAngle).height); + } + return _results; + }).call(this); + this.bottom -= Math.max.apply(Math, bottomOffsets); + } + this.width = Math.max(1, this.right - this.left); + this.height = Math.max(1, this.bottom - this.top); + this.dx = this.width / (this.xmax - this.xmin); + this.dy = this.height / (this.ymax - this.ymin); + if (this.calc) { + return this.calc(); + } + } + }; + + Grid.prototype.transY = function(y) { + return this.bottom - (y - this.ymin) * this.dy; + }; + + Grid.prototype.transX = function(x) { + if (this.data.length === 1) { + return (this.left + this.right) / 2; + } else { + return this.left + (x - this.xmin) * this.dx; + } + }; + + Grid.prototype.redraw = function() { + this.raphael.clear(); + this._calc(); + this.drawGrid(); + this.drawGoals(); + this.drawEvents(); + if (this.draw) { + return this.draw(); + } + }; + + Grid.prototype.measureText = function(text, angle) { + var ret, tt; + if (angle == null) { + angle = 0; + } + tt = this.raphael.text(100, 100, text).attr('font-size', this.options.gridTextSize).attr('font-family', this.options.gridTextFamily).attr('font-weight', this.options.gridTextWeight).rotate(angle); + ret = tt.getBBox(); + tt.remove(); + return ret; + }; + + Grid.prototype.yAxisFormat = function(label) { + return this.yLabelFormat(label); + }; + + Grid.prototype.yLabelFormat = function(label) { + if (typeof this.options.yLabelFormat === 'function') { + return this.options.yLabelFormat(label); + } else { + return "" + this.options.preUnits + (Morris.commas(label)) + this.options.postUnits; + } + }; + + Grid.prototype.updateHover = function(x, y) { + var hit, _ref; + hit = this.hitTest(x, y); + if (hit != null) { + return (_ref = this.hover).update.apply(_ref, hit); + } + }; + + Grid.prototype.drawGrid = function() { + var lineY, y, _i, _len, _ref, _results; + if (this.options.grid === false && this.options.axes === false) { + return; + } + _ref = this.grid; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + lineY = _ref[_i]; + y = this.transY(lineY); + if (this.options.axes) { + this.drawYAxisLabel(this.left - this.options.padding / 2, y, this.yAxisFormat(lineY)); + } + if (this.options.grid) { + _results.push(this.drawGridLine("M" + this.left + "," + y + "H" + (this.left + this.width))); + } else { + _results.push(void 0); + } + } + return _results; + }; + + Grid.prototype.drawGoals = function() { + var color, goal, i, _i, _len, _ref, _results; + _ref = this.options.goals; + _results = []; + for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) { + goal = _ref[i]; + color = this.options.goalLineColors[i % this.options.goalLineColors.length]; + _results.push(this.drawGoal(goal, color)); + } + return _results; + }; + + Grid.prototype.drawEvents = function() { + var color, event, i, _i, _len, _ref, _results; + _ref = this.events; + _results = []; + for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) { + event = _ref[i]; + color = this.options.eventLineColors[i % this.options.eventLineColors.length]; + _results.push(this.drawEvent(event, color)); + } + return _results; + }; + + Grid.prototype.drawGoal = function(goal, color) { + return this.raphael.path("M" + this.left + "," + (this.transY(goal)) + "H" + this.right).attr('stroke', color).attr('stroke-width', this.options.goalStrokeWidth); + }; + + Grid.prototype.drawEvent = function(event, color) { + return this.raphael.path("M" + (this.transX(event)) + "," + this.bottom + "V" + this.top).attr('stroke', color).attr('stroke-width', this.options.eventStrokeWidth); + }; + + Grid.prototype.drawYAxisLabel = function(xPos, yPos, text) { + return this.raphael.text(xPos, yPos, text).attr('font-size', this.options.gridTextSize).attr('font-family', this.options.gridTextFamily).attr('font-weight', this.options.gridTextWeight).attr('fill', this.options.gridTextColor).attr('text-anchor', 'end'); + }; + + Grid.prototype.drawGridLine = function(path) { + return this.raphael.path(path).attr('stroke', this.options.gridLineColor).attr('stroke-width', this.options.gridStrokeWidth); + }; + + return Grid; + + })(Morris.EventEmitter); + + Morris.parseDate = function(date) { + var isecs, m, msecs, n, o, offsetmins, p, q, r, ret, secs; + if (typeof date === 'number') { + return date; + } + m = date.match(/^(\d+) Q(\d)$/); + n = date.match(/^(\d+)-(\d+)$/); + o = date.match(/^(\d+)-(\d+)-(\d+)$/); + p = date.match(/^(\d+) W(\d+)$/); + q = date.match(/^(\d+)-(\d+)-(\d+)[ T](\d+):(\d+)(Z|([+-])(\d\d):?(\d\d))?$/); + r = date.match(/^(\d+)-(\d+)-(\d+)[ T](\d+):(\d+):(\d+(\.\d+)?)(Z|([+-])(\d\d):?(\d\d))?$/); + if (m) { + return new Date(parseInt(m[1], 10), parseInt(m[2], 10) * 3 - 1, 1).getTime(); + } else if (n) { + return new Date(parseInt(n[1], 10), parseInt(n[2], 10) - 1, 1).getTime(); + } else if (o) { + return new Date(parseInt(o[1], 10), parseInt(o[2], 10) - 1, parseInt(o[3], 10)).getTime(); + } else if (p) { + ret = new Date(parseInt(p[1], 10), 0, 1); + if (ret.getDay() !== 4) { + ret.setMonth(0, 1 + ((4 - ret.getDay()) + 7) % 7); + } + return ret.getTime() + parseInt(p[2], 10) * 604800000; + } else if (q) { + if (!q[6]) { + return new Date(parseInt(q[1], 10), parseInt(q[2], 10) - 1, parseInt(q[3], 10), parseInt(q[4], 10), parseInt(q[5], 10)).getTime(); + } else { + offsetmins = 0; + if (q[6] !== 'Z') { + offsetmins = parseInt(q[8], 10) * 60 + parseInt(q[9], 10); + if (q[7] === '+') { + offsetmins = 0 - offsetmins; + } + } + return Date.UTC(parseInt(q[1], 10), parseInt(q[2], 10) - 1, parseInt(q[3], 10), parseInt(q[4], 10), parseInt(q[5], 10) + offsetmins); + } + } else if (r) { + secs = parseFloat(r[6]); + isecs = Math.floor(secs); + msecs = Math.round((secs - isecs) * 1000); + if (!r[8]) { + return new Date(parseInt(r[1], 10), parseInt(r[2], 10) - 1, parseInt(r[3], 10), parseInt(r[4], 10), parseInt(r[5], 10), isecs, msecs).getTime(); + } else { + offsetmins = 0; + if (r[8] !== 'Z') { + offsetmins = parseInt(r[10], 10) * 60 + parseInt(r[11], 10); + if (r[9] === '+') { + offsetmins = 0 - offsetmins; + } + } + return Date.UTC(parseInt(r[1], 10), parseInt(r[2], 10) - 1, parseInt(r[3], 10), parseInt(r[4], 10), parseInt(r[5], 10) + offsetmins, isecs, msecs); + } + } else { + return new Date(parseInt(date, 10), 0, 1).getTime(); + } + }; + + Morris.Hover = (function() { + + Hover.defaults = { + "class": 'morris-hover morris-default-style' + }; + + function Hover(options) { + if (options == null) { + options = {}; + } + this.options = $.extend({}, Morris.Hover.defaults, options); + this.el = $("
                          "); + this.el.hide(); + this.options.parent.append(this.el); + } + + Hover.prototype.update = function(html, x, y) { + this.html(html); + this.show(); + return this.moveTo(x, y); + }; + + Hover.prototype.html = function(content) { + return this.el.html(content); + }; + + Hover.prototype.moveTo = function(x, y) { + var hoverHeight, hoverWidth, left, parentHeight, parentWidth, top; + parentWidth = this.options.parent.innerWidth(); + parentHeight = this.options.parent.innerHeight(); + hoverWidth = this.el.outerWidth(); + hoverHeight = this.el.outerHeight(); + left = Math.min(Math.max(0, x - hoverWidth / 2), parentWidth - hoverWidth); + if (y != null) { + top = y - hoverHeight - 10; + if (top < 0) { + top = y + 10; + if (top + hoverHeight > parentHeight) { + top = parentHeight / 2 - hoverHeight / 2; + } + } + } else { + top = parentHeight / 2 - hoverHeight / 2; + } + return this.el.css({ + left: left + "px", + top: parseInt(top) + "px" + }); + }; + + Hover.prototype.show = function() { + return this.el.show(); + }; + + Hover.prototype.hide = function() { + return this.el.hide(); + }; + + return Hover; + + })(); + + Morris.Line = (function(_super) { + + __extends(Line, _super); + + function Line(options) { + this.hilight = __bind(this.hilight, this); + + this.onHoverOut = __bind(this.onHoverOut, this); + + this.onHoverMove = __bind(this.onHoverMove, this); + + this.onGridClick = __bind(this.onGridClick, this); + if (!(this instanceof Morris.Line)) { + return new Morris.Line(options); + } + Line.__super__.constructor.call(this, options); + } + + Line.prototype.init = function() { + this.pointGrow = Raphael.animation({ + r: this.options.pointSize + 3 + }, 25, 'linear'); + this.pointShrink = Raphael.animation({ + r: this.options.pointSize + }, 25, 'linear'); + if (this.options.hideHover !== 'always') { + this.hover = new Morris.Hover({ + parent: this.el + }); + this.on('hovermove', this.onHoverMove); + this.on('hoverout', this.onHoverOut); + return this.on('gridclick', this.onGridClick); + } + }; + + Line.prototype.defaults = { + lineWidth: 3, + pointSize: 4, + lineColors: ['#0b62a4', '#7A92A3', '#4da74d', '#afd8f8', '#edc240', '#cb4b4b', '#9440ed'], + pointWidths: [1], + pointStrokeColors: ['#ffffff'], + pointFillColors: [], + smooth: true, + xLabels: 'auto', + xLabelFormat: null, + xLabelMargin: 24, + continuousLine: true, + hideHover: false + }; + + Line.prototype.calc = function() { + this.calcPoints(); + return this.generatePaths(); + }; + + Line.prototype.calcPoints = function() { + var row, y, _i, _len, _ref, _results; + _ref = this.data; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + row = _ref[_i]; + row._x = this.transX(row.x); + row._y = (function() { + var _j, _len1, _ref1, _results1; + _ref1 = row.y; + _results1 = []; + for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { + y = _ref1[_j]; + if (y != null) { + _results1.push(this.transY(y)); + } else { + _results1.push(y); + } + } + return _results1; + }).call(this); + _results.push(row._ymax = Math.min.apply(null, [this.bottom].concat((function() { + var _j, _len1, _ref1, _results1; + _ref1 = row._y; + _results1 = []; + for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { + y = _ref1[_j]; + if (y != null) { + _results1.push(y); + } + } + return _results1; + })()))); + } + return _results; + }; + + Line.prototype.hitTest = function(x, y) { + var index, r, _i, _len, _ref; + if (this.data.length === 0) { + return null; + } + _ref = this.data.slice(1); + for (index = _i = 0, _len = _ref.length; _i < _len; index = ++_i) { + r = _ref[index]; + if (x < (r._x + this.data[index]._x) / 2) { + break; + } + } + return index; + }; + + Line.prototype.onGridClick = function(x, y) { + var index; + index = this.hitTest(x, y); + return this.fire('click', index, this.options.data[index], x, y); + }; + + Line.prototype.onHoverMove = function(x, y) { + var index; + index = this.hitTest(x, y); + return this.displayHoverForRow(index); + }; + + Line.prototype.onHoverOut = function() { + if (this.options.hideHover !== false) { + return this.displayHoverForRow(null); + } + }; + + Line.prototype.displayHoverForRow = function(index) { + var _ref; + if (index != null) { + (_ref = this.hover).update.apply(_ref, this.hoverContentForRow(index)); + return this.hilight(index); + } else { + this.hover.hide(); + return this.hilight(); + } + }; + + Line.prototype.hoverContentForRow = function(index) { + var content, j, row, y, _i, _len, _ref; + row = this.data[index]; + content = "
                          " + row.label + "
                          "; + _ref = row.y; + for (j = _i = 0, _len = _ref.length; _i < _len; j = ++_i) { + y = _ref[j]; + content += "
                          \n " + this.options.labels[j] + ":\n " + (this.yLabelFormat(y)) + "\n
                          "; + } + if (typeof this.options.hoverCallback === 'function') { + content = this.options.hoverCallback(index, this.options, content); + } + return [content, row._x, row._ymax]; + }; + + Line.prototype.generatePaths = function() { + var c, coords, i, r, smooth; + return this.paths = (function() { + var _i, _ref, _ref1, _results; + _results = []; + for (i = _i = 0, _ref = this.options.ykeys.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { + smooth = this.options.smooth === true || (_ref1 = this.options.ykeys[i], __indexOf.call(this.options.smooth, _ref1) >= 0); + coords = (function() { + var _j, _len, _ref2, _results1; + _ref2 = this.data; + _results1 = []; + for (_j = 0, _len = _ref2.length; _j < _len; _j++) { + r = _ref2[_j]; + if (r._y[i] !== void 0) { + _results1.push({ + x: r._x, + y: r._y[i] + }); + } + } + return _results1; + }).call(this); + if (this.options.continuousLine) { + coords = (function() { + var _j, _len, _results1; + _results1 = []; + for (_j = 0, _len = coords.length; _j < _len; _j++) { + c = coords[_j]; + if (c.y !== null) { + _results1.push(c); + } + } + return _results1; + })(); + } + if (coords.length > 1) { + _results.push(Morris.Line.createPath(coords, smooth, this.bottom)); + } else { + _results.push(null); + } + } + return _results; + }).call(this); + }; + + Line.prototype.draw = function() { + if (this.options.axes) { + this.drawXAxis(); + } + this.drawSeries(); + if (this.options.hideHover === false) { + return this.displayHoverForRow(this.data.length - 1); + } + }; + + Line.prototype.drawXAxis = function() { + var drawLabel, l, labels, prevAngleMargin, prevLabelMargin, row, ypos, _i, _len, _results, + _this = this; + ypos = this.bottom + this.options.padding / 2; + prevLabelMargin = null; + prevAngleMargin = null; + drawLabel = function(labelText, xpos) { + var label, labelBox, margin, offset, textBox; + label = _this.drawXAxisLabel(_this.transX(xpos), ypos, labelText); + textBox = label.getBBox(); + label.transform("r" + (-_this.options.xLabelAngle)); + labelBox = label.getBBox(); + label.transform("t0," + (labelBox.height / 2) + "..."); + if (_this.options.xLabelAngle !== 0) { + offset = -0.5 * textBox.width * Math.cos(_this.options.xLabelAngle * Math.PI / 180.0); + label.transform("t" + offset + ",0..."); + } + labelBox = label.getBBox(); + if ((!(prevLabelMargin != null) || prevLabelMargin >= labelBox.x + labelBox.width || (prevAngleMargin != null) && prevAngleMargin >= labelBox.x) && labelBox.x >= 0 && (labelBox.x + labelBox.width) < _this.el.width()) { + if (_this.options.xLabelAngle !== 0) { + margin = 1.25 * _this.options.gridTextSize / Math.sin(_this.options.xLabelAngle * Math.PI / 180.0); + prevAngleMargin = labelBox.x - margin; + } + return prevLabelMargin = labelBox.x - _this.options.xLabelMargin; + } else { + return label.remove(); + } + }; + if (this.options.parseTime) { + if (this.data.length === 1 && this.options.xLabels === 'auto') { + labels = [[this.data[0].label, this.data[0].x]]; + } else { + labels = Morris.labelSeries(this.xmin, this.xmax, this.width, this.options.xLabels, this.options.xLabelFormat); + } + } else { + labels = (function() { + var _i, _len, _ref, _results; + _ref = this.data; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + row = _ref[_i]; + _results.push([row.label, row.x]); + } + return _results; + }).call(this); + } + labels.reverse(); + _results = []; + for (_i = 0, _len = labels.length; _i < _len; _i++) { + l = labels[_i]; + _results.push(drawLabel(l[0], l[1])); + } + return _results; + }; + + Line.prototype.drawSeries = function() { + var i, _i, _j, _ref, _ref1, _results; + this.seriesPoints = []; + for (i = _i = _ref = this.options.ykeys.length - 1; _ref <= 0 ? _i <= 0 : _i >= 0; i = _ref <= 0 ? ++_i : --_i) { + this._drawLineFor(i); + } + _results = []; + for (i = _j = _ref1 = this.options.ykeys.length - 1; _ref1 <= 0 ? _j <= 0 : _j >= 0; i = _ref1 <= 0 ? ++_j : --_j) { + _results.push(this._drawPointFor(i)); + } + return _results; + }; + + Line.prototype._drawPointFor = function(index) { + var circle, row, _i, _len, _ref, _results; + this.seriesPoints[index] = []; + _ref = this.data; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + row = _ref[_i]; + circle = null; + if (row._y[index] != null) { + circle = this.drawLinePoint(row._x, row._y[index], this.options.pointSize, this.colorFor(row, index, 'point'), index); + } + _results.push(this.seriesPoints[index].push(circle)); + } + return _results; + }; + + Line.prototype._drawLineFor = function(index) { + var path; + path = this.paths[index]; + if (path !== null) { + return this.drawLinePath(path, this.colorFor(null, index, 'line')); + } + }; + + Line.createPath = function(coords, smooth, bottom) { + var coord, g, grads, i, ix, lg, path, prevCoord, x1, x2, y1, y2, _i, _len; + path = ""; + if (smooth) { + grads = Morris.Line.gradients(coords); + } + prevCoord = { + y: null + }; + for (i = _i = 0, _len = coords.length; _i < _len; i = ++_i) { + coord = coords[i]; + if (coord.y != null) { + if (prevCoord.y != null) { + if (smooth) { + g = grads[i]; + lg = grads[i - 1]; + ix = (coord.x - prevCoord.x) / 4; + x1 = prevCoord.x + ix; + y1 = Math.min(bottom, prevCoord.y + ix * lg); + x2 = coord.x - ix; + y2 = Math.min(bottom, coord.y - ix * g); + path += "C" + x1 + "," + y1 + "," + x2 + "," + y2 + "," + coord.x + "," + coord.y; + } else { + path += "L" + coord.x + "," + coord.y; + } + } else { + if (!smooth || (grads[i] != null)) { + path += "M" + coord.x + "," + coord.y; + } + } + } + prevCoord = coord; + } + return path; + }; + + Line.gradients = function(coords) { + var coord, grad, i, nextCoord, prevCoord, _i, _len, _results; + grad = function(a, b) { + return (a.y - b.y) / (a.x - b.x); + }; + _results = []; + for (i = _i = 0, _len = coords.length; _i < _len; i = ++_i) { + coord = coords[i]; + if (coord.y != null) { + nextCoord = coords[i + 1] || { + y: null + }; + prevCoord = coords[i - 1] || { + y: null + }; + if ((prevCoord.y != null) && (nextCoord.y != null)) { + _results.push(grad(prevCoord, nextCoord)); + } else if (prevCoord.y != null) { + _results.push(grad(prevCoord, coord)); + } else if (nextCoord.y != null) { + _results.push(grad(coord, nextCoord)); + } else { + _results.push(null); + } + } else { + _results.push(null); + } + } + return _results; + }; + + Line.prototype.hilight = function(index) { + var i, _i, _j, _ref, _ref1; + if (this.prevHilight !== null && this.prevHilight !== index) { + for (i = _i = 0, _ref = this.seriesPoints.length - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; i = 0 <= _ref ? ++_i : --_i) { + if (this.seriesPoints[i][this.prevHilight]) { + this.seriesPoints[i][this.prevHilight].animate(this.pointShrink); + } + } + } + if (index !== null && this.prevHilight !== index) { + for (i = _j = 0, _ref1 = this.seriesPoints.length - 1; 0 <= _ref1 ? _j <= _ref1 : _j >= _ref1; i = 0 <= _ref1 ? ++_j : --_j) { + if (this.seriesPoints[i][index]) { + this.seriesPoints[i][index].animate(this.pointGrow); + } + } + } + return this.prevHilight = index; + }; + + Line.prototype.colorFor = function(row, sidx, type) { + if (typeof this.options.lineColors === 'function') { + return this.options.lineColors.call(this, row, sidx, type); + } else if (type === 'point') { + return this.options.pointFillColors[sidx % this.options.pointFillColors.length] || this.options.lineColors[sidx % this.options.lineColors.length]; + } else { + return this.options.lineColors[sidx % this.options.lineColors.length]; + } + }; + + Line.prototype.drawXAxisLabel = function(xPos, yPos, text) { + return this.raphael.text(xPos, yPos, text).attr('font-size', this.options.gridTextSize).attr('font-family', this.options.gridTextFamily).attr('font-weight', this.options.gridTextWeight).attr('fill', this.options.gridTextColor); + }; + + Line.prototype.drawLinePath = function(path, lineColor) { + return this.raphael.path(path).attr('stroke', lineColor).attr('stroke-width', this.options.lineWidth); + }; + + Line.prototype.drawLinePoint = function(xPos, yPos, size, pointColor, lineIndex) { + return this.raphael.circle(xPos, yPos, size).attr('fill', pointColor).attr('stroke-width', this.strokeWidthForSeries(lineIndex)).attr('stroke', this.strokeForSeries(lineIndex)); + }; + + Line.prototype.strokeWidthForSeries = function(index) { + return this.options.pointWidths[index % this.options.pointWidths.length]; + }; + + Line.prototype.strokeForSeries = function(index) { + return this.options.pointStrokeColors[index % this.options.pointStrokeColors.length]; + }; + + return Line; + + })(Morris.Grid); + + Morris.labelSeries = function(dmin, dmax, pxwidth, specName, xLabelFormat) { + var d, d0, ddensity, name, ret, s, spec, t, _i, _len, _ref; + ddensity = 200 * (dmax - dmin) / pxwidth; + d0 = new Date(dmin); + spec = Morris.LABEL_SPECS[specName]; + if (spec === void 0) { + _ref = Morris.AUTO_LABEL_ORDER; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + name = _ref[_i]; + s = Morris.LABEL_SPECS[name]; + if (ddensity >= s.span) { + spec = s; + break; + } + } + } + if (spec === void 0) { + spec = Morris.LABEL_SPECS["second"]; + } + if (xLabelFormat) { + spec = $.extend({}, spec, { + fmt: xLabelFormat + }); + } + d = spec.start(d0); + ret = []; + while ((t = d.getTime()) <= dmax) { + if (t >= dmin) { + ret.push([spec.fmt(d), t]); + } + spec.incr(d); + } + return ret; + }; + + minutesSpecHelper = function(interval) { + return { + span: interval * 60 * 1000, + start: function(d) { + return new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours()); + }, + fmt: function(d) { + return "" + (Morris.pad2(d.getHours())) + ":" + (Morris.pad2(d.getMinutes())); + }, + incr: function(d) { + return d.setUTCMinutes(d.getUTCMinutes() + interval); + } + }; + }; + + secondsSpecHelper = function(interval) { + return { + span: interval * 1000, + start: function(d) { + return new Date(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes()); + }, + fmt: function(d) { + return "" + (Morris.pad2(d.getHours())) + ":" + (Morris.pad2(d.getMinutes())) + ":" + (Morris.pad2(d.getSeconds())); + }, + incr: function(d) { + return d.setUTCSeconds(d.getUTCSeconds() + interval); + } + }; + }; + + Morris.LABEL_SPECS = { + "decade": { + span: 172800000000, + start: function(d) { + return new Date(d.getFullYear() - d.getFullYear() % 10, 0, 1); + }, + fmt: function(d) { + return "" + (d.getFullYear()); + }, + incr: function(d) { + return d.setFullYear(d.getFullYear() + 10); + } + }, + "year": { + span: 17280000000, + start: function(d) { + return new Date(d.getFullYear(), 0, 1); + }, + fmt: function(d) { + return "" + (d.getFullYear()); + }, + incr: function(d) { + return d.setFullYear(d.getFullYear() + 1); + } + }, + "month": { + span: 2419200000, + start: function(d) { + return new Date(d.getFullYear(), d.getMonth(), 1); + }, + fmt: function(d) { + return "" + (d.getFullYear()) + "-" + (Morris.pad2(d.getMonth() + 1)); + }, + incr: function(d) { + return d.setMonth(d.getMonth() + 1); + } + }, + "day": { + span: 86400000, + start: function(d) { + return new Date(d.getFullYear(), d.getMonth(), d.getDate()); + }, + fmt: function(d) { + return "" + (d.getFullYear()) + "-" + (Morris.pad2(d.getMonth() + 1)) + "-" + (Morris.pad2(d.getDate())); + }, + incr: function(d) { + return d.setDate(d.getDate() + 1); + } + }, + "hour": minutesSpecHelper(60), + "30min": minutesSpecHelper(30), + "15min": minutesSpecHelper(15), + "10min": minutesSpecHelper(10), + "5min": minutesSpecHelper(5), + "minute": minutesSpecHelper(1), + "30sec": secondsSpecHelper(30), + "15sec": secondsSpecHelper(15), + "10sec": secondsSpecHelper(10), + "5sec": secondsSpecHelper(5), + "second": secondsSpecHelper(1) + }; + + Morris.AUTO_LABEL_ORDER = ["decade", "year", "month", "day", "hour", "30min", "15min", "10min", "5min", "minute", "30sec", "15sec", "10sec", "5sec", "second"]; + + Morris.Area = (function(_super) { + var areaDefaults; + + __extends(Area, _super); + + areaDefaults = { + fillOpacity: 'auto', + behaveLikeLine: false + }; + + function Area(options) { + var areaOptions; + if (!(this instanceof Morris.Area)) { + return new Morris.Area(options); + } + areaOptions = $.extend({}, areaDefaults, options); + this.cumulative = !areaOptions.behaveLikeLine; + if (areaOptions.fillOpacity === 'auto') { + areaOptions.fillOpacity = areaOptions.behaveLikeLine ? .8 : 1; + } + Area.__super__.constructor.call(this, areaOptions); + } + + Area.prototype.calcPoints = function() { + var row, total, y, _i, _len, _ref, _results; + _ref = this.data; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + row = _ref[_i]; + row._x = this.transX(row.x); + total = 0; + row._y = (function() { + var _j, _len1, _ref1, _results1; + _ref1 = row.y; + _results1 = []; + for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { + y = _ref1[_j]; + if (this.options.behaveLikeLine) { + _results1.push(this.transY(y)); + } else { + total += y || 0; + _results1.push(this.transY(total)); + } + } + return _results1; + }).call(this); + _results.push(row._ymax = Math.max.apply(Math, row._y)); + } + return _results; + }; + + Area.prototype.drawSeries = function() { + var i, range, _i, _j, _k, _len, _ref, _ref1, _results, _results1, _results2; + this.seriesPoints = []; + if (this.options.behaveLikeLine) { + range = (function() { + _results = []; + for (var _i = 0, _ref = this.options.ykeys.length - 1; 0 <= _ref ? _i <= _ref : _i >= _ref; 0 <= _ref ? _i++ : _i--){ _results.push(_i); } + return _results; + }).apply(this); + } else { + range = (function() { + _results1 = []; + for (var _j = _ref1 = this.options.ykeys.length - 1; _ref1 <= 0 ? _j <= 0 : _j >= 0; _ref1 <= 0 ? _j++ : _j--){ _results1.push(_j); } + return _results1; + }).apply(this); + } + _results2 = []; + for (_k = 0, _len = range.length; _k < _len; _k++) { + i = range[_k]; + this._drawFillFor(i); + this._drawLineFor(i); + _results2.push(this._drawPointFor(i)); + } + return _results2; + }; + + Area.prototype._drawFillFor = function(index) { + var path; + path = this.paths[index]; + if (path !== null) { + path = path + ("L" + (this.transX(this.xmax)) + "," + this.bottom + "L" + (this.transX(this.xmin)) + "," + this.bottom + "Z"); + return this.drawFilledPath(path, this.fillForSeries(index)); + } + }; + + Area.prototype.fillForSeries = function(i) { + var color; + color = Raphael.rgb2hsl(this.colorFor(this.data[i], i, 'line')); + return Raphael.hsl(color.h, this.options.behaveLikeLine ? color.s * 0.9 : color.s * 0.75, Math.min(0.98, this.options.behaveLikeLine ? color.l * 1.2 : color.l * 1.25)); + }; + + Area.prototype.drawFilledPath = function(path, fill) { + return this.raphael.path(path).attr('fill', fill).attr('fill-opacity', this.options.fillOpacity).attr('stroke-width', 0); + }; + + return Area; + + })(Morris.Line); + + Morris.Bar = (function(_super) { + + __extends(Bar, _super); + + function Bar(options) { + this.onHoverOut = __bind(this.onHoverOut, this); + + this.onHoverMove = __bind(this.onHoverMove, this); + + this.onGridClick = __bind(this.onGridClick, this); + if (!(this instanceof Morris.Bar)) { + return new Morris.Bar(options); + } + Bar.__super__.constructor.call(this, $.extend({}, options, { + parseTime: false + })); + } + + Bar.prototype.init = function() { + this.cumulative = this.options.stacked; + if (this.options.hideHover !== 'always') { + this.hover = new Morris.Hover({ + parent: this.el + }); + this.on('hovermove', this.onHoverMove); + this.on('hoverout', this.onHoverOut); + return this.on('gridclick', this.onGridClick); + } + }; + + Bar.prototype.defaults = { + barSizeRatio: 0.75, + barGap: 3, + barColors: ['#0b62a4', '#7a92a3', '#4da74d', '#afd8f8', '#edc240', '#cb4b4b', '#9440ed'], + xLabelMargin: 50 + }; + + Bar.prototype.calc = function() { + var _ref; + this.calcBars(); + if (this.options.hideHover === false) { + return (_ref = this.hover).update.apply(_ref, this.hoverContentForRow(this.data.length - 1)); + } + }; + + Bar.prototype.calcBars = function() { + var idx, row, y, _i, _len, _ref, _results; + _ref = this.data; + _results = []; + for (idx = _i = 0, _len = _ref.length; _i < _len; idx = ++_i) { + row = _ref[idx]; + row._x = this.left + this.width * (idx + 0.5) / this.data.length; + _results.push(row._y = (function() { + var _j, _len1, _ref1, _results1; + _ref1 = row.y; + _results1 = []; + for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { + y = _ref1[_j]; + if (y != null) { + _results1.push(this.transY(y)); + } else { + _results1.push(null); + } + } + return _results1; + }).call(this)); + } + return _results; + }; + + Bar.prototype.draw = function() { + if (this.options.axes) { + this.drawXAxis(); + } + return this.drawSeries(); + }; + + Bar.prototype.drawXAxis = function() { + var i, label, labelBox, margin, offset, prevAngleMargin, prevLabelMargin, row, textBox, ypos, _i, _ref, _results; + ypos = this.bottom + this.options.padding / 2; + prevLabelMargin = null; + prevAngleMargin = null; + _results = []; + for (i = _i = 0, _ref = this.data.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { + row = this.data[this.data.length - 1 - i]; + label = this.drawXAxisLabel(row._x, ypos, row.label); + textBox = label.getBBox(); + label.transform("r" + (-this.options.xLabelAngle)); + labelBox = label.getBBox(); + label.transform("t0," + (labelBox.height / 2) + "..."); + if (this.options.xLabelAngle !== 0) { + offset = -0.5 * textBox.width * Math.cos(this.options.xLabelAngle * Math.PI / 180.0); + label.transform("t" + offset + ",0..."); + } + if ((!(prevLabelMargin != null) || prevLabelMargin >= labelBox.x + labelBox.width || (prevAngleMargin != null) && prevAngleMargin >= labelBox.x) && labelBox.x >= 0 && (labelBox.x + labelBox.width) < this.el.width()) { + if (this.options.xLabelAngle !== 0) { + margin = 1.25 * this.options.gridTextSize / Math.sin(this.options.xLabelAngle * Math.PI / 180.0); + prevAngleMargin = labelBox.x - margin; + } + _results.push(prevLabelMargin = labelBox.x - this.options.xLabelMargin); + } else { + _results.push(label.remove()); + } + } + return _results; + }; + + Bar.prototype.drawSeries = function() { + var barWidth, bottom, groupWidth, idx, lastTop, left, leftPadding, numBars, row, sidx, size, top, ypos, zeroPos; + groupWidth = this.width / this.options.data.length; + numBars = this.options.stacked != null ? 1 : this.options.ykeys.length; + barWidth = (groupWidth * this.options.barSizeRatio - this.options.barGap * (numBars - 1)) / numBars; + leftPadding = groupWidth * (1 - this.options.barSizeRatio) / 2; + zeroPos = this.ymin <= 0 && this.ymax >= 0 ? this.transY(0) : null; + return this.bars = (function() { + var _i, _len, _ref, _results; + _ref = this.data; + _results = []; + for (idx = _i = 0, _len = _ref.length; _i < _len; idx = ++_i) { + row = _ref[idx]; + lastTop = 0; + _results.push((function() { + var _j, _len1, _ref1, _results1; + _ref1 = row._y; + _results1 = []; + for (sidx = _j = 0, _len1 = _ref1.length; _j < _len1; sidx = ++_j) { + ypos = _ref1[sidx]; + if (ypos !== null) { + if (zeroPos) { + top = Math.min(ypos, zeroPos); + bottom = Math.max(ypos, zeroPos); + } else { + top = ypos; + bottom = this.bottom; + } + left = this.left + idx * groupWidth + leftPadding; + if (!this.options.stacked) { + left += sidx * (barWidth + this.options.barGap); + } + size = bottom - top; + if (this.options.stacked) { + top -= lastTop; + } + this.drawBar(left, top, barWidth, size, this.colorFor(row, sidx, 'bar')); + _results1.push(lastTop += size); + } else { + _results1.push(null); + } + } + return _results1; + }).call(this)); + } + return _results; + }).call(this); + }; + + Bar.prototype.colorFor = function(row, sidx, type) { + var r, s; + if (typeof this.options.barColors === 'function') { + r = { + x: row.x, + y: row.y[sidx], + label: row.label + }; + s = { + index: sidx, + key: this.options.ykeys[sidx], + label: this.options.labels[sidx] + }; + return this.options.barColors.call(this, r, s, type); + } else { + return this.options.barColors[sidx % this.options.barColors.length]; + } + }; + + Bar.prototype.hitTest = function(x, y) { + if (this.data.length === 0) { + return null; + } + x = Math.max(Math.min(x, this.right), this.left); + return Math.min(this.data.length - 1, Math.floor((x - this.left) / (this.width / this.data.length))); + }; + + Bar.prototype.onGridClick = function(x, y) { + var index; + index = this.hitTest(x, y); + return this.fire('click', index, this.options.data[index], x, y); + }; + + Bar.prototype.onHoverMove = function(x, y) { + var index, _ref; + index = this.hitTest(x, y); + return (_ref = this.hover).update.apply(_ref, this.hoverContentForRow(index)); + }; + + Bar.prototype.onHoverOut = function() { + if (this.options.hideHover !== false) { + return this.hover.hide(); + } + }; + + Bar.prototype.hoverContentForRow = function(index) { + var content, j, row, x, y, _i, _len, _ref; + row = this.data[index]; + content = "
                          " + row.label + "
                          "; + _ref = row.y; + for (j = _i = 0, _len = _ref.length; _i < _len; j = ++_i) { + y = _ref[j]; + content += "
                          \n " + this.options.labels[j] + ":\n " + (this.yLabelFormat(y)) + "\n
                          "; + } + if (typeof this.options.hoverCallback === 'function') { + content = this.options.hoverCallback(index, this.options, content); + } + x = this.left + (index + 0.5) * this.width / this.data.length; + return [content, x]; + }; + + Bar.prototype.drawXAxisLabel = function(xPos, yPos, text) { + var label; + return label = this.raphael.text(xPos, yPos, text).attr('font-size', this.options.gridTextSize).attr('font-family', this.options.gridTextFamily).attr('font-weight', this.options.gridTextWeight).attr('fill', this.options.gridTextColor); + }; + + Bar.prototype.drawBar = function(xPos, yPos, width, height, barColor) { + return this.raphael.rect(xPos, yPos, width, height).attr('fill', barColor).attr('stroke-width', 0); + }; + + return Bar; + + })(Morris.Grid); + + Morris.Donut = (function(_super) { + + __extends(Donut, _super); + + Donut.prototype.defaults = { + colors: ['#0B62A4', '#3980B5', '#679DC6', '#95BBD7', '#B0CCE1', '#095791', '#095085', '#083E67', '#052C48', '#042135'], + backgroundColor: '#FFFFFF', + labelColor: '#000000', + formatter: Morris.commas + }; + + function Donut(options) { + this.select = __bind(this.select, this); + + this.click = __bind(this.click, this); + + var row; + if (!(this instanceof Morris.Donut)) { + return new Morris.Donut(options); + } + if (typeof options.element === 'string') { + this.el = $(document.getElementById(options.element)); + } else { + this.el = $(options.element); + } + this.options = $.extend({}, this.defaults, options); + if (this.el === null || this.el.length === 0) { + throw new Error("Graph placeholder not found."); + } + if (options.data === void 0 || options.data.length === 0) { + return; + } + this.data = options.data; + this.values = (function() { + var _i, _len, _ref, _results; + _ref = this.data; + _results = []; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + row = _ref[_i]; + _results.push(parseFloat(row.value)); + } + return _results; + }).call(this); + this.redraw(); + } + + Donut.prototype.redraw = function() { + var C, cx, cy, i, idx, last, max_value, min, next, seg, total, value, w, _i, _j, _k, _len, _len1, _len2, _ref, _ref1, _ref2, _results; + this.el.empty(); + this.raphael = new Raphael(this.el[0]); + cx = this.el.width() / 2; + cy = this.el.height() / 2; + w = (Math.min(cx, cy) - 10) / 3; + total = 0; + _ref = this.values; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + value = _ref[_i]; + total += value; + } + min = 5 / (2 * w); + C = 1.9999 * Math.PI - min * this.data.length; + last = 0; + idx = 0; + this.segments = []; + _ref1 = this.values; + for (i = _j = 0, _len1 = _ref1.length; _j < _len1; i = ++_j) { + value = _ref1[i]; + next = last + min + C * (value / total); + seg = new Morris.DonutSegment(cx, cy, w * 2, w, last, next, this.options.colors[idx % this.options.colors.length], this.options.backgroundColor, idx, this.raphael); + seg.render(); + this.segments.push(seg); + seg.on('hover', this.select); + seg.on('click', this.click); + last = next; + idx += 1; + } + this.text1 = this.drawEmptyDonutLabel(cx, cy - 10, this.options.labelColor, 15, 800); + this.text2 = this.drawEmptyDonutLabel(cx, cy + 10, this.options.labelColor, 14); + max_value = Math.max.apply(null, (function() { + var _k, _len2, _ref2, _results; + _ref2 = this.values; + _results = []; + for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { + value = _ref2[_k]; + _results.push(value); + } + return _results; + }).call(this)); + idx = 0; + _ref2 = this.values; + _results = []; + for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { + value = _ref2[_k]; + if (value === max_value) { + this.select(idx); + break; + } + _results.push(idx += 1); + } + return _results; + }; + + Donut.prototype.click = function(idx) { + return this.fire('click', idx, this.data[idx]); + }; + + Donut.prototype.select = function(idx) { + var row, s, segment, _i, _len, _ref; + _ref = this.segments; + for (_i = 0, _len = _ref.length; _i < _len; _i++) { + s = _ref[_i]; + s.deselect(); + } + segment = this.segments[idx]; + segment.select(); + row = this.data[idx]; + return this.setLabels(row.label, this.options.formatter(row.value, row)); + }; + + Donut.prototype.setLabels = function(label1, label2) { + var inner, maxHeightBottom, maxHeightTop, maxWidth, text1bbox, text1scale, text2bbox, text2scale; + inner = (Math.min(this.el.width() / 2, this.el.height() / 2) - 10) * 2 / 3; + maxWidth = 1.8 * inner; + maxHeightTop = inner / 2; + maxHeightBottom = inner / 3; + this.text1.attr({ + text: label1, + transform: '' + }); + text1bbox = this.text1.getBBox(); + text1scale = Math.min(maxWidth / text1bbox.width, maxHeightTop / text1bbox.height); + this.text1.attr({ + transform: "S" + text1scale + "," + text1scale + "," + (text1bbox.x + text1bbox.width / 2) + "," + (text1bbox.y + text1bbox.height) + }); + this.text2.attr({ + text: label2, + transform: '' + }); + text2bbox = this.text2.getBBox(); + text2scale = Math.min(maxWidth / text2bbox.width, maxHeightBottom / text2bbox.height); + return this.text2.attr({ + transform: "S" + text2scale + "," + text2scale + "," + (text2bbox.x + text2bbox.width / 2) + "," + text2bbox.y + }); + }; + + Donut.prototype.drawEmptyDonutLabel = function(xPos, yPos, color, fontSize, fontWeight) { + var text; + text = this.raphael.text(xPos, yPos, '').attr('font-size', fontSize).attr('fill', color); + if (fontWeight != null) { + text.attr('font-weight', fontWeight); + } + return text; + }; + + return Donut; + + })(Morris.EventEmitter); + + Morris.DonutSegment = (function(_super) { + + __extends(DonutSegment, _super); + + function DonutSegment(cx, cy, inner, outer, p0, p1, color, backgroundColor, index, raphael) { + this.cx = cx; + this.cy = cy; + this.inner = inner; + this.outer = outer; + this.color = color; + this.backgroundColor = backgroundColor; + this.index = index; + this.raphael = raphael; + this.deselect = __bind(this.deselect, this); + + this.select = __bind(this.select, this); + + this.sin_p0 = Math.sin(p0); + this.cos_p0 = Math.cos(p0); + this.sin_p1 = Math.sin(p1); + this.cos_p1 = Math.cos(p1); + this.is_long = (p1 - p0) > Math.PI ? 1 : 0; + this.path = this.calcSegment(this.inner + 3, this.inner + this.outer - 5); + this.selectedPath = this.calcSegment(this.inner + 3, this.inner + this.outer); + this.hilight = this.calcArc(this.inner); + } + + DonutSegment.prototype.calcArcPoints = function(r) { + return [this.cx + r * this.sin_p0, this.cy + r * this.cos_p0, this.cx + r * this.sin_p1, this.cy + r * this.cos_p1]; + }; + + DonutSegment.prototype.calcSegment = function(r1, r2) { + var ix0, ix1, iy0, iy1, ox0, ox1, oy0, oy1, _ref, _ref1; + _ref = this.calcArcPoints(r1), ix0 = _ref[0], iy0 = _ref[1], ix1 = _ref[2], iy1 = _ref[3]; + _ref1 = this.calcArcPoints(r2), ox0 = _ref1[0], oy0 = _ref1[1], ox1 = _ref1[2], oy1 = _ref1[3]; + return ("M" + ix0 + "," + iy0) + ("A" + r1 + "," + r1 + ",0," + this.is_long + ",0," + ix1 + "," + iy1) + ("L" + ox1 + "," + oy1) + ("A" + r2 + "," + r2 + ",0," + this.is_long + ",1," + ox0 + "," + oy0) + "Z"; + }; + + DonutSegment.prototype.calcArc = function(r) { + var ix0, ix1, iy0, iy1, _ref; + _ref = this.calcArcPoints(r), ix0 = _ref[0], iy0 = _ref[1], ix1 = _ref[2], iy1 = _ref[3]; + return ("M" + ix0 + "," + iy0) + ("A" + r + "," + r + ",0," + this.is_long + ",0," + ix1 + "," + iy1); + }; + + DonutSegment.prototype.render = function() { + var _this = this; + this.arc = this.drawDonutArc(this.hilight, this.color); + return this.seg = this.drawDonutSegment(this.path, this.color, this.backgroundColor, function() { + return _this.fire('hover', _this.index); + }, function() { + return _this.fire('click', _this.index); + }); + }; + + DonutSegment.prototype.drawDonutArc = function(path, color) { + return this.raphael.path(path).attr({ + stroke: color, + 'stroke-width': 2, + opacity: 0 + }); + }; + + DonutSegment.prototype.drawDonutSegment = function(path, fillColor, strokeColor, hoverFunction, clickFunction) { + return this.raphael.path(path).attr({ + fill: fillColor, + stroke: strokeColor, + 'stroke-width': 3 + }).hover(hoverFunction).click(clickFunction); + }; + + DonutSegment.prototype.select = function() { + if (!this.selected) { + this.seg.animate({ + path: this.selectedPath + }, 150, '<>'); + this.arc.animate({ + opacity: 1 + }, 150, '<>'); + return this.selected = true; + } + }; + + DonutSegment.prototype.deselect = function() { + if (this.selected) { + this.seg.animate({ + path: this.path + }, 150, '<>'); + this.arc.animate({ + opacity: 0 + }, 150, '<>'); + return this.selected = false; + } + }; + + return DonutSegment; + + })(Morris.EventEmitter); + +}).call(this); From 307300feddbdf6e43a60ffb2d1214079de0f54d0 Mon Sep 17 00:00:00 2001 From: Ellis Berner Date: Thu, 10 Oct 2013 17:05:35 -0700 Subject: [PATCH 11/26] Create morris.min.js --- ajax/libs/morris.js/0.4.3/morris.min.js | 1 + 1 file changed, 1 insertion(+) create mode 100644 ajax/libs/morris.js/0.4.3/morris.min.js diff --git a/ajax/libs/morris.js/0.4.3/morris.min.js b/ajax/libs/morris.js/0.4.3/morris.min.js new file mode 100644 index 000000000..a0a5e2f4e --- /dev/null +++ b/ajax/libs/morris.js/0.4.3/morris.min.js @@ -0,0 +1 @@ +(function(){var e,t,n,r,i=[].slice,s={}.hasOwnProperty,o=function(e,t){function r(){this.constructor=e}for(var n in t)s.call(t,n)&&(e[n]=t[n]);return r.prototype=t.prototype,e.prototype=new r,e.__super__=t.prototype,e},u=function(e,t){return function(){return e.apply(t,arguments)}},a=[].indexOf||function(e){for(var t=0,n=this.length;tn.length&&(r+=i.slice(n.length)),r):"-"},t.pad2=function(e){return(e<10?"0":"")+e},t.Grid=function(n){function r(t){var n=this;typeof t.element=="string"?this.el=e(document.getElementById(t.element)):this.el=e(t.element);if(this.el==null||this.el.length===0)throw new Error("Graph container element not found");this.el.css("position")==="static"&&this.el.css("position","relative"),this.options=e.extend({},this.gridDefaults,this.defaults||{},t),typeof this.options.units=="string"&&(this.options.postUnits=t.units),this.raphael=new Raphael(this.el[0]),this.elementWidth=null,this.elementHeight=null,this.dirty=!1,this.init&&this.init(),this.setData(this.options.data),this.el.bind("mousemove",function(e){var t;return t=n.el.offset(),n.fire("hovermove",e.pageX-t.left,e.pageY-t.top)}),this.el.bind("mouseout",function(e){return n.fire("hoverout")}),this.el.bind("touchstart touchmove touchend",function(e){var t,r;return r=e.originalEvent.touches[0]||e.originalEvent.changedTouches[0],t=n.el.offset(),n.fire("hover",r.pageX-t.left,r.pageY-t.top),r}),this.el.bind("click",function(e){var t;return t=n.el.offset(),n.fire("gridclick",e.pageX-t.left,e.pageY-t.top)}),this.postInit&&this.postInit()}return o(r,n),r.prototype.gridDefaults={dateFormat:null,axes:!0,grid:!0,gridLineColor:"#aaa",gridStrokeWidth:.5,gridTextColor:"#888",gridTextSize:12,gridTextFamily:"sans-serif",gridTextWeight:"normal",hideHover:!1,yLabelFormat:null,xLabelAngle:0,numLines:5,padding:25,parseTime:!0,postUnits:"",preUnits:"",ymax:"auto",ymin:"auto 0",goals:[],goalStrokeWidth:1,goalLineColors:["#666633","#999966","#cc6666","#663333"],events:[],eventStrokeWidth:1,eventLineColors:["#005a04","#ccffbb","#3a5f0b","#005502"]},r.prototype.setData=function(e,n){var r,i,s,o,u,a,f,l,c,h,p,d,v,m;n==null&&(n=!0),this.options.data=e;if(e==null||e.length===0){this.data=[],this.raphael.clear(),this.hover!=null&&this.hover.hide();return}d=this.cumulative?0:null,v=this.cumulative?0:null,this.options.goals.length>0&&(u=Math.min.apply(null,this.options.goals),o=Math.max.apply(null,this.options.goals),v=v!=null?Math.min(v,u):u,d=d!=null?Math.max(d,o):o),this.data=function(){var n,r,o;o=[];for(s=n=0,r=e.length;nt.x)-(t.x>e.x)})),this.xmin=this.data[0].x,this.xmax=this.data[this.data.length-1].x,this.events=[],this.options.parseTime&&this.options.events.length>0&&(this.events=function(){var e,n,i,s;i=this.options.events,s=[];for(e=0,n=i.length;e=n;h=e+=l)r.push(h);return r}.call(this));this.dirty=!0;if(n)return this.redraw()},r.prototype.yboundary=function(e,t){var n,r;return n=this.options["y"+e],typeof n=="string"?n.slice(0,4)==="auto"?n.length>5?(r=parseInt(n.slice(5),10),t==null?r:Math[e](t,r)):t!=null?t:0:parseInt(n,10):n},r.prototype.autoGridLines=function(e,t,n){var r,i,s,o,u,a,f,l,c;return u=t-e,c=Math.floor(Math.log(u)/Math.log(10)),f=Math.pow(10,c),i=Math.floor(e/f)*f,r=Math.ceil(t/f)*f,a=(r-i)/(n-1),f===1&&a>1&&Math.ceil(a)!==a&&(a=Math.ceil(a),r=i+a*(n-1)),i<0&&r>0&&(i=Math.floor(e/a)*a,r=Math.ceil(t/a)*a),a<1?(o=Math.floor(Math.log(a)/Math.log(10)),s=function(){var e,t;t=[];for(l=e=i;i<=r?e<=r:e>=r;l=e+=a)t.push(parseFloat(l.toFixed(1-o)));return t}()):s=function(){var e,t;t=[];for(l=e=i;i<=r?e<=r:e>=r;l=e+=a)t.push(l);return t}(),s},r.prototype._calc=function(){var e,t,n,r,i,s;i=this.el.width(),n=this.el.height();if(this.elementWidth!==i||this.elementHeight!==n||this.dirty){this.elementWidth=i,this.elementHeight=n,this.dirty=!1,this.left=this.options.padding,this.right=this.elementWidth-this.options.padding,this.top=this.options.padding,this.bottom=this.elementHeight-this.options.padding,this.options.axes&&(s=function(){var e,n,r,i;r=this.grid,i=[];for(e=0,n=r.length;et;r=0<=t?++e:--e)n.push(this.measureText(this.data[r].text,-this.options.xLabelAngle).height);return n}.call(this),this.bottom-=Math.max.apply(Math,e)),this.width=Math.max(1,this.right-this.left),this.height=Math.max(1,this.bottom-this.top),this.dx=this.width/(this.xmax-this.xmin),this.dy=this.height/(this.ymax-this.ymin);if(this.calc)return this.calc()}},r.prototype.transY=function(e){return this.bottom-(e-this.ymin)*this.dy},r.prototype.transX=function(e){return this.data.length===1?(this.left+this.right)/2:this.left+(e-this.xmin)*this.dx},r.prototype.redraw=function(){this.raphael.clear(),this._calc(),this.drawGrid(),this.drawGoals(),this.drawEvents();if(this.draw)return this.draw()},r.prototype.measureText=function(e,t){var n,r;return t==null&&(t=0),r=this.raphael.text(100,100,e).attr("font-size",this.options.gridTextSize).attr("font-family",this.options.gridTextFamily).attr("font-weight",this.options.gridTextWeight).rotate(t),n=r.getBBox(),r.remove(),n},r.prototype.yAxisFormat=function(e){return this.yLabelFormat(e)},r.prototype.yLabelFormat=function(e){return typeof this.options.yLabelFormat=="function"?this.options.yLabelFormat(e):""+this.options.preUnits+t.commas(e)+this.options.postUnits},r.prototype.updateHover=function(e,t){var n,r;n=this.hitTest(e,t);if(n!=null)return(r=this.hover).update.apply(r,n)},r.prototype.drawGrid=function(){var e,t,n,r,i,s;if(this.options.grid===!1&&this.options.axes===!1)return;i=this.grid,s=[];for(n=0,r=i.length;n
                          "),this.el.hide(),this.options.parent.append(this.el)}return n.defaults={"class":"morris-hover morris-default-style"},n.prototype.update=function(e,t,n){return this.html(e),this.show(),this.moveTo(t,n)},n.prototype.html=function(e){return this.el.html(e)},n.prototype.moveTo=function(e,t){var n,r,i,s,o,u;return o=this.options.parent.innerWidth(),s=this.options.parent.innerHeight(),r=this.el.outerWidth(),n=this.el.outerHeight(),i=Math.min(Math.max(0,e-r/2),o-r),t!=null?(u=t-n-10,u<0&&(u=t+10,u+n>s&&(u=s/2-n/2))):u=s/2-n/2,this.el.css({left:i+"px",top:parseInt(u)+"px"})},n.prototype.show=function(){return this.el.show()},n.prototype.hide=function(){return this.el.hide()},n}(),t.Line=function(e){function n(e){this.hilight=u(this.hilight,this),this.onHoverOut=u(this.onHoverOut,this),this.onHoverMove=u(this.onHoverMove,this),this.onGridClick=u(this.onGridClick,this);if(!(this instanceof t.Line))return new t.Line(e);n.__super__.constructor.call(this,e)}return o(n,e),n.prototype.init=function(){this.pointGrow=Raphael.animation({r:this.options.pointSize+3},25,"linear"),this.pointShrink=Raphael.animation({r:this.options.pointSize},25,"linear");if(this.options.hideHover!=="always")return this.hover=new t.Hover({parent:this.el}),this.on("hovermove",this.onHoverMove),this.on("hoverout",this.onHoverOut),this.on("gridclick",this.onGridClick)},n.prototype.defaults={lineWidth:3,pointSize:4,lineColors:["#0b62a4","#7A92A3","#4da74d","#afd8f8","#edc240","#cb4b4b","#9440ed"],pointWidths:[1],pointStrokeColors:["#ffffff"],pointFillColors:[],smooth:!0,xLabels:"auto",xLabelFormat:null,xLabelMargin:24,continuousLine:!0,hideHover:!1},n.prototype.calc=function(){return this.calcPoints(),this.generatePaths()},n.prototype.calcPoints=function(){var e,t,n,r,i,s;i=this.data,s=[];for(n=0,r=i.length;n"+r.label+"
                          ",u=r.y;for(n=s=0,o=u.length;s\n "+this.options.labels[n]+":\n "+this.yLabelFormat(i)+"\n
                          ";return typeof this.options.hoverCallback=="function"&&(t=this.options.hoverCallback(e,this.options,t)),[t,r._x,r._ymax]},n.prototype.generatePaths=function(){var e,n,r,i,s;return this.paths=function(){var o,u,f,l;l=[];for(r=o=0,u=this.options.ykeys.length;0<=u?ou;r=0<=u?++o:--o)s=this.options.smooth===!0||(f=this.options.ykeys[r],a.call(this.options.smooth,f)>=0),n=function(){var e,t,n,s;n=this.data,s=[];for(e=0,t=n.length;e1?l.push(t.Line.createPath(n,s,this.bottom)):l.push(null);return l}.call(this)},n.prototype.draw=function(){this.options.axes&&this.drawXAxis(),this.drawSeries();if(this.options.hideHover===!1)return this.displayHoverForRow(this.data.length-1)},n.prototype.drawXAxis=function(){var e,n,r,i,s,o,u,a,f,l,c=this;u=this.bottom+this.options.padding/2,s=null,i=null,e=function(e,t){var n,r,o,a,f;return n=c.drawXAxisLabel(c.transX(t),u,e),f=n.getBBox(),n.transform("r"+ -c.options.xLabelAngle),r=n.getBBox(),n.transform("t0,"+r.height/2+"..."),c.options.xLabelAngle!==0&&(a=-0.5*f.width*Math.cos(c.options.xLabelAngle*Math.PI/180),n.transform("t"+a+",0...")),r=n.getBBox(),(s==null||s>=r.x+r.width||i!=null&&i>=r.x)&&r.x>=0&&r.x+r.width=0;e=r<=0?++t:--t)this._drawLineFor(e);s=[];for(e=n=i=this.options.ykeys.length-1;i<=0?n<=0:n>=0;e=i<=0?++n:--n)s.push(this._drawPointFor(e));return s},n.prototype._drawPointFor=function(e){var t,n,r,i,s,o;this.seriesPoints[e]=[],s=this.data,o=[];for(r=0,i=s.length;r=i;t=0<=i?++n:--n)this.seriesPoints[t][this.prevHilight]&&this.seriesPoints[t][this.prevHilight].animate(this.pointShrink);if(e!==null&&this.prevHilight!==e)for(t=r=0,s=this.seriesPoints.length-1;0<=s?r<=s:r>=s;t=0<=s?++r:--r)this.seriesPoints[t][e]&&this.seriesPoints[t][e].animate(this.pointGrow);return this.prevHilight=e},n.prototype.colorFor=function(e,t,n){return typeof this.options.lineColors=="function"?this.options.lineColors.call(this,e,t,n):n==="point"?this.options.pointFillColors[t%this.options.pointFillColors.length]||this.options.lineColors[t%this.options.lineColors.length]:this.options.lineColors[t%this.options.lineColors.length]},n.prototype.drawXAxisLabel=function(e,t,n){return this.raphael.text(e,t,n).attr("font-size",this.options.gridTextSize).attr("font-family",this.options.gridTextFamily).attr("font-weight",this.options.gridTextWeight).attr("fill",this.options.gridTextColor)},n.prototype.drawLinePath=function(e,t){return this.raphael.path(e).attr("stroke",t).attr("stroke-width",this.options.lineWidth)},n.prototype.drawLinePoint=function(e,t,n,r,i){return this.raphael.circle(e,t,n).attr("fill",r).attr("stroke-width",this.strokeWidthForSeries(i)).attr("stroke",this.strokeForSeries(i))},n.prototype.strokeWidthForSeries=function(e){return this.options.pointWidths[e%this.options.pointWidths.length]},n.prototype.strokeForSeries=function(e){return this.options.pointStrokeColors[e%this.options.pointStrokeColors.length]},n}(t.Grid),t.labelSeries=function(n,r,i,s,o){var u,a,f,l,c,h,p,d,v,m,g;f=200*(r-n)/i,a=new Date(n),p=t.LABEL_SPECS[s];if(p===void 0){g=t.AUTO_LABEL_ORDER;for(v=0,m=g.length;v=h.span){p=h;break}}}p===void 0&&(p=t.LABEL_SPECS.second),o&&(p=e.extend({},p,{fmt:o})),u=p.start(a),c=[];while((d=u.getTime())<=r)d>=n&&c.push([p.fmt(u),d]),p.incr(u);return c},n=function(e){return{span:e*60*1e3,start:function(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours())},fmt:function(e){return""+t.pad2(e.getHours())+":"+t.pad2(e.getMinutes())},incr:function(t){return t.setUTCMinutes(t.getUTCMinutes()+e)}}},r=function(e){return{span:e*1e3,start:function(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes())},fmt:function(e){return""+t.pad2(e.getHours())+":"+t.pad2(e.getMinutes())+":"+t.pad2(e.getSeconds())},incr:function(t){return t.setUTCSeconds(t.getUTCSeconds()+e)}}},t.LABEL_SPECS={decade:{span:1728e8,start:function(e){return new Date(e.getFullYear()-e.getFullYear()%10,0,1)},fmt:function(e){return""+e.getFullYear()},incr:function(e){return e.setFullYear(e.getFullYear()+10)}},year:{span:1728e7,start:function(e){return new Date(e.getFullYear(),0,1)},fmt:function(e){return""+e.getFullYear()},incr:function(e){return e.setFullYear(e.getFullYear()+1)}},month:{span:24192e5,start:function(e){return new Date(e.getFullYear(),e.getMonth(),1)},fmt:function(e){return""+e.getFullYear()+"-"+t.pad2(e.getMonth()+1)},incr:function(e){return e.setMonth(e.getMonth()+1)}},day:{span:864e5,start:function(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate())},fmt:function(e){return""+e.getFullYear()+"-"+t.pad2(e.getMonth()+1)+"-"+t.pad2(e.getDate())},incr:function(e){return e.setDate(e.getDate()+1)}},hour:n(60),"30min":n(30),"15min":n(15),"10min":n(10),"5min":n(5),minute:n(1),"30sec":r(30),"15sec":r(15),"10sec":r(10),"5sec":r(5),second:r(1)},t.AUTO_LABEL_ORDER=["decade","year","month","day","hour","30min","15min","10min","5min","minute","30sec","15sec","10sec","5sec","second"],t.Area=function(n){function i(n){var s;if(!(this instanceof t.Area))return new t.Area(n);s=e.extend({},r,n),this.cumulative=!s.behaveLikeLine,s.fillOpacity==="auto"&&(s.fillOpacity=s.behaveLikeLine?.8:1),i.__super__.constructor.call(this,s)}var r;return o(i,n),r={fillOpacity:"auto",behaveLikeLine:!1},i.prototype.calcPoints=function(){var e,t,n,r,i,s,o;s=this.data,o=[];for(r=0,i=s.length;r=t;0<=t?e++:e--)a.push(e);return a}.apply(this):t=function(){f=[];for(var e=u=this.options.ykeys.length-1;u<=0?e<=0:e>=0;u<=0?e++:e--)f.push(e);return f}.apply(this),l=[];for(i=0,s=t.length;ic;e=0<=c?++l:--l)u=this.data[this.data.length-1-e],t=this.drawXAxisLabel(u._x,f,u.label),a=t.getBBox(),t.transform("r"+ -this.options.xLabelAngle),n=t.getBBox(),t.transform("t0,"+n.height/2+"..."),this.options.xLabelAngle!==0&&(i=-0.5*a.width*Math.cos(this.options.xLabelAngle*Math.PI/180),t.transform("t"+i+",0...")),(o==null||o>=n.x+n.width||s!=null&&s>=n.x)&&n.x>=0&&n.x+n.width=0?this.transY(0):null,this.bars=function(){var u,d,v,m;v=this.data,m=[];for(r=u=0,d=v.length;u"+r.label+"
                          ",a=r.y;for(n=o=0,u=a.length;o\n "+this.options.labels[n]+":\n "+this.yLabelFormat(s)+"\n
                          ";return typeof this.options.hoverCallback=="function"&&(t=this.options.hoverCallback(e,this.options,t)),i=this.left+(e+.5)*this.width/this.data.length,[t,i]},r.prototype.drawXAxisLabel=function(e,t,n){var r;return r=this.raphael.text(e,t,n).attr("font-size",this.options.gridTextSize).attr("font-family",this.options.gridTextFamily).attr("font-weight",this.options.gridTextWeight).attr("fill",this.options.gridTextColor)},r.prototype.drawBar=function(e,t,n,r,i){return this.raphael.rect(e,t,n,r).attr("fill",i).attr("stroke-width",0)},r}(t.Grid),t.Donut=function(n){function r(n){this.select=u(this.select,this),this.click=u(this.click,this);var r;if(!(this instanceof t.Donut))return new t.Donut(n);typeof n.element=="string"?this.el=e(document.getElementById(n.element)):this.el=e(n.element),this.options=e.extend({},this.defaults,n);if(this.el===null||this.el.length===0)throw new Error("Graph placeholder not found.");if(n.data===void 0||n.data.length===0)return;this.data=n.data,this.values=function(){var e,t,n,i;n=this.data,i=[];for(e=0,t=n.length;eMath.PI?1:0,this.path=this.calcSegment(this.inner+3,this.inner+this.outer-5),this.selectedPath=this.calcSegment(this.inner+3,this.inner+this.outer),this.hilight=this.calcArc(this.inner)}return o(t,e),t.prototype.calcArcPoints=function(e){return[this.cx+e*this.sin_p0,this.cy+e*this.cos_p0,this.cx+e*this.sin_p1,this.cy+e*this.cos_p1]},t.prototype.calcSegment=function(e,t){var n,r,i,s,o,u,a,f,l,c;return l=this.calcArcPoints(e),n=l[0],i=l[1],r=l[2],s=l[3],c=this.calcArcPoints(t),o=c[0],a=c[1],u=c[2],f=c[3],"M"+n+","+i+("A"+e+","+e+",0,"+this.is_long+",0,"+r+","+s)+("L"+u+","+f)+("A"+t+","+t+",0,"+this.is_long+",1,"+o+","+a)+"Z"},t.prototype.calcArc=function(e){var t,n,r,i,s;return s=this.calcArcPoints(e),t=s[0],r=s[1],n=s[2],i=s[3],"M"+t+","+r+("A"+e+","+e+",0,"+this.is_long+",0,"+n+","+i)},t.prototype.render=function(){var e=this;return this.arc=this.drawDonutArc(this.hilight,this.color),this.seg=this.drawDonutSegment(this.path,this.color,this.backgroundColor,function(){return e.fire("hover",e.index)},function(){return e.fire("click",e.index)})},t.prototype.drawDonutArc=function(e,t){return this.raphael.path(e).attr({stroke:t,"stroke-width":2,opacity:0})},t.prototype.drawDonutSegment=function(e,t,n,r,i){return this.raphael.path(e).attr({fill:t,stroke:n,"stroke-width":3}).hover(r).click(i)},t.prototype.select=function(){if(!this.selected)return this.seg.animate({path:this.selectedPath},150,"<>"),this.arc.animate({opacity:1},150,"<>"),this.selected=!0},t.prototype.deselect=function(){if(this.selected)return this.seg.animate({path:this.path},150,"<>"),this.arc.animate({opacity:0},150,"<>"),this.selected=!1},t}(t.EventEmitter)}).call(this); From 36f57a520486022f2130b323e62e96845b1a4fe9 Mon Sep 17 00:00:00 2001 From: Ken Merthe Date: Sun, 13 Oct 2013 09:33:29 -0700 Subject: [PATCH 12/26] Added pegjs 0.7.0 --- ajax/libs/pegjs/0.7.0/peg.js | 4528 ++++++++++++++++++++++++++++++ ajax/libs/pegjs/0.7.0/peg.min.js | 9 + ajax/libs/pegjs/package.json | 25 + 3 files changed, 4562 insertions(+) create mode 100644 ajax/libs/pegjs/0.7.0/peg.js create mode 100644 ajax/libs/pegjs/0.7.0/peg.min.js create mode 100644 ajax/libs/pegjs/package.json diff --git a/ajax/libs/pegjs/0.7.0/peg.js b/ajax/libs/pegjs/0.7.0/peg.js new file mode 100644 index 000000000..c8ac03e07 --- /dev/null +++ b/ajax/libs/pegjs/0.7.0/peg.js @@ -0,0 +1,4528 @@ +/* + * PEG.js 0.7.0 + * + * http://pegjs.majda.cz/ + * + * Copyright (c) 2010-2012 David Majda + * Licensend under the MIT license. + */ +var PEG = (function(undefined) { + +var PEG = { + /* PEG.js version (uses semantic versioning). */ + VERSION: "0.7.0", + + /* + * Generates a parser from a specified grammar and returns it. + * + * The grammar must be a string in the format described by the metagramar in + * the parser.pegjs file. + * + * Throws |PEG.parser.SyntaxError| if the grammar contains a syntax error or + * |PEG.GrammarError| if it contains a semantic error. Note that not all + * errors are detected during the generation and some may protrude to the + * generated parser and cause its malfunction. + */ + buildParser: function(grammar, options) { + return PEG.compiler.compile(PEG.parser.parse(grammar), options); + } +}; + +/* Thrown when the grammar contains an error. */ + +PEG.GrammarError = function(message) { + this.name = "PEG.GrammarError"; + this.message = message; +}; + +PEG.GrammarError.prototype = Error.prototype; + +/* Like Python's |range|, but without |step|. */ +function range(start, stop) { + if (stop === undefined) { + stop = start; + start = 0; + } + + var result = new Array(Math.max(0, stop - start)); + for (var i = 0, j = start; j < stop; i++, j++) { + result[i] = j; + } + return result; +} + +function find(array, callback) { + var length = array.length; + for (var i = 0; i < length; i++) { + if (callback(array[i])) { + return array[i]; + } + } +} + +function contains(array, value) { + /* + * Stupid IE does not have Array.prototype.indexOf, otherwise this function + * would be a one-liner. + */ + var length = array.length; + for (var i = 0; i < length; i++) { + if (array[i] === value) { + return true; + } + } + return false; +} + +function each(array, callback) { + var length = array.length; + for (var i = 0; i < length; i++) { + callback(array[i], i); + } +} + +function map(array, callback) { + var result = []; + var length = array.length; + for (var i = 0; i < length; i++) { + result[i] = callback(array[i], i); + } + return result; +} + +function pluck(array, key) { + return map(array, function (e) { return e[key]; }); +} + +function keys(object) { + var result = []; + for (var key in object) { + result.push(key); + } + return result; +} + +function values(object) { + var result = []; + for (var key in object) { + result.push(object[key]); + } + return result; +} + +/* + * Returns a string padded on the left to a desired length with a character. + * + * The code needs to be in sync with the code template in the compilation + * function for "action" nodes. + */ +function padLeft(input, padding, length) { + var result = input; + + var padLength = length - input.length; + for (var i = 0; i < padLength; i++) { + result = padding + result; + } + + return result; +} + +/* + * Returns an escape sequence for given character. Uses \x for characters <= + * 0xFF to save space, \u for the rest. + * + * The code needs to be in sync with the code template in the compilation + * function for "action" nodes. + */ +function escape(ch) { + var charCode = ch.charCodeAt(0); + var escapeChar; + var length; + + if (charCode <= 0xFF) { + escapeChar = 'x'; + length = 2; + } else { + escapeChar = 'u'; + length = 4; + } + + return '\\' + escapeChar + padLeft(charCode.toString(16).toUpperCase(), '0', length); +} + +/* + * Surrounds the string with quotes and escapes characters inside so that the + * result is a valid JavaScript string. + * + * The code needs to be in sync with the code template in the compilation + * function for "action" nodes. + */ +function quote(s) { + /* + * ECMA-262, 5th ed., 7.8.4: All characters may appear literally in a string + * literal except for the closing quote character, backslash, carriage return, + * line separator, paragraph separator, and line feed. Any character may + * appear in the form of an escape sequence. + * + * For portability, we also escape escape all control and non-ASCII + * characters. Note that "\0" and "\v" escape sequences are not used because + * JSHint does not like the first and IE the second. + */ + return '"' + s + .replace(/\\/g, '\\\\') // backslash + .replace(/"/g, '\\"') // closing quote character + .replace(/\x08/g, '\\b') // backspace + .replace(/\t/g, '\\t') // horizontal tab + .replace(/\n/g, '\\n') // line feed + .replace(/\f/g, '\\f') // form feed + .replace(/\r/g, '\\r') // carriage return + .replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g, escape) + + '"'; +} + +/* + * Escapes characters inside the string so that it can be used as a list of + * characters in a character class of a regular expression. + */ +function quoteForRegexpClass(s) { + /* + * Based on ECMA-262, 5th ed., 7.8.5 & 15.10.1. + * + * For portability, we also escape escape all control and non-ASCII + * characters. + */ + return s + .replace(/\\/g, '\\\\') // backslash + .replace(/\//g, '\\/') // closing slash + .replace(/\]/g, '\\]') // closing bracket + .replace(/-/g, '\\-') // dash + .replace(/\0/g, '\\0') // null + .replace(/\t/g, '\\t') // horizontal tab + .replace(/\n/g, '\\n') // line feed + .replace(/\v/g, '\\x0B') // vertical tab + .replace(/\f/g, '\\f') // form feed + .replace(/\r/g, '\\r') // carriage return + .replace(/[\x01-\x08\x0E-\x1F\x80-\uFFFF]/g, escape); +} + +/* + * Builds a node visitor -- a function which takes a node and any number of + * other parameters, calls an appropriate function according to the node type, + * passes it all its parameters and returns its value. The functions for various + * node types are passed in a parameter to |buildNodeVisitor| as a hash. + */ +function buildNodeVisitor(functions) { + return function(node) { + return functions[node.type].apply(null, arguments); + }; +} + +function findRuleByName(ast, name) { + return find(ast.rules, function(r) { return r.name === name; }); +} +PEG.parser = (function(){ + /* + * Generated by PEG.js 0.7.0. + * + * http://pegjs.majda.cz/ + */ + + function quote(s) { + /* + * ECMA-262, 5th ed., 7.8.4: All characters may appear literally in a + * string literal except for the closing quote character, backslash, + * carriage return, line separator, paragraph separator, and line feed. + * Any character may appear in the form of an escape sequence. + * + * For portability, we also escape escape all control and non-ASCII + * characters. Note that "\0" and "\v" escape sequences are not used + * because JSHint does not like the first and IE the second. + */ + return '"' + s + .replace(/\\/g, '\\\\') // backslash + .replace(/"/g, '\\"') // closing quote character + .replace(/\x08/g, '\\b') // backspace + .replace(/\t/g, '\\t') // horizontal tab + .replace(/\n/g, '\\n') // line feed + .replace(/\f/g, '\\f') // form feed + .replace(/\r/g, '\\r') // carriage return + .replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g, escape) + + '"'; + } + + var result = { + /* + * Parses the input with a generated parser. If the parsing is successfull, + * returns a value explicitly or implicitly specified by the grammar from + * which the parser was generated (see |PEG.buildParser|). If the parsing is + * unsuccessful, throws |PEG.parser.SyntaxError| describing the error. + */ + parse: function(input, startRule) { + var parseFunctions = { + "grammar": parse_grammar, + "initializer": parse_initializer, + "rule": parse_rule, + "choice": parse_choice, + "sequence": parse_sequence, + "labeled": parse_labeled, + "prefixed": parse_prefixed, + "suffixed": parse_suffixed, + "primary": parse_primary, + "action": parse_action, + "braced": parse_braced, + "nonBraceCharacters": parse_nonBraceCharacters, + "nonBraceCharacter": parse_nonBraceCharacter, + "equals": parse_equals, + "colon": parse_colon, + "semicolon": parse_semicolon, + "slash": parse_slash, + "and": parse_and, + "not": parse_not, + "question": parse_question, + "star": parse_star, + "plus": parse_plus, + "lparen": parse_lparen, + "rparen": parse_rparen, + "dot": parse_dot, + "identifier": parse_identifier, + "literal": parse_literal, + "string": parse_string, + "doubleQuotedString": parse_doubleQuotedString, + "doubleQuotedCharacter": parse_doubleQuotedCharacter, + "simpleDoubleQuotedCharacter": parse_simpleDoubleQuotedCharacter, + "singleQuotedString": parse_singleQuotedString, + "singleQuotedCharacter": parse_singleQuotedCharacter, + "simpleSingleQuotedCharacter": parse_simpleSingleQuotedCharacter, + "class": parse_class, + "classCharacterRange": parse_classCharacterRange, + "classCharacter": parse_classCharacter, + "bracketDelimitedCharacter": parse_bracketDelimitedCharacter, + "simpleBracketDelimitedCharacter": parse_simpleBracketDelimitedCharacter, + "simpleEscapeSequence": parse_simpleEscapeSequence, + "zeroEscapeSequence": parse_zeroEscapeSequence, + "hexEscapeSequence": parse_hexEscapeSequence, + "unicodeEscapeSequence": parse_unicodeEscapeSequence, + "eolEscapeSequence": parse_eolEscapeSequence, + "digit": parse_digit, + "hexDigit": parse_hexDigit, + "letter": parse_letter, + "lowerCaseLetter": parse_lowerCaseLetter, + "upperCaseLetter": parse_upperCaseLetter, + "__": parse___, + "comment": parse_comment, + "singleLineComment": parse_singleLineComment, + "multiLineComment": parse_multiLineComment, + "eol": parse_eol, + "eolChar": parse_eolChar, + "whitespace": parse_whitespace + }; + + if (startRule !== undefined) { + if (parseFunctions[startRule] === undefined) { + throw new Error("Invalid rule name: " + quote(startRule) + "."); + } + } else { + startRule = "grammar"; + } + + var pos = 0; + var reportFailures = 0; + var rightmostFailuresPos = 0; + var rightmostFailuresExpected = []; + + function padLeft(input, padding, length) { + var result = input; + + var padLength = length - input.length; + for (var i = 0; i < padLength; i++) { + result = padding + result; + } + + return result; + } + + function escape(ch) { + var charCode = ch.charCodeAt(0); + var escapeChar; + var length; + + if (charCode <= 0xFF) { + escapeChar = 'x'; + length = 2; + } else { + escapeChar = 'u'; + length = 4; + } + + return '\\' + escapeChar + padLeft(charCode.toString(16).toUpperCase(), '0', length); + } + + function matchFailed(failure) { + if (pos < rightmostFailuresPos) { + return; + } + + if (pos > rightmostFailuresPos) { + rightmostFailuresPos = pos; + rightmostFailuresExpected = []; + } + + rightmostFailuresExpected.push(failure); + } + + function parse_grammar() { + var result0, result1, result2, result3; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + result0 = parse___(); + if (result0 !== null) { + result1 = parse_initializer(); + result1 = result1 !== null ? result1 : ""; + if (result1 !== null) { + result3 = parse_rule(); + if (result3 !== null) { + result2 = []; + while (result3 !== null) { + result2.push(result3); + result3 = parse_rule(); + } + } else { + result2 = null; + } + if (result2 !== null) { + result0 = [result0, result1, result2]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, initializer, rules) { + return { + type: "grammar", + initializer: initializer !== "" ? initializer : null, + rules: rules, + startRule: rules[0].name + }; + })(pos0, result0[1], result0[2]); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_initializer() { + var result0, result1; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + result0 = parse_action(); + if (result0 !== null) { + result1 = parse_semicolon(); + result1 = result1 !== null ? result1 : ""; + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, code) { + return { + type: "initializer", + code: code + }; + })(pos0, result0[0]); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_rule() { + var result0, result1, result2, result3, result4; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + result0 = parse_identifier(); + if (result0 !== null) { + result1 = parse_string(); + result1 = result1 !== null ? result1 : ""; + if (result1 !== null) { + result2 = parse_equals(); + if (result2 !== null) { + result3 = parse_choice(); + if (result3 !== null) { + result4 = parse_semicolon(); + result4 = result4 !== null ? result4 : ""; + if (result4 !== null) { + result0 = [result0, result1, result2, result3, result4]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, name, displayName, expression) { + return { + type: "rule", + name: name, + displayName: displayName !== "" ? displayName : null, + expression: expression + }; + })(pos0, result0[0], result0[1], result0[3]); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_choice() { + var result0, result1, result2, result3; + var pos0, pos1, pos2; + + pos0 = pos; + pos1 = pos; + result0 = parse_sequence(); + if (result0 !== null) { + result1 = []; + pos2 = pos; + result2 = parse_slash(); + if (result2 !== null) { + result3 = parse_sequence(); + if (result3 !== null) { + result2 = [result2, result3]; + } else { + result2 = null; + pos = pos2; + } + } else { + result2 = null; + pos = pos2; + } + while (result2 !== null) { + result1.push(result2); + pos2 = pos; + result2 = parse_slash(); + if (result2 !== null) { + result3 = parse_sequence(); + if (result3 !== null) { + result2 = [result2, result3]; + } else { + result2 = null; + pos = pos2; + } + } else { + result2 = null; + pos = pos2; + } + } + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, head, tail) { + if (tail.length > 0) { + var alternatives = [head].concat(map( + tail, + function(element) { return element[1]; } + )); + return { + type: "choice", + alternatives: alternatives + }; + } else { + return head; + } + })(pos0, result0[0], result0[1]); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_sequence() { + var result0, result1; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + result0 = []; + result1 = parse_labeled(); + while (result1 !== null) { + result0.push(result1); + result1 = parse_labeled(); + } + if (result0 !== null) { + result1 = parse_action(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, elements, code) { + var expression = elements.length !== 1 + ? { + type: "sequence", + elements: elements + } + : elements[0]; + return { + type: "action", + expression: expression, + code: code + }; + })(pos0, result0[0], result0[1]); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + pos0 = pos; + result0 = []; + result1 = parse_labeled(); + while (result1 !== null) { + result0.push(result1); + result1 = parse_labeled(); + } + if (result0 !== null) { + result0 = (function(offset, elements) { + return elements.length !== 1 + ? { + type: "sequence", + elements: elements + } + : elements[0]; + })(pos0, result0); + } + if (result0 === null) { + pos = pos0; + } + } + return result0; + } + + function parse_labeled() { + var result0, result1, result2; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + result0 = parse_identifier(); + if (result0 !== null) { + result1 = parse_colon(); + if (result1 !== null) { + result2 = parse_prefixed(); + if (result2 !== null) { + result0 = [result0, result1, result2]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, label, expression) { + return { + type: "labeled", + label: label, + expression: expression + }; + })(pos0, result0[0], result0[2]); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + result0 = parse_prefixed(); + } + return result0; + } + + function parse_prefixed() { + var result0, result1; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + result0 = parse_and(); + if (result0 !== null) { + result1 = parse_action(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, code) { + return { + type: "semantic_and", + code: code + }; + })(pos0, result0[1]); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + pos0 = pos; + pos1 = pos; + result0 = parse_and(); + if (result0 !== null) { + result1 = parse_suffixed(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, expression) { + return { + type: "simple_and", + expression: expression + }; + })(pos0, result0[1]); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + pos0 = pos; + pos1 = pos; + result0 = parse_not(); + if (result0 !== null) { + result1 = parse_action(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, code) { + return { + type: "semantic_not", + code: code + }; + })(pos0, result0[1]); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + pos0 = pos; + pos1 = pos; + result0 = parse_not(); + if (result0 !== null) { + result1 = parse_suffixed(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, expression) { + return { + type: "simple_not", + expression: expression + }; + })(pos0, result0[1]); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + result0 = parse_suffixed(); + } + } + } + } + return result0; + } + + function parse_suffixed() { + var result0, result1; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + result0 = parse_primary(); + if (result0 !== null) { + result1 = parse_question(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, expression) { + return { + type: "optional", + expression: expression + }; + })(pos0, result0[0]); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + pos0 = pos; + pos1 = pos; + result0 = parse_primary(); + if (result0 !== null) { + result1 = parse_star(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, expression) { + return { + type: "zero_or_more", + expression: expression + }; + })(pos0, result0[0]); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + pos0 = pos; + pos1 = pos; + result0 = parse_primary(); + if (result0 !== null) { + result1 = parse_plus(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, expression) { + return { + type: "one_or_more", + expression: expression + }; + })(pos0, result0[0]); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + result0 = parse_primary(); + } + } + } + return result0; + } + + function parse_primary() { + var result0, result1, result2; + var pos0, pos1, pos2, pos3; + + pos0 = pos; + pos1 = pos; + result0 = parse_identifier(); + if (result0 !== null) { + pos2 = pos; + reportFailures++; + pos3 = pos; + result1 = parse_string(); + result1 = result1 !== null ? result1 : ""; + if (result1 !== null) { + result2 = parse_equals(); + if (result2 !== null) { + result1 = [result1, result2]; + } else { + result1 = null; + pos = pos3; + } + } else { + result1 = null; + pos = pos3; + } + reportFailures--; + if (result1 === null) { + result1 = ""; + } else { + result1 = null; + pos = pos2; + } + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, name) { + return { + type: "rule_ref", + name: name + }; + })(pos0, result0[0]); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + result0 = parse_literal(); + if (result0 === null) { + pos0 = pos; + result0 = parse_dot(); + if (result0 !== null) { + result0 = (function(offset) { return { type: "any" }; })(pos0); + } + if (result0 === null) { + pos = pos0; + } + if (result0 === null) { + result0 = parse_class(); + if (result0 === null) { + pos0 = pos; + pos1 = pos; + result0 = parse_lparen(); + if (result0 !== null) { + result1 = parse_choice(); + if (result1 !== null) { + result2 = parse_rparen(); + if (result2 !== null) { + result0 = [result0, result1, result2]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, expression) { return expression; })(pos0, result0[1]); + } + if (result0 === null) { + pos = pos0; + } + } + } + } + } + return result0; + } + + function parse_action() { + var result0, result1; + var pos0, pos1; + + reportFailures++; + pos0 = pos; + pos1 = pos; + result0 = parse_braced(); + if (result0 !== null) { + result1 = parse___(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, braced) { return braced.substr(1, braced.length - 2); })(pos0, result0[0]); + } + if (result0 === null) { + pos = pos0; + } + reportFailures--; + if (reportFailures === 0 && result0 === null) { + matchFailed("action"); + } + return result0; + } + + function parse_braced() { + var result0, result1, result2; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 123) { + result0 = "{"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"{\""); + } + } + if (result0 !== null) { + result1 = []; + result2 = parse_braced(); + if (result2 === null) { + result2 = parse_nonBraceCharacter(); + } + while (result2 !== null) { + result1.push(result2); + result2 = parse_braced(); + if (result2 === null) { + result2 = parse_nonBraceCharacter(); + } + } + if (result1 !== null) { + if (input.charCodeAt(pos) === 125) { + result2 = "}"; + pos++; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("\"}\""); + } + } + if (result2 !== null) { + result0 = [result0, result1, result2]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, parts) { + return "{" + parts.join("") + "}"; + })(pos0, result0[1]); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_nonBraceCharacters() { + var result0, result1; + var pos0; + + pos0 = pos; + result1 = parse_nonBraceCharacter(); + if (result1 !== null) { + result0 = []; + while (result1 !== null) { + result0.push(result1); + result1 = parse_nonBraceCharacter(); + } + } else { + result0 = null; + } + if (result0 !== null) { + result0 = (function(offset, chars) { return chars.join(""); })(pos0, result0); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_nonBraceCharacter() { + var result0; + + if (/^[^{}]/.test(input.charAt(pos))) { + result0 = input.charAt(pos); + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("[^{}]"); + } + } + return result0; + } + + function parse_equals() { + var result0, result1; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 61) { + result0 = "="; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"=\""); + } + } + if (result0 !== null) { + result1 = parse___(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset) { return "="; })(pos0); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_colon() { + var result0, result1; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 58) { + result0 = ":"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\":\""); + } + } + if (result0 !== null) { + result1 = parse___(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset) { return ":"; })(pos0); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_semicolon() { + var result0, result1; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 59) { + result0 = ";"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\";\""); + } + } + if (result0 !== null) { + result1 = parse___(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset) { return ";"; })(pos0); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_slash() { + var result0, result1; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 47) { + result0 = "/"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"/\""); + } + } + if (result0 !== null) { + result1 = parse___(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset) { return "/"; })(pos0); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_and() { + var result0, result1; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 38) { + result0 = "&"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"&\""); + } + } + if (result0 !== null) { + result1 = parse___(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset) { return "&"; })(pos0); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_not() { + var result0, result1; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 33) { + result0 = "!"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"!\""); + } + } + if (result0 !== null) { + result1 = parse___(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset) { return "!"; })(pos0); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_question() { + var result0, result1; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 63) { + result0 = "?"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"?\""); + } + } + if (result0 !== null) { + result1 = parse___(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset) { return "?"; })(pos0); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_star() { + var result0, result1; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 42) { + result0 = "*"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"*\""); + } + } + if (result0 !== null) { + result1 = parse___(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset) { return "*"; })(pos0); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_plus() { + var result0, result1; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 43) { + result0 = "+"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"+\""); + } + } + if (result0 !== null) { + result1 = parse___(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset) { return "+"; })(pos0); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_lparen() { + var result0, result1; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 40) { + result0 = "("; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"(\""); + } + } + if (result0 !== null) { + result1 = parse___(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset) { return "("; })(pos0); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_rparen() { + var result0, result1; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 41) { + result0 = ")"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\")\""); + } + } + if (result0 !== null) { + result1 = parse___(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset) { return ")"; })(pos0); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_dot() { + var result0, result1; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 46) { + result0 = "."; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\".\""); + } + } + if (result0 !== null) { + result1 = parse___(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset) { return "."; })(pos0); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_identifier() { + var result0, result1, result2; + var pos0, pos1; + + reportFailures++; + pos0 = pos; + pos1 = pos; + result0 = parse_letter(); + if (result0 === null) { + if (input.charCodeAt(pos) === 95) { + result0 = "_"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"_\""); + } + } + if (result0 === null) { + if (input.charCodeAt(pos) === 36) { + result0 = "$"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"$\""); + } + } + } + } + if (result0 !== null) { + result1 = []; + result2 = parse_letter(); + if (result2 === null) { + result2 = parse_digit(); + if (result2 === null) { + if (input.charCodeAt(pos) === 95) { + result2 = "_"; + pos++; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("\"_\""); + } + } + if (result2 === null) { + if (input.charCodeAt(pos) === 36) { + result2 = "$"; + pos++; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("\"$\""); + } + } + } + } + } + while (result2 !== null) { + result1.push(result2); + result2 = parse_letter(); + if (result2 === null) { + result2 = parse_digit(); + if (result2 === null) { + if (input.charCodeAt(pos) === 95) { + result2 = "_"; + pos++; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("\"_\""); + } + } + if (result2 === null) { + if (input.charCodeAt(pos) === 36) { + result2 = "$"; + pos++; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("\"$\""); + } + } + } + } + } + } + if (result1 !== null) { + result2 = parse___(); + if (result2 !== null) { + result0 = [result0, result1, result2]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, head, tail) { + return head + tail.join(""); + })(pos0, result0[0], result0[1]); + } + if (result0 === null) { + pos = pos0; + } + reportFailures--; + if (reportFailures === 0 && result0 === null) { + matchFailed("identifier"); + } + return result0; + } + + function parse_literal() { + var result0, result1, result2; + var pos0, pos1; + + reportFailures++; + pos0 = pos; + pos1 = pos; + result0 = parse_doubleQuotedString(); + if (result0 === null) { + result0 = parse_singleQuotedString(); + } + if (result0 !== null) { + if (input.charCodeAt(pos) === 105) { + result1 = "i"; + pos++; + } else { + result1 = null; + if (reportFailures === 0) { + matchFailed("\"i\""); + } + } + result1 = result1 !== null ? result1 : ""; + if (result1 !== null) { + result2 = parse___(); + if (result2 !== null) { + result0 = [result0, result1, result2]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, value, flags) { + return { + type: "literal", + value: value, + ignoreCase: flags === "i" + }; + })(pos0, result0[0], result0[1]); + } + if (result0 === null) { + pos = pos0; + } + reportFailures--; + if (reportFailures === 0 && result0 === null) { + matchFailed("literal"); + } + return result0; + } + + function parse_string() { + var result0, result1; + var pos0, pos1; + + reportFailures++; + pos0 = pos; + pos1 = pos; + result0 = parse_doubleQuotedString(); + if (result0 === null) { + result0 = parse_singleQuotedString(); + } + if (result0 !== null) { + result1 = parse___(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, string) { return string; })(pos0, result0[0]); + } + if (result0 === null) { + pos = pos0; + } + reportFailures--; + if (reportFailures === 0 && result0 === null) { + matchFailed("string"); + } + return result0; + } + + function parse_doubleQuotedString() { + var result0, result1, result2; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 34) { + result0 = "\""; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"\\\"\""); + } + } + if (result0 !== null) { + result1 = []; + result2 = parse_doubleQuotedCharacter(); + while (result2 !== null) { + result1.push(result2); + result2 = parse_doubleQuotedCharacter(); + } + if (result1 !== null) { + if (input.charCodeAt(pos) === 34) { + result2 = "\""; + pos++; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("\"\\\"\""); + } + } + if (result2 !== null) { + result0 = [result0, result1, result2]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, chars) { return chars.join(""); })(pos0, result0[1]); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_doubleQuotedCharacter() { + var result0; + + result0 = parse_simpleDoubleQuotedCharacter(); + if (result0 === null) { + result0 = parse_simpleEscapeSequence(); + if (result0 === null) { + result0 = parse_zeroEscapeSequence(); + if (result0 === null) { + result0 = parse_hexEscapeSequence(); + if (result0 === null) { + result0 = parse_unicodeEscapeSequence(); + if (result0 === null) { + result0 = parse_eolEscapeSequence(); + } + } + } + } + } + return result0; + } + + function parse_simpleDoubleQuotedCharacter() { + var result0, result1; + var pos0, pos1, pos2; + + pos0 = pos; + pos1 = pos; + pos2 = pos; + reportFailures++; + if (input.charCodeAt(pos) === 34) { + result0 = "\""; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"\\\"\""); + } + } + if (result0 === null) { + if (input.charCodeAt(pos) === 92) { + result0 = "\\"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"\\\\\""); + } + } + if (result0 === null) { + result0 = parse_eolChar(); + } + } + reportFailures--; + if (result0 === null) { + result0 = ""; + } else { + result0 = null; + pos = pos2; + } + if (result0 !== null) { + if (input.length > pos) { + result1 = input.charAt(pos); + pos++; + } else { + result1 = null; + if (reportFailures === 0) { + matchFailed("any character"); + } + } + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, char_) { return char_; })(pos0, result0[1]); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_singleQuotedString() { + var result0, result1, result2; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 39) { + result0 = "'"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"'\""); + } + } + if (result0 !== null) { + result1 = []; + result2 = parse_singleQuotedCharacter(); + while (result2 !== null) { + result1.push(result2); + result2 = parse_singleQuotedCharacter(); + } + if (result1 !== null) { + if (input.charCodeAt(pos) === 39) { + result2 = "'"; + pos++; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("\"'\""); + } + } + if (result2 !== null) { + result0 = [result0, result1, result2]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, chars) { return chars.join(""); })(pos0, result0[1]); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_singleQuotedCharacter() { + var result0; + + result0 = parse_simpleSingleQuotedCharacter(); + if (result0 === null) { + result0 = parse_simpleEscapeSequence(); + if (result0 === null) { + result0 = parse_zeroEscapeSequence(); + if (result0 === null) { + result0 = parse_hexEscapeSequence(); + if (result0 === null) { + result0 = parse_unicodeEscapeSequence(); + if (result0 === null) { + result0 = parse_eolEscapeSequence(); + } + } + } + } + } + return result0; + } + + function parse_simpleSingleQuotedCharacter() { + var result0, result1; + var pos0, pos1, pos2; + + pos0 = pos; + pos1 = pos; + pos2 = pos; + reportFailures++; + if (input.charCodeAt(pos) === 39) { + result0 = "'"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"'\""); + } + } + if (result0 === null) { + if (input.charCodeAt(pos) === 92) { + result0 = "\\"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"\\\\\""); + } + } + if (result0 === null) { + result0 = parse_eolChar(); + } + } + reportFailures--; + if (result0 === null) { + result0 = ""; + } else { + result0 = null; + pos = pos2; + } + if (result0 !== null) { + if (input.length > pos) { + result1 = input.charAt(pos); + pos++; + } else { + result1 = null; + if (reportFailures === 0) { + matchFailed("any character"); + } + } + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, char_) { return char_; })(pos0, result0[1]); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_class() { + var result0, result1, result2, result3, result4, result5; + var pos0, pos1; + + reportFailures++; + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 91) { + result0 = "["; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"[\""); + } + } + if (result0 !== null) { + if (input.charCodeAt(pos) === 94) { + result1 = "^"; + pos++; + } else { + result1 = null; + if (reportFailures === 0) { + matchFailed("\"^\""); + } + } + result1 = result1 !== null ? result1 : ""; + if (result1 !== null) { + result2 = []; + result3 = parse_classCharacterRange(); + if (result3 === null) { + result3 = parse_classCharacter(); + } + while (result3 !== null) { + result2.push(result3); + result3 = parse_classCharacterRange(); + if (result3 === null) { + result3 = parse_classCharacter(); + } + } + if (result2 !== null) { + if (input.charCodeAt(pos) === 93) { + result3 = "]"; + pos++; + } else { + result3 = null; + if (reportFailures === 0) { + matchFailed("\"]\""); + } + } + if (result3 !== null) { + if (input.charCodeAt(pos) === 105) { + result4 = "i"; + pos++; + } else { + result4 = null; + if (reportFailures === 0) { + matchFailed("\"i\""); + } + } + result4 = result4 !== null ? result4 : ""; + if (result4 !== null) { + result5 = parse___(); + if (result5 !== null) { + result0 = [result0, result1, result2, result3, result4, result5]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, inverted, parts, flags) { + var partsConverted = map(parts, function(part) { return part.data; }); + var rawText = "[" + + inverted + + map(parts, function(part) { return part.rawText; }).join("") + + "]" + + flags; + + return { + type: "class", + inverted: inverted === "^", + ignoreCase: flags === "i", + parts: partsConverted, + // FIXME: Get the raw text from the input directly. + rawText: rawText + }; + })(pos0, result0[1], result0[2], result0[4]); + } + if (result0 === null) { + pos = pos0; + } + reportFailures--; + if (reportFailures === 0 && result0 === null) { + matchFailed("character class"); + } + return result0; + } + + function parse_classCharacterRange() { + var result0, result1, result2; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + result0 = parse_classCharacter(); + if (result0 !== null) { + if (input.charCodeAt(pos) === 45) { + result1 = "-"; + pos++; + } else { + result1 = null; + if (reportFailures === 0) { + matchFailed("\"-\""); + } + } + if (result1 !== null) { + result2 = parse_classCharacter(); + if (result2 !== null) { + result0 = [result0, result1, result2]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, begin, end) { + if (begin.data.charCodeAt(0) > end.data.charCodeAt(0)) { + throw new this.SyntaxError( + "Invalid character range: " + begin.rawText + "-" + end.rawText + "." + ); + } + + return { + data: [begin.data, end.data], + // FIXME: Get the raw text from the input directly. + rawText: begin.rawText + "-" + end.rawText + }; + })(pos0, result0[0], result0[2]); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_classCharacter() { + var result0; + var pos0; + + pos0 = pos; + result0 = parse_bracketDelimitedCharacter(); + if (result0 !== null) { + result0 = (function(offset, char_) { + return { + data: char_, + // FIXME: Get the raw text from the input directly. + rawText: quoteForRegexpClass(char_) + }; + })(pos0, result0); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_bracketDelimitedCharacter() { + var result0; + + result0 = parse_simpleBracketDelimitedCharacter(); + if (result0 === null) { + result0 = parse_simpleEscapeSequence(); + if (result0 === null) { + result0 = parse_zeroEscapeSequence(); + if (result0 === null) { + result0 = parse_hexEscapeSequence(); + if (result0 === null) { + result0 = parse_unicodeEscapeSequence(); + if (result0 === null) { + result0 = parse_eolEscapeSequence(); + } + } + } + } + } + return result0; + } + + function parse_simpleBracketDelimitedCharacter() { + var result0, result1; + var pos0, pos1, pos2; + + pos0 = pos; + pos1 = pos; + pos2 = pos; + reportFailures++; + if (input.charCodeAt(pos) === 93) { + result0 = "]"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"]\""); + } + } + if (result0 === null) { + if (input.charCodeAt(pos) === 92) { + result0 = "\\"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"\\\\\""); + } + } + if (result0 === null) { + result0 = parse_eolChar(); + } + } + reportFailures--; + if (result0 === null) { + result0 = ""; + } else { + result0 = null; + pos = pos2; + } + if (result0 !== null) { + if (input.length > pos) { + result1 = input.charAt(pos); + pos++; + } else { + result1 = null; + if (reportFailures === 0) { + matchFailed("any character"); + } + } + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, char_) { return char_; })(pos0, result0[1]); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_simpleEscapeSequence() { + var result0, result1, result2; + var pos0, pos1, pos2; + + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 92) { + result0 = "\\"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"\\\\\""); + } + } + if (result0 !== null) { + pos2 = pos; + reportFailures++; + result1 = parse_digit(); + if (result1 === null) { + if (input.charCodeAt(pos) === 120) { + result1 = "x"; + pos++; + } else { + result1 = null; + if (reportFailures === 0) { + matchFailed("\"x\""); + } + } + if (result1 === null) { + if (input.charCodeAt(pos) === 117) { + result1 = "u"; + pos++; + } else { + result1 = null; + if (reportFailures === 0) { + matchFailed("\"u\""); + } + } + if (result1 === null) { + result1 = parse_eolChar(); + } + } + } + reportFailures--; + if (result1 === null) { + result1 = ""; + } else { + result1 = null; + pos = pos2; + } + if (result1 !== null) { + if (input.length > pos) { + result2 = input.charAt(pos); + pos++; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("any character"); + } + } + if (result2 !== null) { + result0 = [result0, result1, result2]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, char_) { + return char_ + .replace("b", "\b") + .replace("f", "\f") + .replace("n", "\n") + .replace("r", "\r") + .replace("t", "\t") + .replace("v", "\x0B"); // IE does not recognize "\v". + })(pos0, result0[2]); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_zeroEscapeSequence() { + var result0, result1; + var pos0, pos1, pos2; + + pos0 = pos; + pos1 = pos; + if (input.substr(pos, 2) === "\\0") { + result0 = "\\0"; + pos += 2; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"\\\\0\""); + } + } + if (result0 !== null) { + pos2 = pos; + reportFailures++; + result1 = parse_digit(); + reportFailures--; + if (result1 === null) { + result1 = ""; + } else { + result1 = null; + pos = pos2; + } + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset) { return "\x00"; })(pos0); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_hexEscapeSequence() { + var result0, result1, result2; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + if (input.substr(pos, 2) === "\\x") { + result0 = "\\x"; + pos += 2; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"\\\\x\""); + } + } + if (result0 !== null) { + result1 = parse_hexDigit(); + if (result1 !== null) { + result2 = parse_hexDigit(); + if (result2 !== null) { + result0 = [result0, result1, result2]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, h1, h2) { + return String.fromCharCode(parseInt(h1 + h2, 16)); + })(pos0, result0[1], result0[2]); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_unicodeEscapeSequence() { + var result0, result1, result2, result3, result4; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + if (input.substr(pos, 2) === "\\u") { + result0 = "\\u"; + pos += 2; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"\\\\u\""); + } + } + if (result0 !== null) { + result1 = parse_hexDigit(); + if (result1 !== null) { + result2 = parse_hexDigit(); + if (result2 !== null) { + result3 = parse_hexDigit(); + if (result3 !== null) { + result4 = parse_hexDigit(); + if (result4 !== null) { + result0 = [result0, result1, result2, result3, result4]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, h1, h2, h3, h4) { + return String.fromCharCode(parseInt(h1 + h2 + h3 + h4, 16)); + })(pos0, result0[1], result0[2], result0[3], result0[4]); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_eolEscapeSequence() { + var result0, result1; + var pos0, pos1; + + pos0 = pos; + pos1 = pos; + if (input.charCodeAt(pos) === 92) { + result0 = "\\"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"\\\\\""); + } + } + if (result0 !== null) { + result1 = parse_eol(); + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos1; + } + } else { + result0 = null; + pos = pos1; + } + if (result0 !== null) { + result0 = (function(offset, eol) { return eol; })(pos0, result0[1]); + } + if (result0 === null) { + pos = pos0; + } + return result0; + } + + function parse_digit() { + var result0; + + if (/^[0-9]/.test(input.charAt(pos))) { + result0 = input.charAt(pos); + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("[0-9]"); + } + } + return result0; + } + + function parse_hexDigit() { + var result0; + + if (/^[0-9a-fA-F]/.test(input.charAt(pos))) { + result0 = input.charAt(pos); + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("[0-9a-fA-F]"); + } + } + return result0; + } + + function parse_letter() { + var result0; + + result0 = parse_lowerCaseLetter(); + if (result0 === null) { + result0 = parse_upperCaseLetter(); + } + return result0; + } + + function parse_lowerCaseLetter() { + var result0; + + if (/^[a-z]/.test(input.charAt(pos))) { + result0 = input.charAt(pos); + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("[a-z]"); + } + } + return result0; + } + + function parse_upperCaseLetter() { + var result0; + + if (/^[A-Z]/.test(input.charAt(pos))) { + result0 = input.charAt(pos); + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("[A-Z]"); + } + } + return result0; + } + + function parse___() { + var result0, result1; + + result0 = []; + result1 = parse_whitespace(); + if (result1 === null) { + result1 = parse_eol(); + if (result1 === null) { + result1 = parse_comment(); + } + } + while (result1 !== null) { + result0.push(result1); + result1 = parse_whitespace(); + if (result1 === null) { + result1 = parse_eol(); + if (result1 === null) { + result1 = parse_comment(); + } + } + } + return result0; + } + + function parse_comment() { + var result0; + + reportFailures++; + result0 = parse_singleLineComment(); + if (result0 === null) { + result0 = parse_multiLineComment(); + } + reportFailures--; + if (reportFailures === 0 && result0 === null) { + matchFailed("comment"); + } + return result0; + } + + function parse_singleLineComment() { + var result0, result1, result2, result3; + var pos0, pos1, pos2; + + pos0 = pos; + if (input.substr(pos, 2) === "//") { + result0 = "//"; + pos += 2; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"//\""); + } + } + if (result0 !== null) { + result1 = []; + pos1 = pos; + pos2 = pos; + reportFailures++; + result2 = parse_eolChar(); + reportFailures--; + if (result2 === null) { + result2 = ""; + } else { + result2 = null; + pos = pos2; + } + if (result2 !== null) { + if (input.length > pos) { + result3 = input.charAt(pos); + pos++; + } else { + result3 = null; + if (reportFailures === 0) { + matchFailed("any character"); + } + } + if (result3 !== null) { + result2 = [result2, result3]; + } else { + result2 = null; + pos = pos1; + } + } else { + result2 = null; + pos = pos1; + } + while (result2 !== null) { + result1.push(result2); + pos1 = pos; + pos2 = pos; + reportFailures++; + result2 = parse_eolChar(); + reportFailures--; + if (result2 === null) { + result2 = ""; + } else { + result2 = null; + pos = pos2; + } + if (result2 !== null) { + if (input.length > pos) { + result3 = input.charAt(pos); + pos++; + } else { + result3 = null; + if (reportFailures === 0) { + matchFailed("any character"); + } + } + if (result3 !== null) { + result2 = [result2, result3]; + } else { + result2 = null; + pos = pos1; + } + } else { + result2 = null; + pos = pos1; + } + } + if (result1 !== null) { + result0 = [result0, result1]; + } else { + result0 = null; + pos = pos0; + } + } else { + result0 = null; + pos = pos0; + } + return result0; + } + + function parse_multiLineComment() { + var result0, result1, result2, result3; + var pos0, pos1, pos2; + + pos0 = pos; + if (input.substr(pos, 2) === "/*") { + result0 = "/*"; + pos += 2; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"/*\""); + } + } + if (result0 !== null) { + result1 = []; + pos1 = pos; + pos2 = pos; + reportFailures++; + if (input.substr(pos, 2) === "*/") { + result2 = "*/"; + pos += 2; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("\"*/\""); + } + } + reportFailures--; + if (result2 === null) { + result2 = ""; + } else { + result2 = null; + pos = pos2; + } + if (result2 !== null) { + if (input.length > pos) { + result3 = input.charAt(pos); + pos++; + } else { + result3 = null; + if (reportFailures === 0) { + matchFailed("any character"); + } + } + if (result3 !== null) { + result2 = [result2, result3]; + } else { + result2 = null; + pos = pos1; + } + } else { + result2 = null; + pos = pos1; + } + while (result2 !== null) { + result1.push(result2); + pos1 = pos; + pos2 = pos; + reportFailures++; + if (input.substr(pos, 2) === "*/") { + result2 = "*/"; + pos += 2; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("\"*/\""); + } + } + reportFailures--; + if (result2 === null) { + result2 = ""; + } else { + result2 = null; + pos = pos2; + } + if (result2 !== null) { + if (input.length > pos) { + result3 = input.charAt(pos); + pos++; + } else { + result3 = null; + if (reportFailures === 0) { + matchFailed("any character"); + } + } + if (result3 !== null) { + result2 = [result2, result3]; + } else { + result2 = null; + pos = pos1; + } + } else { + result2 = null; + pos = pos1; + } + } + if (result1 !== null) { + if (input.substr(pos, 2) === "*/") { + result2 = "*/"; + pos += 2; + } else { + result2 = null; + if (reportFailures === 0) { + matchFailed("\"*/\""); + } + } + if (result2 !== null) { + result0 = [result0, result1, result2]; + } else { + result0 = null; + pos = pos0; + } + } else { + result0 = null; + pos = pos0; + } + } else { + result0 = null; + pos = pos0; + } + return result0; + } + + function parse_eol() { + var result0; + + reportFailures++; + if (input.charCodeAt(pos) === 10) { + result0 = "\n"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"\\n\""); + } + } + if (result0 === null) { + if (input.substr(pos, 2) === "\r\n") { + result0 = "\r\n"; + pos += 2; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"\\r\\n\""); + } + } + if (result0 === null) { + if (input.charCodeAt(pos) === 13) { + result0 = "\r"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"\\r\""); + } + } + if (result0 === null) { + if (input.charCodeAt(pos) === 8232) { + result0 = "\u2028"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"\\u2028\""); + } + } + if (result0 === null) { + if (input.charCodeAt(pos) === 8233) { + result0 = "\u2029"; + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("\"\\u2029\""); + } + } + } + } + } + } + reportFailures--; + if (reportFailures === 0 && result0 === null) { + matchFailed("end of line"); + } + return result0; + } + + function parse_eolChar() { + var result0; + + if (/^[\n\r\u2028\u2029]/.test(input.charAt(pos))) { + result0 = input.charAt(pos); + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("[\\n\\r\\u2028\\u2029]"); + } + } + return result0; + } + + function parse_whitespace() { + var result0; + + reportFailures++; + if (/^[ \t\x0B\f\xA0\uFEFF\u1680\u180E\u2000-\u200A\u202F\u205F\u3000]/.test(input.charAt(pos))) { + result0 = input.charAt(pos); + pos++; + } else { + result0 = null; + if (reportFailures === 0) { + matchFailed("[ \\t\\x0B\\f\\xA0\\uFEFF\\u1680\\u180E\\u2000-\\u200A\\u202F\\u205F\\u3000]"); + } + } + reportFailures--; + if (reportFailures === 0 && result0 === null) { + matchFailed("whitespace"); + } + return result0; + } + + + function cleanupExpected(expected) { + expected.sort(); + + var lastExpected = null; + var cleanExpected = []; + for (var i = 0; i < expected.length; i++) { + if (expected[i] !== lastExpected) { + cleanExpected.push(expected[i]); + lastExpected = expected[i]; + } + } + return cleanExpected; + } + + function computeErrorPosition() { + /* + * The first idea was to use |String.split| to break the input up to the + * error position along newlines and derive the line and column from + * there. However IE's |split| implementation is so broken that it was + * enough to prevent it. + */ + + var line = 1; + var column = 1; + var seenCR = false; + + for (var i = 0; i < Math.max(pos, rightmostFailuresPos); i++) { + var ch = input.charAt(i); + if (ch === "\n") { + if (!seenCR) { line++; } + column = 1; + seenCR = false; + } else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") { + line++; + column = 1; + seenCR = true; + } else { + column++; + seenCR = false; + } + } + + return { line: line, column: column }; + } + + + var result = parseFunctions[startRule](); + + /* + * The parser is now in one of the following three states: + * + * 1. The parser successfully parsed the whole input. + * + * - |result !== null| + * - |pos === input.length| + * - |rightmostFailuresExpected| may or may not contain something + * + * 2. The parser successfully parsed only a part of the input. + * + * - |result !== null| + * - |pos < input.length| + * - |rightmostFailuresExpected| may or may not contain something + * + * 3. The parser did not successfully parse any part of the input. + * + * - |result === null| + * - |pos === 0| + * - |rightmostFailuresExpected| contains at least one failure + * + * All code following this comment (including called functions) must + * handle these states. + */ + if (result === null || pos !== input.length) { + var offset = Math.max(pos, rightmostFailuresPos); + var found = offset < input.length ? input.charAt(offset) : null; + var errorPosition = computeErrorPosition(); + + throw new this.SyntaxError( + cleanupExpected(rightmostFailuresExpected), + found, + offset, + errorPosition.line, + errorPosition.column + ); + } + + return result; + }, + + /* Returns the parser source code. */ + toSource: function() { return this._source; } + }; + + /* Thrown when a parser encounters a syntax error. */ + + result.SyntaxError = function(expected, found, offset, line, column) { + function buildMessage(expected, found) { + var expectedHumanized, foundHumanized; + + switch (expected.length) { + case 0: + expectedHumanized = "end of input"; + break; + case 1: + expectedHumanized = expected[0]; + break; + default: + expectedHumanized = expected.slice(0, expected.length - 1).join(", ") + + " or " + + expected[expected.length - 1]; + } + + foundHumanized = found ? quote(found) : "end of input"; + + return "Expected " + expectedHumanized + " but " + foundHumanized + " found."; + } + + this.name = "SyntaxError"; + this.expected = expected; + this.found = found; + this.message = buildMessage(expected, found); + this.offset = offset; + this.line = line; + this.column = column; + }; + + result.SyntaxError.prototype = Error.prototype; + + return result; +})(); +PEG.compiler = { + /* + * Names of passes that will get run during the compilation (in the specified + * order). + */ + appliedPassNames: [ + "reportMissingRules", + "reportLeftRecursion", + "removeProxyRules", + "computeVarNames", + "computeParams" + ], + + /* + * Generates a parser from a specified grammar AST. Throws |PEG.GrammarError| + * if the AST contains a semantic error. Note that not all errors are detected + * during the generation and some may protrude to the generated parser and + * cause its malfunction. + */ + compile: function(ast, options) { + var that = this; + + each(this.appliedPassNames, function(passName) { + that.passes[passName](ast); + }); + + var source = this.emitter(ast, options); + var result = eval(source); + result._source = source; + + return result; + } +}; + +/* + * Compiler passes. + * + * Each pass is a function that is passed the AST. It can perform checks on it + * or modify it as needed. If the pass encounters a semantic error, it throws + * |PEG.GrammarError|. + */ +PEG.compiler.passes = { + /* Checks that all referenced rules exist. */ + reportMissingRules: function(ast) { + function nop() {} + + function checkExpression(node) { check(node.expression); } + + function checkSubnodes(propertyName) { + return function(node) { each(node[propertyName], check); }; + } + + var check = buildNodeVisitor({ + grammar: checkSubnodes("rules"), + rule: checkExpression, + choice: checkSubnodes("alternatives"), + sequence: checkSubnodes("elements"), + labeled: checkExpression, + simple_and: checkExpression, + simple_not: checkExpression, + semantic_and: nop, + semantic_not: nop, + optional: checkExpression, + zero_or_more: checkExpression, + one_or_more: checkExpression, + action: checkExpression, + + rule_ref: + function(node) { + if (!findRuleByName(ast, node.name)) { + throw new PEG.GrammarError( + "Referenced rule \"" + node.name + "\" does not exist." + ); + } + }, + + literal: nop, + any: nop, + "class": nop + }); + + check(ast); + }, + + /* Checks that no left recursion is present. */ + reportLeftRecursion: function(ast) { + function nop() {} + + function checkExpression(node, appliedRules) { + check(node.expression, appliedRules); + } + + function checkSubnodes(propertyName) { + return function(node, appliedRules) { + each(node[propertyName], function(subnode) { + check(subnode, appliedRules); + }); + }; + } + + var check = buildNodeVisitor({ + grammar: checkSubnodes("rules"), + + rule: + function(node, appliedRules) { + check(node.expression, appliedRules.concat(node.name)); + }, + + choice: checkSubnodes("alternatives"), + + sequence: + function(node, appliedRules) { + if (node.elements.length > 0) { + check(node.elements[0], appliedRules); + } + }, + + labeled: checkExpression, + simple_and: checkExpression, + simple_not: checkExpression, + semantic_and: nop, + semantic_not: nop, + optional: checkExpression, + zero_or_more: checkExpression, + one_or_more: checkExpression, + action: checkExpression, + + rule_ref: + function(node, appliedRules) { + if (contains(appliedRules, node.name)) { + throw new PEG.GrammarError( + "Left recursion detected for rule \"" + node.name + "\"." + ); + } + check(findRuleByName(ast, node.name), appliedRules); + }, + + literal: nop, + any: nop, + "class": nop + }); + + check(ast, []); + }, + + /* + * Removes proxy rules -- that is, rules that only delegate to other rule. + */ + removeProxyRules: function(ast) { + function isProxyRule(node) { + return node.type === "rule" && node.expression.type === "rule_ref"; + } + + function replaceRuleRefs(ast, from, to) { + function nop() {} + + function replaceInExpression(node, from, to) { + replace(node.expression, from, to); + } + + function replaceInSubnodes(propertyName) { + return function(node, from, to) { + each(node[propertyName], function(subnode) { + replace(subnode, from, to); + }); + }; + } + + var replace = buildNodeVisitor({ + grammar: replaceInSubnodes("rules"), + rule: replaceInExpression, + choice: replaceInSubnodes("alternatives"), + sequence: replaceInSubnodes("elements"), + labeled: replaceInExpression, + simple_and: replaceInExpression, + simple_not: replaceInExpression, + semantic_and: nop, + semantic_not: nop, + optional: replaceInExpression, + zero_or_more: replaceInExpression, + one_or_more: replaceInExpression, + action: replaceInExpression, + + rule_ref: + function(node, from, to) { + if (node.name === from) { + node.name = to; + } + }, + + literal: nop, + any: nop, + "class": nop + }); + + replace(ast, from, to); + } + + var indices = []; + + each(ast.rules, function(rule, i) { + if (isProxyRule(rule)) { + replaceRuleRefs(ast, rule.name, rule.expression.name); + if (rule.name === ast.startRule) { + ast.startRule = rule.expression.name; + } + indices.push(i); + } + }); + + indices.reverse(); + + each(indices, function(index) { + ast.rules.splice(index, 1); + }); + }, + + /* + * Computes names of variables used for storing match results and parse + * positions in generated code. These variables are organized as two stacks. + * The following will hold after running this pass: + * + * * All nodes except "grammar" and "rule" nodes will have a |resultVar| + * property. It will contain a name of the variable that will store a + * match result of the expression represented by the node in generated + * code. + * + * * Some nodes will have a |posVar| property. It will contain a name of the + * variable that will store a parse position in generated code. + * + * * All "rule" nodes will contain |resultVars| and |posVars| properties. + * They will contain a list of values of |resultVar| and |posVar| + * properties used in rule's subnodes. (This is useful to declare + * variables in generated code.) + */ + computeVarNames: function(ast) { + function resultVar(index) { return "result" + index; } + function posVar(index) { return "pos" + index; } + + function computeLeaf(node, index) { + node.resultVar = resultVar(index.result); + + return { result: 0, pos: 0 }; + } + + function computeFromExpression(delta) { + return function(node, index) { + var depth = compute( + node.expression, + { + result: index.result + delta.result, + pos: index.pos + delta.pos + } + ); + + node.resultVar = resultVar(index.result); + if (delta.pos !== 0) { + node.posVar = posVar(index.pos); + } + + return { + result: depth.result + delta.result, + pos: depth.pos + delta.pos + }; + }; + } + + var compute = buildNodeVisitor({ + grammar: + function(node, index) { + each(node.rules, function(node) { + compute(node, index); + }); + }, + + rule: + function(node, index) { + var depth = compute(node.expression, index); + + node.resultVar = resultVar(index.result); + node.resultVars = map(range(depth.result + 1), resultVar); + node.posVars = map(range(depth.pos), posVar); + }, + + choice: + function(node, index) { + var depths = map(node.alternatives, function(alternative) { + return compute(alternative, index); + }); + + node.resultVar = resultVar(index.result); + + return { + result: Math.max.apply(null, pluck(depths, "result")), + pos: Math.max.apply(null, pluck(depths, "pos")) + }; + }, + + sequence: + function(node, index) { + var depths = map(node.elements, function(element, i) { + return compute( + element, + { result: index.result + i, pos: index.pos + 1 } + ); + }); + + node.resultVar = resultVar(index.result); + node.posVar = posVar(index.pos); + + return { + result: + node.elements.length > 0 + ? Math.max.apply( + null, + map(depths, function(d, i) { return i + d.result; }) + ) + : 0, + + pos: + node.elements.length > 0 + ? 1 + Math.max.apply(null, pluck(depths, "pos")) + : 1 + }; + }, + + labeled: computeFromExpression({ result: 0, pos: 0 }), + simple_and: computeFromExpression({ result: 0, pos: 1 }), + simple_not: computeFromExpression({ result: 0, pos: 1 }), + semantic_and: computeLeaf, + semantic_not: computeLeaf, + optional: computeFromExpression({ result: 0, pos: 0 }), + zero_or_more: computeFromExpression({ result: 1, pos: 0 }), + one_or_more: computeFromExpression({ result: 1, pos: 0 }), + action: computeFromExpression({ result: 0, pos: 1 }), + rule_ref: computeLeaf, + literal: computeLeaf, + any: computeLeaf, + "class": computeLeaf + }); + + compute(ast, { result: 0, pos: 0 }); + }, + + /* + * This pass walks through the AST and tracks what labels are visible at each + * point. For "action", "semantic_and" and "semantic_or" nodes it computes + * parameter names and values for the function used in generated code. (In the + * emitter, user's code is wrapped into a function that is immediately + * executed. Its parameter names correspond to visible labels and its + * parameter values to their captured values). Implicitly, this pass defines + * scoping rules for labels. + * + * After running this pass, all "action", "semantic_and" and "semantic_or" + * nodes will have a |params| property containing an object mapping parameter + * names to the expressions that will be used as their values. + */ + computeParams: function(ast) { + var envs = []; + + function scoped(f) { + envs.push({}); + f(); + envs.pop(); + } + + function nop() {} + + function computeForScopedExpression(node) { + scoped(function() { compute(node.expression); }); + } + + function computeParams(node) { + var env = envs[envs.length - 1], params = {}, name; + + for (name in env) { + params[name] = env[name]; + } + node.params = params; + } + + var compute = buildNodeVisitor({ + grammar: + function(node) { + each(node.rules, compute); + }, + + rule: computeForScopedExpression, + + choice: + function(node) { + scoped(function() { each(node.alternatives, compute); }); + }, + + sequence: + function(node) { + var env = envs[envs.length - 1], name; + + function fixup(name) { + each(pluck(node.elements, "resultVar"), function(resultVar, i) { + if ((new RegExp("^" + resultVar + "(\\[\\d+\\])*$")).test(env[name])) { + env[name] = node.resultVar + "[" + i + "]" + + env[name].substr(resultVar.length); + } + }); + } + + each(node.elements, compute); + + for (name in env) { + fixup(name); + } + }, + + labeled: + function(node) { + envs[envs.length - 1][node.label] = node.resultVar; + + scoped(function() { compute(node.expression); }); + }, + + simple_and: computeForScopedExpression, + simple_not: computeForScopedExpression, + semantic_and: computeParams, + semantic_not: computeParams, + optional: computeForScopedExpression, + zero_or_more: computeForScopedExpression, + one_or_more: computeForScopedExpression, + + action: + function(node) { + scoped(function() { + compute(node.expression); + computeParams(node); + }); + }, + + rule_ref: nop, + literal: nop, + any: nop, + "class": nop + }); + + compute(ast); + } +}; +/* Emits the generated code for the AST. */ +PEG.compiler.emitter = function(ast, options) { + options = options || {}; + if (options.cache === undefined) { + options.cache = false; + } + if (options.trackLineAndColumn === undefined) { + options.trackLineAndColumn = false; + } + + /* + * Codie 1.1.0 + * + * https://github.com/dmajda/codie + * + * Copyright (c) 2011-2012 David Majda + * Licensend under the MIT license. + */ + var Codie = (function(undefined) { + + function stringEscape(s) { + function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); } + + /* + * ECMA-262, 5th ed., 7.8.4: All characters may appear literally in a + * string literal except for the closing quote character, backslash, + * carriage return, line separator, paragraph separator, and line feed. + * Any character may appear in the form of an escape sequence. + * + * For portability, we also escape escape all control and non-ASCII + * characters. Note that "\0" and "\v" escape sequences are not used + * because JSHint does not like the first and IE the second. + */ + return s + .replace(/\\/g, '\\\\') // backslash + .replace(/"/g, '\\"') // closing double quote + .replace(/\x08/g, '\\b') // backspace + .replace(/\t/g, '\\t') // horizontal tab + .replace(/\n/g, '\\n') // line feed + .replace(/\f/g, '\\f') // form feed + .replace(/\r/g, '\\r') // carriage return + .replace(/[\x00-\x07\x0B\x0E\x0F]/g, function(ch) { return '\\x0' + hex(ch); }) + .replace(/[\x10-\x1F\x80-\xFF]/g, function(ch) { return '\\x' + hex(ch); }) + .replace(/[\u0180-\u0FFF]/g, function(ch) { return '\\u0' + hex(ch); }) + .replace(/[\u1080-\uFFFF]/g, function(ch) { return '\\u' + hex(ch); }); + } + + function push(s) { return '__p.push(' + s + ');'; } + + function pushRaw(template, length, state) { + function unindent(code, level, unindentFirst) { + return code.replace( + new RegExp('^.{' + level +'}', "gm"), + function(str, offset) { + if (offset === 0) { + return unindentFirst ? '' : str; + } else { + return ""; + } + } + ); + } + + var escaped = stringEscape(unindent( + template.substring(0, length), + state.indentLevel(), + state.atBOL + )); + + return escaped.length > 0 ? push('"' + escaped + '"') : ''; + } + + + var Codie = { + /* Codie version (uses semantic versioning). */ + VERSION: "1.1.0", + + /* + * Specifies by how many characters do #if/#else and #for unindent their + * content in the generated code. + */ + indentStep: 2, + + /* Description of #-commands. Extend to define your own commands. */ + commands: { + "if": { + params: /^(.*)$/, + compile: function(state, prefix, params) { + return ['if(' + params[0] + '){', []]; + }, + stackOp: "push" + }, + "else": { + params: /^$/, + compile: function(state) { + var stack = state.commandStack, + insideElse = stack[stack.length - 1] === "else", + insideIf = stack[stack.length - 1] === "if"; + + if (insideElse) { throw new Error("Multiple #elses."); } + if (!insideIf) { throw new Error("Using #else outside of #if."); } + + return ['}else{', []]; + }, + stackOp: "replace" + }, + "for": { + params: /^([a-zA-Z_][a-zA-Z0-9_]*)[ \t]+in[ \t]+(.*)$/, + init: function(state) { + state.forCurrLevel = 0; // current level of #for loop nesting + state.forMaxLevel = 0; // maximum level of #for loop nesting + }, + compile: function(state, prefix, params) { + var c = '__c' + state.forCurrLevel, // __c for "collection" + l = '__l' + state.forCurrLevel, // __l for "length" + i = '__i' + state.forCurrLevel; // __i for "index" + + state.forCurrLevel++; + if (state.forMaxLevel < state.forCurrLevel) { + state.forMaxLevel = state.forCurrLevel; + } + + return [ + c + '=' + params[1] + ';' + + l + '=' + c + '.length;' + + 'for(' + i + '=0;' + i + '<' + l + ';' + i + '++){' + + params[0] + '=' + c + '[' + i + '];', + [params[0], c, l, i] + ]; + }, + exit: function(state) { state.forCurrLevel--; }, + stackOp: "push" + }, + "end": { + params: /^$/, + compile: function(state) { + var stack = state.commandStack, exit; + + if (stack.length === 0) { throw new Error("Too many #ends."); } + + exit = Codie.commands[stack[stack.length - 1]].exit; + if (exit) { exit(state); } + + return ['}', []]; + }, + stackOp: "pop" + }, + "block": { + params: /^(.*)$/, + compile: function(state, prefix, params) { + var x = '__x', // __x for "prefix", + n = '__n', // __n for "lines" + l = '__l', // __l for "length" + i = '__i'; // __i for "index" + + /* + * Originally, the generated code used |String.prototype.replace|, but + * it is buggy in certain versions of V8 so it was rewritten. See the + * tests for details. + */ + return [ + x + '="' + stringEscape(prefix.substring(state.indentLevel())) + '";' + + n + '=(' + params[0] + ').toString().split("\\n");' + + l + '=' + n + '.length;' + + 'for(' + i + '=0;' + i + '<' + l + ';' + i + '++){' + + n + '[' + i +']=' + x + '+' + n + '[' + i + ']+"\\n";' + + '}' + + push(n + '.join("")'), + [x, n, l, i] + ]; + }, + stackOp: "nop" + } + }, + + /* + * Compiles a template into a function. When called, this function will + * execute the template in the context of an object passed in a parameter and + * return the result. + */ + template: function(template) { + var stackOps = { + push: function(stack, name) { stack.push(name); }, + replace: function(stack, name) { stack[stack.length - 1] = name; }, + pop: function(stack) { stack.pop(); }, + nop: function() { } + }; + + function compileExpr(state, expr) { + state.atBOL = false; + return [push(expr), []]; + } + + function compileCommand(state, prefix, name, params) { + var command, match, result; + + command = Codie.commands[name]; + if (!command) { throw new Error("Unknown command: #" + name + "."); } + + match = command.params.exec(params); + if (match === null) { + throw new Error( + "Invalid params for command #" + name + ": " + params + "." + ); + } + + result = command.compile(state, prefix, match.slice(1)); + stackOps[command.stackOp](state.commandStack, name); + state.atBOL = true; + return result; + } + + var state = { // compilation state + commandStack: [], // stack of commands as they were nested + atBOL: true, // is the next character to process at BOL? + indentLevel: function() { + return Codie.indentStep * this.commandStack.length; + } + }, + code = '', // generated template function code + vars = ['__p=[]'], // variables used by generated code + name, match, result, i; + + /* Initialize state. */ + for (name in Codie.commands) { + if (Codie.commands[name].init) { Codie.commands[name].init(state); } + } + + /* Compile the template. */ + while ((match = /^([ \t]*)#([a-zA-Z_][a-zA-Z0-9_]*)(?:[ \t]+([^ \t\n][^\n]*))?[ \t]*(?:\n|$)|#\{([^}]*)\}/m.exec(template)) !== null) { + code += pushRaw(template, match.index, state); + result = match[2] !== undefined && match[2] !== "" + ? compileCommand(state, match[1], match[2], match[3] || "") // #-command + : compileExpr(state, match[4]); // #{...} + code += result[0]; + vars = vars.concat(result[1]); + template = template.substring(match.index + match[0].length); + } + code += pushRaw(template, template.length, state); + + /* Check the final state. */ + if (state.commandStack.length > 0) { throw new Error("Missing #end."); } + + /* Sanitize the list of variables used by commands. */ + vars.sort(); + for (i = 0; i < vars.length; i++) { + if (vars[i] === vars[i - 1]) { vars.splice(i--, 1); } + } + + /* Create the resulting function. */ + return new Function("__v", [ + '__v=__v||{};', + 'var ' + vars.join(',') + ';', + 'with(__v){', + code, + 'return __p.join("").replace(/^\\n+|\\n+$/g,"");};' + ].join('')); + } + }; + + return Codie; + + })(); + + var templates = (function() { + var name, + templates = {}, + sources = { + grammar: [ + '(function(){', + ' /*', + ' * Generated by PEG.js 0.7.0.', + ' *', + ' * http://pegjs.majda.cz/', + ' */', + ' ', + /* This needs to be in sync with |quote| in utils.js. */ + ' function quote(s) {', + ' /*', + ' * ECMA-262, 5th ed., 7.8.4: All characters may appear literally in a', + ' * string literal except for the closing quote character, backslash,', + ' * carriage return, line separator, paragraph separator, and line feed.', + ' * Any character may appear in the form of an escape sequence.', + ' *', + ' * For portability, we also escape escape all control and non-ASCII', + ' * characters. Note that "\\0" and "\\v" escape sequences are not used', + ' * because JSHint does not like the first and IE the second.', + ' */', + ' return \'"\' + s', + ' .replace(/\\\\/g, \'\\\\\\\\\') // backslash', + ' .replace(/"/g, \'\\\\"\') // closing quote character', + ' .replace(/\\x08/g, \'\\\\b\') // backspace', + ' .replace(/\\t/g, \'\\\\t\') // horizontal tab', + ' .replace(/\\n/g, \'\\\\n\') // line feed', + ' .replace(/\\f/g, \'\\\\f\') // form feed', + ' .replace(/\\r/g, \'\\\\r\') // carriage return', + ' .replace(/[\\x00-\\x07\\x0B\\x0E-\\x1F\\x80-\\uFFFF]/g, escape)', + ' + \'"\';', + ' }', + ' ', + ' var result = {', + ' /*', + ' * Parses the input with a generated parser. If the parsing is successfull,', + ' * returns a value explicitly or implicitly specified by the grammar from', + ' * which the parser was generated (see |PEG.buildParser|). If the parsing is', + ' * unsuccessful, throws |PEG.parser.SyntaxError| describing the error.', + ' */', + ' parse: function(input, startRule) {', + ' var parseFunctions = {', + ' #for rule in node.rules', + ' #{string(rule.name) + ": parse_" + rule.name + (rule !== node.rules[node.rules.length - 1] ? "," : "")}', + ' #end', + ' };', + ' ', + ' if (startRule !== undefined) {', + ' if (parseFunctions[startRule] === undefined) {', + ' throw new Error("Invalid rule name: " + quote(startRule) + ".");', + ' }', + ' } else {', + ' startRule = #{string(node.startRule)};', + ' }', + ' ', + ' #{posInit("pos")};', + ' var reportFailures = 0;', // 0 = report, anything > 0 = do not report + ' #{posInit("rightmostFailuresPos")};', + ' var rightmostFailuresExpected = [];', + ' #if options.cache', + ' var cache = {};', + ' #end', + ' ', + /* This needs to be in sync with |padLeft| in utils.js. */ + ' function padLeft(input, padding, length) {', + ' var result = input;', + ' ', + ' var padLength = length - input.length;', + ' for (var i = 0; i < padLength; i++) {', + ' result = padding + result;', + ' }', + ' ', + ' return result;', + ' }', + ' ', + /* This needs to be in sync with |escape| in utils.js. */ + ' function escape(ch) {', + ' var charCode = ch.charCodeAt(0);', + ' var escapeChar;', + ' var length;', + ' ', + ' if (charCode <= 0xFF) {', + ' escapeChar = \'x\';', + ' length = 2;', + ' } else {', + ' escapeChar = \'u\';', + ' length = 4;', + ' }', + ' ', + ' return \'\\\\\' + escapeChar + padLeft(charCode.toString(16).toUpperCase(), \'0\', length);', + ' }', + ' ', + ' #if options.trackLineAndColumn', + ' function clone(object) {', + ' var result = {};', + ' for (var key in object) {', + ' result[key] = object[key];', + ' }', + ' return result;', + ' }', + ' ', + ' function advance(pos, n) {', + ' var endOffset = pos.offset + n;', + ' ', + ' for (var offset = pos.offset; offset < endOffset; offset++) {', + ' var ch = input.charAt(offset);', + ' if (ch === "\\n") {', + ' if (!pos.seenCR) { pos.line++; }', + ' pos.column = 1;', + ' pos.seenCR = false;', + ' } else if (ch === "\\r" || ch === "\\u2028" || ch === "\\u2029") {', + ' pos.line++;', + ' pos.column = 1;', + ' pos.seenCR = true;', + ' } else {', + ' pos.column++;', + ' pos.seenCR = false;', + ' }', + ' }', + ' ', + ' pos.offset += n;', + ' }', + ' ', + ' #end', + ' function matchFailed(failure) {', + ' if (#{posOffset("pos")} < #{posOffset("rightmostFailuresPos")}) {', + ' return;', + ' }', + ' ', + ' if (#{posOffset("pos")} > #{posOffset("rightmostFailuresPos")}) {', + ' rightmostFailuresPos = #{posClone("pos")};', + ' rightmostFailuresExpected = [];', + ' }', + ' ', + ' rightmostFailuresExpected.push(failure);', + ' }', + ' ', + ' #for rule in node.rules', + ' #block emit(rule)', + ' ', + ' #end', + ' ', + ' function cleanupExpected(expected) {', + ' expected.sort();', + ' ', + ' var lastExpected = null;', + ' var cleanExpected = [];', + ' for (var i = 0; i < expected.length; i++) {', + ' if (expected[i] !== lastExpected) {', + ' cleanExpected.push(expected[i]);', + ' lastExpected = expected[i];', + ' }', + ' }', + ' return cleanExpected;', + ' }', + ' ', + ' #if !options.trackLineAndColumn', + ' function computeErrorPosition() {', + ' /*', + ' * The first idea was to use |String.split| to break the input up to the', + ' * error position along newlines and derive the line and column from', + ' * there. However IE\'s |split| implementation is so broken that it was', + ' * enough to prevent it.', + ' */', + ' ', + ' var line = 1;', + ' var column = 1;', + ' var seenCR = false;', + ' ', + ' for (var i = 0; i < Math.max(pos, rightmostFailuresPos); i++) {', + ' var ch = input.charAt(i);', + ' if (ch === "\\n") {', + ' if (!seenCR) { line++; }', + ' column = 1;', + ' seenCR = false;', + ' } else if (ch === "\\r" || ch === "\\u2028" || ch === "\\u2029") {', + ' line++;', + ' column = 1;', + ' seenCR = true;', + ' } else {', + ' column++;', + ' seenCR = false;', + ' }', + ' }', + ' ', + ' return { line: line, column: column };', + ' }', + ' #end', + ' ', + ' #if node.initializer', + ' #block emit(node.initializer)', + ' #end', + ' ', + ' var result = parseFunctions[startRule]();', + ' ', + ' /*', + ' * The parser is now in one of the following three states:', + ' *', + ' * 1. The parser successfully parsed the whole input.', + ' *', + ' * - |result !== null|', + ' * - |#{posOffset("pos")} === input.length|', + ' * - |rightmostFailuresExpected| may or may not contain something', + ' *', + ' * 2. The parser successfully parsed only a part of the input.', + ' *', + ' * - |result !== null|', + ' * - |#{posOffset("pos")} < input.length|', + ' * - |rightmostFailuresExpected| may or may not contain something', + ' *', + ' * 3. The parser did not successfully parse any part of the input.', + ' *', + ' * - |result === null|', + ' * - |#{posOffset("pos")} === 0|', + ' * - |rightmostFailuresExpected| contains at least one failure', + ' *', + ' * All code following this comment (including called functions) must', + ' * handle these states.', + ' */', + ' if (result === null || #{posOffset("pos")} !== input.length) {', + ' var offset = Math.max(#{posOffset("pos")}, #{posOffset("rightmostFailuresPos")});', + ' var found = offset < input.length ? input.charAt(offset) : null;', + ' #if options.trackLineAndColumn', + ' var errorPosition = #{posOffset("pos")} > #{posOffset("rightmostFailuresPos")} ? pos : rightmostFailuresPos;', + ' #else', + ' var errorPosition = computeErrorPosition();', + ' #end', + ' ', + ' throw new this.SyntaxError(', + ' cleanupExpected(rightmostFailuresExpected),', + ' found,', + ' offset,', + ' errorPosition.line,', + ' errorPosition.column', + ' );', + ' }', + ' ', + ' return result;', + ' },', + ' ', + ' /* Returns the parser source code. */', + ' toSource: function() { return this._source; }', + ' };', + ' ', + ' /* Thrown when a parser encounters a syntax error. */', + ' ', + ' result.SyntaxError = function(expected, found, offset, line, column) {', + ' function buildMessage(expected, found) {', + ' var expectedHumanized, foundHumanized;', + ' ', + ' switch (expected.length) {', + ' case 0:', + ' expectedHumanized = "end of input";', + ' break;', + ' case 1:', + ' expectedHumanized = expected[0];', + ' break;', + ' default:', + ' expectedHumanized = expected.slice(0, expected.length - 1).join(", ")', + ' + " or "', + ' + expected[expected.length - 1];', + ' }', + ' ', + ' foundHumanized = found ? quote(found) : "end of input";', + ' ', + ' return "Expected " + expectedHumanized + " but " + foundHumanized + " found.";', + ' }', + ' ', + ' this.name = "SyntaxError";', + ' this.expected = expected;', + ' this.found = found;', + ' this.message = buildMessage(expected, found);', + ' this.offset = offset;', + ' this.line = line;', + ' this.column = column;', + ' };', + ' ', + ' result.SyntaxError.prototype = Error.prototype;', + ' ', + ' return result;', + '})()' + ], + rule: [ + 'function parse_#{node.name}() {', + ' #if options.cache', + ' var cacheKey = "#{node.name}@" + #{posOffset("pos")};', + ' var cachedResult = cache[cacheKey];', + ' if (cachedResult) {', + ' pos = #{posClone("cachedResult.nextPos")};', + ' return cachedResult.result;', + ' }', + ' ', + ' #end', + ' #if node.resultVars.length > 0', + ' var #{node.resultVars.join(", ")};', + ' #end', + ' #if node.posVars.length > 0', + ' var #{node.posVars.join(", ")};', + ' #end', + ' ', + ' #if node.displayName !== null', + ' reportFailures++;', + ' #end', + ' #block emit(node.expression)', + ' #if node.displayName !== null', + ' reportFailures--;', + ' if (reportFailures === 0 && #{node.resultVar} === null) {', + ' matchFailed(#{string(node.displayName)});', + ' }', + ' #end', + ' #if options.cache', + ' ', + ' cache[cacheKey] = {', + ' nextPos: #{posClone("pos")},', + ' result: #{node.resultVar}', + ' };', + ' #end', + ' return #{node.resultVar};', + '}' + ], + choice: [ + '#block emit(alternative)', + '#block nextAlternativesCode' + ], + "choice.next": [ + 'if (#{node.resultVar} === null) {', + ' #block code', + '}' + ], + sequence: [ + '#{posSave(node)};', + '#block code' + ], + "sequence.iteration": [ + '#block emit(element)', + 'if (#{element.resultVar} !== null) {', + ' #block code', + '} else {', + ' #{node.resultVar} = null;', + ' #{posRestore(node)};', + '}' + ], + "sequence.inner": [ + '#{node.resultVar} = [#{pluck(node.elements, "resultVar").join(", ")}];' + ], + simple_and: [ + '#{posSave(node)};', + 'reportFailures++;', + '#block emit(node.expression)', + 'reportFailures--;', + 'if (#{node.resultVar} !== null) {', + ' #{node.resultVar} = "";', + ' #{posRestore(node)};', + '} else {', + ' #{node.resultVar} = null;', + '}' + ], + simple_not: [ + '#{posSave(node)};', + 'reportFailures++;', + '#block emit(node.expression)', + 'reportFailures--;', + 'if (#{node.resultVar} === null) {', + ' #{node.resultVar} = "";', + '} else {', + ' #{node.resultVar} = null;', + ' #{posRestore(node)};', + '}' + ], + semantic_and: [ + '#{node.resultVar} = (function(#{(options.trackLineAndColumn ? ["offset", "line", "column"] : ["offset"]).concat(keys(node.params)).join(", ")}) {#{node.code}})(#{(options.trackLineAndColumn ? ["pos.offset", "pos.line", "pos.column"] : ["pos"]).concat(values(node.params)).join(", ")}) ? "" : null;' + ], + semantic_not: [ + '#{node.resultVar} = (function(#{(options.trackLineAndColumn ? ["offset", "line", "column"] : ["offset"]).concat(keys(node.params)).join(", ")}) {#{node.code}})(#{(options.trackLineAndColumn ? ["pos.offset", "pos.line", "pos.column"] : ["pos"]).concat(values(node.params)).join(", ")}) ? null : "";' + ], + optional: [ + '#block emit(node.expression)', + '#{node.resultVar} = #{node.resultVar} !== null ? #{node.resultVar} : "";' + ], + zero_or_more: [ + '#{node.resultVar} = [];', + '#block emit(node.expression)', + 'while (#{node.expression.resultVar} !== null) {', + ' #{node.resultVar}.push(#{node.expression.resultVar});', + ' #block emit(node.expression)', + '}' + ], + one_or_more: [ + '#block emit(node.expression)', + 'if (#{node.expression.resultVar} !== null) {', + ' #{node.resultVar} = [];', + ' while (#{node.expression.resultVar} !== null) {', + ' #{node.resultVar}.push(#{node.expression.resultVar});', + ' #block emit(node.expression)', + ' }', + '} else {', + ' #{node.resultVar} = null;', + '}' + ], + action: [ + '#{posSave(node)};', + '#block emit(node.expression)', + 'if (#{node.resultVar} !== null) {', + ' #{node.resultVar} = (function(#{(options.trackLineAndColumn ? ["offset", "line", "column"] : ["offset"]).concat(keys(node.params)).join(", ")}) {#{node.code}})(#{(options.trackLineAndColumn ? [node.posVar + ".offset", node.posVar + ".line", node.posVar + ".column"] : [node.posVar]).concat(values(node.params)).join(", ")});', + '}', + 'if (#{node.resultVar} === null) {', + ' #{posRestore(node)};', + '}' + ], + rule_ref: [ + '#{node.resultVar} = parse_#{node.name}();' + ], + literal: [ + '#if node.value.length === 0', + ' #{node.resultVar} = "";', + '#else', + ' #if !node.ignoreCase', + ' #if node.value.length === 1', + ' if (input.charCodeAt(#{posOffset("pos")}) === #{node.value.charCodeAt(0)}) {', + ' #else', + ' if (input.substr(#{posOffset("pos")}, #{node.value.length}) === #{string(node.value)}) {', + ' #end', + ' #else', + /* + * One-char literals are not optimized when case-insensitive + * matching is enabled. This is because there is no simple way to + * lowercase a character code that works for character outside ASCII + * letters. Moreover, |toLowerCase| can change string length, + * meaning the result of lowercasing a character can be more + * characters. + */ + ' if (input.substr(#{posOffset("pos")}, #{node.value.length}).toLowerCase() === #{string(node.value.toLowerCase())}) {', + ' #end', + ' #if !node.ignoreCase', + ' #{node.resultVar} = #{string(node.value)};', + ' #else', + ' #{node.resultVar} = input.substr(#{posOffset("pos")}, #{node.value.length});', + ' #end', + ' #{posAdvance(node.value.length)};', + ' } else {', + ' #{node.resultVar} = null;', + ' if (reportFailures === 0) {', + ' matchFailed(#{string(string(node.value))});', + ' }', + ' }', + '#end' + ], + any: [ + 'if (input.length > #{posOffset("pos")}) {', + ' #{node.resultVar} = input.charAt(#{posOffset("pos")});', + ' #{posAdvance(1)};', + '} else {', + ' #{node.resultVar} = null;', + ' if (reportFailures === 0) {', + ' matchFailed("any character");', + ' }', + '}' + ], + "class": [ + 'if (#{regexp}.test(input.charAt(#{posOffset("pos")}))) {', + ' #{node.resultVar} = input.charAt(#{posOffset("pos")});', + ' #{posAdvance(1)};', + '} else {', + ' #{node.resultVar} = null;', + ' if (reportFailures === 0) {', + ' matchFailed(#{string(node.rawText)});', + ' }', + '}' + ] + }; + + for (name in sources) { + templates[name] = Codie.template(sources[name].join('\n')); + } + + return templates; + })(); + + function fill(name, vars) { + vars.string = quote; + vars.pluck = pluck; + vars.keys = keys; + vars.values = values; + vars.emit = emit; + vars.options = options; + + /* Position-handling macros */ + if (options.trackLineAndColumn) { + vars.posInit = function(name) { + return "var " + + name + + " = " + + "{ offset: 0, line: 1, column: 1, seenCR: false }"; + }; + vars.posClone = function(name) { return "clone(" + name + ")"; }; + vars.posOffset = function(name) { return name + ".offset"; }; + + vars.posAdvance = function(n) { return "advance(pos, " + n + ")"; }; + } else { + vars.posInit = function(name) { return "var " + name + " = 0"; }; + vars.posClone = function(name) { return name; }; + vars.posOffset = function(name) { return name; }; + + vars.posAdvance = function(n) { + return n === 1 ? "pos++" : "pos += " + n; + }; + } + vars.posSave = function(node) { + return node.posVar + " = " + vars.posClone("pos"); + }; + vars.posRestore = function(node) { + return "pos" + " = " + vars.posClone(node.posVar); + }; + + return templates[name](vars); + } + + function emitSimple(name) { + return function(node) { return fill(name, { node: node }); }; + } + + var emit = buildNodeVisitor({ + grammar: emitSimple("grammar"), + + initializer: function(node) { return node.code; }, + + rule: emitSimple("rule"), + + /* + * The contract for all code fragments generated by the following functions + * is as follows. + * + * The code fragment tries to match a part of the input starting with the + * position indicated in |pos|. That position may point past the end of the + * input. + * + * * If the code fragment matches the input, it advances |pos| to point to + * the first chracter following the matched part of the input and sets + * variable with a name stored in |node.resultVar| to an appropriate + * value. This value is always non-|null|. + * + * * If the code fragment does not match the input, it returns with |pos| + * set to the original value and it sets a variable with a name stored in + * |node.resultVar| to |null|. + * + * The code can use variables with names stored in |resultVar| and |posVar| + * properties of the current node's subnodes. It can't use any other + * variables. + */ + + choice: function(node) { + var code, nextAlternativesCode; + + for (var i = node.alternatives.length - 1; i >= 0; i--) { + nextAlternativesCode = i !== node.alternatives.length - 1 + ? fill("choice.next", { node: node, code: code }) + : ''; + code = fill("choice", { + alternative: node.alternatives[i], + nextAlternativesCode: nextAlternativesCode + }); + } + + return code; + }, + + sequence: function(node) { + var code = fill("sequence.inner", { node: node }); + + for (var i = node.elements.length - 1; i >= 0; i--) { + code = fill("sequence.iteration", { + node: node, + element: node.elements[i], + code: code + }); + } + + return fill("sequence", { node: node, code: code }); + }, + + labeled: function(node) { return emit(node.expression); }, + + simple_and: emitSimple("simple_and"), + simple_not: emitSimple("simple_not"), + semantic_and: emitSimple("semantic_and"), + semantic_not: emitSimple("semantic_not"), + optional: emitSimple("optional"), + zero_or_more: emitSimple("zero_or_more"), + one_or_more: emitSimple("one_or_more"), + action: emitSimple("action"), + rule_ref: emitSimple("rule_ref"), + literal: emitSimple("literal"), + any: emitSimple("any"), + + "class": function(node) { + var regexp; + + if (node.parts.length > 0) { + regexp = '/^[' + + (node.inverted ? '^' : '') + + map(node.parts, function(part) { + return part instanceof Array + ? quoteForRegexpClass(part[0]) + + '-' + + quoteForRegexpClass(part[1]) + : quoteForRegexpClass(part); + }).join('') + + ']/' + (node.ignoreCase ? 'i' : ''); + } else { + /* + * Stupid IE considers regexps /[]/ and /[^]/ syntactically invalid, so + * we translate them into euqivalents it can handle. + */ + regexp = node.inverted ? '/^[\\S\\s]/' : '/^(?!)/'; + } + + return fill("class", { node: node, regexp: regexp }); + } + }); + + return emit(ast); +}; + +return PEG; + +})(); + +if (typeof module !== "undefined") { + module.exports = PEG; +} diff --git a/ajax/libs/pegjs/0.7.0/peg.min.js b/ajax/libs/pegjs/0.7.0/peg.min.js new file mode 100644 index 000000000..ed16abd23 --- /dev/null +++ b/ajax/libs/pegjs/0.7.0/peg.min.js @@ -0,0 +1,9 @@ +/* + * PEG.js 0.7.0 + * + * http://pegjs.majda.cz/ + * + * Copyright (c) 2010-2012 David Majda + * Licensend under the MIT license. + */var PEG=function(undefined){function range(a,b){b===undefined&&(b=a,a=0);var c=new Array(Math.max(0,b-a));for(var d=0,e=a;eg&&(g=e,h=[]),h.push(a)}function l(){var a,b,c,d,f,g;f=e,g=e,a=bg();if(a!==null){b=m(),b=b!==null?b:"";if(b!==null){d=n();if(d!==null){c=[];while(d!==null)c.push(d),d=n()}else c=null;c!==null?a=[a,b,c]:(a=null,e=g)}else a=null,e=g}else a=null,e=g;return a!==null&&(a=function(a,b,c){return{type:"grammar",initializer:b!==""?b:null,rules:c,startRule:c[0].name}}(f,a[1],a[2])),a===null&&(e=f),a}function m(){var a,b,c,d;return c=e,d=e,a=u(),a!==null?(b=A(),b=b!==null?b:"",b!==null?a=[a,b]:(a=null,e=d)):(a=null,e=d),a!==null&&(a=function(a,b){return{type:"initializer",code:b}}(c,a[0])),a===null&&(e=c),a}function n(){var a,b,c,d,f,g,h;return g=e,h=e,a=K(),a!==null?(b=M(),b=b!==null?b:"",b!==null?(c=y(),c!==null?(d=o(),d!==null?(f=A(),f=f!==null?f:"",f!==null?a=[a,b,c,d,f]:(a=null,e=h)):(a=null,e=h)):(a=null,e=h)):(a=null,e=h)):(a=null,e=h),a!==null&&(a=function(a,b,c,d){return{type:"rule",name:b,displayName:c!==""?c:null,expression:d}}(g,a[0],a[1],a[3])),a===null&&(e=g),a}function o(){var a,b,c,d,f,g,h;f=e,g=e,a=p();if(a!==null){b=[],h=e,c=B(),c!==null?(d=p(),d!==null?c=[c,d]:(c=null,e=h)):(c=null,e=h);while(c!==null)b.push(c),h=e,c=B(),c!==null?(d=p(),d!==null?c=[c,d]:(c=null,e=h)):(c=null,e=h);b!==null?a=[a,b]:(a=null,e=g)}else a=null,e=g;return a!==null&&(a=function(a,b,c){if(c.length>0){var d=[b].concat(map(c,function(a){return a[1]}));return{type:"choice",alternatives:d}}return b}(f,a[0],a[1])),a===null&&(e=f),a}function p(){var a,b,c,d;c=e,d=e,a=[],b=q();while(b!==null)a.push(b),b=q();a!==null?(b=u(),b!==null?a=[a,b]:(a=null,e=d)):(a=null,e=d),a!==null&&(a=function(a,b,c){var d=b.length!==1?{type:"sequence",elements:b}:b[0];return{type:"action",expression:d,code:c}}(c,a[0],a[1])),a===null&&(e=c);if(a===null){c=e,a=[],b=q();while(b!==null)a.push(b),b=q();a!==null&&(a=function(a,b){return b.length!==1?{type:"sequence",elements:b}:b[0]}(c,a)),a===null&&(e=c)}return a}function q(){var a,b,c,d,f;return d=e,f=e,a=K(),a!==null?(b=z(),b!==null?(c=r(),c!==null?a=[a,b,c]:(a=null,e=f)):(a=null,e=f)):(a=null,e=f),a!==null&&(a=function(a,b,c){return{type:"labeled",label:b,expression:c}}(d,a[0],a[2])),a===null&&(e=d),a===null&&(a=r()),a}function r(){var a,b,c,d;return c=e,d=e,a=C(),a!==null?(b=u(),b!==null?a=[a,b]:(a=null,e=d)):(a=null,e=d),a!==null&&(a=function(a,b){return{type:"semantic_and",code:b}}(c,a[1])),a===null&&(e=c),a===null&&(c=e,d=e,a=C(),a!==null?(b=s(),b!==null?a=[a,b]:(a=null,e=d)):(a=null,e=d),a!==null&&(a=function(a,b){return{type:"simple_and",expression:b}}(c,a[1])),a===null&&(e=c),a===null&&(c=e,d=e,a=D(),a!==null?(b=u(),b!==null?a=[a,b]:(a=null,e=d)):(a=null,e=d),a!==null&&(a=function(a,b){return{type:"semantic_not",code:b}}(c,a[1])),a===null&&(e=c),a===null&&(c=e,d=e,a=D(),a!==null?(b=s(),b!==null?a=[a,b]:(a=null,e=d)):(a=null,e=d),a!==null&&(a=function(a,b){return{type:"simple_not",expression:b}}(c,a[1])),a===null&&(e=c),a===null&&(a=s())))),a}function s(){var a,b,c,d;return c=e,d=e,a=t(),a!==null?(b=E(),b!==null?a=[a,b]:(a=null,e=d)):(a=null,e=d),a!==null&&(a=function(a,b){return{type:"optional",expression:b}}(c,a[0])),a===null&&(e=c),a===null&&(c=e,d=e,a=t(),a!==null?(b=F(),b!==null?a=[a,b]:(a=null,e=d)):(a=null,e=d),a!==null&&(a=function(a,b){return{type:"zero_or_more",expression:b}}(c,a[0])),a===null&&(e=c),a===null&&(c=e,d=e,a=t(),a!==null?(b=G(),b!==null?a=[a,b]:(a=null,e=d)):(a=null,e=d),a!==null&&(a=function(a,b){return{type:"one_or_more",expression:b}}(c,a[0])),a===null&&(e=c),a===null&&(a=t()))),a}function t(){var a,b,c,d,g,h,i;return d=e,g=e,a=K(),a!==null?(h=e,f++,i=e,b=M(),b=b!==null?b:"",b!==null?(c=y(),c!==null?b=[b,c]:(b=null,e=i)):(b=null,e=i),f--,b===null?b="":(b=null,e=h),b!==null?a=[a,b]:(a=null,e=g)):(a=null,e=g),a!==null&&(a=function(a,b){return{type:"rule_ref",name:b}}(d,a[0])),a===null&&(e=d),a===null&&(a=L(),a===null&&(d=e,a=J(),a!==null&&(a=function(a){return{type:"any"}}(d)),a===null&&(e=d),a===null&&(a=T(),a===null&&(d=e,g=e,a=H(),a!==null?(b=o(),b!==null?(c=I(),c!==null?a=[a,b,c]:(a=null,e=g)):(a=null,e=g)):(a=null,e=g),a!==null&&(a=function(a,b){return b}(d,a[1])),a===null&&(e=d))))),a}function u(){var a,b,c,d;return f++,c=e,d=e,a=v(),a!==null?(b=bg(),b!==null?a=[a,b]:(a=null,e=d)):(a=null,e=d),a!==null&&(a=function(a,b){return b.substr(1,b.length-2)}(c,a[0])),a===null&&(e=c),f--,f===0&&a===null&&k("action"),a}function v(){var a,c,d,g,h;g=e,h=e,b.charCodeAt(e)===123?(a="{",e++):(a=null,f===0&&k('"{"'));if(a!==null){c=[],d=v(),d===null&&(d=x());while(d!==null)c.push(d),d=v(),d===null&&(d=x());c!==null?(b.charCodeAt(e)===125?(d="}",e++):(d=null,f===0&&k('"}"')),d!==null?a=[a,c,d]:(a=null,e=h)):(a=null,e=h)}else a=null,e=h;return a!==null&&(a=function(a,b){return"{"+b.join("")+"}"}(g,a[1])),a===null&&(e=g),a}function w(){var a,b,c;c=e,b=x();if(b!==null){a=[];while(b!==null)a.push(b),b=x()}else a=null;return a!==null&&(a=function(a,b){return b.join("")}(c,a)),a===null&&(e=c),a}function x(){var a;return/^[^{}]/.test(b.charAt(e))?(a=b.charAt(e),e++):(a=null,f===0&&k("[^{}]")),a}function y(){var a,c,d,g;return d=e,g=e,b.charCodeAt(e)===61?(a="=",e++):(a=null,f===0&&k('"="')),a!==null?(c=bg(),c!==null?a=[a,c]:(a=null,e=g)):(a=null,e=g),a!==null&&(a=function(a){return"="}(d)),a===null&&(e=d),a}function z(){var a,c,d,g;return d=e,g=e,b.charCodeAt(e)===58?(a=":",e++):(a=null,f===0&&k('":"')),a!==null?(c=bg(),c!==null?a=[a,c]:(a=null,e=g)):(a=null,e=g),a!==null&&(a=function(a){return":"}(d)),a===null&&(e=d),a}function A(){var a,c,d,g;return d=e,g=e,b.charCodeAt(e)===59?(a=";",e++):(a=null,f===0&&k('";"')),a!==null?(c=bg(),c!==null?a=[a,c]:(a=null,e=g)):(a=null,e=g),a!==null&&(a=function(a){return";"}(d)),a===null&&(e=d),a}function B(){var a,c,d,g;return d=e,g=e,b.charCodeAt(e)===47?(a="/",e++):(a=null,f===0&&k('"/"')),a!==null?(c=bg(),c!==null?a=[a,c]:(a=null,e=g)):(a=null,e=g),a!==null&&(a=function(a){return"/"}(d)),a===null&&(e=d),a}function C(){var a,c,d,g;return d=e,g=e,b.charCodeAt(e)===38?(a="&",e++):(a=null,f===0&&k('"&"')),a!==null?(c=bg(),c!==null?a=[a,c]:(a=null,e=g)):(a=null,e=g),a!==null&&(a=function(a){return"&"}(d)),a===null&&(e=d),a}function D(){var a,c,d,g;return d=e,g=e,b.charCodeAt(e)===33?(a="!",e++):(a=null,f===0&&k('"!"')),a!==null?(c=bg(),c!==null?a=[a,c]:(a=null,e=g)):(a=null,e=g),a!==null&&(a=function(a){return"!"}(d)),a===null&&(e=d),a}function E(){var a,c,d,g;return d=e,g=e,b.charCodeAt(e)===63?(a="?",e++):(a=null,f===0&&k('"?"')),a!==null?(c=bg(),c!==null?a=[a,c]:(a=null,e=g)):(a=null,e=g),a!==null&&(a=function(a){return"?"}(d)),a===null&&(e=d),a}function F(){var a,c,d,g;return d=e,g=e,b.charCodeAt(e)===42?(a="*",e++):(a=null,f===0&&k('"*"')),a!==null?(c=bg(),c!==null?a=[a,c]:(a=null,e=g)):(a=null,e=g),a!==null&&(a=function(a){return"*"}(d)),a===null&&(e=d),a}function G(){var a,c,d,g;return d=e,g=e,b.charCodeAt(e)===43?(a="+",e++):(a=null,f===0&&k('"+"')),a!==null?(c=bg(),c!==null?a=[a,c]:(a=null,e=g)):(a=null,e=g),a!==null&&(a=function(a){return"+"}(d)),a===null&&(e=d),a}function H(){var a,c,d,g;return d=e,g=e,b.charCodeAt(e)===40?(a="(",e++):(a=null,f===0&&k('"("')),a!==null?(c=bg(),c!==null?a=[a,c]:(a=null,e=g)):(a=null,e=g),a!==null&&(a=function(a){return"("}(d)),a===null&&(e=d),a}function I(){var a,c,d,g;return d=e,g=e,b.charCodeAt(e)===41?(a=")",e++):(a=null,f===0&&k('")"')),a!==null?(c=bg(),c!==null?a=[a,c]:(a=null,e=g)):(a=null,e=g),a!==null&&(a=function(a){return")"}(d)),a===null&&(e=d),a}function J(){var a,c,d,g;return d=e,g=e,b.charCodeAt(e)===46?(a=".",e++):(a=null,f===0&&k('"."')),a!==null?(c=bg(),c!==null?a=[a,c]:(a=null,e=g)):(a=null,e=g),a!==null&&(a=function(a){return"."}(d)),a===null&&(e=d),a}function K(){var a,c,d,g,h;f++,g=e,h=e,a=bd(),a===null&&(b.charCodeAt(e)===95?(a="_",e++):(a=null,f===0&&k('"_"')),a===null&&(b.charCodeAt(e)===36?(a="$",e++):(a=null,f===0&&k('"$"'))));if(a!==null){c=[],d=bd(),d===null&&(d=bb(),d===null&&(b.charCodeAt(e)===95?(d="_",e++):(d=null,f===0&&k('"_"')),d===null&&(b.charCodeAt(e)===36?(d="$",e++):(d=null,f===0&&k('"$"')))));while(d!==null)c.push(d),d=bd(),d===null&&(d=bb(),d===null&&(b.charCodeAt(e)===95?(d="_",e++):(d=null,f===0&&k('"_"')),d===null&&(b.charCodeAt(e)===36?(d="$",e++):(d=null,f===0&&k('"$"')))));c!==null?(d=bg(),d!==null?a=[a,c,d]:(a=null,e=h)):(a=null,e=h)}else a=null,e=h;return a!==null&&(a=function(a,b,c){return b+c.join("")}(g,a[0],a[1])),a===null&&(e=g),f--,f===0&&a===null&&k("identifier"),a}function L(){var a,c,d,g,h;return f++,g=e,h=e,a=N(),a===null&&(a=Q()),a!==null?(b.charCodeAt(e)===105?(c="i",e++):(c=null,f===0&&k('"i"')),c=c!==null?c:"",c!==null?(d=bg(),d!==null?a=[a,c,d]:(a=null,e=h)):(a=null,e=h)):(a=null,e=h),a!==null&&(a=function(a,b,c){return{type:"literal",value:b,ignoreCase:c==="i"}}(g,a[0],a[1])),a===null&&(e=g),f--,f===0&&a===null&&k("literal"),a}function M(){var a,b,c,d;return f++,c=e,d=e,a=N(),a===null&&(a=Q()),a!==null?(b=bg(),b!==null?a=[a,b]:(a=null,e=d)):(a=null,e=d),a!==null&&(a=function(a,b){return b}(c,a[0])),a===null&&(e=c),f--,f===0&&a===null&&k("string"),a}function N(){var a,c,d,g,h;g=e,h=e,b.charCodeAt(e)===34?(a='"',e++):(a=null,f===0&&k('"\\""'));if(a!==null){c=[],d=O();while(d!==null)c.push(d),d=O();c!==null?(b.charCodeAt(e)===34?(d='"',e++):(d=null,f===0&&k('"\\""')),d!==null?a=[a,c,d]:(a=null,e=h)):(a=null,e=h)}else a=null,e=h;return a!==null&&(a=function(a,b){return b.join("")}(g,a[1])),a===null&&(e=g),a}function O(){var a;return a=P(),a===null&&(a=Y(),a===null&&(a=Z(),a===null&&(a=$(),a===null&&(a=_(),a===null&&(a=ba()))))),a}function P(){var a,c,d,g,h;return d=e,g=e,h=e,f++,b.charCodeAt(e)===34?(a='"',e++):(a=null,f===0&&k('"\\""')),a===null&&(b.charCodeAt(e)===92?(a="\\",e++):(a=null,f===0&&k('"\\\\"')),a===null&&(a=bl())),f--,a===null?a="":(a=null,e=h),a!==null?(b.length>e?(c=b.charAt(e),e++):(c=null,f===0&&k("any character")),c!==null?a=[a,c]:(a=null,e=g)):(a=null,e=g),a!==null&&(a=function(a,b){return b}(d,a[1])),a===null&&(e=d),a}function Q(){var a,c,d,g,h;g=e,h=e,b.charCodeAt(e)===39?(a="'",e++):(a=null,f===0&&k('"\'"'));if(a!==null){c=[],d=R();while(d!==null)c.push(d),d=R();c!==null?(b.charCodeAt(e)===39?(d="'",e++):(d=null,f===0&&k('"\'"')),d!==null?a=[a,c,d]:(a=null,e=h)):(a=null,e=h)}else a=null,e=h;return a!==null&&(a=function(a,b){return b.join("")}(g,a[1])),a===null&&(e=g),a}function R(){var a;return a=S(),a===null&&(a=Y(),a===null&&(a=Z(),a===null&&(a=$(),a===null&&(a=_(),a===null&&(a=ba()))))),a}function S(){var a,c,d,g,h;return d=e,g=e,h=e,f++,b.charCodeAt(e)===39?(a="'",e++):(a=null,f===0&&k('"\'"')),a===null&&(b.charCodeAt(e)===92?(a="\\",e++):(a=null,f===0&&k('"\\\\"')),a===null&&(a=bl())),f--,a===null?a="":(a=null,e=h),a!==null?(b.length>e?(c=b.charAt(e),e++):(c=null,f===0&&k("any character")),c!==null?a=[a,c]:(a=null,e=g)):(a=null,e=g),a!==null&&(a=function(a,b){return b}(d,a[1])),a===null&&(e=d),a}function T(){var a,c,d,g,h,i,j,l;f++,j=e,l=e,b.charCodeAt(e)===91?(a="[",e++):(a=null,f===0&&k('"["'));if(a!==null){b.charCodeAt(e)===94?(c="^",e++):(c=null,f===0&&k('"^"')),c=c!==null?c:"";if(c!==null){d=[],g=U(),g===null&&(g=V());while(g!==null)d.push(g),g=U(),g===null&&(g=V());d!==null?(b.charCodeAt(e)===93?(g="]",e++):(g=null,f===0&&k('"]"')),g!==null?(b.charCodeAt(e)===105?(h="i",e++):(h=null,f===0&&k('"i"')),h=h!==null?h:"",h!==null?(i=bg(),i!==null?a=[a,c,d,g,h,i]:(a=null,e=l)):(a=null,e=l)):(a=null,e=l)):(a=null,e=l)}else a=null,e=l}else a=null,e=l;return a!==null&&(a=function(a,b,c,d){var e=map(c,function(a){return a.data}),f="["+b+map(c,function(a){return a.rawText}).join("")+"]"+d;return{type:"class",inverted:b==="^",ignoreCase:d==="i",parts:e,rawText:f}}(j,a[1],a[2],a[4])),a===null&&(e=j),f--,f===0&&a===null&&k("character class"),a}function U(){var a,c,d,g,h;return g=e,h=e,a=V(),a!==null?(b.charCodeAt(e)===45?(c="-",e++):(c=null,f===0&&k('"-"')),c!==null?(d=V(),d!==null?a=[a,c,d]:(a=null,e=h)):(a=null,e=h)):(a=null,e=h),a!==null&&(a=function(a,b,c){if(b.data.charCodeAt(0)>c.data.charCodeAt(0))throw new this.SyntaxError("Invalid character range: "+b.rawText+"-"+c.rawText+".");return{data:[b.data,c.data],rawText:b.rawText+"-"+c.rawText}}(g,a[0],a[2])),a===null&&(e=g),a}function V(){var a,b;return b=e,a=W(),a!==null&&(a=function(a,b){return{data:b,rawText:quoteForRegexpClass(b)}}(b,a)),a===null&&(e=b),a}function W(){var a;return a=X(),a===null&&(a=Y(),a===null&&(a=Z(),a===null&&(a=$(),a===null&&(a=_(),a===null&&(a=ba()))))),a}function X(){var a,c,d,g,h;return d=e,g=e,h=e,f++,b.charCodeAt(e)===93?(a="]",e++):(a=null,f===0&&k('"]"')),a===null&&(b.charCodeAt(e)===92?(a="\\",e++):(a=null,f===0&&k('"\\\\"')),a===null&&(a=bl())),f--,a===null?a="":(a=null,e=h),a!==null?(b.length>e?(c=b.charAt(e),e++):(c=null,f===0&&k("any character")),c!==null?a=[a,c]:(a=null,e=g)):(a=null,e=g),a!==null&&(a=function(a,b){return b}(d,a[1])),a===null&&(e=d),a}function Y(){var a,c,d,g,h,i;return g=e,h=e,b.charCodeAt(e)===92?(a="\\",e++):(a=null,f===0&&k('"\\\\"')),a!==null?(i=e,f++,c=bb(),c===null&&(b.charCodeAt(e)===120?(c="x",e++):(c=null,f===0&&k('"x"')),c===null&&(b.charCodeAt(e)===117?(c="u",e++):(c=null,f===0&&k('"u"')),c===null&&(c=bl()))),f--,c===null?c="":(c=null,e=i),c!==null?(b.length>e?(d=b.charAt(e),e++):(d=null,f===0&&k("any character")),d!==null?a=[a,c,d]:(a=null,e=h)):(a=null,e=h)):(a=null,e=h),a!==null&&(a=function(a,b){return b.replace("b","\b").replace("f","\f").replace("n","\n").replace("r","\r").replace("t","\t").replace("v"," ")}(g,a[2])),a===null&&(e=g),a}function Z(){var a,c,d,g,h;return d=e,g=e,b.substr(e,2)==="\\0"?(a="\\0",e+=2):(a=null,f===0&&k('"\\\\0"')),a!==null?(h=e,f++,c=bb(),f--,c===null?c="":(c=null,e=h),c!==null?a=[a,c]:(a=null,e=g)):(a=null,e=g),a!==null&&(a=function(a){return"\0"}(d)),a===null&&(e=d),a}function $(){var a,c,d,g,h;return g=e,h=e,b.substr(e,2)==="\\x"?(a="\\x",e+=2):(a=null,f===0&&k('"\\\\x"')),a!==null?(c=bc(),c!==null?(d=bc(),d!==null?a=[a,c,d]:(a=null,e=h)):(a=null,e=h)):(a=null,e=h),a!==null&&(a=function(a,b,c){return String.fromCharCode(parseInt(b+c,16))}(g,a[1],a[2])),a===null&&(e=g),a}function _(){var a,c,d,g,h,i,j;return i=e,j=e,b.substr(e,2)==="\\u"?(a="\\u",e+=2):(a=null,f===0&&k('"\\\\u"')),a!==null?(c=bc(),c!==null?(d=bc(),d!==null?(g=bc(),g!==null?(h=bc(),h!==null?a=[a,c,d,g,h]:(a=null,e=j)):(a=null,e=j)):(a=null,e=j)):(a=null,e=j)):(a=null,e=j),a!==null&&(a=function(a,b,c,d,e){return String.fromCharCode(parseInt(b+c+d+e,16))}(i,a[1],a[2],a[3],a[4])),a===null&&(e=i),a}function ba(){var a,c,d,g;return d=e,g=e,b.charCodeAt(e)===92?(a="\\",e++):(a=null,f===0&&k('"\\\\"')),a!==null?(c=bk(),c!==null?a=[a,c]:(a=null,e=g)):(a=null,e=g),a!==null&&(a=function(a,b){return b}(d,a[1])),a===null&&(e=d),a}function bb(){var a;return/^[0-9]/.test(b.charAt(e))?(a=b.charAt(e),e++):(a=null,f===0&&k("[0-9]")),a}function bc(){var a;return/^[0-9a-fA-F]/.test(b.charAt(e))?(a=b.charAt(e),e++):(a=null,f===0&&k("[0-9a-fA-F]")),a}function bd(){var a;return a=be(),a===null&&(a=bf()),a}function be(){var a;return/^[a-z]/.test(b.charAt(e))?(a=b.charAt(e),e++):(a=null,f===0&&k("[a-z]")),a}function bf(){var a;return/^[A-Z]/.test(b.charAt(e))?(a=b.charAt(e),e++):(a=null,f===0&&k("[A-Z]")),a}function bg(){var a,b;a=[],b=bm(),b===null&&(b=bk(),b===null&&(b=bh()));while(b!==null)a.push(b),b=bm(),b===null&&(b=bk(),b===null&&(b=bh()));return a}function bh(){var a;return f++,a=bi(),a===null&&(a=bj()),f--,f===0&&a===null&&k("comment"),a}function bi(){var a,c,d,g,h,i,j;h=e,b.substr(e,2)==="//"?(a="//",e+=2):(a=null,f===0&&k('"//"'));if(a!==null){c=[],i=e,j=e,f++,d=bl(),f--,d===null?d="":(d=null,e=j),d!==null?(b.length>e?(g=b.charAt(e),e++):(g=null,f===0&&k("any character")),g!==null?d=[d,g]:(d=null,e=i)):(d=null,e=i);while(d!==null)c.push(d),i=e,j=e,f++,d=bl(),f--,d===null?d="":(d=null,e=j),d!==null?(b.length>e?(g=b.charAt(e),e++):(g=null,f===0&&k("any character")),g!==null?d=[d,g]:(d=null,e=i)):(d=null,e=i);c!==null?a=[a,c]:(a=null,e=h)}else a=null,e=h;return a}function bj(){var a,c,d,g,h,i,j;h=e,b.substr(e,2)==="/*"?(a="/*",e+=2):(a=null,f===0&&k('"/*"'));if(a!==null){c=[],i=e,j=e,f++,b.substr(e,2)==="*/"?(d="*/",e+=2):(d=null,f===0&&k('"*/"')),f--,d===null?d="":(d=null,e=j),d!==null?(b.length>e?(g=b.charAt(e),e++):(g=null,f===0&&k("any character")),g!==null?d=[d,g]:(d=null,e=i)):(d=null,e=i);while(d!==null)c.push(d),i=e,j=e,f++,b.substr(e,2)==="*/"?(d="*/",e+=2):(d=null,f===0&&k('"*/"')),f--,d===null?d="":(d=null,e=j),d!==null?(b.length>e?(g=b.charAt(e),e++):(g=null,f===0&&k("any character")),g!==null?d=[d,g]:(d=null,e=i)):(d=null,e=i);c!==null?(b.substr(e,2)==="*/"?(d="*/",e+=2):(d=null,f===0&&k('"*/"')),d!==null?a=[a,c,d]:(a=null,e=h)):(a=null,e=h)}else a=null,e=h;return a}function bk(){var a;return f++,b.charCodeAt(e)===10?(a="\n",e++):(a=null,f===0&&k('"\\n"')),a===null&&(b.substr(e,2)==="\r\n"?(a="\r\n",e+=2):(a=null,f===0&&k('"\\r\\n"')),a===null&&(b.charCodeAt(e)===13?(a="\r",e++):(a=null,f===0&&k('"\\r"')),a===null&&(b.charCodeAt(e)===8232?(a="\u2028",e++):(a=null,f===0&&k('"\\u2028"')),a===null&&(b.charCodeAt(e)===8233?(a="\u2029",e++):(a=null,f===0&&k('"\\u2029"')))))),f--,f===0&&a===null&&k("end of line"),a}function bl(){var a;return/^[\n\r\u2028\u2029]/.test(b.charAt(e))?(a=b.charAt(e),e++):(a=null,f===0&&k("[\\n\\r\\u2028\\u2029]")),a}function bm(){var a;return f++,/^[ \t\x0B\f\xA0\uFEFF\u1680\u180E\u2000-\u200A\u202F\u205F\u3000]/.test(b.charAt(e))?(a=b.charAt(e),e++):(a=null,f===0&&k("[ \\t\\x0B\\f\\xA0\\uFEFF\\u1680\\u180E\\u2000-\\u200A\\u202F\\u205F\\u3000]")),f--,f===0&&a===null&&k("whitespace"),a}function bn(a){a.sort();var b=null,c=[];for(var d=0;d0&&e(a.elements[0],b)},labeled:c,simple_and:c,simple_not:c,semantic_and:b,semantic_not:b,optional:c,zero_or_more:c,one_or_more:c,action:c,rule_ref:function(b,c){if(contains(c,b.name))throw new PEG.GrammarError('Left recursion detected for rule "'+b.name+'".');e(findRuleByName(a,b.name),c)},literal:b,any:b,"class":b});e(a,[])},removeProxyRules:function(a){function b(a){return a.type==="rule"&&a.expression.type==="rule_ref"}function c(a,b,c){function d(){}function e(a,b,c){g(a.expression,b,c)}function f(a){return function(b,c,d){each(b[a],function(a){g(a,c,d)})}}var g=buildNodeVisitor({grammar:f("rules"),rule:e,choice:f("alternatives"),sequence:f("elements"),labeled:e,simple_and:e,simple_not:e,semantic_and:d,semantic_not:d,optional:e,zero_or_more:e,one_or_more:e,action:e,rule_ref:function(a,b,c){a.name===b&&(a.name=c)},literal:d,any:d,"class":d});g(a,b,c)}var d=[];each(a.rules,function(e,f){b(e)&&(c(a,e.name,e.expression.name),e.name===a.startRule&&(a.startRule=e.expression.name),d.push(f))}),d.reverse(),each(d,function(b){a.rules.splice(b,1)})},computeVarNames:function(a){function b(a){return"result"+a}function c(a){return"pos"+a}function d(a,c){return a.resultVar=b(c.result),{result:0,pos:0}}function e(a){return function(d,e){var g=f(d.expression,{result:e.result+a.result,pos:e.pos+a.pos});return d.resultVar=b(e.result),a.pos!==0&&(d.posVar=c(e.pos)),{result:g.result+a.result,pos:g.pos+a.pos}}}var f=buildNodeVisitor({grammar:function(a,b){each(a.rules,function(a){f(a,b)})},rule:function(a,d){var e=f(a.expression,d);a.resultVar=b(d.result),a.resultVars=map(range(e.result+1),b),a.posVars=map(range(e.pos),c)},choice:function(a,c){var d=map(a.alternatives,function(a){return f(a,c)});return a.resultVar=b(c.result),{result:Math.max.apply(null,pluck(d,"result")),pos:Math.max.apply(null,pluck(d,"pos"))}},sequence:function(a,d){var e=map(a.elements,function(a,b){return f(a,{result:d.result+b,pos:d.pos+1})});return a.resultVar=b(d.result),a.posVar=c(d.pos),{result:a.elements.length>0?Math.max.apply(null,map(e,function(a,b){return b+a.result})):0,pos:a.elements.length>0?1+Math.max.apply(null,pluck(e,"pos")):1}},labeled:e({result:0,pos:0}),simple_and:e({result:0,pos:1}),simple_not:e({result:0,pos:1}),semantic_and:d,semantic_not:d,optional:e({result:0,pos:0}),zero_or_more:e({result:1,pos:0}),one_or_more:e({result:1,pos:0}),action:e({result:0,pos:1}),rule_ref:d,literal:d,any:d,"class":d});f(a,{result:0,pos:0})},computeParams:function(a){function c(a){b.push({}),a(),b.pop()}function d(){}function e(a){c(function(){g(a.expression)})}function f(a){var c=b[b.length-1],d={},e;for(e in c)d[e]=c[e];a.params=d}var b=[],g=buildNodeVisitor({grammar:function(a){each(a.rules,g)},rule:e,choice:function(a){c(function(){each(a.alternatives,g)})},sequence:function(a){function e(b){each(pluck(a.elements,"resultVar"),function(d,e){(new RegExp("^"+d+"(\\[\\d+\\])*$")).test(c[b])&&(c[b]=a.resultVar+"["+e+"]"+c[b].substr(d.length))})}var c=b[b.length-1],d;each(a.elements,g);for(d in c)e(d)},labeled:function(a){b[b.length-1][a.label]=a.resultVar,c(function(){g(a.expression)})},simple_and:e,simple_not:e,semantic_and:f,semantic_not:f,optional:e,zero_or_more:e,one_or_more:e,action:function(a){c(function(){g(a.expression),f(a)})},rule_ref:d,literal:d,any:d,"class":d});g(a)}},PEG.compiler.emitter=function(a,b){function e(a,c){return c.string=quote,c.pluck=pluck,c.keys=keys,c.values=values,c.emit=g,c.options=b,b.trackLineAndColumn?(c.posInit=function(a){return"var "+a+" = "+"{ offset: 0, line: 1, column: 1, seenCR: false }"},c.posClone=function(a){return"clone("+a+")"},c.posOffset=function(a){return a+".offset"},c.posAdvance=function(a){return"advance(pos, "+a+")"}):(c.posInit=function(a){return"var "+a+" = 0"},c.posClone=function(a){return a},c.posOffset=function(a){return a},c.posAdvance=function(a){return a===1?"pos++":"pos += "+a}),c.posSave=function(a){return a.posVar+" = "+c.posClone("pos")},c.posRestore=function(a){return"pos = "+c.posClone(a.posVar)},d[a](c)}function f(a){return function(b){return e(a,{node:b})}}b=b||{},b.cache===undefined&&(b.cache=!1),b.trackLineAndColumn===undefined&&(b.trackLineAndColumn=!1);var c=function(a){function b(a){function b(a){return a.charCodeAt(0).toString(16).toUpperCase()}return a.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\x08/g,"\\b").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\f/g,"\\f").replace(/\r/g,"\\r").replace(/[\x00-\x07\x0B\x0E\x0F]/g,function(a){return"\\x0"+b(a)}).replace(/[\x10-\x1F\x80-\xFF]/g,function(a){return"\\x"+b(a)}).replace(/[\u0180-\u0FFF]/g,function(a){return"\\u0"+b(a)}).replace(/[\u1080-\uFFFF]/g,function(a){return"\\u"+b(a)})}function c(a){return"__p.push("+a+");"}function d(a,d,e){function f(a,b,c){return a.replace(new RegExp("^.{"+b+"}","gm"),function(a,b){return b===0?c?"":a:""})}var g=b(f(a.substring(0,d),e.indentLevel(),e.atBOL));return g.length>0?c('"'+g+'"'):""}var e={VERSION:"1.1.0",indentStep:2,commands:{"if":{params:/^(.*)$/,compile:function(a,b,c){return["if("+c[0]+"){",[]]},stackOp:"push"},"else":{params:/^$/,compile:function(a){var b=a.commandStack,c=b[b.length-1]==="else",d=b[b.length-1]==="if";if(c)throw new Error("Multiple #elses.");if(!d)throw new Error("Using #else outside of #if.");return["}else{",[]]},stackOp:"replace"},"for":{params:/^([a-zA-Z_][a-zA-Z0-9_]*)[ \t]+in[ \t]+(.*)$/,init:function(a){a.forCurrLevel=0,a.forMaxLevel=0},compile:function(a,b,c){var d="__c"+a.forCurrLevel,e="__l"+a.forCurrLevel,f="__i"+a.forCurrLevel;return a.forCurrLevel++,a.forMaxLevel0)throw new Error("Missing #end.");k.sort();for(o=0;o #{posOffset("rightmostFailuresPos")}) {',' rightmostFailuresPos = #{posClone("pos")};'," rightmostFailuresExpected = [];"," }"," "," rightmostFailuresExpected.push(failure);"," }"," "," #for rule in node.rules"," #block emit(rule)"," "," #end"," "," function cleanupExpected(expected) {"," expected.sort();"," "," var lastExpected = null;"," var cleanExpected = [];"," for (var i = 0; i < expected.length; i++) {"," if (expected[i] !== lastExpected) {"," cleanExpected.push(expected[i]);"," lastExpected = expected[i];"," }"," }"," return cleanExpected;"," }"," "," #if !options.trackLineAndColumn"," function computeErrorPosition() {"," /*"," * The first idea was to use |String.split| to break the input up to the"," * error position along newlines and derive the line and column from"," * there. However IE's |split| implementation is so broken that it was"," * enough to prevent it."," */"," "," var line = 1;"," var column = 1;"," var seenCR = false;"," "," for (var i = 0; i < Math.max(pos, rightmostFailuresPos); i++) {"," var ch = input.charAt(i);",' if (ch === "\\n") {'," if (!seenCR) { line++; }"," column = 1;"," seenCR = false;",' } else if (ch === "\\r" || ch === "\\u2028" || ch === "\\u2029") {'," line++;"," column = 1;"," seenCR = true;"," } else {"," column++;"," seenCR = false;"," }"," }"," "," return { line: line, column: column };"," }"," #end"," "," #if node.initializer"," #block emit(node.initializer)"," #end"," "," var result = parseFunctions[startRule]();"," "," /*"," * The parser is now in one of the following three states:"," *"," * 1. The parser successfully parsed the whole input."," *"," * - |result !== null|",' * - |#{posOffset("pos")} === input.length|'," * - |rightmostFailuresExpected| may or may not contain something"," *"," * 2. The parser successfully parsed only a part of the input."," *"," * - |result !== null|",' * - |#{posOffset("pos")} < input.length|'," * - |rightmostFailuresExpected| may or may not contain something"," *"," * 3. The parser did not successfully parse any part of the input."," *"," * - |result === null|",' * - |#{posOffset("pos")} === 0|'," * - |rightmostFailuresExpected| contains at least one failure"," *"," * All code following this comment (including called functions) must"," * handle these states."," */",' if (result === null || #{posOffset("pos")} !== input.length) {',' var offset = Math.max(#{posOffset("pos")}, #{posOffset("rightmostFailuresPos")});'," var found = offset < input.length ? input.charAt(offset) : null;"," #if options.trackLineAndColumn",' var errorPosition = #{posOffset("pos")} > #{posOffset("rightmostFailuresPos")} ? pos : rightmostFailuresPos;'," #else"," var errorPosition = computeErrorPosition();"," #end"," "," throw new this.SyntaxError("," cleanupExpected(rightmostFailuresExpected),"," found,"," offset,"," errorPosition.line,"," errorPosition.column"," );"," }"," "," return result;"," },"," "," /* Returns the parser source code. */"," toSource: function() { return this._source; }"," };"," "," /* Thrown when a parser encounters a syntax error. */"," "," result.SyntaxError = function(expected, found, offset, line, column) {"," function buildMessage(expected, found) {"," var expectedHumanized, foundHumanized;"," "," switch (expected.length) {"," case 0:",' expectedHumanized = "end of input";'," break;"," case 1:"," expectedHumanized = expected[0];"," break;"," default:",' expectedHumanized = expected.slice(0, expected.length - 1).join(", ")',' + " or "'," + expected[expected.length - 1];"," }"," ",' foundHumanized = found ? quote(found) : "end of input";'," ",' return "Expected " + expectedHumanized + " but " + foundHumanized + " found.";'," }"," ",' this.name = "SyntaxError";'," this.expected = expected;"," this.found = found;"," this.message = buildMessage(expected, found);"," this.offset = offset;"," this.line = line;"," this.column = column;"," };"," "," result.SyntaxError.prototype = Error.prototype;"," "," return result;","})()"],rule:["function parse_#{node.name}() {"," #if options.cache",' var cacheKey = "#{node.name}@" + #{posOffset("pos")};'," var cachedResult = cache[cacheKey];"," if (cachedResult) {",' pos = #{posClone("cachedResult.nextPos")};'," return cachedResult.result;"," }"," "," #end"," #if node.resultVars.length > 0",' var #{node.resultVars.join(", ")};'," #end"," #if node.posVars.length > 0",' var #{node.posVars.join(", ")};'," #end"," "," #if node.displayName !== null"," reportFailures++;"," #end"," #block emit(node.expression)"," #if node.displayName !== null"," reportFailures--;"," if (reportFailures === 0 && #{node.resultVar} === null) {"," matchFailed(#{string(node.displayName)});"," }"," #end"," #if options.cache"," "," cache[cacheKey] = {",' nextPos: #{posClone("pos")},'," result: #{node.resultVar}"," };"," #end"," return #{node.resultVar};","}"],choice:["#block emit(alternative)","#block nextAlternativesCode"],"choice.next":["if (#{node.resultVar} === null) {"," #block code","}"],sequence:["#{posSave(node)};","#block code"],"sequence.iteration":["#block emit(element)","if (#{element.resultVar} !== null) {"," #block code","} else {"," #{node.resultVar} = null;"," #{posRestore(node)};","}"],"sequence.inner":['#{node.resultVar} = [#{pluck(node.elements, "resultVar").join(", ")}];'],simple_and:["#{posSave(node)};","reportFailures++;","#block emit(node.expression)","reportFailures--;","if (#{node.resultVar} !== null) {",' #{node.resultVar} = "";'," #{posRestore(node)};","} else {"," #{node.resultVar} = null;","}"],simple_not:["#{posSave(node)};","reportFailures++;","#block emit(node.expression)","reportFailures--;","if (#{node.resultVar} === null) {",' #{node.resultVar} = "";',"} else {"," #{node.resultVar} = null;"," #{posRestore(node)};","}"],semantic_and:['#{node.resultVar} = (function(#{(options.trackLineAndColumn ? ["offset", "line", "column"] : ["offset"]).concat(keys(node.params)).join(", ")}) {#{node.code}})(#{(options.trackLineAndColumn ? ["pos.offset", "pos.line", "pos.column"] : ["pos"]).concat(values(node.params)).join(", ")}) ? "" : null;'],semantic_not:['#{node.resultVar} = (function(#{(options.trackLineAndColumn ? ["offset", "line", "column"] : ["offset"]).concat(keys(node.params)).join(", ")}) {#{node.code}})(#{(options.trackLineAndColumn ? ["pos.offset", "pos.line", "pos.column"] : ["pos"]).concat(values(node.params)).join(", ")}) ? null : "";'],optional:["#block emit(node.expression)",'#{node.resultVar} = #{node.resultVar} !== null ? #{node.resultVar} : "";'],zero_or_more:["#{node.resultVar} = [];","#block emit(node.expression)","while (#{node.expression.resultVar} !== null) {"," #{node.resultVar}.push(#{node.expression.resultVar});"," #block emit(node.expression)","}"],one_or_more:["#block emit(node.expression)","if (#{node.expression.resultVar} !== null) {"," #{node.resultVar} = [];"," while (#{node.expression.resultVar} !== null) {"," #{node.resultVar}.push(#{node.expression.resultVar});"," #block emit(node.expression)"," }","} else {"," #{node.resultVar} = null;","}"],action:["#{posSave(node)};","#block emit(node.expression)","if (#{node.resultVar} !== null) {",' #{node.resultVar} = (function(#{(options.trackLineAndColumn ? ["offset", "line", "column"] : ["offset"]).concat(keys(node.params)).join(", ")}) {#{node.code}})(#{(options.trackLineAndColumn ? [node.posVar + ".offset", node.posVar + ".line", node.posVar + ".column"] : [node.posVar]).concat(values(node.params)).join(", ")});',"}","if (#{node.resultVar} === null) {"," #{posRestore(node)};","}"],rule_ref:["#{node.resultVar} = parse_#{node.name}();"],literal:["#if node.value.length === 0",' #{node.resultVar} = "";',"#else"," #if !node.ignoreCase"," #if node.value.length === 1",' if (input.charCodeAt(#{posOffset("pos")}) === #{node.value.charCodeAt(0)}) {'," #else",' if (input.substr(#{posOffset("pos")}, #{node.value.length}) === #{string(node.value)}) {'," #end"," #else",' if (input.substr(#{posOffset("pos")}, #{node.value.length}).toLowerCase() === #{string(node.value.toLowerCase())}) {'," #end"," #if !node.ignoreCase"," #{node.resultVar} = #{string(node.value)};"," #else",' #{node.resultVar} = input.substr(#{posOffset("pos")}, #{node.value.length});'," #end"," #{posAdvance(node.value.length)};"," } else {"," #{node.resultVar} = null;"," if (reportFailures === 0) {"," matchFailed(#{string(string(node.value))});"," }"," }","#end"],any:['if (input.length > #{posOffset("pos")}) {',' #{node.resultVar} = input.charAt(#{posOffset("pos")});'," #{posAdvance(1)};","} else {"," #{node.resultVar} = null;"," if (reportFailures === 0) {",' matchFailed("any character");'," }","}"],"class":['if (#{regexp}.test(input.charAt(#{posOffset("pos")}))) {',' #{node.resultVar} = input.charAt(#{posOffset("pos")});'," #{posAdvance(1)};","} else {"," #{node.resultVar} = null;"," if (reportFailures === 0) {"," matchFailed(#{string(node.rawText)});"," }","}"]};for(a in d)b[a]=c.template(d[a].join("\n"));return b}(),g=buildNodeVisitor({grammar:f("grammar"),initializer:function(a){return a.code},rule:f("rule"),choice:function(a){var b,c;for(var d=a.alternatives.length-1;d>=0;d--)c=d!==a.alternatives.length-1?e("choice.next",{node:a,code:b}):"",b=e("choice",{alternative:a.alternatives[d],nextAlternativesCode:c});return b},sequence:function(a){var b=e("sequence.inner",{node:a});for(var c=a.elements.length-1;c>=0;c--)b=e("sequence.iteration",{node:a,element:a.elements[c],code:b});return e("sequence",{node:a,code:b})},labeled:function(a){return g(a.expression)},simple_and:f("simple_and"),simple_not:f("simple_not"),semantic_and:f("semantic_and"),semantic_not:f("semantic_not"),optional:f("optional"),zero_or_more:f("zero_or_more"),one_or_more:f("one_or_more"),action:f("action"),rule_ref:f("rule_ref"),literal:f("literal"),any:f("any"),"class":function(a){var b;return a.parts.length>0?b="/^["+(a.inverted?"^":"")+map(a.parts,function(a){return a instanceof Array?quoteForRegexpClass(a[0])+"-"+quoteForRegexpClass(a[1]):quoteForRegexpClass(a)}).join("")+"]/"+(a.ignoreCase?"i":""):b=a.inverted?"/^[\\S\\s]/":"/^(?!)/",e("class",{node:a,regexp:b})}});return g(a)},PEG}();typeof module!="undefined"&&(module.exports=PEG); \ No newline at end of file diff --git a/ajax/libs/pegjs/package.json b/ajax/libs/pegjs/package.json new file mode 100644 index 000000000..5e685f311 --- /dev/null +++ b/ajax/libs/pegjs/package.json @@ -0,0 +1,25 @@ +{ + "name": "pegjs", + "filename": "peg.min.js", + "version": "0.7.0", + "description": "Parser generator for JavaScript", + "homepage": "http://pegjs.majda.cz/", + "keywords": [ + "parser", + "generator", + "peg" + ], + "maintainers": [ + { + "name": "David Majda", + "web": "http://majda.cz" + } + ], + "repositories": [ + { + "type": "git", + "url": "https://github.com/dmajda/pegjs" + } + ] + +} From 180b9f1a36dd9626ac54e1b33639d97f6e15134d Mon Sep 17 00:00:00 2001 From: Andreas Savvides Date: Mon, 14 Oct 2013 17:44:51 +0100 Subject: [PATCH 13/26] Adding pace.js --- ajax/libs/pace/0.4.15/pace.js | 752 ++++++++++++++++++++++++++++++ ajax/libs/pace/0.4.15/pace.min.js | 2 + ajax/libs/pace/package.json | 18 + 3 files changed, 772 insertions(+) create mode 100644 ajax/libs/pace/0.4.15/pace.js create mode 100644 ajax/libs/pace/0.4.15/pace.min.js create mode 100644 ajax/libs/pace/package.json diff --git a/ajax/libs/pace/0.4.15/pace.js b/ajax/libs/pace/0.4.15/pace.js new file mode 100644 index 000000000..c09d9543e --- /dev/null +++ b/ajax/libs/pace/0.4.15/pace.js @@ -0,0 +1,752 @@ +(function() { + var AjaxMonitor, Bar, DocumentMonitor, ElementMonitor, ElementTracker, EventLagMonitor, Events, NoTargetError, RequestIntercept, SOURCE_KEYS, Scaler, SocketRequestTracker, XHRRequestTracker, animation, avgAmplitude, bar, cancelAnimation, cancelAnimationFrame, defaultOptions, extend, extendNative, getFromDOM, getIntercept, handlePushState, init, now, options, requestAnimationFrame, result, runAnimation, scalers, sources, uniScaler, _WebSocket, _XDomainRequest, _XMLHttpRequest, _intercept, _pushState, _ref, _replaceState, + __slice = [].slice, + __hasProp = {}.hasOwnProperty, + __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, + __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; + + defaultOptions = { + catchupTime: 500, + initialRate: .03, + minTime: 500, + ghostTime: 250, + maxProgressPerFrame: 10, + easeFactor: 1.25, + startOnPageLoad: true, + restartOnPushState: true, + restartOnRequestAfter: 500, + target: 'body', + elements: { + checkInterval: 100, + selectors: ['body'] + }, + eventLag: { + minSamples: 10, + sampleCount: 3, + lagThreshold: 3 + }, + ajax: { + trackMethods: ['GET'], + trackWebSockets: false + } + }; + + now = function() { + var _ref; + return (_ref = typeof performance !== "undefined" && performance !== null ? typeof performance.now === "function" ? performance.now() : void 0 : void 0) != null ? _ref : +(new Date); + }; + + requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; + + cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame; + + if (requestAnimationFrame == null) { + requestAnimationFrame = function(fn) { + return setTimeout(fn, 50); + }; + cancelAnimationFrame = function(id) { + return clearTimeout(id); + }; + } + + runAnimation = function(fn) { + var last, tick; + last = now(); + tick = function() { + var diff; + diff = now() - last; + last = now(); + return fn(diff, function() { + return requestAnimationFrame(tick); + }); + }; + return tick(); + }; + + result = function() { + var args, key, obj; + obj = arguments[0], key = arguments[1], args = 3 <= arguments.length ? __slice.call(arguments, 2) : []; + if (typeof obj[key] === 'function') { + return obj[key].apply(obj, args); + } else { + return obj[key]; + } + }; + + extend = function() { + var key, out, source, sources, val, _i, _len; + out = arguments[0], sources = 2 <= arguments.length ? __slice.call(arguments, 1) : []; + for (_i = 0, _len = sources.length; _i < _len; _i++) { + source = sources[_i]; + if (source) { + for (key in source) { + if (!__hasProp.call(source, key)) continue; + val = source[key]; + if ((out[key] != null) && typeof out[key] === 'object' && (val != null) && typeof val === 'object') { + extend(out[key], val); + } else { + out[key] = val; + } + } + } + } + return out; + }; + + avgAmplitude = function(arr) { + var count, sum, v, _i, _len; + sum = count = 0; + for (_i = 0, _len = arr.length; _i < _len; _i++) { + v = arr[_i]; + sum += Math.abs(v); + count++; + } + return sum / count; + }; + + getFromDOM = function(key, json) { + var data, e, el; + if (key == null) { + key = 'options'; + } + if (json == null) { + json = true; + } + el = document.querySelector("[data-pace-" + key + "]"); + if (!el) { + return; + } + data = el.getAttribute("data-pace-" + key); + if (!json) { + return data; + } + try { + return JSON.parse(data); + } catch (_error) { + e = _error; + return typeof console !== "undefined" && console !== null ? console.error("Error parsing inline pace options", e) : void 0; + } + }; + + if (window.Pace == null) { + window.Pace = {}; + } + + options = Pace.options = extend(defaultOptions, window.paceOptions, getFromDOM()); + + NoTargetError = (function(_super) { + __extends(NoTargetError, _super); + + function NoTargetError() { + _ref = NoTargetError.__super__.constructor.apply(this, arguments); + return _ref; + } + + return NoTargetError; + + })(Error); + + Bar = (function() { + function Bar() { + this.progress = 0; + } + + Bar.prototype.getElement = function() { + var targetElement; + if (this.el == null) { + targetElement = document.querySelector(options.target); + if (!targetElement) { + throw new NoTargetError; + } + this.el = document.createElement('div'); + this.el.className = "pace pace-active"; + document.body.className = document.body.className.replace('pace-done', ''); + document.body.className += ' pace-running'; + this.el.innerHTML = '
                          \n
                          \n
                          \n
                          '; + if (targetElement.firstChild != null) { + targetElement.insertBefore(this.el, targetElement.firstChild); + } else { + targetElement.appendChild(this.el); + } + } + return this.el; + }; + + Bar.prototype.finish = function() { + var el; + el = this.getElement(); + el.className = el.className.replace('pace-active', ''); + el.className += ' pace-inactive'; + document.body.className = document.body.className.replace('pace-running', ''); + return document.body.className += ' pace-done'; + }; + + Bar.prototype.update = function(prog) { + this.progress = prog; + return this.render(); + }; + + Bar.prototype.destroy = function() { + this.getElement().parentNode.removeChild(this.getElement()); + return this.el = void 0; + }; + + Bar.prototype.render = function() { + var el, progressStr; + if (document.querySelector(options.target) == null) { + return false; + } + el = this.getElement(); + el.children[0].style.width = "" + this.progress + "%"; + if (!this.lastRenderedProgress || this.lastRenderedProgress | 0 !== this.progress | 0) { + el.children[0].setAttribute('data-progress-text', "" + (this.progress | 0) + "%"); + if (this.progress >= 100) { + progressStr = '99'; + } else { + progressStr = this.progress < 10 ? "0" : ""; + progressStr += this.progress | 0; + } + el.children[0].setAttribute('data-progress', "" + progressStr); + } + return this.lastRenderedProgress = this.progress; + }; + + Bar.prototype.done = function() { + return this.progress >= 100; + }; + + return Bar; + + })(); + + Events = (function() { + function Events() { + this.bindings = {}; + } + + Events.prototype.trigger = function(name, val) { + var binding, _i, _len, _ref1, _results; + if (this.bindings[name] != null) { + _ref1 = this.bindings[name]; + _results = []; + for (_i = 0, _len = _ref1.length; _i < _len; _i++) { + binding = _ref1[_i]; + _results.push(binding.call(this, val)); + } + return _results; + } + }; + + Events.prototype.on = function(name, fn) { + var _base; + if ((_base = this.bindings)[name] == null) { + _base[name] = []; + } + return this.bindings[name].push(fn); + }; + + return Events; + + })(); + + _XMLHttpRequest = window.XMLHttpRequest; + + _XDomainRequest = window.XDomainRequest; + + _WebSocket = window.WebSocket; + + extendNative = function(to, from) { + var e, key, val, _results; + _results = []; + for (key in from.prototype) { + try { + val = from.prototype[key]; + if ((to[key] == null) && typeof val !== 'function') { + _results.push(to[key] = val); + } else { + _results.push(void 0); + } + } catch (_error) { + e = _error; + } + } + return _results; + }; + + RequestIntercept = (function(_super) { + __extends(RequestIntercept, _super); + + function RequestIntercept() { + var monitorXHR, + _this = this; + RequestIntercept.__super__.constructor.apply(this, arguments); + monitorXHR = function(req) { + var _open; + _open = req.open; + return req.open = function(type, url, async) { + var _ref1; + if (_ref1 = (type != null ? type : 'GET').toUpperCase(), __indexOf.call(options.ajax.trackMethods, _ref1) >= 0) { + _this.trigger('request', { + type: type, + url: url, + request: req + }); + } + return _open.apply(req, arguments); + }; + }; + window.XMLHttpRequest = function(flags) { + var req; + req = new _XMLHttpRequest(flags); + monitorXHR(req); + return req; + }; + extendNative(window.XMLHttpRequest, _XMLHttpRequest); + if (_XDomainRequest != null) { + window.XDomainRequest = function() { + var req; + req = new _XDomainRequest; + monitorXHR(req); + return req; + }; + extendNative(window.XDomainRequest, _XDomainRequest); + } + if ((_WebSocket != null) && options.ajax.trackWebSockets) { + window.WebSocket = function(url, protocols) { + var req; + req = new _WebSocket(url, protocols); + _this.trigger('request', { + type: 'socket', + url: url, + protocols: protocols, + request: req + }); + return req; + }; + extendNative(window.WebSocket, _WebSocket); + } + } + + return RequestIntercept; + + })(Events); + + _intercept = null; + + getIntercept = function() { + if (_intercept == null) { + _intercept = new RequestIntercept; + } + return _intercept; + }; + + if (options.restartOnRequestAfter !== false) { + getIntercept().on('request', function(_arg) { + var args, request, type; + type = _arg.type, request = _arg.request; + if (!Pace.running) { + args = arguments; + return setTimeout(function() { + var source, stillActive, _i, _len, _ref1, _ref2, _results; + if (type === 'socket') { + stillActive = request.readyState < 2; + } else { + stillActive = (0 < (_ref1 = request.readyState) && _ref1 < 4); + } + if (stillActive) { + Pace.restart(); + _ref2 = Pace.sources; + _results = []; + for (_i = 0, _len = _ref2.length; _i < _len; _i++) { + source = _ref2[_i]; + if (source instanceof AjaxMonitor) { + source.watch.apply(source, args); + break; + } else { + _results.push(void 0); + } + } + return _results; + } + }, options.restartOnRequestAfter); + } + }); + } + + AjaxMonitor = (function() { + function AjaxMonitor() { + var _this = this; + this.elements = []; + getIntercept().on('request', function() { + return _this.watch.apply(_this, arguments); + }); + } + + AjaxMonitor.prototype.watch = function(_arg) { + var request, tracker, type; + type = _arg.type, request = _arg.request; + if (type === 'socket') { + tracker = new SocketRequestTracker(request); + } else { + tracker = new XHRRequestTracker(request); + } + return this.elements.push(tracker); + }; + + return AjaxMonitor; + + })(); + + XHRRequestTracker = (function() { + function XHRRequestTracker(request) { + var event, size, _i, _len, _onreadystatechange, _ref1, + _this = this; + this.progress = 0; + if (window.ProgressEvent != null) { + size = null; + request.addEventListener('progress', function(evt) { + if (evt.lengthComputable) { + return _this.progress = 100 * evt.loaded / evt.total; + } else { + return _this.progress = _this.progress + (100 - _this.progress) / 2; + } + }); + _ref1 = ['load', 'abort', 'timeout', 'error']; + for (_i = 0, _len = _ref1.length; _i < _len; _i++) { + event = _ref1[_i]; + request.addEventListener(event, function() { + return _this.progress = 100; + }); + } + } else { + _onreadystatechange = request.onreadystatechange; + request.onreadystatechange = function() { + var _ref2; + if ((_ref2 = request.readyState) === 0 || _ref2 === 4) { + _this.progress = 100; + } else if (request.readyState === 3) { + _this.progress = 50; + } + return typeof _onreadystatechange === "function" ? _onreadystatechange.apply(null, arguments) : void 0; + }; + } + } + + return XHRRequestTracker; + + })(); + + SocketRequestTracker = (function() { + function SocketRequestTracker(request) { + var event, _i, _len, _ref1, + _this = this; + this.progress = 0; + _ref1 = ['error', 'open']; + for (_i = 0, _len = _ref1.length; _i < _len; _i++) { + event = _ref1[_i]; + request.addEventListener(event, function() { + return _this.progress = 100; + }); + } + } + + return SocketRequestTracker; + + })(); + + ElementMonitor = (function() { + function ElementMonitor(options) { + var selector, _i, _len, _ref1; + if (options == null) { + options = {}; + } + this.elements = []; + if (options.selectors == null) { + options.selectors = []; + } + _ref1 = options.selectors; + for (_i = 0, _len = _ref1.length; _i < _len; _i++) { + selector = _ref1[_i]; + this.elements.push(new ElementTracker(selector)); + } + } + + return ElementMonitor; + + })(); + + ElementTracker = (function() { + function ElementTracker(selector) { + this.selector = selector; + this.progress = 0; + this.check(); + } + + ElementTracker.prototype.check = function() { + var _this = this; + if (document.querySelector(this.selector)) { + return this.done(); + } else { + return setTimeout((function() { + return _this.check(); + }), options.elements.checkInterval); + } + }; + + ElementTracker.prototype.done = function() { + return this.progress = 100; + }; + + return ElementTracker; + + })(); + + DocumentMonitor = (function() { + DocumentMonitor.prototype.states = { + loading: 0, + interactive: 50, + complete: 100 + }; + + function DocumentMonitor() { + var _onreadystatechange, _ref1, + _this = this; + this.progress = (_ref1 = this.states[document.readyState]) != null ? _ref1 : 100; + _onreadystatechange = document.onreadystatechange; + document.onreadystatechange = function() { + if (_this.states[document.readyState] != null) { + _this.progress = _this.states[document.readyState]; + } + return typeof _onreadystatechange === "function" ? _onreadystatechange.apply(null, arguments) : void 0; + }; + } + + return DocumentMonitor; + + })(); + + EventLagMonitor = (function() { + function EventLagMonitor() { + var avg, interval, last, points, samples, + _this = this; + this.progress = 0; + avg = 0; + samples = []; + points = 0; + last = now(); + interval = setInterval(function() { + var diff; + diff = now() - last - 50; + last = now(); + samples.push(diff); + if (samples.length > options.eventLag.sampleCount) { + samples.shift(); + } + avg = avgAmplitude(samples); + if (++points >= options.eventLag.minSamples && avg < options.eventLag.lagThreshold) { + _this.progress = 100; + return clearInterval(interval); + } else { + return _this.progress = 100 * (3 / (avg + 3)); + } + }, 50); + } + + return EventLagMonitor; + + })(); + + Scaler = (function() { + function Scaler(source) { + this.source = source; + this.last = this.sinceLastUpdate = 0; + this.rate = options.initialRate; + this.catchup = 0; + this.progress = this.lastProgress = 0; + if (this.source != null) { + this.progress = result(this.source, 'progress'); + } + } + + Scaler.prototype.tick = function(frameTime, val) { + var scaling; + if (val == null) { + val = result(this.source, 'progress'); + } + if (val >= 100) { + this.done = true; + } + if (val === this.last) { + this.sinceLastUpdate += frameTime; + } else { + if (this.sinceLastUpdate) { + this.rate = (val - this.last) / this.sinceLastUpdate; + } + this.catchup = (val - this.progress) / options.catchupTime; + this.sinceLastUpdate = 0; + this.last = val; + } + if (val > this.progress) { + this.progress += this.catchup * frameTime; + } + scaling = 1 - Math.pow(this.progress / 100, options.easeFactor); + this.progress += scaling * this.rate * frameTime; + this.progress = Math.min(this.lastProgress + options.maxProgressPerFrame, this.progress); + this.progress = Math.max(0, this.progress); + this.progress = Math.min(100, this.progress); + this.lastProgress = this.progress; + return this.progress; + }; + + return Scaler; + + })(); + + sources = null; + + scalers = null; + + bar = null; + + uniScaler = null; + + animation = null; + + cancelAnimation = null; + + Pace.running = false; + + handlePushState = function() { + if (options.restartOnPushState) { + return Pace.restart(); + } + }; + + if (window.history.pushState != null) { + _pushState = window.history.pushState; + window.history.pushState = function() { + handlePushState(); + return _pushState.apply(window.history, arguments); + }; + } + + if (window.history.replaceState != null) { + _replaceState = window.history.replaceState; + window.history.replaceState = function() { + handlePushState(); + return _replaceState.apply(window.history, arguments); + }; + } + + SOURCE_KEYS = { + ajax: AjaxMonitor, + elements: ElementMonitor, + document: DocumentMonitor, + eventLag: EventLagMonitor + }; + + (init = function() { + var source, type, _i, _j, _len, _len1, _ref1, _ref2, _ref3; + Pace.sources = sources = []; + _ref1 = ['ajax', 'elements', 'document', 'eventLag']; + for (_i = 0, _len = _ref1.length; _i < _len; _i++) { + type = _ref1[_i]; + if (options[type] !== false) { + sources.push(new SOURCE_KEYS[type](options[type])); + } + } + _ref3 = (_ref2 = options.extraSources) != null ? _ref2 : []; + for (_j = 0, _len1 = _ref3.length; _j < _len1; _j++) { + source = _ref3[_j]; + sources.push(new source(options)); + } + Pace.bar = bar = new Bar; + scalers = []; + return uniScaler = new Scaler; + })(); + + Pace.stop = function() { + Pace.running = false; + bar.destroy(); + cancelAnimation = true; + if (animation != null) { + if (typeof cancelAnimationFrame === "function") { + cancelAnimationFrame(animation); + } + animation = null; + } + return init(); + }; + + Pace.restart = function() { + Pace.stop(); + return Pace.go(); + }; + + Pace.go = function() { + Pace.running = true; + bar.render(); + cancelAnimation = false; + return animation = runAnimation(function(frameTime, enqueueNextFrame) { + var avg, count, done, element, elements, i, j, remaining, scaler, scalerList, source, start, sum, _i, _j, _len, _len1, _ref1; + remaining = 100 - bar.progress; + count = sum = 0; + done = true; + for (i = _i = 0, _len = sources.length; _i < _len; i = ++_i) { + source = sources[i]; + scalerList = scalers[i] != null ? scalers[i] : scalers[i] = []; + elements = (_ref1 = source.elements) != null ? _ref1 : [source]; + for (j = _j = 0, _len1 = elements.length; _j < _len1; j = ++_j) { + element = elements[j]; + scaler = scalerList[j] != null ? scalerList[j] : scalerList[j] = new Scaler(element); + done &= scaler.done; + if (scaler.done) { + continue; + } + count++; + sum += scaler.tick(frameTime); + } + } + avg = sum / count; + bar.update(uniScaler.tick(frameTime, avg)); + start = now(); + if (bar.done() || done || cancelAnimation) { + bar.update(100); + return setTimeout(function() { + bar.finish(); + return Pace.running = false; + }, Math.max(options.ghostTime, Math.min(options.minTime, now() - start))); + } else { + return enqueueNextFrame(); + } + }); + }; + + Pace.start = function(_options) { + extend(options, _options); + Pace.running = true; + try { + bar.render(); + } catch (_error) { + NoTargetError = _error; + } + if (!document.querySelector('.pace')) { + return setTimeout(Pace.start, 50); + } else { + return Pace.go(); + } + }; + + if (typeof define === 'function' && define.amd) { + define(function() { + return Pace; + }); + } else if (typeof exports === 'object') { + module.exports = Pace; + } else { + if (options.startOnPageLoad) { + Pace.start(); + } + } + +}).call(this); \ No newline at end of file diff --git a/ajax/libs/pace/0.4.15/pace.min.js b/ajax/libs/pace/0.4.15/pace.min.js new file mode 100644 index 000000000..17280c1a9 --- /dev/null +++ b/ajax/libs/pace/0.4.15/pace.min.js @@ -0,0 +1,2 @@ +/*! pace 0.4.15 */ +(function(){var a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O=[].slice,P={}.hasOwnProperty,Q=function(a,b){function c(){this.constructor=a}for(var d in b)P.call(b,d)&&(a[d]=b[d]);return c.prototype=b.prototype,a.prototype=new c,a.__super__=b.prototype,a},R=[].indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(b in this&&this[b]===a)return b;return-1};s={catchupTime:500,initialRate:.03,minTime:500,ghostTime:250,maxProgressPerFrame:10,easeFactor:1.25,startOnPageLoad:!0,restartOnPushState:!0,restartOnRequestAfter:500,target:"body",elements:{checkInterval:100,selectors:["body"]},eventLag:{minSamples:10,sampleCount:3,lagThreshold:3},ajax:{trackMethods:["GET"],trackWebSockets:!1}},z=function(){var a;return null!=(a="undefined"!=typeof performance&&null!==performance?"function"==typeof performance.now?performance.now():void 0:void 0)?a:+new Date},B=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame,r=window.cancelAnimationFrame||window.mozCancelAnimationFrame,null==B&&(B=function(a){return setTimeout(a,50)},r=function(a){return clearTimeout(a)}),D=function(a){var b,c;return b=z(),c=function(){var d;return d=z()-b,b=z(),a(d,function(){return B(c)})},c()},C=function(){var a,b,c;return c=arguments[0],b=arguments[1],a=3<=arguments.length?O.call(arguments,2):[],"function"==typeof c[b]?c[b].apply(c,a):c[b]},t=function(){var a,b,c,d,e,f,g;for(b=arguments[0],d=2<=arguments.length?O.call(arguments,1):[],f=0,g=d.length;g>f;f++)if(c=d[f])for(a in c)P.call(c,a)&&(e=c[a],null!=b[a]&&"object"==typeof b[a]&&null!=e&&"object"==typeof e?t(b[a],e):b[a]=e);return b},o=function(a){var b,c,d,e,f;for(c=b=0,e=0,f=a.length;f>e;e++)d=a[e],c+=Math.abs(d),b++;return c/b},v=function(a,b){var c,d,e;if(null==a&&(a="options"),null==b&&(b=!0),e=document.querySelector("[data-pace-"+a+"]")){if(c=e.getAttribute("data-pace-"+a),!b)return c;try{return JSON.parse(c)}catch(f){return d=f,"undefined"!=typeof console&&null!==console?console.error("Error parsing inline pace options",d):void 0}}},null==window.Pace&&(window.Pace={}),A=Pace.options=t(s,window.paceOptions,v()),h=function(a){function b(){return M=b.__super__.constructor.apply(this,arguments)}return Q(b,a),b}(Error),b=function(){function a(){this.progress=0}return a.prototype.getElement=function(){var a;if(null==this.el){if(a=document.querySelector(A.target),!a)throw new h;this.el=document.createElement("div"),this.el.className="pace pace-active",document.body.className=document.body.className.replace("pace-done",""),document.body.className+=" pace-running",this.el.innerHTML='
                          \n
                          \n
                          \n
                          ',null!=a.firstChild?a.insertBefore(this.el,a.firstChild):a.appendChild(this.el)}return this.el},a.prototype.finish=function(){var a;return a=this.getElement(),a.className=a.className.replace("pace-active",""),a.className+=" pace-inactive",document.body.className=document.body.className.replace("pace-running",""),document.body.className+=" pace-done"},a.prototype.update=function(a){return this.progress=a,this.render()},a.prototype.destroy=function(){return this.getElement().parentNode.removeChild(this.getElement()),this.el=void 0},a.prototype.render=function(){var a,b;return null==document.querySelector(A.target)?!1:(a=this.getElement(),a.children[0].style.width=""+this.progress+"%",(!this.lastRenderedProgress||0|(this.lastRenderedProgress|0!==this.progress))&&(a.children[0].setAttribute("data-progress-text",""+(0|this.progress)+"%"),this.progress>=100?b="99":(b=this.progress<10?"0":"",b+=0|this.progress),a.children[0].setAttribute("data-progress",""+b)),this.lastRenderedProgress=this.progress)},a.prototype.done=function(){return this.progress>=100},a}(),g=function(){function a(){this.bindings={}}return a.prototype.trigger=function(a,b){var c,d,e,f,g;if(null!=this.bindings[a]){for(f=this.bindings[a],g=[],d=0,e=f.length;e>d;d++)c=f[d],g.push(c.call(this,b));return g}},a.prototype.on=function(a,b){var c;return null==(c=this.bindings)[a]&&(c[a]=[]),this.bindings[a].push(b)},a}(),J=window.XMLHttpRequest,I=window.XDomainRequest,H=window.WebSocket,u=function(a,b){var c,d,e,f;f=[];for(d in b.prototype)try{e=b.prototype[d],null==a[d]&&"function"!=typeof e?f.push(a[d]=e):f.push(void 0)}catch(g){c=g}return f},i=function(a){function b(){var a,c=this;b.__super__.constructor.apply(this,arguments),a=function(a){var b;return b=a.open,a.open=function(d,e){var f;return f=(null!=d?d:"GET").toUpperCase(),R.call(A.ajax.trackMethods,f)>=0&&c.trigger("request",{type:d,url:e,request:a}),b.apply(a,arguments)}},window.XMLHttpRequest=function(b){var c;return c=new J(b),a(c),c},u(window.XMLHttpRequest,J),null!=I&&(window.XDomainRequest=function(){var b;return b=new I,a(b),b},u(window.XDomainRequest,I)),null!=H&&A.ajax.trackWebSockets&&(window.WebSocket=function(a,b){var d;return d=new H(a,b),c.trigger("request",{type:"socket",url:a,protocols:b,request:d}),d},u(window.WebSocket,H))}return Q(b,a),b}(g),K=null,w=function(){return null==K&&(K=new i),K},A.restartOnRequestAfter!==!1&&w().on("request",function(b){var c,d,e;return e=b.type,d=b.request,Pace.running?void 0:(c=arguments,setTimeout(function(){var b,f,g,h,i,j,k;if(f="socket"===e?d.readyState<2:0<(i=d.readyState)&&4>i){for(Pace.restart(),j=Pace.sources,k=[],g=0,h=j.length;h>g;g++){if(b=j[g],b instanceof a){b.watch.apply(b,c);break}k.push(void 0)}return k}},A.restartOnRequestAfter))}),a=function(){function a(){var a=this;this.elements=[],w().on("request",function(){return a.watch.apply(a,arguments)})}return a.prototype.watch=function(a){var b,c,d;return d=a.type,b=a.request,c="socket"===d?new l(b):new m(b),this.elements.push(c)},a}(),m=function(){function a(a){var b,c,d,e,f,g,h=this;if(this.progress=0,null!=window.ProgressEvent)for(c=null,a.addEventListener("progress",function(a){return h.progress=a.lengthComputable?100*a.loaded/a.total:h.progress+(100-h.progress)/2}),g=["load","abort","timeout","error"],d=0,e=g.length;e>d;d++)b=g[d],a.addEventListener(b,function(){return h.progress=100});else f=a.onreadystatechange,a.onreadystatechange=function(){var b;return 0===(b=a.readyState)||4===b?h.progress=100:3===a.readyState&&(h.progress=50),"function"==typeof f?f.apply(null,arguments):void 0}}return a}(),l=function(){function a(a){var b,c,d,e,f=this;for(this.progress=0,e=["error","open"],c=0,d=e.length;d>c;c++)b=e[c],a.addEventListener(b,function(){return f.progress=100})}return a}(),d=function(){function a(a){var b,c,d,f;for(null==a&&(a={}),this.elements=[],null==a.selectors&&(a.selectors=[]),f=a.selectors,c=0,d=f.length;d>c;c++)b=f[c],this.elements.push(new e(b))}return a}(),e=function(){function a(a){this.selector=a,this.progress=0,this.check()}return a.prototype.check=function(){var a=this;return document.querySelector(this.selector)?this.done():setTimeout(function(){return a.check()},A.elements.checkInterval)},a.prototype.done=function(){return this.progress=100},a}(),c=function(){function a(){var a,b,c=this;this.progress=null!=(b=this.states[document.readyState])?b:100,a=document.onreadystatechange,document.onreadystatechange=function(){return null!=c.states[document.readyState]&&(c.progress=c.states[document.readyState]),"function"==typeof a?a.apply(null,arguments):void 0}}return a.prototype.states={loading:0,interactive:50,complete:100},a}(),f=function(){function a(){var a,b,c,d,e,f=this;this.progress=0,a=0,e=[],d=0,c=z(),b=setInterval(function(){var g;return g=z()-c-50,c=z(),e.push(g),e.length>A.eventLag.sampleCount&&e.shift(),a=o(e),++d>=A.eventLag.minSamples&&a=100&&(this.done=!0),b===this.last?this.sinceLastUpdate+=a:(this.sinceLastUpdate&&(this.rate=(b-this.last)/this.sinceLastUpdate),this.catchup=(b-this.progress)/A.catchupTime,this.sinceLastUpdate=0,this.last=b),b>this.progress&&(this.progress+=this.catchup*a),c=1-Math.pow(this.progress/100,A.easeFactor),this.progress+=c*this.rate*a,this.progress=Math.min(this.lastProgress+A.maxProgressPerFrame,this.progress),this.progress=Math.max(0,this.progress),this.progress=Math.min(100,this.progress),this.lastProgress=this.progress,this.progress},a}(),F=null,E=null,p=null,G=null,n=null,q=null,Pace.running=!1,x=function(){return A.restartOnPushState?Pace.restart():void 0},null!=window.history.pushState&&(L=window.history.pushState,window.history.pushState=function(){return x(),L.apply(window.history,arguments)}),null!=window.history.replaceState&&(N=window.history.replaceState,window.history.replaceState=function(){return x(),N.apply(window.history,arguments)}),j={ajax:a,elements:d,document:c,eventLag:f},(y=function(){var a,c,d,e,f,g,h,i,l;for(Pace.sources=F=[],h=["ajax","elements","document","eventLag"],d=0,f=h.length;f>d;d++)c=h[d],A[c]!==!1&&F.push(new j[c](A[c]));for(l=null!=(i=A.extraSources)?i:[],e=0,g=l.length;g>e;e++)a=l[e],F.push(new a(A));return Pace.bar=p=new b,E=[],G=new k})(),Pace.stop=function(){return Pace.running=!1,p.destroy(),q=!0,null!=n&&("function"==typeof r&&r(n),n=null),y()},Pace.restart=function(){return Pace.stop(),Pace.go()},Pace.go=function(){return Pace.running=!0,p.render(),q=!1,n=D(function(a,b){var c,d,e,f,g,h,i,j,l,m,n,o,r,s,t,u,v,w;for(j=100-p.progress,d=r=0,e=!0,h=s=0,u=F.length;u>s;h=++s)for(n=F[h],m=null!=E[h]?E[h]:E[h]=[],g=null!=(w=n.elements)?w:[n],i=t=0,v=g.length;v>t;i=++t)f=g[i],l=null!=m[i]?m[i]:m[i]=new k(f),e&=l.done,l.done||(d++,r+=l.tick(a));return c=r/d,p.update(G.tick(a,c)),o=z(),p.done()||e||q?(p.update(100),setTimeout(function(){return p.finish(),Pace.running=!1},Math.max(A.ghostTime,Math.min(A.minTime,z()-o)))):b()})},Pace.start=function(a){t(A,a),Pace.running=!0;try{p.render()}catch(b){h=b}return document.querySelector(".pace")?Pace.go():setTimeout(Pace.start,50)},"function"==typeof define&&define.amd?define(function(){return Pace}):"object"==typeof exports?module.exports=Pace:A.startOnPageLoad&&Pace.start()}).call(this); \ No newline at end of file diff --git a/ajax/libs/pace/package.json b/ajax/libs/pace/package.json new file mode 100644 index 000000000..5bd7010da --- /dev/null +++ b/ajax/libs/pace/package.json @@ -0,0 +1,18 @@ +{ + "name": "pace", + "filename": "pace.js", + "version": "0.4.15", + "description": "Automatic web page progress bar", + "homepage": "http://github.hubspot.com/pace/", + "keywords": [ + "pace", + "pace.js" + ], + "repositories": [ + { + "type": "git", + "url": "https://github.com/HubSpot/pace" + } + ] + +} From c030d4488bd59ef1e9577341423da91ca0fb7404 Mon Sep 17 00:00:00 2001 From: Evan Moran Date: Mon, 14 Oct 2013 15:17:20 -0400 Subject: [PATCH 14/26] Updating OJ to version 0.2.1! Download url: http://ojjs.org/download.html Repro url: http://github.com/ojjs/oj --- ajax/libs/oj/0.2.0/oj.js | 3081 +++++++++++++++++++++++++++++++++ ajax/libs/oj/0.2.0/oj.min.js | 2 + ajax/libs/oj/0.2.1/oj.js | 3074 ++++++++++++++++++++++++++++++++ ajax/libs/oj/0.2.1/oj.min.js | 2 + ajax/libs/oj/latest/oj.js | 51 +- ajax/libs/oj/latest/oj.min.js | 4 +- ajax/libs/oj/package.json | 2 +- 7 files changed, 6192 insertions(+), 24 deletions(-) create mode 100644 ajax/libs/oj/0.2.0/oj.js create mode 100644 ajax/libs/oj/0.2.0/oj.min.js create mode 100644 ajax/libs/oj/0.2.1/oj.js create mode 100644 ajax/libs/oj/0.2.1/oj.min.js diff --git a/ajax/libs/oj/0.2.0/oj.js b/ajax/libs/oj/0.2.0/oj.js new file mode 100644 index 000000000..92faafb16 --- /dev/null +++ b/ajax/libs/oj/0.2.0/oj.js @@ -0,0 +1,3081 @@ +// +// oj.js v0.2.0 +// ojjs.org +// +// Copyright 2013, Evan Moran +// Released under the MIT License +// +// =================================================================== +// Unified templating for the people. Thirsty people. + +;(function(){ + + var root = this, + ArrP = Array.prototype, + FunP = Function.prototype, + ObjP = Object.prototype, + slice = ArrP.slice, + unshift = ArrP.unshift, + concat = ArrP.concat, + pass = function(v){return v}, + _udf = 'undefined' + + // oj function: highest level of capture for tag functions + function oj(){ + return oj.tag.apply(this, ['oj'].concat(slice.call(arguments)).concat([{__quiet__:1}])) + }; + + oj.version = '0.2.0' + + oj.isClient = !(typeof process !== "undefined" && process !== null ? process.versions != null ? process.versions.node : 0 : 0) + + // Detect jQuery globally or in required module + if (typeof $ != _udf) + oj.$ = $ + else if (typeof require != _udf) + try { + oj.$ = require('jquery') + } catch (e){} + + // Export as a module in node + if (typeof require != _udf) + module.exports = oj + // Export globally if not in node + else + root['oj'] = oj + + // Reference ourselves for template files to see + oj.oj = oj + + // oj.load: load the page specified generating necessary html, css, and client side events + oj.load = function(page){ + // Defer dom manipulation until the page is ready + return oj.$(function(){ + oj.$.ojBody(require(page)) + + // Trigger events bound through onload + return oj.onload() + }); + }; + + // oj.onload: Enlist in onload action or run them. + var _onLoadQueue = {queue: [], loaded: false} + oj.onload = function(f){ + // Call everything if no arguments + if (oj.isUndefined(f)){ + _onLoadQueue.loaded = true + while ((f = _onLoadQueue.queue.shift())) + f() + } + // Call load if already loaded + else if (_onLoadQueue.loaded) + f() + // Queue function for later + else + _onLoadQueue.queue.push(f) + } + + // oj.emit: Used by plugins to group multiple elements as if it is a single tag. + oj.emit = function(){return oj.tag.apply(oj, ['oj'].concat(slice.call(arguments)))} + + // Type Helpers + oj.isDefined = function(a){return typeof a !== _udf} + oj.isOJ = function(obj){return !!(obj != null ? obj.isOJ : void 0)} + oj.isOJType = function(a){return oj.isOJ(a) && a.type === a} + oj.isOJInstance = function(a){return oj.isOJ(a) && !oj.isOJType(a)} + oj.isEvented = function(a){return !!(a && a.on && a.off && a.trigger)} + oj.isDOM = function(a){return !!(a && (a.nodeType != null))} + oj.isDOMElement = function(a){return !!(a && a.nodeType === 1)} + oj.isDOMAttribute = function(a){return !!(a && a.nodeType === 2)} + oj.isDOMText = function(a){return !!(a && a.nodeType === 3)} + oj.isjQuery = function(a){return !!(a && a.jquery)} + oj.isUndefined = function(a){return a === void 0} + oj.isBoolean = function(a){return a === true || a === false || ObjP.toString.call(a) === '[object Boolean]'} + oj.isNumber = function(a){return !!(a === 0 || (a && a.toExponential && a.toFixed))} + oj.isString = function(a){return !!(a === '' || (a && a.charCodeAt && a.substr))} + oj.isDate = function(a){return !!(a && a.getTimezoneOffset && a.setUTCFullYear)} + oj.isPlainObject = function(a){return oj.$.isPlainObject(a) && !oj.isOJ(a)} + oj.isFunction = oj.$.isFunction + oj.isArray = oj.$.isArray + oj.isRegEx = function(a){return ObjP.toString.call(a) === '[object RegExp]'} + oj.isArguments = function(a){return ObjP.toString.call(a) === '[object Arguments]'} + oj.parse = function(str){ + var n, o = str + if (str === _udf) + o = void 0 + else if (str === 'null') + o = null + else if (str === 'true') + o = true + else if (str === 'false') + o = false + else if (!isNaN(n = parseFloat(str))) + o = n + return o; + }; + + // unionArguments: Union arguments into options and args + oj.unionArguments = function(argList){ + var options = {}, args = [], v, ix = 0 + for (; ix < argList.length; ix++){ + v = argList[ix] + if (oj.isPlainObject(v)) + options = _extend(options, v) + else + args.push(v) + } + return {options: options, args: args} + } + + // argumentShift: Shift argument out of options with key + oj.argumentShift = function(options, key){ + var value + if ((oj.isPlainObject(options)) && (key != null) && (options[key] != null)){ + value = options[key] + delete options[key] + } + return value + }; + + // Utility Helpers + var _keys = Object.keys, + _extend = oj.$.extend + + function _isCapitalLetter(c){return !!(c.match(/[A-Z]/));}; + + function _has(obj, key){return ObjP.hasOwnProperty.call(obj, key)} + + function _values(obj){ + var keys = _keys(obj), + len = keys.length, + values = new Array(len), + i = 0 + for (; i < len; i++) + values[i] = obj[keys[i]] + return values + } + + function _toArray(obj){ + if (!obj) + return [] + if (oj.isArray(obj)) + return slice.call(obj) + if (oj.isArguments(obj)) + return slice.call(obj) + if (obj.toArray && oj.isFunction(obj.toArray)) + return obj.toArray() + return _values(obj) + } + + function _isEmpty(o){ + if (oj.isArray(o)) + return o.length === 0 + for (var k in o) + if (_has(o, k)) + return false + return true + }; + + function _clone(o){ + if (!(oj.isArray(o) || oj.isPlainObject(o))) + return o + if (oj.isArray(o)) + return o.slice() + else + return _extend({}, o) + } + + // _setObject(obj, k1, k2, ..., value): + // Set object deeply key by key ensure each part is an object + function _setObject(obj){ + var args = arguments, + o = obj, + len = args.length, + // keys are args ix: 1 to n-2 + keys = 3 <= len ? slice.call(args, 1, len = len - 1) : (len = 1, []), + // value is last arg + value = args[len++], + ix, k + + for (ix = 0; ix < keys.length; ix++){ + k = keys[ix] + + // Initialize key to empty object if necessary + if (typeof o[k] !== 'object') + o[k] = {} + + // Set final value if this is the last key + if (ix === keys.length - 1) + o[k] = value + else + // Continue deeper + o = o[k] + } + return obj + }; + + // uniqueSort: + function uniqueSort(arr, isSorted){ + if (isSorted == null) + isSorted = false + + if (!isSorted) + arr.sort() + + var out = [], ix, item + for (ix = 0; ix < arr.length; ix++){ + item = arr[ix] + if (ix > 0 && arr[ix - 1] === arr[ix]) + continue + out.push(item) + } + return out + }; + + // _d(args...): initialization helper that returns first arg that isn't null + function _d(){ + for (var ix = 0;ix < arguments.length; ix++) + if (arguments[ix] != null) + return arguments[ix] + return null + } + + // _e: error by throwing msg with optional fn name + function _e(fn, msg){ + msg = _d(msg, fn, '') + fn = _d(fn, 0) + var pfx = "oj: " + if (fn) + pfx = "oj." + fn + ": " + throw new Error(pfx + msg) + } + + // _a: assert when cond is false with msg and with optional fn name + function _a(cond, fn, msg){if (!cond) _e(fn,msg)} + + // _v: validate argument n with fn name and message + function _v(fn, n, v, type){ + n = {1:'first',2:'second',3: 'third', 4: 'fourth'}[n] + _a(!type || (typeof v === type), fn, "" + type + " expected for " + n + " argument") + } + + // _splitAndTrim: Split string by seperator and trim result + function _splitAndTrim(str, seperator, limit){ + return str.split(seperator, limit).map(function(v){ + return v.trim() + }) + } + + // _decamelize: Convert from camal case to underscore case + function _decamelize(str){return str.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase()} + + // _dasherize: Convert from camal case or space seperated to dashes + function _dasherize(str){return _decamelize(str).replace(/[ _]/g, '-')} + + // oj.addMethod: add multiple methods to an object + oj.addMethods = function(obj, mapNameToMethod){ + for (var methodName in mapNameToMethod) + oj.addMethod(obj, methodName, mapNameToMethod[methodName]); + } + + // oj.addMethod: Add method to object with name and fn + oj.addMethod = function(obj, name, fn){ + _v('addMethod', 2, name, 'string') + _v('addMethod', 3, fn, 'function') + // Methods are non-enumerable, non-writable properties + Object.defineProperty(obj, name, { + value: fn, + enumerable: false, + writable: false, + configurable: true + }) + } + + // oj.removeMethod: Remove a method with name from an object + oj.removeMethod = function(obj, name){ + _v('removeMethod', 2, name, 'string'); + delete obj[name] + }; + + // oj.addProperties: add multiple properties to an object + // Properties can be specified by get/set methods or by a value + // Optionally you can include writable or enumerable settings + oj.addProperties = function(obj, mapNameToInfo){ + + // Iterate over properties + var propInfo, propName; + + for (propName in mapNameToInfo){ + propInfo = mapNameToInfo[propName]; + + // Wrap the value if propInfo is not already a prop definition + if (((propInfo != null ? propInfo.get : void 0) == null) && + ((propInfo != null ? propInfo.value : void 0) == null)) + propInfo = {value: propInfo, writable: true} + + oj.addProperty(obj, propName, propInfo); + } + }; + + // oj.addProperty: Add property to object with name and info + oj.addProperty = function(obj, name, info){ + _v('addProperty', 2, name, 'string') + _v('addProperty', 3, info, 'object') + + // Default properties to enumerable and configurable + info = _extend({enumerable: true, configurable: true}, info) + + // Remove property if it already exists + if (Object.getOwnPropertyDescriptor(obj, name) != null) + oj.removeProperty(obj, name) + + // Add the property + Object.defineProperty(obj, name, info) + }; + + // oj.removeProperty: remove property from object with name + oj.removeProperty = function(obj, name){ + _v('removeProperty', 2, name, 'string') + delete obj[name] + } + + // oj.isProperty: Determine property in object is a get/set property + oj.isProperty = function(obj, name){ + _v('isProperty', 2, name, 'string') + return Object.getOwnPropertyDescriptor(obj, name).get != null + }; + + // oj.copyProperty: Copy source.propName to dest.propName + oj.copyProperty = function(dest, source, propName){ + var info = Object.getOwnPropertyDescriptor(source, propName) + if (info.value != null) + info.value = _clone(info.value) + return Object.defineProperty(dest, propName, info) + } + + // _argsStack: Abstraction to wrap global arguments stack. + // This makes me sad but it is necessary for div -> syntax + var _argsStack = []; + + // Access the top of the stack + oj._argsTop = function(){ + if (_argsStack.length) + return _argsStack[_argsStack.length - 1] + else + return null + } + + // Push scope onto arguments + oj._argsPush = function(args){ + _argsStack.push(_d(args,[])) + } + + // Pop scope from arguments + oj._argsPop = function(){ + if (_argsStack.length) + return _argsStack.pop() + return null + } + + // Append argument + oj._argsAppend = function(arg){ + var top = oj._argsTop() + if (top != null) + top.push(arg) + } + + // oj.tag (name, attributes, rest...) + oj.tag = function(name){ + _v('tag', 1, name, 'string') + + var rest = 2 <= arguments.length ? slice.call(arguments, 1) : [], + u = oj.unionArguments(rest), + args = u.args, + attributes = u.options, + isQuiet = attributes.__quiet__, + arg, len, r, ix, + // Build ojml starting with tag + ojml = [name] + + if (isQuiet) + delete attributes.__quiet__; + + // Add attributes to ojml if they exist + if (!_isEmpty(attributes)) + ojml.push(attributes); + + // Store current tag context + oj._argsPush(ojml) + + // Loop over attributes + for (ix = 0; ix < args.length; ix++){ + arg = args[ix] + + if (oj.isPlainObject(arg)) + continue + + else if (oj.isFunction(arg)){ + len = oj._argsTop().length + + // Call the fn tags will append to oj._argsTop + r = arg() + + // Use return value instead if oj._argsTop didn't change + if (len === oj._argsTop().length && (r != null)) + oj._argsAppend(r) + + } else + oj._argsAppend(arg) + } + + // Restore previous tag context + oj._argsPop() + + // Append the final result to your parent's arguments + // if there exists an argument to append to. + // Do not emit when quiet is set, + if (!isQuiet) + oj._argsAppend(ojml) + + return ojml + } + + // Define all elements as closed or open + oj.tag.elements = { + closed: 'a abbr acronym address applet article aside audio b bdo big blockquote body button canvas caption center cite code colgroup command datalist dd del details dfn dir div dl dt em embed fieldset figcaption figure font footer form frameset h1 h2 h3 h4 h5 h6 head header hgroup html i iframe ins keygen kbd label legend li map mark menu meter nav noframes noscript object ol optgroup option output p pre progress q rp rt ruby s samp script section select small source span strike strong style sub summary sup table tbody td textarea tfoot th thead time title tr tt u ul var video wbr xmp'.split(' '), + open: 'area base br col command css !DOCTYPE embed hr img input keygen link meta param source track wbr'.split(' ') + } + + // Keep track of all valid elements + oj.tag.elements.all = (oj.tag.elements.closed.concat(oj.tag.elements.open)).sort() + + // tag.isClosed: Determine if an element is closed or open + oj.tag.isClosed = function(tag){return oj.tag.elements.open.indexOf(tag) === -1} + + // _setTagName: Record tag name on a given tag function + function _setTagName(tag, name){if (tag != null) tag.tagName = name } + + // _getTagName: Get a tag name on a given tag function + function _getTagName(tag){return tag.tagName} + + // _getQuietTagName: Get quiet tag name + function _getQuietTagName(tag){return '_' + tag} + + // _setInstanceOnElement: Record an oj instance on a given element + function _setInstanceOnElement(el, inst){if (el != null) el.oj = inst} + + // _getInstanceOnElement: Get a oj instance on a given element + function _getInstanceOnElement(el){ + if ((el != null ? el.oj : 0) != null) + return el.oj + else + return null + } + + // Create tag methods for all elements + for (var ix = 0; ix < oj.tag.elements.all.length; ix++){ + t = oj.tag.elements.all[ix] + ;(function(t){ + // Define tag function named t + oj[t] = function(){return oj.tag.apply(oj, [t].concat(slice.call(arguments)))} + + // Quiet tag functions do not emit + // Define quiet tag function named qt + var qt = _getQuietTagName(t) + oj[qt] = function(){return oj.tag.apply(oj, [t, {__quiet__: 1 }].concat(slice.call(arguments)))} + + // Tag functions remember their name so the OJML syntax can use the function + _setTagName(oj[t], t) + _setTagName(oj[qt], t) + })(t) + } + + // oj.doctype: Method to define doctypes based on short names + + var dhp = 'HTML PUBLIC "-//W3C//DTD HTML 4.01', + w3 = '"http://www.w3.org/TR/html4/', + strict5 = 'html', + strict4 = dhp + '//EN" ' + w3 + 'strict.dtd"', + _doctypes = { + '5': strict5, + 'HTML 5': strict5, + '4': strict4, + 'HTML 4.01 Strict': strict4, + 'HTML 4.01 Frameset': dhp + ' Frameset//EN" ' + w3 + 'frameset.dtd"', + 'HTML 4.01 Transitional': dhp + ' Transitional//EN" ' + w3 + 'loose.dtd"' + } + + // Define the method passing through to !DOCTYPE tag function + oj.doctype = function(typeOrValue){ + typeOrValue = _d(typeOrValue,'5') + return oj['!DOCTYPE'](_d(_doctypes[typeOrValue], typeOrValue)) + }; + + // oj.extendInto (context): Extend all OJ methods into a context. + // Defaults to root, which is either `global` or `window` + + // Methods that start with _ are not extended + oj.useGlobally = oj.extendInto = function(context){ + context = _d(context,root) + + var o = {}, k, qn, v; + + // For all keys and values in oj + for (k in oj){ + v = oj[k] + + // Extend into new object + if (k[0] !== '_' && k !== 'extendInto' && k !== 'useGlobally'){ + o[k] = v + + // Export _tag and _Type methods + qn = _getQuietTagName(k) + if (oj[qn]) + o[qn] = oj[qn] + } + } + _extend(context, o) + }; + + // oj.compile(options, ojml) + // --- + // Compile ojml into meaningful parts + // options: + // * html - Compile to html + // * dom - Compile to dom + // * css - Compile to css + // * cssMap - Record css as a javascript object + // * styles -- Output css as style tags + // * minify - Minify js and css + // * ignore:{html:1} - Map of tags to ignore while compiling + + oj.compile = function(options, ojml){ + // Options is optional + ojml = _d(ojml, options) + + var css, cssMap, dom, html, + + // Default options to compile everything + options = _extend({html:1, dom:0, css:0, cssMap:0, minify:0, ignore:{}}, options), + + // Init accumulator + acc = _clone(options) + + acc.html = options.html ? [] : null + acc.dom = options.dom && (typeof document !== "undefined" && document !== null) ? document.createElement('OJ') : null + acc.css = options.css || options.cssMap ? {} : null; + acc.indent = '' + + // Accumulate insert events per element + acc.inserts = [] + + if (options.dom) + acc.types = [] + + acc.tags = {} + + // Always ignore oj and css tags + _extend(options.ignore, {oj:1, css:1}) + + // Recursive compile to accumulator + _compileAny(ojml, acc) + + // Flatten CSS + if (acc.css != null) + cssMap = _flattenCSSMap(acc.css) + + // Generate css if necessary + if (options.css) + css = _cssFromPluginObject(cssMap, {minify: options.minify, tags: 0}) + + // Output cssMap if necessary + if (!options.cssMap) + cssMap = undefined + + // Generate HTML if necessary + if (options.html) + html = acc.html.join('') + + // Generate dom if necessary + if (options.dom){ + + // Remove the wrapping from the dom element + dom = acc.dom.childNodes; + + // Cleanup inconsistencies of childNodes + if (dom.length != null){ + // Make dom a real array + dom = _toArray(dom) + + // Filter out anything that isn't a dom element + dom = dom.filter(function(v){return oj.isDOM(v)}) + } + + // Ensure dom is null if empty + if (dom.length === 0) + dom = null + + // Single elements are not returned as a list + else if (dom.length === 1) + // Reasoning: The common cases don't have multiple elements + // ,, etc and this is abstracted for you anyway + // with jQuery plugins + dom = dom[0] + } + return { + html: html, + dom: dom, + css: css, + cssMap: cssMap, + types: acc.types, + tags: acc.tags, + inserts: acc.inserts + } + }; + + // _styleFromObject: Convert object to style string + function _styleFromObject(obj, options){ + options = _extend({ + inline: true, + indent: '' + }, options) + + // Trailing semi should only exist on when we aren't indenting + options.semi = !options.inline; + + var out = "", + + // Sort keys to create consistent output + keys = _keys(obj).sort(), + + // Support indention and inlining + indent = options.indent != null ? options.indent : '', + newline = options.inline ? '' : '\n', + ix, k, kFancy, semi + + for (ix = 0; ix < keys.length; ix++){ + kFancy = keys[ix] + + // Add semi if it is not inline or it is not the last key + semi = options.semi || ix !== keys.length - 1 ? ";" : '' + + // Allow keys to be camal case + k = _dasherize(kFancy) + + // Collect css result for this key + out += "" + indent + k + ":" + obj[kFancy] + semi + newline + } + return out + }; + + // _attributesFromObject: Convert object to attribute string with no special conversions + function _attributesFromObject(obj){ + if (!oj.isPlainObject(obj)) + return obj + + // Pass through non objects + var k, v, ix, + out = '', + space = '', + // Serialize attributes in order for consistent output + attrs = _keys(obj).sort() + + for (ix = 0; ix < attrs.length; ix++){ + k = attrs[ix] + v = obj[k] + + // Boolean attributes have no value + if (v === true) + out += "" + space + k + + // Other attributes have a value + else + out += "" + space + k + "=\"" + v + "\"" + + space = ' ' + } + return out; + }; + + // _flattenCSSMap: Take an OJ cssMap and flatten it into the form + // `'plugin' -> '@media query' -> 'selector' ->'rulesMap'` + // + // This method vastly simplifies `_cssFromPluginObject` + // Nested, media, and comma definitions are resolved and merged + function _flattenCSSMap(cssMap){ + var flatMap = {}, plugin, cssMap_ + for (plugin in cssMap){ + cssMap_ = cssMap[plugin] + _flattenCSSMap_(cssMap_, flatMap, [''], [''], plugin) + } + return flatMap + }; + + // Recursive helper with accumulators (it outputs flatMapAcc) + function _flattenCSSMap_(cssMap, flatMapAcc, selectorsAcc, mediasAcc, plugin){ + + // Built in media helpers + var acc, cur, inner, isMedia, mediaJoined, mediasNext, next, outer, parts, rules, selector, selectorJoined, selectorsNext, o, i, + + medias = { + 'widescreen': 'only screen and (min-width: 1200px)', + 'monitor': '', + 'tablet': 'only screen and (min-width: 768px) and (max-width: 959px)', + 'phone': 'only screen and (max-width: 767px)' + }; + + for (selector in cssMap){ + rules = cssMap[selector] + + // Base Case: Record our selector when `rules` is a value + if (typeof rules !== 'object'){ + + // Join selectors and media accumulators with commas + selectorJoined = selectorsAcc.sort().join(',') + mediaJoined = mediasAcc.sort().join(',') + + // Prepend @media as that was removed previously when spliting into parts + if (mediaJoined !== '') + mediaJoined = "@media " + mediaJoined + + // Record the rule deeply in `flatMapAcc` + _setObject(flatMapAcc, plugin, mediaJoined, selectorJoined, selector, rules) + // Recursive Case: Recurse on `rules` when it is an object + } else { + + // (r1) Media Query found: Generate the next media queries + if (selector.indexOf('@media') === 0){ + isMedia = true + mediasNext = next = [] + selectorsNext = selectorsAcc + selector = (selector.slice('@media'.length)).trim() + acc = mediasAcc + + // (r2) Selector found: Generate the next selectors + } else { + isMedia = false + selectorsNext = next = [] + mediasNext = mediasAcc + acc = selectorsAcc + } + + // Media queries and Selectors can be comma seperated + parts = _splitAndTrim(selector, ',') + + // Media queries have convience substitutions like 'phone', 'tablet' + if (isMedia){ + parts = parts.map(function(v){ + return _d(medias[v], v) + }); + } + + // Determine the next selectors or media queries + for (o = 0; o < acc.length; o++){ + outer = acc[o] + + for (i = 0; i < parts.length; i++){ + inner = parts[i] + + // When `&` is not present just insert in front with the correct join operator + cur = inner + if ((inner.indexOf('&')) === -1 && outer !== '') + cur = (isMedia ? '& and ' : '& ') + cur; + + next.push(cur.replace(/&/g, outer)); + } + } + + // Recurse through objects after calculating the next selectors + _flattenCSSMap_( + rules, flatMapAcc, selectorsNext, mediasNext, plugin + ); + } + } + }; + + // _styleClassFromPlugin: Abstract plugin "; + } + + // _cssFromMediaObject: Convert css from a flattened mediaMap rule object. + // The rule object is of the form: + // mediaQuery => selector => rulesObject + function _cssFromMediaObject(mediaMap, options){ + options = _d(options, {}) + + var indent, indentRule, media, rules, selector, selectorMap, space, styles, + + minify = options.minify != null ? options.minify : 0, + tags = options.tags != null ? options.tags : 0, + + // Deterine what output characters are needed + newline = minify ? '' : '\n', + space = minify ? '' : ' ', + inline = minify, + css = '' + + // Build css for media => selector => rules + for (media in mediaMap){ + selectorMap = mediaMap[media]; + + // Serialize media query + if (media){ + media = media.replace(/,/g, "," + space); + css += "" + media + space + "{" + newline; + } + + for (selector in selectorMap){ + styles = selectorMap[selector] + indent = (!minify) && media ? '\t' : '' + + // Serialize selector + selector = selector.replace(/,/g, "," + newline) + css += "" + indent + selector + space + "{" + newline + + // Serialize style rules + indentRule = !minify ? indent + '\t' : indent + rules = _styleFromObject(styles, { + inline: inline, + indent: indentRule + }); + css += rules + indent + '}' + newline + } + + // End media query + if (media !== '') + css += '}' + newline + + } + try { + css = oj._minifyCSS(css, options) + } catch (e){ + throw new Error("css minification error: " + e.message + "\nCould not minify:\n" + css) + } + return css + }; + + // _cssFromPluginObject: Convert flattened css selectors and rules to a string + // pluginMaps are of the form: + // pluginName => mediaQuery => selector => rulesObject + // minify:false will output newlines + // tags:true will output the css in `" + newline + } + return css + }; + + // _compileDeeper: Recursive helper for compiling that wraps indention + function _compileDeeper(method, ojml, options){ + var i = options.indent + options.indent += '\t' + method(ojml, options) + options.indent = i + }; + + // _compileAny Recursive helper for compiling ojml or any type + function _compileAny(any, options){ + // Array + if (oj.isArray(any)) + _compileTag(any, options) + + // String + else if (oj.isString(any)){ + if (options.html != null) + options.html.push(any) + + if (any.length > 0 && any[0] === '<'){ + var root = document.createElement('div') + root.innerHTML = any; + if (options.dom != null) + options.dom.appendChild(root); + } else { + if (options.dom != null) + options.dom.appendChild(document.createTextNode(any)) + } + + // Boolean or Number + } else if (oj.isBoolean(any) || oj.isNumber(any)){ + if (options.html != null) + options.html.push("" + any) + + if (options.dom != null) + options.dom.appendChild(document.createTextNode("" + any)); + + // Function + } else if (oj.isFunction(any)){ + + // Wrap function call to allow full oj generation within any + _compileAny(oj(any), options); + + // Date + } else if (oj.isDate(any)){ + if (options.html != null) + options.html.push("" + (any.toLocaleString())); + + if (options.dom != null) + options.dom.appendChild(document.createTextNode("" + (any.toLocaleString()))); + + // OJ Type or Instance + } else if (oj.isOJ(any)){ + if (options.types != null) + options.types.push(any) + + if (options.html != null) + options.html.push(any.toHTML(options)) + + if (options.dom != null) + options.dom.appendChild(any.toDOM(options)) + + if (options.css != null) + _extend(options.css, any.toCSSMap(options)); + } + // Do nothing for: null, undefined, object + }; + + + // _compileTag: Recursive helper for compiling ojml tags + function _compileTag(ojml, options){ + + // Empty list compiles to undefined + if (ojml.length === 0) return + + // The first part of ojml is the tag + var tag = ojml[0], + tagType = typeof tag, + u = oj.unionArguments(ojml.slice(1)), + attributes = u.options, + children = u.args, + styles, + selector + + // Allow the tag parameter to be 'table' (string) or oj.table (function) or oj.Table (object) + if ((tagType === 'function' || tagType === 'object')) + tag = _d(_getTagName(tag), tag) + + // Fail if no tag found + if (!(oj.isString(tag) && tag.length > 0)) + _e('compile', 'tag name is missing') + + // Record tag as encountered + options.tags[tag] = true + + // Instance oj object if tag is capitalized + if (_isCapitalLetter(tag[0])) + return _compileDeeper(_compileAny, new oj[tag](ojml.slice(1)), options) + + // Compile to css if requested + if (options.css && tag === 'css'){ + + // Extend options.css with rules + for (selector in attributes){ + styles = attributes[selector] + options.css['oj'] = _d(options.css['oj'], {}) + options.css['oj'][selector] = _d(options.css['oj'][selector], {}) + _extend(options.css['oj'][selector], styles); + } + } + + // Compile DOCTYPE as special case because it is not really an element + // It has attributes with spaces and cannot be created by dom manipulation + // In this way it is HTML generation only. + + if (tag === '!DOCTYPE'){ + _v('compile', 1, ojml[1], 'string'); + if (!options.ignore[tag]){ + if (options.html) + options.html.push("<" + tag + " " + ojml[1] + ">") + // options.dom is purposely ignored + } + return; + } + if (!options.ignore[tag]){ + var events = _attributesProcessedForOJ(attributes), el + + // Compile to dom if requested + // Add dom element with attributes + if (options.dom && (typeof document !== "undefined" && document !== null)){ + + // Create element + el = document.createElement(tag) + + // Add self to parent + if (oj.isDOMElement(options.dom)) + options.dom.appendChild(el) + + // Push ourselves on the dom stack (to handle children) + options.dom = el + + // Set attributes in sorted order for consistency + if (oj.isPlainObject(attributes)){ + var keys = _keys(attributes).sort(), ix, attrName, attrValue + for (ix = 0; ix < keys.length; ix++){ + attrName = keys[ix] + attrValue = attributes[attrName] + + // Boolean attributes have no value + if (attrValue === true) + el.setAttributeNode(document.createAttribute(attrName)) + else + el.setAttribute(attrName, attrValue) + } + } + + // Bind events + _attributesBindEventsToDOM(events, el, options.inserts) + } + + // Compile to html if requested + // Add tag with attributes + if (options.html){ + var attr = _d(_attributesFromObject(attributes), ''), + space = attr === '' ? '' : ' ' + options.html.push("<" + tag + space + attr + ">") + // Recurse through children if this tag isn't ignored deeply + } + } + if (options.ignore[tag] !== 'deep'){ + for (ix = 0; ix < children.length; ix++){ + var child = children[ix] + // Skip indention if there is only one child + if (options.html != null && !options.minify && children.length > 1) + options.html.push("\n\t" + options.indent) + _compileDeeper(_compileAny, child, options) + } + } + + // Skip indention if there is only one child + if (options.html != null && !options.minify && children.length > 1) + options.html.push("\n" + options.indent) + + // End html tag if you have children or your tag closes + if (!options.ignore[tag]){ + + // Close tag if html + if (options.html != null && (children.length > 0 || oj.tag.isClosed(tag))) + options.html.push("") + + // Pop ourselves if dom + if (options.dom) + options.dom = options.dom.parentNode + } + }; + + // _attributesProcessedForOJ: Process attributes to make them easier to use + function _attributesProcessedForOJ(attr){ + var jqEvents = {bind:1, on:1, off:1, live:1, blur:1, change:1, click:1, dblclick:1, focus:1, focusin:1, focusout:1, hover:1, keydown:1, keypress:1, keyup:1, mousedown:1, mouseenter:1, mouseleave:1, mousemove:1, mouseout:1, mouseup:1, ready:1, resize:1, scroll:1, select:1, insert:1}, + events, k, v + + // Allow attributes to alias c to class and use arrays instead of space seperated strings + // Convert to c and class from arrays to strings + if (oj.isArray(attr != null ? attr.c : void 0)) + attr.c = attr.c.join(' ') + + if (oj.isArray(attr != null ? attr["class"] : void 0)) + attr["class"] = attr["class"].join(' ') + + // Move c to class + if ((attr != null ? attr.c : void 0) != null){ + if ((attr != null ? attr["class"] : void 0) != null) + attr["class"] += ' ' + attr.c + else + attr["class"] = attr.c + delete attr.c + } + + // Allow attributes to take style as an object + if (oj.isPlainObject(attr != null ? attr.style : void 0)){ + attr.style = _styleFromObject(attr.style, { + inline: true + }); + } + + // Omit attributes with values of false, null, or undefined + if (oj.isPlainObject(attr)){ + for (k in attr){ + v = attr[k] + if (v === null || v === void 0 || v === false) + delete attr[k] + } + } + + // Filter out jquery events + events = {} + if (oj.isPlainObject(attr)){ + + // Filter out attributes that are jquery events + for (k in attr){ + v = attr[k] + + // If this attribute (k) is an event + if (jqEvents[k] != null){ + events[k] = v + delete attr[k] + } + } + } + + // Returns bindable events + return events + }; + + // Bind events to dom + function _attributesBindEventsToDOM(events, el, inserts){ + console.log("inserts: ", inserts); + var ek, ev, _results = [] + for (ek in events){ + ev = events[ek] + _a(oj.$ != null, "jquery is missing when binding a '" + ek + "' event") + if (ek == 'insert' && inserts) { + console.log("load event found"); + console.log("ev: ", ev); + inserts.push(function(){ + console.log("calling onload"); + ev.call(el,el) + }); + } + else if (oj.isArray(ev)) + _results.push(oj.$(el)[ek].apply(this, ev)); + else + _results.push(oj.$(el)[ek](ev)); + + } + return _results; + }; + + // oj.toHTML: Compile directly to HTML only + oj.toHTML = function(options, ojml){ + + // Options is optional + if (!oj.isPlainObject(options)){ + ojml = options + options = {} + } + + // Create html only + _extend(options, {dom: 0, js: 0, html: 1, css: 0}) + return (oj.compile(options, ojml)).html + }; + + // oj.toCSS: Compile directly to CSS only + oj.toCSS = function(options, ojml){ + // Options is optional + if (!oj.isPlain(options)){ + ojml = options + options = {} + } + // Create css only + _extend(options, {dom: 0, js: 0, html: 0, css: 1}) + return (oj.compile(options, ojml)).css + }; + + // _inherit: Inherit Child from Parent + // Based on, but sadly incompatable with, coffeescript inheritance + function _inherit(Child, Parent){ + var Ctor, prop + + // Copy class properties and methods + for (prop in Parent) + oj.copyProperty(Child, Parent, prop) + + Ctor = function(){}; + Ctor.prototype = Parent.prototype; + Child.prototype = new Ctor() + + // Provide easy access for base class methods + // Example: Parent.base.methodName(arguments...) + Child.base = Child.__super__ = Parent.prototype + }; + + // _construct(Type, arg1, arg2, ...): Construct type as if using call + function _construct(Type){return new (FunP.bind.apply(Type, arguments))}; + + // oj.createType: Create OJ type with args object supporting: + // base, constructor, properties, and methods + oj.createType = function(name, args){ + + args = _d(args, {}) + args.methods = _d(args.methods, {}) + args.properties = _d(args.properties, {}) + + _v('createType', 1, name, 'string'); + _v('createType', 2, args, 'object'); + + var methodKeys, propKeys, typeProps, + + // When auto newing you need to delay construct the properties + // or they will be constructed twice. + delay = '__DELAYED__', + + // Constructor to return + Out = new Function("return function " + name + "(){\n var _t = this;\n if ( !(this instanceof " + name + ") ){\n _t = new " + name + "('" + delay + "');\n _t.__autonew__ = true;\n }\n\n if (arguments && arguments[0] != '" + delay + "')\n " + name + ".prototype.constructor.apply(_t, arguments);\n\n return _t;\n}")() + + // Default the constructor to call its base + if (args.base != null && (args.constructor == null || (!args.hasOwnProperty('constructor')))){ + args.constructor = function(){ + return Out.base != null ? Out.base.constructor.apply(this, arguments) : void 0 + } + } + + // Inherit if necessary + if (args.base != null) + _inherit(Out, args.base) + + // Add the constructor as a method + oj.addMethod(Out.prototype, 'constructor', args.constructor) + + // Mark new type and its instances with a non-enumerable type and isOJ properties + typeProps = { + type: { + value: Out, + writable: false, + enumerable: false + }, + typeName: { + value: name, + writable: false, + enumerable: false + }, + isOJ: { + value: true, + writable: false, + enumerable: false + } + } + oj.addProperties(Out, typeProps) + oj.addProperties(Out.prototype, typeProps) + + // Add properties all oj Types have + propKeys = (_keys(args.properties)).sort() + if (Out.prototype.properties != null) + propKeys = uniqueSort(Out.prototype.properties.concat(propKeys)) + + oj.addProperty(Out.prototype, 'properties', { + value: propKeys, + writable: false, + enumerable: false + }) + + // Add methods helper to instance + methodKeys = (_keys(args.methods)).sort() + if (Out.prototype.methods != null) + methodKeys = uniqueSort(Out.prototype.methods.concat(methodKeys)) + + oj.addProperty(Out.prototype, 'methods', { + value: methodKeys, + writable: false, + enumerable: false + }) + + // Add methods all oj Types have + _extend(args.methods, { + + // get: Get property by key or get all properties + get: function(k){ + // get specific property + if (oj.isString(k)){ + if (this.has(k)) + return this[k] + // get all properties + } else { + var out = {}, ix, p + for (ix = 0; ix < this.properties.length; ix++){ + p = this.properties[ix]; + out[p] = this[p]; + } + return out + } + }, + + // set: Set property by key, or set all properties with object + set: function(k, v){ + var key, obj = k, value; + + // Optionally take key, value instead of object + if (!oj.isPlainObject(k)){ + obj = {}; + obj[k] = v; + } + + // Set all keys that are valid properties + for (key in obj){ + value = obj[key]; + if (this.has(key)){ + this[key] = value; + } + } + }, + + // has: Determine if property exists + has: function(k){return this.properties.some(function(v){return v === k})}, + + // can: Determine if method exists + can: function(k){return this.methods.some(function(v){return v === k})}, + + // toJSON: Use properties to generate json + toJSON: function(){ + var json = {}, + prop, + ix = 0 + for (;ix < this.properties.length; ix++){ + prop = this.properties[ix] + json[prop] = this[prop] + } + return json + } + }); + + // Add methods + oj.addMethods(Out.prototype, args.methods); + + // Add the properties + oj.addProperties(Out.prototype, args.properties); + return Out; + }; + + // _createQuietType: Takes an OJ Type and creates the _Type that doesn't emit + _createQuietType = function(typeName){ + return oj[_getQuietTagName(typeName)] = function(){ + return _construct.apply(null, [oj[typeName]].concat(slice.call(arguments), [{ + __quiet__: 1 + }])); + } + } + + // oj.createEnum + oj.createEnum = function(name, args){_e('createEnum', 'NYI')} + + // oj.View + oj.View = oj.createType('View', { + + // Views are special objects map properties together. This is a union of arguments + // With the remaining arguments becoming a list + constructor: function(){ + _a(oj.isDOM(this.el), this.typeName, 'constructor did not set this.el') + + // Set instance on @el + _setInstanceOnElement(this.el, this) + + var u = oj.unionArguments(arguments), + options = u.options, + args = u.args + + // Emit as a tag if it isn't quiet or used new keyword + if (this.__autonew__ && !options.__quiet__) + this.emit() + + // Remove quiet flag as it has served its purpose + if (options.__quiet__ != null) + delete options.__quiet__ + + // Add class oj-typeName + this.$el.addClass("oj-" + this.typeName) + + // Views automatically set all options to their properties + // arguments directly to properties + this.set(options) + + // Remove options that were set + options = _clone(options); + this.properties.forEach(function(v){return delete options[v]}) + + // Views pass through remaining options to be attributes on the root element + // This can include jquery events and interpreted arguments + this.addAttributes(options) + + // Record if view is fully constructed + return this._isConstructed = true + }, + properties: { + // The element backing the View + el: { + get: function(){return this._el}, + set: function(v){ + // Set the element directly if this is a dom element + if (oj.isDOMElement(v)){ + this._el = v + // Clear cache of $el + this._$el = null + } else { + // Generate the dom element + this._el = oj.compile({dom:1, css:0, cssMap:0, html:0}, v).dom + } + } + }, + + // Get and cache jquery-enabled element (readonly) + $el: { + get: function(){ + return this._$el != null ? this._$el : (this._$el = oj.$(this.el)) + } + }, + + // Get and set id attribute of view + id: { + get: function(){return this.$el.attr('id')}, + set: function(v){return this.$el.attr('id', v)} + }, + // class: + // get: -> @$el.attr 'class' + // set: (v) -> + // # Join arrays with spaces + // if oj.isArray v + // v = v.join ' ' + // @$el.attr 'class', v + // return + // Alias for classes + // c: + // get: -> @class + // set: (v) -> @class = v; return + // Get all currently set attributes (readonly) + + attributes: { + get: function(){ + var out = {} + slice.call(this.el.attributes).forEach(function(attr){ + return out[attr.name] = attr.value + }) + return out + } + }, + + // Get all classes as an array (readwrite) + classes: { + get: function(){return this.$el.attr('class').split(/\s+/)}, + set: function(v){this.$el.attr('class', v.join(' '))} + }, + + // Get / set all currently set themes (readwrite) + themes: { + get: function(){ + var thms = [], + prefix = 'theme-', + ix = 0, + cls + for (; ix < this.classes.length; ix++){ + cls = this.classes[ix] + if (cls.indexOf(prefix) === 0) + thms.push(cls.slice(prefix.length)) + } + return thms + }, + set: function(v){ + if (!oj.isArray(v)) + v = [v] + this.clearThemes() + var theme, ix = 0 + for (;ix < v.length; ix++){ + theme = v[ix] + this.addTheme(theme) + } + } + }, + theme: { + get: function(){return this.themes}, + set: function(v){this.themes = v} + }, + + // Determine if this view has been fully constructed (readonly) + isConstructed: {get: function(){return _d(this._isConstructed, false)}}, + + // Determine if this view has been fully inserted (readonly) + isInserted: {get: function(){return _d(this._isInserted, false)}} + }, + methods: { + + // $: Find element from within root + $: function(){return this.$el.find.apply(this.$el, arguments)}, + + // addAttribute: Add a single attribute + addAttribute: function(name, value){ + var attr = {} + attr[name] = value + this.addAttributes(attr) + }, + + // addAttributes: Add attributes and apply the oj magic with jquery binding + addAttributes: function(attributes){ + var attr = _clone(attributes), + events = _attributesProcessedForOJ(attr), + k, v + + // Add attributes as object + if (oj.isPlainObject(attr)){ + for (k in attr){ + v = attr[k] + if (k === 'class') + this.addClass(v) + else if (v === true) + // Boolean attributes have no value + this.el.setAttributeNode(document.createAttribute(k)) + else + // Otherwise add it normally + this.$el.attr(k, v) + } + } + + // Bind events + if (events != null) + _attributesBindEventsToDOM(events, this.el) + }, + + // Remove a single attribute + removeAttribute: function(name){this.$el.removeAttr(name)}, + + // Remove multiple attributes + removeAttributes: function(list){var _t = this; list.forEach(function(v){_t.removeAttribute(v)})}, + + // Add a single class + addClass: function(name){this.$el.addClass(name)}, + + // Remove a single class + removeClass: function(name){this.$el.removeClass(name)}, + + // Determine if class is applied + hasClass: function(name){return this.$el.hasClass(name)}, + + // Add a single theme + addTheme: function(name){this.addClass("theme-" + name)}, + + // Remove a single theme + removeTheme: function(name){this.removeClass("theme-" + name)}, + + // Determine if theme is applied + hasTheme: function(name){return this.hasClass("theme-" + name)}, + + // Clear all themes + clearThemes: function(){var _t = this; this.themes.forEach(function(t){_t.removeTheme(t)}) }, + + // emit: Emit instance as a tag function would do + emit: function(){oj._argsAppend(this)}, + + // Convert View to html + toHTML: function(options){ + return this.el.outerHTML + ((options != null ? options.minify : void 0) ? '' : '\n'); + }, + + // Convert View to dom (for compiling) + toDOM: function(){return this.el}, + + // Convert + toCSS: function(options){ + return _cssFromPluginObject(_flattenCSSMap(this.cssMap), _extend({}, { + minify: options.minify, + tags: 0 + })); + }, + + // Convert + toCSSMap: function(){return this.type.cssMap}, + + // Convert View to string (for debugging) + toString: function(){return this.toHTML()}, + + // detach: -> throw 'detach nyi' + // The implementation is to set el manipulate it, and remember how to set it back + + // attach: -> throw 'attach nyi' + // The implementation is to unset el from detach + // inserted is called the instance is inserted in the dom (override) + + inserted: function(){return this._isInserted = true} + } + }); + + + // oj.View.cssMap: remember css for this View + oj.View.cssMap = {} + + // oj.View.css: set view's css with css object mapping, or raw css string + oj.View.css = function(css){ + _a(oj.isString(css) || oj.isPlainObject(css), this.typeName, 'object or string expected for first argument'); + + var cssMap, _base, _base1, _name, _name1, _ref2, _ref3; + + if (oj.isString(css)){ + if ((_ref2 = (_base = this.cssMap)[_name = "oj-" + this.typeName]) == null){ + _base[_name] = ""; + } + this.cssMap["oj-" + this.typeName] += css; + } else { + if ((_ref3 = (_base1 = this.cssMap)[_name1 = "oj-" + this.typeName]) == null){ + _base1[_name1] = {}; + } + cssMap = _setObject({}, ".oj-" + this.typeName, css); + _extend(this.cssMap["oj-" + this.typeName], cssMap); + } + }; + + // oj.View.themes: Remember themes for this View + oj.View.themes = [] + + // oj.View.theme: create a View specific theme with css object mapping + oj.View.theme = function(name, css){ + _v(this.typeName, 1, name, 'string'); + _v(this.typeName, 2, css, 'object'); + + // Calculate styleName + var dashName = _dasherize(name), + styleName = "oj-" + this.typeName, + + // Wrap css in plugin name + cssMap = _setObject({}, ".oj-" + this.typeName + ".theme-" + dashName, css) + + // Extend into this views cssMap + this.cssMap[styleName] = _d(this.cssMap[styleName], {}) + _extend(this.cssMap["oj-" + this.typeName], cssMap) + + // Remember the theme item + this.themes.push(dashName) + this.themes = uniqueSort(this.themes) + }; + + // oj.CollectionView: Inheritable base type that enables two-way collection binding + oj.CollectionView = oj.createType('CollectionView', { + base: oj.View, + constructor: function(options){ + if ((options != null ? options.each : void 0) != null) + this.each = oj.argumentShift(options, 'each') + + if ((options != null ? options.models : void 0) != null) + this.models = oj.argumentShift(options, 'models') + + oj.CollectionView.base.constructor.apply(this, arguments); + + // Once everything is constructed call make precisely once. + return this.make() + }, + properties: { + each: { + get: function(){return this._each}, + set: function(v){ + this._each = v + if (this.isConstructed) + this.make() + } + }, + collection: { + get: function(){return this.models}, + set: function(v){return this.models = v} + }, + models: { + get: function(){return this._models}, + set: function(v){ + // Unbind events if collection + if (oj.isFunction(this._models != null ? this._models.off : void 0)) + this._models.off('add remove change reset destroy', null, this) + + this._models = v + + // Bind events if collection + if (oj.isFunction(this._models != null ? this._models.on : void 0)){ + this._models.on('add', this.collectionModelAdded, this) + this._models.on('remove', this.collectionModelRemoved, this) + this._models.on('change', this.collectionModelChanged, this) + this._models.on('destroy', this.collectionModelDestroyed, this) + this._models.on('reset', this.collectionReset, this) + } + if (this.isConstructed) + this.make() + } + } + }, + methods: { + + // Override make to create your view + make: function(){_e(this.typeName, '`make` method not implemented by custom view')}, + + // Override these events to minimally update on change + collectionModelAdded: function(mod, cols){return this.make()}, + collectionModelRemoved: function(mod, cols, opt){return this.make()}, + collectionModelChanged: function(mod, cols, opt){}, + collectionModelDestroyed: function(cols, opt){return this.make()}, + collectionReset: function(cols, opt){return this.make()} + } + }); + + // oj.ModelView: Inheritable base type that enables two-way model binding + oj.ModelView = oj.createType('ModelView', { + base: oj.View, + constructor: function(options){ + if ((options != null ? options.value : void 0) != null) + this.value = oj.argumentShift(options, 'value') + + if ((options != null ? options.model : void 0) != null) + this.model = oj.argumentShift(options, 'model') + + return oj.ModelView.base.constructor.apply(this, arguments) + }, + properties: { + model: { + get: function(){ + return this._model + }, + set: function(v){ + // Unbind events on the old model + if (oj.isEvented(this._model)) + this._model.off('change', null, this); + + this._model = v + + // Bind events on the new model + if (oj.isEvented(this._model)) + this._model.on('change', this.modelChanged, this); + + // Trigger change manually when settings new model + this.modelChanged() + } + } + }, + methods: { + + // Override modelChanged if you don't want a full remake + modelChanged: function(){ + var _t = this; + return this.$el.oj(function(){ + return _t.make(_t.mode) + }); + }, + make: function(model){ + return _e(this.typeName, '`make` method not implemented by custom view'); + } + } + }); + + // oj.ModelViewView: Inheritable base type that enables two-way model binding to a specific key + oj.ModelKeyView = oj.createType('ModelKeyView', { + + // Inherit ModelView to handle model and bindings + base: oj.ModelView, + constructor: function(options){ + + if ((options != null ? options.key : void 0) != null) + this.key = oj.argumentShift(options, 'key') + + // Call super to bind model and value + return oj.ModelKeyView.base.constructor.apply(this, arguments); + }, + properties: { + // Key used to access model + key: null, + + // Override this property and call this.viewChanged when appropriate + value: { + get: function(){_e(this.typeName, 'value getter not implemented')}, + set: function(v){_e(this.typeName, 'value setter not implemented')} + } + }, + + methods: { + + // modelChanged: called by model binding code to + // automatically set this.value when the model changes + modelChanged: function(){ + if ((this.model != null) && (this.key != null)){ + // Update the view if necessary + if (!this._viewUpdatedModel) + this.value = this.model.get(this.key) + } + }, + + // viewChanged: Will set the model whenever this.value is set + viewChanged: function(){ + var _t = this + + // Briefly delay view changes because they often change before + // the controls visually update + setTimeout((function(){ + if ((_t.model != null) && (_t.key != null)){ + // Ensure view changes aren't triggered twice + _t._viewUpdatedModel = true + _t.model.set(_t.key, _t.value) + _t._viewUpdatedModel = false + } + }), 10) + } + } + }); + + // oj.TextBox + oj.TextBox = oj.createType('TextBox', { + base: oj.ModelKeyView, + constructor: function(){ + var _t = this, + u = oj.unionArguments(arguments), + options = u.options, + args = u.args + + this.el = oj(function(){ + oj.input({type: 'text'}, { + // When live changes are set indicate change on every keypress + // Delay change events slighty as value is visually updated after key presses + keydown: function(){ + if (_t.live) + setTimeout((function(){return _t.$el.change()}), 10) + }, + keyup: function(){ + if (_t.live) + setTimeout((function(){return _t.$el.change()}), 10) + }, + change: function(){_t.viewChanged()} + }) + }) + + // Value can be set by argument + if (args.length > 0) + this.value = args[0] + + // Set live if it exists + if ((options != null ? options.live : void 0) != null) + this.live = oj.argumentShift(options, 'live') + + return oj.TextBox.base.constructor.apply(this, [options]) + }, + properties: { + value: { + get: function(){ + var v = this.el.value + if ((v == null) || v === _udf) + v = '' + return v + }, + set: function(v){this.el.value = v} + }, + + // Live update model as text changes + live: true + } + }); + + // oj.CheckBox + oj.CheckBox = oj.createType('CheckBox', { + base: oj.ModelKeyView, + constructor: function(){ + var _t = this, + u = oj.unionArguments(arguments), + options = u.options, + args = u.args + + this.el = oj(function(){ + oj.input({type: 'checkbox'}, { + change: function(){_t.viewChanged()} + }) + }) + + // Value can be set by argument + if (args.length > 0) + this.value = args[0] + + return oj.CheckBox.base.constructor.call(this, options); + }, + properties: { + value: { + get: function(){return this.el.checked}, + set: function(v){ + this.el.checked = v = !!v + if (v) + this.$el.attr('checked', 'checked') + else + this.$el.removeAttr('checked') + } + } + } + }); + + // oj.Text + oj.Text = oj.createType('Text', { + base: oj.ModelKeyView, + constructor: function(){ + var _t = this, + u = oj.unionArguments(arguments), + options = u.options, + args = u.args + + // Get tag name if provided + this._tagName = oj.argumentShift(options, 'tagName') + + // Create element with tagName + this.el = oj(function(){ + return oj[_t.tagName]() + }); + + // Value can be set by argument + if (args.length > 0) + this.value = args[0] + + return oj.Text.base.constructor.call(this, options); + }, + + properties: { + // value: text value of this object (readwrite) + value: { + get: function(){return this.$el.ojValue()}, + set: function(v){this.$el.oj(v)} + }, + + // tagName: name of root tag (writeonce) + tagName: {get: function(){return _d(this._tagName, 'div')}} + } + }); + + // oj.TextArea + oj.TextArea = oj.createType('TextArea', { + base: oj.ModelKeyView, + constructor: function(){ + var _t = this, + u = oj.unionArguments(arguments), + options = u.options, + args = u.args + + this.el = oj(function(){ + return oj.textarea({ + // When live changes are set indicate change on every keypress + // Delay change events slighty as value is visually updated after key presses + keydown: function(){ + if (_t.live) + setTimeout((function(){return _t.$el.change()}), 10) + }, + keyup: function(){ + if (_t.live) + setTimeout((function(){return _t.$el.change()}), 10) + }, + change: function(){ + _t.viewChanged() + } + }); + }); + + // Value can be set by argument + this.value = oj.argumentShift(options, 'value') || args.join('\n') + return oj.TextArea.base.constructor.call(this, options) + }, + properties: { + value: { + get: function(){return this.el.value}, + set: function(v){this.el.value = v} + }, + + // Live update model as text changes + live: true + } + }); + + // oj.ListBox + oj.ListBox = oj.createType('ListBox', { + base: oj.ModelKeyView, + constructor: function(){ + var _t = this, + u = oj.unionArguments(arguments), + options = u.options, + args = u.args + + this.el = oj(function(){ + return oj.select({ + change: function(){_t.viewChanged()} + }) + }) + + // @options is a list of elements + this.options = oj.argumentShift(options, 'options'); + + // Value can be set by argument + if (args.length > 0) + this.value = args[0] + + return oj.ListBox.base.constructor.apply(this, [options]); + }, + properties: { + value: { + get: function(){ + return this.$el.val(); + }, + set: function(v){ + this.$el.val(v); + } + }, + options: { + get: function(){ + return this._options; + }, + set: function(v){ + if (!oj.isArray(v)){ + throw new Error("oj." + this.typeName + ".options array is missing"); + } + this._options = v; + this.$el.oj(function(){ + var op, _j, _len1; + + for (_j = 0, _len1 = v.length; _j < _len1; _j++){ + op = v[_j]; + oj.option(op); + } + }); + } + } + } + }); + + // oj.Button + oj.Button = oj.createType('Button', { + base: oj.View, + constructor: function(){ + var _t = this, + u = oj.unionArguments(arguments), + options = u.options, + args = u.args, + + // Label is first argument + title = '' + if (args.length > 0) + title = args[0] + + // Label is specified as option + if (options.title != null) + title = oj.argumentShift(options, 'title') + + // Create element + this.el = oj(function(){return oj.button(title)}) + + oj.Button.base.constructor.apply(this, [options]); + return this.title = title; + }, + properties: { + title: { + get: function(){return _d(this._title, '')}, + set: function(v){this.$el.oj((this._title = v))} + } + }, + methods: { + click: function(){ + if (arguments.length > 0) + return this.$el.click.apply(this.$el, arguments) + else + return this.$el.click() + } + } + }); + + // oj.List: List control with two-way collection binding + oj.List = oj.createType('List', { + base: oj.CollectionView, + constructor: function(){ + var _t = this, + u = oj.unionArguments(arguments), + options = u.options, + args = u.args, + items + + // tagName is write-once + this._tagName = oj.argumentShift(options, 'tagName') + this.itemTagName = oj.argumentShift(options, 'itemTagName') + + // Create the root element + this.el = oj(function(){return oj[_t.tagName]()}); + + // Use el if it was passed in + if (options.el != null) + this.el = oj.argumentShift(options, 'el') + + // Default @each function to pass through values + if (options.each == null){ + options.each = function(model){ + if (oj.isString(model) || oj.isNumber(model) || oj.isBoolean(model)) + return model + else + return JSON.stringify(model) + } + } + + // Args have been handled so don't pass them on + oj.List.base.constructor.apply(this, [options]); + + // Set @items to options or args if they exist + items = args.length > 0 ? args : null; + return this.items = options.items != null ? oj.argumentShift(options, 'items') : items; + }, + + properties: { + // items: get or set all items at once (readwrite) + items: { + get: function(){ + // Found in cache + if (this._items != null) + return this._items + + // Calc from ojValues + return this.$items.ojValues() + }, + set: function(v){ + this._items = v + this.make() + } + }, + count: {get: function(){return this.$items.length}}, + + // tagName: name of root tag (writeonce) + tagName: {get: function(){return _d(this._tagName, 'div')}}, + + // itemTagName: name of item tags (readwrite) + itemTagName: { + get: function(){return _d(this._itemTagName, 'div')}, + set: function(v){this._itemTagName = v; this.make();} + }, + + // $items: list of `
                        • ` elements (readonly) + $items: { + get: function(){ + // Get from cache or cache the recalculated list + return this._$items != null ? this._$items : this._$items = this.$("> " + this.itemTagName) + } + } + }, + + methods: { + // item: get or set item value at item ix + item: function(ix, ojml){ + ix = this._bound(ix, this.count, ".item: index") + if (ojml != null) + this.$item(ix).oj(ojml) + else + return this.$item(ix).ojValue() + }, + + // $item: `
                        • ` element for a given item ix. The tag name may change. + $item: function(ix){return this.$items.eq(this._bound(ix, this.count, ".$item: index"))}, + + // make: Remake view from model data using each + make: function(){ + // Do nothing until fully constructed + if (!this.isConstructed) + return + + // Some properties call make before construction completes + var _t = this, ix, model, models, views, out + + // Convert models to views using each + if ((this.models != null) && (this.each != null)){ + + // Get list of models from collection or array + models = oj.isEvented(this.models) ? this.models.models : this.models; + + // Add view item for every model + views = models.map(function(model){return _t._itemFromModel(model)}) + + // Items are already views so just use them + } else if (this.items != null) { + views = this.items + } + + // Render the views + this.$el.oj(function(){return views.map(function(view){_t._itemElFromItem(view)}) }) + + // Indicate to CollectionView the items changed + this.itemsChanged() + }, + + // collectionModelAdded: Model add occurred, add the item + collectionModelAdded: function(m, c){this.add(c.indexOf(m), this._itemFromModel(m))}, + + // collectionModelRemoved: Model remove occured, delete the item + collectionModelRemoved: function(m, c, o){this.remove(o.index)}, + + // collectionModelRemoved: Model reset occured, full rebuild + collectionReset: function(){this.make()}, + + // Helper Methods + // _itemFromModel: Helper to map model to item + _itemFromModel: function(model){ + var _t = this; + return oj(function(){return _t.each(model)}); + }, + + // _itemElFromItem: Helper to create itemTagName wrapped item + _itemElFromItem: function(item){ + return oj[this.itemTagName](item); + }, + + // _bound: Bound index to allow negatives, throw when out of range + _bound: function(ix, count, message){ + var ixNew = ix < 0 ? ix + count : ix + if (!(0 <= ixNew && ixNew < count)) + _e(this.typeName, message + " is out of bounds (" + ix + " in [0," + (count - 1) + "])") + return ixNew + }, + + // itemsChanged: Model changed occured, clear relevant cached values + itemsChanged: function(){this._items = null; this._$items = null}, + + // Manipulation Methods + add: function(ix, ojml){ + // ix defaults to -1 and is optional + if (ojml == null){ + ojml = ix + ix = -1 + } + + ix = this._bound(ix, this.count + 1, ".add: index") + var tag = this.itemTagName + + // Empty + if (this.count === 0) + this.$el.oj(function(){return oj[tag](ojml)}) + + // Last + else if (ix === this.count) + this.$item(ix - 1).ojAfter(function(){return oj[tag](ojml)}) + + // Not last + else + this.$item(ix).ojBefore(function(){return oj[tag](ojml)}) + + this.itemsChanged() + }, + + remove: function(ix){ + ix = _d(ix,-1) + ix = this._bound(ix, this.count, ".remove: index") + var out = this.item(ix) + this.$item(ix).remove() + this.itemsChanged() + return out + }, + + move: function(ixFrom, ixTo){ + ixTo = _d(ixTo, -1) + if (ixFrom === ixTo) + return + ixFrom = this._bound(ixFrom, this.count, ".move: fromIndex") + ixTo = this._bound(ixTo, this.count, ".move: toIndex") + if (ixTo > ixFrom) + this.$item(ixFrom).insertAfter(this.$item(ixTo)) + else + this.$item(ixFrom).insertBefore(this.$item(ixTo)) + this.itemsChanged() + }, + swap: function(ix1, ix2){ + if (ix1 === ix2) + return + ix1 = this._bound(ix1, this.count, ".swap: firstIndex"); + ix2 = this._bound(ix2, this.count, ".swap: secondIndex"); + if (Math.abs(ix1 - ix2) === 1) + this.move(ix1, ix2) + else { + var ixMin = Math.min(ix1, ix2), + ixMax = Math.max(ix1, ix2) + this.move(ixMax, ixMin) + this.move(ixMin + 1, ixMax) + } + this.itemsChanged() + }, + unshift: function(v){this.add(0, v)}, + shift: function(){return this.remove(0)}, + push: function(v){this.add(this.count, v)}, + pop: function(){return this.remove(-1)}, + clear: function(){this.$items.remove(); this.itemsChanged()} + } + }); + + + // oj.NumberList: NumberList is a `List` specialized with `
                            ` and `
                          1. ` tags + oj.NumberList = oj.createType('NumberList', { + base: oj.List, + constructor: function(){ + var args = [{tagName:'ol', itemTagName:'li'}].concat(slice.call(arguments)) + return oj.NumberList.base.constructor.apply(this, args) + } + }) + + // oj.BulletList: BulletList is a `List` specialized with `
                              ` and `
                            • ` tags + oj.BulletList = oj.createType('BulletList', { + base: oj.List, + constructor: function(){ + var args = [{tagName:'ul', itemTagName:'li'}].concat(slice.call(arguments)) + return oj.BulletList.base.constructor.apply(this, args) + } + }) + + // oj.Table + oj.Table = oj.createType('Table', { + base: oj.CollectionView, + constructor: function(){ + var _t = this, + u = oj.unionArguments(arguments), + options = u.options, + args = u.args, + rows, ix + + // Generate root + this.el = oj(function(){return oj.table()}) + + // Use el if it was passed in + if (options.el != null) + this.el = oj.argumentShift(options, 'el') + + // Default @each function to pass through values + if (options.each == null){ + options.each = function(model, cell){ + var values = (oj.isString(model)) || (oj.isNumber(model)) || (oj.isBoolean(model)) ? [model] : (oj.isEvented(model)) && typeof model.attributes === 'object' ? _values(model.attributes) : _values(model) + return values.map(function(v){cell(v)}); + }; + } + + // Args have been handled so don't pass them on + oj.Table.base.constructor.apply(this, [options]); + + // Validate args as arrays + for(ix = 0; ix < args.length; ix++) + _a(oj.isArray(args[ix]), 'Table', 'array expected for row arguments') + + // Set @rows to options or args if they exist + rows = _d(oj.argumentShift(options, 'rows'), args) + if (rows.length > 0) + return this.rows = rows + }, + properties: { + + // rowCount: The number of rows (readonly) + rowCount: {get: function(){return this.$trs.length}}, + + // columnCount: The number of columns (readonly) + columnCount: {get: function(){ + // The number of columns is number of `` in rows, header, or footer + var tflen, thlen, trlen + if ((trlen = this.$tr(0).find('> td').length) > 0) + return trlen + else if ((thlen = this.$theadTR.find('> th').length) > 0) + return thlen + else if ((tflen = this.$tfootTR.find('> td').length) > 0) + return tflen + return 0 + }}, + + // rows: Row values as a list of lists as interpreted by ojValue plugin (readwrite) + rows: { + get: function(){ + // Get cached result + if (this._rows != null) + return this._rows + + // Calculate rows by mapping from td to ojValue + var r, rx = 0 + this._rows = [] + for (; rx < this.rowCount; rx++){ + r = this.$tdsRow(rx).toArray().map(function(el){return $(el).ojValue()}) + this._rows.push(r); + } + return this._rows + }, + set: function(list){ + if (!((list != null) && list.length > 0)) + return this.clearBody() + this._rows = list + this.make() + } + }, + + // header: Array of header values as interpreted by ojValue plugin (readwrite) + header: { + get: function(){return this.$theadTR.find('> th').ojValues()}, + set: function(list){ + _a(oj.isArray(list), this.typeName + '.header', 'array expected for first argument') + + if (!((list != null) && list.length > 0)) + return this.clearHeader() + + return this.$theadTRMake.oj(function(){ + return list.map(function(ojml){oj.th(ojml)}) + }); + } + }, + + // footer: Array of footer values as interpreted by ojValue plugin (readwrite) + footer: { + get: function(){ + return this.$tfootTR.find('> td').ojValues(); + }, + set: function(list){ + var _t = this; + + if (!oj.isArray(list)){ + throw new Error('oj.Table.footer: array expected for first argument'); + } + if (!((list != null) && list.length > 0)){ + return this.clearFooter(); + } + return this.$tfootTRMake.oj(function(){ + var ojml, _j, _len1, _results; + + _results = []; + for (_j = 0, _len1 = list.length; _j < _len1; _j++){ + ojml = list[_j]; + _results.push(oj.td(ojml)); + } + return _results; + }); + } + }, + + // caption: The table caption (readwrite) + caption: { + get: function(){return this.$caption.ojValue()}, + set: function(v){this.$captionMake.oj(v)} + }, + + // Element accessors + $table: {get: function(){return this.$el}}, + $caption: {get: function(){return this.$('> caption')}}, + $colgroup: {get: function(){return this.$('> colgroup')}}, + $thead: {get: function(){return this.$('> thead')}}, + $tfoot: {get: function(){return this.$('> tfoot')}}, + $tbody: {get: function(){return this.$('> tbody')}}, + $theadTR: {get: function(){return this.$thead.find('> tr')}}, + $tfootTR: {get: function(){return this.$tfoot.find('> tr')}}, + $ths: {get: function(){return this.$theadTR.find('> th')}}, + $trs: {get: function(){ + // Cache or calculate + return this._$trs != null ? this._$trs : this._$trs = this.$("> tbody > tr") + }}, + + // Table tags must have an order: `` `` `` `` `` + // These accessors create table tags and preserve this order very carefully + // $colgroupMake: get or create `` after `` or prepended to `` + + $colgroupMake: {get: function(){ + if (this.$colgroup.length > 0) + return this.$colgroup + t = '' + if (this.$caption.length > 0) + this.$caption.insertAfter(t) + else + this.$table.append(t) + return this.$tbody + }}, + + // $captionMake: get or create `
                              ` prepended to `` + $captionMake: { + get: function(){ + if (this.$caption.length > 0) + return this.$caption + this.$table.prepend('') + return this.$caption + } + }, + + // $tfootMake: get or create `` before `` or appended to `
                              ` + $tfootMake: { + get: function(){ + if (this.$tfoot.length > 0) + return this.$tfoot + t = '' + if (this.$tfoot.length > 0) + this.$tfoot.insertBefore(t) + else + this.$table.append(t) + + return this.$tfoot + } + }, + + // $theadMake: get or create `` after `` or after `
                              `, or prepended to `` + $theadMake: { + get: function(){ + if (this.$thead.length > 0) + return this.$thead + t = '' + if (this.$colgroup.length > 0) + this.$colgroup.insertAfter(t); + else if (this.$caption.length > 0) + this.$caption.insertAfter(t) + else + this.$table.prepend(t) + return this.$thead + } + }, + + // $tbodyMake: get or create `` appened to `
                              ` + $tbodyMake: { + get: function(){ + if (this.$tbody.length > 0) + return this.$tbody + this.$table.append('') + return this.$tbody; + } + }, + + // $theadTRMake: get or create `` inside of `` + $theadTRMake: { + get: function(){ + if (this.$theadTR.length > 0) + return this.$theadTR + this.$theadMake.html('') + return this.$theadTR + } + }, + + // $tfootTRMake: get or create `` inside of `` + $tfootTRMake: { + get: function(){ + if (this.$tfootTR.length > 0) + return this.$tfootTR + this.$tfootMake.html('') + return this.$tfootTR + } + } + }, + + methods: { + + // make: Remake everything (override) + make: function(){ + if (!this.isConstructed) + return + + // Some properties call make before construction completes + var _t = this, models, rowViews = [] + + // Convert models to views if model/each exists + if ((this.models != null) && (this.each != null)){ + models = oj.isEvented(this.models) ? this.models.models : this._models + rowViews = models.map(function(model){return _t._rowFromModel(model)}) + // Convert rows to views + } else if (this.rows != null){ + rowViews = this.rows.map(function(row){ + return oj(function(){ + row.forEach(function(cell){oj.td(cell)}) + }) + }) + } + + // Render rows into tbody + if (rowViews.length > 0) + this.$tbodyMake.oj(function(){ + rowViews.forEach(function(r){ + oj.tr(r) + }) + }) + + this.bodyChanged() + }, + + collectionModelAdded: function(m, c){ + var rx = c.indexOf(m), + row = this._rowFromModel(m) + this._addRowTR(rx, oj(function(){ + return oj.tr(row) + })) + }, + + collectionModelRemoved: function(m, c, o){this.removeRow(o.index)}, + + collectionReset: function(){this.make()}, + + // $tr: Get `` jquery element at row rx + $tr: function(rx){ + rx = rx < 0 ? rx + count : rx + return this.$trs.eq(rx) + }, + + // $tdsRow: Get list of `` + _addRowTR: function(rx, tr){ + // Empty + if (this.rowCount === 0) + this.$el.oj(tr) + + // Last + else if (rx === this.rowCount) + this.$tr(rx - 1).ojAfter(tr) + + // Not last + else + this.$tr(rx).ojBefore(tr) + + this.bodyChanged() + }, + + // removeRow: Remove row at index rx (defaults to end) + removeRow: function(rx){ + if (rx == null) + rx = -1 + rx = this._bound(rx, this.rowCount, ".removeRow: index"); + var out = this.row(rx) + this.$tr(rx).remove() + this.bodyChanged() + return out + }, + + // moveRow: Move row at index rx (defaults to end) + moveRow: function(rxFrom, rxTo){ + if (rxFrom === rxTo) + return + + rxFrom = this._bound(rxFrom, this.rowCount, ".moveRow: fromIndex") + rxTo = this._bound(rxTo, this.rowCount, ".moveRow: toIndex") + var insert = rxTo > rxFrom ? 'insertAfter' : 'insertBefore' + this.$tr(rxFrom)[insert](this.$tr(rxTo)) + this.bodyChanged(); + }, + + // swapRow: Swap row rx1 and rx2 + swapRow: function(rx1, rx2){ + if (rx1 === rx2) + return + rx1 = this._bound(rx1, this.rowCount, ".swap: firstIndex"); + rx2 = this._bound(rx2, this.rowCount, ".swap: secondIndex"); + if (Math.abs(rx1 - rx2) === 1) + this.moveRow(rx1, rx2) + else { + var rxMin = Math.min(rx1, rx2), + rxMax = Math.max(rx1, rx2) + this.moveRow(rxMax, rxMin); + this.moveRow(rxMin + 1, rxMax); + } + this.bodyChanged(); + }, + unshiftRow: function(v){this.addRow(0, v)}, + shiftRow: function(){return this.removeRow(0)}, + pushRow: function(v){this.addRow(this.rowCount, v)}, + popRow: function(){return this.removeRow(-1)}, + clearColgroup: function(){this.$colgroup.remove()}, + clearBody: function(){ + this.$tbody.remove(); + this.bodyChanged(); + }, + clearHeader: function(){ + this.$thead.remove(); + this.headerChanged(); + }, + clearFooter: function(){ + this.$tfoot.remove(); + this.footerChanged(); + }, + clearCaption: function(){ + this.$capation.remove(); + }, + clear: function(){ + this.clearBody(); + this.clearHeader(); + this.clearFooter(); + return this.$caption.remove(); + }, + + // When body changes clear relevant cached values + bodyChanged: function(){this._rows = null; this._columns = null; this._$trs = null}, + + // When header changes clear relevant cached values + headerChanged: function(){this._header = null}, + + // When footer changes clear relevant cached values + footerChanged: function(){this._footer = null}, + + // _rowFromModel: Helper to map model to row + _rowFromModel: function(model){ + var _t = this; + return oj(function(){ + return _t.each(model, oj.td); + }); + }, + + // _bound: Bound index to allow negatives, throw when out of range + _bound: function(ix, count, message){ + var ixNew = ix < 0 ? ix + count : ix + if (!(0 <= ixNew && ixNew < count)){ + throw new Error("oj." + this.typeName + message + " is out of bounds (" + ix + " in [0," + (count - 1) + "])"); + } + return ixNew; + } + } + }); + + // Create Quiet _Types + for (var typeName in oj){ + // Type with captital first letter that doesn't end in "View" + if (_isCapitalLetter(typeName[0]) && typeName.slice(typeName.length - 4) !== 'View'){ + oj[_getQuietTagName(typeName)] = _createQuietType(typeName); + } + } + + // oj.sandbox: The sandbox is a readonly version of oj exposed to the user when templating server-side + oj.sandbox = {}; + _keys(oj).forEach(function(key){ + if ((key.length > 0 && key[0] !== '_') || (key.length > 0 && key[0] === '_' && (oj[key.slice(1)] != null))){ + oj.addProperty(oj.sandbox, key, {value: oj[key], writable: false}); + } + }) + + // oj.use(plugin, settings): import a plugin of OJ with optional settings + oj.use = function(plugin, settings){ + settings = _d(settings, {}) + _v('use', 1, plugin, 'function') + _v('use', 2, settings, 'object') + + // Call plugin to gather extension map + var pluginResult = plugin(oj, settings), + pluginMap = _clone(pluginResult), + name, value + + // Add _Type quiet types + for (name in pluginResult){ + value = pluginResult[name] + if (oj.isOJType(value)) + pluginMap[_getQuietTagName(name)] = _createQuietType(value.typeName); + } + + // Extend all properties + for (name in pluginMap){ + value = pluginMap[name] + + // Add to oj + oj[name] = value + + // Add plugin to sandbox + oj.addProperty(oj.sandbox, name, {value: value, writable: false}) + } + }; + + // _jqExtend(fn): Create a jquery plugin with the following options: + // option.get is called to retrieve value per element + // option.set is called when setting elements + // option.first:true means return only the first get, + // otherwise it is returned as an array + function _jqExtend(options){ + if (options == null) + options = {} + + options = _extend({ + get: pass, + set: pass, + first: false + }, options) + + return function(){ + var el, out, r, ix, + args = _toArray(arguments), + $els = jQuery(this) + + // Map over jquery selection if no arguments + if ((oj.isFunction(options.get)) && args.length === 0){ + out = [] + for (ix = 0; ix < $els.length; ix++){ + el = $els[ix]; + out.push(options.get(oj.$(el))) + if (options.first) + return out[0] + } + return out + } else if (oj.isFunction(options.set)){ + + // By default return this for chaining + out = $els; + for (ix = 0; ix < $els.length; ix++){ + el = $els[ix] + r = options.set(oj.$(el), args) + // Short circuit if anything is returned + if (r != null) + return r + } + return $els + } + }; + }; + + function _triggerInserted(types, inserts){ + var ix = 0 + for (; ix < types.length; ix++) + types[ix].inserted() + if(inserts) { + for (ix = 0; ix < inserts.length; ix++) + inserts[ix]() + } + } + + function _insertStyles(pluginMap, options){ + var mediaMap, plugin + for (plugin in pluginMap){ + mediaMap = pluginMap[plugin] + + // Skip global css if options.global is true + if (plugin === 'oj-style' && !(options != null ? options.global : 0)) + continue + + // Create "+o);return f}function Q(e,t,n){var r=n.indent;n.indent+=" ",e(t,n),n.indent=r}function G(e,t){if(l.isArray(e))Y(e,t);else if(l.isString(e)){t.html!=null&&t.html.push(e);if(e.length>0&&e[0]==="<"){var n=document.createElement("div");n.innerHTML=e,t.dom!=null&&t.dom.appendChild(n)}else t.dom!=null&&t.dom.appendChild(document.createTextNode(e))}else l.isBoolean(e)||l.isNumber(e)?(t.html!=null&&t.html.push(""+e),t.dom!=null&&t.dom.appendChild(document.createTextNode(""+e))):l.isFunction(e)?G(l(e),t):l.isDate(e)?(t.html!=null&&t.html.push(""+e.toLocaleString()),t.dom!=null&&t.dom.appendChild(document.createTextNode(""+e.toLocaleString()))):l.isOJ(e)&&(t.types!=null&&t.types.push(e),t.html!=null&&t.html.push(e.toHTML(t)),t.dom!=null&&t.dom.appendChild(e.toDOM(t)),t.css!=null&&d(t.css,e.toCSSMap(t)))}function Y(e,t){if(e.length===0)return;var n=e[0],r=typeof n,i=l.unionArguments(e.slice(1)),s=i.options,o=i.args,u,a;if(r==="function"||r==="object")n=x(_(n),n);l.isString(n)&&n.length>0||T("compile","tag name is missing"),t.tags[n]=!0;if(v(n[0]))return Q(G,new l[n](e.slice(1)),t);if(t.css&&n==="css")for(a in s)u=s[a],t.css.oj=x(t.css.oj,{}),t.css.oj[a]=x(t.css.oj[a],{}),d(t.css.oj[a],u);if(n==="!DOCTYPE"){C("compile",1,e[1],"string"),t.ignore[n]||t.html&&t.html.push("<"+n+" "+e[1]+">");return}if(!t.ignore[n]){var f=Z(s),c;if(t.dom&&typeof document!="undefined"&&document!==null){c=document.createElement(n),l.isDOMElement(t.dom)&&t.dom.appendChild(c),t.dom=c;if(l.isPlainObject(s)){var h=p(s).sort(),m,g,y;for(m=0;m")}}if(t.ignore[n]!=="deep")for(m=0;m1&&t.html.push("\n "+t.indent),Q(G,E,t)}t.html!=null&&!t.minify&&o.length>1&&t.html.push("\n"+t.indent),t.ignore[n]||(t.html!=null&&(o.length>0||l.tag.isClosed(n))&&t.html.push(""),t.dom&&(t.dom=t.dom.parentNode))}function Z(e){var t={bind:1,on:1,off:1,live:1,blur:1,change:1,click:1,dblclick:1,focus:1,focusin:1,focusout:1,hover:1,keydown:1,keypress:1,keyup:1,mousedown:1,mouseenter:1,mouseleave:1,mousemove:1,mouseout:1,mouseup:1,ready:1,resize:1,scroll:1,select:1,insert:1},n,r,i;l.isArray(e!=null?e.c:void 0)&&(e.c=e.c.join(" ")),l.isArray(e!=null?e["class"]:void 0)&&(e["class"]=e["class"].join(" ")),(e!=null?e.c:void 0)!=null&&((e!=null?e["class"]:void 0)!=null?e["class"]+=" "+e.c:e["class"]=e.c,delete e.c),l.isPlainObject(e!=null?e.style:void 0)&&(e.style=U(e.style,{inline:!0}));if(l.isPlainObject(e))for(r in e)i=e[r],(i===null||i===void 0||i===!1)&&delete e[r];n={};if(l.isPlainObject(e))for(r in e)i=e[r],t[r]!=null&&(n[r]=i,delete e[r]);return n}function et(e,t,n){console.log("inserts: ",n);var r,i,s=[];for(r in e)i=e[r],N(l.$!=null,"jquery is missing when binding a '"+r+"' event"),r=="insert"&&n?(console.log("load event found"),console.log("ev: ",i),n.push(function(){console.log("calling onload"),i.call(t,t)})):l.isArray(i)?s.push(l.$(t)[r].apply(this,i)):s.push(l.$(t)[r](i));return s}function tt(e,t){var n,r;for(r in t)l.copyProperty(e,t,r);n=function(){},n.prototype=t.prototype,e.prototype=new n,e.base=e.__super__=t.prototype}function nt(e){return new(r.bind.apply(e,arguments))}function it(e){return e==null&&(e={}),e=d({get:a,set:a,first:!1},e),function(){var t,n,r,i,s=y(arguments),o=jQuery(this);if(l.isFunction(e.get)&&s.length===0){n=[];for(i=0;i=0)i=e[r],i==="."?e.splice(r,1):i===".."?(e.splice(r,1),n++):n&&(e.splice(r,1),n--),r--;if(t)while(n--)e.unshift("..");return e}var e=this,n=Array.prototype,r=Function.prototype,i=Object.prototype,s=n.slice,o=n.unshift,u=n.concat,a=function(e){return e},f="undefined";l.version="0.2.0",l.isClient=!(typeof process!="undefined"&&process!==null?process.versions!=null?process.versions.node:0:0);if(typeof $!=f)l.$=$;else if(typeof require!=f)try{l.$=require("jquery")}catch(c){}typeof require!=f?module.exports=l:e.oj=l,l.oj=l,l.load=function(e){return l.$(function(){return l.$.ojBody(require(e)),l.onload()})};var h={queue:[],loaded:!1};l.onload=function(e){if(l.isUndefined(e)){h.loaded=!0;while(e=h.queue.shift())e()}else h.loaded?e():h.queue.push(e)},l.emit=function(){return l.tag.apply(l,["oj"].concat(s.call(arguments)))},l.isDefined=function(e){return typeof e!==f},l.isOJ=function(e){return e!=null?!!e.isOJ:!!void 0},l.isOJType=function(e){return l.isOJ(e)&&e.type===e},l.isOJInstance=function(e){return l.isOJ(e)&&!l.isOJType(e)},l.isEvented=function(e){return!!(e&&e.on&&e.off&&e.trigger)},l.isDOM=function(e){return!!e&&e.nodeType!=null},l.isDOMElement=function(e){return!!e&&e.nodeType===1},l.isDOMAttribute=function(e){return!!e&&e.nodeType===2},l.isDOMText=function(e){return!!e&&e.nodeType===3},l.isjQuery=function(e){return!!e&&!!e.jquery},l.isUndefined=function(e){return e===void 0},l.isBoolean=function(e){return e===!0||e===!1||i.toString.call(e)==="[object Boolean]"},l.isNumber=function(e){return!!(e===0||e&&e.toExponential&&e.toFixed)},l.isString=function(e){return!!(e===""||e&&e.charCodeAt&&e.substr)},l.isDate=function(e){return!!(e&&e.getTimezoneOffset&&e.setUTCFullYear)},l.isPlainObject=function(e){return l.$.isPlainObject(e)&&!l.isOJ(e)},l.isFunction=l.$.isFunction,l.isArray=l.$.isArray,l.isRegEx=function(e){return i.toString.call(e)==="[object RegExp]"},l.isArguments=function(e){return i.toString.call(e)==="[object Arguments]"},l.parse=function(e){var t,n=e;return e===f?n=void 0:e==="null"?n=null:e==="true"?n=!0:e==="false"?n=!1:isNaN(t=parseFloat(e))||(n=t),n},l.unionArguments=function(e){var t={},n=[],r,i=0;for(;i'+r+i+""},l.toHTML=function(e,t){return l.isPlainObject(e)||(t=e,e={}),d(e,{dom:0,js:0,html:1,css:0}),l.compile(e,t).html},l.toCSS=function(e,t){return l.isPlain(e)||(t=e,e={}),d(e,{dom:0,js:0,html:0,css:1}),l.compile(e,t).css},l.createType=function(e,t){t=x(t,{}),t.methods=x(t.methods,{}),t.properties=x(t.properties,{}),C("createType",1,e,"string"),C("createType",2,t,"object");var n,r,i,s="__DELAYED__",o=(new Function("return function "+e+"(){\n var _t = this;\n if ( !(this instanceof "+e+") ){\n _t = new "+e+"('"+s+"');\n _t.__autonew__ = true;\n }\n\n if (arguments && arguments[0] != '"+s+"')\n "+e+".prototype.constructor.apply(_t, arguments);\n\n return _t;\n}"))();return t.base!=null&&(t.constructor==null||!t.hasOwnProperty("constructor"))&&(t.constructor=function(){return o.base!=null?o.base.constructor.apply(this,arguments):void 0}),t.base!=null&&tt(o,t.base),l.addMethod(o.prototype,"constructor",t.constructor),i={type:{value:o,writable:!1,enumerable:!1},typeName:{value:e,writable:!1,enumerable:!1},isOJ:{value:!0,writable:!1,enumerable:!1}},l.addProperties(o,i),l.addProperties(o.prototype,i),r=p(t.properties).sort(),o.prototype.properties!=null&&(r=S(o.prototype.properties.concat(r))),l.addProperty(o.prototype,"properties",{value:r,writable:!1,enumerable:!1}),n=p(t.methods).sort(),o.prototype.methods!=null&&(n=S(o.prototype.methods.concat(n))),l.addProperty(o.prototype,"methods",{value:n,writable:!1,enumerable:!1}),d(t.methods,{get:function(e){if(!l.isString(e)){var t={},n,r;for(n=0;n0&&(this.value=r[0]),(n!=null?n.live:void 0)!=null&&(this.live=l.argumentShift(n,"live")),l.TextBox.base.constructor.apply(this,[n])},properties:{value:{get:function(){var e=this.el.value;if(e==null||e===f)e="";return e},set:function(e){this.el.value=e}},live:!0}}),l.CheckBox=l.createType("CheckBox",{base:l.ModelKeyView,constructor:function(){var e=this,t=l.unionArguments(arguments),n=t.options,r=t.args;return this.el=l(function(){l.input({type:"checkbox"},{change:function(){e.viewChanged()}})}),r.length>0&&(this.value=r[0]),l.CheckBox.base.constructor.call(this,n)},properties:{value:{get:function(){return this.el.checked},set:function(e){this.el.checked=e=!!e,e?this.$el.attr("checked","checked"):this.$el.removeAttr("checked")}}}}),l.Text=l.createType("Text",{base:l.ModelKeyView,constructor:function(){var e=this,t=l.unionArguments(arguments),n=t.options,r=t.args;return this._tagName=l.argumentShift(n,"tagName"),this.el=l(function(){return l[e.tagName]()}),r.length>0&&(this.value=r[0]),l.Text.base.constructor.call(this,n)},properties:{value:{get:function(){return this.$el.ojValue()},set:function(e){this.$el.oj(e)}},tagName:{get:function(){return x(this._tagName,"div")}}}}),l.TextArea=l.createType("TextArea",{base:l.ModelKeyView,constructor:function(){var e=this,t=l.unionArguments(arguments),n=t.options,r=t.args;return this.el=l(function(){return l.textarea({keydown:function(){e.live&&setTimeout(function(){return e.$el.change()},10)},keyup:function(){e.live&&setTimeout(function(){return e.$el.change()},10)},change:function(){e.viewChanged()}})}),this.value=l.argumentShift(n,"value")||r.join("\n"),l.TextArea.base.constructor.call(this,n)},properties:{value:{get:function(){return this.el.value},set:function(e){this.el.value=e}},live:!0}}),l.ListBox=l.createType("ListBox",{base:l.ModelKeyView,constructor:function(){var e=this,t=l.unionArguments(arguments),n=t.options,r=t.args;return this.el=l(function(){return l.select({change:function(){e.viewChanged()}})}),this.options=l.argumentShift(n,"options"),r.length>0&&(this.value=r[0]),l.ListBox.base.constructor.apply(this,[n])},properties:{value:{get:function(){return this.$el.val()},set:function(e){this.$el.val(e)}},options:{get:function(){return this._options},set:function(e){if(!l.isArray(e))throw new Error("oj."+this.typeName+".options array is missing");this._options=e,this.$el.oj(function(){var t,n,r;for(n=0,r=e.length;n0&&(i=r[0]),n.title!=null&&(i=l.argumentShift(n,"title")),this.el=l(function(){return l.button(i)}),l.Button.base.constructor.apply(this,[n]),this.title=i},properties:{title:{get:function(){return x(this._title,"")},set:function(e){this.$el.oj(this._title=e)}}},methods:{click:function(){return arguments.length>0?this.$el.click.apply(this.$el,arguments):this.$el.click()}}}),l.List=l.createType("List",{base:l.CollectionView,constructor:function(){var e=this,t=l.unionArguments(arguments),n=t.options,r=t.args,i;return this._tagName=l.argumentShift(n,"tagName"),this.itemTagName=l.argumentShift(n,"itemTagName"),this.el=l(function(){return l[e.tagName]()}),n.el!=null&&(this.el=l.argumentShift(n,"el")),n.each==null&&(n.each=function(e){return l.isString(e)||l.isNumber(e)||l.isBoolean(e)?e:JSON.stringify(e)}),l.List.base.constructor.apply(this,[n]),i=r.length>0?r:null,this.items=n.items!=null?l.argumentShift(n,"items"):i},properties:{items:{get:function(){return this._items!=null?this._items:this.$items.ojValues()},set:function(e){this._items=e,this.make()}},count:{get:function(){return this.$items.length}},tagName:{get:function(){return x(this._tagName,"div")}},itemTagName:{get:function(){return x(this._itemTagName,"div")},set:function(e){this._itemTagName=e,this.make()}},$items:{get:function(){return this._$items!=null?this._$items:this._$items=this.$("> "+this.itemTagName)}}},methods:{item:function(e,t){e=this._bound(e,this.count,".item: index");if(t==null)return this.$item(e).ojValue();this.$item(e).oj(t)},$item:function(e){return this.$items.eq(this._bound(e,this.count,".$item: index"))},make:function(){if(!this.isConstructed)return;var e=this,t,n,r,i,s;this.models!=null&&this.each!=null?(r=l.isEvented(this.models)?this.models.models:this.models,i=r.map(function(t){return e._itemFromModel(t)})):this.items!=null&&(i=this.items),this.$el.oj(function(){return i.map(function(t){e._itemElFromItem(t)})}),this.itemsChanged()},collectionModelAdded:function(e,t){this.add(t.indexOf(e),this._itemFromModel(e))},collectionModelRemoved:function(e,t,n){this.remove(n.index)},collectionReset:function(){this.make()},_itemFromModel:function(e){var t=this;return l(function(){return t.each(e)})},_itemElFromItem:function(e){return l[this.itemTagName](e)},_bound:function(e,t,n){var r=e<0?e+t:e;return 0<=r&&re?this.$item(e).insertAfter(this.$item(t)):this.$item(e).insertBefore(this.$item(t)),this.itemsChanged()},swap:function(e,t){if(e===t)return;e=this._bound(e,this.count,".swap: firstIndex"),t=this._bound(t,this.count,".swap: secondIndex");if(Math.abs(e-t)===1)this.move(e,t);else{var n=Math.min(e,t),r=Math.max(e,t);this.move(r,n),this.move(n+1,r)}this.itemsChanged()},unshift:function(e){this.add(0,e)},shift:function(){return this.remove(0)},push:function(e){this.add(this.count,e)},pop:function(){return this.remove(-1)},clear:function(){this.$items.remove(),this.itemsChanged()}}}),l.NumberList=l.createType("NumberList",{base:l.List,constructor:function(){var e=[{tagName:"ol",itemTagName:"li"}].concat(s.call(arguments));return l.NumberList.base.constructor.apply(this,e)}}),l.BulletList=l.createType("BulletList",{base:l.List,constructor:function(){var e=[{tagName:"ul",itemTagName:"li"}].concat(s.call(arguments));return l.BulletList.base.constructor.apply(this,e)}}),l.Table=l.createType("Table",{base:l.CollectionView,constructor:function(){var e=this,t=l.unionArguments(arguments),n=t.options,r=t.args,i,s;this.el=l(function(){return l.table()}),n.el!=null&&(this.el=l.argumentShift(n,"el")),n.each==null&&(n.each=function(e,t){var n=l.isString(e)||l.isNumber(e)||l.isBoolean(e)?[e]:l.isEvented(e)&&typeof e.attributes=="object"?g(e.attributes):g(e);return n.map(function(e){t(e)})}),l.Table.base.constructor.apply(this,[n]);for(s=0;s0)return this.rows=i},properties:{rowCount:{get:function(){return this.$trs.length}},columnCount:{get:function(){var e,t,n;return(n=this.$tr(0).find("> td").length)>0?n:(t=this.$theadTR.find("> th").length)>0?t:(e=this.$tfootTR.find("> td").length)>0?e:0}},rows:{get:function(){if(this._rows!=null)return this._rows;var e,t=0;this._rows=[];for(;t0))return this.clearBody();this._rows=e,this.make()}},header:{get:function(){return this.$theadTR.find("> th").ojValues()},set:function(e){return N(l.isArray(e),this.typeName+".header","array expected for first argument"),e!=null&&e.length>0?this.$theadTRMake.oj(function(){return e.map(function(e){l.th(e)})}):this.clearHeader()}},footer:{get:function(){return this.$tfootTR.find("> td").ojValues()},set:function(e){var t=this;if(!l.isArray(e))throw new Error("oj.Table.footer: array expected for first argument");return e!=null&&e.length>0?this.$tfootTRMake.oj(function(){var t,n,r,i;i=[];for(n=0,r=e.length;n caption")}},$colgroup:{get:function(){return this.$("> colgroup")}},$thead:{get:function(){return this.$("> thead")}},$tfoot:{get:function(){return this.$("> tfoot")}},$tbody:{get:function(){return this.$("> tbody")}},$theadTR:{get:function(){return this.$thead.find("> tr")}},$tfootTR:{get:function(){return this.$tfoot.find("> tr")}},$ths:{get:function(){return this.$theadTR.find("> th")}},$trs:{get:function(){return this._$trs!=null?this._$trs:this._$trs=this.$("> tbody > tr")}},$colgroupMake:{get:function(){return this.$colgroup.length>0?this.$colgroup:(t="",this.$caption.length>0?this.$caption.insertAfter(t):this.$table.append(t),this.$tbody)}},$captionMake:{get:function(){return this.$caption.length>0?this.$caption:(this.$table.prepend(""),this.$caption)}},$tfootMake:{get:function(){return this.$tfoot.length>0?this.$tfoot:(t="",this.$tfoot.length>0?this.$tfoot.insertBefore(t):this.$table.append(t),this.$tfoot)}},$theadMake:{get:function(){return this.$thead.length>0?this.$thead:(t="",this.$colgroup.length>0?this.$colgroup.insertAfter(t):this.$caption.length>0?this.$caption.insertAfter(t):this.$table.prepend(t),this.$thead)}},$tbodyMake:{get:function(){return this.$tbody.length>0?this.$tbody:(this.$table.append(""),this.$tbody)}},$theadTRMake:{get:function(){return this.$theadTR.length>0?this.$theadTR:(this.$theadMake.html(""),this.$theadTR)}},$tfootTRMake:{get:function(){return this.$tfootTR.length>0?this.$tfootTR:(this.$tfootMake.html(""),this.$tfootTR)}}},methods:{make:function(){if(!this.isConstructed)return;var e=this,t,n=[];this.models!=null&&this.each!=null?(t=l.isEvented(this.models)?this.models.models:this._models,n=t.map(function(t){return e._rowFromModel(t)})):this.rows!=null&&(n=this.rows.map(function(e){return l(function(){e.forEach(function(e){l.td(e)})})})),n.length>0&&this.$tbodyMake.oj(function(){n.forEach(function(e){l.tr(e)})}),this.bodyChanged()},collectionModelAdded:function(e,t){var n=t.indexOf(e),r=this._rowFromModel(e);this._addRowTR(n,l(function(){return l.tr(r)}))},collectionModelRemoved:function(e,t,n){this.removeRow(n.index)},collectionReset:function(){this.make()},$tr:function(e){return e=e<0?e+count:e,this.$trs.eq(e)},$tdsRow:function(e){return e=e<0?e+count:e,this.$tr(e).find("> td")},$td:function(e,t){return e=e<0?e+this.rowCount:e,t=t<0?t+this.columnCount:t,this.$tdsRow(e).eq(t)},row:function(e,t){e=this._bound(e,this.rowCount,".row: rx");if(t==null)return this.$tdsRow(e).ojValues();N(t.length===cellCount(e),this.typeName,"array expected for second argument with length ("+e+")"),t.forEach(function(t,n){this.$td(e,n).oj(t)})},cell:function(e,t,n){return n!=null?this.$td(e,t).oj(n):this.$td(e,t).ojValue()},addRow:function(e,t){t==null&&(t=e,e=-1),e=this._bound(e,this.rowCount+1,".addRow: rx"),N(l.isArray(t),"addRow","expected array for row content"),this._addRowTR(e,function(){l.tr(function(){t.forEach(function(e){l.td(e)})})})},_addRowTR:function(e,t){this.rowCount===0?this.$el.oj(t):e===this.rowCount?this.$tr(e-1).ojAfter(t):this.$tr(e).ojBefore(t),this.bodyChanged()},removeRow:function(e){e==null&&(e=-1),e=this._bound(e,this.rowCount,".removeRow: index");var t=this.row(e);return this.$tr(e).remove(),this.bodyChanged(),t},moveRow:function(e,t){if(e===t)return;e=this._bound(e,this.rowCount,".moveRow: fromIndex"),t=this._bound(t,this.rowCount,".moveRow: toIndex");var n=t>e?"insertAfter":"insertBefore";this.$tr(e)[n](this.$tr(t)),this.bodyChanged()},swapRow:function(e,t){if(e===t)return;e=this._bound(e,this.rowCount,".swap: firstIndex"),t=this._bound(t,this.rowCount,".swap: secondIndex");if(Math.abs(e-t)===1)this.moveRow(e,t);else{var n=Math.min(e,t),r=Math.max(e,t);this.moveRow(r,n),this.moveRow(n+1,r)}this.bodyChanged()},unshiftRow:function(e){this.addRow(0,e)},shiftRow:function(){return this.removeRow(0)},pushRow:function(e){this.addRow(this.rowCount,e)},popRow:function(){return this.removeRow(-1)},clearColgroup:function(){this.$colgroup.remove()},clearBody:function(){this.$tbody.remove(),this.bodyChanged()},clearHeader:function(){this.$thead.remove(),this.headerChanged()},clearFooter:function(){this.$tfoot.remove(),this.footerChanged()},clearCaption:function(){this.$capation.remove()},clear:function(){return this.clearBody(),this.clearHeader(),this.clearFooter(),this.$caption.remove()},bodyChanged:function(){this._rows=null,this._columns=null,this._$trs=null},headerChanged:function(){this._header=null},footerChanged:function(){this._footer=null},_rowFromModel:function(e){var t=this;return l(function(){return t.each(e,l.td)})},_bound:function(e,t,n){var r=e<0?e+t:e;if(0<=r&&r0&&e[0]!=="_"||e.length>0&&e[0]==="_"&&l[e.slice(1)]!=null)&&l.addProperty(l.sandbox,e,{value:l[e],writable:!1})}),l.use=function(e,t){t=x(t,{}),C("use",1,e,"function"),C("use",2,t,"object");var n=e(l,t),r=w(n),i,s;for(i in n)s=n[i],l.isOJType(s)&&(r[D(i)]=_createQuietType(s.typeName));for(i in r)s=r[i],l[i]=s,l.addProperty(l.sandbox,i,{value:s,writable:!1})},l.$.fn.oj=it({get:function(e){return e[0].oj},set:function(e,t){if(t.length===0)return e[0].oj;var n=l.compile.apply(l,[{dom:1,html:0,cssMap:1}].concat(s.call(t)));ot(n.cssMap,{global:0}),e.html(""),l.isArray(n.dom)||(n.dom=[n.dom]);for(var r=0;r=-1&&!t){r=n>=0?arguments[n]:process.cwd();if(typeof r!="string"||!r)continue;e=r+"/"+e,t=r.charAt(0)==="/",n--}return e=pt(e.split("/").filter(function(e){return!!e}),!t).join("/"),(t?"/":"")+e||"."},l._pathNormalize=function(e){var t=e.charAt(0)==="/",n=e.substr(-1)==="/";return e=pt(e.split("/").filter(function(e){return!!e}),!t).join("/"),!e&&!t&&(e="."),e&&n&&(e+="/"),(t?"/":"")+e},l._pathJoin=function(){var e=s.call(arguments,0);return l._pathNormalize(e.filter(function(e,t){return e&&typeof e=="string"}).join("/"))},l._pathDirname=function(e){var t=ht(e),n=t[0],r=t[1];return!n&&!r?".":(r&&(r=r.substr(0,r.length-1)),n+r)}}).call(this) \ No newline at end of file diff --git a/ajax/libs/oj/0.2.1/oj.js b/ajax/libs/oj/0.2.1/oj.js new file mode 100644 index 000000000..4b621ff09 --- /dev/null +++ b/ajax/libs/oj/0.2.1/oj.js @@ -0,0 +1,3074 @@ +// +// oj.js v0.2.1 +// ojjs.org +// +// Copyright 2013, Evan Moran +// Released under the MIT License +// +// =================================================================== +// Unified templating for the people. Thirsty people. + +;(function(){ + + var root = this, + ArrP = Array.prototype, + FunP = Function.prototype, + ObjP = Object.prototype, + slice = ArrP.slice, + unshift = ArrP.unshift, + concat = ArrP.concat, + pass = function(v){return v}, + _udf = 'undefined' + + // oj function: highest level of capture for tag functions + function oj(){ + return oj.tag.apply(this, ['oj'].concat(slice.call(arguments)).concat([{__quiet__:1}])) + }; + + oj.version = '0.2.1' + + oj.isClient = !(typeof process !== "undefined" && process !== null ? process.versions != null ? process.versions.node : 0 : 0) + + // Detect jQuery globally or in required module + if (typeof $ != _udf) + oj.$ = $ + else if (typeof require != _udf) + try { + oj.$ = require('jquery') + } catch (e){} + + // Export as a module in node + if (typeof require != _udf) + module.exports = oj + // Export globally if not in node + else + root['oj'] = oj + + // Reference ourselves for template files to see + oj.oj = oj + + // oj.load: load the page specified generating necessary html, css, and client side events + oj.load = function(page){ + // Defer dom manipulation until the page is ready + return oj.$(function(){ + oj.$.ojBody(require(page)) + + // Trigger events bound through onload + return oj.onload() + }); + }; + + // oj.onload: Enlist in onload action or run them. + var _onLoadQueue = {queue: [], loaded: false} + oj.onload = function(f){ + // Call everything if no arguments + if (oj.isUndefined(f)){ + _onLoadQueue.loaded = true + while ((f = _onLoadQueue.queue.shift())) + f() + } + // Call load if already loaded + else if (_onLoadQueue.loaded) + f() + // Queue function for later + else + _onLoadQueue.queue.push(f) + } + + // oj.emit: Used by plugins to group multiple elements as if it is a single tag. + oj.emit = function(){return oj.tag.apply(oj, ['oj'].concat(slice.call(arguments)))} + + // Type Helpers + oj.isDefined = function(a){return typeof a !== _udf} + oj.isOJ = function(obj){return !!(obj != null ? obj.isOJ : void 0)} + oj.isOJType = function(a){return oj.isOJ(a) && a.type === a} + oj.isOJInstance = function(a){return oj.isOJ(a) && !oj.isOJType(a)} + oj.isEvented = function(a){return !!(a && a.on && a.off && a.trigger)} + oj.isDOM = function(a){return !!(a && (a.nodeType != null))} + oj.isDOMElement = function(a){return !!(a && a.nodeType === 1)} + oj.isDOMAttribute = function(a){return !!(a && a.nodeType === 2)} + oj.isDOMText = function(a){return !!(a && a.nodeType === 3)} + oj.isjQuery = function(a){return !!(a && a.jquery)} + oj.isUndefined = function(a){return a === void 0} + oj.isBoolean = function(a){return a === true || a === false || ObjP.toString.call(a) === '[object Boolean]'} + oj.isNumber = function(a){return !!(a === 0 || (a && a.toExponential && a.toFixed))} + oj.isString = function(a){return !!(a === '' || (a && a.charCodeAt && a.substr))} + oj.isDate = function(a){return !!(a && a.getTimezoneOffset && a.setUTCFullYear)} + oj.isPlainObject = function(a){return oj.$.isPlainObject(a) && !oj.isOJ(a)} + oj.isFunction = oj.$.isFunction + oj.isArray = oj.$.isArray + oj.isRegEx = function(a){return ObjP.toString.call(a) === '[object RegExp]'} + oj.isArguments = function(a){return ObjP.toString.call(a) === '[object Arguments]'} + oj.parse = function(str){ + var n, o = str + if (str === _udf) + o = void 0 + else if (str === 'null') + o = null + else if (str === 'true') + o = true + else if (str === 'false') + o = false + else if (!isNaN(n = parseFloat(str))) + o = n + return o; + }; + + // unionArguments: Union arguments into options and args + oj.unionArguments = function(argList){ + var options = {}, args = [], v, ix = 0 + for (; ix < argList.length; ix++){ + v = argList[ix] + if (oj.isPlainObject(v)) + options = _extend(options, v) + else + args.push(v) + } + return {options: options, args: args} + } + + // argumentShift: Shift argument out of options with key + oj.argumentShift = function(options, key){ + var value + if ((oj.isPlainObject(options)) && (key != null) && (options[key] != null)){ + value = options[key] + delete options[key] + } + return value + }; + + // Utility Helpers + var _keys = Object.keys, + _extend = oj.$.extend + + function _isCapitalLetter(c){return !!(c.match(/[A-Z]/));}; + + function _has(obj, key){return ObjP.hasOwnProperty.call(obj, key)} + + function _values(obj){ + var keys = _keys(obj), + len = keys.length, + values = new Array(len), + i = 0 + for (; i < len; i++) + values[i] = obj[keys[i]] + return values + } + + function _toArray(obj){ + if (!obj) + return [] + if (oj.isArray(obj)) + return slice.call(obj) + if (oj.isArguments(obj)) + return slice.call(obj) + if (obj.toArray && oj.isFunction(obj.toArray)) + return obj.toArray() + return _values(obj) + } + + function _isEmpty(o){ + if (oj.isArray(o)) + return o.length === 0 + for (var k in o) + if (_has(o, k)) + return false + return true + }; + + function _clone(o){ + if (!(oj.isArray(o) || oj.isPlainObject(o))) + return o + if (oj.isArray(o)) + return o.slice() + else + return _extend({}, o) + } + + // _setObject(obj, k1, k2, ..., value): + // Set object deeply key by key ensure each part is an object + function _setObject(obj){ + var args = arguments, + o = obj, + len = args.length, + // keys are args ix: 1 to n-2 + keys = 3 <= len ? slice.call(args, 1, len = len - 1) : (len = 1, []), + // value is last arg + value = args[len++], + ix, k + + for (ix = 0; ix < keys.length; ix++){ + k = keys[ix] + + // Initialize key to empty object if necessary + if (typeof o[k] !== 'object') + o[k] = {} + + // Set final value if this is the last key + if (ix === keys.length - 1) + o[k] = value + else + // Continue deeper + o = o[k] + } + return obj + }; + + // uniqueSort: + function uniqueSort(arr, isSorted){ + if (isSorted == null) + isSorted = false + + if (!isSorted) + arr.sort() + + var out = [], ix, item + for (ix = 0; ix < arr.length; ix++){ + item = arr[ix] + if (ix > 0 && arr[ix - 1] === arr[ix]) + continue + out.push(item) + } + return out + }; + + // _d(args...): initialization helper that returns first arg that isn't null + function _d(){ + for (var ix = 0;ix < arguments.length; ix++) + if (arguments[ix] != null) + return arguments[ix] + return null + } + + // _e: error by throwing msg with optional fn name + function _e(fn, msg){ + msg = _d(msg, fn, '') + fn = _d(fn, 0) + var pfx = "oj: " + if (fn) + pfx = "oj." + fn + ": " + throw new Error(pfx + msg) + } + + // _a: assert when cond is false with msg and with optional fn name + function _a(cond, fn, msg){if (!cond) _e(fn,msg)} + + // _v: validate argument n with fn name and message + function _v(fn, n, v, type){ + n = {1:'first',2:'second',3: 'third', 4: 'fourth'}[n] + _a(!type || (typeof v === type), fn, "" + type + " expected for " + n + " argument") + } + + // _splitAndTrim: Split string by seperator and trim result + function _splitAndTrim(str, seperator, limit){ + return str.split(seperator, limit).map(function(v){ + return v.trim() + }) + } + + // _decamelize: Convert from camal case to underscore case + function _decamelize(str){return str.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase()} + + // _dasherize: Convert from camal case or space seperated to dashes + function _dasherize(str){return _decamelize(str).replace(/[ _]/g, '-')} + + // oj.addMethod: add multiple methods to an object + oj.addMethods = function(obj, mapNameToMethod){ + for (var methodName in mapNameToMethod) + oj.addMethod(obj, methodName, mapNameToMethod[methodName]); + } + + // oj.addMethod: Add method to object with name and fn + oj.addMethod = function(obj, name, fn){ + _v('addMethod', 2, name, 'string') + _v('addMethod', 3, fn, 'function') + // Methods are non-enumerable, non-writable properties + Object.defineProperty(obj, name, { + value: fn, + enumerable: false, + writable: false, + configurable: true + }) + } + + // oj.removeMethod: Remove a method with name from an object + oj.removeMethod = function(obj, name){ + _v('removeMethod', 2, name, 'string'); + delete obj[name] + }; + + // oj.addProperties: add multiple properties to an object + // Properties can be specified by get/set methods or by a value + // Optionally you can include writable or enumerable settings + oj.addProperties = function(obj, mapNameToInfo){ + + // Iterate over properties + var propInfo, propName; + + for (propName in mapNameToInfo){ + propInfo = mapNameToInfo[propName]; + + // Wrap the value if propInfo is not already a prop definition + if (((propInfo != null ? propInfo.get : void 0) == null) && + ((propInfo != null ? propInfo.value : void 0) == null)) + propInfo = {value: propInfo, writable: true} + + oj.addProperty(obj, propName, propInfo); + } + }; + + // oj.addProperty: Add property to object with name and info + oj.addProperty = function(obj, name, info){ + _v('addProperty', 2, name, 'string') + _v('addProperty', 3, info, 'object') + + // Default properties to enumerable and configurable + info = _extend({enumerable: true, configurable: true}, info) + + // Remove property if it already exists + if (Object.getOwnPropertyDescriptor(obj, name) != null) + oj.removeProperty(obj, name) + + // Add the property + Object.defineProperty(obj, name, info) + }; + + // oj.removeProperty: remove property from object with name + oj.removeProperty = function(obj, name){ + _v('removeProperty', 2, name, 'string') + delete obj[name] + } + + // oj.isProperty: Determine property in object is a get/set property + oj.isProperty = function(obj, name){ + _v('isProperty', 2, name, 'string') + return Object.getOwnPropertyDescriptor(obj, name).get != null + }; + + // oj.copyProperty: Copy source.propName to dest.propName + oj.copyProperty = function(dest, source, propName){ + var info = Object.getOwnPropertyDescriptor(source, propName) + if (info.value != null) + info.value = _clone(info.value) + return Object.defineProperty(dest, propName, info) + } + + // _argsStack: Abstraction to wrap global arguments stack. + // This makes me sad but it is necessary for div -> syntax + var _argsStack = []; + + // Access the top of the stack + oj._argsTop = function(){ + if (_argsStack.length) + return _argsStack[_argsStack.length - 1] + else + return null + } + + // Push scope onto arguments + oj._argsPush = function(args){ + _argsStack.push(_d(args,[])) + } + + // Pop scope from arguments + oj._argsPop = function(){ + if (_argsStack.length) + return _argsStack.pop() + return null + } + + // Append argument + oj._argsAppend = function(arg){ + var top = oj._argsTop() + if (top != null) + top.push(arg) + } + + // oj.tag (name, attributes, rest...) + oj.tag = function(name){ + _v('tag', 1, name, 'string') + + var rest = 2 <= arguments.length ? slice.call(arguments, 1) : [], + u = oj.unionArguments(rest), + args = u.args, + attributes = u.options, + isQuiet = attributes.__quiet__, + arg, len, r, ix, + // Build ojml starting with tag + ojml = [name] + + if (isQuiet) + delete attributes.__quiet__; + + // Add attributes to ojml if they exist + if (!_isEmpty(attributes)) + ojml.push(attributes); + + // Store current tag context + oj._argsPush(ojml) + + // Loop over attributes + for (ix = 0; ix < args.length; ix++){ + arg = args[ix] + + if (oj.isPlainObject(arg)) + continue + + else if (oj.isFunction(arg)){ + len = oj._argsTop().length + + // Call the fn tags will append to oj._argsTop + r = arg() + + // Use return value instead if oj._argsTop didn't change + if (len === oj._argsTop().length && (r != null)) + oj._argsAppend(r) + + } else + oj._argsAppend(arg) + } + + // Restore previous tag context + oj._argsPop() + + // Append the final result to your parent's arguments + // if there exists an argument to append to. + // Do not emit when quiet is set, + if (!isQuiet) + oj._argsAppend(ojml) + + return ojml + } + + // Define all elements as closed or open + oj.tag.elements = { + closed: 'a abbr acronym address applet article aside audio b bdo big blockquote body button canvas caption center cite code colgroup command datalist dd del details dfn dir div dl dt em embed fieldset figcaption figure font footer form frameset h1 h2 h3 h4 h5 h6 head header hgroup html i iframe ins keygen kbd label legend li map mark menu meter nav noframes noscript object ol optgroup option output p pre progress q rp rt ruby s samp script section select small source span strike strong style sub summary sup table tbody td textarea tfoot th thead time title tr tt u ul var video wbr xmp'.split(' '), + open: 'area base br col command css !DOCTYPE embed hr img input keygen link meta param source track wbr'.split(' ') + } + + // Keep track of all valid elements + oj.tag.elements.all = (oj.tag.elements.closed.concat(oj.tag.elements.open)).sort() + + // tag.isClosed: Determine if an element is closed or open + oj.tag.isClosed = function(tag){return oj.tag.elements.open.indexOf(tag) === -1} + + // _setTagName: Record tag name on a given tag function + function _setTagName(tag, name){if (tag != null) tag.tagName = name } + + // _getTagName: Get a tag name on a given tag function + function _getTagName(tag){return tag.tagName} + + // _getQuietTagName: Get quiet tag name + function _getQuietTagName(tag){return '_' + tag} + + // _setInstanceOnElement: Record an oj instance on a given element + function _setInstanceOnElement(el, inst){if (el != null) el.oj = inst} + + // _getInstanceOnElement: Get a oj instance on a given element + function _getInstanceOnElement(el){ + if ((el != null ? el.oj : 0) != null) + return el.oj + else + return null + } + + // Create tag methods for all elements + for (var ix = 0; ix < oj.tag.elements.all.length; ix++){ + t = oj.tag.elements.all[ix] + ;(function(t){ + // Define tag function named t + oj[t] = function(){return oj.tag.apply(oj, [t].concat(slice.call(arguments)))} + + // Quiet tag functions do not emit + // Define quiet tag function named qt + var qt = _getQuietTagName(t) + oj[qt] = function(){return oj.tag.apply(oj, [t, {__quiet__: 1 }].concat(slice.call(arguments)))} + + // Tag functions remember their name so the OJML syntax can use the function + _setTagName(oj[t], t) + _setTagName(oj[qt], t) + })(t) + } + + // oj.doctype: Method to define doctypes based on short names + + var dhp = 'HTML PUBLIC "-//W3C//DTD HTML 4.01', + w3 = '"http://www.w3.org/TR/html4/', + strict5 = 'html', + strict4 = dhp + '//EN" ' + w3 + 'strict.dtd"', + _doctypes = { + '5': strict5, + 'HTML 5': strict5, + '4': strict4, + 'HTML 4.01 Strict': strict4, + 'HTML 4.01 Frameset': dhp + ' Frameset//EN" ' + w3 + 'frameset.dtd"', + 'HTML 4.01 Transitional': dhp + ' Transitional//EN" ' + w3 + 'loose.dtd"' + } + + // Define the method passing through to !DOCTYPE tag function + oj.doctype = function(typeOrValue){ + typeOrValue = _d(typeOrValue,'5') + return oj['!DOCTYPE'](_d(_doctypes[typeOrValue], typeOrValue)) + }; + + // oj.extendInto (context): Extend all OJ methods into a context. + // Defaults to root, which is either `global` or `window` + + // Methods that start with _ are not extended + oj.useGlobally = oj.extendInto = function(context){ + context = _d(context,root) + + var o = {}, k, qn, v; + + // For all keys and values in oj + for (k in oj){ + v = oj[k] + + // Extend into new object + if (k[0] !== '_' && k !== 'extendInto' && k !== 'useGlobally'){ + o[k] = v + + // Export _tag and _Type methods + qn = _getQuietTagName(k) + if (oj[qn]) + o[qn] = oj[qn] + } + } + _extend(context, o) + }; + + // oj.compile(options, ojml) + // --- + // Compile ojml into meaningful parts + // options: + // * html - Compile to html + // * dom - Compile to dom + // * css - Compile to css + // * cssMap - Record css as a javascript object + // * styles -- Output css as style tags + // * minify - Minify js and css + // * ignore:{html:1} - Map of tags to ignore while compiling + + oj.compile = function(options, ojml){ + // Options is optional + ojml = _d(ojml, options) + + var css, cssMap, dom, html, + + // Default options to compile everything + options = _extend({html:1, dom:0, css:0, cssMap:0, minify:0, ignore:{}}, options), + + // Init accumulator + acc = _clone(options) + + acc.html = options.html ? [] : null + acc.dom = options.dom && (typeof document !== "undefined" && document !== null) ? document.createElement('OJ') : null + acc.css = options.css || options.cssMap ? {} : null; + acc.indent = '' + + // Accumulate insert events per element + acc.inserts = [] + + if (options.dom) + acc.types = [] + + acc.tags = {} + + // Always ignore oj and css tags + _extend(options.ignore, {oj:1, css:1}) + + // Recursive compile to accumulator + _compileAny(ojml, acc) + + // Flatten CSS + if (acc.css != null) + cssMap = _flattenCSSMap(acc.css) + + // Generate css if necessary + if (options.css) + css = _cssFromPluginObject(cssMap, {minify: options.minify, tags: 0}) + + // Output cssMap if necessary + if (!options.cssMap) + cssMap = undefined + + // Generate HTML if necessary + if (options.html) + html = acc.html.join('') + + // Generate dom if necessary + if (options.dom){ + + // Remove the wrapping from the dom element + dom = acc.dom.childNodes; + + // Cleanup inconsistencies of childNodes + if (dom.length != null){ + // Make dom a real array + dom = _toArray(dom) + + // Filter out anything that isn't a dom element + dom = dom.filter(function(v){return oj.isDOM(v)}) + } + + // Ensure dom is null if empty + if (dom.length === 0) + dom = null + + // Single elements are not returned as a list + else if (dom.length === 1) + // Reasoning: The common cases don't have multiple elements + // ,, etc and this is abstracted for you anyway + // with jQuery plugins + dom = dom[0] + } + return { + html: html, + dom: dom, + css: css, + cssMap: cssMap, + types: acc.types, + tags: acc.tags, + inserts: acc.inserts + } + }; + + // _styleFromObject: Convert object to style string + function _styleFromObject(obj, options){ + options = _extend({ + inline: true, + indent: '' + }, options) + + // Trailing semi should only exist on when we aren't indenting + options.semi = !options.inline; + + var out = "", + + // Sort keys to create consistent output + keys = _keys(obj).sort(), + + // Support indention and inlining + indent = options.indent != null ? options.indent : '', + newline = options.inline ? '' : '\n', + ix, k, kFancy, semi + + for (ix = 0; ix < keys.length; ix++){ + kFancy = keys[ix] + + // Add semi if it is not inline or it is not the last key + semi = options.semi || ix !== keys.length - 1 ? ";" : '' + + // Allow keys to be camal case + k = _dasherize(kFancy) + + // Collect css result for this key + out += "" + indent + k + ":" + obj[kFancy] + semi + newline + } + return out + }; + + // _attributesFromObject: Convert object to attribute string with no special conversions + function _attributesFromObject(obj){ + if (!oj.isPlainObject(obj)) + return obj + + // Pass through non objects + var k, v, ix, + out = '', + space = '', + // Serialize attributes in order for consistent output + attrs = _keys(obj).sort() + + for (ix = 0; ix < attrs.length; ix++){ + k = attrs[ix] + v = obj[k] + + // Boolean attributes have no value + if (v === true) + out += "" + space + k + + // Other attributes have a value + else + out += "" + space + k + "=\"" + v + "\"" + + space = ' ' + } + return out; + }; + + // _flattenCSSMap: Take an OJ cssMap and flatten it into the form + // `'plugin' -> '@media query' -> 'selector' ->'rulesMap'` + // + // This method vastly simplifies `_cssFromPluginObject` + // Nested, media, and comma definitions are resolved and merged + function _flattenCSSMap(cssMap){ + var flatMap = {}, plugin, cssMap_ + for (plugin in cssMap){ + cssMap_ = cssMap[plugin] + _flattenCSSMap_(cssMap_, flatMap, [''], [''], plugin) + } + return flatMap + }; + + // Recursive helper with accumulators (it outputs flatMapAcc) + function _flattenCSSMap_(cssMap, flatMapAcc, selectorsAcc, mediasAcc, plugin){ + + // Built in media helpers + var acc, cur, inner, isMedia, mediaJoined, mediasNext, next, outer, parts, rules, selector, selectorJoined, selectorsNext, o, i, + + medias = { + 'widescreen': 'only screen and (min-width: 1200px)', + 'monitor': '', + 'tablet': 'only screen and (min-width: 768px) and (max-width: 959px)', + 'phone': 'only screen and (max-width: 767px)' + }; + + for (selector in cssMap){ + rules = cssMap[selector] + + // Base Case: Record our selector when `rules` is a value + if (typeof rules !== 'object'){ + + // Join selectors and media accumulators with commas + selectorJoined = selectorsAcc.sort().join(',') + mediaJoined = mediasAcc.sort().join(',') + + // Prepend @media as that was removed previously when spliting into parts + if (mediaJoined !== '') + mediaJoined = "@media " + mediaJoined + + // Record the rule deeply in `flatMapAcc` + _setObject(flatMapAcc, plugin, mediaJoined, selectorJoined, selector, rules) + // Recursive Case: Recurse on `rules` when it is an object + } else { + + // (r1) Media Query found: Generate the next media queries + if (selector.indexOf('@media') === 0){ + isMedia = true + mediasNext = next = [] + selectorsNext = selectorsAcc + selector = (selector.slice('@media'.length)).trim() + acc = mediasAcc + + // (r2) Selector found: Generate the next selectors + } else { + isMedia = false + selectorsNext = next = [] + mediasNext = mediasAcc + acc = selectorsAcc + } + + // Media queries and Selectors can be comma seperated + parts = _splitAndTrim(selector, ',') + + // Media queries have convience substitutions like 'phone', 'tablet' + if (isMedia){ + parts = parts.map(function(v){ + return _d(medias[v], v) + }); + } + + // Determine the next selectors or media queries + for (o = 0; o < acc.length; o++){ + outer = acc[o] + + for (i = 0; i < parts.length; i++){ + inner = parts[i] + + // When `&` is not present just insert in front with the correct join operator + cur = inner + if ((inner.indexOf('&')) === -1 && outer !== '') + cur = (isMedia ? '& and ' : '& ') + cur; + + next.push(cur.replace(/&/g, outer)); + } + } + + // Recurse through objects after calculating the next selectors + _flattenCSSMap_( + rules, flatMapAcc, selectorsNext, mediasNext, plugin + ); + } + } + }; + + // _styleClassFromPlugin: Abstract plugin "; + } + + // _cssFromMediaObject: Convert css from a flattened mediaMap rule object. + // The rule object is of the form: + // mediaQuery => selector => rulesObject + function _cssFromMediaObject(mediaMap, options){ + options = _d(options, {}) + + var indent, indentRule, media, rules, selector, selectorMap, space, styles, + + minify = options.minify != null ? options.minify : 0, + tags = options.tags != null ? options.tags : 0, + + // Deterine what output characters are needed + newline = minify ? '' : '\n', + space = minify ? '' : ' ', + inline = minify, + css = '' + + // Build css for media => selector => rules + for (media in mediaMap){ + selectorMap = mediaMap[media]; + + // Serialize media query + if (media){ + media = media.replace(/,/g, "," + space); + css += "" + media + space + "{" + newline; + } + + for (selector in selectorMap){ + styles = selectorMap[selector] + indent = (!minify) && media ? '\t' : '' + + // Serialize selector + selector = selector.replace(/,/g, "," + newline) + css += "" + indent + selector + space + "{" + newline + + // Serialize style rules + indentRule = !minify ? indent + '\t' : indent + rules = _styleFromObject(styles, { + inline: inline, + indent: indentRule + }); + css += rules + indent + '}' + newline + } + + // End media query + if (media !== '') + css += '}' + newline + + } + try { + css = oj._minifyCSS(css, options) + } catch (e){ + throw new Error("css minification error: " + e.message + "\nCould not minify:\n" + css) + } + return css + }; + + // _cssFromPluginObject: Convert flattened css selectors and rules to a string + // pluginMaps are of the form: + // pluginName => mediaQuery => selector => rulesObject + // minify:false will output newlines + // tags:true will output the css in `" + newline + } + return css + }; + + // _compileDeeper: Recursive helper for compiling that wraps indention + function _compileDeeper(method, ojml, options){ + var i = options.indent + options.indent += '\t' + method(ojml, options) + options.indent = i + }; + + // _compileAny Recursive helper for compiling ojml or any type + function _compileAny(any, options){ + // Array + if (oj.isArray(any)) + _compileTag(any, options) + + // String + else if (oj.isString(any)){ + if (options.html != null) + options.html.push(any) + + if (any.length > 0 && any[0] === '<'){ + var root = document.createElement('div') + root.innerHTML = any; + if (options.dom != null) + options.dom.appendChild(root); + } else { + if (options.dom != null) + options.dom.appendChild(document.createTextNode(any)) + } + + // Boolean or Number + } else if (oj.isBoolean(any) || oj.isNumber(any)){ + if (options.html != null) + options.html.push("" + any) + + if (options.dom != null) + options.dom.appendChild(document.createTextNode("" + any)); + + // Function + } else if (oj.isFunction(any)){ + + // Wrap function call to allow full oj generation within any + _compileAny(oj(any), options); + + // Date + } else if (oj.isDate(any)){ + if (options.html != null) + options.html.push("" + (any.toLocaleString())); + + if (options.dom != null) + options.dom.appendChild(document.createTextNode("" + (any.toLocaleString()))); + + // OJ Type or Instance + } else if (oj.isOJ(any)){ + if (options.types != null) + options.types.push(any) + + if (options.html != null) + options.html.push(any.toHTML(options)) + + if (options.dom != null) + options.dom.appendChild(any.toDOM(options)) + + if (options.css != null) + _extend(options.css, any.toCSSMap(options)); + } + // Do nothing for: null, undefined, object + }; + + + // _compileTag: Recursive helper for compiling ojml tags + function _compileTag(ojml, options){ + + // Empty list compiles to undefined + if (ojml.length === 0) return + + // The first part of ojml is the tag + var tag = ojml[0], + tagType = typeof tag, + u = oj.unionArguments(ojml.slice(1)), + attributes = u.options, + children = u.args, + styles, + selector + + // Allow the tag parameter to be 'table' (string) or oj.table (function) or oj.Table (object) + if ((tagType === 'function' || tagType === 'object')) + tag = _d(_getTagName(tag), tag) + + // Fail if no tag found + if (!(oj.isString(tag) && tag.length > 0)) + _e('compile', 'tag name is missing') + + // Record tag as encountered + options.tags[tag] = true + + // Instance oj object if tag is capitalized + if (_isCapitalLetter(tag[0])) + return _compileDeeper(_compileAny, new oj[tag](ojml.slice(1)), options) + + // Compile to css if requested + if (options.css && tag === 'css'){ + + // Extend options.css with rules + for (selector in attributes){ + styles = attributes[selector] + options.css['oj'] = _d(options.css['oj'], {}) + options.css['oj'][selector] = _d(options.css['oj'][selector], {}) + _extend(options.css['oj'][selector], styles); + } + } + + // Compile DOCTYPE as special case because it is not really an element + // It has attributes with spaces and cannot be created by dom manipulation + // In this way it is HTML generation only. + + if (tag === '!DOCTYPE'){ + _v('compile', 1, ojml[1], 'string'); + if (!options.ignore[tag]){ + if (options.html) + options.html.push("<" + tag + " " + ojml[1] + ">") + // options.dom is purposely ignored + } + return; + } + if (!options.ignore[tag]){ + var events = _attributesProcessedForOJ(attributes), el + + // Compile to dom if requested + // Add dom element with attributes + if (options.dom && (typeof document !== "undefined" && document !== null)){ + + // Create element + el = document.createElement(tag) + + // Add self to parent + if (oj.isDOMElement(options.dom)) + options.dom.appendChild(el) + + // Push ourselves on the dom stack (to handle children) + options.dom = el + + // Set attributes in sorted order for consistency + if (oj.isPlainObject(attributes)){ + var keys = _keys(attributes).sort(), ix, attrName, attrValue + for (ix = 0; ix < keys.length; ix++){ + attrName = keys[ix] + attrValue = attributes[attrName] + + // Boolean attributes have no value + if (attrValue === true) + el.setAttributeNode(document.createAttribute(attrName)) + else + el.setAttribute(attrName, attrValue) + } + } + + // Bind events + _attributesBindEventsToDOM(events, el, options.inserts) + } + + // Compile to html if requested + // Add tag with attributes + if (options.html){ + var attr = _d(_attributesFromObject(attributes), ''), + space = attr === '' ? '' : ' ' + options.html.push("<" + tag + space + attr + ">") + // Recurse through children if this tag isn't ignored deeply + } + } + if (options.ignore[tag] !== 'deep'){ + for (ix = 0; ix < children.length; ix++){ + var child = children[ix] + // Skip indention if there is only one child + if (options.html != null && !options.minify && children.length > 1) + options.html.push("\n\t" + options.indent) + _compileDeeper(_compileAny, child, options) + } + } + + // Skip indention if there is only one child + if (options.html != null && !options.minify && children.length > 1) + options.html.push("\n" + options.indent) + + // End html tag if you have children or your tag closes + if (!options.ignore[tag]){ + + // Close tag if html + if (options.html != null && (children.length > 0 || oj.tag.isClosed(tag))) + options.html.push("") + + // Pop ourselves if dom + if (options.dom) + options.dom = options.dom.parentNode + } + }; + + // _attributesProcessedForOJ: Process attributes to make them easier to use + function _attributesProcessedForOJ(attr){ + var jqEvents = {bind:1, on:1, off:1, live:1, blur:1, change:1, click:1, dblclick:1, focus:1, focusin:1, focusout:1, hover:1, keydown:1, keypress:1, keyup:1, mousedown:1, mouseenter:1, mouseleave:1, mousemove:1, mouseout:1, mouseup:1, ready:1, resize:1, scroll:1, select:1, insert:1}, + events, k, v + + // Allow attributes to alias c to class and use arrays instead of space seperated strings + // Convert to c and class from arrays to strings + if (oj.isArray(attr != null ? attr.c : void 0)) + attr.c = attr.c.join(' ') + + if (oj.isArray(attr != null ? attr["class"] : void 0)) + attr["class"] = attr["class"].join(' ') + + // Move c to class + if ((attr != null ? attr.c : void 0) != null){ + if ((attr != null ? attr["class"] : void 0) != null) + attr["class"] += ' ' + attr.c + else + attr["class"] = attr.c + delete attr.c + } + + // Allow attributes to take style as an object + if (oj.isPlainObject(attr != null ? attr.style : void 0)){ + attr.style = _styleFromObject(attr.style, { + inline: true + }); + } + + // Omit attributes with values of false, null, or undefined + if (oj.isPlainObject(attr)){ + for (k in attr){ + v = attr[k] + if (v === null || v === void 0 || v === false) + delete attr[k] + } + } + + // Filter out jquery events + events = {} + if (oj.isPlainObject(attr)){ + + // Filter out attributes that are jquery events + for (k in attr){ + v = attr[k] + + // If this attribute (k) is an event + if (jqEvents[k] != null){ + events[k] = v + delete attr[k] + } + } + } + + // Returns bindable events + return events + }; + + // Bind events to dom + function _attributesBindEventsToDOM(events, el, inserts){ + var ek, ev, _results = [] + for (ek in events){ + ev = events[ek] + _a(oj.$ != null, "jquery is missing when binding a '" + ek + "' event") + // accumulate insert events manually since DOMNodeInserted is slow and depreciated + if (ek == 'insert' && inserts) + inserts.push(function(){ev.call(el,el)}) + else if (oj.isArray(ev)) + _results.push(oj.$(el)[ek].apply(this, ev)) + else + _results.push(oj.$(el)[ek](ev)) + } + return _results + }; + + // oj.toHTML: Compile directly to HTML only + oj.toHTML = function(options, ojml){ + + // Options is optional + if (!oj.isPlainObject(options)){ + ojml = options + options = {} + } + + // Create html only + _extend(options, {dom: 0, js: 0, html: 1, css: 0}) + return (oj.compile(options, ojml)).html + }; + + // oj.toCSS: Compile directly to CSS only + oj.toCSS = function(options, ojml){ + // Options is optional + if (!oj.isPlain(options)){ + ojml = options + options = {} + } + // Create css only + _extend(options, {dom: 0, js: 0, html: 0, css: 1}) + return (oj.compile(options, ojml)).css + }; + + // _inherit: Inherit Child from Parent + // Based on, but sadly incompatable with, coffeescript inheritance + function _inherit(Child, Parent){ + var Ctor, prop + + // Copy class properties and methods + for (prop in Parent) + oj.copyProperty(Child, Parent, prop) + + Ctor = function(){}; + Ctor.prototype = Parent.prototype; + Child.prototype = new Ctor() + + // Provide easy access for base class methods + // Example: Parent.base.methodName(arguments...) + Child.base = Child.__super__ = Parent.prototype + }; + + // _construct(Type, arg1, arg2, ...): Construct type as if using call + function _construct(Type){return new (FunP.bind.apply(Type, arguments))}; + + // oj.createType: Create OJ type with args object supporting: + // base, constructor, properties, and methods + oj.createType = function(name, args){ + + args = _d(args, {}) + args.methods = _d(args.methods, {}) + args.properties = _d(args.properties, {}) + + _v('createType', 1, name, 'string'); + _v('createType', 2, args, 'object'); + + var methodKeys, propKeys, typeProps, + + // When auto newing you need to delay construct the properties + // or they will be constructed twice. + delay = '__DELAYED__', + + // Constructor to return + Out = new Function("return function " + name + "(){\n var _t = this;\n if ( !(this instanceof " + name + ") ){\n _t = new " + name + "('" + delay + "');\n _t.__autonew__ = true;\n }\n\n if (arguments && arguments[0] != '" + delay + "')\n " + name + ".prototype.constructor.apply(_t, arguments);\n\n return _t;\n}")() + + // Default the constructor to call its base + if (args.base != null && (args.constructor == null || (!args.hasOwnProperty('constructor')))){ + args.constructor = function(){ + return Out.base != null ? Out.base.constructor.apply(this, arguments) : void 0 + } + } + + // Inherit if necessary + if (args.base != null) + _inherit(Out, args.base) + + // Add the constructor as a method + oj.addMethod(Out.prototype, 'constructor', args.constructor) + + // Mark new type and its instances with a non-enumerable type and isOJ properties + typeProps = { + type: { + value: Out, + writable: false, + enumerable: false + }, + typeName: { + value: name, + writable: false, + enumerable: false + }, + isOJ: { + value: true, + writable: false, + enumerable: false + } + } + oj.addProperties(Out, typeProps) + oj.addProperties(Out.prototype, typeProps) + + // Add properties all oj Types have + propKeys = (_keys(args.properties)).sort() + if (Out.prototype.properties != null) + propKeys = uniqueSort(Out.prototype.properties.concat(propKeys)) + + oj.addProperty(Out.prototype, 'properties', { + value: propKeys, + writable: false, + enumerable: false + }) + + // Add methods helper to instance + methodKeys = (_keys(args.methods)).sort() + if (Out.prototype.methods != null) + methodKeys = uniqueSort(Out.prototype.methods.concat(methodKeys)) + + oj.addProperty(Out.prototype, 'methods', { + value: methodKeys, + writable: false, + enumerable: false + }) + + // Add methods all oj Types have + _extend(args.methods, { + + // get: Get property by key or get all properties + get: function(k){ + // get specific property + if (oj.isString(k)){ + if (this.has(k)) + return this[k] + // get all properties + } else { + var out = {}, ix, p + for (ix = 0; ix < this.properties.length; ix++){ + p = this.properties[ix]; + out[p] = this[p]; + } + return out + } + }, + + // set: Set property by key, or set all properties with object + set: function(k, v){ + var key, obj = k, value; + + // Optionally take key, value instead of object + if (!oj.isPlainObject(k)){ + obj = {}; + obj[k] = v; + } + + // Set all keys that are valid properties + for (key in obj){ + value = obj[key]; + if (this.has(key)){ + this[key] = value; + } + } + }, + + // has: Determine if property exists + has: function(k){return this.properties.some(function(v){return v === k})}, + + // can: Determine if method exists + can: function(k){return this.methods.some(function(v){return v === k})}, + + // toJSON: Use properties to generate json + toJSON: function(){ + var json = {}, + prop, + ix = 0 + for (;ix < this.properties.length; ix++){ + prop = this.properties[ix] + json[prop] = this[prop] + } + return json + } + }); + + // Add methods + oj.addMethods(Out.prototype, args.methods); + + // Add the properties + oj.addProperties(Out.prototype, args.properties); + return Out; + }; + + // _createQuietType: Takes an OJ Type and creates the _Type that doesn't emit + _createQuietType = function(typeName){ + return oj[_getQuietTagName(typeName)] = function(){ + return _construct.apply(null, [oj[typeName]].concat(slice.call(arguments), [{ + __quiet__: 1 + }])); + } + } + + // oj.createEnum + oj.createEnum = function(name, args){_e('createEnum', 'NYI')} + + // oj.View + oj.View = oj.createType('View', { + + // Views are special objects map properties together. This is a union of arguments + // With the remaining arguments becoming a list + constructor: function(){ + _a(oj.isDOM(this.el), this.typeName, 'constructor did not set this.el') + + // Set instance on @el + _setInstanceOnElement(this.el, this) + + var u = oj.unionArguments(arguments), + options = u.options, + args = u.args + + // Emit as a tag if it isn't quiet or used new keyword + if (this.__autonew__ && !options.__quiet__) + this.emit() + + // Remove quiet flag as it has served its purpose + if (options.__quiet__ != null) + delete options.__quiet__ + + // Add class oj-typeName + this.$el.addClass("oj-" + this.typeName) + + // Views automatically set all options to their properties + // arguments directly to properties + this.set(options) + + // Remove options that were set + options = _clone(options); + this.properties.forEach(function(v){return delete options[v]}) + + // Views pass through remaining options to be attributes on the root element + // This can include jquery events and interpreted arguments + this.addAttributes(options) + + // Record if view is fully constructed + return this._isConstructed = true + }, + properties: { + // The element backing the View + el: { + get: function(){return this._el}, + set: function(v){ + // Set the element directly if this is a dom element + if (oj.isDOMElement(v)){ + this._el = v + // Clear cache of $el + this._$el = null + } else { + // Generate the dom element + this._el = oj.compile({dom:1, css:0, cssMap:0, html:0}, v).dom + } + } + }, + + // Get and cache jquery-enabled element (readonly) + $el: { + get: function(){ + return this._$el != null ? this._$el : (this._$el = oj.$(this.el)) + } + }, + + // Get and set id attribute of view + id: { + get: function(){return this.$el.attr('id')}, + set: function(v){return this.$el.attr('id', v)} + }, + // class: + // get: -> @$el.attr 'class' + // set: (v) -> + // # Join arrays with spaces + // if oj.isArray v + // v = v.join ' ' + // @$el.attr 'class', v + // return + // Alias for classes + // c: + // get: -> @class + // set: (v) -> @class = v; return + // Get all currently set attributes (readonly) + + attributes: { + get: function(){ + var out = {} + slice.call(this.el.attributes).forEach(function(attr){ + return out[attr.name] = attr.value + }) + return out + } + }, + + // Get all classes as an array (readwrite) + classes: { + get: function(){return this.$el.attr('class').split(/\s+/)}, + set: function(v){this.$el.attr('class', v.join(' '))} + }, + + // Get / set all currently set themes (readwrite) + themes: { + get: function(){ + var thms = [], + prefix = 'theme-', + ix = 0, + cls + for (; ix < this.classes.length; ix++){ + cls = this.classes[ix] + if (cls.indexOf(prefix) === 0) + thms.push(cls.slice(prefix.length)) + } + return thms + }, + set: function(v){ + if (!oj.isArray(v)) + v = [v] + this.clearThemes() + var theme, ix = 0 + for (;ix < v.length; ix++){ + theme = v[ix] + this.addTheme(theme) + } + } + }, + theme: { + get: function(){return this.themes}, + set: function(v){this.themes = v} + }, + + // Determine if this view has been fully constructed (readonly) + isConstructed: {get: function(){return _d(this._isConstructed, false)}}, + + // Determine if this view has been fully inserted (readonly) + isInserted: {get: function(){return _d(this._isInserted, false)}} + }, + methods: { + + // $: Find element from within root + $: function(){return this.$el.find.apply(this.$el, arguments)}, + + // addAttribute: Add a single attribute + addAttribute: function(name, value){ + var attr = {} + attr[name] = value + this.addAttributes(attr) + }, + + // addAttributes: Add attributes and apply the oj magic with jquery binding + addAttributes: function(attributes){ + var attr = _clone(attributes), + events = _attributesProcessedForOJ(attr), + k, v + + // Add attributes as object + if (oj.isPlainObject(attr)){ + for (k in attr){ + v = attr[k] + if (k === 'class') + this.addClass(v) + else if (v === true) + // Boolean attributes have no value + this.el.setAttributeNode(document.createAttribute(k)) + else + // Otherwise add it normally + this.$el.attr(k, v) + } + } + + // Bind events + if (events != null) + _attributesBindEventsToDOM(events, this.el) + }, + + // Remove a single attribute + removeAttribute: function(name){this.$el.removeAttr(name)}, + + // Remove multiple attributes + removeAttributes: function(list){var _t = this; list.forEach(function(v){_t.removeAttribute(v)})}, + + // Add a single class + addClass: function(name){this.$el.addClass(name)}, + + // Remove a single class + removeClass: function(name){this.$el.removeClass(name)}, + + // Determine if class is applied + hasClass: function(name){return this.$el.hasClass(name)}, + + // Add a single theme + addTheme: function(name){this.addClass("theme-" + name)}, + + // Remove a single theme + removeTheme: function(name){this.removeClass("theme-" + name)}, + + // Determine if theme is applied + hasTheme: function(name){return this.hasClass("theme-" + name)}, + + // Clear all themes + clearThemes: function(){var _t = this; this.themes.forEach(function(t){_t.removeTheme(t)}) }, + + // emit: Emit instance as a tag function would do + emit: function(){oj._argsAppend(this)}, + + // Convert View to html + toHTML: function(options){ + return this.el.outerHTML + ((options != null ? options.minify : void 0) ? '' : '\n'); + }, + + // Convert View to dom (for compiling) + toDOM: function(){return this.el}, + + // Convert + toCSS: function(options){ + return _cssFromPluginObject(_flattenCSSMap(this.cssMap), _extend({}, { + minify: options.minify, + tags: 0 + })); + }, + + // Convert + toCSSMap: function(){return this.type.cssMap}, + + // Convert View to string (for debugging) + toString: function(){return this.toHTML()}, + + // detach: -> throw 'detach nyi' + // The implementation is to set el manipulate it, and remember how to set it back + + // attach: -> throw 'attach nyi' + // The implementation is to unset el from detach + // inserted is called the instance is inserted in the dom (override) + + inserted: function(){return this._isInserted = true} + } + }); + + + // oj.View.cssMap: remember css for this View + oj.View.cssMap = {} + + // oj.View.css: set view's css with css object mapping, or raw css string + oj.View.css = function(css){ + _a(oj.isString(css) || oj.isPlainObject(css), this.typeName, 'object or string expected for first argument'); + + var cssMap, _base, _base1, _name, _name1, _ref2, _ref3; + + if (oj.isString(css)){ + if ((_ref2 = (_base = this.cssMap)[_name = "oj-" + this.typeName]) == null){ + _base[_name] = ""; + } + this.cssMap["oj-" + this.typeName] += css; + } else { + if ((_ref3 = (_base1 = this.cssMap)[_name1 = "oj-" + this.typeName]) == null){ + _base1[_name1] = {}; + } + cssMap = _setObject({}, ".oj-" + this.typeName, css); + _extend(this.cssMap["oj-" + this.typeName], cssMap); + } + }; + + // oj.View.themes: Remember themes for this View + oj.View.themes = [] + + // oj.View.theme: create a View specific theme with css object mapping + oj.View.theme = function(name, css){ + _v(this.typeName, 1, name, 'string'); + _v(this.typeName, 2, css, 'object'); + + // Calculate styleName + var dashName = _dasherize(name), + styleName = "oj-" + this.typeName, + + // Wrap css in plugin name + cssMap = _setObject({}, ".oj-" + this.typeName + ".theme-" + dashName, css) + + // Extend into this views cssMap + this.cssMap[styleName] = _d(this.cssMap[styleName], {}) + _extend(this.cssMap["oj-" + this.typeName], cssMap) + + // Remember the theme item + this.themes.push(dashName) + this.themes = uniqueSort(this.themes) + }; + + // oj.CollectionView: Inheritable base type that enables two-way collection binding + oj.CollectionView = oj.createType('CollectionView', { + base: oj.View, + constructor: function(options){ + if ((options != null ? options.each : void 0) != null) + this.each = oj.argumentShift(options, 'each') + + if ((options != null ? options.models : void 0) != null) + this.models = oj.argumentShift(options, 'models') + + oj.CollectionView.base.constructor.apply(this, arguments); + + // Once everything is constructed call make precisely once. + return this.make() + }, + properties: { + each: { + get: function(){return this._each}, + set: function(v){ + this._each = v + if (this.isConstructed) + this.make() + } + }, + collection: { + get: function(){return this.models}, + set: function(v){return this.models = v} + }, + models: { + get: function(){return this._models}, + set: function(v){ + // Unbind events if collection + if (oj.isFunction(this._models != null ? this._models.off : void 0)) + this._models.off('add remove change reset destroy', null, this) + + this._models = v + + // Bind events if collection + if (oj.isFunction(this._models != null ? this._models.on : void 0)){ + this._models.on('add', this.collectionModelAdded, this) + this._models.on('remove', this.collectionModelRemoved, this) + this._models.on('change', this.collectionModelChanged, this) + this._models.on('destroy', this.collectionModelDestroyed, this) + this._models.on('reset', this.collectionReset, this) + } + if (this.isConstructed) + this.make() + } + } + }, + methods: { + + // Override make to create your view + make: function(){_e(this.typeName, '`make` method not implemented by custom view')}, + + // Override these events to minimally update on change + collectionModelAdded: function(mod, cols){return this.make()}, + collectionModelRemoved: function(mod, cols, opt){return this.make()}, + collectionModelChanged: function(mod, cols, opt){}, + collectionModelDestroyed: function(cols, opt){return this.make()}, + collectionReset: function(cols, opt){return this.make()} + } + }); + + // oj.ModelView: Inheritable base type that enables two-way model binding + oj.ModelView = oj.createType('ModelView', { + base: oj.View, + constructor: function(options){ + if ((options != null ? options.value : void 0) != null) + this.value = oj.argumentShift(options, 'value') + + if ((options != null ? options.model : void 0) != null) + this.model = oj.argumentShift(options, 'model') + + return oj.ModelView.base.constructor.apply(this, arguments) + }, + properties: { + model: { + get: function(){ + return this._model + }, + set: function(v){ + // Unbind events on the old model + if (oj.isEvented(this._model)) + this._model.off('change', null, this); + + this._model = v + + // Bind events on the new model + if (oj.isEvented(this._model)) + this._model.on('change', this.modelChanged, this); + + // Trigger change manually when settings new model + this.modelChanged() + } + } + }, + methods: { + + // Override modelChanged if you don't want a full remake + modelChanged: function(){ + var _t = this; + return this.$el.oj(function(){ + return _t.make(_t.mode) + }); + }, + make: function(model){ + return _e(this.typeName, '`make` method not implemented by custom view'); + } + } + }); + + // oj.ModelViewView: Inheritable base type that enables two-way model binding to a specific key + oj.ModelKeyView = oj.createType('ModelKeyView', { + + // Inherit ModelView to handle model and bindings + base: oj.ModelView, + constructor: function(options){ + + if ((options != null ? options.key : void 0) != null) + this.key = oj.argumentShift(options, 'key') + + // Call super to bind model and value + return oj.ModelKeyView.base.constructor.apply(this, arguments); + }, + properties: { + // Key used to access model + key: null, + + // Override this property and call this.viewChanged when appropriate + value: { + get: function(){_e(this.typeName, 'value getter not implemented')}, + set: function(v){_e(this.typeName, 'value setter not implemented')} + } + }, + + methods: { + + // modelChanged: called by model binding code to + // automatically set this.value when the model changes + modelChanged: function(){ + if ((this.model != null) && (this.key != null)){ + // Update the view if necessary + if (!this._viewUpdatedModel) + this.value = this.model.get(this.key) + } + }, + + // viewChanged: Will set the model whenever this.value is set + viewChanged: function(){ + var _t = this + + // Briefly delay view changes because they often change before + // the controls visually update + setTimeout((function(){ + if ((_t.model != null) && (_t.key != null)){ + // Ensure view changes aren't triggered twice + _t._viewUpdatedModel = true + _t.model.set(_t.key, _t.value) + _t._viewUpdatedModel = false + } + }), 10) + } + } + }); + + // oj.TextBox + oj.TextBox = oj.createType('TextBox', { + base: oj.ModelKeyView, + constructor: function(){ + var _t = this, + u = oj.unionArguments(arguments), + options = u.options, + args = u.args + + this.el = oj(function(){ + oj.input({type: 'text'}, { + // When live changes are set indicate change on every keypress + // Delay change events slighty as value is visually updated after key presses + keydown: function(){ + if (_t.live) + setTimeout((function(){return _t.$el.change()}), 10) + }, + keyup: function(){ + if (_t.live) + setTimeout((function(){return _t.$el.change()}), 10) + }, + change: function(){_t.viewChanged()} + }) + }) + + // Value can be set by argument + if (args.length > 0) + this.value = args[0] + + // Set live if it exists + if ((options != null ? options.live : void 0) != null) + this.live = oj.argumentShift(options, 'live') + + return oj.TextBox.base.constructor.apply(this, [options]) + }, + properties: { + value: { + get: function(){ + var v = this.el.value + if ((v == null) || v === _udf) + v = '' + return v + }, + set: function(v){this.el.value = v} + }, + + // Live update model as text changes + live: true + } + }); + + // oj.CheckBox + oj.CheckBox = oj.createType('CheckBox', { + base: oj.ModelKeyView, + constructor: function(){ + var _t = this, + u = oj.unionArguments(arguments), + options = u.options, + args = u.args + + this.el = oj(function(){ + oj.input({type: 'checkbox'}, { + change: function(){_t.viewChanged()} + }) + }) + + // Value can be set by argument + if (args.length > 0) + this.value = args[0] + + return oj.CheckBox.base.constructor.call(this, options); + }, + properties: { + value: { + get: function(){return this.el.checked}, + set: function(v){ + this.el.checked = v = !!v + if (v) + this.$el.attr('checked', 'checked') + else + this.$el.removeAttr('checked') + } + } + } + }); + + // oj.Text + oj.Text = oj.createType('Text', { + base: oj.ModelKeyView, + constructor: function(){ + var _t = this, + u = oj.unionArguments(arguments), + options = u.options, + args = u.args + + // Get tag name if provided + this._tagName = oj.argumentShift(options, 'tagName') + + // Create element with tagName + this.el = oj(function(){ + return oj[_t.tagName]() + }); + + // Value can be set by argument + if (args.length > 0) + this.value = args[0] + + return oj.Text.base.constructor.call(this, options); + }, + + properties: { + // value: text value of this object (readwrite) + value: { + get: function(){return this.$el.ojValue()}, + set: function(v){this.$el.oj(v)} + }, + + // tagName: name of root tag (writeonce) + tagName: {get: function(){return _d(this._tagName, 'div')}} + } + }); + + // oj.TextArea + oj.TextArea = oj.createType('TextArea', { + base: oj.ModelKeyView, + constructor: function(){ + var _t = this, + u = oj.unionArguments(arguments), + options = u.options, + args = u.args + + this.el = oj(function(){ + return oj.textarea({ + // When live changes are set indicate change on every keypress + // Delay change events slighty as value is visually updated after key presses + keydown: function(){ + if (_t.live) + setTimeout((function(){return _t.$el.change()}), 10) + }, + keyup: function(){ + if (_t.live) + setTimeout((function(){return _t.$el.change()}), 10) + }, + change: function(){ + _t.viewChanged() + } + }); + }); + + // Value can be set by argument + this.value = oj.argumentShift(options, 'value') || args.join('\n') + return oj.TextArea.base.constructor.call(this, options) + }, + properties: { + value: { + get: function(){return this.el.value}, + set: function(v){this.el.value = v} + }, + + // Live update model as text changes + live: true + } + }); + + // oj.ListBox + oj.ListBox = oj.createType('ListBox', { + base: oj.ModelKeyView, + constructor: function(){ + var _t = this, + u = oj.unionArguments(arguments), + options = u.options, + args = u.args + + this.el = oj(function(){ + return oj.select({ + change: function(){_t.viewChanged()} + }) + }) + + // @options is a list of elements + this.options = oj.argumentShift(options, 'options'); + + // Value can be set by argument + if (args.length > 0) + this.value = args[0] + + return oj.ListBox.base.constructor.apply(this, [options]); + }, + properties: { + value: { + get: function(){ + return this.$el.val(); + }, + set: function(v){ + this.$el.val(v); + } + }, + options: { + get: function(){ + return this._options; + }, + set: function(v){ + if (!oj.isArray(v)){ + throw new Error("oj." + this.typeName + ".options array is missing"); + } + this._options = v; + this.$el.oj(function(){ + var op, _j, _len1; + + for (_j = 0, _len1 = v.length; _j < _len1; _j++){ + op = v[_j]; + oj.option(op); + } + }); + } + } + } + }); + + // oj.Button + oj.Button = oj.createType('Button', { + base: oj.View, + constructor: function(){ + var _t = this, + u = oj.unionArguments(arguments), + options = u.options, + args = u.args, + + // Label is first argument + title = '' + if (args.length > 0) + title = args[0] + + // Label is specified as option + if (options.title != null) + title = oj.argumentShift(options, 'title') + + // Create element + this.el = oj(function(){return oj.button(title)}) + + oj.Button.base.constructor.apply(this, [options]); + return this.title = title; + }, + properties: { + title: { + get: function(){return _d(this._title, '')}, + set: function(v){this.$el.oj((this._title = v))} + } + }, + methods: { + click: function(){ + if (arguments.length > 0) + return this.$el.click.apply(this.$el, arguments) + else + return this.$el.click() + } + } + }); + + // oj.List: List control with two-way collection binding + oj.List = oj.createType('List', { + base: oj.CollectionView, + constructor: function(){ + var _t = this, + u = oj.unionArguments(arguments), + options = u.options, + args = u.args, + items + + // tagName is write-once + this._tagName = oj.argumentShift(options, 'tagName') + this.itemTagName = oj.argumentShift(options, 'itemTagName') + + // Create the root element + this.el = oj(function(){return oj[_t.tagName]()}); + + // Use el if it was passed in + if (options.el != null) + this.el = oj.argumentShift(options, 'el') + + // Default @each function to pass through values + if (options.each == null){ + options.each = function(model){ + if (oj.isString(model) || oj.isNumber(model) || oj.isBoolean(model)) + return model + else + return JSON.stringify(model) + } + } + + // Args have been handled so don't pass them on + oj.List.base.constructor.apply(this, [options]); + + // Set @items to options or args if they exist + items = args.length > 0 ? args : null; + return this.items = options.items != null ? oj.argumentShift(options, 'items') : items; + }, + + properties: { + // items: get or set all items at once (readwrite) + items: { + get: function(){ + // Found in cache + if (this._items != null) + return this._items + + // Calc from ojValues + return this.$items.ojValues() + }, + set: function(v){ + this._items = v + this.make() + } + }, + count: {get: function(){return this.$items.length}}, + + // tagName: name of root tag (writeonce) + tagName: {get: function(){return _d(this._tagName, 'div')}}, + + // itemTagName: name of item tags (readwrite) + itemTagName: { + get: function(){return _d(this._itemTagName, 'div')}, + set: function(v){this._itemTagName = v; this.make();} + }, + + // $items: list of `
                            • ` elements (readonly) + $items: { + get: function(){ + // Get from cache or cache the recalculated list + return this._$items != null ? this._$items : this._$items = this.$("> " + this.itemTagName) + } + } + }, + + methods: { + // item: get or set item value at item ix + item: function(ix, ojml){ + ix = this._bound(ix, this.count, ".item: index") + if (ojml != null) + this.$item(ix).oj(ojml) + else + return this.$item(ix).ojValue() + }, + + // $item: `
                            • ` element for a given item ix. The tag name may change. + $item: function(ix){return this.$items.eq(this._bound(ix, this.count, ".$item: index"))}, + + // make: Remake view from model data using each + make: function(){ + // Do nothing until fully constructed + if (!this.isConstructed) + return + + // Some properties call make before construction completes + var _t = this, ix, model, models, views, out + + // Convert models to views using each + if ((this.models != null) && (this.each != null)){ + + // Get list of models from collection or array + models = oj.isEvented(this.models) ? this.models.models : this.models; + + // Add view item for every model + views = models.map(function(model){return _t._itemFromModel(model)}) + + // Items are already views so just use them + } else if (this.items != null) { + views = this.items + } + + // Render the views + this.$el.oj(function(){return views.map(function(view){_t._itemElFromItem(view)}) }) + + // Indicate to CollectionView the items changed + this.itemsChanged() + }, + + // collectionModelAdded: Model add occurred, add the item + collectionModelAdded: function(m, c){this.add(c.indexOf(m), this._itemFromModel(m))}, + + // collectionModelRemoved: Model remove occured, delete the item + collectionModelRemoved: function(m, c, o){this.remove(o.index)}, + + // collectionModelRemoved: Model reset occured, full rebuild + collectionReset: function(){this.make()}, + + // Helper Methods + // _itemFromModel: Helper to map model to item + _itemFromModel: function(model){ + var _t = this; + return oj(function(){return _t.each(model)}); + }, + + // _itemElFromItem: Helper to create itemTagName wrapped item + _itemElFromItem: function(item){ + return oj[this.itemTagName](item); + }, + + // _bound: Bound index to allow negatives, throw when out of range + _bound: function(ix, count, message){ + var ixNew = ix < 0 ? ix + count : ix + if (!(0 <= ixNew && ixNew < count)) + _e(this.typeName, message + " is out of bounds (" + ix + " in [0," + (count - 1) + "])") + return ixNew + }, + + // itemsChanged: Model changed occured, clear relevant cached values + itemsChanged: function(){this._items = null; this._$items = null}, + + // Manipulation Methods + add: function(ix, ojml){ + // ix defaults to -1 and is optional + if (ojml == null){ + ojml = ix + ix = -1 + } + + ix = this._bound(ix, this.count + 1, ".add: index") + var tag = this.itemTagName + + // Empty + if (this.count === 0) + this.$el.oj(function(){return oj[tag](ojml)}) + + // Last + else if (ix === this.count) + this.$item(ix - 1).ojAfter(function(){return oj[tag](ojml)}) + + // Not last + else + this.$item(ix).ojBefore(function(){return oj[tag](ojml)}) + + this.itemsChanged() + }, + + remove: function(ix){ + ix = _d(ix,-1) + ix = this._bound(ix, this.count, ".remove: index") + var out = this.item(ix) + this.$item(ix).remove() + this.itemsChanged() + return out + }, + + move: function(ixFrom, ixTo){ + ixTo = _d(ixTo, -1) + if (ixFrom === ixTo) + return + ixFrom = this._bound(ixFrom, this.count, ".move: fromIndex") + ixTo = this._bound(ixTo, this.count, ".move: toIndex") + if (ixTo > ixFrom) + this.$item(ixFrom).insertAfter(this.$item(ixTo)) + else + this.$item(ixFrom).insertBefore(this.$item(ixTo)) + this.itemsChanged() + }, + swap: function(ix1, ix2){ + if (ix1 === ix2) + return + ix1 = this._bound(ix1, this.count, ".swap: firstIndex"); + ix2 = this._bound(ix2, this.count, ".swap: secondIndex"); + if (Math.abs(ix1 - ix2) === 1) + this.move(ix1, ix2) + else { + var ixMin = Math.min(ix1, ix2), + ixMax = Math.max(ix1, ix2) + this.move(ixMax, ixMin) + this.move(ixMin + 1, ixMax) + } + this.itemsChanged() + }, + unshift: function(v){this.add(0, v)}, + shift: function(){return this.remove(0)}, + push: function(v){this.add(this.count, v)}, + pop: function(){return this.remove(-1)}, + clear: function(){this.$items.remove(); this.itemsChanged()} + } + }); + + + // oj.NumberList: NumberList is a `List` specialized with `
                                ` and `
                              1. ` tags + oj.NumberList = oj.createType('NumberList', { + base: oj.List, + constructor: function(){ + var args = [{tagName:'ol', itemTagName:'li'}].concat(slice.call(arguments)) + return oj.NumberList.base.constructor.apply(this, args) + } + }) + + // oj.BulletList: BulletList is a `List` specialized with `
                                  ` and `
                                • ` tags + oj.BulletList = oj.createType('BulletList', { + base: oj.List, + constructor: function(){ + var args = [{tagName:'ul', itemTagName:'li'}].concat(slice.call(arguments)) + return oj.BulletList.base.constructor.apply(this, args) + } + }) + + // oj.Table + oj.Table = oj.createType('Table', { + base: oj.CollectionView, + constructor: function(){ + var _t = this, + u = oj.unionArguments(arguments), + options = u.options, + args = u.args, + rows, ix + + // Generate root + this.el = oj(function(){return oj.table()}) + + // Use el if it was passed in + if (options.el != null) + this.el = oj.argumentShift(options, 'el') + + // Default @each function to pass through values + if (options.each == null){ + options.each = function(model, cell){ + var values = (oj.isString(model)) || (oj.isNumber(model)) || (oj.isBoolean(model)) ? [model] : (oj.isEvented(model)) && typeof model.attributes === 'object' ? _values(model.attributes) : _values(model) + return values.map(function(v){cell(v)}); + }; + } + + // Args have been handled so don't pass them on + oj.Table.base.constructor.apply(this, [options]); + + // Validate args as arrays + for(ix = 0; ix < args.length; ix++) + _a(oj.isArray(args[ix]), 'Table', 'array expected for row arguments') + + // Set @rows to options or args if they exist + rows = _d(oj.argumentShift(options, 'rows'), args) + if (rows.length > 0) + return this.rows = rows + }, + properties: { + + // rowCount: The number of rows (readonly) + rowCount: {get: function(){return this.$trs.length}}, + + // columnCount: The number of columns (readonly) + columnCount: {get: function(){ + // The number of columns is number of `
                            • ` in rows, header, or footer + var tflen, thlen, trlen + if ((trlen = this.$tr(0).find('> td').length) > 0) + return trlen + else if ((thlen = this.$theadTR.find('> th').length) > 0) + return thlen + else if ((tflen = this.$tfootTR.find('> td').length) > 0) + return tflen + return 0 + }}, + + // rows: Row values as a list of lists as interpreted by ojValue plugin (readwrite) + rows: { + get: function(){ + // Get cached result + if (this._rows != null) + return this._rows + + // Calculate rows by mapping from td to ojValue + var r, rx = 0 + this._rows = [] + for (; rx < this.rowCount; rx++){ + r = this.$tdsRow(rx).toArray().map(function(el){return $(el).ojValue()}) + this._rows.push(r); + } + return this._rows + }, + set: function(list){ + if (!((list != null) && list.length > 0)) + return this.clearBody() + this._rows = list + this.make() + } + }, + + // header: Array of header values as interpreted by ojValue plugin (readwrite) + header: { + get: function(){return this.$theadTR.find('> th').ojValues()}, + set: function(list){ + _a(oj.isArray(list), this.typeName + '.header', 'array expected for first argument') + + if (!((list != null) && list.length > 0)) + return this.clearHeader() + + return this.$theadTRMake.oj(function(){ + return list.map(function(ojml){oj.th(ojml)}) + }); + } + }, + + // footer: Array of footer values as interpreted by ojValue plugin (readwrite) + footer: { + get: function(){ + return this.$tfootTR.find('> td').ojValues(); + }, + set: function(list){ + var _t = this; + + if (!oj.isArray(list)){ + throw new Error('oj.Table.footer: array expected for first argument'); + } + if (!((list != null) && list.length > 0)){ + return this.clearFooter(); + } + return this.$tfootTRMake.oj(function(){ + var ojml, _j, _len1, _results; + + _results = []; + for (_j = 0, _len1 = list.length; _j < _len1; _j++){ + ojml = list[_j]; + _results.push(oj.td(ojml)); + } + return _results; + }); + } + }, + + // caption: The table caption (readwrite) + caption: { + get: function(){return this.$caption.ojValue()}, + set: function(v){this.$captionMake.oj(v)} + }, + + // Element accessors + $table: {get: function(){return this.$el}}, + $caption: {get: function(){return this.$('> caption')}}, + $colgroup: {get: function(){return this.$('> colgroup')}}, + $thead: {get: function(){return this.$('> thead')}}, + $tfoot: {get: function(){return this.$('> tfoot')}}, + $tbody: {get: function(){return this.$('> tbody')}}, + $theadTR: {get: function(){return this.$thead.find('> tr')}}, + $tfootTR: {get: function(){return this.$tfoot.find('> tr')}}, + $ths: {get: function(){return this.$theadTR.find('> th')}}, + $trs: {get: function(){ + // Cache or calculate + return this._$trs != null ? this._$trs : this._$trs = this.$("> tbody > tr") + }}, + + // Table tags must have an order: `` `` `` `` + // These accessors create table tags and preserve this order very carefully + // $colgroupMake: get or create `` after `
                              `s in row rx + $tdsRow: function(rx){ + rx = rx < 0 ? rx + count : rx + return this.$tr(rx).find('> td') + }, + + // $td: Get `` row rx, column cx + $td: function(rx, cx){ + rx = rx < 0 ? rx + this.rowCount : rx + cx = cx < 0 ? cx + this.columnCount : cx + return this.$tdsRow(rx).eq(cx) + }, + + // row: Get values at a given row + row: function(rx, listOJML){ + rx = this._bound(rx, this.rowCount, ".row: rx") + + if (listOJML != null){ + _a(listOJML.length === cellCount(rx), this.typeName, "array expected for second argument with length (" + rx + ")") + + // Set tds + listOJML.forEach(function(ojml,cx){ + this.$td(rx, cx).oj(ojml) + }) + + } else { + return this.$tdsRow(rx).ojValues() + } + }, + + // cell: Get or set value at row rx, column cx + cell: function(rx, cx, ojml){ + if (ojml != null) + return this.$td(rx, cx).oj(ojml) + else + return this.$td(rx, cx).ojValue() + }, + + // addRow: Add row to index rx + addRow: function(rx, listOJML){ + + if (listOJML == null){ + listOJML = rx + rx = -1 + } + rx = this._bound(rx, this.rowCount + 1, ".addRow: rx") + _a(oj.isArray(listOJML), 'addRow', 'expected array for row content') + + this._addRowTR(rx, function(){ + oj.tr(function(){ + listOJML.forEach(function(cell){ + oj.td(cell) + }) + }); + }); + }, + + // _addRowTR: Helper to add row directly with `
                              ` `` or prepended to `` + + $colgroupMake: {get: function(){ + if (this.$colgroup.length > 0) + return this.$colgroup + t = '' + if (this.$caption.length > 0) + this.$caption.insertAfter(t) + else + this.$table.append(t) + return this.$tbody + }}, + + // $captionMake: get or create ` from table fragments + if ( !jQuery.support.tbody ) { + + // String was a
                              ` prepended to `` + $captionMake: { + get: function(){ + if (this.$caption.length > 0) + return this.$caption + this.$table.prepend('') + return this.$caption + } + }, + + // $tfootMake: get or create `` before `` or appended to `
                              ` + $tfootMake: { + get: function(){ + if (this.$tfoot.length > 0) + return this.$tfoot + t = '' + if (this.$tfoot.length > 0) + this.$tfoot.insertBefore(t) + else + this.$table.append(t) + + return this.$tfoot + } + }, + + // $theadMake: get or create `` after `` or after `]", "i"), + rcheckableType = /^(?:checkbox|radio)$/, + // checked="checked" or checked + rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, + rscriptType = /\/(java|ecma)script/i, + rcleanScript = /^\s*\s*$/g, + wrapMap = { + option: [ 1, "" ], + legend: [ 1, "
                              ", "
                              " ], + thead: [ 1, "
                              `, or prepended to `` + $theadMake: { + get: function(){ + if (this.$thead.length > 0) + return this.$thead + t = '' + if (this.$colgroup.length > 0) + this.$colgroup.insertAfter(t); + else if (this.$caption.length > 0) + this.$caption.insertAfter(t) + else + this.$table.prepend(t) + return this.$thead + } + }, + + // $tbodyMake: get or create `` appened to `
                              ` + $tbodyMake: { + get: function(){ + if (this.$tbody.length > 0) + return this.$tbody + this.$table.append('') + return this.$tbody; + } + }, + + // $theadTRMake: get or create `` inside of `` + $theadTRMake: { + get: function(){ + if (this.$theadTR.length > 0) + return this.$theadTR + this.$theadMake.html('') + return this.$theadTR + } + }, + + // $tfootTRMake: get or create `` inside of `` + $tfootTRMake: { + get: function(){ + if (this.$tfootTR.length > 0) + return this.$tfootTR + this.$tfootMake.html('') + return this.$tfootTR + } + } + }, + + methods: { + + // make: Remake everything (override) + make: function(){ + if (!this.isConstructed) + return + + // Some properties call make before construction completes + var _t = this, models, rowViews = [] + + // Convert models to views if model/each exists + if ((this.models != null) && (this.each != null)){ + models = oj.isEvented(this.models) ? this.models.models : this._models + rowViews = models.map(function(model){return _t._rowFromModel(model)}) + // Convert rows to views + } else if (this.rows != null){ + rowViews = this.rows.map(function(row){ + return oj(function(){ + row.forEach(function(cell){oj.td(cell)}) + }) + }) + } + + // Render rows into tbody + if (rowViews.length > 0) + this.$tbodyMake.oj(function(){ + rowViews.forEach(function(r){ + oj.tr(r) + }) + }) + + this.bodyChanged() + }, + + collectionModelAdded: function(m, c){ + var rx = c.indexOf(m), + row = this._rowFromModel(m) + this._addRowTR(rx, oj(function(){ + return oj.tr(row) + })) + }, + + collectionModelRemoved: function(m, c, o){this.removeRow(o.index)}, + + collectionReset: function(){this.make()}, + + // $tr: Get `` jquery element at row rx + $tr: function(rx){ + rx = rx < 0 ? rx + count : rx + return this.$trs.eq(rx) + }, + + // $tdsRow: Get list of `` + _addRowTR: function(rx, tr){ + // Empty + if (this.rowCount === 0) + this.$el.oj(tr) + + // Last + else if (rx === this.rowCount) + this.$tr(rx - 1).ojAfter(tr) + + // Not last + else + this.$tr(rx).ojBefore(tr) + + this.bodyChanged() + }, + + // removeRow: Remove row at index rx (defaults to end) + removeRow: function(rx){ + if (rx == null) + rx = -1 + rx = this._bound(rx, this.rowCount, ".removeRow: index"); + var out = this.row(rx) + this.$tr(rx).remove() + this.bodyChanged() + return out + }, + + // moveRow: Move row at index rx (defaults to end) + moveRow: function(rxFrom, rxTo){ + if (rxFrom === rxTo) + return + + rxFrom = this._bound(rxFrom, this.rowCount, ".moveRow: fromIndex") + rxTo = this._bound(rxTo, this.rowCount, ".moveRow: toIndex") + var insert = rxTo > rxFrom ? 'insertAfter' : 'insertBefore' + this.$tr(rxFrom)[insert](this.$tr(rxTo)) + this.bodyChanged(); + }, + + // swapRow: Swap row rx1 and rx2 + swapRow: function(rx1, rx2){ + if (rx1 === rx2) + return + rx1 = this._bound(rx1, this.rowCount, ".swap: firstIndex"); + rx2 = this._bound(rx2, this.rowCount, ".swap: secondIndex"); + if (Math.abs(rx1 - rx2) === 1) + this.moveRow(rx1, rx2) + else { + var rxMin = Math.min(rx1, rx2), + rxMax = Math.max(rx1, rx2) + this.moveRow(rxMax, rxMin); + this.moveRow(rxMin + 1, rxMax); + } + this.bodyChanged(); + }, + unshiftRow: function(v){this.addRow(0, v)}, + shiftRow: function(){return this.removeRow(0)}, + pushRow: function(v){this.addRow(this.rowCount, v)}, + popRow: function(){return this.removeRow(-1)}, + clearColgroup: function(){this.$colgroup.remove()}, + clearBody: function(){ + this.$tbody.remove(); + this.bodyChanged(); + }, + clearHeader: function(){ + this.$thead.remove(); + this.headerChanged(); + }, + clearFooter: function(){ + this.$tfoot.remove(); + this.footerChanged(); + }, + clearCaption: function(){ + this.$capation.remove(); + }, + clear: function(){ + this.clearBody(); + this.clearHeader(); + this.clearFooter(); + return this.$caption.remove(); + }, + + // When body changes clear relevant cached values + bodyChanged: function(){this._rows = null; this._columns = null; this._$trs = null}, + + // When header changes clear relevant cached values + headerChanged: function(){this._header = null}, + + // When footer changes clear relevant cached values + footerChanged: function(){this._footer = null}, + + // _rowFromModel: Helper to map model to row + _rowFromModel: function(model){ + var _t = this; + return oj(function(){ + return _t.each(model, oj.td); + }); + }, + + // _bound: Bound index to allow negatives, throw when out of range + _bound: function(ix, count, message){ + var ixNew = ix < 0 ? ix + count : ix + if (!(0 <= ixNew && ixNew < count)){ + throw new Error("oj." + this.typeName + message + " is out of bounds (" + ix + " in [0," + (count - 1) + "])"); + } + return ixNew; + } + } + }); + + // Create Quiet _Types + for (var typeName in oj){ + // Type with captital first letter that doesn't end in "View" + if (_isCapitalLetter(typeName[0]) && typeName.slice(typeName.length - 4) !== 'View'){ + oj[_getQuietTagName(typeName)] = _createQuietType(typeName); + } + } + + // oj.sandbox: The sandbox is a readonly version of oj exposed to the user when templating server-side + oj.sandbox = {}; + _keys(oj).forEach(function(key){ + if ((key.length > 0 && key[0] !== '_') || (key.length > 0 && key[0] === '_' && (oj[key.slice(1)] != null))){ + oj.addProperty(oj.sandbox, key, {value: oj[key], writable: false}); + } + }) + + // oj.use(plugin, settings): import a plugin of OJ with optional settings + oj.use = function(plugin, settings){ + settings = _d(settings, {}) + _v('use', 1, plugin, 'function') + _v('use', 2, settings, 'object') + + // Call plugin to gather extension map + var pluginResult = plugin(oj, settings), + pluginMap = _clone(pluginResult), + name, value + + // Add _Type quiet types + for (name in pluginResult){ + value = pluginResult[name] + if (oj.isOJType(value)) + pluginMap[_getQuietTagName(name)] = _createQuietType(value.typeName); + } + + // Extend all properties + for (name in pluginMap){ + value = pluginMap[name] + + // Add to oj + oj[name] = value + + // Add plugin to sandbox + oj.addProperty(oj.sandbox, name, {value: value, writable: false}) + } + }; + + // _jqExtend(fn): Create a jquery plugin with the following options: + // option.get is called to retrieve value per element + // option.set is called when setting elements + // option.first:true means return only the first get, + // otherwise it is returned as an array + function _jqExtend(options){ + if (options == null) + options = {} + + options = _extend({ + get: pass, + set: pass, + first: false + }, options) + + return function(){ + var el, out, r, ix, + args = _toArray(arguments), + $els = jQuery(this) + + // Map over jquery selection if no arguments + if ((oj.isFunction(options.get)) && args.length === 0){ + out = [] + for (ix = 0; ix < $els.length; ix++){ + el = $els[ix]; + out.push(options.get(oj.$(el))) + if (options.first) + return out[0] + } + return out + } else if (oj.isFunction(options.set)){ + + // By default return this for chaining + out = $els; + for (ix = 0; ix < $els.length; ix++){ + el = $els[ix] + r = options.set(oj.$(el), args) + // Short circuit if anything is returned + if (r != null) + return r + } + return $els + } + }; + }; + + function _triggerInserted(types, inserts){ + var ix = 0 + for (; ix < types.length; ix++) + types[ix].inserted() + if(inserts) { + for (ix = 0; ix < inserts.length; ix++) + inserts[ix]() + } + } + + function _insertStyles(pluginMap, options){ + var mediaMap, plugin + for (plugin in pluginMap){ + mediaMap = pluginMap[plugin] + + // Skip global css if options.global is true + if (plugin === 'oj-style' && !(options != null ? options.global : 0)) + continue + + // Create "+o);return f}function Q(e,t,n){var r=n.indent;n.indent+=" ",e(t,n),n.indent=r}function G(e,t){if(l.isArray(e))Y(e,t);else if(l.isString(e)){t.html!=null&&t.html.push(e);if(e.length>0&&e[0]==="<"){var n=document.createElement("div");n.innerHTML=e,t.dom!=null&&t.dom.appendChild(n)}else t.dom!=null&&t.dom.appendChild(document.createTextNode(e))}else l.isBoolean(e)||l.isNumber(e)?(t.html!=null&&t.html.push(""+e),t.dom!=null&&t.dom.appendChild(document.createTextNode(""+e))):l.isFunction(e)?G(l(e),t):l.isDate(e)?(t.html!=null&&t.html.push(""+e.toLocaleString()),t.dom!=null&&t.dom.appendChild(document.createTextNode(""+e.toLocaleString()))):l.isOJ(e)&&(t.types!=null&&t.types.push(e),t.html!=null&&t.html.push(e.toHTML(t)),t.dom!=null&&t.dom.appendChild(e.toDOM(t)),t.css!=null&&d(t.css,e.toCSSMap(t)))}function Y(e,t){if(e.length===0)return;var n=e[0],r=typeof n,i=l.unionArguments(e.slice(1)),s=i.options,o=i.args,u,a;if(r==="function"||r==="object")n=x(_(n),n);l.isString(n)&&n.length>0||T("compile","tag name is missing"),t.tags[n]=!0;if(v(n[0]))return Q(G,new l[n](e.slice(1)),t);if(t.css&&n==="css")for(a in s)u=s[a],t.css.oj=x(t.css.oj,{}),t.css.oj[a]=x(t.css.oj[a],{}),d(t.css.oj[a],u);if(n==="!DOCTYPE"){C("compile",1,e[1],"string"),t.ignore[n]||t.html&&t.html.push("<"+n+" "+e[1]+">");return}if(!t.ignore[n]){var f=Z(s),c;if(t.dom&&typeof document!="undefined"&&document!==null){c=document.createElement(n),l.isDOMElement(t.dom)&&t.dom.appendChild(c),t.dom=c;if(l.isPlainObject(s)){var h=p(s).sort(),m,g,y;for(m=0;m")}}if(t.ignore[n]!=="deep")for(m=0;m1&&t.html.push("\n "+t.indent),Q(G,E,t)}t.html!=null&&!t.minify&&o.length>1&&t.html.push("\n"+t.indent),t.ignore[n]||(t.html!=null&&(o.length>0||l.tag.isClosed(n))&&t.html.push(""),t.dom&&(t.dom=t.dom.parentNode))}function Z(e){var t={bind:1,on:1,off:1,live:1,blur:1,change:1,click:1,dblclick:1,focus:1,focusin:1,focusout:1,hover:1,keydown:1,keypress:1,keyup:1,mousedown:1,mouseenter:1,mouseleave:1,mousemove:1,mouseout:1,mouseup:1,ready:1,resize:1,scroll:1,select:1,insert:1},n,r,i;l.isArray(e!=null?e.c:void 0)&&(e.c=e.c.join(" ")),l.isArray(e!=null?e["class"]:void 0)&&(e["class"]=e["class"].join(" ")),(e!=null?e.c:void 0)!=null&&((e!=null?e["class"]:void 0)!=null?e["class"]+=" "+e.c:e["class"]=e.c,delete e.c),l.isPlainObject(e!=null?e.style:void 0)&&(e.style=U(e.style,{inline:!0}));if(l.isPlainObject(e))for(r in e)i=e[r],(i===null||i===void 0||i===!1)&&delete e[r];n={};if(l.isPlainObject(e))for(r in e)i=e[r],t[r]!=null&&(n[r]=i,delete e[r]);return n}function et(e,t,n){var r,i,s=[];for(r in e)i=e[r],N(l.$!=null,"jquery is missing when binding a '"+r+"' event"),r=="insert"&&n?n.push(function(){i.call(t,t)}):l.isArray(i)?s.push(l.$(t)[r].apply(this,i)):s.push(l.$(t)[r](i));return s}function tt(e,t){var n,r;for(r in t)l.copyProperty(e,t,r);n=function(){},n.prototype=t.prototype,e.prototype=new n,e.base=e.__super__=t.prototype}function nt(e){return new(r.bind.apply(e,arguments))}function it(e){return e==null&&(e={}),e=d({get:a,set:a,first:!1},e),function(){var t,n,r,i,s=y(arguments),o=jQuery(this);if(l.isFunction(e.get)&&s.length===0){n=[];for(i=0;i=0)i=e[r],i==="."?e.splice(r,1):i===".."?(e.splice(r,1),n++):n&&(e.splice(r,1),n--),r--;if(t)while(n--)e.unshift("..");return e}var e=this,n=Array.prototype,r=Function.prototype,i=Object.prototype,s=n.slice,o=n.unshift,u=n.concat,a=function(e){return e},f="undefined";l.version="0.2.1",l.isClient=!(typeof process!="undefined"&&process!==null?process.versions!=null?process.versions.node:0:0);if(typeof $!=f)l.$=$;else if(typeof require!=f)try{l.$=require("jquery")}catch(c){}typeof require!=f?module.exports=l:e.oj=l,l.oj=l,l.load=function(e){return l.$(function(){return l.$.ojBody(require(e)),l.onload()})};var h={queue:[],loaded:!1};l.onload=function(e){if(l.isUndefined(e)){h.loaded=!0;while(e=h.queue.shift())e()}else h.loaded?e():h.queue.push(e)},l.emit=function(){return l.tag.apply(l,["oj"].concat(s.call(arguments)))},l.isDefined=function(e){return typeof e!==f},l.isOJ=function(e){return e!=null?!!e.isOJ:!!void 0},l.isOJType=function(e){return l.isOJ(e)&&e.type===e},l.isOJInstance=function(e){return l.isOJ(e)&&!l.isOJType(e)},l.isEvented=function(e){return!!(e&&e.on&&e.off&&e.trigger)},l.isDOM=function(e){return!!e&&e.nodeType!=null},l.isDOMElement=function(e){return!!e&&e.nodeType===1},l.isDOMAttribute=function(e){return!!e&&e.nodeType===2},l.isDOMText=function(e){return!!e&&e.nodeType===3},l.isjQuery=function(e){return!!e&&!!e.jquery},l.isUndefined=function(e){return e===void 0},l.isBoolean=function(e){return e===!0||e===!1||i.toString.call(e)==="[object Boolean]"},l.isNumber=function(e){return!!(e===0||e&&e.toExponential&&e.toFixed)},l.isString=function(e){return!!(e===""||e&&e.charCodeAt&&e.substr)},l.isDate=function(e){return!!(e&&e.getTimezoneOffset&&e.setUTCFullYear)},l.isPlainObject=function(e){return l.$.isPlainObject(e)&&!l.isOJ(e)},l.isFunction=l.$.isFunction,l.isArray=l.$.isArray,l.isRegEx=function(e){return i.toString.call(e)==="[object RegExp]"},l.isArguments=function(e){return i.toString.call(e)==="[object Arguments]"},l.parse=function(e){var t,n=e;return e===f?n=void 0:e==="null"?n=null:e==="true"?n=!0:e==="false"?n=!1:isNaN(t=parseFloat(e))||(n=t),n},l.unionArguments=function(e){var t={},n=[],r,i=0;for(;i'+r+i+""},l.toHTML=function(e,t){return l.isPlainObject(e)||(t=e,e={}),d(e,{dom:0,js:0,html:1,css:0}),l.compile(e,t).html},l.toCSS=function(e,t){return l.isPlain(e)||(t=e,e={}),d(e,{dom:0,js:0,html:0,css:1}),l.compile(e,t).css},l.createType=function(e,t){t=x(t,{}),t.methods=x(t.methods,{}),t.properties=x(t.properties,{}),C("createType",1,e,"string"),C("createType",2,t,"object");var n,r,i,s="__DELAYED__",o=(new Function("return function "+e+"(){\n var _t = this;\n if ( !(this instanceof "+e+") ){\n _t = new "+e+"('"+s+"');\n _t.__autonew__ = true;\n }\n\n if (arguments && arguments[0] != '"+s+"')\n "+e+".prototype.constructor.apply(_t, arguments);\n\n return _t;\n}"))();return t.base!=null&&(t.constructor==null||!t.hasOwnProperty("constructor"))&&(t.constructor=function(){return o.base!=null?o.base.constructor.apply(this,arguments):void 0}),t.base!=null&&tt(o,t.base),l.addMethod(o.prototype,"constructor",t.constructor),i={type:{value:o,writable:!1,enumerable:!1},typeName:{value:e,writable:!1,enumerable:!1},isOJ:{value:!0,writable:!1,enumerable:!1}},l.addProperties(o,i),l.addProperties(o.prototype,i),r=p(t.properties).sort(),o.prototype.properties!=null&&(r=S(o.prototype.properties.concat(r))),l.addProperty(o.prototype,"properties",{value:r,writable:!1,enumerable:!1}),n=p(t.methods).sort(),o.prototype.methods!=null&&(n=S(o.prototype.methods.concat(n))),l.addProperty(o.prototype,"methods",{value:n,writable:!1,enumerable:!1}),d(t.methods,{get:function(e){if(!l.isString(e)){var t={},n,r;for(n=0;n0&&(this.value=r[0]),(n!=null?n.live:void 0)!=null&&(this.live=l.argumentShift(n,"live")),l.TextBox.base.constructor.apply(this,[n])},properties:{value:{get:function(){var e=this.el.value;if(e==null||e===f)e="";return e},set:function(e){this.el.value=e}},live:!0}}),l.CheckBox=l.createType("CheckBox",{base:l.ModelKeyView,constructor:function(){var e=this,t=l.unionArguments(arguments),n=t.options,r=t.args;return this.el=l(function(){l.input({type:"checkbox"},{change:function(){e.viewChanged()}})}),r.length>0&&(this.value=r[0]),l.CheckBox.base.constructor.call(this,n)},properties:{value:{get:function(){return this.el.checked},set:function(e){this.el.checked=e=!!e,e?this.$el.attr("checked","checked"):this.$el.removeAttr("checked")}}}}),l.Text=l.createType("Text",{base:l.ModelKeyView,constructor:function(){var e=this,t=l.unionArguments(arguments),n=t.options,r=t.args;return this._tagName=l.argumentShift(n,"tagName"),this.el=l(function(){return l[e.tagName]()}),r.length>0&&(this.value=r[0]),l.Text.base.constructor.call(this,n)},properties:{value:{get:function(){return this.$el.ojValue()},set:function(e){this.$el.oj(e)}},tagName:{get:function(){return x(this._tagName,"div")}}}}),l.TextArea=l.createType("TextArea",{base:l.ModelKeyView,constructor:function(){var e=this,t=l.unionArguments(arguments),n=t.options,r=t.args;return this.el=l(function(){return l.textarea({keydown:function(){e.live&&setTimeout(function(){return e.$el.change()},10)},keyup:function(){e.live&&setTimeout(function(){return e.$el.change()},10)},change:function(){e.viewChanged()}})}),this.value=l.argumentShift(n,"value")||r.join("\n"),l.TextArea.base.constructor.call(this,n)},properties:{value:{get:function(){return this.el.value},set:function(e){this.el.value=e}},live:!0}}),l.ListBox=l.createType("ListBox",{base:l.ModelKeyView,constructor:function(){var e=this,t=l.unionArguments(arguments),n=t.options,r=t.args;return this.el=l(function(){return l.select({change:function(){e.viewChanged()}})}),this.options=l.argumentShift(n,"options"),r.length>0&&(this.value=r[0]),l.ListBox.base.constructor.apply(this,[n])},properties:{value:{get:function(){return this.$el.val()},set:function(e){this.$el.val(e)}},options:{get:function(){return this._options},set:function(e){if(!l.isArray(e))throw new Error("oj."+this.typeName+".options array is missing");this._options=e,this.$el.oj(function(){var t,n,r;for(n=0,r=e.length;n0&&(i=r[0]),n.title!=null&&(i=l.argumentShift(n,"title")),this.el=l(function(){return l.button(i)}),l.Button.base.constructor.apply(this,[n]),this.title=i},properties:{title:{get:function(){return x(this._title,"")},set:function(e){this.$el.oj(this._title=e)}}},methods:{click:function(){return arguments.length>0?this.$el.click.apply(this.$el,arguments):this.$el.click()}}}),l.List=l.createType("List",{base:l.CollectionView,constructor:function(){var e=this,t=l.unionArguments(arguments),n=t.options,r=t.args,i;return this._tagName=l.argumentShift(n,"tagName"),this.itemTagName=l.argumentShift(n,"itemTagName"),this.el=l(function(){return l[e.tagName]()}),n.el!=null&&(this.el=l.argumentShift(n,"el")),n.each==null&&(n.each=function(e){return l.isString(e)||l.isNumber(e)||l.isBoolean(e)?e:JSON.stringify(e)}),l.List.base.constructor.apply(this,[n]),i=r.length>0?r:null,this.items=n.items!=null?l.argumentShift(n,"items"):i},properties:{items:{get:function(){return this._items!=null?this._items:this.$items.ojValues()},set:function(e){this._items=e,this.make()}},count:{get:function(){return this.$items.length}},tagName:{get:function(){return x(this._tagName,"div")}},itemTagName:{get:function(){return x(this._itemTagName,"div")},set:function(e){this._itemTagName=e,this.make()}},$items:{get:function(){return this._$items!=null?this._$items:this._$items=this.$("> "+this.itemTagName)}}},methods:{item:function(e,t){e=this._bound(e,this.count,".item: index");if(t==null)return this.$item(e).ojValue();this.$item(e).oj(t)},$item:function(e){return this.$items.eq(this._bound(e,this.count,".$item: index"))},make:function(){if(!this.isConstructed)return;var e=this,t,n,r,i,s;this.models!=null&&this.each!=null?(r=l.isEvented(this.models)?this.models.models:this.models,i=r.map(function(t){return e._itemFromModel(t)})):this.items!=null&&(i=this.items),this.$el.oj(function(){return i.map(function(t){e._itemElFromItem(t)})}),this.itemsChanged()},collectionModelAdded:function(e,t){this.add(t.indexOf(e),this._itemFromModel(e))},collectionModelRemoved:function(e,t,n){this.remove(n.index)},collectionReset:function(){this.make()},_itemFromModel:function(e){var t=this;return l(function(){return t.each(e)})},_itemElFromItem:function(e){return l[this.itemTagName](e)},_bound:function(e,t,n){var r=e<0?e+t:e;return 0<=r&&re?this.$item(e).insertAfter(this.$item(t)):this.$item(e).insertBefore(this.$item(t)),this.itemsChanged()},swap:function(e,t){if(e===t)return;e=this._bound(e,this.count,".swap: firstIndex"),t=this._bound(t,this.count,".swap: secondIndex");if(Math.abs(e-t)===1)this.move(e,t);else{var n=Math.min(e,t),r=Math.max(e,t);this.move(r,n),this.move(n+1,r)}this.itemsChanged()},unshift:function(e){this.add(0,e)},shift:function(){return this.remove(0)},push:function(e){this.add(this.count,e)},pop:function(){return this.remove(-1)},clear:function(){this.$items.remove(),this.itemsChanged()}}}),l.NumberList=l.createType("NumberList",{base:l.List,constructor:function(){var e=[{tagName:"ol",itemTagName:"li"}].concat(s.call(arguments));return l.NumberList.base.constructor.apply(this,e)}}),l.BulletList=l.createType("BulletList",{base:l.List,constructor:function(){var e=[{tagName:"ul",itemTagName:"li"}].concat(s.call(arguments));return l.BulletList.base.constructor.apply(this,e)}}),l.Table=l.createType("Table",{base:l.CollectionView,constructor:function(){var e=this,t=l.unionArguments(arguments),n=t.options,r=t.args,i,s;this.el=l(function(){return l.table()}),n.el!=null&&(this.el=l.argumentShift(n,"el")),n.each==null&&(n.each=function(e,t){var n=l.isString(e)||l.isNumber(e)||l.isBoolean(e)?[e]:l.isEvented(e)&&typeof e.attributes=="object"?g(e.attributes):g(e);return n.map(function(e){t(e)})}),l.Table.base.constructor.apply(this,[n]);for(s=0;s0)return this.rows=i},properties:{rowCount:{get:function(){return this.$trs.length}},columnCount:{get:function(){var e,t,n;return(n=this.$tr(0).find("> td").length)>0?n:(t=this.$theadTR.find("> th").length)>0?t:(e=this.$tfootTR.find("> td").length)>0?e:0}},rows:{get:function(){if(this._rows!=null)return this._rows;var e,t=0;this._rows=[];for(;t0))return this.clearBody();this._rows=e,this.make()}},header:{get:function(){return this.$theadTR.find("> th").ojValues()},set:function(e){return N(l.isArray(e),this.typeName+".header","array expected for first argument"),e!=null&&e.length>0?this.$theadTRMake.oj(function(){return e.map(function(e){l.th(e)})}):this.clearHeader()}},footer:{get:function(){return this.$tfootTR.find("> td").ojValues()},set:function(e){var t=this;if(!l.isArray(e))throw new Error("oj.Table.footer: array expected for first argument");return e!=null&&e.length>0?this.$tfootTRMake.oj(function(){var t,n,r,i;i=[];for(n=0,r=e.length;n caption")}},$colgroup:{get:function(){return this.$("> colgroup")}},$thead:{get:function(){return this.$("> thead")}},$tfoot:{get:function(){return this.$("> tfoot")}},$tbody:{get:function(){return this.$("> tbody")}},$theadTR:{get:function(){return this.$thead.find("> tr")}},$tfootTR:{get:function(){return this.$tfoot.find("> tr")}},$ths:{get:function(){return this.$theadTR.find("> th")}},$trs:{get:function(){return this._$trs!=null?this._$trs:this._$trs=this.$("> tbody > tr")}},$colgroupMake:{get:function(){return this.$colgroup.length>0?this.$colgroup:(t="",this.$caption.length>0?this.$caption.insertAfter(t):this.$table.append(t),this.$tbody)}},$captionMake:{get:function(){return this.$caption.length>0?this.$caption:(this.$table.prepend(""),this.$caption)}},$tfootMake:{get:function(){return this.$tfoot.length>0?this.$tfoot:(t="",this.$tfoot.length>0?this.$tfoot.insertBefore(t):this.$table.append(t),this.$tfoot)}},$theadMake:{get:function(){return this.$thead.length>0?this.$thead:(t="",this.$colgroup.length>0?this.$colgroup.insertAfter(t):this.$caption.length>0?this.$caption.insertAfter(t):this.$table.prepend(t),this.$thead)}},$tbodyMake:{get:function(){return this.$tbody.length>0?this.$tbody:(this.$table.append(""),this.$tbody)}},$theadTRMake:{get:function(){return this.$theadTR.length>0?this.$theadTR:(this.$theadMake.html(""),this.$theadTR)}},$tfootTRMake:{get:function(){return this.$tfootTR.length>0?this.$tfootTR:(this.$tfootMake.html(""),this.$tfootTR)}}},methods:{make:function(){if(!this.isConstructed)return;var e=this,t,n=[];this.models!=null&&this.each!=null?(t=l.isEvented(this.models)?this.models.models:this._models,n=t.map(function(t){return e._rowFromModel(t)})):this.rows!=null&&(n=this.rows.map(function(e){return l(function(){e.forEach(function(e){l.td(e)})})})),n.length>0&&this.$tbodyMake.oj(function(){n.forEach(function(e){l.tr(e)})}),this.bodyChanged()},collectionModelAdded:function(e,t){var n=t.indexOf(e),r=this._rowFromModel(e);this._addRowTR(n,l(function(){return l.tr(r)}))},collectionModelRemoved:function(e,t,n){this.removeRow(n.index)},collectionReset:function(){this.make()},$tr:function(e){return e=e<0?e+count:e,this.$trs.eq(e)},$tdsRow:function(e){return e=e<0?e+count:e,this.$tr(e).find("> td")},$td:function(e,t){return e=e<0?e+this.rowCount:e,t=t<0?t+this.columnCount:t,this.$tdsRow(e).eq(t)},row:function(e,t){e=this._bound(e,this.rowCount,".row: rx");if(t==null)return this.$tdsRow(e).ojValues();N(t.length===cellCount(e),this.typeName,"array expected for second argument with length ("+e+")"),t.forEach(function(t,n){this.$td(e,n).oj(t)})},cell:function(e,t,n){return n!=null?this.$td(e,t).oj(n):this.$td(e,t).ojValue()},addRow:function(e,t){t==null&&(t=e,e=-1),e=this._bound(e,this.rowCount+1,".addRow: rx"),N(l.isArray(t),"addRow","expected array for row content"),this._addRowTR(e,function(){l.tr(function(){t.forEach(function(e){l.td(e)})})})},_addRowTR:function(e,t){this.rowCount===0?this.$el.oj(t):e===this.rowCount?this.$tr(e-1).ojAfter(t):this.$tr(e).ojBefore(t),this.bodyChanged()},removeRow:function(e){e==null&&(e=-1),e=this._bound(e,this.rowCount,".removeRow: index");var t=this.row(e);return this.$tr(e).remove(),this.bodyChanged(),t},moveRow:function(e,t){if(e===t)return;e=this._bound(e,this.rowCount,".moveRow: fromIndex"),t=this._bound(t,this.rowCount,".moveRow: toIndex");var n=t>e?"insertAfter":"insertBefore";this.$tr(e)[n](this.$tr(t)),this.bodyChanged()},swapRow:function(e,t){if(e===t)return;e=this._bound(e,this.rowCount,".swap: firstIndex"),t=this._bound(t,this.rowCount,".swap: secondIndex");if(Math.abs(e-t)===1)this.moveRow(e,t);else{var n=Math.min(e,t),r=Math.max(e,t);this.moveRow(r,n),this.moveRow(n+1,r)}this.bodyChanged()},unshiftRow:function(e){this.addRow(0,e)},shiftRow:function(){return this.removeRow(0)},pushRow:function(e){this.addRow(this.rowCount,e)},popRow:function(){return this.removeRow(-1)},clearColgroup:function(){this.$colgroup.remove()},clearBody:function(){this.$tbody.remove(),this.bodyChanged()},clearHeader:function(){this.$thead.remove(),this.headerChanged()},clearFooter:function(){this.$tfoot.remove(),this.footerChanged()},clearCaption:function(){this.$capation.remove()},clear:function(){return this.clearBody(),this.clearHeader(),this.clearFooter(),this.$caption.remove()},bodyChanged:function(){this._rows=null,this._columns=null,this._$trs=null},headerChanged:function(){this._header=null},footerChanged:function(){this._footer=null},_rowFromModel:function(e){var t=this;return l(function(){return t.each(e,l.td)})},_bound:function(e,t,n){var r=e<0?e+t:e;if(0<=r&&r0&&e[0]!=="_"||e.length>0&&e[0]==="_"&&l[e.slice(1)]!=null)&&l.addProperty(l.sandbox,e,{value:l[e],writable:!1})}),l.use=function(e,t){t=x(t,{}),C("use",1,e,"function"),C("use",2,t,"object");var n=e(l,t),r=w(n),i,s;for(i in n)s=n[i],l.isOJType(s)&&(r[D(i)]=_createQuietType(s.typeName));for(i in r)s=r[i],l[i]=s,l.addProperty(l.sandbox,i,{value:s,writable:!1})},l.$.fn.oj=it({get:function(e){return e[0].oj},set:function(e,t){if(t.length===0)return e[0].oj;var n=l.compile.apply(l,[{dom:1,html:0,cssMap:1}].concat(s.call(t)));ot(n.cssMap,{global:0}),e.html(""),l.isArray(n.dom)||(n.dom=[n.dom]);for(var r=0;r=-1&&!t){r=n>=0?arguments[n]:process.cwd();if(typeof r!="string"||!r)continue;e=r+"/"+e,t=r.charAt(0)==="/",n--}return e=pt(e.split("/").filter(function(e){return!!e}),!t).join("/"),(t?"/":"")+e||"."},l._pathNormalize=function(e){var t=e.charAt(0)==="/",n=e.substr(-1)==="/";return e=pt(e.split("/").filter(function(e){return!!e}),!t).join("/"),!e&&!t&&(e="."),e&&n&&(e+="/"),(t?"/":"")+e},l._pathJoin=function(){var e=s.call(arguments,0);return l._pathNormalize(e.filter(function(e,t){return e&&typeof e=="string"}).join("/"))},l._pathDirname=function(e){var t=ht(e),n=t[0],r=t[1];return!n&&!r?".":(r&&(r=r.substr(0,r.length-1)),n+r)}}).call(this) \ No newline at end of file diff --git a/ajax/libs/oj/latest/oj.js b/ajax/libs/oj/latest/oj.js index dc37975e0..4b621ff09 100644 --- a/ajax/libs/oj/latest/oj.js +++ b/ajax/libs/oj/latest/oj.js @@ -1,5 +1,5 @@ // -// oj.js v0.2.0 +// oj.js v0.2.1 // ojjs.org // // Copyright 2013, Evan Moran @@ -25,7 +25,7 @@ return oj.tag.apply(this, ['oj'].concat(slice.call(arguments)).concat([{__quiet__:1}])) }; - oj.version = '0.2.0' + oj.version = '0.2.1' oj.isClient = !(typeof process !== "undefined" && process !== null ? process.versions != null ? process.versions.node : 0 : 0) @@ -566,8 +566,11 @@ acc.css = options.css || options.cssMap ? {} : null; acc.indent = '' + // Accumulate insert events per element + acc.inserts = [] + if (options.dom) - acc.types = []; + acc.types = [] acc.tags = {} @@ -625,7 +628,8 @@ css: css, cssMap: cssMap, types: acc.types, - tags: acc.tags + tags: acc.tags, + inserts: acc.inserts } }; @@ -1044,7 +1048,7 @@ } // Bind events - _attributesBindEventsToDOM(events, el) + _attributesBindEventsToDOM(events, el, options.inserts) } // Compile to html if requested @@ -1085,7 +1089,7 @@ // _attributesProcessedForOJ: Process attributes to make them easier to use function _attributesProcessedForOJ(attr){ - var jqEvents = {bind:1, on:1, off:1, live:1, blur:1, change:1, click:1, dblclick:1, focus:1, focusin:1, focusout:1, hover:1, keydown:1, keypress:1, keyup:1, mousedown:1, mouseenter:1, mouseleave:1, mousemove:1, mouseout:1, mouseup:1, ready:1, resize:1, scroll:1, select:1}, + var jqEvents = {bind:1, on:1, off:1, live:1, blur:1, change:1, click:1, dblclick:1, focus:1, focusin:1, focusout:1, hover:1, keydown:1, keypress:1, keyup:1, mousedown:1, mouseenter:1, mouseleave:1, mousemove:1, mouseout:1, mouseup:1, ready:1, resize:1, scroll:1, select:1, insert:1}, events, k, v // Allow attributes to alias c to class and use arrays instead of space seperated strings @@ -1142,20 +1146,20 @@ }; // Bind events to dom - function _attributesBindEventsToDOM(events, el){ - var ek, ev, _results; - - _results = []; + function _attributesBindEventsToDOM(events, el, inserts){ + var ek, ev, _results = [] for (ek in events){ ev = events[ek] _a(oj.$ != null, "jquery is missing when binding a '" + ek + "' event") - if (oj.isArray(ev)){ - _results.push(oj.$(el)[ek].apply(this, ev)); - } else { - _results.push(oj.$(el)[ek](ev)); - } + // accumulate insert events manually since DOMNodeInserted is slow and depreciated + if (ek == 'insert' && inserts) + inserts.push(function(){ev.call(el,el)}) + else if (oj.isArray(ev)) + _results.push(oj.$(el)[ek].apply(this, ev)) + else + _results.push(oj.$(el)[ek](ev)) } - return _results; + return _results }; // oj.toHTML: Compile directly to HTML only @@ -2850,9 +2854,14 @@ }; }; - function _triggerInserted(types){ - for (var ix = 0;ix < types.length; ix++) + function _triggerInserted(types, inserts){ + var ix = 0 + for (; ix < types.length; ix++) types[ix].inserted() + if(inserts) { + for (ix = 0; ix < inserts.length; ix++) + inserts[ix]() + } } function _insertStyles(pluginMap, options){ @@ -2899,7 +2908,7 @@ $el.append(r.dom[ix]) // Trigger inserted events - _triggerInserted(r.types) + _triggerInserted(r.types, r.inserts) } }); @@ -2922,7 +2931,7 @@ _insertStyles(r.cssMap, {global:1}) - _triggerInserted(r.types) + _triggerInserted(r.types, r.inserts) }; // Helper method that abstracts getting oj values @@ -2968,7 +2977,7 @@ // Append to the dom $el[jqName](r.dom); - _triggerInserted(r.types); + _triggerInserted(r.types, r.inserts); }, get: null }); diff --git a/ajax/libs/oj/latest/oj.min.js b/ajax/libs/oj/latest/oj.min.js index dc5057120..18f10a599 100644 --- a/ajax/libs/oj/latest/oj.min.js +++ b/ajax/libs/oj/latest/oj.min.js @@ -1,2 +1,2 @@ -// oj.min.js v0.2.0 | Copyright 2013 Evan Moran | ojjs.org/license -(function(){function l(){return l.tag.apply(this,["oj"].concat(s.call(arguments)).concat([{__quiet__:1}]))}function v(e){return!!e.match(/[A-Z]/)}function m(e,t){return i.hasOwnProperty.call(e,t)}function g(e){var t=p(e),n=t.length,r=new Array(n),i=0;for(;i0&&e[r-1]===e[r])continue;n.push(i)}return n}function x(){for(var e=0;e'+o),f+=J(n,t),s&&(f+=""+o+""+o);return f}function Q(e,t,n){var r=n.indent;n.indent+=" ",e(t,n),n.indent=r}function G(e,t){if(l.isArray(e))Y(e,t);else if(l.isString(e)){t.html!=null&&t.html.push(e);if(e.length>0&&e[0]==="<"){var n=document.createElement("div");n.innerHTML=e,t.dom!=null&&t.dom.appendChild(n)}else t.dom!=null&&t.dom.appendChild(document.createTextNode(e))}else l.isBoolean(e)||l.isNumber(e)?(t.html!=null&&t.html.push(""+e),t.dom!=null&&t.dom.appendChild(document.createTextNode(""+e))):l.isFunction(e)?G(l(e),t):l.isDate(e)?(t.html!=null&&t.html.push(""+e.toLocaleString()),t.dom!=null&&t.dom.appendChild(document.createTextNode(""+e.toLocaleString()))):l.isOJ(e)&&(t.types!=null&&t.types.push(e),t.html!=null&&t.html.push(e.toHTML(t)),t.dom!=null&&t.dom.appendChild(e.toDOM(t)),t.css!=null&&d(t.css,e.toCSSMap(t)))}function Y(e,t){if(e.length===0)return;var n=e[0],r=typeof n,i=l.unionArguments(e.slice(1)),s=i.options,o=i.args,u,a;if(r==="function"||r==="object")n=x(_(n),n);l.isString(n)&&n.length>0||T("compile","tag name is missing"),t.tags[n]=!0;if(v(n[0]))return Q(G,new l[n](e.slice(1)),t);if(t.css&&n==="css")for(a in s)u=s[a],t.css.oj=x(t.css.oj,{}),t.css.oj[a]=x(t.css.oj[a],{}),d(t.css.oj[a],u);if(n==="!DOCTYPE"){C("compile",1,e[1],"string"),t.ignore[n]||t.html&&t.html.push("<"+n+" "+e[1]+">");return}if(!t.ignore[n]){var f=Z(s),c;if(t.dom&&typeof document!="undefined"&&document!==null){c=document.createElement(n),l.isDOMElement(t.dom)&&t.dom.appendChild(c),t.dom=c;if(l.isPlainObject(s)){var h=p(s).sort(),m,g,y;for(m=0;m")}}if(t.ignore[n]!=="deep")for(m=0;m1&&t.html.push("\n "+t.indent),Q(G,E,t)}t.html!=null&&!t.minify&&o.length>1&&t.html.push("\n"+t.indent),t.ignore[n]||(t.html!=null&&(o.length>0||l.tag.isClosed(n))&&t.html.push(""),t.dom&&(t.dom=t.dom.parentNode))}function Z(e){var t={bind:1,on:1,off:1,live:1,blur:1,change:1,click:1,dblclick:1,focus:1,focusin:1,focusout:1,hover:1,keydown:1,keypress:1,keyup:1,mousedown:1,mouseenter:1,mouseleave:1,mousemove:1,mouseout:1,mouseup:1,ready:1,resize:1,scroll:1,select:1},n,r,i;l.isArray(e!=null?e.c:void 0)&&(e.c=e.c.join(" ")),l.isArray(e!=null?e["class"]:void 0)&&(e["class"]=e["class"].join(" ")),(e!=null?e.c:void 0)!=null&&((e!=null?e["class"]:void 0)!=null?e["class"]+=" "+e.c:e["class"]=e.c,delete e.c),l.isPlainObject(e!=null?e.style:void 0)&&(e.style=U(e.style,{inline:!0}));if(l.isPlainObject(e))for(r in e)i=e[r],(i===null||i===void 0||i===!1)&&delete e[r];n={};if(l.isPlainObject(e))for(r in e)i=e[r],t[r]!=null&&(n[r]=i,delete e[r]);return n}function et(e,t){var n,r,i;i=[];for(n in e)r=e[n],N(l.$!=null,"jquery is missing when binding a '"+n+"' event"),l.isArray(r)?i.push(l.$(t)[n].apply(this,r)):i.push(l.$(t)[n](r));return i}function tt(e,t){var n,r;for(r in t)l.copyProperty(e,t,r);n=function(){},n.prototype=t.prototype,e.prototype=new n,e.base=e.__super__=t.prototype}function nt(e){return new(r.bind.apply(e,arguments))}function it(e){return e==null&&(e={}),e=d({get:a,set:a,first:!1},e),function(){var t,n,r,i,s=y(arguments),o=jQuery(this);if(l.isFunction(e.get)&&s.length===0){n=[];for(i=0;i=0)i=e[r],i==="."?e.splice(r,1):i===".."?(e.splice(r,1),n++):n&&(e.splice(r,1),n--),r--;if(t)while(n--)e.unshift("..");return e}var e=this,n=Array.prototype,r=Function.prototype,i=Object.prototype,s=n.slice,o=n.unshift,u=n.concat,a=function(e){return e},f="undefined";l.version="0.2.0",l.isClient=!(typeof process!="undefined"&&process!==null?process.versions!=null?process.versions.node:0:0);if(typeof $!=f)l.$=$;else if(typeof require!=f)try{l.$=require("jquery")}catch(c){}typeof require!=f?module.exports=l:e.oj=l,l.oj=l,l.load=function(e){return l.$(function(){return l.$.ojBody(require(e)),l.onload()})};var h={queue:[],loaded:!1};l.onload=function(e){if(l.isUndefined(e)){h.loaded=!0;while(e=h.queue.shift())e()}else h.loaded?e():h.queue.push(e)},l.emit=function(){return l.tag.apply(l,["oj"].concat(s.call(arguments)))},l.isDefined=function(e){return typeof e!==f},l.isOJ=function(e){return e!=null?!!e.isOJ:!!void 0},l.isOJType=function(e){return l.isOJ(e)&&e.type===e},l.isOJInstance=function(e){return l.isOJ(e)&&!l.isOJType(e)},l.isEvented=function(e){return!!(e&&e.on&&e.off&&e.trigger)},l.isDOM=function(e){return!!e&&e.nodeType!=null},l.isDOMElement=function(e){return!!e&&e.nodeType===1},l.isDOMAttribute=function(e){return!!e&&e.nodeType===2},l.isDOMText=function(e){return!!e&&e.nodeType===3},l.isjQuery=function(e){return!!e&&!!e.jquery},l.isUndefined=function(e){return e===void 0},l.isBoolean=function(e){return e===!0||e===!1||i.toString.call(e)==="[object Boolean]"},l.isNumber=function(e){return!!(e===0||e&&e.toExponential&&e.toFixed)},l.isString=function(e){return!!(e===""||e&&e.charCodeAt&&e.substr)},l.isDate=function(e){return!!(e&&e.getTimezoneOffset&&e.setUTCFullYear)},l.isPlainObject=function(e){return l.$.isPlainObject(e)&&!l.isOJ(e)},l.isFunction=l.$.isFunction,l.isArray=l.$.isArray,l.isRegEx=function(e){return i.toString.call(e)==="[object RegExp]"},l.isArguments=function(e){return i.toString.call(e)==="[object Arguments]"},l.parse=function(e){var t,n=e;return e===f?n=void 0:e==="null"?n=null:e==="true"?n=!0:e==="false"?n=!1:isNaN(t=parseFloat(e))||(n=t),n},l.unionArguments=function(e){var t={},n=[],r,i=0;for(;i'+r+i+""},l.toHTML=function(e,t){return l.isPlainObject(e)||(t=e,e={}),d(e,{dom:0,js:0,html:1,css:0}),l.compile(e,t).html},l.toCSS=function(e,t){return l.isPlain(e)||(t=e,e={}),d(e,{dom:0,js:0,html:0,css:1}),l.compile(e,t).css},l.createType=function(e,t){t=x(t,{}),t.methods=x(t.methods,{}),t.properties=x(t.properties,{}),C("createType",1,e,"string"),C("createType",2,t,"object");var n,r,i,s="__DELAYED__",o=(new Function("return function "+e+"(){\n var _t = this;\n if ( !(this instanceof "+e+") ){\n _t = new "+e+"('"+s+"');\n _t.__autonew__ = true;\n }\n\n if (arguments && arguments[0] != '"+s+"')\n "+e+".prototype.constructor.apply(_t, arguments);\n\n return _t;\n}"))();return t.base!=null&&(t.constructor==null||!t.hasOwnProperty("constructor"))&&(t.constructor=function(){return o.base!=null?o.base.constructor.apply(this,arguments):void 0}),t.base!=null&&tt(o,t.base),l.addMethod(o.prototype,"constructor",t.constructor),i={type:{value:o,writable:!1,enumerable:!1},typeName:{value:e,writable:!1,enumerable:!1},isOJ:{value:!0,writable:!1,enumerable:!1}},l.addProperties(o,i),l.addProperties(o.prototype,i),r=p(t.properties).sort(),o.prototype.properties!=null&&(r=S(o.prototype.properties.concat(r))),l.addProperty(o.prototype,"properties",{value:r,writable:!1,enumerable:!1}),n=p(t.methods).sort(),o.prototype.methods!=null&&(n=S(o.prototype.methods.concat(n))),l.addProperty(o.prototype,"methods",{value:n,writable:!1,enumerable:!1}),d(t.methods,{get:function(e){if(!l.isString(e)){var t={},n,r;for(n=0;n0&&(this.value=r[0]),(n!=null?n.live:void 0)!=null&&(this.live=l.argumentShift(n,"live")),l.TextBox.base.constructor.apply(this,[n])},properties:{value:{get:function(){var e=this.el.value;if(e==null||e===f)e="";return e},set:function(e){this.el.value=e}},live:!0}}),l.CheckBox=l.createType("CheckBox",{base:l.ModelKeyView,constructor:function(){var e=this,t=l.unionArguments(arguments),n=t.options,r=t.args;return this.el=l(function(){l.input({type:"checkbox"},{change:function(){e.viewChanged()}})}),r.length>0&&(this.value=r[0]),l.CheckBox.base.constructor.call(this,n)},properties:{value:{get:function(){return this.el.checked},set:function(e){this.el.checked=e=!!e,e?this.$el.attr("checked","checked"):this.$el.removeAttr("checked")}}}}),l.Text=l.createType("Text",{base:l.ModelKeyView,constructor:function(){var e=this,t=l.unionArguments(arguments),n=t.options,r=t.args;return this._tagName=l.argumentShift(n,"tagName"),this.el=l(function(){return l[e.tagName]()}),r.length>0&&(this.value=r[0]),l.Text.base.constructor.call(this,n)},properties:{value:{get:function(){return this.$el.ojValue()},set:function(e){this.$el.oj(e)}},tagName:{get:function(){return x(this._tagName,"div")}}}}),l.TextArea=l.createType("TextArea",{base:l.ModelKeyView,constructor:function(){var e=this,t=l.unionArguments(arguments),n=t.options,r=t.args;return this.el=l(function(){return l.textarea({keydown:function(){e.live&&setTimeout(function(){return e.$el.change()},10)},keyup:function(){e.live&&setTimeout(function(){return e.$el.change()},10)},change:function(){e.viewChanged()}})}),this.value=l.argumentShift(n,"value")||r.join("\n"),l.TextArea.base.constructor.call(this,n)},properties:{value:{get:function(){return this.el.value},set:function(e){this.el.value=e}},live:!0}}),l.ListBox=l.createType("ListBox",{base:l.ModelKeyView,constructor:function(){var e=this,t=l.unionArguments(arguments),n=t.options,r=t.args;return this.el=l(function(){return l.select({change:function(){e.viewChanged()}})}),this.options=l.argumentShift(n,"options"),r.length>0&&(this.value=r[0]),l.ListBox.base.constructor.apply(this,[n])},properties:{value:{get:function(){return this.$el.val()},set:function(e){this.$el.val(e)}},options:{get:function(){return this._options},set:function(e){if(!l.isArray(e))throw new Error("oj."+this.typeName+".options array is missing");this._options=e,this.$el.oj(function(){var t,n,r;for(n=0,r=e.length;n0&&(i=r[0]),n.title!=null&&(i=l.argumentShift(n,"title")),this.el=l(function(){return l.button(i)}),l.Button.base.constructor.apply(this,[n]),this.title=i},properties:{title:{get:function(){return x(this._title,"")},set:function(e){this.$el.oj(this._title=e)}}},methods:{click:function(){return arguments.length>0?this.$el.click.apply(this.$el,arguments):this.$el.click()}}}),l.List=l.createType("List",{base:l.CollectionView,constructor:function(){var e=this,t=l.unionArguments(arguments),n=t.options,r=t.args,i;return this._tagName=l.argumentShift(n,"tagName"),this.itemTagName=l.argumentShift(n,"itemTagName"),this.el=l(function(){return l[e.tagName]()}),n.el!=null&&(this.el=l.argumentShift(n,"el")),n.each==null&&(n.each=function(e){return l.isString(e)||l.isNumber(e)||l.isBoolean(e)?e:JSON.stringify(e)}),l.List.base.constructor.apply(this,[n]),i=r.length>0?r:null,this.items=n.items!=null?l.argumentShift(n,"items"):i},properties:{items:{get:function(){return this._items!=null?this._items:this.$items.ojValues()},set:function(e){this._items=e,this.make()}},count:{get:function(){return this.$items.length}},tagName:{get:function(){return x(this._tagName,"div")}},itemTagName:{get:function(){return x(this._itemTagName,"div")},set:function(e){this._itemTagName=e,this.make()}},$items:{get:function(){return this._$items!=null?this._$items:this._$items=this.$("> "+this.itemTagName)}}},methods:{item:function(e,t){e=this._bound(e,this.count,".item: index");if(t==null)return this.$item(e).ojValue();this.$item(e).oj(t)},$item:function(e){return this.$items.eq(this._bound(e,this.count,".$item: index"))},make:function(){if(!this.isConstructed)return;var e=this,t,n,r,i,s;this.models!=null&&this.each!=null?(r=l.isEvented(this.models)?this.models.models:this.models,i=r.map(function(t){return e._itemFromModel(t)})):this.items!=null&&(i=this.items),this.$el.oj(function(){return i.map(function(t){e._itemElFromItem(t)})}),this.itemsChanged()},collectionModelAdded:function(e,t){this.add(t.indexOf(e),this._itemFromModel(e))},collectionModelRemoved:function(e,t,n){this.remove(n.index)},collectionReset:function(){this.make()},_itemFromModel:function(e){var t=this;return l(function(){return t.each(e)})},_itemElFromItem:function(e){return l[this.itemTagName](e)},_bound:function(e,t,n){var r=e<0?e+t:e;return 0<=r&&re?this.$item(e).insertAfter(this.$item(t)):this.$item(e).insertBefore(this.$item(t)),this.itemsChanged()},swap:function(e,t){if(e===t)return;e=this._bound(e,this.count,".swap: firstIndex"),t=this._bound(t,this.count,".swap: secondIndex");if(Math.abs(e-t)===1)this.move(e,t);else{var n=Math.min(e,t),r=Math.max(e,t);this.move(r,n),this.move(n+1,r)}this.itemsChanged()},unshift:function(e){this.add(0,e)},shift:function(){return this.remove(0)},push:function(e){this.add(this.count,e)},pop:function(){return this.remove(-1)},clear:function(){this.$items.remove(),this.itemsChanged()}}}),l.NumberList=l.createType("NumberList",{base:l.List,constructor:function(){var e=[{tagName:"ol",itemTagName:"li"}].concat(s.call(arguments));return l.NumberList.base.constructor.apply(this,e)}}),l.BulletList=l.createType("BulletList",{base:l.List,constructor:function(){var e=[{tagName:"ul",itemTagName:"li"}].concat(s.call(arguments));return l.BulletList.base.constructor.apply(this,e)}}),l.Table=l.createType("Table",{base:l.CollectionView,constructor:function(){var e=this,t=l.unionArguments(arguments),n=t.options,r=t.args,i,s;this.el=l(function(){return l.table()}),n.el!=null&&(this.el=l.argumentShift(n,"el")),n.each==null&&(n.each=function(e,t){var n=l.isString(e)||l.isNumber(e)||l.isBoolean(e)?[e]:l.isEvented(e)&&typeof e.attributes=="object"?g(e.attributes):g(e);return n.map(function(e){t(e)})}),l.Table.base.constructor.apply(this,[n]);for(s=0;s0)return this.rows=i},properties:{rowCount:{get:function(){return this.$trs.length}},columnCount:{get:function(){var e,t,n;return(n=this.$tr(0).find("> td").length)>0?n:(t=this.$theadTR.find("> th").length)>0?t:(e=this.$tfootTR.find("> td").length)>0?e:0}},rows:{get:function(){if(this._rows!=null)return this._rows;var e,t=0;this._rows=[];for(;t0))return this.clearBody();this._rows=e,this.make()}},header:{get:function(){return this.$theadTR.find("> th").ojValues()},set:function(e){return N(l.isArray(e),this.typeName+".header","array expected for first argument"),e!=null&&e.length>0?this.$theadTRMake.oj(function(){return e.map(function(e){l.th(e)})}):this.clearHeader()}},footer:{get:function(){return this.$tfootTR.find("> td").ojValues()},set:function(e){var t=this;if(!l.isArray(e))throw new Error("oj.Table.footer: array expected for first argument");return e!=null&&e.length>0?this.$tfootTRMake.oj(function(){var t,n,r,i;i=[];for(n=0,r=e.length;n caption")}},$colgroup:{get:function(){return this.$("> colgroup")}},$thead:{get:function(){return this.$("> thead")}},$tfoot:{get:function(){return this.$("> tfoot")}},$tbody:{get:function(){return this.$("> tbody")}},$theadTR:{get:function(){return this.$thead.find("> tr")}},$tfootTR:{get:function(){return this.$tfoot.find("> tr")}},$ths:{get:function(){return this.$theadTR.find("> th")}},$trs:{get:function(){return this._$trs!=null?this._$trs:this._$trs=this.$("> tbody > tr")}},$colgroupMake:{get:function(){return this.$colgroup.length>0?this.$colgroup:(t="",this.$caption.length>0?this.$caption.insertAfter(t):this.$table.append(t),this.$tbody)}},$captionMake:{get:function(){return this.$caption.length>0?this.$caption:(this.$table.prepend(""),this.$caption)}},$tfootMake:{get:function(){return this.$tfoot.length>0?this.$tfoot:(t="",this.$tfoot.length>0?this.$tfoot.insertBefore(t):this.$table.append(t),this.$tfoot)}},$theadMake:{get:function(){return this.$thead.length>0?this.$thead:(t="",this.$colgroup.length>0?this.$colgroup.insertAfter(t):this.$caption.length>0?this.$caption.insertAfter(t):this.$table.prepend(t),this.$thead)}},$tbodyMake:{get:function(){return this.$tbody.length>0?this.$tbody:(this.$table.append(""),this.$tbody)}},$theadTRMake:{get:function(){return this.$theadTR.length>0?this.$theadTR:(this.$theadMake.html(""),this.$theadTR)}},$tfootTRMake:{get:function(){return this.$tfootTR.length>0?this.$tfootTR:(this.$tfootMake.html(""),this.$tfootTR)}}},methods:{make:function(){if(!this.isConstructed)return;var e=this,t,n=[];this.models!=null&&this.each!=null?(t=l.isEvented(this.models)?this.models.models:this._models,n=t.map(function(t){return e._rowFromModel(t)})):this.rows!=null&&(n=this.rows.map(function(e){return l(function(){e.forEach(function(e){l.td(e)})})})),n.length>0&&this.$tbodyMake.oj(function(){n.forEach(function(e){l.tr(e)})}),this.bodyChanged()},collectionModelAdded:function(e,t){var n=t.indexOf(e),r=this._rowFromModel(e);this._addRowTR(n,l(function(){return l.tr(r)}))},collectionModelRemoved:function(e,t,n){this.removeRow(n.index)},collectionReset:function(){this.make()},$tr:function(e){return e=e<0?e+count:e,this.$trs.eq(e)},$tdsRow:function(e){return e=e<0?e+count:e,this.$tr(e).find("> td")},$td:function(e,t){return e=e<0?e+this.rowCount:e,t=t<0?t+this.columnCount:t,this.$tdsRow(e).eq(t)},row:function(e,t){e=this._bound(e,this.rowCount,".row: rx");if(t==null)return this.$tdsRow(e).ojValues();N(t.length===cellCount(e),this.typeName,"array expected for second argument with length ("+e+")"),t.forEach(function(t,n){this.$td(e,n).oj(t)})},cell:function(e,t,n){return n!=null?this.$td(e,t).oj(n):this.$td(e,t).ojValue()},addRow:function(e,t){t==null&&(t=e,e=-1),e=this._bound(e,this.rowCount+1,".addRow: rx"),N(l.isArray(t),"addRow","expected array for row content"),this._addRowTR(e,function(){l.tr(function(){t.forEach(function(e){l.td(e)})})})},_addRowTR:function(e,t){this.rowCount===0?this.$el.oj(t):e===this.rowCount?this.$tr(e-1).ojAfter(t):this.$tr(e).ojBefore(t),this.bodyChanged()},removeRow:function(e){e==null&&(e=-1),e=this._bound(e,this.rowCount,".removeRow: index");var t=this.row(e);return this.$tr(e).remove(),this.bodyChanged(),t},moveRow:function(e,t){if(e===t)return;e=this._bound(e,this.rowCount,".moveRow: fromIndex"),t=this._bound(t,this.rowCount,".moveRow: toIndex");var n=t>e?"insertAfter":"insertBefore";this.$tr(e)[n](this.$tr(t)),this.bodyChanged()},swapRow:function(e,t){if(e===t)return;e=this._bound(e,this.rowCount,".swap: firstIndex"),t=this._bound(t,this.rowCount,".swap: secondIndex");if(Math.abs(e-t)===1)this.moveRow(e,t);else{var n=Math.min(e,t),r=Math.max(e,t);this.moveRow(r,n),this.moveRow(n+1,r)}this.bodyChanged()},unshiftRow:function(e){this.addRow(0,e)},shiftRow:function(){return this.removeRow(0)},pushRow:function(e){this.addRow(this.rowCount,e)},popRow:function(){return this.removeRow(-1)},clearColgroup:function(){this.$colgroup.remove()},clearBody:function(){this.$tbody.remove(),this.bodyChanged()},clearHeader:function(){this.$thead.remove(),this.headerChanged()},clearFooter:function(){this.$tfoot.remove(),this.footerChanged()},clearCaption:function(){this.$capation.remove()},clear:function(){return this.clearBody(),this.clearHeader(),this.clearFooter(),this.$caption.remove()},bodyChanged:function(){this._rows=null,this._columns=null,this._$trs=null},headerChanged:function(){this._header=null},footerChanged:function(){this._footer=null},_rowFromModel:function(e){var t=this;return l(function(){return t.each(e,l.td)})},_bound:function(e,t,n){var r=e<0?e+t:e;if(0<=r&&r0&&e[0]!=="_"||e.length>0&&e[0]==="_"&&l[e.slice(1)]!=null)&&l.addProperty(l.sandbox,e,{value:l[e],writable:!1})}),l.use=function(e,t){t=x(t,{}),C("use",1,e,"function"),C("use",2,t,"object");var n=e(l,t),r=w(n),i,s;for(i in n)s=n[i],l.isOJType(s)&&(r[D(i)]=_createQuietType(s.typeName));for(i in r)s=r[i],l[i]=s,l.addProperty(l.sandbox,i,{value:s,writable:!1})},l.$.fn.oj=it({get:function(e){return e[0].oj},set:function(e,t){if(t.length===0)return e[0].oj;var n=l.compile.apply(l,[{dom:1,html:0,cssMap:1}].concat(s.call(t)));ot(n.cssMap,{global:0}),e.html(""),l.isArray(n.dom)||(n.dom=[n.dom]);for(var r=0;r=-1&&!t){r=n>=0?arguments[n]:process.cwd();if(typeof r!="string"||!r)continue;e=r+"/"+e,t=r.charAt(0)==="/",n--}return e=pt(e.split("/").filter(function(e){return!!e}),!t).join("/"),(t?"/":"")+e||"."},l._pathNormalize=function(e){var t=e.charAt(0)==="/",n=e.substr(-1)==="/";return e=pt(e.split("/").filter(function(e){return!!e}),!t).join("/"),!e&&!t&&(e="."),e&&n&&(e+="/"),(t?"/":"")+e},l._pathJoin=function(){var e=s.call(arguments,0);return l._pathNormalize(e.filter(function(e,t){return e&&typeof e=="string"}).join("/"))},l._pathDirname=function(e){var t=ht(e),n=t[0],r=t[1];return!n&&!r?".":(r&&(r=r.substr(0,r.length-1)),n+r)}}).call(this) \ No newline at end of file +// oj.min.js v0.2.1 | Copyright 2013 Evan Moran | ojjs.org/license +(function(){function l(){return l.tag.apply(this,["oj"].concat(s.call(arguments)).concat([{__quiet__:1}]))}function v(e){return!!e.match(/[A-Z]/)}function m(e,t){return i.hasOwnProperty.call(e,t)}function g(e){var t=p(e),n=t.length,r=new Array(n),i=0;for(;i0&&e[r-1]===e[r])continue;n.push(i)}return n}function x(){for(var e=0;e'+o),f+=J(n,t),s&&(f+=""+o+""+o);return f}function Q(e,t,n){var r=n.indent;n.indent+=" ",e(t,n),n.indent=r}function G(e,t){if(l.isArray(e))Y(e,t);else if(l.isString(e)){t.html!=null&&t.html.push(e);if(e.length>0&&e[0]==="<"){var n=document.createElement("div");n.innerHTML=e,t.dom!=null&&t.dom.appendChild(n)}else t.dom!=null&&t.dom.appendChild(document.createTextNode(e))}else l.isBoolean(e)||l.isNumber(e)?(t.html!=null&&t.html.push(""+e),t.dom!=null&&t.dom.appendChild(document.createTextNode(""+e))):l.isFunction(e)?G(l(e),t):l.isDate(e)?(t.html!=null&&t.html.push(""+e.toLocaleString()),t.dom!=null&&t.dom.appendChild(document.createTextNode(""+e.toLocaleString()))):l.isOJ(e)&&(t.types!=null&&t.types.push(e),t.html!=null&&t.html.push(e.toHTML(t)),t.dom!=null&&t.dom.appendChild(e.toDOM(t)),t.css!=null&&d(t.css,e.toCSSMap(t)))}function Y(e,t){if(e.length===0)return;var n=e[0],r=typeof n,i=l.unionArguments(e.slice(1)),s=i.options,o=i.args,u,a;if(r==="function"||r==="object")n=x(_(n),n);l.isString(n)&&n.length>0||T("compile","tag name is missing"),t.tags[n]=!0;if(v(n[0]))return Q(G,new l[n](e.slice(1)),t);if(t.css&&n==="css")for(a in s)u=s[a],t.css.oj=x(t.css.oj,{}),t.css.oj[a]=x(t.css.oj[a],{}),d(t.css.oj[a],u);if(n==="!DOCTYPE"){C("compile",1,e[1],"string"),t.ignore[n]||t.html&&t.html.push("<"+n+" "+e[1]+">");return}if(!t.ignore[n]){var f=Z(s),c;if(t.dom&&typeof document!="undefined"&&document!==null){c=document.createElement(n),l.isDOMElement(t.dom)&&t.dom.appendChild(c),t.dom=c;if(l.isPlainObject(s)){var h=p(s).sort(),m,g,y;for(m=0;m")}}if(t.ignore[n]!=="deep")for(m=0;m1&&t.html.push("\n "+t.indent),Q(G,E,t)}t.html!=null&&!t.minify&&o.length>1&&t.html.push("\n"+t.indent),t.ignore[n]||(t.html!=null&&(o.length>0||l.tag.isClosed(n))&&t.html.push(""),t.dom&&(t.dom=t.dom.parentNode))}function Z(e){var t={bind:1,on:1,off:1,live:1,blur:1,change:1,click:1,dblclick:1,focus:1,focusin:1,focusout:1,hover:1,keydown:1,keypress:1,keyup:1,mousedown:1,mouseenter:1,mouseleave:1,mousemove:1,mouseout:1,mouseup:1,ready:1,resize:1,scroll:1,select:1,insert:1},n,r,i;l.isArray(e!=null?e.c:void 0)&&(e.c=e.c.join(" ")),l.isArray(e!=null?e["class"]:void 0)&&(e["class"]=e["class"].join(" ")),(e!=null?e.c:void 0)!=null&&((e!=null?e["class"]:void 0)!=null?e["class"]+=" "+e.c:e["class"]=e.c,delete e.c),l.isPlainObject(e!=null?e.style:void 0)&&(e.style=U(e.style,{inline:!0}));if(l.isPlainObject(e))for(r in e)i=e[r],(i===null||i===void 0||i===!1)&&delete e[r];n={};if(l.isPlainObject(e))for(r in e)i=e[r],t[r]!=null&&(n[r]=i,delete e[r]);return n}function et(e,t,n){var r,i,s=[];for(r in e)i=e[r],N(l.$!=null,"jquery is missing when binding a '"+r+"' event"),r=="insert"&&n?n.push(function(){i.call(t,t)}):l.isArray(i)?s.push(l.$(t)[r].apply(this,i)):s.push(l.$(t)[r](i));return s}function tt(e,t){var n,r;for(r in t)l.copyProperty(e,t,r);n=function(){},n.prototype=t.prototype,e.prototype=new n,e.base=e.__super__=t.prototype}function nt(e){return new(r.bind.apply(e,arguments))}function it(e){return e==null&&(e={}),e=d({get:a,set:a,first:!1},e),function(){var t,n,r,i,s=y(arguments),o=jQuery(this);if(l.isFunction(e.get)&&s.length===0){n=[];for(i=0;i=0)i=e[r],i==="."?e.splice(r,1):i===".."?(e.splice(r,1),n++):n&&(e.splice(r,1),n--),r--;if(t)while(n--)e.unshift("..");return e}var e=this,n=Array.prototype,r=Function.prototype,i=Object.prototype,s=n.slice,o=n.unshift,u=n.concat,a=function(e){return e},f="undefined";l.version="0.2.1",l.isClient=!(typeof process!="undefined"&&process!==null?process.versions!=null?process.versions.node:0:0);if(typeof $!=f)l.$=$;else if(typeof require!=f)try{l.$=require("jquery")}catch(c){}typeof require!=f?module.exports=l:e.oj=l,l.oj=l,l.load=function(e){return l.$(function(){return l.$.ojBody(require(e)),l.onload()})};var h={queue:[],loaded:!1};l.onload=function(e){if(l.isUndefined(e)){h.loaded=!0;while(e=h.queue.shift())e()}else h.loaded?e():h.queue.push(e)},l.emit=function(){return l.tag.apply(l,["oj"].concat(s.call(arguments)))},l.isDefined=function(e){return typeof e!==f},l.isOJ=function(e){return e!=null?!!e.isOJ:!!void 0},l.isOJType=function(e){return l.isOJ(e)&&e.type===e},l.isOJInstance=function(e){return l.isOJ(e)&&!l.isOJType(e)},l.isEvented=function(e){return!!(e&&e.on&&e.off&&e.trigger)},l.isDOM=function(e){return!!e&&e.nodeType!=null},l.isDOMElement=function(e){return!!e&&e.nodeType===1},l.isDOMAttribute=function(e){return!!e&&e.nodeType===2},l.isDOMText=function(e){return!!e&&e.nodeType===3},l.isjQuery=function(e){return!!e&&!!e.jquery},l.isUndefined=function(e){return e===void 0},l.isBoolean=function(e){return e===!0||e===!1||i.toString.call(e)==="[object Boolean]"},l.isNumber=function(e){return!!(e===0||e&&e.toExponential&&e.toFixed)},l.isString=function(e){return!!(e===""||e&&e.charCodeAt&&e.substr)},l.isDate=function(e){return!!(e&&e.getTimezoneOffset&&e.setUTCFullYear)},l.isPlainObject=function(e){return l.$.isPlainObject(e)&&!l.isOJ(e)},l.isFunction=l.$.isFunction,l.isArray=l.$.isArray,l.isRegEx=function(e){return i.toString.call(e)==="[object RegExp]"},l.isArguments=function(e){return i.toString.call(e)==="[object Arguments]"},l.parse=function(e){var t,n=e;return e===f?n=void 0:e==="null"?n=null:e==="true"?n=!0:e==="false"?n=!1:isNaN(t=parseFloat(e))||(n=t),n},l.unionArguments=function(e){var t={},n=[],r,i=0;for(;i'+r+i+""},l.toHTML=function(e,t){return l.isPlainObject(e)||(t=e,e={}),d(e,{dom:0,js:0,html:1,css:0}),l.compile(e,t).html},l.toCSS=function(e,t){return l.isPlain(e)||(t=e,e={}),d(e,{dom:0,js:0,html:0,css:1}),l.compile(e,t).css},l.createType=function(e,t){t=x(t,{}),t.methods=x(t.methods,{}),t.properties=x(t.properties,{}),C("createType",1,e,"string"),C("createType",2,t,"object");var n,r,i,s="__DELAYED__",o=(new Function("return function "+e+"(){\n var _t = this;\n if ( !(this instanceof "+e+") ){\n _t = new "+e+"('"+s+"');\n _t.__autonew__ = true;\n }\n\n if (arguments && arguments[0] != '"+s+"')\n "+e+".prototype.constructor.apply(_t, arguments);\n\n return _t;\n}"))();return t.base!=null&&(t.constructor==null||!t.hasOwnProperty("constructor"))&&(t.constructor=function(){return o.base!=null?o.base.constructor.apply(this,arguments):void 0}),t.base!=null&&tt(o,t.base),l.addMethod(o.prototype,"constructor",t.constructor),i={type:{value:o,writable:!1,enumerable:!1},typeName:{value:e,writable:!1,enumerable:!1},isOJ:{value:!0,writable:!1,enumerable:!1}},l.addProperties(o,i),l.addProperties(o.prototype,i),r=p(t.properties).sort(),o.prototype.properties!=null&&(r=S(o.prototype.properties.concat(r))),l.addProperty(o.prototype,"properties",{value:r,writable:!1,enumerable:!1}),n=p(t.methods).sort(),o.prototype.methods!=null&&(n=S(o.prototype.methods.concat(n))),l.addProperty(o.prototype,"methods",{value:n,writable:!1,enumerable:!1}),d(t.methods,{get:function(e){if(!l.isString(e)){var t={},n,r;for(n=0;n0&&(this.value=r[0]),(n!=null?n.live:void 0)!=null&&(this.live=l.argumentShift(n,"live")),l.TextBox.base.constructor.apply(this,[n])},properties:{value:{get:function(){var e=this.el.value;if(e==null||e===f)e="";return e},set:function(e){this.el.value=e}},live:!0}}),l.CheckBox=l.createType("CheckBox",{base:l.ModelKeyView,constructor:function(){var e=this,t=l.unionArguments(arguments),n=t.options,r=t.args;return this.el=l(function(){l.input({type:"checkbox"},{change:function(){e.viewChanged()}})}),r.length>0&&(this.value=r[0]),l.CheckBox.base.constructor.call(this,n)},properties:{value:{get:function(){return this.el.checked},set:function(e){this.el.checked=e=!!e,e?this.$el.attr("checked","checked"):this.$el.removeAttr("checked")}}}}),l.Text=l.createType("Text",{base:l.ModelKeyView,constructor:function(){var e=this,t=l.unionArguments(arguments),n=t.options,r=t.args;return this._tagName=l.argumentShift(n,"tagName"),this.el=l(function(){return l[e.tagName]()}),r.length>0&&(this.value=r[0]),l.Text.base.constructor.call(this,n)},properties:{value:{get:function(){return this.$el.ojValue()},set:function(e){this.$el.oj(e)}},tagName:{get:function(){return x(this._tagName,"div")}}}}),l.TextArea=l.createType("TextArea",{base:l.ModelKeyView,constructor:function(){var e=this,t=l.unionArguments(arguments),n=t.options,r=t.args;return this.el=l(function(){return l.textarea({keydown:function(){e.live&&setTimeout(function(){return e.$el.change()},10)},keyup:function(){e.live&&setTimeout(function(){return e.$el.change()},10)},change:function(){e.viewChanged()}})}),this.value=l.argumentShift(n,"value")||r.join("\n"),l.TextArea.base.constructor.call(this,n)},properties:{value:{get:function(){return this.el.value},set:function(e){this.el.value=e}},live:!0}}),l.ListBox=l.createType("ListBox",{base:l.ModelKeyView,constructor:function(){var e=this,t=l.unionArguments(arguments),n=t.options,r=t.args;return this.el=l(function(){return l.select({change:function(){e.viewChanged()}})}),this.options=l.argumentShift(n,"options"),r.length>0&&(this.value=r[0]),l.ListBox.base.constructor.apply(this,[n])},properties:{value:{get:function(){return this.$el.val()},set:function(e){this.$el.val(e)}},options:{get:function(){return this._options},set:function(e){if(!l.isArray(e))throw new Error("oj."+this.typeName+".options array is missing");this._options=e,this.$el.oj(function(){var t,n,r;for(n=0,r=e.length;n0&&(i=r[0]),n.title!=null&&(i=l.argumentShift(n,"title")),this.el=l(function(){return l.button(i)}),l.Button.base.constructor.apply(this,[n]),this.title=i},properties:{title:{get:function(){return x(this._title,"")},set:function(e){this.$el.oj(this._title=e)}}},methods:{click:function(){return arguments.length>0?this.$el.click.apply(this.$el,arguments):this.$el.click()}}}),l.List=l.createType("List",{base:l.CollectionView,constructor:function(){var e=this,t=l.unionArguments(arguments),n=t.options,r=t.args,i;return this._tagName=l.argumentShift(n,"tagName"),this.itemTagName=l.argumentShift(n,"itemTagName"),this.el=l(function(){return l[e.tagName]()}),n.el!=null&&(this.el=l.argumentShift(n,"el")),n.each==null&&(n.each=function(e){return l.isString(e)||l.isNumber(e)||l.isBoolean(e)?e:JSON.stringify(e)}),l.List.base.constructor.apply(this,[n]),i=r.length>0?r:null,this.items=n.items!=null?l.argumentShift(n,"items"):i},properties:{items:{get:function(){return this._items!=null?this._items:this.$items.ojValues()},set:function(e){this._items=e,this.make()}},count:{get:function(){return this.$items.length}},tagName:{get:function(){return x(this._tagName,"div")}},itemTagName:{get:function(){return x(this._itemTagName,"div")},set:function(e){this._itemTagName=e,this.make()}},$items:{get:function(){return this._$items!=null?this._$items:this._$items=this.$("> "+this.itemTagName)}}},methods:{item:function(e,t){e=this._bound(e,this.count,".item: index");if(t==null)return this.$item(e).ojValue();this.$item(e).oj(t)},$item:function(e){return this.$items.eq(this._bound(e,this.count,".$item: index"))},make:function(){if(!this.isConstructed)return;var e=this,t,n,r,i,s;this.models!=null&&this.each!=null?(r=l.isEvented(this.models)?this.models.models:this.models,i=r.map(function(t){return e._itemFromModel(t)})):this.items!=null&&(i=this.items),this.$el.oj(function(){return i.map(function(t){e._itemElFromItem(t)})}),this.itemsChanged()},collectionModelAdded:function(e,t){this.add(t.indexOf(e),this._itemFromModel(e))},collectionModelRemoved:function(e,t,n){this.remove(n.index)},collectionReset:function(){this.make()},_itemFromModel:function(e){var t=this;return l(function(){return t.each(e)})},_itemElFromItem:function(e){return l[this.itemTagName](e)},_bound:function(e,t,n){var r=e<0?e+t:e;return 0<=r&&re?this.$item(e).insertAfter(this.$item(t)):this.$item(e).insertBefore(this.$item(t)),this.itemsChanged()},swap:function(e,t){if(e===t)return;e=this._bound(e,this.count,".swap: firstIndex"),t=this._bound(t,this.count,".swap: secondIndex");if(Math.abs(e-t)===1)this.move(e,t);else{var n=Math.min(e,t),r=Math.max(e,t);this.move(r,n),this.move(n+1,r)}this.itemsChanged()},unshift:function(e){this.add(0,e)},shift:function(){return this.remove(0)},push:function(e){this.add(this.count,e)},pop:function(){return this.remove(-1)},clear:function(){this.$items.remove(),this.itemsChanged()}}}),l.NumberList=l.createType("NumberList",{base:l.List,constructor:function(){var e=[{tagName:"ol",itemTagName:"li"}].concat(s.call(arguments));return l.NumberList.base.constructor.apply(this,e)}}),l.BulletList=l.createType("BulletList",{base:l.List,constructor:function(){var e=[{tagName:"ul",itemTagName:"li"}].concat(s.call(arguments));return l.BulletList.base.constructor.apply(this,e)}}),l.Table=l.createType("Table",{base:l.CollectionView,constructor:function(){var e=this,t=l.unionArguments(arguments),n=t.options,r=t.args,i,s;this.el=l(function(){return l.table()}),n.el!=null&&(this.el=l.argumentShift(n,"el")),n.each==null&&(n.each=function(e,t){var n=l.isString(e)||l.isNumber(e)||l.isBoolean(e)?[e]:l.isEvented(e)&&typeof e.attributes=="object"?g(e.attributes):g(e);return n.map(function(e){t(e)})}),l.Table.base.constructor.apply(this,[n]);for(s=0;s0)return this.rows=i},properties:{rowCount:{get:function(){return this.$trs.length}},columnCount:{get:function(){var e,t,n;return(n=this.$tr(0).find("> td").length)>0?n:(t=this.$theadTR.find("> th").length)>0?t:(e=this.$tfootTR.find("> td").length)>0?e:0}},rows:{get:function(){if(this._rows!=null)return this._rows;var e,t=0;this._rows=[];for(;t0))return this.clearBody();this._rows=e,this.make()}},header:{get:function(){return this.$theadTR.find("> th").ojValues()},set:function(e){return N(l.isArray(e),this.typeName+".header","array expected for first argument"),e!=null&&e.length>0?this.$theadTRMake.oj(function(){return e.map(function(e){l.th(e)})}):this.clearHeader()}},footer:{get:function(){return this.$tfootTR.find("> td").ojValues()},set:function(e){var t=this;if(!l.isArray(e))throw new Error("oj.Table.footer: array expected for first argument");return e!=null&&e.length>0?this.$tfootTRMake.oj(function(){var t,n,r,i;i=[];for(n=0,r=e.length;n caption")}},$colgroup:{get:function(){return this.$("> colgroup")}},$thead:{get:function(){return this.$("> thead")}},$tfoot:{get:function(){return this.$("> tfoot")}},$tbody:{get:function(){return this.$("> tbody")}},$theadTR:{get:function(){return this.$thead.find("> tr")}},$tfootTR:{get:function(){return this.$tfoot.find("> tr")}},$ths:{get:function(){return this.$theadTR.find("> th")}},$trs:{get:function(){return this._$trs!=null?this._$trs:this._$trs=this.$("> tbody > tr")}},$colgroupMake:{get:function(){return this.$colgroup.length>0?this.$colgroup:(t="",this.$caption.length>0?this.$caption.insertAfter(t):this.$table.append(t),this.$tbody)}},$captionMake:{get:function(){return this.$caption.length>0?this.$caption:(this.$table.prepend(""),this.$caption)}},$tfootMake:{get:function(){return this.$tfoot.length>0?this.$tfoot:(t="",this.$tfoot.length>0?this.$tfoot.insertBefore(t):this.$table.append(t),this.$tfoot)}},$theadMake:{get:function(){return this.$thead.length>0?this.$thead:(t="",this.$colgroup.length>0?this.$colgroup.insertAfter(t):this.$caption.length>0?this.$caption.insertAfter(t):this.$table.prepend(t),this.$thead)}},$tbodyMake:{get:function(){return this.$tbody.length>0?this.$tbody:(this.$table.append(""),this.$tbody)}},$theadTRMake:{get:function(){return this.$theadTR.length>0?this.$theadTR:(this.$theadMake.html(""),this.$theadTR)}},$tfootTRMake:{get:function(){return this.$tfootTR.length>0?this.$tfootTR:(this.$tfootMake.html(""),this.$tfootTR)}}},methods:{make:function(){if(!this.isConstructed)return;var e=this,t,n=[];this.models!=null&&this.each!=null?(t=l.isEvented(this.models)?this.models.models:this._models,n=t.map(function(t){return e._rowFromModel(t)})):this.rows!=null&&(n=this.rows.map(function(e){return l(function(){e.forEach(function(e){l.td(e)})})})),n.length>0&&this.$tbodyMake.oj(function(){n.forEach(function(e){l.tr(e)})}),this.bodyChanged()},collectionModelAdded:function(e,t){var n=t.indexOf(e),r=this._rowFromModel(e);this._addRowTR(n,l(function(){return l.tr(r)}))},collectionModelRemoved:function(e,t,n){this.removeRow(n.index)},collectionReset:function(){this.make()},$tr:function(e){return e=e<0?e+count:e,this.$trs.eq(e)},$tdsRow:function(e){return e=e<0?e+count:e,this.$tr(e).find("> td")},$td:function(e,t){return e=e<0?e+this.rowCount:e,t=t<0?t+this.columnCount:t,this.$tdsRow(e).eq(t)},row:function(e,t){e=this._bound(e,this.rowCount,".row: rx");if(t==null)return this.$tdsRow(e).ojValues();N(t.length===cellCount(e),this.typeName,"array expected for second argument with length ("+e+")"),t.forEach(function(t,n){this.$td(e,n).oj(t)})},cell:function(e,t,n){return n!=null?this.$td(e,t).oj(n):this.$td(e,t).ojValue()},addRow:function(e,t){t==null&&(t=e,e=-1),e=this._bound(e,this.rowCount+1,".addRow: rx"),N(l.isArray(t),"addRow","expected array for row content"),this._addRowTR(e,function(){l.tr(function(){t.forEach(function(e){l.td(e)})})})},_addRowTR:function(e,t){this.rowCount===0?this.$el.oj(t):e===this.rowCount?this.$tr(e-1).ojAfter(t):this.$tr(e).ojBefore(t),this.bodyChanged()},removeRow:function(e){e==null&&(e=-1),e=this._bound(e,this.rowCount,".removeRow: index");var t=this.row(e);return this.$tr(e).remove(),this.bodyChanged(),t},moveRow:function(e,t){if(e===t)return;e=this._bound(e,this.rowCount,".moveRow: fromIndex"),t=this._bound(t,this.rowCount,".moveRow: toIndex");var n=t>e?"insertAfter":"insertBefore";this.$tr(e)[n](this.$tr(t)),this.bodyChanged()},swapRow:function(e,t){if(e===t)return;e=this._bound(e,this.rowCount,".swap: firstIndex"),t=this._bound(t,this.rowCount,".swap: secondIndex");if(Math.abs(e-t)===1)this.moveRow(e,t);else{var n=Math.min(e,t),r=Math.max(e,t);this.moveRow(r,n),this.moveRow(n+1,r)}this.bodyChanged()},unshiftRow:function(e){this.addRow(0,e)},shiftRow:function(){return this.removeRow(0)},pushRow:function(e){this.addRow(this.rowCount,e)},popRow:function(){return this.removeRow(-1)},clearColgroup:function(){this.$colgroup.remove()},clearBody:function(){this.$tbody.remove(),this.bodyChanged()},clearHeader:function(){this.$thead.remove(),this.headerChanged()},clearFooter:function(){this.$tfoot.remove(),this.footerChanged()},clearCaption:function(){this.$capation.remove()},clear:function(){return this.clearBody(),this.clearHeader(),this.clearFooter(),this.$caption.remove()},bodyChanged:function(){this._rows=null,this._columns=null,this._$trs=null},headerChanged:function(){this._header=null},footerChanged:function(){this._footer=null},_rowFromModel:function(e){var t=this;return l(function(){return t.each(e,l.td)})},_bound:function(e,t,n){var r=e<0?e+t:e;if(0<=r&&r0&&e[0]!=="_"||e.length>0&&e[0]==="_"&&l[e.slice(1)]!=null)&&l.addProperty(l.sandbox,e,{value:l[e],writable:!1})}),l.use=function(e,t){t=x(t,{}),C("use",1,e,"function"),C("use",2,t,"object");var n=e(l,t),r=w(n),i,s;for(i in n)s=n[i],l.isOJType(s)&&(r[D(i)]=_createQuietType(s.typeName));for(i in r)s=r[i],l[i]=s,l.addProperty(l.sandbox,i,{value:s,writable:!1})},l.$.fn.oj=it({get:function(e){return e[0].oj},set:function(e,t){if(t.length===0)return e[0].oj;var n=l.compile.apply(l,[{dom:1,html:0,cssMap:1}].concat(s.call(t)));ot(n.cssMap,{global:0}),e.html(""),l.isArray(n.dom)||(n.dom=[n.dom]);for(var r=0;r=-1&&!t){r=n>=0?arguments[n]:process.cwd();if(typeof r!="string"||!r)continue;e=r+"/"+e,t=r.charAt(0)==="/",n--}return e=pt(e.split("/").filter(function(e){return!!e}),!t).join("/"),(t?"/":"")+e||"."},l._pathNormalize=function(e){var t=e.charAt(0)==="/",n=e.substr(-1)==="/";return e=pt(e.split("/").filter(function(e){return!!e}),!t).join("/"),!e&&!t&&(e="."),e&&n&&(e+="/"),(t?"/":"")+e},l._pathJoin=function(){var e=s.call(arguments,0);return l._pathNormalize(e.filter(function(e,t){return e&&typeof e=="string"}).join("/"))},l._pathDirname=function(e){var t=ht(e),n=t[0],r=t[1];return!n&&!r?".":(r&&(r=r.substr(0,r.length-1)),n+r)}}).call(this) \ No newline at end of file diff --git a/ajax/libs/oj/package.json b/ajax/libs/oj/package.json index f7ae8fc67..16e42aaac 100644 --- a/ajax/libs/oj/package.json +++ b/ajax/libs/oj/package.json @@ -1,6 +1,6 @@ { "name": "oj", - "version": "0.1.6", + "version": "0.2.1", "description": "A unified templating language for the people. Thirsty people.", "homepage": "http://ojjs.org", "keywords": [ From 64a5ed0819ce528b6a16784952a351b8e30e74e4 Mon Sep 17 00:00:00 2001 From: Mark Healey Date: Tue, 15 Oct 2013 07:52:00 -0600 Subject: [PATCH 15/26] F2 version 1.3.1 release --- ajax/libs/F2/1.3.1/f2.basic.js | 4602 +++++ ajax/libs/F2/1.3.1/f2.basic.min.js | 69 + ajax/libs/F2/1.3.1/f2.js | 16841 ++++++++++++++++ ajax/libs/F2/1.3.1/f2.min.js | 144 + ajax/libs/F2/1.3.1/f2.min.map | 1 + ajax/libs/F2/1.3.1/f2.no-bootstrap.js | 16595 +++++++++++++++ ajax/libs/F2/1.3.1/f2.no-bootstrap.min.js | 125 + ajax/libs/F2/1.3.1/f2.no-easyXDM.js | 14334 +++++++++++++ ajax/libs/F2/1.3.1/f2.no-easyXDM.min.js | 119 + .../F2/1.3.1/f2.no-jquery-or-bootstrap.js | 7109 +++++++ .../F2/1.3.1/f2.no-jquery-or-bootstrap.min.js | 93 + ajax/libs/F2/package.json | 4 +- 12 files changed, 60034 insertions(+), 2 deletions(-) create mode 100644 ajax/libs/F2/1.3.1/f2.basic.js create mode 100644 ajax/libs/F2/1.3.1/f2.basic.min.js create mode 100644 ajax/libs/F2/1.3.1/f2.js create mode 100644 ajax/libs/F2/1.3.1/f2.min.js create mode 100644 ajax/libs/F2/1.3.1/f2.min.map create mode 100644 ajax/libs/F2/1.3.1/f2.no-bootstrap.js create mode 100644 ajax/libs/F2/1.3.1/f2.no-bootstrap.min.js create mode 100644 ajax/libs/F2/1.3.1/f2.no-easyXDM.js create mode 100644 ajax/libs/F2/1.3.1/f2.no-easyXDM.min.js create mode 100644 ajax/libs/F2/1.3.1/f2.no-jquery-or-bootstrap.js create mode 100644 ajax/libs/F2/1.3.1/f2.no-jquery-or-bootstrap.min.js diff --git a/ajax/libs/F2/1.3.1/f2.basic.js b/ajax/libs/F2/1.3.1/f2.basic.js new file mode 100644 index 000000000..953442c60 --- /dev/null +++ b/ajax/libs/F2/1.3.1/f2.basic.js @@ -0,0 +1,4602 @@ +;(function(exports) { + + if (exports.F2 && !exports.F2_TESTING_MODE) { + return; + } + +/*! + JSON.org requires the following notice to accompany json2: + + Copyright (c) 2002 JSON.org + + http://json.org + + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + + The Software shall be used for Good, not Evil. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + IN THE SOFTWARE. +*/ +/* + This code should be minified before deployment. + See http://javascript.crockford.com/jsmin.html + + USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO + NOT CONTROL. + + + This file creates a global JSON object containing two methods: stringify + and parse. + + JSON.stringify(value, replacer, space) + value any JavaScript value, usually an object or array. + + replacer an optional parameter that determines how object + values are stringified for objects. It can be a + function or an array of strings. + + space an optional parameter that specifies the indentation + of nested structures. If it is omitted, the text will + be packed without extra whitespace. If it is a number, + it will specify the number of spaces to indent at each + level. If it is a string (such as '\t' or ' '), + it contains the characters used to indent at each level. + + This method produces a JSON text from a JavaScript value. + + When an object value is found, if the object contains a toJSON + method, its toJSON method will be called and the result will be + stringified. A toJSON method does not serialize: it returns the + value represented by the name/value pair that should be serialized, + or undefined if nothing should be serialized. The toJSON method + will be passed the key associated with the value, and this will be + bound to the value + + For example, this would serialize Dates as ISO strings. + + Date.prototype.toJSON = function (key) { + function f(n) { + // Format integers to have at least two digits. + return n < 10 ? '0' + n : n; + } + + return this.getUTCFullYear() + '-' + + f(this.getUTCMonth() + 1) + '-' + + f(this.getUTCDate()) + 'T' + + f(this.getUTCHours()) + ':' + + f(this.getUTCMinutes()) + ':' + + f(this.getUTCSeconds()) + 'Z'; + }; + + You can provide an optional replacer method. It will be passed the + key and value of each member, with this bound to the containing + object. The value that is returned from your method will be + serialized. If your method returns undefined, then the member will + be excluded from the serialization. + + If the replacer parameter is an array of strings, then it will be + used to select the members to be serialized. It filters the results + such that only members with keys listed in the replacer array are + stringified. + + Values that do not have JSON representations, such as undefined or + functions, will not be serialized. Such values in objects will be + dropped; in arrays they will be replaced with null. You can use + a replacer function to replace those with JSON values. + JSON.stringify(undefined) returns undefined. + + The optional space parameter produces a stringification of the + value that is filled with line breaks and indentation to make it + easier to read. + + If the space parameter is a non-empty string, then that string will + be used for indentation. If the space parameter is a number, then + the indentation will be that many spaces. + + Example: + + text = JSON.stringify(['e', {pluribus: 'unum'}]); + // text is '["e",{"pluribus":"unum"}]' + + + text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); + // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' + + text = JSON.stringify([new Date()], function (key, value) { + return this[key] instanceof Date ? + 'Date(' + this[key] + ')' : value; + }); + // text is '["Date(---current time---)"]' + + + JSON.parse(text, reviver) + This method parses a JSON text to produce an object or array. + It can throw a SyntaxError exception. + + The optional reviver parameter is a function that can filter and + transform the results. It receives each of the keys and values, + and its return value is used instead of the original value. + If it returns what it received, then the structure is not modified. + If it returns undefined then the member is deleted. + + Example: + + // Parse the text. Values that look like ISO date strings will + // be converted to Date objects. + + myData = JSON.parse(text, function (key, value) { + var a; + if (typeof value === 'string') { + a = +/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); + if (a) { + return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], + +a[5], +a[6])); + } + } + return value; + }); + + myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { + var d; + if (typeof value === 'string' && + value.slice(0, 5) === 'Date(' && + value.slice(-1) === ')') { + d = new Date(value.slice(5, -1)); + if (d) { + return d; + } + } + return value; + }); + + + This is a reference implementation. You are free to copy, modify, or + redistribute. +*/ + +/*jslint evil: true, regexp: true */ + +/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, + call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, + getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, + lastIndex, length, parse, prototype, push, replace, slice, stringify, + test, toJSON, toString, valueOf +*/ + + +// Create a JSON object only if one does not already exist. We create the +// methods in a closure to avoid creating global variables. + +if (typeof JSON !== 'object') { + JSON = {}; +} + +(function () { + 'use strict'; + + function f(n) { + // Format integers to have at least two digits. + return n < 10 ? '0' + n : n; + } + + if (typeof Date.prototype.toJSON !== 'function') { + + Date.prototype.toJSON = function (key) { + + return isFinite(this.valueOf()) + ? this.getUTCFullYear() + '-' + + f(this.getUTCMonth() + 1) + '-' + + f(this.getUTCDate()) + 'T' + + f(this.getUTCHours()) + ':' + + f(this.getUTCMinutes()) + ':' + + f(this.getUTCSeconds()) + 'Z' + : null; + }; + + String.prototype.toJSON = + Number.prototype.toJSON = + Boolean.prototype.toJSON = function (key) { + return this.valueOf(); + }; + } + + var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, + escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, + gap, + indent, + meta = { // table of character substitutions + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + '"' : '\\"', + '\\': '\\\\' + }, + rep; + + + function quote(string) { + +// If the string contains no control characters, no quote characters, and no +// backslash characters, then we can safely slap some quotes around it. +// Otherwise we must also replace the offending characters with safe escape +// sequences. + + escapable.lastIndex = 0; + return escapable.test(string) ? '"' + string.replace(escapable, function (a) { + var c = meta[a]; + return typeof c === 'string' + ? c + : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }) + '"' : '"' + string + '"'; + } + + + function str(key, holder) { + +// Produce a string from holder[key]. + + var i, // The loop counter. + k, // The member key. + v, // The member value. + length, + mind = gap, + partial, + value = holder[key]; + +// If the value has a toJSON method, call it to obtain a replacement value. + + if (value && typeof value === 'object' && + typeof value.toJSON === 'function') { + value = value.toJSON(key); + } + +// If we were called with a replacer function, then call the replacer to +// obtain a replacement value. + + if (typeof rep === 'function') { + value = rep.call(holder, key, value); + } + +// What happens next depends on the value's type. + + switch (typeof value) { + case 'string': + return quote(value); + + case 'number': + +// JSON numbers must be finite. Encode non-finite numbers as null. + + return isFinite(value) ? String(value) : 'null'; + + case 'boolean': + case 'null': + +// If the value is a boolean or null, convert it to a string. Note: +// typeof null does not produce 'null'. The case is included here in +// the remote chance that this gets fixed someday. + + return String(value); + +// If the type is 'object', we might be dealing with an object or an array or +// null. + + case 'object': + +// Due to a specification blunder in ECMAScript, typeof null is 'object', +// so watch out for that case. + + if (!value) { + return 'null'; + } + +// Make an array to hold the partial results of stringifying this object value. + + gap += indent; + partial = []; + +// Is the value an array? + + if (Object.prototype.toString.apply(value) === '[object Array]') { + +// The value is an array. Stringify every element. Use null as a placeholder +// for non-JSON values. + + length = value.length; + for (i = 0; i < length; i += 1) { + partial[i] = str(i, value) || 'null'; + } + +// Join all of the elements together, separated with commas, and wrap them in +// brackets. + + v = partial.length === 0 + ? '[]' + : gap + ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' + : '[' + partial.join(',') + ']'; + gap = mind; + return v; + } + +// If the replacer is an array, use it to select the members to be stringified. + + if (rep && typeof rep === 'object') { + length = rep.length; + for (i = 0; i < length; i += 1) { + if (typeof rep[i] === 'string') { + k = rep[i]; + v = str(k, value); + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } else { + +// Otherwise, iterate through all of the keys in the object. + + for (k in value) { + if (Object.prototype.hasOwnProperty.call(value, k)) { + v = str(k, value); + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } + +// Join all of the member texts together, separated with commas, +// and wrap them in braces. + + v = partial.length === 0 + ? '{}' + : gap + ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' + : '{' + partial.join(',') + '}'; + gap = mind; + return v; + } + } + +// If the JSON object does not yet have a stringify method, give it one. + + if (typeof JSON.stringify !== 'function') { + JSON.stringify = function (value, replacer, space) { + +// The stringify method takes a value and an optional replacer, and an optional +// space parameter, and returns a JSON text. The replacer can be a function +// that can replace values, or an array of strings that will select the keys. +// A default replacer method can be provided. Use of the space parameter can +// produce text that is more easily readable. + + var i; + gap = ''; + indent = ''; + +// If the space parameter is a number, make an indent string containing that +// many spaces. + + if (typeof space === 'number') { + for (i = 0; i < space; i += 1) { + indent += ' '; + } + +// If the space parameter is a string, it will be used as the indent string. + + } else if (typeof space === 'string') { + indent = space; + } + +// If there is a replacer, it must be a function or an array. +// Otherwise, throw an error. + + rep = replacer; + if (replacer && typeof replacer !== 'function' && + (typeof replacer !== 'object' || + typeof replacer.length !== 'number')) { + throw new Error('JSON.stringify'); + } + +// Make a fake root object containing our value under the key of ''. +// Return the result of stringifying the value. + + return str('', {'': value}); + }; + } + + +// If the JSON object does not yet have a parse method, give it one. + + if (typeof JSON.parse !== 'function') { + JSON.parse = function (text, reviver) { + +// The parse method takes a text and an optional reviver function, and returns +// a JavaScript value if the text is a valid JSON text. + + var j; + + function walk(holder, key) { + +// The walk method is used to recursively walk the resulting structure so +// that modifications can be made. + + var k, v, value = holder[key]; + if (value && typeof value === 'object') { + for (k in value) { + if (Object.prototype.hasOwnProperty.call(value, k)) { + v = walk(value, k); + if (v !== undefined) { + value[k] = v; + } else { + delete value[k]; + } + } + } + } + return reviver.call(holder, key, value); + } + + +// Parsing happens in four stages. In the first stage, we replace certain +// Unicode characters with escape sequences. JavaScript handles many characters +// incorrectly, either silently deleting them, or treating them as line endings. + + text = String(text); + cx.lastIndex = 0; + if (cx.test(text)) { + text = text.replace(cx, function (a) { + return '\\u' + + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }); + } + +// In the second stage, we run the text against regular expressions that look +// for non-JSON patterns. We are especially concerned with '()' and 'new' +// because they can cause invocation, and '=' because it can cause mutation. +// But just to be safe, we want to reject all unexpected forms. + +// We split the second stage into 4 regexp operations in order to work around +// crippling inefficiencies in IE's and Safari's regexp engines. First we +// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we +// replace all simple value tokens with ']' characters. Third, we delete all +// open brackets that follow a colon or comma or that begin the text. Finally, +// we look to see that the remaining characters are only whitespace or ']' or +// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. + + if (/^[\],:{}\s]*$/ + .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') + .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') + .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { + +// In the third stage we use the eval function to compile the text into a +// JavaScript structure. The '{' operator is subject to a syntactic ambiguity +// in JavaScript: it can begin a block or an object literal. We wrap the text +// in parens to eliminate the ambiguity. + + j = eval('(' + text + ')'); + +// In the optional fourth stage, we recursively walk the new structure, passing +// each name/value pair to a reviver function for possible transformation. + + return typeof reviver === 'function' + ? walk({'': j}, '') + : j; + } + +// If the text is not JSON parseable, then a SyntaxError is thrown. + + throw new SyntaxError('JSON.parse'); + }; + } +}()); + +/*! + * Hij1nx requires the following notice to accompany EventEmitter: + * + * Copyright (c) 2011 hij1nx + * + * http://www.twitter.com/hij1nx + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the 'Software'), to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO + * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +!function(exports, undefined) { + + var isArray = Array.isArray ? Array.isArray : function _isArray(obj) { + return Object.prototype.toString.call(obj) === "[object Array]"; + }; + var defaultMaxListeners = 10; + + function init() { + this._events = new Object; + } + + function configure(conf) { + if (conf) { + conf.delimiter && (this.delimiter = conf.delimiter); + conf.wildcard && (this.wildcard = conf.wildcard); + if (this.wildcard) { + this.listenerTree = new Object; + } + } + } + + function EventEmitter(conf) { + this._events = new Object; + configure.call(this, conf); + } + + // + // Attention, function return type now is array, always ! + // It has zero elements if no any matches found and one or more + // elements (leafs) if there are matches + // + function searchListenerTree(handlers, type, tree, i) { + if (!tree) { + return []; + } + var listeners=[], leaf, len, branch, xTree, xxTree, isolatedBranch, endReached, + typeLength = type.length, currentType = type[i], nextType = type[i+1]; + if (i === typeLength && tree._listeners) { + // + // If at the end of the event(s) list and the tree has listeners + // invoke those listeners. + // + if (typeof tree._listeners === 'function') { + handlers && handlers.push(tree._listeners); + return [tree]; + } else { + for (leaf = 0, len = tree._listeners.length; leaf < len; leaf++) { + handlers && handlers.push(tree._listeners[leaf]); + } + return [tree]; + } + } + + if ((currentType === '*' || currentType === '**') || tree[currentType]) { + // + // If the event emitted is '*' at this part + // or there is a concrete match at this patch + // + if (currentType === '*') { + for (branch in tree) { + if (branch !== '_listeners' && tree.hasOwnProperty(branch)) { + listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+1)); + } + } + return listeners; + } else if(currentType === '**') { + endReached = (i+1 === typeLength || (i+2 === typeLength && nextType === '*')); + if(endReached && tree._listeners) { + // The next element has a _listeners, add it to the handlers. + listeners = listeners.concat(searchListenerTree(handlers, type, tree, typeLength)); + } + + for (branch in tree) { + if (branch !== '_listeners' && tree.hasOwnProperty(branch)) { + if(branch === '*' || branch === '**') { + if(tree[branch]._listeners && !endReached) { + listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], typeLength)); + } + listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i)); + } else if(branch === nextType) { + listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+2)); + } else { + // No match on this one, shift into the tree but not in the type array. + listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i)); + } + } + } + return listeners; + } + + listeners = listeners.concat(searchListenerTree(handlers, type, tree[currentType], i+1)); + } + + xTree = tree['*']; + if (xTree) { + // + // If the listener tree will allow any match for this part, + // then recursively explore all branches of the tree + // + searchListenerTree(handlers, type, xTree, i+1); + } + + xxTree = tree['**']; + if(xxTree) { + if(i < typeLength) { + if(xxTree._listeners) { + // If we have a listener on a '**', it will catch all, so add its handler. + searchListenerTree(handlers, type, xxTree, typeLength); + } + + // Build arrays of matching next branches and others. + for(branch in xxTree) { + if(branch !== '_listeners' && xxTree.hasOwnProperty(branch)) { + if(branch === nextType) { + // We know the next element will match, so jump twice. + searchListenerTree(handlers, type, xxTree[branch], i+2); + } else if(branch === currentType) { + // Current node matches, move into the tree. + searchListenerTree(handlers, type, xxTree[branch], i+1); + } else { + isolatedBranch = {}; + isolatedBranch[branch] = xxTree[branch]; + searchListenerTree(handlers, type, { '**': isolatedBranch }, i+1); + } + } + } + } else if(xxTree._listeners) { + // We have reached the end and still on a '**' + searchListenerTree(handlers, type, xxTree, typeLength); + } else if(xxTree['*'] && xxTree['*']._listeners) { + searchListenerTree(handlers, type, xxTree['*'], typeLength); + } + } + + return listeners; + } + + function growListenerTree(type, listener) { + + type = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); + + // + // Looks for two consecutive '**', if so, don't add the event at all. + // + for(var i = 0, len = type.length; i+1 < len; i++) { + if(type[i] === '**' && type[i+1] === '**') { + return; + } + } + + var tree = this.listenerTree; + var name = type.shift(); + + while (name) { + + if (!tree[name]) { + tree[name] = new Object; + } + + tree = tree[name]; + + if (type.length === 0) { + + if (!tree._listeners) { + tree._listeners = listener; + } + else if(typeof tree._listeners === 'function') { + tree._listeners = [tree._listeners, listener]; + } + else if (isArray(tree._listeners)) { + + tree._listeners.push(listener); + + if (!tree._listeners.warned) { + + var m = defaultMaxListeners; + + if (typeof this._events.maxListeners !== 'undefined') { + m = this._events.maxListeners; + } + + if (m > 0 && tree._listeners.length > m) { + + tree._listeners.warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + tree._listeners.length); + console.trace(); + } + } + } + return true; + } + name = type.shift(); + } + return true; + }; + + // By default EventEmitters will print a warning if more than + // 10 listeners are added to it. This is a useful default which + // helps finding memory leaks. + // + // Obviously not all Emitters should be limited to 10. This function allows + // that to be increased. Set to zero for unlimited. + + EventEmitter.prototype.delimiter = '.'; + + EventEmitter.prototype.setMaxListeners = function(n) { + this._events || init.call(this); + this._events.maxListeners = n; + }; + + EventEmitter.prototype.event = ''; + + EventEmitter.prototype.once = function(event, fn) { + this.many(event, 1, fn); + return this; + }; + + EventEmitter.prototype.many = function(event, ttl, fn) { + var self = this; + + if (typeof fn !== 'function') { + throw new Error('many only accepts instances of Function'); + } + + function listener() { + if (--ttl === 0) { + self.off(event, listener); + } + fn.apply(this, arguments); + }; + + listener._origin = fn; + + this.on(event, listener); + + return self; + }; + + EventEmitter.prototype.emit = function() { + this._events || init.call(this); + + var type = arguments[0]; + + if (type === 'newListener') { + if (!this._events.newListener) { return false; } + } + + // Loop through the *_all* functions and invoke them. + if (this._all) { + var l = arguments.length; + var args = new Array(l - 1); + for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; + for (i = 0, l = this._all.length; i < l; i++) { + this.event = type; + this._all[i].apply(this, args); + } + } + + // If there is no 'error' event listener then throw. + if (type === 'error') { + + if (!this._all && + !this._events.error && + !(this.wildcard && this.listenerTree.error)) { + + if (arguments[1] instanceof Error) { + throw arguments[1]; // Unhandled 'error' event + } else { + throw new Error("Uncaught, unspecified 'error' event."); + } + return false; + } + } + + var handler; + + if(this.wildcard) { + handler = []; + var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); + searchListenerTree.call(this, handler, ns, this.listenerTree, 0); + } + else { + handler = this._events[type]; + } + + if (typeof handler === 'function') { + this.event = type; + if (arguments.length === 1) { + handler.call(this); + } + else if (arguments.length > 1) + switch (arguments.length) { + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + var l = arguments.length; + var args = new Array(l - 1); + for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; + handler.apply(this, args); + } + return true; + } + else if (handler) { + var l = arguments.length; + var args = new Array(l - 1); + for (var i = 1; i < l; i++) args[i - 1] = arguments[i]; + + var listeners = handler.slice(); + for (var i = 0, l = listeners.length; i < l; i++) { + this.event = type; + listeners[i].apply(this, args); + } + return (listeners.length > 0) || this._all; + } + else { + return this._all; + } + + }; + + EventEmitter.prototype.on = function(type, listener) { + + if (typeof type === 'function') { + this.onAny(type); + return this; + } + + if (typeof listener !== 'function') { + throw new Error('on only accepts instances of Function'); + } + this._events || init.call(this); + + // To avoid recursion in the case that type == "newListeners"! Before + // adding it to the listeners, first emit "newListeners". + this.emit('newListener', type, listener); + + if(this.wildcard) { + growListenerTree.call(this, type, listener); + return this; + } + + if (!this._events[type]) { + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + } + else if(typeof this._events[type] === 'function') { + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; + } + else if (isArray(this._events[type])) { + // If we've already got an array, just append. + this._events[type].push(listener); + + // Check for listener leak + if (!this._events[type].warned) { + + var m = defaultMaxListeners; + + if (typeof this._events.maxListeners !== 'undefined') { + m = this._events.maxListeners; + } + + if (m > 0 && this._events[type].length > m) { + + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + console.trace(); + } + } + } + return this; + }; + + EventEmitter.prototype.onAny = function(fn) { + + if(!this._all) { + this._all = []; + } + + if (typeof fn !== 'function') { + throw new Error('onAny only accepts instances of Function'); + } + + // Add the function to the event listener collection. + this._all.push(fn); + return this; + }; + + EventEmitter.prototype.addListener = EventEmitter.prototype.on; + + EventEmitter.prototype.off = function(type, listener) { + if (typeof listener !== 'function') { + throw new Error('removeListener only takes instances of Function'); + } + + var handlers,leafs=[]; + + if(this.wildcard) { + var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); + leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); + } + else { + // does not use listeners(), so no side effect of creating _events[type] + if (!this._events[type]) return this; + handlers = this._events[type]; + leafs.push({_listeners:handlers}); + } + + for (var iLeaf=0; iLeaf 0) { + fns = this._all; + for(i = 0, l = fns.length; i < l; i++) { + if(fn === fns[i]) { + fns.splice(i, 1); + return this; + } + } + } else { + this._all = []; + } + return this; + }; + + EventEmitter.prototype.removeListener = EventEmitter.prototype.off; + + EventEmitter.prototype.removeAllListeners = function(type) { + if (arguments.length === 0) { + !this._events || init.call(this); + return this; + } + + if(this.wildcard) { + var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice(); + var leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0); + + for (var iLeaf=0; iLeaf -1; + }, + /** + * Tests a URL to see if it's on the same domain (local) or not + * @method isLocalRequest + * @param {URL to test} url + * @returns {bool} Whether the URL is local or not + * Derived from: https://github.com/jquery/jquery/blob/master/src/ajax.js + */ + isLocalRequest: function(url){ + var rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, + urlLower = url.toLowerCase(), + parts = rurl.exec( urlLower ), + ajaxLocation, + ajaxLocParts; + + try { + ajaxLocation = location.href; + } catch( e ) { + // Use the href attribute of an A element + // since IE will modify it given document.location + ajaxLocation = document.createElement('a'); + ajaxLocation.href = ''; + ajaxLocation = ajaxLocation.href; + } + + ajaxLocation = ajaxLocation.toLowerCase(); + + // uh oh, the url must be relative + // make it fully qualified and re-regex url + if (!parts){ + urlLower = _absolutizeURI(ajaxLocation,urlLower).toLowerCase(); + parts = rurl.exec( urlLower ); + } + + // Segment location into parts + ajaxLocParts = rurl.exec( ajaxLocation ) || []; + + // do hostname and protocol and port of manifest URL match location.href? (a "local" request on the same domain) + var matched = !(parts && + (parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || + (parts[ 3 ] || (parts[ 1 ] === 'http:' ? '80' : '443')) !== + (ajaxLocParts[ 3 ] || (ajaxLocParts[ 1 ] === 'http:' ? '80' : '443')))); + + return matched; + }, + /** + * Utility method to determine whether or not the argument passed in is or is not a native dom node. + * @method isNativeDOMNode + * @param {object} testObject The object you want to check as native dom node. + * @return {bool} Returns true if the object passed is a native dom node. + */ + isNativeDOMNode: function(testObject) { + var bIsNode = ( + typeof Node === 'object' ? testObject instanceof Node : + testObject && typeof testObject === 'object' && typeof testObject.nodeType === 'number' && typeof testObject.nodeName === 'string' + ); + + var bIsElement = ( + typeof HTMLElement === 'object' ? testObject instanceof HTMLElement : //DOM2 + testObject && typeof testObject === 'object' && testObject.nodeType === 1 && typeof testObject.nodeName === 'string' + ); + + return (bIsNode || bIsElement); + }, + /** + * A utility logging function to write messages or objects to the browser console. This is a proxy for the [`console` API](https://developers.google.com/chrome-developer-tools/docs/console). + * @method log + * @param {object|string} Object/Method An object to be logged _or_ a `console` API method name, such as `warn` or `error`. All of the console method names are [detailed in the Chrome docs](https://developers.google.com/chrome-developer-tools/docs/console-api). + * @param {object} [obj2]* An object to be logged + * @example + //Pass any object (string, int, array, object, bool) to .log() + F2.log('foo'); + F2.log(myArray); + //Use a console method name as the first argument. + F2.log('error', err); + F2.log('info', 'The session ID is ' + sessionId); + * Some code derived from [HTML5 Boilerplate console plugin](https://github.com/h5bp/html5-boilerplate/blob/master/js/plugins.js) + */ + log: function() { + var _log; + var _logMethod = 'log'; + var method; + var noop = function () { }; + var methods = [ + 'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', + 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', + 'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd', + 'timeStamp', 'trace', 'warn' + ]; + var length = methods.length; + var console = (window.console = window.console || {}); + var args; + + while (length--) { + method = methods[length]; + + // Only stub undefined methods. + if (!console[method]) { + console[method] = noop; + } + + //if first arg is a console function, use it. + //defaults to console.log() + if (arguments && arguments.length > 1 && arguments[0] == method){ + _logMethod = method; + //remove console func from args + args = Array.prototype.slice.call(arguments, 1); + } + } + + if (Function.prototype.bind) { + _log = Function.prototype.bind.call(console[_logMethod], console); + } else { + _log = function() { + Function.prototype.apply.call(console[_logMethod], console, (args || arguments)); + }; + } + + _log.apply(this, (args || arguments)); + }, + /** + * Wrapper to convert a JSON string to an object + * @method parse + * @param {string} str The JSON string to convert + * @return {object} The parsed object + */ + parse: function(str) { + return JSON.parse(str); + }, + /** + * Wrapper to convert an object to JSON + * + * **Note: When using F2.stringify on an F2.AppConfig object, it is + * recommended to pass F2.appConfigReplacer as the replacer function in + * order to prevent circular serialization errors.** + * @method stringify + * @param {object} value The object to convert + * @param {function|Array} replacer An optional parameter that determines + * how object values are stringified for objects. It can be a function or an + * array of strings. + * @param {int|string} space An optional parameter that specifies the + * indentation of nested structures. If it is omitted, the text will be + * packed without extra whitespace. If it is a number, it will specify the + * number of spaces to indent at each level. If it is a string (such as '\t' + * or ' '), it contains the characters used to indent at each level. + * @return {string} The JSON string + */ + stringify: function(value, replacer, space) { + return JSON.stringify(value, replacer, space); + }, + /** + * Function to get the F2 version number + * @method version + * @return {string} F2 version number + */ + version: function() { return '{{sdk.version}}'; } + }; +})(); + +/** + * The new `AppHandlers` functionality provides Container Developers a higher level of control over configuring app rendering and interaction. + * + *

                              + *The addition of `F2.AppHandlers` replaces the previous {{#crossLink "F2.ContainerConfig"}}{{/crossLink}} properties `beforeAppRender`, `appRender`, and `afterAppRender`. These methods were deprecated—but not removed—in version 1.2. They will be permanently removed in a future version of F2. + *

                              + * + *

                              + *Starting with F2 version 1.2, `AppHandlers` is the preferred method for Container Developers to manage app layout. + *

                              + * + * ### Order of Execution + * + * **App Rendering** + * + * 0. {{#crossLink "F2/registerApps"}}F2.registerApps(){{/crossLink}} method is called by the Container Developer and the following methods are run for *each* {{#crossLink "F2.AppConfig"}}{{/crossLink}} passed. + * 1. **'appCreateRoot'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_CREATE\_ROOT*) handlers are fired in the order they were attached. + * 2. **'appRenderBefore'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER\_BEFORE*) handlers are fired in the order they were attached. + * 3. Each app's `manifestUrl` is requested asynchronously; on success the following methods are fired. + * 3. **'appRender'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER*) handlers are fired in the order they were attached. + * 4. **'appRenderAfter'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER\_AFTER*) handlers are fired in the order they were attached. + * + * + * **App Removal** + + * 0. {{#crossLink "F2/removeApp"}}F2.removeApp(){{/crossLink}} with a specific {{#crossLink "F2.AppConfig/instanceId "}}{{/crossLink}} or {{#crossLink "F2/removeAllApps"}}F2.removeAllApps(){{/crossLink}} method is called by the Container Developer and the following methods are run. + * 1. **'appDestroyBefore'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY\_BEFORE*) handlers are fired in the order they were attached. + * 2. **'appDestroy'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY*) handlers are fired in the order they were attached. + * 3. **'appDestroyAfter'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY\_AFTER*) handlers are fired in the order they were attached. + * + * **Error Handling** + + * 0. **'appScriptLoadFailed'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_SCRIPT\_LOAD\_FAILED*) handlers are fired in the order they were attached. + * + * @class F2.AppHandlers + */ +F2.extend('AppHandlers', (function() { + + // the hidden token that we will check against every time someone tries to add, remove, fire handler + var _ct = F2.guid(); + var _f2t = F2.guid(); + + var _handlerCollection = { + appCreateRoot: [], + appRenderBefore: [], + appDestroyBefore: [], + appRenderAfter: [], + appDestroyAfter: [], + appRender: [], + appDestroy: [], + appScriptLoadFailed: [] + }; + + var _defaultMethods = { + appRender: function(appConfig, appHtml) + { + var $root = null; + + // if no app root is defined use the app's outer most node + if(!F2.isNativeDOMNode(appConfig.root)) + { + appConfig.root = jQuery(appHtml).get(0); + // get a handle on the root in jQuery + $root = jQuery(appConfig.root); + } + else + { + // get a handle on the root in jQuery + $root = jQuery(appConfig.root); + + // append the app html to the root + $root.append(appHtml); + } + + // append the root to the body by default. + jQuery('body').append($root); + }, + appDestroy: function(appInstance) + { + // call the apps destroy method, if it has one + if(appInstance && appInstance.app && appInstance.app.destroy && typeof(appInstance.app.destroy) == 'function') + { + appInstance.app.destroy(); + } + // warn the Container and App Developer that even though they have a destroy method it hasn't been + else if(appInstance && appInstance.app && appInstance.app.destroy) + { + F2.log(appInstance.config.appId + ' has a destroy property, but destroy is not of type function and as such will not be executed.'); + } + + // fade out and remove the root + jQuery(appInstance.config.root).fadeOut(500, function() { + jQuery(this).remove(); + }); + } + }; + + var _createHandler = function(token, sNamespace, func_or_element, bDomNodeAppropriate) + { + // will throw an exception and stop execution if the token is invalid + _validateToken(token); + + // create handler structure. Not all arguments properties will be populated/used. + var handler = { + func: (typeof(func_or_element)) ? func_or_element : null, + namespace: sNamespace, + domNode: (F2.isNativeDOMNode(func_or_element)) ? func_or_element : null + }; + + if(!handler.func && !handler.domNode) + { + throw ('Invalid or null argument passed. Handler will not be added to collection. A valid dom element or callback function is required.'); + } + + if(handler.domNode && !bDomNodeAppropriate) + { + throw ('Invalid argument passed. Handler will not be added to collection. A callback function is required for this event type.'); + } + + return handler; + }; + + var _validateToken = function(sToken) + { + // check token against F2 and container + if(_ct != sToken && _f2t != sToken) { throw ('Invalid token passed. Please verify that you have correctly received and stored token from F2.AppHandlers.getToken().'); } + }; + + var _removeHandler = function(sToken, eventKey, sNamespace) + { + // will throw an exception and stop execution if the token is invalid + _validateToken(sToken); + + if(!sNamespace && !eventKey) + { + return; + } + // remove by event key + else if(!sNamespace && eventKey) + { + _handlerCollection[eventKey] = []; + } + // remove by namespace only + else if(sNamespace && !eventKey) + { + sNamespace = sNamespace.toLowerCase(); + + for(var currentEventKey in _handlerCollection) + { + var eventCollection = _handlerCollection[currentEventKey]; + var newEvents = []; + + for(var i = 0, ec = eventCollection.length; i < ec; i++) + { + var currentEventHandler = eventCollection[i]; + if(currentEventHandler) + { + if(!currentEventHandler.namespace || currentEventHandler.namespace.toLowerCase() != sNamespace) + { + newEvents.push(currentEventHandler); + } + } + } + + eventCollection = newEvents; + } + } + else if(sNamespace && _handlerCollection[eventKey]) + { + sNamespace = sNamespace.toLowerCase(); + + var newHandlerCollection = []; + + for(var iCounter = 0, hc = _handlerCollection[eventKey].length; iCounter < hc; iCounter++) + { + var currentHandler = _handlerCollection[eventKey][iCounter]; + if(currentHandler) + { + if(!currentHandler.namespace || currentHandler.namespace.toLowerCase() != sNamespace) + { + newHandlerCollection.push(currentHandler); + } + } + } + + _handlerCollection[eventKey] = newHandlerCollection; + } + }; + + return { + /** + * Allows Container Developer to retrieve a unique token which must be passed to + * all `on` and `off` methods. This function will self destruct and can only be called + * one time. Container Developers must store the return value inside of a closure. + * @method getToken + **/ + getToken: function() + { + // delete this method for security that way only the container has access to the token 1 time. + // kind of Ethan Hunt-ish, this message will self destruct immediately. + delete this.getToken; + // return the token, which we validate against. + return _ct; + }, + /** + * Allows F2 to get a token internally. Token is required to call {{#crossLink "F2.AppHandlers/\_\_trigger:method"}}{{/crossLink}}. + * This function will self destruct to eliminate other sources from using the {{#crossLink "F2.AppHandlers/\_\_trigger:method"}}{{/crossLink}} + * and additional internal methods. + * @method __f2GetToken + * @private + **/ + __f2GetToken: function() + { + // delete this method for security that way only the F2 internally has access to the token 1 time. + // kind of Ethan Hunt-ish, this message will self destruct immediately. + delete this.__f2GetToken; + // return the token, which we validate against. + return _f2t; + }, + /** + * Allows F2 to trigger specific events internally. + * @method __trigger + * @private + * @chainable + * @param {String} token The token received from {{#crossLink "F2.AppHandlers/\_\_f2GetToken:method"}}{{/crossLink}}. + * @param {String} eventKey The event to fire. The complete list of event keys is available in {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. + **/ + __trigger: function(token, eventKey) // additional arguments will likely be passed + { + // will throw an exception and stop execution if the token is invalid + if(token != _f2t) + { + throw ('Token passed is invalid. Only F2 is allowed to call F2.AppHandlers.__trigger().'); + } + + if(_handlerCollection && _handlerCollection[eventKey]) + { + // create a collection of arguments that are safe to pass to the callback. + var passableArgs = []; + + // populate that collection with all arguments except token and eventKey + for(var i = 2, j = arguments.length; i < j; i++) + { + passableArgs.push(arguments[i]); + } + + if(_handlerCollection[eventKey].length === 0 && _defaultMethods[eventKey]) + { + _defaultMethods[eventKey].apply(F2, passableArgs); + return this; + } + else if(_handlerCollection[eventKey].length === 0 && !_handlerCollection[eventKey]) + { + return this; + } + + // fire all event listeners in the order that they were added. + for(var iCounter = 0, hcl = _handlerCollection[eventKey].length; iCounter < hcl; iCounter++) + { + var handler = _handlerCollection[eventKey][iCounter]; + + // appRender where root is already defined + if (handler.domNode && arguments[2] && arguments[2].root && arguments[3]) + { + var $appRoot = jQuery(arguments[2].root).append(arguments[3]); + jQuery(handler.domNode).append($appRoot); + } + else if (handler.domNode && arguments[2] && !arguments[2].root && arguments[3]) + { + // set the root to the actual HTML of the app + arguments[2].root = jQuery(arguments[3]).get(0); + // appends the root to the dom node specified + jQuery(handler.domNode).append(arguments[2].root); + } + else + { + handler.func.apply(F2, passableArgs); + } + } + } + else + { + throw ('Invalid EventKey passed. Check your inputs and try again.'); + } + + return this; + }, + /** + * Allows Container Developer to easily tell all apps to render in a specific location. Only valid for eventType `appRender`. + * @method on + * @chainable + * @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}. + * @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. The namespace is useful for removal + * purposes. At this time it does not affect when an event is fired. Complete list of event keys available in + * {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. + * @params {HTMLElement} element Specific DOM element to which app gets appended. + * @example + * var _token = F2.AppHandlers.getToken(); + * F2.AppHandlers.on( + * _token, + * 'appRender', + * document.getElementById('my_app') + * ); + * + * Or: + * @example + * F2.AppHandlers.on( + * _token, + * 'appRender.myNamespace', + * document.getElementById('my_app') + * ); + **/ + /** + * Allows Container Developer to add listener method that will be triggered when a specific event occurs. + * @method on + * @chainable + * @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}. + * @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. The namespace is useful for removal + * purposes. At this time it does not affect when an event is fired. Complete list of event keys available in + * {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. + * @params {Function} listener A function that will be triggered when a specific event occurs. For detailed argument definition refer to {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. + * @example + * var _token = F2.AppHandlers.getToken(); + * F2.AppHandlers.on( + * _token, + * 'appRenderBefore' + * function() { F2.log('before app rendered!'); } + * ); + * + * Or: + * @example + * F2.AppHandlers.on( + * _token, + * 'appRenderBefore.myNamespace', + * function() { F2.log('before app rendered!'); } + * ); + **/ + on: function(token, eventKey, func_or_element) + { + var sNamespace = null; + + if(!eventKey) + { + throw ('eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.'); + } + + // we need to check the key for a namespace + if(eventKey.indexOf('.') > -1) + { + var arData = eventKey.split('.'); + eventKey = arData[0]; + sNamespace = arData[1]; + } + + if(_handlerCollection && _handlerCollection[eventKey]) + { + _handlerCollection[eventKey].push( + _createHandler( + token, + sNamespace, + func_or_element, + (eventKey == 'appRender') + ) + ); + } + else + { + throw ('Invalid EventKey passed. Check your inputs and try again.'); + } + + return this; + }, + /** + * Allows Container Developer to remove listener methods for specific events + * @method off + * @chainable + * @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}. + * @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. If no namespace is provided all + * listeners for the specified event type will be removed. + * Complete list available in {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}. + * @example + * var _token = F2.AppHandlers.getToken(); + * F2.AppHandlers.off(_token,'appRenderBefore'); + * + **/ + off: function(token, eventKey) + { + var sNamespace = null; + + if(!eventKey) + { + throw ('eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.'); + } + + // we need to check the key for a namespace + if(eventKey.indexOf('.') > -1) + { + var arData = eventKey.split('.'); + eventKey = arData[0]; + sNamespace = arData[1]; + } + + if(_handlerCollection && _handlerCollection[eventKey]) + { + _removeHandler( + token, + eventKey, + sNamespace + ); + } + else + { + throw ('Invalid EventKey passed. Check your inputs and try again.'); + } + + return this; + } + }; +})()); + +F2.extend('Constants', { + /** + * A convenient collection of all available appHandler events. + * @class F2.Constants.AppHandlers + **/ + AppHandlers: (function() + { + return { + /** + * Equivalent to `appCreateRoot`. Identifies the create root method for use in AppHandlers.on/off. + * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the + * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} ) + * @property APP_CREATE_ROOT + * @type string + * @static + * @final + * @example + * var _token = F2.AppHandlers.getToken(); + * F2.AppHandlers.on( + * _token, + * F2.Constants.AppHandlers.APP_CREATE_ROOT, + * function(appConfig) + * { + * // If you want to create a custom root. By default F2 uses the app's outermost HTML element. + * // the app's html is not available until after the manifest is retrieved so this logic occurs in F2.Constants.AppHandlers.APP_RENDER + * appConfig.root = jQuery('
                              ').get(0); + * } + * ); + */ + APP_CREATE_ROOT: 'appCreateRoot', + /** + * Equivalent to `appRenderBefore`. Identifies the before app render method for use in AppHandlers.on/off. + * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the + * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} ) + * @property APP_RENDER_BEFORE + * @type string + * @static + * @final + * @example + * var _token = F2.AppHandlers.getToken(); + * F2.AppHandlers.on( + * _token, + * F2.Constants.AppHandlers.APP_RENDER_BEFORE, + * function(appConfig) + * { + * F2.log(appConfig); + * } + * ); + */ + APP_RENDER_BEFORE: 'appRenderBefore', + /** + * Equivalent to `appRender`. Identifies the app render method for use in AppHandlers.on/off. + * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the + * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}}, [appHtml](../../app-development.html#app-design) ) + * @property APP_RENDER + * @type string + * @static + * @final + * @example + * var _token = F2.AppHandlers.getToken(); + * F2.AppHandlers.on( + * _token, + * F2.Constants.AppHandlers.APP_RENDER, + * function(appConfig, appHtml) + * { + * var $root = null; + * + * // if no app root is defined use the app's outer most node + * if(!F2.isNativeDOMNode(appConfig.root)) + * { + * appConfig.root = jQuery(appHtml).get(0); + * // get a handle on the root in jQuery + * $root = jQuery(appConfig.root); + * } + * else + * { + * // get a handle on the root in jQuery + * $root = jQuery(appConfig.root); + * + * // append the app html to the root + * $root.append(appHtml); + * } + * + * // append the root to the body by default. + * jQuery('body').append($root); + * } + * ); + */ + APP_RENDER: 'appRender', + /** + * Equivalent to `appRenderAfter`. Identifies the after app render method for use in AppHandlers.on/off. + * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the + * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} ) + * @property APP_RENDER_AFTER + * @type string + * @static + * @final + * @example + * var _token = F2.AppHandlers.getToken(); + * F2.AppHandlers.on( + * _token, + * F2.Constants.AppHandlers.APP_RENDER_AFTER, + * function(appConfig) + * { + * F2.log(appConfig); + * } + * ); + */ + APP_RENDER_AFTER: 'appRenderAfter', + /** + * Equivalent to `appDestroyBefore`. Identifies the before app destroy method for use in AppHandlers.on/off. + * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the + * following argument(s): ( appInstance ) + * @property APP_DESTROY_BEFORE + * @type string + * @static + * @final + * @example + * var _token = F2.AppHandlers.getToken(); + * F2.AppHandlers.on( + * _token, + * F2.Constants.AppHandlers.APP_DESTROY_BEFORE, + * function(appInstance) + * { + * F2.log(appInstance); + * } + * ); + */ + APP_DESTROY_BEFORE: 'appDestroyBefore', + /** + * Equivalent to `appDestroy`. Identifies the app destroy method for use in AppHandlers.on/off. + * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the + * following argument(s): ( appInstance ) + * @property APP_DESTROY + * @type string + * @static + * @final + * @example + * var _token = F2.AppHandlers.getToken(); + * F2.AppHandlers.on( + * _token, + * F2.Constants.AppHandlers.APP_DESTROY, + * function(appInstance) + * { + * // call the apps destroy method, if it has one + * if(appInstance && appInstance.app && appInstance.app.destroy && typeof(appInstance.app.destroy) == 'function') + * { + * appInstance.app.destroy(); + * } + * else if(appInstance && appInstance.app && appInstance.app.destroy) + * { + * F2.log(appInstance.config.appId + ' has a destroy property, but destroy is not of type function and as such will not be executed.'); + * } + * + * // fade out and remove the root + * jQuery(appInstance.config.root).fadeOut(500, function() { + * jQuery(this).remove(); + * }); + * } + * ); + */ + APP_DESTROY: 'appDestroy', + /** + * Equivalent to `appDestroyAfter`. Identifies the after app destroy method for use in AppHandlers.on/off. + * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the + * following argument(s): ( appInstance ) + * @property APP_DESTROY_AFTER + * @type string + * @static + * @final + * @example + * var _token = F2.AppHandlers.getToken(); + * F2.AppHandlers.on( + * _token, + * F2.Constants.AppHandlers.APP_DESTROY_AFTER, + * function(appInstance) + * { + * F2.log(appInstance); + * } + * ); + */ + APP_DESTROY_AFTER: 'appDestroyAfter', + /** + * Equivalent to `appScriptLoadFailed`. Identifies the app script load failed method for use in AppHandlers.on/off. + * When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the + * following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}}, scriptInfo ) + * @property APP_SCRIPT_LOAD_FAILED + * @type string + * @static + * @final + * @example + * var _token = F2.AppHandlers.getToken(); + * F2.AppHandlers.on( + * _token, + * F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED, + * function(appConfig, scriptInfo) + * { + * F2.log(appConfig.appId); + * } + * ); + */ + APP_SCRIPT_LOAD_FAILED: 'appScriptLoadFailed' + }; + })() +}); +/** + * Class stubs for documentation purposes + * @main F2 + */ +F2.extend('', { + /** + * The App Class is an optional class that can be namespaced onto the + * {{#crossLink "F2\Apps"}}{{/crossLink}} namespace. The + * [F2 Docs](../../app-development.html#app-class) + * has more information on the usage of the App Class. + * @class F2.App + * @constructor + * @param {F2.AppConfig} appConfig The F2.AppConfig object for the app + * @param {F2.AppManifest.AppContent} appContent The F2.AppManifest.AppContent + * object + * @param {Element} root The root DOM Element for the app + */ + App: function(appConfig, appContent, root) { + return { + /** + * An optional init function that will automatically be called when + * F2.{{#crossLink "F2\registerApps"}}{{/crossLink}} is called. + * @method init + * @optional + */ + init:function() {} + }; + }, + /** + * The AppConfig object represents an app's meta data + * @class F2.AppConfig + */ + AppConfig: { + /** + * The unique ID of the app. More information can be found + * [here](../../app-development.html#f2-appid) + * @property appId + * @type string + * @required + */ + appId: '', + /** + * An object that represents the context of an app + * @property context + * @type object + */ + context: {}, + /** + * True if the app should be requested in a single request with other apps. + * @property enableBatchRequests + * @type bool + * @default false + */ + enableBatchRequests: false, + /** + * The height of the app. The initial height will be pulled from + * the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object, but later + * modified by calling + * F2.UI.{{#crossLink "F2.UI/updateHeight"}}{{/crossLink}}. This is used + * for secure apps to be able to set the initial height of the iframe. + * @property height + * @type int + */ + height: 0, + /** + * The unique runtime ID of the app. + * + * **This property is populated during the + * F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process** + * @property instanceId + * @type string + */ + instanceId: '', + /** + * True if the app will be loaded in an iframe. This property + * will be true if the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object + * sets isSecure = true. It will also be true if the + * [container](../../container-development.html) has made the decision to + * run apps in iframes. + * @property isSecure + * @type bool + * @default false + */ + isSecure: false, + /** + * The url to retrieve the {{#crossLink "F2.AppManifest"}}{{/crossLink}} + * object. + * @property manifestUrl + * @type string + * @required + */ + manifestUrl: '', + /** + * The recommended maximum width in pixels that this app should be run. + * **It is up to the [container](../../container-development.html) to + * implement the logic to prevent an app from being run when the maxWidth + * requirements are not met.** + * @property maxWidth + * @type int + */ + maxWidth: 0, + /** + * The recommended minimum grid size that this app should be run. This + * value corresponds to the 12-grid system that is used by the + * [container](../../container-development.html). This property should be + * set by apps that require a certain number of columns in their layout. + * @property minGridSize + * @type int + * @default 4 + */ + minGridSize: 4, + /** + * The recommended minimum width in pixels that this app should be run. **It + * is up to the [container](../../container-development.html) to implement + * the logic to prevent an app from being run when the minWidth requirements + * are not met. + * @property minWidth + * @type int + * @default 300 + */ + minWidth: 300, + /** + * The name of the app + * @property name + * @type string + * @required + */ + name: '', + /** + * The root DOM element that contains the app + * + * **This property is populated during the + * F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process** + * @property root + * @type Element + */ + root: undefined, + /** + * The instance of F2.UI providing easy access to F2.UI methods + * + * **This property is populated during the + * F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process** + * @property ui + * @type F2.UI + */ + ui: undefined, + /** + * The views that this app supports. Available views + * are defined in {{#crossLink "F2.Constants.Views"}}{{/crossLink}}. The + * presence of a view can be checked via + * F2.{{#crossLink "F2/inArray"}}{{/crossLink}}: + * + * F2.inArray(F2.Constants.Views.SETTINGS, app.views) + * + * @property views + * @type Array + */ + views: [] + }, + /** + * The assets needed to render an app on the page + * @class F2.AppManifest + */ + AppManifest: { + /** + * The array of {{#crossLink "F2.AppManifest.AppContent"}}{{/crossLink}} + * objects + * @property apps + * @type Array + * @required + */ + apps: [], + /** + * Any inline javascript tha should initially be run + * @property inlineScripts + * @type Array + * @optional + */ + inlineScripts: [], + /** + * Urls to javascript files required by the app + * @property scripts + * @type Array + * @optional + */ + scripts: [], + /** + * Urls to CSS files required by the app + * @property styles + * @type Array + * @optional + */ + styles: [] + }, + /** + * The AppContent object + * @class F2.AppManifest.AppContent + **/ + AppContent: { + /** + * Arbitrary data to be passed along with the app + * @property data + * @type object + * @optional + */ + data: {}, + /** + * The string of HTML representing the app + * @property html + * @type string + * @required + */ + html: '', + /** + * A status message + * @property status + * @type string + * @optional + */ + status: '' + }, + /** + * An object containing configuration information for the + * [container](../../container-development.html) + * @class F2.ContainerConfig + */ + ContainerConfig: { + /** + * Allows the [container](../../container-development.html) to override how + * an app's html is inserted into the page. The function should accept an + * {{#crossLink "F2.AppConfig"}}{{/crossLink}} object and also a string of + * html + * @method afterAppRender + * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 + * @param {F2.AppConfig} appConfig The F2.AppConfig object + * @param {string} html The string of html representing the app + * @return {Element} The DOM Element surrounding the app + */ + afterAppRender: function(appConfig, html) {}, + /** + * Allows the [container](../../container-development.html) to wrap an app + * in extra html. The function should accept an + * {{#crossLink "F2.AppConfig"}}{{/crossLink}} object and also a string of + * html. The extra html can provide links to edit app settings and remove an + * app from the container. See + * {{#crossLink "F2.Constants.Css"}}{{/crossLink}} for CSS classes that + * should be applied to elements. + * @method appRender + * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 + * @param {F2.AppConfig} appConfig The F2.AppConfig object + * @param {string} html The string of html representing the app + */ + appRender: function(appConfig, html) {}, + /** + * Allows the container to render html for an app before the AppManifest for + * an app has loaded. This can be useful if the design calls for loading + * icons to appear for each app before each app is loaded and rendered to + * the page. + * @method beforeAppRender + * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 + * @param {F2.AppConfig} appConfig The F2.AppConfig object + * @return {Element} The DOM Element surrounding the app + */ + beforeAppRender: function(appConfig) {}, + /** + * True to enable debug mode in F2.js. Adds additional logging, resource cache busting, etc. + * @property debugMode + * @type bool + * @default false + */ + debugMode: false, + /** + * Milliseconds before F2 fires callback on script resource load errors. Due to issue with the way Internet Explorer attaches load events to script elements, the error event doesn't fire. + * @property scriptErrorTimeout + * @type milliseconds + * @default 7000 (7 seconds) + */ + scriptErrorTimeout: 7000, + /** + * Tells the container that it is currently running within + * a secure app page + * @property isSecureAppPage + * @type bool + */ + isSecureAppPage: false, + /** + * Allows the container to specify which page is used when + * loading a secure app. The page must reside on a different domain than the + * container + * @property secureAppPagePath + * @type string + * @for F2.ContainerConfig + */ + secureAppPagePath: '', + /** + * Specifies what views a container will provide buttons + * or links to. Generally, the views will be switched via buttons or links + * in the app's header. + * @property supportedViews + * @type Array + * @required + */ + supportedViews: [], + /** + * An object containing configuration defaults for F2.UI + * @class F2.ContainerConfig.UI + */ + UI: { + /** + * An object containing configuration defaults for the + * F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} and + * F2.UI.{{#crossLink "F2.UI/hideMask"}}{{/crossLink}} methods. + * @class F2.ContainerConfig.UI.Mask + */ + Mask: { + /** + * The backround color of the overlay + * @property backgroundColor + * @type string + * @default #FFF + */ + backgroundColor: '#FFF', + /** + * The path to the loading icon + * @property loadingIcon + * @type string + */ + loadingIcon: '', + /** + * The opacity of the background overlay + * @property opacity + * @type int + * @default 0.6 + */ + opacity: 0.6, + /** + * Do not use inline styles for mask functinality. Instead classes will + * be applied to the elements and it is up to the container provider to + * implement the class definitions. + * @property useClasses + * @type bool + * @default false + */ + useClasses: false, + /** + * The z-index to use for the overlay + * @property zIndex + * @type int + * @default 2 + */ + zIndex: 2 + } + }, + /** + * Allows the container to fully override how the AppManifest request is + * made inside of F2. + * + * @method xhr + * @param {string} url The manifest url + * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} + * objects + * @param {function} success The function to be called if the request + * succeeds + * @param {function} error The function to be called if the request fails + * @param {function} complete The function to be called when the request + * finishes (after success and error callbacks have been executed) + * @return {XMLHttpRequest} The XMLHttpRequest object (or an object that has + * an `abort` function (such as the jqXHR object in jQuery) to abort the + * request) + * + * @example + * F2.init({ + * xhr: function(url, appConfigs, success, error, complete) { + * $.ajax({ + * url: url, + * type: 'POST', + * data: { + * params: F2.stringify(appConfigs, F2.appConfigReplacer) + * }, + * jsonp: false, // do not put 'callback=' in the query string + * jsonpCallback: F2.Constants.JSONP_CALLBACK + appConfigs[0].appId, // Unique function name + * dataType: 'json', + * success: function(appManifest) { + * // custom success logic + * success(appManifest); // fire success callback + * }, + * error: function() { + * // custom error logic + * error(); // fire error callback + * }, + * complete: function() { + * // custom complete logic + * complete(); // fire complete callback + * } + * }); + * } + * }); + * + * @for F2.ContainerConfig + */ + //xhr: function(url, appConfigs, success, error, complete) {}, + /** + * Allows the container to override individual parts of the AppManifest + * request. See properties and methods with the `xhr.` prefix. + * @property xhr + * @type Object + * + * @example + * F2.init({ + * xhr: { + * url: function(url, appConfigs) { + * return 'http://example.com/proxy.php?url=' + encocdeURIComponent(url); + * } + * } + * }); + */ + xhr: { + /** + * Allows the container to override the request data type (JSON or JSONP) + * that is used for the request + * @method xhr.dataType + * @param {string} url The manifest url + * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} + * objects + * @return {string} The request data type that should be used + * + * @example + * F2.init({ + * xhr: { + * dataType: function(url) { + * return F2.isLocalRequest(url) ? 'json' : 'jsonp'; + * }, + * type: function(url) { + * return F2.isLocalRequest(url) ? 'POST' : 'GET'; + * } + * } + * }); + */ + dataType: function(url, appConfigs) {}, + /** + * Allows the container to override the request method that is used (just + * like the `type` parameter to `jQuery.ajax()`. + * @method xhr.type + * @param {string} url The manifest url + * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} + * objects + * @return {string} The request method that should be used + * + * @example + * F2.init({ + * xhr: { + * dataType: function(url) { + * return F2.isLocalRequest(url) ? 'json' : 'jsonp'; + * }, + * type: function(url) { + * return F2.isLocalRequest(url) ? 'POST' : 'GET'; + * } + * } + * }); + */ + type: function(url, appConfigs) {}, + /** + * Allows the container to override the url that is used to request an + * app's F2.{{#crossLink "F2.AppManifest"}}{{/crossLink}} + * @method xhr.url + * @param {string} url The manifest url + * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} + * objects + * @return {string} The url that should be used for the request + * + * @example + * F2.init({ + * xhr: { + * url: function(url, appConfigs) { + * return 'http://example.com/proxy.php?url=' + encocdeURIComponent(url); + * } + * } + * }); + */ + url: function(url, appConfigs) {} + } + } +}); +/** + * Constants used throughout the Open Financial Framework + * @class F2.Constants + * @static + */ +F2.extend('Constants', { + /** + * CSS class constants + * @class F2.Constants.Css + */ + Css: (function() { + + /** @private */ + var _PREFIX = 'f2-'; + + return { + /** + * The APP class should be applied to the DOM Element that surrounds the + * entire app, including any extra html that surrounds the APP\_CONTAINER + * that is inserted by the container. See the + * {{#crossLink "F2.ContainerConfig"}}{{/crossLink}} object. + * @property APP + * @type string + * @static + * @final + */ + APP: _PREFIX + 'app', + /** + * The APP\_CONTAINER class should be applied to the outermost DOM Element + * of the app. + * @property APP_CONTAINER + * @type string + * @static + * @final + */ + APP_CONTAINER: _PREFIX + 'app-container', + /** + * The APP\_TITLE class should be applied to the DOM Element that contains + * the title for an app. If this class is not present, then + * F2.UI.{{#crossLink "F2.UI/setTitle"}}{{/crossLink}} will not function. + * @property APP_TITLE + * @type string + * @static + * @final + */ + APP_TITLE: _PREFIX + 'app-title', + /** + * The APP\_VIEW class should be applied to the DOM Element that contains + * a view for an app. The DOM Element should also have a + * {{#crossLink "F2.Constants.Views"}}{{/crossLink}}.DATA_ATTRIBUTE + * attribute that specifies which + * {{#crossLink "F2.Constants.Views"}}{{/crossLink}} it is. + * @property APP_VIEW + * @type string + * @static + * @final + */ + APP_VIEW: _PREFIX + 'app-view', + /** + * APP\_VIEW\_TRIGGER class should be applied to the DOM Elements that + * trigger an + * {{#crossLink "F2.Constants.Events"}}{{/crossLink}}.APP\_VIEW\_CHANGE + * event. The DOM Element should also have a + * {{#crossLink "F2.Constants.Views"}}{{/crossLink}}.DATA_ATTRIBUTE + * attribute that specifies which + * {{#crossLink "F2.Constants.Views"}}{{/crossLink}} it will trigger. + * @property APP_VIEW_TRIGGER + * @type string + * @static + * @final + */ + APP_VIEW_TRIGGER: _PREFIX + 'app-view-trigger', + /** + * The MASK class is applied to the overlay element that is created + * when the F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} method is + * fired. + * @property MASK + * @type string + * @static + * @final + */ + MASK: _PREFIX + 'mask', + /** + * The MASK_CONTAINER class is applied to the Element that is passed into + * the F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} method. + * @property MASK_CONTAINER + * @type string + * @static + * @final + */ + MASK_CONTAINER: _PREFIX + 'mask-container' + }; + })(), + + /** + * Events constants + * @class F2.Constants.Events + */ + Events: (function() { + /** @private */ + var _APP_EVENT_PREFIX = 'App.'; + /** @private */ + var _CONTAINER_EVENT_PREFIX = 'Container.'; + + return { + /** + * The APP\_SYMBOL\_CHANGE event is fired when the symbol is changed in an + * app. It is up to the app developer to fire this event. + * Returns an object with the symbol and company name: + * + * { symbol: 'MSFT', name: 'Microsoft Corp (NASDAQ)' } + * + * @property APP_SYMBOL_CHANGE + * @type string + * @static + * @final + */ + APP_SYMBOL_CHANGE: _APP_EVENT_PREFIX + 'symbolChange', + /** + * The APP\_WIDTH\_CHANGE event will be fired by the container when the + * width of an app is changed. The app's instanceId should be concatenated + * to this constant. + * Returns an object with the gridSize and width in pixels: + * + * { gridSize:8, width:620 } + * + * @property APP_WIDTH_CHANGE + * @type string + * @static + * @final + */ + APP_WIDTH_CHANGE: _APP_EVENT_PREFIX + 'widthChange.', + /** + * The CONTAINER\_SYMBOL\_CHANGE event is fired when the symbol is changed + * at the container level. This event should only be fired by the + * container or container provider. + * Returns an object with the symbol and company name: + * + * { symbol: 'MSFT', name: 'Microsoft Corp (NASDAQ)' } + * + * @property CONTAINER_SYMBOL_CHANGE + * @type string + * @static + * @final + */ + CONTAINER_SYMBOL_CHANGE: _CONTAINER_EVENT_PREFIX + 'symbolChange', + /** + * The CONTAINER\_WIDTH\_CHANGE event will be fired by the container when + * the width of the container has changed. + * @property CONTAINER_WIDTH_CHANGE + * @type string + * @static + * @final + */ + CONTAINER_WIDTH_CHANGE: _CONTAINER_EVENT_PREFIX + 'widthChange' + }; + })(), + + JSONP_CALLBACK: 'F2_jsonpCallback_', + + /** + * Constants for use with cross-domain sockets + * @class F2.Constants.Sockets + * @protected + */ + Sockets: { + /** + * The EVENT message is sent whenever + * F2.Events.{{#crossLink "F2.Events/emit"}}{{/crossLink}} is fired + * @property EVENT + * @type string + * @static + * @final + */ + EVENT: '__event__', + /** + * The LOAD message is sent when an iframe socket initially loads. + * Returns a JSON string that represents: + * + * [ App, AppManifest] + * + * @property LOAD + * @type string + * @static + * @final + */ + LOAD: '__socketLoad__', + /** + * The RPC message is sent when a method is passed up from within a secure + * app page. + * @property RPC + * @type string + * @static + * @final + */ + RPC: '__rpc__', + /** + * The RPC\_CALLBACK message is sent when a call back from an RPC method is + * fired. + * @property RPC_CALLBACK + * @type string + * @static + * @final + */ + RPC_CALLBACK: '__rpcCallback__', + /** + * The UI\_RPC message is sent when a UI method called. + * @property UI_RPC + * @type string + * @static + * @final + */ + UI_RPC: '__uiRpc__' + }, + + /** + * The available view types to apps. The view should be specified by applying + * the {{#crossLink "F2.Constants.Css"}}{{/crossLink}}.APP\_VIEW class to the + * containing DOM Element. A DATA\_ATTRIBUTE attribute should be added to the + * Element as well which defines what view type is represented. + * The `hide` class can be applied to views that should be hidden by default. + * @class F2.Constants.Views + */ + Views: { + /** + * The DATA_ATTRIBUTE should be placed on the DOM Element that contains the + * view. + * @property DATA_ATTRIBUTE + * @type string + * @static + * @final + */ + DATA_ATTRIBUTE: 'data-f2-view', + /** + * The ABOUT view gives details about the app. + * @property ABOUT + * @type string + * @static + * @final + */ + ABOUT: 'about', + /** + * The HELP view provides users with help information for using an app. + * @property HELP + * @type string + * @static + * @final + */ + HELP: 'help', + /** + * The HOME view is the main view for an app. This view should always + * be provided by an app. + * @property HOME + * @type string + * @static + * @final + */ + HOME: 'home', + /** + * The REMOVE view is a special view that handles the removal of an app + * from the container. + * @property REMOVE + * @type string + * @static + * @final + */ + REMOVE: 'remove', + /** + * The SETTINGS view provides users the ability to modify advanced settings + * for an app. + * @property SETTINGS + * @type string + * @static + * @final + */ + SETTINGS: 'settings' + } +}); +/** + * Handles [Context](../../app-development.html#context) passing from + * containers to apps and apps to apps. + * @class F2.Events + */ +F2.extend('Events', (function() { + // init EventEmitter + var _events = new EventEmitter2({ + wildcard:true + }); + + // unlimited listeners, set to > 0 for debugging + _events.setMaxListeners(0); + + return { + /** + * Same as F2.Events.emit except that it will not send the event + * to all sockets. + * @method _socketEmit + * @private + * @param {string} event The event name + * @param {object} [arg]* The arguments to be passed + */ + _socketEmit: function() { + return EventEmitter2.prototype.emit.apply(_events, [].slice.call(arguments)); + }, + /** + * Execute each of the listeners that may be listening for the specified + * event name in order with the list of arguments. + * @method emit + * @param {string} event The event name + * @param {object} [arg]* The arguments to be passed + */ + emit: function() { + F2.Rpc.broadcast(F2.Constants.Sockets.EVENT, [].slice.call(arguments)); + return EventEmitter2.prototype.emit.apply(_events, [].slice.call(arguments)); + }, + /** + * Adds a listener that will execute n times for the event before being + * removed. The listener is invoked only the first time the event is + * fired, after which it is removed. + * @method many + * @param {string} event The event name + * @param {int} timesToListen The number of times to execute the event + * before being removed + * @param {function} listener The function to be fired when the event is + * emitted + */ + many: function(event, timesToListen, listener) { + return _events.many(event, timesToListen, listener); + }, + /** + * Remove a listener for the specified event. + * @method off + * @param {string} event The event name + * @param {function} listener The function that will be removed + */ + off: function(event, listener) { + return _events.off(event, listener); + }, + /** + * Adds a listener for the specified event + * @method on + * @param {string} event The event name + * @param {function} listener The function to be fired when the event is + * emitted + */ + on: function(event, listener){ + return _events.on(event, listener); + }, + /** + * Adds a one time listener for the event. The listener is invoked only + * the first time the event is fired, after which it is removed. + * @method once + * @param {string} event The event name + * @param {function} listener The function to be fired when the event is + * emitted + */ + once: function(event, listener) { + return _events.once(event, listener); + } + }; +})()); +/** + * Handles socket communication between the container and secure apps + * @class F2.Rpc + */ +F2.extend('Rpc', (function(){ + var _callbacks = {}; + var _secureAppPagePath = ''; + var _apps = {}; + var _rEvents = new RegExp('^' + F2.Constants.Sockets.EVENT); + var _rRpc = new RegExp('^' + F2.Constants.Sockets.RPC); + var _rRpcCallback = new RegExp('^' + F2.Constants.Sockets.RPC_CALLBACK); + var _rSocketLoad = new RegExp('^' + F2.Constants.Sockets.LOAD); + var _rUiCall = new RegExp('^' + F2.Constants.Sockets.UI_RPC); + + /** + * Creates a socket connection from the app to the container using + * easyXDM. + * @method _createAppToContainerSocket + * @private + */ + var _createAppToContainerSocket = function() { + + var appConfig; // socket closure + var isLoaded = false; + // its possible for messages to be received before the socket load event has + // happened. We'll save off these messages and replay them once the socket + // is ready + var messagePlayback = []; + + var socket = new easyXDM.Socket({ + onMessage: function(message, origin){ + + // handle Socket Load + if (!isLoaded && _rSocketLoad.test(message)) { + message = message.replace(_rSocketLoad, ''); + var appParts = F2.parse(message); + + // make sure we have the AppConfig and AppManifest + if (appParts.length == 2) { + appConfig = appParts[0]; + + // save socket + _apps[appConfig.instanceId] = { + config:appConfig, + socket:socket + }; + + // register app + F2.registerApps([appConfig], [appParts[1]]); + + // socket message playback + jQuery.each(messagePlayback, function(i, e) { + _onMessage(appConfig, message, origin); + }); + + isLoaded = true; + } + } else if (isLoaded) { + // pass everyting else to _onMessage + _onMessage(appConfig, message, origin); + } else { + //F2.log('socket not ready, queuing message', message); + messagePlayback.push(message); + } + } + }); + }; + + /** + * Creates a socket connection from the container to the app using + * easyXDM. + * @method _createContainerToAppSocket + * @private + * @param {appConfig} appConfig The F2.AppConfig object + * @param {F2.AppManifest} appManifest The F2.AppManifest object + */ + var _createContainerToAppSocket = function(appConfig, appManifest) { + + var container = jQuery(appConfig.root); + + if (!container.is('.' + F2.Constants.Css.APP_CONTAINER)) { + container.find('.' + F2.Constants.Css.APP_CONTAINER); + } + + if (!container.length) { + F2.log('Unable to locate app in order to establish secure connection.'); + return; + } + + var iframeProps = { + scrolling:'no', + style:{ + width:'100%' + } + }; + + if (appConfig.height) { + iframeProps.style.height = appConfig.height + 'px'; + } + + var socket = new easyXDM.Socket({ + remote: _secureAppPagePath, + container: container.get(0), + props:iframeProps, + onMessage: function(message, origin) { + // pass everything to _onMessage + _onMessage(appConfig, message, origin); + }, + onReady: function() { + socket.postMessage(F2.Constants.Sockets.LOAD + F2.stringify([appConfig, appManifest], F2.appConfigReplacer)); + } + }); + + return socket; + }; + + /** + * @method _createRpcCallback + * @private + * @param {string} instanceId The app's Instance ID + * @param {function} callbackId The callback ID + * @return {function} A function to make the RPC call + */ + var _createRpcCallback = function(instanceId, callbackId) { + return function() { + F2.Rpc.call( + instanceId, + F2.Constants.Sockets.RPC_CALLBACK, + callbackId, + [].slice.call(arguments).slice(2) + ); + }; + }; + + /** + * Handles messages that come across the sockets + * @method _onMessage + * @private + * @param {F2.AppConfig} appConfig The F2.AppConfig object + * @param {string} message The socket message + * @param {string} origin The originator + */ + var _onMessage = function(appConfig, message, origin) { + + var obj, func; + + function parseFunction(parent, functionName) { + var path = String(functionName).split('.'); + for (var i = 0; i < path.length; i++) { + if (parent[path[i]] === undefined) { + parent = undefined; + break; + } + parent = parent[path[i]]; + } + return parent; + } + + function parseMessage(regEx, message, instanceId) { + var o = F2.parse(message.replace(regEx, '')); + + // if obj.callbacks + // for each callback + // for each params + // if callback matches param + // replace param with _createRpcCallback(app.instanceId, callback) + if (o.params && o.params.length && o.callbacks && o.callbacks.length) { + jQuery.each(o.callbacks, function(i, c) { + jQuery.each(o.params, function(i, p) { + if (c == p) { + o.params[i] = _createRpcCallback(instanceId, c); + } + }); + }); + } + + return o; + } + + // handle UI Call + if (_rUiCall.test(message)) { + obj = parseMessage(_rUiCall, message, appConfig.instanceId); + func = parseFunction(appConfig.ui, obj.functionName); + // if we found the function, call it + if (func !== undefined) { + func.apply(appConfig.ui, obj.params); + } else { + F2.log('Unable to locate UI RPC function: ' + obj.functionName); + } + + // handle RPC + } else if (_rRpc.test(message)) { + obj = parseMessage(_rRpc, message, appConfig.instanceId); + func = parseFunction(window, obj.functionName); + if (func !== undefined) { + func.apply(func, obj.params); + } else { + F2.log('Unable to locate RPC function: ' + obj.functionName); + } + + // handle RPC Callback + } else if (_rRpcCallback.test(message)) { + obj = parseMessage(_rRpcCallback, message, appConfig.instanceId); + if (_callbacks[obj.functionName] !== undefined) { + _callbacks[obj.functionName].apply(_callbacks[obj.functionName], obj.params); + delete _callbacks[obj.functionName]; + } + + // handle Events + } else if (_rEvents.test(message)) { + obj = parseMessage(_rEvents, message, appConfig.instanceId); + F2.Events._socketEmit.apply(F2.Events, obj); + } + }; + + /** + * Registers a callback function + * @method _registerCallback + * @private + * @param {function} callback The callback function + * @return {string} The callback ID + */ + var _registerCallback = function(callback) { + var callbackId = F2.guid(); + _callbacks[callbackId] = callback; + return callbackId; + }; + + return { + /** + * Broadcast an RPC function to all sockets + * @method broadcast + * @param {string} messageType The message type + * @param {Array} params The parameters to broadcast + */ + broadcast: function(messageType, params) { + // check valid messageType + var message = messageType + F2.stringify(params); + jQuery.each(_apps, function(i, a) { + a.socket.postMessage(message); + }); + }, + /** + * Calls a remote function + * @method call + * @param {string} instanceId The app's Instance ID + * @param {string} messageType The message type + * @param {string} functionName The name of the remote function + * @param {Array} params An array of parameters to pass to the remote + * function. Any functions found within the params will be treated as a + * callback function. + */ + call: function(instanceId, messageType, functionName, params) { + // loop through params and find functions and convert them to callbacks + var callbacks = []; + jQuery.each(params, function(i, e) { + if (typeof e === 'function') { + var cid = _registerCallback(e); + params[i] = cid; + callbacks.push(cid); + } + }); + // check valid messageType + _apps[instanceId].socket.postMessage( + messageType + F2.stringify({ + functionName:functionName, + params:params, + callbacks:callbacks + }) + ); + }, + + /** + * Init function which tells F2.Rpc whether it is running at the container- + * level or the app-level. This method is generally called by + * F2.{{#crossLink "F2/init"}}{{/crossLink}} + * @method init + * @param {string} [secureAppPagePath] The + * {{#crossLink "F2.ContainerConfig"}}{{/crossLink}}.secureAppPagePath + * property + */ + init: function(secureAppPagePath) { + _secureAppPagePath = secureAppPagePath; + if (!_secureAppPagePath) { + _createAppToContainerSocket(); + } + }, + + /** + * Determines whether the Instance ID is considered to be 'remote'. This is + * determined by checking if 1) the app has an open socket and 2) whether + * F2.Rpc is running inside of an iframe + * @method isRemote + * @param {string} instanceId The Instance ID + * @return {bool} True if there is an open socket + */ + isRemote: function(instanceId) { + return ( + // we have an app + _apps[instanceId] !== undefined && + // the app is secure + _apps[instanceId].config.isSecure && + // we can't access the iframe + jQuery(_apps[instanceId].config.root).find('iframe').length === 0 + ); + }, + + /** + * Creates a container-to-app or app-to-container socket for communication + * @method register + * @param {F2.AppConfig} [appConfig] The F2.AppConfig object + * @param {F2.AppManifest} [appManifest] The F2.AppManifest object + */ + register: function(appConfig, appManifest) { + if (!!appConfig && !!appManifest) { + _apps[appConfig.instanceId] = { + config:appConfig, + socket:_createContainerToAppSocket(appConfig, appManifest) + }; + } else { + F2.log('Unable to register socket connection. Please check container configuration.'); + } + } + }; +})()); +F2.extend('UI', (function(){ + + var _containerConfig; + + /** + * UI helper methods + * @class F2.UI + * @constructor + * @param {F2.AppConfig} appConfig The F2.AppConfig object + */ + var UI_Class = function(appConfig) { + + var _appConfig = appConfig; + var $root = jQuery(appConfig.root); + + var _updateHeight = function(height) { + height = height || jQuery(_appConfig.root).outerHeight(); + + if (F2.Rpc.isRemote(_appConfig.instanceId)) { + F2.Rpc.call( + _appConfig.instanceId, + F2.Constants.Sockets.UI_RPC, + 'updateHeight', + [ + height + ] + ); + } else { + _appConfig.height = height; + $root.find('iframe').height(_appConfig.height); + } + }; + + return { + /** + * Removes a overlay from an Element on the page + * @method hideMask + * @param {string|Element} selector The Element or selector to an Element + * that currently contains the loader + */ + hideMask: function(selector) { + F2.UI.hideMask(_appConfig.instanceId, selector); + }, + /** + * Helper methods for creating and using Modals + * @class F2.UI.Modals + * @for F2.UI + */ + Modals: (function(){ + + var _renderAlert = function(message) { + return [ + '' + ].join(''); + }; + + var _renderConfirm = function(message) { + return [ + '' + ].join(''); + }; + + return { + /** + * Display an alert message on the page + * @method alert + * @param {string} message The message to be displayed + * @param {function} [callback] The callback to be fired when the user + * closes the dialog + * @for F2.UI.Modals + */ + alert: function(message, callback) { + + if (!F2.isInit()) { + F2.log('F2.init() must be called before F2.UI.Modals.alert()'); + return; + } + + if (F2.Rpc.isRemote(_appConfig.instanceId)) { + F2.Rpc.call( + _appConfig.instanceId, + F2.Constants.Sockets.UI_RPC, + 'Modals.alert', + [].slice.call(arguments) + ); + } else { + // display the alert + jQuery(_renderAlert(message)) + .on('show', function() { + var modal = this; + jQuery(modal).find('.btn-primary').on('click', function() { + jQuery(modal).modal('hide').remove(); + (callback || jQuery.noop)(); + }); + }) + .modal({backdrop:true}); + } + }, + /** + * Display a confirm message on the page + * @method confirm + * @param {string} message The message to be displayed + * @param {function} okCallback The function that will be called when the OK + * button is pressed + * @param {function} cancelCallback The function that will be called when + * the Cancel button is pressed + * @for F2.UI.Modals + */ + confirm: function(message, okCallback, cancelCallback) { + + if (!F2.isInit()) { + F2.log('F2.init() must be called before F2.UI.Modals.confirm()'); + return; + } + + if (F2.Rpc.isRemote(_appConfig.instanceId)) { + F2.Rpc.call( + _appConfig.instanceId, + F2.Constants.Sockets.UI_RPC, + 'Modals.confirm', + [].slice.call(arguments) + ); + } else { + // display the alert + jQuery(_renderConfirm(message)) + .on('show', function() { + var modal = this; + + jQuery(modal).find('.btn-ok').on('click', function() { + jQuery(modal).modal('hide').remove(); + (okCallback || jQuery.noop)(); + }); + + jQuery(modal).find('.btn-cancel').on('click', function() { + jQuery(modal).modal('hide').remove(); + (cancelCallback || jQuery.noop)(); + }); + }) + .modal({backdrop:true}); + } + } + }; + })(), + /** + * Sets the title of the app as shown in the browser. Depending on the + * container HTML, this method may do nothing if the container has not been + * configured properly or else the container provider does not allow Title's + * to be set. + * @method setTitle + * @params {string} title The title of the app + * @for F2.UI + */ + setTitle: function(title) { + + if (F2.Rpc.isRemote(_appConfig.instanceId)) { + F2.Rpc.call( + _appConfig.instanceId, + F2.Constants.Sockets.UI_RPC, + 'setTitle', + [ + title + ] + ); + } else { + jQuery(_appConfig.root).find('.' + F2.Constants.Css.APP_TITLE).text(title); + } + }, + /** + * Display an ovarlay over an Element on the page + * @method showMask + * @param {string|Element} selector The Element or selector to an Element + * over which to display the loader + * @param {bool} showLoading Display a loading icon + */ + showMask: function(selector, showLoader) { + F2.UI.showMask(_appConfig.instanceId, selector, showLoader); + }, + /** + * For secure apps, this method updates the size of the iframe that + * contains the app. **Note: It is recommended that app developers call + * this method anytime Elements are added or removed from the DOM** + * @method updateHeight + * @params {int} height The height of the app + */ + updateHeight: _updateHeight, + /** + * Helper methods for creating and using Views + * @class F2.UI.Views + * @for F2.UI + */ + Views: (function(){ + + var _events = new EventEmitter2(); + var _rValidEvents = /change/i; + + // unlimited listeners, set to > 0 for debugging + _events.setMaxListeners(0); + + var _isValid = function(eventName) { + if (_rValidEvents.test(eventName)) { + return true; + } else { + F2.log('"' + eventName + '" is not a valid F2.UI.Views event name'); + return false; + } + }; + + return { + /** + * Change the current view for the app or add an event listener + * @method change + * @param {string|function} [input] If a string is passed in, the view + * will be changed for the app. If a function is passed in, a change + * event listener will be added. + * @for F2.UI.Views + */ + change: function(input) { + + if (typeof input === 'function') { + this.on('change', input); + } else if (typeof input === 'string') { + + if (_appConfig.isSecure && !F2.Rpc.isRemote(_appConfig.instanceId)) { + F2.Rpc.call( + _appConfig.instanceId, + F2.Constants.Sockets.UI_RPC, + 'Views.change', + [].slice.call(arguments) + ); + } else if (F2.inArray(input, _appConfig.views)) { + jQuery('.' + F2.Constants.Css.APP_VIEW, $root) + .addClass('hide') + .filter('[data-f2-view="' + input + '"]', $root) + .removeClass('hide'); + + _updateHeight(); + _events.emit('change', input); + } + } + }, + /** + * Removes a view event listener + * @method off + * @param {string} event The event name + * @param {function} listener The function that will be removed + * @for F2.UI.Views + */ + off: function(event, listener) { + if (_isValid(event)) { + _events.off(event, listener); + } + }, + /** + * Adds a view event listener + * @method on + * @param {string} event The event name + * @param {function} listener The function to be fired when the event is + * emitted + * @for F2.UI.Views + */ + on: function(event, listener) { + if (_isValid(event)) { + _events.on(event, listener); + } + } + }; + })() + }; + }; + + /** + * Removes a overlay from an Element on the page + * @method hideMask + * @static + * @param {string} instanceId The Instance ID of the app + * @param {string|Element} selector The Element or selector to an Element + * that currently contains the loader + * @for F2.UI + */ + UI_Class.hideMask = function(instanceId, selector) { + + if (!F2.isInit()) { + F2.log('F2.init() must be called before F2.UI.hideMask()'); + return; + } + + if (F2.Rpc.isRemote(instanceId) && !jQuery(selector).is('.' + F2.Constants.Css.APP)) { + F2.Rpc.call( + instanceId, + F2.Constants.Sockets.RPC, + 'F2.UI.hideMask', + [ + instanceId, + // must only pass the selector argument. if we pass an Element there + // will be F2.stringify() errors + jQuery(selector).selector + ] + ); + } else { + + var container = jQuery(selector); + container.find('> .' + F2.Constants.Css.MASK).remove(); + container.removeClass(F2.Constants.Css.MASK_CONTAINER); + + // if the element contains this data property, we need to reset static + // position + if (container.data(F2.Constants.Css.MASK_CONTAINER)) { + container.css({'position':'static'}); + } + } + }; + + /** + * + * @method init + * @static + * @param {F2.ContainerConfig} containerConfig The F2.ContainerConfig object + */ + UI_Class.init = function(containerConfig) { + _containerConfig = containerConfig; + + // set defaults + _containerConfig.UI = jQuery.extend(true, {}, F2.ContainerConfig.UI, _containerConfig.UI || {}); + }; + + /** + * Display an ovarlay over an Element on the page + * @method showMask + * @static + * @param {string} instanceId The Instance ID of the app + * @param {string|Element} selector The Element or selector to an Element + * over which to display the loader + * @param {bool} showLoading Display a loading icon + */ + UI_Class.showMask = function(instanceId, selector, showLoading) { + + if (!F2.isInit()) { + F2.log('F2.init() must be called before F2.UI.showMask()'); + return; + } + + if (F2.Rpc.isRemote(instanceId) && jQuery(selector).is('.' + F2.Constants.Css.APP)) { + F2.Rpc.call( + instanceId, + F2.Constants.Sockets.RPC, + 'F2.UI.showMask', + [ + instanceId, + // must only pass the selector argument. if we pass an Element there + // will be F2.stringify() errors + jQuery(selector).selector, + showLoading + ] + ); + } else { + + if (showLoading && !_containerConfig.UI.Mask.loadingIcon) { + F2.log('Unable to display loading icon. Please set F2.ContainerConfig.UI.Mask.loadingIcon when calling F2.init();'); + } + + var container = jQuery(selector).addClass(F2.Constants.Css.MASK_CONTAINER); + var mask = jQuery('
                              ') + .height('100%' /*container.outerHeight()*/) + .width('100%' /*container.outerWidth()*/) + .addClass(F2.Constants.Css.MASK); + + // set inline styles if useClasses is false + if (!_containerConfig.UI.Mask.useClasses) { + mask.css({ + 'background-color':_containerConfig.UI.Mask.backgroundColor, + 'background-image': !!_containerConfig.UI.Mask.loadingIcon ? ('url(' + _containerConfig.UI.Mask.loadingIcon + ')') : '', + 'background-position':'50% 50%', + 'background-repeat':'no-repeat', + 'display':'block', + 'left':0, + 'min-height':30, + 'padding':0, + 'position':'absolute', + 'top':0, + 'z-index':_containerConfig.UI.Mask.zIndex, + + 'filter':'alpha(opacity=' + (_containerConfig.UI.Mask.opacity * 100) + ')', + 'opacity':_containerConfig.UI.Mask.opacity + }); + } + + // only set the position if the container is currently static + if (container.css('position') === 'static') { + container.css({'position':'relative'}); + // setting this data property tells hideMask to set the position + // back to static + container.data(F2.Constants.Css.MASK_CONTAINER, true); + } + + // add the mask to the container + container.append(mask); + } + }; + + return UI_Class; +})()); +/** + * Root namespace of the F2 SDK + * @module f2 + * @class F2 + */ +F2.extend('', (function(){ + + var _apps = {}; + var _config = false; + var _bUsesAppHandlers = false; + var _sAppHandlerToken = F2.AppHandlers.__f2GetToken(); + + /** + * Appends the app's html to the DOM + * @method _afterAppRender + * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 + * @private + * @param {F2.AppConfig} appConfig The F2.AppConfig object + * @param {string} html The string of html + * @return {Element} The DOM Element that contains the app + */ + var _afterAppRender = function(appConfig, html) { + + var handler = _config.afterAppRender || function(appConfig, html) { + return jQuery(html).appendTo('body'); + }; + var appContainer = handler(appConfig, html); + + if (!!_config.afterAppRender && !appContainer) { + F2.log('F2.ContainerConfig.afterAppRender() must return the DOM Element that contains the app'); + return; + } else { + // apply APP class and Instance ID + jQuery(appContainer).addClass(F2.Constants.Css.APP); + return appContainer.get(0); + } + }; + + /** + * Renders the html for an app. + * @method _appRender + * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 + * @private + * @param {F2.AppConfig} appConfig The F2.AppConfig object + * @param {string} html The string of html + */ + var _appRender = function(appConfig, html) { + + // apply APP_CONTAINER class + html = _outerHtml(jQuery(html).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appConfig.appId)); + + // optionally apply wrapper html + if (_config.appRender) { + html = _config.appRender(appConfig, html); + } + + // apply APP class and instanceId + return _outerHtml(html); + }; + + /** + * Rendering hook to allow containers to render some html prior to an app + * loading + * @method _beforeAppRender + * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 + * @private + * @param {F2.AppConfig} appConfig The F2.AppConfig object + * @return {Element} The DOM Element surrounding the app + */ + var _beforeAppRender = function(appConfig) { + var handler = _config.beforeAppRender || jQuery.noop; + return handler(appConfig); + }; + + /** + * Handler to inform the container that a script failed to load + * @method _onScriptLoadFailure + * @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0 + * @private + * @param {F2.AppConfig} appConfig The F2.AppConfig object + * @param scriptInfo The path of the script that failed to load or the exception info + * for the inline script that failed to execute + */ + var _appScriptLoadFailed = function(appConfig, scriptInfo) { + var handler = _config.appScriptLoadFailed || jQuery.noop; + return handler(appConfig, scriptInfo); + }; + + /** + * Adds properties to the AppConfig object + * @method _createAppConfig + * @private + * @param {F2.AppConfig} appConfig The F2.AppConfig object + * @return {F2.AppConfig} The new F2.AppConfig object, prepopulated with + * necessary properties + */ + var _createAppConfig = function(appConfig) { + + // make a copy of the app config to ensure that the original is not modified + appConfig = jQuery.extend(true, {}, appConfig); + + // create the instanceId for the app + appConfig.instanceId = appConfig.instanceId || F2.guid(); + + // default the views if not provided + appConfig.views = appConfig.views || []; + if (!F2.inArray(F2.Constants.Views.HOME, appConfig.views)) { + appConfig.views.push(F2.Constants.Views.HOME); + } + + return appConfig; + }; + + /** + * Adds properties to the ContainerConfig object to take advantage of defaults + * @method _hydrateContainerConfig + * @private + * @param {F2.ContainerConfig} containerConfig The F2.ContainerConfig object + */ + var _hydrateContainerConfig = function(containerConfig) { + if (!containerConfig.scriptErrorTimeout){ + containerConfig.scriptErrorTimeout = F2.ContainerConfig.scriptErrorTimeout; + } + + if (containerConfig.debugMode !== true){ + containerConfig.debugMode = F2.ContainerConfig.debugMode; + } + }; + + /** + * Attach app events + * @method _initAppEvents + * @private + */ + var _initAppEvents = function (appConfig) { + + jQuery(appConfig.root).on('click', '.' + F2.Constants.Css.APP_VIEW_TRIGGER + '[' + F2.Constants.Views.DATA_ATTRIBUTE + ']', function(event) { + + event.preventDefault(); + + var view = jQuery(this).attr(F2.Constants.Views.DATA_ATTRIBUTE).toLowerCase(); + + // handle the special REMOVE view + if (view == F2.Constants.Views.REMOVE) { + F2.removeApp(appConfig.instanceId); + } else { + appConfig.ui.Views.change(view); + } + }); + }; + + /** + * Attach container Events + * @method _initContainerEvents + * @private + */ + var _initContainerEvents = function() { + + var resizeTimeout; + var resizeHandler = function() { + F2.Events.emit(F2.Constants.Events.CONTAINER_WIDTH_CHANGE); + }; + + jQuery(window).on('resize', function() { + clearTimeout(resizeTimeout); + resizeTimeout = setTimeout(resizeHandler, 100); + }); + }; + + /** + * Has the container been init? + * @method _isInit + * @private + * @return {bool} True if the container has been init + */ + var _isInit = function() { + return !!_config; + }; + + /** + * Instantiates each app from it's appConfig and stores that in a local private collection + * @method _createAppInstance + * @private + * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} objects + */ + var _createAppInstance = function(appConfig, appContent){ + // instantiate F2.UI + appConfig.ui = new F2.UI(appConfig); + + // instantiate F2.App + if (F2.Apps[appConfig.appId] !== undefined) { + if (typeof F2.Apps[appConfig.appId] === 'function') { + + // IE + setTimeout(function() { + _apps[appConfig.instanceId].app = new F2.Apps[appConfig.appId](appConfig, appContent, appConfig.root); + if (_apps[appConfig.instanceId].app['init'] !== undefined) { + _apps[appConfig.instanceId].app.init(); + } + }, 0); + + } else { + F2.log('app initialization class is defined but not a function. (' + appConfig.appId + ')'); + } + } + }; + + /** + * Loads the app's html/css/javascript + * @method loadApp + * @private + * @param {Array} appConfigs An array of + * {{#crossLink "F2.AppConfig"}}{{/crossLink}} objects + * @param {F2.AppManifest} [appManifest] The AppManifest object + */ + var _loadApps = function(appConfigs, appManifest) { + + appConfigs = [].concat(appConfigs); + + // check for secure app + if (appConfigs.length == 1 && appConfigs[0].isSecure && !_config.isSecureAppPage) { + _loadSecureApp(appConfigs[0], appManifest); + return; + } + + // check that the number of apps in manifest matches the number requested + if (appConfigs.length != appManifest.apps.length) { + F2.log('The number of apps defined in the AppManifest do not match the number requested.', appManifest); + return; + } + + var scripts = appManifest.scripts || []; + var styles = appManifest.styles || []; + var inlines = appManifest.inlineScripts || []; + var scriptCount = scripts.length; + var scriptsLoaded = 0; + var appInit = function() { + jQuery.each(appConfigs, function(i, a) { + _createAppInstance(a, appManifest.apps[i]); + }); + }; + //Check to see if any of the ways a file can be ready are available as properties on the file's element (borrowed from yepnope) + var isFileReady = function(readyState) { + return ( !readyState || readyState == 'loaded' || readyState == 'complete' || readyState == 'uninitialized' ); + }; + var _onload = function(e){ + if ( e.type == 'load' || isFileReady((e.currentTarget || e.srcElement).readyState) ){ + //done, cleanup + var script = e.currentTarget || e.srcElement; + if (script.detachEvent){ + script.detachEvent('onreadystatechange', _onload);//IE + } else { + removeEventListener(script, _onload, 'load'); + removeEventListener(script, _error, 'error'); + } + } + + //are we done loading all scripts for this app? + if (++scriptsLoaded == scriptCount) { + evalInlines(); + appInit(); + } + }; + var _error = function(e){ + //log and emit event for the failed (400,500) scripts + setTimeout(function(){ + var evtData = { + src: e.target.src, + appId: appConfigs[0].appId + }; + //send error to console + F2.log('Script defined in \'' + evtData.appId + '\' failed to load \'' + evtData.src + '\''); + //emit event + F2.Events.emit('RESOURCE_FAILED_TO_LOAD', evtData); + if(!_bUsesAppHandlers) { + _appScriptLoadFailed(appConfigs[0],evtData.src); + } + else { + F2.AppHandlers.__trigger( + _sAppHandlerToken, + F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED, + appConfigs[0], + evtData.src + ); + } + }, _config.scriptErrorTimeout);//defaults to 7000 + }; + //eval inlines + var evalInlines = function(){ + jQuery.each(inlines, function(i, e) { + try { + eval(e); + } catch (exception) { + F2.log('Error loading inline script: ' + exception + '\n\n' + e); + if(!_bUsesAppHandlers) { + _appScriptLoadFailed(appConfigs[0],exception); + } + else { + F2.AppHandlers.__trigger( + _sAppHandlerToken, + F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED, + appConfigs[0], + exception + ); + } + } + }); + }; + + // load styles, see #101 + var stylesFragment = null, + useCreateStyleSheet = !!document.createStyleSheet; + jQuery.each(styles, function(i, e) { + if (useCreateStyleSheet) { + document.createStyleSheet(e); + } else { + stylesFragment = stylesFragment || []; + stylesFragment.push(''); + } + }); + + if (stylesFragment){ + jQuery('head').append(stylesFragment.join('')); + } + + // load html + jQuery.each(appManifest.apps, function(i, a) { + if(!_bUsesAppHandlers) { + // load html and save the root node + appConfigs[i].root = _afterAppRender(appConfigs[i], _appRender(appConfigs[i], a.html)); + } else { + + F2.AppHandlers.__trigger( + _sAppHandlerToken, + F2.Constants.AppHandlers.APP_RENDER, + appConfigs[i], // the app config + _outerHtml(a.html) + ); + + var appId = appConfigs[i].appId; + + if (!appConfigs[i].root) { + throw('Root for ' +appId+ ' must be a native DOM element and cannot be null or undefined. Check your AppHandler callbacks to ensure you have set App root to a native DOM element.'); + } + + var $root = jQuery(appConfigs[i].root); + + if ($root.parents('body:first').length === 0) { + throw('App root for ' +appId+ ' was not appended to the DOM. Check your AppHandler callbacks to ensure you have rendered the app root to the DOM.'); + } + + F2.AppHandlers.__trigger( + _sAppHandlerToken, + F2.Constants.AppHandlers.APP_RENDER_AFTER, + appConfigs[i] // the app config + ); + + if(!F2.isNativeDOMNode(appConfigs[i].root)) { + throw('App root for ' +appId+ ' must be a native DOM element. Check your AppHandler callbacks to ensure you have set app root to a native DOM element.'); + } + + $root.addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appId); + } + + // init events + _initAppEvents(appConfigs[i]); + }); + + // load scripts and eval inlines once complete + jQuery.each(scripts, function(i, e) { + var doc = document, + script = doc.createElement('script'), + resourceUrl = e; + + //if in debugMode, add cache buster to each script URL + if (_config.debugMode){ + resourceUrl += '?cachebuster=' + new Date().getTime(); + } + + //scripts needed to be loaded in order they're defined in the AppManifest + script.async = false; + //add other attrs + script.src = resourceUrl; + script.type = 'text/javascript'; + script.charset = 'utf-8'; + //attach load event to script to evaluate inline scripts and init the AppClass + if (script.attachEvent && !(script.attachEvent.toString && script.attachEvent.toString().indexOf('[native code') < 0)){//for IE, from requirejs + script.attachEvent('onreadystatechange', _onload); + } else { + script.addEventListener('load', _onload, false); + //attach error event for 400s and 500s + script.addEventListener('error', _error, false); + } + + doc.body.appendChild(script); + }); + + // if no scripts were to be processed, fire the appInit event + if (!scriptCount) { + evalInlines(); + appInit(); + } + }; + + /** + * Loads the app's html/css/javascript into an iframe + * @method loadSecureApp + * @private + * @param {F2.AppConfig} appConfig The F2.AppConfig object + * @param {F2.AppManifest} appManifest The app's html/css/js to be loaded into the + * page. + */ + var _loadSecureApp = function(appConfig, appManifest) { + + // make sure the container is configured for secure apps + if (_config.secureAppPagePath) { + if(!_bUsesAppHandlers) { + // create the html container for the iframe + appConfig.root = _afterAppRender(appConfig, _appRender(appConfig, '
                              ')); + } else { + var $root = jQuery(appConfig.root); + + F2.AppHandlers.__trigger( + _sAppHandlerToken, + F2.Constants.AppHandlers.APP_RENDER, + appConfig, // the app config + appManifest.html + ); + + if ($root.parents('body:first').length === 0) { + throw('App was never rendered on the page. Please check your AppHandler callbacks to ensure you have rendered the app root to the DOM.'); + } + + F2.AppHandlers.__trigger( + _sAppHandlerToken, + F2.Constants.AppHandlers.APP_RENDER_AFTER, + appConfig // the app config + ); + + if (!appConfig.root) { + throw('App Root must be a native dom node and can not be null or undefined. Please check your AppHandler callbacks to ensure you have set App Root to a native dom node.'); + } + + if (!F2.isNativeDOMNode(appConfig.root)) { + throw('App Root must be a native dom node. Please check your AppHandler callbacks to ensure you have set App Root to a native dom node.'); + } + + jQuery(appConfig.root).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appConfig.appId); + } + + // instantiate F2.UI + appConfig.ui = new F2.UI(appConfig); + // init events + _initAppEvents(appConfig); + // create RPC socket + F2.Rpc.register(appConfig, appManifest); + } else { + F2.log('Unable to load secure app: "secureAppPagePath" is not defined in F2.ContainerConfig.'); + } + }; + + var _outerHtml = function(html) { + return jQuery('
                              ').append(html).html(); + }; + + /** + * Checks if the app is valid + * @method _validateApp + * @private + * @param {F2.AppConfig} appConfig The F2.AppConfig object + * @returns {bool} True if the app is valid + */ + var _validateApp = function(appConfig) { + + // check for valid app configurations + if (!appConfig.appId) { + F2.log('"appId" missing from app object'); + return false; + } else if (!appConfig.root && !appConfig.manifestUrl) { + F2.log('"manifestUrl" missing from app object'); + return false; + } + + return true; + }; + + /** + * Checks if the ContainerConfig is valid + * @method _validateContainerConfig + * @private + * @returns {bool} True if the config is valid + */ + var _validateContainerConfig = function() { + + if (_config) { + if (_config.xhr) { + if (!(typeof _config.xhr === 'function' || typeof _config.xhr === 'object')) { + throw('ContainerConfig.xhr should be a function or an object'); + } + if (_config.xhr.dataType && typeof _config.xhr.dataType !== 'function') { + throw('ContainerConfig.xhr.dataType should be a function'); + } + if (_config.xhr.type && typeof _config.xhr.type !== 'function') { + throw('ContainerConfig.xhr.type should be a function'); + } + if (_config.xhr.url && typeof _config.xhr.url !== 'function') { + throw('ContainerConfig.xhr.url should be a function'); + } + } + } + + return true; + }; + + return { + /** + * Gets the current list of apps in the container + * @method getContainerState + * @returns {Array} An array of objects containing the appId + */ + getContainerState: function() { + if (!_isInit()) { + F2.log('F2.init() must be called before F2.getContainerState()'); + return; + } + + return jQuery.map(_apps, function(app) { + return { appId: app.config.appId }; + }); + }, + /** + * Initializes the container. This method must be called before performing + * any other actions in the container. + * @method init + * @param {F2.ContainerConfig} config The configuration object + */ + init: function(config) { + _config = config || {}; + + _validateContainerConfig(); + + _hydrateContainerConfig(_config); + + // dictates whether we use the old logic or the new logic. + // TODO: Remove in v2.0 + _bUsesAppHandlers = (!_config.beforeAppRender && !_config.appRender && !_config.afterAppRender && !_config.appScriptLoadFailed); + + // only establish RPC connection if the container supports the secure app page + if (!!_config.secureAppPagePath || _config.isSecureAppPage) { + F2.Rpc.init(!!_config.secureAppPagePath ? _config.secureAppPagePath : false); + } + + F2.UI.init(_config); + + if (!_config.isSecureAppPage) { + _initContainerEvents(); + } + }, + /** + * Has the container been init? + * @method isInit + * @return {bool} True if the container has been init + */ + isInit: _isInit, + /** + * Begins the loading process for all apps and/or initialization process for pre-loaded apps. + * The app will be passed the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object which will + * contain the app's unique instanceId within the container. If the + * {{#crossLink "F2.AppConfig"}}{{/crossLink}}.root property is populated the app is considered + * to be a pre-loaded app and will be handled accordingly. Optionally, the + * {{#crossLink "F2.AppManifest"}}{{/crossLink}} can be passed in and those + * assets will be used instead of making a request. + * @method registerApps + * @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} + * objects + * @param {Array} [appManifests] An array of + * {{#crossLink "F2.AppManifest"}}{{/crossLink}} + * objects. This array must be the same length as the apps array that is + * objects. This array must be the same length as the apps array that is + * passed in. This can be useful if apps are loaded on the server-side and + * passed down to the client. + * @example + * Traditional App requests. + * + * // Traditional f2 app configs + * var arConfigs = [ + * { + * appId: 'com_externaldomain_example_app', + * context: {}, + * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' + * }, + * { + * appId: 'com_externaldomain_example_app', + * context: {}, + * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' + * }, + * { + * appId: 'com_externaldomain_example_app2', + * context: {}, + * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' + * } + * ]; + * + * F2.init(); + * F2.registerApps(arConfigs); + * + * @example + * Pre-loaded and tradition apps mixed. + * + * // Pre-loaded apps and traditional f2 app configs + * // you can preload the same app multiple times as long as you have a unique root for each + * var arConfigs = [ + * { + * appId: 'com_mydomain_example_app', + * context: {}, + * root: 'div#example-app-1', + * manifestUrl: '' + * }, + * { + * appId: 'com_mydomain_example_app', + * context: {}, + * root: 'div#example-app-2', + * manifestUrl: '' + * }, + * { + * appId: 'com_externaldomain_example_app', + * context: {}, + * manifestUrl: 'http://www.externaldomain.com/F2/AppManifest' + * } + * ]; + * + * F2.init(); + * F2.registerApps(arConfigs); + * + * @example + * Apps with predefined manifests. + * + * // Traditional f2 app configs + * var arConfigs = [ + * {appId: 'com_externaldomain_example_app', context: {}}, + * {appId: 'com_externaldomain_example_app', context: {}}, + * {appId: 'com_externaldomain_example_app2', context: {}} + * ]; + * + * // Pre requested manifest responses + * var arManifests = [ + * { + * apps: ['
                              Example App!
                              '], + * inlineScripts: [], + * scripts: ['http://www.domain.com/js/AppClass.js'], + * styles: ['http://www.domain.com/css/AppStyles.css'] + * }, + * { + * apps: ['
                              Example App!
                              '], + * inlineScripts: [], + * scripts: ['http://www.domain.com/js/AppClass.js'], + * styles: ['http://www.domain.com/css/AppStyles.css'] + * }, + * { + * apps: ['
                              Example App 2!
                              '], + * inlineScripts: [], + * scripts: ['http://www.domain.com/js/App2Class.js'], + * styles: ['http://www.domain.com/css/App2Styles.css'] + * } + * ]; + * + * F2.init(); + * F2.registerApps(arConfigs, arManifests); + */ + registerApps: function(appConfigs, appManifests) { + + if (!_isInit()) { + F2.log('F2.init() must be called before F2.registerApps()'); + return; + } else if (!appConfigs) { + F2.log('At least one AppConfig must be passed when calling F2.registerApps()'); + return; + } + + var appStack = []; + var batches = {}; + var callbackStack = {}; + var haveManifests = false; + appConfigs = [].concat(appConfigs); + appManifests = [].concat(appManifests || []); + haveManifests = !!appManifests.length; + + // appConfigs must have a length + if (!appConfigs.length) { + F2.log('At least one AppConfig must be passed when calling F2.registerApps()'); + return; + // ensure that the array of apps and manifests are qual + } else if (appConfigs.length && haveManifests && appConfigs.length != appManifests.length) { + F2.log('The length of "apps" does not equal the length of "appManifests"'); + return; + } + + // validate each app and assign it an instanceId + // then determine which apps can be batched together + jQuery.each(appConfigs, function(i, a) { + + // add properties and methods + a = _createAppConfig(a); + + // Will set to itself, for preloaded apps, or set to null for apps that aren't already + // on the page. + a.root = a.root || null; + + // we validate the app after setting the root property because pre-load apps do no require + // manifest url + if (!_validateApp(a)) { + return; // move to the next app + } + + // save app + _apps[a.instanceId] = { config:a }; + + // If the root property is defined then this app is considered to be preloaded and we will + // run it through that logic. + if(a.root) + { + if((!a.root && typeof(a.root) != 'string') && !F2.isNativeDOMNode(a.root)) + { + F2.log('AppConfig invalid for pre-load, not a valid string and not dom node'); + F2.log('AppConfig instance:', a); + throw('Preloaded appConfig.root property must be a native dom node or a string representing a sizzle selector. Please check your inputs and try again.'); + } + else if(jQuery(a.root).length != 1) + { + F2.log('AppConfig invalid for pre-load, root not unique'); + F2.log('AppConfig instance:', a); + F2.log('Number of dom node instances:', jQuery(a.root).length); + throw('Preloaded appConfig.root property must map to a unique dom node. Please check your inputs and try again.'); + } + + // instantiate F2.App + _createAppInstance(a); + + // init events + _initAppEvents(a); + + // Continue on in the .each loop, no need to continue because the app is on the page + // the js in initialized, and it is ready to role. + return; // equivalent to continue in .each + } + + if(!_bUsesAppHandlers) + { + // fire beforeAppRender + a.root = _beforeAppRender(a); + } + else + { + F2.AppHandlers.__trigger( + _sAppHandlerToken, + F2.Constants.AppHandlers.APP_CREATE_ROOT, + a // the app config + ); + + F2.AppHandlers.__trigger( + _sAppHandlerToken, + F2.Constants.AppHandlers.APP_RENDER_BEFORE, + a // the app config + ); + } + + // if we have the manifest, go ahead and load the app + if (haveManifests) { + _loadApps(a, appManifests[i]); + } else { + // check if this app can be batched + if (a.enableBatchRequests && !a.isSecure) { + batches[a.manifestUrl.toLowerCase()] = batches[a.manifestUrl.toLowerCase()] || []; + batches[a.manifestUrl.toLowerCase()].push(a); + } else { + appStack.push({ + apps:[a], + url:a.manifestUrl + }); + } + } + }); + + // we don't have the manifests, go ahead and load them + if (!haveManifests) { + // add the batches to the appStack + jQuery.each(batches, function(i, b) { + appStack.push({ url:i, apps:b }); + }); + + // if an app is being loaded more than once on the page, there is the + // potential that the jsonp callback will be clobbered if the request + // for the AppManifest for the app comes back at the same time as + // another request for the same app. We'll create a callbackStack + // that will ensure that requests for the same app are loaded in order + // rather than at the same time + jQuery.each(appStack, function(i, req) { + // define the callback function based on the first app's App ID + var jsonpCallback = F2.Constants.JSONP_CALLBACK + req.apps[0].appId; + + // push the request onto the callback stack + callbackStack[jsonpCallback] = callbackStack[jsonpCallback] || []; + callbackStack[jsonpCallback].push(req); + }); + + // loop through each item in the callback stack and make the request + // for the AppManifest. When the request is complete, pop the next + // request off the stack and make the request. + jQuery.each(callbackStack, function(i, requests) { + + var manifestRequest = function(jsonpCallback, req) { + if (!req) { return; } + + // setup defaults and callbacks + var url = req.url, + type = 'GET', + dataType = 'jsonp', + completeFunc = function() { + manifestRequest(i, requests.pop()); + }, + errorFunc = function() { + jQuery.each(req.apps, function(idx,item){ + F2.log('Removed failed ' +item.name+ ' app', item); + F2.removeApp(item.instanceId); + }); + }, + successFunc = function(appManifest) { + _loadApps(req.apps, appManifest); + }; + + // optionally fire xhr overrides + if (_config.xhr && _config.xhr.dataType) { + dataType = _config.xhr.dataType(req.url, req.apps); + if (typeof dataType !== 'string') { + throw('ContainerConfig.xhr.dataType should return a string'); + } + } + if (_config.xhr && _config.xhr.type) { + type = _config.xhr.type(req.url, req.apps); + if (typeof type !== 'string') { + throw('ContainerConfig.xhr.type should return a string'); + } + } + if (_config.xhr && _config.xhr.url) { + url = _config.xhr.url(req.url, req.apps); + if (typeof url !== 'string') { + throw('ContainerConfig.xhr.url should return a string'); + } + } + + // setup the default request function if an override is not present + var requestFunc = _config.xhr; + if (typeof requestFunc !== 'function') { + requestFunc = function(url, appConfigs, successCallback, errorCallback, completeCallback) { + jQuery.ajax({ + url: url, + type: type, + data: { + params: F2.stringify(req.apps, F2.appConfigReplacer) + }, + jsonp: false, // do not put 'callback=' in the query string + jsonpCallback: jsonpCallback, // Unique function name + dataType: dataType, + success: successCallback, + error: function(jqxhr, settings, exception) { + F2.log('Failed to load app(s)', exception.toString(), req.apps); + errorCallback(); + }, + complete: completeCallback + }); + }; + } + + requestFunc(url, req.apps, successFunc, errorFunc, completeFunc); + }; + + manifestRequest(i, requests.pop()); + }); + } + }, + /** + * Removes all apps from the container + * @method removeAllApps + */ + removeAllApps: function() { + + if (!_isInit()) { + F2.log('F2.init() must be called before F2.removeAllApps()'); + return; + } + + jQuery.each(_apps, function(i, a) { + F2.removeApp(a.config.instanceId); + }); + }, + /** + * Removes an app from the container + * @method removeApp + * @param {string} instanceId The app's instanceId + */ + removeApp: function(instanceId) { + + if (!_isInit()) { + F2.log('F2.init() must be called before F2.removeApp()'); + return; + } + + if (_apps[instanceId]) { + F2.AppHandlers.__trigger( + _sAppHandlerToken, + F2.Constants.AppHandlers.APP_DESTROY_BEFORE, + _apps[instanceId] // the app instance + ); + + F2.AppHandlers.__trigger( + _sAppHandlerToken, + F2.Constants.AppHandlers.APP_DESTROY, + _apps[instanceId] // the app instance + ); + + F2.AppHandlers.__trigger( + _sAppHandlerToken, + F2.Constants.AppHandlers.APP_DESTROY_AFTER, + _apps[instanceId] // the app instance + ); + + delete _apps[instanceId]; + } + } + }; +})()); + + exports.F2 = F2; + + if (typeof define !== 'undefined' && define.amd) { + + define(function() { + return F2; + }); + + } + +})(typeof exports !== 'undefined' ? exports : window); \ No newline at end of file diff --git a/ajax/libs/F2/1.3.1/f2.basic.min.js b/ajax/libs/F2/1.3.1/f2.basic.min.js new file mode 100644 index 000000000..be09d891c --- /dev/null +++ b/ajax/libs/F2/1.3.1/f2.basic.min.js @@ -0,0 +1,69 @@ +/*! F2 - v1.3.1 - 10-15-2013 - See below for copyright and license */ +(function(exports){if(!exports.F2||exports.F2_TESTING_MODE){/*! + JSON.org requires the following notice to accompany json2: + + Copyright (c) 2002 JSON.org + + http://json.org + + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + + The Software shall be used for Good, not Evil. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + IN THE SOFTWARE. +*/ +"object"!=typeof JSON&&(JSON={}),function(){"use strict";function f(e){return 10>e?"0"+e:e}function quote(e){return escapable.lastIndex=0,escapable.test(e)?'"'+e.replace(escapable,function(e){var t=meta[e];return"string"==typeof t?t:"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+e+'"'}function str(e,t){var n,r,o,i,a,s=gap,l=t[e];switch(l&&"object"==typeof l&&"function"==typeof l.toJSON&&(l=l.toJSON(e)),"function"==typeof rep&&(l=rep.call(t,e,l)),typeof l){case"string":return quote(l);case"number":return isFinite(l)?l+"":"null";case"boolean":case"null":return l+"";case"object":if(!l)return"null";if(gap+=indent,a=[],"[object Array]"===Object.prototype.toString.apply(l)){for(i=l.length,n=0;i>n;n+=1)a[n]=str(n,l)||"null";return o=0===a.length?"[]":gap?"[\n"+gap+a.join(",\n"+gap)+"\n"+s+"]":"["+a.join(",")+"]",gap=s,o}if(rep&&"object"==typeof rep)for(i=rep.length,n=0;i>n;n+=1)"string"==typeof rep[n]&&(r=rep[n],o=str(r,l),o&&a.push(quote(r)+(gap?": ":":")+o));else for(r in l)Object.prototype.hasOwnProperty.call(l,r)&&(o=str(r,l),o&&a.push(quote(r)+(gap?": ":":")+o));return o=0===a.length?"{}":gap?"{\n"+gap+a.join(",\n"+gap)+"\n"+s+"}":"{"+a.join(",")+"}",gap=s,o}}"function"!=typeof Date.prototype.toJSON&&(Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null},String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(){return this.valueOf()});var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;"function"!=typeof JSON.stringify&&(JSON.stringify=function(e,t,n){var r;if(gap="",indent="","number"==typeof n)for(r=0;n>r;r+=1)indent+=" ";else"string"==typeof n&&(indent=n);if(rep=t,t&&"function"!=typeof t&&("object"!=typeof t||"number"!=typeof t.length))throw Error("JSON.stringify");return str("",{"":e})}),"function"!=typeof JSON.parse&&(JSON.parse=function(text,reviver){function walk(e,t){var n,r,o=e[t];if(o&&"object"==typeof o)for(n in o)Object.prototype.hasOwnProperty.call(o,n)&&(r=walk(o,n),void 0!==r?o[n]=r:delete o[n]);return reviver.call(e,t,o)}var j;if(text+="",cx.lastIndex=0,cx.test(text)&&(text=text.replace(cx,function(e){return"\\u"+("0000"+e.charCodeAt(0).toString(16)).slice(-4)})),/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return j=eval("("+text+")"),"function"==typeof reviver?walk({"":j},""):j;throw new SyntaxError("JSON.parse")})}(),/*! + * Hij1nx requires the following notice to accompany EventEmitter: + * + * Copyright (c) 2011 hij1nx + * + * http://www.twitter.com/hij1nx + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the 'Software'), to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, + * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO + * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +!function(e){function t(){this._events={}}function n(e){e&&(e.delimiter&&(this.delimiter=e.delimiter),e.wildcard&&(this.wildcard=e.wildcard),this.wildcard&&(this.listenerTree={}))}function r(e){this._events={},n.call(this,e)}function o(e,t,n,r){if(!n)return[];var i,a,s,l,c,u,p,f=[],d=t.length,h=t[r],g=t[r+1];if(r===d&&n._listeners){if("function"==typeof n._listeners)return e&&e.push(n._listeners),[n];for(i=0,a=n._listeners.length;a>i;i++)e&&e.push(n._listeners[i]);return[n]}if("*"===h||"**"===h||n[h]){if("*"===h){for(s in n)"_listeners"!==s&&n.hasOwnProperty(s)&&(f=f.concat(o(e,t,n[s],r+1)));return f}if("**"===h){p=r+1===d||r+2===d&&"*"===g,p&&n._listeners&&(f=f.concat(o(e,t,n,d)));for(s in n)"_listeners"!==s&&n.hasOwnProperty(s)&&("*"===s||"**"===s?(n[s]._listeners&&!p&&(f=f.concat(o(e,t,n[s],d))),f=f.concat(o(e,t,n[s],r))):f=s===g?f.concat(o(e,t,n[s],r+2)):f.concat(o(e,t,n[s],r)));return f}f=f.concat(o(e,t,n[h],r+1))}if(l=n["*"],l&&o(e,t,l,r+1),c=n["**"])if(d>r){c._listeners&&o(e,t,c,d);for(s in c)"_listeners"!==s&&c.hasOwnProperty(s)&&(s===g?o(e,t,c[s],r+2):s===h?o(e,t,c[s],r+1):(u={},u[s]=c[s],o(e,t,{"**":u},r+1)))}else c._listeners?o(e,t,c,d):c["*"]&&c["*"]._listeners&&o(e,t,c["*"],d);return f}function i(e,t){e="string"==typeof e?e.split(this.delimiter):e.slice();for(var n=0,r=e.length;r>n+1;n++)if("**"===e[n]&&"**"===e[n+1])return;for(var o=this.listenerTree,i=e.shift();i;){if(o[i]||(o[i]={}),o=o[i],0===e.length){if(o._listeners){if("function"==typeof o._listeners)o._listeners=[o._listeners,t];else if(a(o._listeners)&&(o._listeners.push(t),!o._listeners.warned)){var l=s;this._events.maxListeners!==undefined&&(l=this._events.maxListeners),l>0&&o._listeners.length>l&&(o._listeners.warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",o._listeners.length),console.trace())}}else o._listeners=t;return!0}i=e.shift()}return!0}var a=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},s=10;r.prototype.delimiter=".",r.prototype.setMaxListeners=function(e){this._events||t.call(this),this._events.maxListeners=e},r.prototype.event="",r.prototype.once=function(e,t){return this.many(e,1,t),this},r.prototype.many=function(e,t,n){function r(){0===--t&&o.off(e,r),n.apply(this,arguments)}var o=this;if("function"!=typeof n)throw Error("many only accepts instances of Function");return r._origin=n,this.on(e,r),o},r.prototype.emit=function(){this._events||t.call(this);var e=arguments[0];if("newListener"===e&&!this._events.newListener)return!1;if(this._all){for(var n=arguments.length,r=Array(n-1),i=1;n>i;i++)r[i-1]=arguments[i];for(i=0,n=this._all.length;n>i;i++)this.event=e,this._all[i].apply(this,r)}if("error"===e&&!(this._all||this._events.error||this.wildcard&&this.listenerTree.error))throw arguments[1]instanceof Error?arguments[1]:Error("Uncaught, unspecified 'error' event.");var a;if(this.wildcard){a=[];var s="string"==typeof e?e.split(this.delimiter):e.slice();o.call(this,a,s,this.listenerTree,0)}else a=this._events[e];if("function"==typeof a){if(this.event=e,1===arguments.length)a.call(this);else if(arguments.length>1)switch(arguments.length){case 2:a.call(this,arguments[1]);break;case 3:a.call(this,arguments[1],arguments[2]);break;default:for(var n=arguments.length,r=Array(n-1),i=1;n>i;i++)r[i-1]=arguments[i];a.apply(this,r)}return!0}if(a){for(var n=arguments.length,r=Array(n-1),i=1;n>i;i++)r[i-1]=arguments[i];for(var l=a.slice(),i=0,n=l.length;n>i;i++)this.event=e,l[i].apply(this,r);return l.length>0||this._all}return this._all},r.prototype.on=function(e,n){if("function"==typeof e)return this.onAny(e),this;if("function"!=typeof n)throw Error("on only accepts instances of Function");if(this._events||t.call(this),this.emit("newListener",e,n),this.wildcard)return i.call(this,e,n),this;if(this._events[e]){if("function"==typeof this._events[e])this._events[e]=[this._events[e],n];else if(a(this._events[e])&&(this._events[e].push(n),!this._events[e].warned)){var r=s;this._events.maxListeners!==undefined&&(r=this._events.maxListeners),r>0&&this._events[e].length>r&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),console.trace())}}else this._events[e]=n;return this},r.prototype.onAny=function(e){if(this._all||(this._all=[]),"function"!=typeof e)throw Error("onAny only accepts instances of Function");return this._all.push(e),this},r.prototype.addListener=r.prototype.on,r.prototype.off=function(e,t){if("function"!=typeof t)throw Error("removeListener only takes instances of Function");var n,r=[];if(this.wildcard){var i="string"==typeof e?e.split(this.delimiter):e.slice();r=o.call(this,null,i,this.listenerTree,0)}else{if(!this._events[e])return this;n=this._events[e],r.push({_listeners:n})}for(var s=0;r.length>s;s++){var l=r[s];if(n=l._listeners,a(n)){for(var c=-1,u=0,p=n.length;p>u;u++)if(n[u]===t||n[u].listener&&n[u].listener===t||n[u]._origin&&n[u]._origin===t){c=u;break}if(0>c)return this;this.wildcard?l._listeners.splice(c,1):this._events[e].splice(c,1),0===n.length&&(this.wildcard?delete l._listeners:delete this._events[e])}else(n===t||n.listener&&n.listener===t||n._origin&&n._origin===t)&&(this.wildcard?delete l._listeners:delete this._events[e])}return this},r.prototype.offAny=function(e){var t,n=0,r=0;if(e&&this._all&&this._all.length>0){for(t=this._all,n=0,r=t.length;r>n;n++)if(e===t[n])return t.splice(n,1),this}else this._all=[];return this},r.prototype.removeListener=r.prototype.off,r.prototype.removeAllListeners=function(e){if(0===arguments.length)return!this._events||t.call(this),this;if(this.wildcard)for(var n="string"==typeof e?e.split(this.delimiter):e.slice(),r=o.call(this,null,n,this.listenerTree,0),i=0;r.length>i;i++){var a=r[i];a._listeners=null}else{if(!this._events[e])return this;this._events[e]=null}return this},r.prototype.listeners=function(e){if(this.wildcard){var n=[],r="string"==typeof e?e.split(this.delimiter):e.slice();return o.call(this,n,r,this.listenerTree,0),n}return this._events||t.call(this),this._events[e]||(this._events[e]=[]),a(this._events[e])||(this._events[e]=[this._events[e]]),this._events[e]},r.prototype.listenersAny=function(){return this._all?this._all:[]},e.EventEmitter2=r}("undefined"!=typeof process&&process.title!==void 0&&exports!==void 0?exports:window);/*! + * F2 v1.3.1 10-15-2013 + * Copyright (c) 2013 Markit On Demand, Inc. http://www.openf2.org + * + * "F2" is licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed + * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + * Please note that F2 ("Software") may contain third party material that Markit + * On Demand Inc. has a license to use and include within the Software (the + * "Third Party Material"). A list of the software comprising the Third Party Material + * and the terms and conditions under which such Third Party Material is distributed + * are reproduced in the ThirdPartyMaterial.md file available at: + * + * https://github.com/OpenF2/F2/blob/master/ThirdPartyMaterial.md + * + * The inclusion of the Third Party Material in the Software does not grant, provide + * nor result in you having acquiring any rights whatsoever, other than as stipulated + * in the terms and conditions related to the specific Third Party Material, if any. + * + */ +var F2;F2=function(){var e=function(e,n){function r(e){var t=[];return e.replace(/^(\.\.?(\/|$))+/,"").replace(/\/(\.(\/|$))+/g,"/").replace(/\/\.\.$/,"/../").replace(/\/?[^\/]*/g,function(e){"/.."===e?t.pop():t.push(e)}),t.join("").replace(/^\//,"/"===e.charAt(0)?"/":"")}return n=t(n||""),e=t(e||""),n&&e?(n.protocol||e.protocol)+(n.protocol||n.authority?n.authority:e.authority)+r(n.protocol||n.authority||"/"===n.pathname.charAt(0)?n.pathname:n.pathname?(e.authority&&!e.pathname?"/":"")+e.pathname.slice(0,e.pathname.lastIndexOf("/")+1)+n.pathname:e.pathname)+(n.protocol||n.authority||n.pathname?n.search:n.search||e.search)+n.hash:null},t=function(e){var t=(e+"").replace(/^\s+|\s+$/g,"").match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);return t?{href:t[0]||"",protocol:t[1]||"",authority:t[2]||"",host:t[3]||"",hostname:t[4]||"",port:t[5]||"",pathname:t[6]||"",search:t[7]||"",hash:t[8]||""}:null};return{appConfigReplacer:function(e,t){return"root"==e||"ui"==e||"height"==e?void 0:t},Apps:{},extend:function(e,t,n){var r="function"==typeof t,o=e?e.split("."):[],i=this;t=t||{},"F2"===o[0]&&(o=o.slice(1));for(var a=0,s=o.length;s>a;a++)i[o[a]]||(i[o[a]]=r&&a+1==s?t:{}),i=i[o[a]];if(!r)for(var l in t)(i[l]===void 0||n)&&(i[l]=t[l]);return i},guid:function(){var e=function(){return(0|65536*(1+Math.random())).toString(16).substring(1)};return e()+e()+"-"+e()+"-"+e()+"-"+e()+"-"+e()+e()+e()},inArray:function(e,t){return jQuery.inArray(e,t)>-1},isLocalRequest:function(t){var n,r,o=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,i=t.toLowerCase(),a=o.exec(i);try{n=location.href}catch(s){n=document.createElement("a"),n.href="",n=n.href}n=n.toLowerCase(),a||(i=e(n,i).toLowerCase(),a=o.exec(i)),r=o.exec(n)||[];var l=!(a&&(a[1]!==r[1]||a[2]!==r[2]||(a[3]||("http:"===a[1]?"80":"443"))!==(r[3]||("http:"===r[1]?"80":"443"))));return l},isNativeDOMNode:function(e){var t="object"==typeof Node?e instanceof Node:e&&"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName,n="object"==typeof HTMLElement?e instanceof HTMLElement:e&&"object"==typeof e&&1===e.nodeType&&"string"==typeof e.nodeName;return t||n},log:function(){for(var e,t,n,r="log",o=function(){},i=["assert","clear","count","debug","dir","dirxml","error","exception","group","groupCollapsed","groupEnd","info","log","markTimeline","profile","profileEnd","table","time","timeEnd","timeStamp","trace","warn"],a=i.length,s=window.console=window.console||{};a--;)t=i[a],s[t]||(s[t]=o),arguments&&arguments.length>1&&arguments[0]==t&&(r=t,n=Array.prototype.slice.call(arguments,1));e=Function.prototype.bind?Function.prototype.bind.call(s[r],s):function(){Function.prototype.apply.call(s[r],s,n||arguments)},e.apply(this,n||arguments)},parse:function(e){return JSON.parse(e)},stringify:function(e,t,n){return JSON.stringify(e,t,n)},version:function(){return"{{sdk.version}}"}}}(),F2.extend("AppHandlers",function(){var e=F2.guid(),t=F2.guid(),n={appCreateRoot:[],appRenderBefore:[],appDestroyBefore:[],appRenderAfter:[],appDestroyAfter:[],appRender:[],appDestroy:[],appScriptLoadFailed:[]},r={appRender:function(e,t){var n=null;F2.isNativeDOMNode(e.root)?(n=jQuery(e.root),n.append(t)):(e.root=jQuery(t).get(0),n=jQuery(e.root)),jQuery("body").append(n)},appDestroy:function(e){e&&e.app&&e.app.destroy&&"function"==typeof e.app.destroy?e.app.destroy():e&&e.app&&e.app.destroy&&F2.log(e.config.appId+" has a destroy property, but destroy is not of type function and as such will not be executed."),jQuery(e.config.root).fadeOut(500,function(){jQuery(this).remove()})}},o=function(e,t,n,r){i(e);var o={func:n,namespace:t,domNode:F2.isNativeDOMNode(n)?n:null};if(!o.func&&!o.domNode)throw"Invalid or null argument passed. Handler will not be added to collection. A valid dom element or callback function is required.";if(o.domNode&&!r)throw"Invalid argument passed. Handler will not be added to collection. A callback function is required for this event type.";return o},i=function(n){if(e!=n&&t!=n)throw"Invalid token passed. Please verify that you have correctly received and stored token from F2.AppHandlers.getToken()."},a=function(e,t,r){if(i(e),r||t)if(!r&&t)n[t]=[];else if(r&&!t){r=r.toLowerCase();for(var o in n){for(var a=n[o],s=[],l=0,c=a.length;c>l;l++){var u=a[l];u&&(u.namespace&&u.namespace.toLowerCase()==r||s.push(u))}a=s}}else if(r&&n[t]){r=r.toLowerCase();for(var p=[],f=0,d=n[t].length;d>f;f++){var h=n[t][f];h&&(h.namespace&&h.namespace.toLowerCase()==r||p.push(h))}n[t]=p}};return{getToken:function(){return delete this.getToken,e},__f2GetToken:function(){return delete this.__f2GetToken,t},__trigger:function(e,o){if(e!=t)throw"Token passed is invalid. Only F2 is allowed to call F2.AppHandlers.__trigger().";if(!n||!n[o])throw"Invalid EventKey passed. Check your inputs and try again.";for(var i=[],a=2,s=arguments.length;s>a;a++)i.push(arguments[a]);if(0===n[o].length&&r[o])return r[o].apply(F2,i),this;if(0===n[o].length&&!n[o])return this;for(var l=0,c=n[o].length;c>l;l++){var u=n[o][l];if(u.domNode&&arguments[2]&&arguments[2].root&&arguments[3]){var p=jQuery(arguments[2].root).append(arguments[3]);jQuery(u.domNode).append(p)}else u.domNode&&arguments[2]&&!arguments[2].root&&arguments[3]?(arguments[2].root=jQuery(arguments[3]).get(0),jQuery(u.domNode).append(arguments[2].root)):u.func.apply(F2,i)}return this},on:function(e,t,r){var i=null;if(!t)throw"eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.";if(t.indexOf(".")>-1){var a=t.split(".");t=a[0],i=a[1]}if(!n||!n[t])throw"Invalid EventKey passed. Check your inputs and try again.";return n[t].push(o(e,i,r,"appRender"==t)),this},off:function(e,t){var r=null;if(!t)throw"eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.";if(t.indexOf(".")>-1){var o=t.split(".");t=o[0],r=o[1]}if(!n||!n[t])throw"Invalid EventKey passed. Check your inputs and try again.";return a(e,t,r),this}}}()),F2.extend("Constants",{AppHandlers:function(){return{APP_CREATE_ROOT:"appCreateRoot",APP_RENDER_BEFORE:"appRenderBefore",APP_RENDER:"appRender",APP_RENDER_AFTER:"appRenderAfter",APP_DESTROY_BEFORE:"appDestroyBefore",APP_DESTROY:"appDestroy",APP_DESTROY_AFTER:"appDestroyAfter",APP_SCRIPT_LOAD_FAILED:"appScriptLoadFailed"}}()}),F2.extend("",{App:function(){return{init:function(){}}},AppConfig:{appId:"",context:{},enableBatchRequests:!1,height:0,instanceId:"",isSecure:!1,manifestUrl:"",maxWidth:0,minGridSize:4,minWidth:300,name:"",root:void 0,ui:void 0,views:[]},AppManifest:{apps:[],inlineScripts:[],scripts:[],styles:[]},AppContent:{data:{},html:"",status:""},ContainerConfig:{afterAppRender:function(){},appRender:function(){},beforeAppRender:function(){},debugMode:!1,scriptErrorTimeout:7e3,isSecureAppPage:!1,secureAppPagePath:"",supportedViews:[],UI:{Mask:{backgroundColor:"#FFF",loadingIcon:"",opacity:.6,useClasses:!1,zIndex:2}},xhr:{dataType:function(){},type:function(){},url:function(){}}}}),F2.extend("Constants",{Css:function(){var e="f2-";return{APP:e+"app",APP_CONTAINER:e+"app-container",APP_TITLE:e+"app-title",APP_VIEW:e+"app-view",APP_VIEW_TRIGGER:e+"app-view-trigger",MASK:e+"mask",MASK_CONTAINER:e+"mask-container"}}(),Events:function(){var e="App.",t="Container.";return{APP_SYMBOL_CHANGE:e+"symbolChange",APP_WIDTH_CHANGE:e+"widthChange.",CONTAINER_SYMBOL_CHANGE:t+"symbolChange",CONTAINER_WIDTH_CHANGE:t+"widthChange"}}(),JSONP_CALLBACK:"F2_jsonpCallback_",Sockets:{EVENT:"__event__",LOAD:"__socketLoad__",RPC:"__rpc__",RPC_CALLBACK:"__rpcCallback__",UI_RPC:"__uiRpc__"},Views:{DATA_ATTRIBUTE:"data-f2-view",ABOUT:"about",HELP:"help",HOME:"home",REMOVE:"remove",SETTINGS:"settings"}}),F2.extend("Events",function(){var e=new EventEmitter2({wildcard:!0});return e.setMaxListeners(0),{_socketEmit:function(){return EventEmitter2.prototype.emit.apply(e,[].slice.call(arguments))},emit:function(){return F2.Rpc.broadcast(F2.Constants.Sockets.EVENT,[].slice.call(arguments)),EventEmitter2.prototype.emit.apply(e,[].slice.call(arguments))},many:function(t,n,r){return e.many(t,n,r)},off:function(t,n){return e.off(t,n)},on:function(t,n){return e.on(t,n)},once:function(t,n){return e.once(t,n)}}}()),F2.extend("Rpc",function(){var e={},t="",n={},r=RegExp("^"+F2.Constants.Sockets.EVENT),o=RegExp("^"+F2.Constants.Sockets.RPC),i=RegExp("^"+F2.Constants.Sockets.RPC_CALLBACK),a=RegExp("^"+F2.Constants.Sockets.LOAD),s=RegExp("^"+F2.Constants.Sockets.UI_RPC),l=function(){var e,t=!1,r=[],o=new easyXDM.Socket({onMessage:function(i,s){if(!t&&a.test(i)){i=i.replace(a,"");var l=F2.parse(i);2==l.length&&(e=l[0],n[e.instanceId]={config:e,socket:o},F2.registerApps([e],[l[1]]),jQuery.each(r,function(){p(e,i,s)}),t=!0)}else t?p(e,i,s):r.push(i)}})},c=function(e,n){var r=jQuery(e.root);if(r.is("."+F2.Constants.Css.APP_CONTAINER)||r.find("."+F2.Constants.Css.APP_CONTAINER),!r.length)return F2.log("Unable to locate app in order to establish secure connection."),void 0;var o={scrolling:"no",style:{width:"100%"}};e.height&&(o.style.height=e.height+"px");var i=new easyXDM.Socket({remote:t,container:r.get(0),props:o,onMessage:function(t,n){p(e,t,n)},onReady:function(){i.postMessage(F2.Constants.Sockets.LOAD+F2.stringify([e,n],F2.appConfigReplacer))}});return i},u=function(e,t){return function(){F2.Rpc.call(e,F2.Constants.Sockets.RPC_CALLBACK,t,[].slice.call(arguments).slice(2))}},p=function(t,n){function a(e,t){for(var n=(t+"").split("."),r=0;n.length>r;r++){if(void 0===e[n[r]]){e=void 0;break}e=e[n[r]]}return e}function l(e,t,n){var r=F2.parse(t.replace(e,""));return r.params&&r.params.length&&r.callbacks&&r.callbacks.length&&jQuery.each(r.callbacks,function(e,t){jQuery.each(r.params,function(e,o){t==o&&(r.params[e]=u(n,t))})}),r}var c,p;s.test(n)?(c=l(s,n,t.instanceId),p=a(t.ui,c.functionName),void 0!==p?p.apply(t.ui,c.params):F2.log("Unable to locate UI RPC function: "+c.functionName)):o.test(n)?(c=l(o,n,t.instanceId),p=a(window,c.functionName),void 0!==p?p.apply(p,c.params):F2.log("Unable to locate RPC function: "+c.functionName)):i.test(n)?(c=l(i,n,t.instanceId),void 0!==e[c.functionName]&&(e[c.functionName].apply(e[c.functionName],c.params),delete e[c.functionName])):r.test(n)&&(c=l(r,n,t.instanceId),F2.Events._socketEmit.apply(F2.Events,c))},f=function(t){var n=F2.guid();return e[n]=t,n};return{broadcast:function(e,t){var r=e+F2.stringify(t);jQuery.each(n,function(e,t){t.socket.postMessage(r)})},call:function(e,t,r,o){var i=[];jQuery.each(o,function(e,t){if("function"==typeof t){var n=f(t);o[e]=n,i.push(n)}}),n[e].socket.postMessage(t+F2.stringify({functionName:r,params:o,callbacks:i}))},init:function(e){t=e,t||l()},isRemote:function(e){return void 0!==n[e]&&n[e].config.isSecure&&0===jQuery(n[e].config.root).find("iframe").length},register:function(e,t){e&&t?n[e.instanceId]={config:e,socket:c(e,t)}:F2.log("Unable to register socket connection. Please check container configuration.")}}}()),F2.extend("UI",function(){var e,t=function(e){var t=e,n=jQuery(e.root),r=function(e){e=e||jQuery(t.root).outerHeight(),F2.Rpc.isRemote(t.instanceId)?F2.Rpc.call(t.instanceId,F2.Constants.Sockets.UI_RPC,"updateHeight",[e]):(t.height=e,n.find("iframe").height(t.height))};return{hideMask:function(e){F2.UI.hideMask(t.instanceId,e)},Modals:function(){var e=function(e){return['"].join("")},n=function(e){return['"].join("")};return{alert:function(n,r){return F2.isInit()?(F2.Rpc.isRemote(t.instanceId)?F2.Rpc.call(t.instanceId,F2.Constants.Sockets.UI_RPC,"Modals.alert",[].slice.call(arguments)):jQuery(e(n)).on("show",function(){var e=this;jQuery(e).find(".btn-primary").on("click",function(){jQuery(e).modal("hide").remove(),(r||jQuery.noop)()})}).modal({backdrop:!0}),void 0):(F2.log("F2.init() must be called before F2.UI.Modals.alert()"),void 0)},confirm:function(e,r,o){return F2.isInit()?(F2.Rpc.isRemote(t.instanceId)?F2.Rpc.call(t.instanceId,F2.Constants.Sockets.UI_RPC,"Modals.confirm",[].slice.call(arguments)):jQuery(n(e)).on("show",function(){var e=this;jQuery(e).find(".btn-ok").on("click",function(){jQuery(e).modal("hide").remove(),(r||jQuery.noop)()}),jQuery(e).find(".btn-cancel").on("click",function(){jQuery(e).modal("hide").remove(),(o||jQuery.noop)()})}).modal({backdrop:!0}),void 0):(F2.log("F2.init() must be called before F2.UI.Modals.confirm()"),void 0)}}}(),setTitle:function(e){F2.Rpc.isRemote(t.instanceId)?F2.Rpc.call(t.instanceId,F2.Constants.Sockets.UI_RPC,"setTitle",[e]):jQuery(t.root).find("."+F2.Constants.Css.APP_TITLE).text(e)},showMask:function(e,n){F2.UI.showMask(t.instanceId,e,n)},updateHeight:r,Views:function(){var e=new EventEmitter2,o=/change/i;e.setMaxListeners(0);var i=function(e){return o.test(e)?!0:(F2.log('"'+e+'" is not a valid F2.UI.Views event name'),!1)};return{change:function(o){"function"==typeof o?this.on("change",o):"string"==typeof o&&(t.isSecure&&!F2.Rpc.isRemote(t.instanceId)?F2.Rpc.call(t.instanceId,F2.Constants.Sockets.UI_RPC,"Views.change",[].slice.call(arguments)):F2.inArray(o,t.views)&&(jQuery("."+F2.Constants.Css.APP_VIEW,n).addClass("hide").filter('[data-f2-view="'+o+'"]',n).removeClass("hide"),r(),e.emit("change",o)))},off:function(t,n){i(t)&&e.off(t,n)},on:function(t,n){i(t)&&e.on(t,n)}}}()}};return t.hideMask=function(e,t){if(!F2.isInit())return F2.log("F2.init() must be called before F2.UI.hideMask()"),void 0;if(F2.Rpc.isRemote(e)&&!jQuery(t).is("."+F2.Constants.Css.APP))F2.Rpc.call(e,F2.Constants.Sockets.RPC,"F2.UI.hideMask",[e,jQuery(t).selector]);else{var n=jQuery(t);n.find("> ."+F2.Constants.Css.MASK).remove(),n.removeClass(F2.Constants.Css.MASK_CONTAINER),n.data(F2.Constants.Css.MASK_CONTAINER)&&n.css({position:"static"})}},t.init=function(t){e=t,e.UI=jQuery.extend(!0,{},F2.ContainerConfig.UI,e.UI||{})},t.showMask=function(t,n,r){if(!F2.isInit())return F2.log("F2.init() must be called before F2.UI.showMask()"),void 0;if(F2.Rpc.isRemote(t)&&jQuery(n).is("."+F2.Constants.Css.APP))F2.Rpc.call(t,F2.Constants.Sockets.RPC,"F2.UI.showMask",[t,jQuery(n).selector,r]);else{r&&!e.UI.Mask.loadingIcon&&F2.log("Unable to display loading icon. Please set F2.ContainerConfig.UI.Mask.loadingIcon when calling F2.init();");var o=jQuery(n).addClass(F2.Constants.Css.MASK_CONTAINER),i=jQuery("
                              ").height("100%").width("100%").addClass(F2.Constants.Css.MASK);e.UI.Mask.useClasses||i.css({"background-color":e.UI.Mask.backgroundColor,"background-image":e.UI.Mask.loadingIcon?"url("+e.UI.Mask.loadingIcon+")":"","background-position":"50% 50%","background-repeat":"no-repeat",display:"block",left:0,"min-height":30,padding:0,position:"absolute",top:0,"z-index":e.UI.Mask.zIndex,filter:"alpha(opacity="+100*e.UI.Mask.opacity+")",opacity:e.UI.Mask.opacity}),"static"===o.css("position")&&(o.css({position:"relative"}),o.data(F2.Constants.Css.MASK_CONTAINER,!0)),o.append(i)}},t}()),F2.extend("",function(){var _apps={},_config=!1,_bUsesAppHandlers=!1,_sAppHandlerToken=F2.AppHandlers.__f2GetToken(),_afterAppRender=function(e,t){var n=_config.afterAppRender||function(e,t){return jQuery(t).appendTo("body")},r=n(e,t);return _config.afterAppRender&&!r?(F2.log("F2.ContainerConfig.afterAppRender() must return the DOM Element that contains the app"),void 0):(jQuery(r).addClass(F2.Constants.Css.APP),r.get(0))},_appRender=function(e,t){return t=_outerHtml(jQuery(t).addClass(F2.Constants.Css.APP_CONTAINER+" "+e.appId)),_config.appRender&&(t=_config.appRender(e,t)),_outerHtml(t)},_beforeAppRender=function(e){var t=_config.beforeAppRender||jQuery.noop;return t(e)},_appScriptLoadFailed=function(e,t){var n=_config.appScriptLoadFailed||jQuery.noop;return n(e,t)},_createAppConfig=function(e){return e=jQuery.extend(!0,{},e),e.instanceId=e.instanceId||F2.guid(),e.views=e.views||[],F2.inArray(F2.Constants.Views.HOME,e.views)||e.views.push(F2.Constants.Views.HOME),e},_hydrateContainerConfig=function(e){e.scriptErrorTimeout||(e.scriptErrorTimeout=F2.ContainerConfig.scriptErrorTimeout),e.debugMode!==!0&&(e.debugMode=F2.ContainerConfig.debugMode)},_initAppEvents=function(e){jQuery(e.root).on("click","."+F2.Constants.Css.APP_VIEW_TRIGGER+"["+F2.Constants.Views.DATA_ATTRIBUTE+"]",function(t){t.preventDefault();var n=jQuery(this).attr(F2.Constants.Views.DATA_ATTRIBUTE).toLowerCase();n==F2.Constants.Views.REMOVE?F2.removeApp(e.instanceId):e.ui.Views.change(n)})},_initContainerEvents=function(){var e,t=function(){F2.Events.emit(F2.Constants.Events.CONTAINER_WIDTH_CHANGE)};jQuery(window).on("resize",function(){clearTimeout(e),e=setTimeout(t,100)})},_isInit=function(){return!!_config},_createAppInstance=function(e,t){e.ui=new F2.UI(e),void 0!==F2.Apps[e.appId]&&("function"==typeof F2.Apps[e.appId]?setTimeout(function(){_apps[e.instanceId].app=new F2.Apps[e.appId](e,t,e.root),void 0!==_apps[e.instanceId].app.init&&_apps[e.instanceId].app.init()},0):F2.log("app initialization class is defined but not a function. ("+e.appId+")"))},_loadApps=function(appConfigs,appManifest){if(appConfigs=[].concat(appConfigs),1==appConfigs.length&&appConfigs[0].isSecure&&!_config.isSecureAppPage)return _loadSecureApp(appConfigs[0],appManifest),void 0;if(appConfigs.length!=appManifest.apps.length)return F2.log("The number of apps defined in the AppManifest do not match the number requested.",appManifest),void 0;var scripts=appManifest.scripts||[],styles=appManifest.styles||[],inlines=appManifest.inlineScripts||[],scriptCount=scripts.length,scriptsLoaded=0,appInit=function(){jQuery.each(appConfigs,function(e,t){_createAppInstance(t,appManifest.apps[e])})},isFileReady=function(e){return!e||"loaded"==e||"complete"==e||"uninitialized"==e},_onload=function(e){if("load"==e.type||isFileReady((e.currentTarget||e.srcElement).readyState)){var t=e.currentTarget||e.srcElement;t.detachEvent?t.detachEvent("onreadystatechange",_onload):(removeEventListener(t,_onload,"load"),removeEventListener(t,_error,"error"))}++scriptsLoaded==scriptCount&&(evalInlines(),appInit())},_error=function(e){setTimeout(function(){var t={src:e.target.src,appId:appConfigs[0].appId};F2.log("Script defined in '"+t.appId+"' failed to load '"+t.src+"'"),F2.Events.emit("RESOURCE_FAILED_TO_LOAD",t),_bUsesAppHandlers?F2.AppHandlers.__trigger(_sAppHandlerToken,F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED,appConfigs[0],t.src):_appScriptLoadFailed(appConfigs[0],t.src)},_config.scriptErrorTimeout)},evalInlines=function(){jQuery.each(inlines,function(i,e){try{eval(e)}catch(exception){F2.log("Error loading inline script: "+exception+"\n\n"+e),_bUsesAppHandlers?F2.AppHandlers.__trigger(_sAppHandlerToken,F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED,appConfigs[0],exception):_appScriptLoadFailed(appConfigs[0],exception)}})},stylesFragment=null,useCreateStyleSheet=!!document.createStyleSheet;jQuery.each(styles,function(e,t){useCreateStyleSheet?document.createStyleSheet(t):(stylesFragment=stylesFragment||[],stylesFragment.push(''))}),stylesFragment&&jQuery("head").append(stylesFragment.join("")),jQuery.each(appManifest.apps,function(e,t){if(_bUsesAppHandlers){F2.AppHandlers.__trigger(_sAppHandlerToken,F2.Constants.AppHandlers.APP_RENDER,appConfigs[e],_outerHtml(t.html));var n=appConfigs[e].appId;if(!appConfigs[e].root)throw"Root for "+n+" must be a native DOM element and cannot be null or undefined. Check your AppHandler callbacks to ensure you have set App root to a native DOM element.";var r=jQuery(appConfigs[e].root);if(0===r.parents("body:first").length)throw"App root for "+n+" was not appended to the DOM. Check your AppHandler callbacks to ensure you have rendered the app root to the DOM.";if(F2.AppHandlers.__trigger(_sAppHandlerToken,F2.Constants.AppHandlers.APP_RENDER_AFTER,appConfigs[e]),!F2.isNativeDOMNode(appConfigs[e].root))throw"App root for "+n+" must be a native DOM element. Check your AppHandler callbacks to ensure you have set app root to a native DOM element.";r.addClass(F2.Constants.Css.APP_CONTAINER+" "+n)}else appConfigs[e].root=_afterAppRender(appConfigs[e],_appRender(appConfigs[e],t.html));_initAppEvents(appConfigs[e])}),jQuery.each(scripts,function(e,t){var n=document,r=n.createElement("script"),o=t;_config.debugMode&&(o+="?cachebuster="+(new Date).getTime()),r.async=!1,r.src=o,r.type="text/javascript",r.charset="utf-8",!r.attachEvent||r.attachEvent.toString&&0>(""+r.attachEvent).indexOf("[native code")?(r.addEventListener("load",_onload,!1),r.addEventListener("error",_error,!1)):r.attachEvent("onreadystatechange",_onload),n.body.appendChild(r)}),scriptCount||(evalInlines(),appInit())},_loadSecureApp=function(e,t){if(_config.secureAppPagePath){if(_bUsesAppHandlers){var n=jQuery(e.root);if(F2.AppHandlers.__trigger(_sAppHandlerToken,F2.Constants.AppHandlers.APP_RENDER,e,t.html),0===n.parents("body:first").length)throw"App was never rendered on the page. Please check your AppHandler callbacks to ensure you have rendered the app root to the DOM.";if(F2.AppHandlers.__trigger(_sAppHandlerToken,F2.Constants.AppHandlers.APP_RENDER_AFTER,e),!e.root)throw"App Root must be a native dom node and can not be null or undefined. Please check your AppHandler callbacks to ensure you have set App Root to a native dom node.";if(!F2.isNativeDOMNode(e.root))throw"App Root must be a native dom node. Please check your AppHandler callbacks to ensure you have set App Root to a native dom node.";jQuery(e.root).addClass(F2.Constants.Css.APP_CONTAINER+" "+e.appId)}else e.root=_afterAppRender(e,_appRender(e,"
                              "));e.ui=new F2.UI(e),_initAppEvents(e),F2.Rpc.register(e,t)}else F2.log('Unable to load secure app: "secureAppPagePath" is not defined in F2.ContainerConfig.')},_outerHtml=function(e){return jQuery("
                              ").append(e).html()},_validateApp=function(e){return e.appId?e.root||e.manifestUrl?!0:(F2.log('"manifestUrl" missing from app object'),!1):(F2.log('"appId" missing from app object'),!1)},_validateContainerConfig=function(){if(_config&&_config.xhr){if("function"!=typeof _config.xhr&&"object"!=typeof _config.xhr)throw"ContainerConfig.xhr should be a function or an object";if(_config.xhr.dataType&&"function"!=typeof _config.xhr.dataType)throw"ContainerConfig.xhr.dataType should be a function";if(_config.xhr.type&&"function"!=typeof _config.xhr.type)throw"ContainerConfig.xhr.type should be a function";if(_config.xhr.url&&"function"!=typeof _config.xhr.url)throw"ContainerConfig.xhr.url should be a function"}return!0};return{getContainerState:function(){return _isInit()?jQuery.map(_apps,function(e){return{appId:e.config.appId}}):(F2.log("F2.init() must be called before F2.getContainerState()"),void 0)},init:function(e){_config=e||{},_validateContainerConfig(),_hydrateContainerConfig(_config),_bUsesAppHandlers=!(_config.beforeAppRender||_config.appRender||_config.afterAppRender||_config.appScriptLoadFailed),(_config.secureAppPagePath||_config.isSecureAppPage)&&F2.Rpc.init(_config.secureAppPagePath?_config.secureAppPagePath:!1),F2.UI.init(_config),_config.isSecureAppPage||_initContainerEvents()},isInit:_isInit,registerApps:function(e,t){if(!_isInit())return F2.log("F2.init() must be called before F2.registerApps()"),void 0;if(!e)return F2.log("At least one AppConfig must be passed when calling F2.registerApps()"),void 0;var n=[],r={},o={},i=!1;return e=[].concat(e),t=[].concat(t||[]),i=!!t.length,e.length?e.length&&i&&e.length!=t.length?(F2.log('The length of "apps" does not equal the length of "appManifests"'),void 0):(jQuery.each(e,function(e,o){if(o=_createAppConfig(o),o.root=o.root||null,_validateApp(o)){if(_apps[o.instanceId]={config:o},o.root){if(!o.root&&"string"!=typeof o.root&&!F2.isNativeDOMNode(o.root))throw F2.log("AppConfig invalid for pre-load, not a valid string and not dom node"),F2.log("AppConfig instance:",o),"Preloaded appConfig.root property must be a native dom node or a string representing a sizzle selector. Please check your inputs and try again.";if(1!=jQuery(o.root).length)throw F2.log("AppConfig invalid for pre-load, root not unique"),F2.log("AppConfig instance:",o),F2.log("Number of dom node instances:",jQuery(o.root).length),"Preloaded appConfig.root property must map to a unique dom node. Please check your inputs and try again.";return _createAppInstance(o),_initAppEvents(o),void 0}_bUsesAppHandlers?(F2.AppHandlers.__trigger(_sAppHandlerToken,F2.Constants.AppHandlers.APP_CREATE_ROOT,o),F2.AppHandlers.__trigger(_sAppHandlerToken,F2.Constants.AppHandlers.APP_RENDER_BEFORE,o)):o.root=_beforeAppRender(o),i?_loadApps(o,t[e]):o.enableBatchRequests&&!o.isSecure?(r[o.manifestUrl.toLowerCase()]=r[o.manifestUrl.toLowerCase()]||[],r[o.manifestUrl.toLowerCase()].push(o)):n.push({apps:[o],url:o.manifestUrl})}}),i||(jQuery.each(r,function(e,t){n.push({url:e,apps:t})}),jQuery.each(n,function(e,t){var n=F2.Constants.JSONP_CALLBACK+t.apps[0].appId;o[n]=o[n]||[],o[n].push(t)}),jQuery.each(o,function(e,t){var n=function(r,o){if(o){var i=o.url,a="GET",s="jsonp",l=function(){n(e,t.pop())},c=function(){jQuery.each(o.apps,function(e,t){F2.log("Removed failed "+t.name+" app",t),F2.removeApp(t.instanceId)})},u=function(e){_loadApps(o.apps,e)};if(_config.xhr&&_config.xhr.dataType&&(s=_config.xhr.dataType(o.url,o.apps),"string"!=typeof s))throw"ContainerConfig.xhr.dataType should return a string";if(_config.xhr&&_config.xhr.type&&(a=_config.xhr.type(o.url,o.apps),"string"!=typeof a))throw"ContainerConfig.xhr.type should return a string";if(_config.xhr&&_config.xhr.url&&(i=_config.xhr.url(o.url,o.apps),"string"!=typeof i))throw"ContainerConfig.xhr.url should return a string";var p=_config.xhr;"function"!=typeof p&&(p=function(e,t,n,i,l){jQuery.ajax({url:e,type:a,data:{params:F2.stringify(o.apps,F2.appConfigReplacer)},jsonp:!1,jsonpCallback:r,dataType:s,success:n,error:function(e,t,n){F2.log("Failed to load app(s)",""+n,o.apps),i()},complete:l})}),p(i,o.apps,u,c,l)}};n(e,t.pop())})),void 0):(F2.log("At least one AppConfig must be passed when calling F2.registerApps()"),void 0)},removeAllApps:function(){return _isInit()?(jQuery.each(_apps,function(e,t){F2.removeApp(t.config.instanceId)}),void 0):(F2.log("F2.init() must be called before F2.removeAllApps()"),void 0)},removeApp:function(e){return _isInit()?(_apps[e]&&(F2.AppHandlers.__trigger(_sAppHandlerToken,F2.Constants.AppHandlers.APP_DESTROY_BEFORE,_apps[e]),F2.AppHandlers.__trigger(_sAppHandlerToken,F2.Constants.AppHandlers.APP_DESTROY,_apps[e]),F2.AppHandlers.__trigger(_sAppHandlerToken,F2.Constants.AppHandlers.APP_DESTROY_AFTER,_apps[e]),delete _apps[e]),void 0):(F2.log("F2.init() must be called before F2.removeApp()"),void 0)}}}()),exports.F2=F2,"undefined"!=typeof define&&define.amd&&define(function(){return F2})}})("undefined"!=typeof exports?exports:window); \ No newline at end of file diff --git a/ajax/libs/F2/1.3.1/f2.js b/ajax/libs/F2/1.3.1/f2.js new file mode 100644 index 000000000..a4b48664d --- /dev/null +++ b/ajax/libs/F2/1.3.1/f2.js @@ -0,0 +1,16841 @@ +;(function(exports) { + + if (exports.F2 && !exports.F2_TESTING_MODE) { + return; + } + +/*! + JSON.org requires the following notice to accompany json2: + + Copyright (c) 2002 JSON.org + + http://json.org + + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + + The Software shall be used for Good, not Evil. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + IN THE SOFTWARE. +*/ +/* + This code should be minified before deployment. + See http://javascript.crockford.com/jsmin.html + + USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO + NOT CONTROL. + + + This file creates a global JSON object containing two methods: stringify + and parse. + + JSON.stringify(value, replacer, space) + value any JavaScript value, usually an object or array. + + replacer an optional parameter that determines how object + values are stringified for objects. It can be a + function or an array of strings. + + space an optional parameter that specifies the indentation + of nested structures. If it is omitted, the text will + be packed without extra whitespace. If it is a number, + it will specify the number of spaces to indent at each + level. If it is a string (such as '\t' or ' '), + it contains the characters used to indent at each level. + + This method produces a JSON text from a JavaScript value. + + When an object value is found, if the object contains a toJSON + method, its toJSON method will be called and the result will be + stringified. A toJSON method does not serialize: it returns the + value represented by the name/value pair that should be serialized, + or undefined if nothing should be serialized. The toJSON method + will be passed the key associated with the value, and this will be + bound to the value + + For example, this would serialize Dates as ISO strings. + + Date.prototype.toJSON = function (key) { + function f(n) { + // Format integers to have at least two digits. + return n < 10 ? '0' + n : n; + } + + return this.getUTCFullYear() + '-' + + f(this.getUTCMonth() + 1) + '-' + + f(this.getUTCDate()) + 'T' + + f(this.getUTCHours()) + ':' + + f(this.getUTCMinutes()) + ':' + + f(this.getUTCSeconds()) + 'Z'; + }; + + You can provide an optional replacer method. It will be passed the + key and value of each member, with this bound to the containing + object. The value that is returned from your method will be + serialized. If your method returns undefined, then the member will + be excluded from the serialization. + + If the replacer parameter is an array of strings, then it will be + used to select the members to be serialized. It filters the results + such that only members with keys listed in the replacer array are + stringified. + + Values that do not have JSON representations, such as undefined or + functions, will not be serialized. Such values in objects will be + dropped; in arrays they will be replaced with null. You can use + a replacer function to replace those with JSON values. + JSON.stringify(undefined) returns undefined. + + The optional space parameter produces a stringification of the + value that is filled with line breaks and indentation to make it + easier to read. + + If the space parameter is a non-empty string, then that string will + be used for indentation. If the space parameter is a number, then + the indentation will be that many spaces. + + Example: + + text = JSON.stringify(['e', {pluribus: 'unum'}]); + // text is '["e",{"pluribus":"unum"}]' + + + text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); + // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' + + text = JSON.stringify([new Date()], function (key, value) { + return this[key] instanceof Date ? + 'Date(' + this[key] + ')' : value; + }); + // text is '["Date(---current time---)"]' + + + JSON.parse(text, reviver) + This method parses a JSON text to produce an object or array. + It can throw a SyntaxError exception. + + The optional reviver parameter is a function that can filter and + transform the results. It receives each of the keys and values, + and its return value is used instead of the original value. + If it returns what it received, then the structure is not modified. + If it returns undefined then the member is deleted. + + Example: + + // Parse the text. Values that look like ISO date strings will + // be converted to Date objects. + + myData = JSON.parse(text, function (key, value) { + var a; + if (typeof value === 'string') { + a = +/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); + if (a) { + return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], + +a[5], +a[6])); + } + } + return value; + }); + + myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { + var d; + if (typeof value === 'string' && + value.slice(0, 5) === 'Date(' && + value.slice(-1) === ')') { + d = new Date(value.slice(5, -1)); + if (d) { + return d; + } + } + return value; + }); + + + This is a reference implementation. You are free to copy, modify, or + redistribute. +*/ + +/*jslint evil: true, regexp: true */ + +/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, + call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, + getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, + lastIndex, length, parse, prototype, push, replace, slice, stringify, + test, toJSON, toString, valueOf +*/ + + +// Create a JSON object only if one does not already exist. We create the +// methods in a closure to avoid creating global variables. + +if (typeof JSON !== 'object') { + JSON = {}; +} + +(function () { + 'use strict'; + + function f(n) { + // Format integers to have at least two digits. + return n < 10 ? '0' + n : n; + } + + if (typeof Date.prototype.toJSON !== 'function') { + + Date.prototype.toJSON = function (key) { + + return isFinite(this.valueOf()) + ? this.getUTCFullYear() + '-' + + f(this.getUTCMonth() + 1) + '-' + + f(this.getUTCDate()) + 'T' + + f(this.getUTCHours()) + ':' + + f(this.getUTCMinutes()) + ':' + + f(this.getUTCSeconds()) + 'Z' + : null; + }; + + String.prototype.toJSON = + Number.prototype.toJSON = + Boolean.prototype.toJSON = function (key) { + return this.valueOf(); + }; + } + + var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, + escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, + gap, + indent, + meta = { // table of character substitutions + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + '"' : '\\"', + '\\': '\\\\' + }, + rep; + + + function quote(string) { + +// If the string contains no control characters, no quote characters, and no +// backslash characters, then we can safely slap some quotes around it. +// Otherwise we must also replace the offending characters with safe escape +// sequences. + + escapable.lastIndex = 0; + return escapable.test(string) ? '"' + string.replace(escapable, function (a) { + var c = meta[a]; + return typeof c === 'string' + ? c + : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }) + '"' : '"' + string + '"'; + } + + + function str(key, holder) { + +// Produce a string from holder[key]. + + var i, // The loop counter. + k, // The member key. + v, // The member value. + length, + mind = gap, + partial, + value = holder[key]; + +// If the value has a toJSON method, call it to obtain a replacement value. + + if (value && typeof value === 'object' && + typeof value.toJSON === 'function') { + value = value.toJSON(key); + } + +// If we were called with a replacer function, then call the replacer to +// obtain a replacement value. + + if (typeof rep === 'function') { + value = rep.call(holder, key, value); + } + +// What happens next depends on the value's type. + + switch (typeof value) { + case 'string': + return quote(value); + + case 'number': + +// JSON numbers must be finite. Encode non-finite numbers as null. + + return isFinite(value) ? String(value) : 'null'; + + case 'boolean': + case 'null': + +// If the value is a boolean or null, convert it to a string. Note: +// typeof null does not produce 'null'. The case is included here in +// the remote chance that this gets fixed someday. + + return String(value); + +// If the type is 'object', we might be dealing with an object or an array or +// null. + + case 'object': + +// Due to a specification blunder in ECMAScript, typeof null is 'object', +// so watch out for that case. + + if (!value) { + return 'null'; + } + +// Make an array to hold the partial results of stringifying this object value. + + gap += indent; + partial = []; + +// Is the value an array? + + if (Object.prototype.toString.apply(value) === '[object Array]') { + +// The value is an array. Stringify every element. Use null as a placeholder +// for non-JSON values. + + length = value.length; + for (i = 0; i < length; i += 1) { + partial[i] = str(i, value) || 'null'; + } + +// Join all of the elements together, separated with commas, and wrap them in +// brackets. + + v = partial.length === 0 + ? '[]' + : gap + ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' + : '[' + partial.join(',') + ']'; + gap = mind; + return v; + } + +// If the replacer is an array, use it to select the members to be stringified. + + if (rep && typeof rep === 'object') { + length = rep.length; + for (i = 0; i < length; i += 1) { + if (typeof rep[i] === 'string') { + k = rep[i]; + v = str(k, value); + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } else { + +// Otherwise, iterate through all of the keys in the object. + + for (k in value) { + if (Object.prototype.hasOwnProperty.call(value, k)) { + v = str(k, value); + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } + +// Join all of the member texts together, separated with commas, +// and wrap them in braces. + + v = partial.length === 0 + ? '{}' + : gap + ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' + : '{' + partial.join(',') + '}'; + gap = mind; + return v; + } + } + +// If the JSON object does not yet have a stringify method, give it one. + + if (typeof JSON.stringify !== 'function') { + JSON.stringify = function (value, replacer, space) { + +// The stringify method takes a value and an optional replacer, and an optional +// space parameter, and returns a JSON text. The replacer can be a function +// that can replace values, or an array of strings that will select the keys. +// A default replacer method can be provided. Use of the space parameter can +// produce text that is more easily readable. + + var i; + gap = ''; + indent = ''; + +// If the space parameter is a number, make an indent string containing that +// many spaces. + + if (typeof space === 'number') { + for (i = 0; i < space; i += 1) { + indent += ' '; + } + +// If the space parameter is a string, it will be used as the indent string. + + } else if (typeof space === 'string') { + indent = space; + } + +// If there is a replacer, it must be a function or an array. +// Otherwise, throw an error. + + rep = replacer; + if (replacer && typeof replacer !== 'function' && + (typeof replacer !== 'object' || + typeof replacer.length !== 'number')) { + throw new Error('JSON.stringify'); + } + +// Make a fake root object containing our value under the key of ''. +// Return the result of stringifying the value. + + return str('', {'': value}); + }; + } + + +// If the JSON object does not yet have a parse method, give it one. + + if (typeof JSON.parse !== 'function') { + JSON.parse = function (text, reviver) { + +// The parse method takes a text and an optional reviver function, and returns +// a JavaScript value if the text is a valid JSON text. + + var j; + + function walk(holder, key) { + +// The walk method is used to recursively walk the resulting structure so +// that modifications can be made. + + var k, v, value = holder[key]; + if (value && typeof value === 'object') { + for (k in value) { + if (Object.prototype.hasOwnProperty.call(value, k)) { + v = walk(value, k); + if (v !== undefined) { + value[k] = v; + } else { + delete value[k]; + } + } + } + } + return reviver.call(holder, key, value); + } + + +// Parsing happens in four stages. In the first stage, we replace certain +// Unicode characters with escape sequences. JavaScript handles many characters +// incorrectly, either silently deleting them, or treating them as line endings. + + text = String(text); + cx.lastIndex = 0; + if (cx.test(text)) { + text = text.replace(cx, function (a) { + return '\\u' + + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }); + } + +// In the second stage, we run the text against regular expressions that look +// for non-JSON patterns. We are especially concerned with '()' and 'new' +// because they can cause invocation, and '=' because it can cause mutation. +// But just to be safe, we want to reject all unexpected forms. + +// We split the second stage into 4 regexp operations in order to work around +// crippling inefficiencies in IE's and Safari's regexp engines. First we +// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we +// replace all simple value tokens with ']' characters. Third, we delete all +// open brackets that follow a colon or comma or that begin the text. Finally, +// we look to see that the remaining characters are only whitespace or ']' or +// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. + + if (/^[\],:{}\s]*$/ + .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') + .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') + .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { + +// In the third stage we use the eval function to compile the text into a +// JavaScript structure. The '{' operator is subject to a syntactic ambiguity +// in JavaScript: it can begin a block or an object literal. We wrap the text +// in parens to eliminate the ambiguity. + + j = eval('(' + text + ')'); + +// In the optional fourth stage, we recursively walk the new structure, passing +// each name/value pair to a reviver function for possible transformation. + + return typeof reviver === 'function' + ? walk({'': j}, '') + : j; + } + +// If the text is not JSON parseable, then a SyntaxError is thrown. + + throw new SyntaxError('JSON.parse'); + }; + } +}()); + +/*! + * jQuery JavaScript Library v1.8.3 + * The jQuery Foundation and other contributors require the following notice to accompany jQuery: + * + * Copyright (c) 2013 jQuery Foundation and other contributors + * + * http://jquery.com + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, + * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software + * is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR + * IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +(function( window, undefined ) { +var + // A central reference to the root jQuery(document) + rootjQuery, + + // The deferred used on DOM ready + readyList, + + // Use the correct document accordingly with window argument (sandbox) + document = window.document, + location = window.location, + navigator = window.navigator, + + // Map over jQuery in case of overwrite + _jQuery = window.jQuery, + + // Map over the $ in case of overwrite + _$ = window.$, + + // Save a reference to some core methods + core_push = Array.prototype.push, + core_slice = Array.prototype.slice, + core_indexOf = Array.prototype.indexOf, + core_toString = Object.prototype.toString, + core_hasOwn = Object.prototype.hasOwnProperty, + core_trim = String.prototype.trim, + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' + return new jQuery.fn.init( selector, context, rootjQuery ); + }, + + // Used for matching numbers + core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source, + + // Used for detecting and trimming whitespace + core_rnotwhite = /\S/, + core_rspace = /\s+/, + + // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) + rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, + + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/, + + // Match a standalone tag + rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, + + // JSON RegExp + rvalidchars = /^[\],:{}\s]*$/, + rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, + rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, + rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g, + + // Matches dashed string for camelizing + rmsPrefix = /^-ms-/, + rdashAlpha = /-([\da-z])/gi, + + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return ( letter + "" ).toUpperCase(); + }, + + // The ready event handler and self cleanup method + DOMContentLoaded = function() { + if ( document.addEventListener ) { + document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + jQuery.ready(); + } else if ( document.readyState === "complete" ) { + // we're here because readyState === "complete" in oldIE + // which is good enough for us to call the dom ready! + document.detachEvent( "onreadystatechange", DOMContentLoaded ); + jQuery.ready(); + } + }, + + // [[Class]] -> type pairs + class2type = {}; + +jQuery.fn = jQuery.prototype = { + constructor: jQuery, + init: function( selector, context, rootjQuery ) { + var match, elem, ret, doc; + + // Handle $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Handle $(DOMElement) + if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + } + + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = rquickExpr.exec( selector ); + } + + // Match html or make sure no context is specified for #id + if ( match && (match[1] || !context) ) { + + // HANDLE: $(html) -> $(array) + if ( match[1] ) { + context = context instanceof jQuery ? context[0] : context; + doc = ( context && context.nodeType ? context.ownerDocument || context : document ); + + // scripts is true for back-compat + selector = jQuery.parseHTML( match[1], doc, true ); + if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { + this.attr.call( selector, context, true ); + } + + return jQuery.merge( this, selector ); + + // HANDLE: $(#id) + } else { + elem = document.getElementById( match[2] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id !== match[2] ) { + return rootjQuery.find( selector ); + } + + // Otherwise, we inject the element directly into the jQuery object + this.length = 1; + this[0] = elem; + } + + this.context = document; + this.selector = selector; + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || rootjQuery ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return rootjQuery.ready( selector ); + } + + if ( selector.selector !== undefined ) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); + }, + + // Start with an empty selector + selector: "", + + // The current version of jQuery being used + jquery: "1.8.3", + + // The default length of a jQuery object is 0 + length: 0, + + // The number of elements contained in the matched element set + size: function() { + return this.length; + }, + + toArray: function() { + return core_slice.call( this ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num == null ? + + // Return a 'clean' array + this.toArray() : + + // Return just the object + ( num < 0 ? this[ this.length + num ] : this[ num ] ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems, name, selector ) { + + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + ret.context = this.context; + + if ( name === "find" ) { + ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; + } else if ( name ) { + ret.selector = this.selector + "." + name + "(" + selector + ")"; + } + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each: function( callback, args ) { + return jQuery.each( this, callback, args ); + }, + + ready: function( fn ) { + // Add the callback + jQuery.ready.promise().done( fn ); + + return this; + }, + + eq: function( i ) { + i = +i; + return i === -1 ? + this.slice( i ) : + this.slice( i, i + 1 ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + slice: function() { + return this.pushStack( core_slice.apply( this, arguments ), + "slice", core_slice.call(arguments).join(",") ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function( elem, i ) { + return callback.call( elem, i, elem ); + })); + }, + + end: function() { + return this.prevObject || this.constructor(null); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: core_push, + sort: [].sort, + splice: [].splice +}; + +// Give the init function the jQuery prototype for later instantiation +jQuery.fn.init.prototype = jQuery.fn; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + target = {}; + } + + // extend jQuery itself if only one argument is passed + if ( length === i ) { + target = this; + --i; + } + + for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) { + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray(src) ? src : []; + + } else { + clone = src && jQuery.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend({ + noConflict: function( deep ) { + if ( window.$ === jQuery ) { + window.$ = _$; + } + + if ( deep && window.jQuery === jQuery ) { + window.jQuery = _jQuery; + } + + return jQuery; + }, + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Hold (or release) the ready event + holdReady: function( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); + } + }, + + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } + + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( !document.body ) { + return setTimeout( jQuery.ready, 1 ); + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.trigger ) { + jQuery( document ).trigger("ready").off("ready"); + } + }, + + // See test/unit/core.js for details concerning isFunction. + // Since version 1.3, DOM methods and functions like alert + // aren't supported. They return false on IE (#2968). + isFunction: function( obj ) { + return jQuery.type(obj) === "function"; + }, + + isArray: Array.isArray || function( obj ) { + return jQuery.type(obj) === "array"; + }, + + isWindow: function( obj ) { + return obj != null && obj == obj.window; + }, + + isNumeric: function( obj ) { + return !isNaN( parseFloat(obj) ) && isFinite( obj ); + }, + + type: function( obj ) { + return obj == null ? + String( obj ) : + class2type[ core_toString.call(obj) ] || "object"; + }, + + isPlainObject: function( obj ) { + // Must be an Object. + // Because of IE, we also have to check the presence of the constructor property. + // Make sure that DOM nodes and window objects don't pass through, as well + if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } + + try { + // Not own constructor property must be Object + if ( obj.constructor && + !core_hasOwn.call(obj, "constructor") && + !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { + return false; + } + } catch ( e ) { + // IE8,9 Will throw exceptions on certain host objects #9897 + return false; + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + + var key; + for ( key in obj ) {} + + return key === undefined || core_hasOwn.call( obj, key ); + }, + + isEmptyObject: function( obj ) { + var name; + for ( name in obj ) { + return false; + } + return true; + }, + + error: function( msg ) { + throw new Error( msg ); + }, + + // data: string of html + // context (optional): If specified, the fragment will be created in this context, defaults to document + // scripts (optional): If true, will include scripts passed in the html string + parseHTML: function( data, context, scripts ) { + var parsed; + if ( !data || typeof data !== "string" ) { + return null; + } + if ( typeof context === "boolean" ) { + scripts = context; + context = 0; + } + context = context || document; + + // Single tag + if ( (parsed = rsingleTag.exec( data )) ) { + return [ context.createElement( parsed[1] ) ]; + } + + parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] ); + return jQuery.merge( [], + (parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes ); + }, + + parseJSON: function( data ) { + if ( !data || typeof data !== "string") { + return null; + } + + // Make sure leading/trailing whitespace is removed (IE can't handle it) + data = jQuery.trim( data ); + + // Attempt to parse using the native JSON parser first + if ( window.JSON && window.JSON.parse ) { + return window.JSON.parse( data ); + } + + // Make sure the incoming data is actual JSON + // Logic borrowed from http://json.org/json2.js + if ( rvalidchars.test( data.replace( rvalidescape, "@" ) + .replace( rvalidtokens, "]" ) + .replace( rvalidbraces, "")) ) { + + return ( new Function( "return " + data ) )(); + + } + jQuery.error( "Invalid JSON: " + data ); + }, + + // Cross-browser xml parsing + parseXML: function( data ) { + var xml, tmp; + if ( !data || typeof data !== "string" ) { + return null; + } + try { + if ( window.DOMParser ) { // Standard + tmp = new DOMParser(); + xml = tmp.parseFromString( data , "text/xml" ); + } else { // IE + xml = new ActiveXObject( "Microsoft.XMLDOM" ); + xml.async = "false"; + xml.loadXML( data ); + } + } catch( e ) { + xml = undefined; + } + if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { + jQuery.error( "Invalid XML: " + data ); + } + return xml; + }, + + noop: function() {}, + + // Evaluates a script in a global context + // Workarounds based on findings by Jim Driscoll + // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context + globalEval: function( data ) { + if ( data && core_rnotwhite.test( data ) ) { + // We use execScript on Internet Explorer + // We use an anonymous function so that context is window + // rather than jQuery in Firefox + ( window.execScript || function( data ) { + window[ "eval" ].call( window, data ); + } )( data ); + } + }, + + // Convert dashed to camelCase; used by the css and data modules + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + }, + + // args is for internal usage only + each: function( obj, callback, args ) { + var name, + i = 0, + length = obj.length, + isObj = length === undefined || jQuery.isFunction( obj ); + + if ( args ) { + if ( isObj ) { + for ( name in obj ) { + if ( callback.apply( obj[ name ], args ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.apply( obj[ i++ ], args ) === false ) { + break; + } + } + } + + // A special, fast, case for the most common use of each + } else { + if ( isObj ) { + for ( name in obj ) { + if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) { + break; + } + } + } else { + for ( ; i < length; ) { + if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) { + break; + } + } + } + } + + return obj; + }, + + // Use native String.trim function wherever possible + trim: core_trim && !core_trim.call("\uFEFF\xA0") ? + function( text ) { + return text == null ? + "" : + core_trim.call( text ); + } : + + // Otherwise use our own trimming functionality + function( text ) { + return text == null ? + "" : + ( text + "" ).replace( rtrim, "" ); + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var type, + ret = results || []; + + if ( arr != null ) { + // The window, strings (and functions) also have 'length' + // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 + type = jQuery.type( arr ); + + if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) { + core_push.call( ret, arr ); + } else { + jQuery.merge( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + var len; + + if ( arr ) { + if ( core_indexOf ) { + return core_indexOf.call( arr, elem, i ); + } + + len = arr.length; + i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; + + for ( ; i < len; i++ ) { + // Skip accessing in sparse arrays + if ( i in arr && arr[ i ] === elem ) { + return i; + } + } + } + + return -1; + }, + + merge: function( first, second ) { + var l = second.length, + i = first.length, + j = 0; + + if ( typeof l === "number" ) { + for ( ; j < l; j++ ) { + first[ i++ ] = second[ j ]; + } + + } else { + while ( second[j] !== undefined ) { + first[ i++ ] = second[ j++ ]; + } + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, inv ) { + var retVal, + ret = [], + i = 0, + length = elems.length; + inv = !!inv; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + retVal = !!callback( elems[ i ], i ); + if ( inv !== retVal ) { + ret.push( elems[ i ] ); + } + } + + return ret; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var value, key, + ret = [], + i = 0, + length = elems.length, + // jquery objects are treated as arrays + isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; + + // Go through the array, translating each of the items to their + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + + // Go through every key on the object, + } else { + for ( key in elems ) { + value = callback( elems[ key ], key, arg ); + + if ( value != null ) { + ret[ ret.length ] = value; + } + } + } + + // Flatten any nested arrays + return ret.concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + var tmp, args, proxy; + + if ( typeof context === "string" ) { + tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + args = core_slice.call( arguments, 2 ); + proxy = function() { + return fn.apply( context, args.concat( core_slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || jQuery.guid++; + + return proxy; + }, + + // Multifunctional method to get and set values of a collection + // The value/s can optionally be executed if it's a function + access: function( elems, fn, key, value, chainable, emptyGet, pass ) { + var exec, + bulk = key == null, + i = 0, + length = elems.length; + + // Sets many values + if ( key && typeof key === "object" ) { + for ( i in key ) { + jQuery.access( elems, fn, i, key[i], 1, emptyGet, value ); + } + chainable = 1; + + // Sets one value + } else if ( value !== undefined ) { + // Optionally, function values get executed if exec is true + exec = pass === undefined && jQuery.isFunction( value ); + + if ( bulk ) { + // Bulk operations only iterate when executing function values + if ( exec ) { + exec = fn; + fn = function( elem, key, value ) { + return exec.call( jQuery( elem ), value ); + }; + + // Otherwise they run against the entire set + } else { + fn.call( elems, value ); + fn = null; + } + } + + if ( fn ) { + for (; i < length; i++ ) { + fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); + } + } + + chainable = 1; + } + + return chainable ? + elems : + + // Gets + bulk ? + fn.call( elems ) : + length ? fn( elems[0], key ) : emptyGet; + }, + + now: function() { + return ( new Date() ).getTime(); + } +}); + +jQuery.ready.promise = function( obj ) { + if ( !readyList ) { + + readyList = jQuery.Deferred(); + + // Catch cases where $(document).ready() is called after the browser event has already occurred. + // we once tried to use readyState "interactive" here, but it caused issues like the one + // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 + if ( document.readyState === "complete" ) { + // Handle it asynchronously to allow scripts the opportunity to delay ready + setTimeout( jQuery.ready, 1 ); + + // Standards-based browsers support DOMContentLoaded + } else if ( document.addEventListener ) { + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", jQuery.ready, false ); + + // If IE event model is used + } else { + // Ensure firing before onload, maybe late but safe also for iframes + document.attachEvent( "onreadystatechange", DOMContentLoaded ); + + // A fallback to window.onload, that will always work + window.attachEvent( "onload", jQuery.ready ); + + // If IE and not a frame + // continually check to see if the document is ready + var top = false; + + try { + top = window.frameElement == null && document.documentElement; + } catch(e) {} + + if ( top && top.doScroll ) { + (function doScrollCheck() { + if ( !jQuery.isReady ) { + + try { + // Use the trick by Diego Perini + // http://javascript.nwbox.com/IEContentLoaded/ + top.doScroll("left"); + } catch(e) { + return setTimeout( doScrollCheck, 50 ); + } + + // and execute any waiting functions + jQuery.ready(); + } + })(); + } + } + } + return readyList.promise( obj ); +}; + +// Populate the class2type map +jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +}); + +// All jQuery objects should point back to these +rootjQuery = jQuery(document); +// String to Object options format cache +var optionsCache = {}; + +// Convert String-formatted options into Object-formatted ones and store in cache +function createOptions( options ) { + var object = optionsCache[ options ] = {}; + jQuery.each( options.split( core_rspace ), function( _, flag ) { + object[ flag ] = true; + }); + return object; +} + +/* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( options ) { + + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + ( optionsCache[ options ] || createOptions( options ) ) : + jQuery.extend( {}, options ); + + var // Last fire value (for non-forgettable lists) + memory, + // Flag to know if list was already fired + fired, + // Flag to know if list is currently firing + firing, + // First callback to fire (used internally by add and fireWith) + firingStart, + // End of the loop when firing + firingLength, + // Index of currently firing callback (modified by remove if needed) + firingIndex, + // Actual callback list + list = [], + // Stack of fire calls for repeatable lists + stack = !options.once && [], + // Fire callbacks + fire = function( data ) { + memory = options.memory && data; + fired = true; + firingIndex = firingStart || 0; + firingStart = 0; + firingLength = list.length; + firing = true; + for ( ; list && firingIndex < firingLength; firingIndex++ ) { + if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { + memory = false; // To prevent further calls using add + break; + } + } + firing = false; + if ( list ) { + if ( stack ) { + if ( stack.length ) { + fire( stack.shift() ); + } + } else if ( memory ) { + list = []; + } else { + self.disable(); + } + } + }, + // Actual Callbacks object + self = { + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + // First, we save the current length + var start = list.length; + (function add( args ) { + jQuery.each( args, function( _, arg ) { + var type = jQuery.type( arg ); + if ( type === "function" ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && type !== "string" ) { + // Inspect recursively + add( arg ); + } + }); + })( arguments ); + // Do we need to add the callbacks to the + // current firing batch? + if ( firing ) { + firingLength = list.length; + // With memory, if we're not firing then + // we should call right away + } else if ( memory ) { + firingStart = start; + fire( memory ); + } + } + return this; + }, + // Remove a callback from the list + remove: function() { + if ( list ) { + jQuery.each( arguments, function( _, arg ) { + var index; + while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + // Handle firing indexes + if ( firing ) { + if ( index <= firingLength ) { + firingLength--; + } + if ( index <= firingIndex ) { + firingIndex--; + } + } + } + }); + } + return this; + }, + // Control if a given callback is in the list + has: function( fn ) { + return jQuery.inArray( fn, list ) > -1; + }, + // Remove all callbacks from the list + empty: function() { + list = []; + return this; + }, + // Have the list do nothing anymore + disable: function() { + list = stack = memory = undefined; + return this; + }, + // Is it disabled? + disabled: function() { + return !list; + }, + // Lock the list in its current state + lock: function() { + stack = undefined; + if ( !memory ) { + self.disable(); + } + return this; + }, + // Is it locked? + locked: function() { + return !stack; + }, + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + if ( list && ( !fired || stack ) ) { + if ( firing ) { + stack.push( args ); + } else { + fire( args ); + } + } + return this; + }, + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; + + return self; +}; +jQuery.extend({ + + Deferred: function( func ) { + var tuples = [ + // action, add listener, listener list, final state + [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], + [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], + [ "notify", "progress", jQuery.Callbacks("memory") ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + then: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + return jQuery.Deferred(function( newDefer ) { + jQuery.each( tuples, function( i, tuple ) { + var action = tuple[ 0 ], + fn = fns[ i ]; + // deferred[ done | fail | progress ] for forwarding actions to newDefer + deferred[ tuple[1] ]( jQuery.isFunction( fn ) ? + function() { + var returned = fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise() + .done( newDefer.resolve ) + .fail( newDefer.reject ) + .progress( newDefer.notify ); + } else { + newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] ); + } + } : + newDefer[ action ] + ); + }); + fns = null; + }).promise(); + }, + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } + }, + deferred = {}; + + // Keep pipe for back-compat + promise.pipe = promise.then; + + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 3 ]; + + // promise[ done | fail | progress ] = list.add + promise[ tuple[1] ] = list.add; + + // Handle state + if ( stateString ) { + list.add(function() { + // state = [ resolved | rejected ] + state = stateString; + + // [ reject_list | resolve_list ].disable; progress_list.lock + }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); + } + + // deferred[ resolve | reject | notify ] = list.fire + deferred[ tuple[0] ] = list.fire; + deferred[ tuple[0] + "With" ] = list.fireWith; + }); + + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( subordinate /* , ..., subordinateN */ ) { + var i = 0, + resolveValues = core_slice.call( arguments ), + length = resolveValues.length, + + // the count of uncompleted subordinates + remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, + + // the master Deferred. If resolveValues consist of only a single Deferred, just use that. + deferred = remaining === 1 ? subordinate : jQuery.Deferred(), + + // Update function for both resolve and progress values + updateFunc = function( i, contexts, values ) { + return function( value ) { + contexts[ i ] = this; + values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; + if( values === progressValues ) { + deferred.notifyWith( contexts, values ); + } else if ( !( --remaining ) ) { + deferred.resolveWith( contexts, values ); + } + }; + }, + + progressValues, progressContexts, resolveContexts; + + // add listeners to Deferred subordinates; treat others as resolved + if ( length > 1 ) { + progressValues = new Array( length ); + progressContexts = new Array( length ); + resolveContexts = new Array( length ); + for ( ; i < length; i++ ) { + if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { + resolveValues[ i ].promise() + .done( updateFunc( i, resolveContexts, resolveValues ) ) + .fail( deferred.reject ) + .progress( updateFunc( i, progressContexts, progressValues ) ); + } else { + --remaining; + } + } + } + + // if we're not waiting on anything, resolve the master + if ( !remaining ) { + deferred.resolveWith( resolveContexts, resolveValues ); + } + + return deferred.promise(); + } +}); +jQuery.support = (function() { + + var support, + all, + a, + select, + opt, + input, + fragment, + eventName, + i, + isSupported, + clickFn, + div = document.createElement("div"); + + // Setup + div.setAttribute( "className", "t" ); + div.innerHTML = "
                              `s in row rx + $tdsRow: function(rx){ + rx = rx < 0 ? rx + count : rx + return this.$tr(rx).find('> td') + }, + + // $td: Get `` row rx, column cx + $td: function(rx, cx){ + rx = rx < 0 ? rx + this.rowCount : rx + cx = cx < 0 ? cx + this.columnCount : cx + return this.$tdsRow(rx).eq(cx) + }, + + // row: Get values at a given row + row: function(rx, listOJML){ + rx = this._bound(rx, this.rowCount, ".row: rx") + + if (listOJML != null){ + _a(listOJML.length === cellCount(rx), this.typeName, "array expected for second argument with length (" + rx + ")") + + // Set tds + listOJML.forEach(function(ojml,cx){ + this.$td(rx, cx).oj(ojml) + }) + + } else { + return this.$tdsRow(rx).ojValues() + } + }, + + // cell: Get or set value at row rx, column cx + cell: function(rx, cx, ojml){ + if (ojml != null) + return this.$td(rx, cx).oj(ojml) + else + return this.$td(rx, cx).ojValue() + }, + + // addRow: Add row to index rx + addRow: function(rx, listOJML){ + + if (listOJML == null){ + listOJML = rx + rx = -1 + } + rx = this._bound(rx, this.rowCount + 1, ".addRow: rx") + _a(oj.isArray(listOJML), 'addRow', 'expected array for row content') + + this._addRowTR(rx, function(){ + oj.tr(function(){ + listOJML.forEach(function(cell){ + oj.td(cell) + }) + }); + }); + }, + + // _addRowTR: Helper to add row directly with `
                              a"; + + // Support tests won't run in some limited or non-browser environments + all = div.getElementsByTagName("*"); + a = div.getElementsByTagName("a")[ 0 ]; + if ( !all || !a || !all.length ) { + return {}; + } + + // First batch of tests + select = document.createElement("select"); + opt = select.appendChild( document.createElement("option") ); + input = div.getElementsByTagName("input")[ 0 ]; + + a.style.cssText = "top:1px;float:left;opacity:.5"; + support = { + // IE strips leading whitespace when .innerHTML is used + leadingWhitespace: ( div.firstChild.nodeType === 3 ), + + // Make sure that tbody elements aren't automatically inserted + // IE will insert them into empty tables + tbody: !div.getElementsByTagName("tbody").length, + + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + htmlSerialize: !!div.getElementsByTagName("link").length, + + // Get the style information from getAttribute + // (IE uses .cssText instead) + style: /top/.test( a.getAttribute("style") ), + + // Make sure that URLs aren't manipulated + // (IE normalizes it by default) + hrefNormalized: ( a.getAttribute("href") === "/a" ), + + // Make sure that element opacity exists + // (IE uses filter instead) + // Use a regex to work around a WebKit issue. See #5145 + opacity: /^0.5/.test( a.style.opacity ), + + // Verify style float existence + // (IE uses styleFloat instead of cssFloat) + cssFloat: !!a.style.cssFloat, + + // Make sure that if no value is specified for a checkbox + // that it defaults to "on". + // (WebKit defaults to "" instead) + checkOn: ( input.value === "on" ), + + // Make sure that a selected-by-default option has a working selected property. + // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) + optSelected: opt.selected, + + // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) + getSetAttribute: div.className !== "t", + + // Tests for enctype support on a form (#6743) + enctype: !!document.createElement("form").enctype, + + // Makes sure cloning an html5 element does not cause problems + // Where outerHTML is undefined, this still works + html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav>", + + // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode + boxModel: ( document.compatMode === "CSS1Compat" ), + + // Will be defined later + submitBubbles: true, + changeBubbles: true, + focusinBubbles: false, + deleteExpando: true, + noCloneEvent: true, + inlineBlockNeedsLayout: false, + shrinkWrapBlocks: false, + reliableMarginRight: true, + boxSizingReliable: true, + pixelPosition: false + }; + + // Make sure checked status is properly cloned + input.checked = true; + support.noCloneChecked = input.cloneNode( true ).checked; + + // Make sure that the options inside disabled selects aren't marked as disabled + // (WebKit marks them as disabled) + select.disabled = true; + support.optDisabled = !opt.disabled; + + // Test to see if it's possible to delete an expando from an element + // Fails in Internet Explorer + try { + delete div.test; + } catch( e ) { + support.deleteExpando = false; + } + + if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { + div.attachEvent( "onclick", clickFn = function() { + // Cloning a node shouldn't copy over any + // bound event handlers (IE does this) + support.noCloneEvent = false; + }); + div.cloneNode( true ).fireEvent("onclick"); + div.detachEvent( "onclick", clickFn ); + } + + // Check if a radio maintains its value + // after being appended to the DOM + input = document.createElement("input"); + input.value = "t"; + input.setAttribute( "type", "radio" ); + support.radioValue = input.value === "t"; + + input.setAttribute( "checked", "checked" ); + + // #11217 - WebKit loses check when the name is after the checked attribute + input.setAttribute( "name", "t" ); + + div.appendChild( input ); + fragment = document.createDocumentFragment(); + fragment.appendChild( div.lastChild ); + + // WebKit doesn't clone checked state correctly in fragments + support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Check if a disconnected checkbox will retain its checked + // value of true after appended to the DOM (IE6/7) + support.appendChecked = input.checked; + + fragment.removeChild( input ); + fragment.appendChild( div ); + + // Technique from Juriy Zaytsev + // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ + // We only care about the case where non-standard event systems + // are used, namely in IE. Short-circuiting here helps us to + // avoid an eval call (in setAttribute) which can cause CSP + // to go haywire. See: https://developer.mozilla.org/en/Security/CSP + if ( div.attachEvent ) { + for ( i in { + submit: true, + change: true, + focusin: true + }) { + eventName = "on" + i; + isSupported = ( eventName in div ); + if ( !isSupported ) { + div.setAttribute( eventName, "return;" ); + isSupported = ( typeof div[ eventName ] === "function" ); + } + support[ i + "Bubbles" ] = isSupported; + } + } + + // Run tests that need a body at doc ready + jQuery(function() { + var container, div, tds, marginDiv, + divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;", + body = document.getElementsByTagName("body")[0]; + + if ( !body ) { + // Return for frameset docs that don't have a body + return; + } + + container = document.createElement("div"); + container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px"; + body.insertBefore( container, body.firstChild ); + + // Construct the test element + div = document.createElement("div"); + container.appendChild( div ); + + // Check if table cells still have offsetWidth/Height when they are set + // to display:none and there are still other visible table cells in a + // table row; if so, offsetWidth/Height are not reliable for use when + // determining if an element has been hidden directly using + // display:none (it is still safe to use offsets if a parent element is + // hidden; don safety goggles and see bug #4512 for more information). + // (only IE 8 fails this test) + div.innerHTML = "
                              t
                              "; + tds = div.getElementsByTagName("td"); + tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; + isSupported = ( tds[ 0 ].offsetHeight === 0 ); + + tds[ 0 ].style.display = ""; + tds[ 1 ].style.display = "none"; + + // Check if empty table cells still have offsetWidth/Height + // (IE <= 8 fail this test) + support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); + + // Check box-sizing and margin behavior + div.innerHTML = ""; + div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; + support.boxSizing = ( div.offsetWidth === 4 ); + support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); + + // NOTE: To any future maintainer, we've window.getComputedStyle + // because jsdom on node.js will break without it. + if ( window.getComputedStyle ) { + support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; + support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; + + // Check if div with explicit width and no margin-right incorrectly + // gets computed margin-right based on width of container. For more + // info see bug #3333 + // Fails in WebKit before Feb 2011 nightlies + // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right + marginDiv = document.createElement("div"); + marginDiv.style.cssText = div.style.cssText = divReset; + marginDiv.style.marginRight = marginDiv.style.width = "0"; + div.style.width = "1px"; + div.appendChild( marginDiv ); + support.reliableMarginRight = + !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); + } + + if ( typeof div.style.zoom !== "undefined" ) { + // Check if natively block-level elements act like inline-block + // elements when setting their display to 'inline' and giving + // them layout + // (IE < 8 does this) + div.innerHTML = ""; + div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; + support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); + + // Check if elements with layout shrink-wrap their children + // (IE 6 does this) + div.style.display = "block"; + div.style.overflow = "visible"; + div.innerHTML = "
                              "; + div.firstChild.style.width = "5px"; + support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); + + container.style.zoom = 1; + } + + // Null elements to avoid leaks in IE + body.removeChild( container ); + container = div = tds = marginDiv = null; + }); + + // Null elements to avoid leaks in IE + fragment.removeChild( div ); + all = a = select = opt = input = fragment = div = null; + + return support; +})(); +var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, + rmultiDash = /([A-Z])/g; + +jQuery.extend({ + cache: {}, + + deletedIds: [], + + // Remove at next major release (1.9/2.0) + uuid: 0, + + // Unique for each copy of jQuery on the page + // Non-digits removed to match rinlinejQuery + expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ), + + // The following elements throw uncatchable exceptions if you + // attempt to add expando properties to them. + noData: { + "embed": true, + // Ban all objects except for Flash (which handle expandos) + "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", + "applet": true + }, + + hasData: function( elem ) { + elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; + return !!elem && !isEmptyDataObject( elem ); + }, + + data: function( elem, name, data, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var thisCache, ret, + internalKey = jQuery.expando, + getByName = typeof name === "string", + + // We have to handle DOM nodes and JS objects differently because IE6-7 + // can't GC object references properly across the DOM-JS boundary + isNode = elem.nodeType, + + // Only DOM nodes need the global jQuery cache; JS object data is + // attached directly to the object so GC can occur automatically + cache = isNode ? jQuery.cache : elem, + + // Only defining an ID for JS objects if its cache already exists allows + // the code to shortcut on the same path as a DOM node with no cache + id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; + + // Avoid doing any more work than we need to when trying to get data on an + // object that has no data at all + if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { + return; + } + + if ( !id ) { + // Only DOM nodes need a new unique ID for each element since their data + // ends up in the global cache + if ( isNode ) { + elem[ internalKey ] = id = jQuery.deletedIds.pop() || jQuery.guid++; + } else { + id = internalKey; + } + } + + if ( !cache[ id ] ) { + cache[ id ] = {}; + + // Avoids exposing jQuery metadata on plain JS objects when the object + // is serialized using JSON.stringify + if ( !isNode ) { + cache[ id ].toJSON = jQuery.noop; + } + } + + // An object can be passed to jQuery.data instead of a key/value pair; this gets + // shallow copied over onto the existing cache + if ( typeof name === "object" || typeof name === "function" ) { + if ( pvt ) { + cache[ id ] = jQuery.extend( cache[ id ], name ); + } else { + cache[ id ].data = jQuery.extend( cache[ id ].data, name ); + } + } + + thisCache = cache[ id ]; + + // jQuery data() is stored in a separate object inside the object's internal data + // cache in order to avoid key collisions between internal data and user-defined + // data. + if ( !pvt ) { + if ( !thisCache.data ) { + thisCache.data = {}; + } + + thisCache = thisCache.data; + } + + if ( data !== undefined ) { + thisCache[ jQuery.camelCase( name ) ] = data; + } + + // Check for both converted-to-camel and non-converted data property names + // If a data property was specified + if ( getByName ) { + + // First Try to find as-is property data + ret = thisCache[ name ]; + + // Test for null|undefined property data + if ( ret == null ) { + + // Try to find the camelCased property + ret = thisCache[ jQuery.camelCase( name ) ]; + } + } else { + ret = thisCache; + } + + return ret; + }, + + removeData: function( elem, name, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var thisCache, i, l, + + isNode = elem.nodeType, + + // See jQuery.data for more information + cache = isNode ? jQuery.cache : elem, + id = isNode ? elem[ jQuery.expando ] : jQuery.expando; + + // If there is already no cache entry for this object, there is no + // purpose in continuing + if ( !cache[ id ] ) { + return; + } + + if ( name ) { + + thisCache = pvt ? cache[ id ] : cache[ id ].data; + + if ( thisCache ) { + + // Support array or space separated string names for data keys + if ( !jQuery.isArray( name ) ) { + + // try the string as a key before any manipulation + if ( name in thisCache ) { + name = [ name ]; + } else { + + // split the camel cased version by spaces unless a key with the spaces exists + name = jQuery.camelCase( name ); + if ( name in thisCache ) { + name = [ name ]; + } else { + name = name.split(" "); + } + } + } + + for ( i = 0, l = name.length; i < l; i++ ) { + delete thisCache[ name[i] ]; + } + + // If there is no data left in the cache, we want to continue + // and let the cache object itself get destroyed + if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { + return; + } + } + } + + // See jQuery.data for more information + if ( !pvt ) { + delete cache[ id ].data; + + // Don't destroy the parent cache unless the internal data object + // had been the only thing left in it + if ( !isEmptyDataObject( cache[ id ] ) ) { + return; + } + } + + // Destroy the cache + if ( isNode ) { + jQuery.cleanData( [ elem ], true ); + + // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) + } else if ( jQuery.support.deleteExpando || cache != cache.window ) { + delete cache[ id ]; + + // When all else fails, null + } else { + cache[ id ] = null; + } + }, + + // For internal use only. + _data: function( elem, name, data ) { + return jQuery.data( elem, name, data, true ); + }, + + // A method for determining if a DOM node can handle the data expando + acceptData: function( elem ) { + var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; + + // nodes accept data unless otherwise specified; rejection can be conditional + return !noData || noData !== true && elem.getAttribute("classid") === noData; + } +}); + +jQuery.fn.extend({ + data: function( key, value ) { + var parts, part, attr, name, l, + elem = this[0], + i = 0, + data = null; + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = jQuery.data( elem ); + + if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { + attr = elem.attributes; + for ( l = attr.length; i < l; i++ ) { + name = attr[i].name; + + if ( !name.indexOf( "data-" ) ) { + name = jQuery.camelCase( name.substring(5) ); + + dataAttr( elem, name, data[ name ] ); + } + } + jQuery._data( elem, "parsedAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each(function() { + jQuery.data( this, key ); + }); + } + + parts = key.split( ".", 2 ); + parts[1] = parts[1] ? "." + parts[1] : ""; + part = parts[1] + "!"; + + return jQuery.access( this, function( value ) { + + if ( value === undefined ) { + data = this.triggerHandler( "getData" + part, [ parts[0] ] ); + + // Try to fetch any internally stored data first + if ( data === undefined && elem ) { + data = jQuery.data( elem, key ); + data = dataAttr( elem, key, data ); + } + + return data === undefined && parts[1] ? + this.data( parts[0] ) : + data; + } + + parts[1] = value; + this.each(function() { + var self = jQuery( this ); + + self.triggerHandler( "setData" + part, parts ); + jQuery.data( this, key, value ); + self.triggerHandler( "changeData" + part, parts ); + }); + }, null, value, arguments.length > 1, null, false ); + }, + + removeData: function( key ) { + return this.each(function() { + jQuery.removeData( this, key ); + }); + } +}); + +function dataAttr( elem, key, data ) { + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + + var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); + + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + // Only convert to a number if it doesn't change the string + +data + "" === data ? +data : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch( e ) {} + + // Make sure we set the data so it isn't changed later + jQuery.data( elem, key, data ); + + } else { + data = undefined; + } + } + + return data; +} + +// checks a cache object for emptiness +function isEmptyDataObject( obj ) { + var name; + for ( name in obj ) { + + // if the public data object is empty, the private is still empty + if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { + continue; + } + if ( name !== "toJSON" ) { + return false; + } + } + + return true; +} +jQuery.extend({ + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = jQuery._data( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || jQuery.isArray(data) ) { + queue = jQuery._data( elem, type, jQuery.makeArray(data) ); + } else { + queue.push( data ); + } + } + return queue || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; + } + + if ( fn ) { + + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + // clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); + } + + if ( !startLength && hooks ) { + hooks.empty.fire(); + } + }, + + // not intended for public consumption - generates a queueHooks object, or returns the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return jQuery._data( elem, key ) || jQuery._data( elem, key, { + empty: jQuery.Callbacks("once memory").add(function() { + jQuery.removeData( elem, type + "queue", true ); + jQuery.removeData( elem, key, true ); + }) + }); + } +}); + +jQuery.fn.extend({ + queue: function( type, data ) { + var setter = 2; + + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } + + if ( arguments.length < setter ) { + return jQuery.queue( this[0], type ); + } + + return data === undefined ? + this : + this.each(function() { + var queue = jQuery.queue( this, type, data ); + + // ensure a hooks for this queue + jQuery._queueHooks( this, type ); + + if ( type === "fx" && queue[0] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + }); + }, + dequeue: function( type ) { + return this.each(function() { + jQuery.dequeue( this, type ); + }); + }, + // Based off of the plugin by Clint Helfers, with permission. + // http://blindsignals.com/index.php/2009/07/jquery-delay/ + delay: function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; + type = type || "fx"; + + return this.queue( type, function( next, hooks ) { + var timeout = setTimeout( next, time ); + hooks.stop = function() { + clearTimeout( timeout ); + }; + }); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + }; + + if ( typeof type !== "string" ) { + obj = type; + type = undefined; + } + type = type || "fx"; + + while( i-- ) { + tmp = jQuery._data( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } + } + resolve(); + return defer.promise( obj ); + } +}); +var nodeHook, boolHook, fixSpecified, + rclass = /[\t\r\n]/g, + rreturn = /\r/g, + rtype = /^(?:button|input)$/i, + rfocusable = /^(?:button|input|object|select|textarea)$/i, + rclickable = /^a(?:rea|)$/i, + rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, + getSetAttribute = jQuery.support.getSetAttribute; + +jQuery.fn.extend({ + attr: function( name, value ) { + return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); + }, + + removeAttr: function( name ) { + return this.each(function() { + jQuery.removeAttr( this, name ); + }); + }, + + prop: function( name, value ) { + return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); + }, + + removeProp: function( name ) { + name = jQuery.propFix[ name ] || name; + return this.each(function() { + // try/catch handles cases where IE balks (such as removing a property on window) + try { + this[ name ] = undefined; + delete this[ name ]; + } catch( e ) {} + }); + }, + + addClass: function( value ) { + var classNames, i, l, elem, + setClass, c, cl; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).addClass( value.call(this, j, this.className) ); + }); + } + + if ( value && typeof value === "string" ) { + classNames = value.split( core_rspace ); + + for ( i = 0, l = this.length; i < l; i++ ) { + elem = this[ i ]; + + if ( elem.nodeType === 1 ) { + if ( !elem.className && classNames.length === 1 ) { + elem.className = value; + + } else { + setClass = " " + elem.className + " "; + + for ( c = 0, cl = classNames.length; c < cl; c++ ) { + if ( setClass.indexOf( " " + classNames[ c ] + " " ) < 0 ) { + setClass += classNames[ c ] + " "; + } + } + elem.className = jQuery.trim( setClass ); + } + } + } + } + + return this; + }, + + removeClass: function( value ) { + var removes, className, elem, c, cl, i, l; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( j ) { + jQuery( this ).removeClass( value.call(this, j, this.className) ); + }); + } + if ( (value && typeof value === "string") || value === undefined ) { + removes = ( value || "" ).split( core_rspace ); + + for ( i = 0, l = this.length; i < l; i++ ) { + elem = this[ i ]; + if ( elem.nodeType === 1 && elem.className ) { + + className = (" " + elem.className + " ").replace( rclass, " " ); + + // loop over each item in the removal list + for ( c = 0, cl = removes.length; c < cl; c++ ) { + // Remove until there is nothing to remove, + while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) { + className = className.replace( " " + removes[ c ] + " " , " " ); + } + } + elem.className = value ? jQuery.trim( className ) : ""; + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value, + isBool = typeof stateVal === "boolean"; + + if ( jQuery.isFunction( value ) ) { + return this.each(function( i ) { + jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); + }); + } + + return this.each(function() { + if ( type === "string" ) { + // toggle individual class names + var className, + i = 0, + self = jQuery( this ), + state = stateVal, + classNames = value.split( core_rspace ); + + while ( (className = classNames[ i++ ]) ) { + // check each className given, space separated list + state = isBool ? state : !self.hasClass( className ); + self[ state ? "addClass" : "removeClass" ]( className ); + } + + } else if ( type === "undefined" || type === "boolean" ) { + if ( this.className ) { + // store className if set + jQuery._data( this, "__className__", this.className ); + } + + // toggle whole className + this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; + } + }); + }, + + hasClass: function( selector ) { + var className = " " + selector + " ", + i = 0, + l = this.length; + for ( ; i < l; i++ ) { + if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { + return true; + } + } + + return false; + }, + + val: function( value ) { + var hooks, ret, isFunction, + elem = this[0]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; + + if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { + return ret; + } + + ret = elem.value; + + return typeof ret === "string" ? + // handle most common string cases + ret.replace(rreturn, "") : + // handle cases where value is null/undef or number + ret == null ? "" : ret; + } + + return; + } + + isFunction = jQuery.isFunction( value ); + + return this.each(function( i ) { + var val, + self = jQuery(this); + + if ( this.nodeType !== 1 ) { + return; + } + + if ( isFunction ) { + val = value.call( this, i, self.val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + } else if ( typeof val === "number" ) { + val += ""; + } else if ( jQuery.isArray( val ) ) { + val = jQuery.map(val, function ( value ) { + return value == null ? "" : value + ""; + }); + } + + hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + }); + } +}); + +jQuery.extend({ + valHooks: { + option: { + get: function( elem ) { + // attributes.value is undefined in Blackberry 4.7 but + // uses .value. See #6932 + var val = elem.attributes.value; + return !val || val.specified ? elem.value : elem.text; + } + }, + select: { + get: function( elem ) { + var value, option, + options = elem.options, + index = elem.selectedIndex, + one = elem.type === "select-one" || index < 0, + values = one ? null : [], + max = one ? index + 1 : options.length, + i = index < 0 ? + max : + one ? index : 0; + + // Loop through all the selected options + for ( ; i < max; i++ ) { + option = options[ i ]; + + // oldIE doesn't update selected after form reset (#2551) + if ( ( option.selected || i === index ) && + // Don't return options that are disabled or in a disabled optgroup + ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && + ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + return values; + }, + + set: function( elem, value ) { + var values = jQuery.makeArray( value ); + + jQuery(elem).find("option").each(function() { + this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; + }); + + if ( !values.length ) { + elem.selectedIndex = -1; + } + return values; + } + } + }, + + // Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9 + attrFn: {}, + + attr: function( elem, name, value, pass ) { + var ret, hooks, notxml, + nType = elem.nodeType; + + // don't get/set attributes on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) { + return jQuery( elem )[ name ]( value ); + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === "undefined" ) { + return jQuery.prop( elem, name, value ); + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + // All attributes are lowercase + // Grab necessary hook if one is defined + if ( notxml ) { + name = name.toLowerCase(); + hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); + } + + if ( value !== undefined ) { + + if ( value === null ) { + jQuery.removeAttr( elem, name ); + return; + + } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + elem.setAttribute( name, value + "" ); + return value; + } + + } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + + ret = elem.getAttribute( name ); + + // Non-existent attributes return null, we normalize to undefined + return ret === null ? + undefined : + ret; + } + }, + + removeAttr: function( elem, value ) { + var propName, attrNames, name, isBool, + i = 0; + + if ( value && elem.nodeType === 1 ) { + + attrNames = value.split( core_rspace ); + + for ( ; i < attrNames.length; i++ ) { + name = attrNames[ i ]; + + if ( name ) { + propName = jQuery.propFix[ name ] || name; + isBool = rboolean.test( name ); + + // See #9699 for explanation of this approach (setting first, then removal) + // Do not do this for boolean attributes (see #10870) + if ( !isBool ) { + jQuery.attr( elem, name, "" ); + } + elem.removeAttribute( getSetAttribute ? name : propName ); + + // Set corresponding property to false for boolean attributes + if ( isBool && propName in elem ) { + elem[ propName ] = false; + } + } + } + } + }, + + attrHooks: { + type: { + set: function( elem, value ) { + // We can't allow the type property to be changed (since it causes problems in IE) + if ( rtype.test( elem.nodeName ) && elem.parentNode ) { + jQuery.error( "type property can't be changed" ); + } else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { + // Setting the type on a radio button after the value resets the value in IE6-9 + // Reset value to it's default in case type is set after value + // This is for element creation + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + }, + // Use the value property for back compat + // Use the nodeHook for button elements in IE6/7 (#1954) + value: { + get: function( elem, name ) { + if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { + return nodeHook.get( elem, name ); + } + return name in elem ? + elem.value : + null; + }, + set: function( elem, value, name ) { + if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { + return nodeHook.set( elem, value, name ); + } + // Does not return so that setAttribute is also used + elem.value = value; + } + } + }, + + propFix: { + tabindex: "tabIndex", + readonly: "readOnly", + "for": "htmlFor", + "class": "className", + maxlength: "maxLength", + cellspacing: "cellSpacing", + cellpadding: "cellPadding", + rowspan: "rowSpan", + colspan: "colSpan", + usemap: "useMap", + frameborder: "frameBorder", + contenteditable: "contentEditable" + }, + + prop: function( elem, name, value ) { + var ret, hooks, notxml, + nType = elem.nodeType; + + // don't get/set properties on text, comment and attribute nodes + if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); + + if ( notxml ) { + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { + return ret; + + } else { + return ( elem[ name ] = value ); + } + + } else { + if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { + return ret; + + } else { + return elem[ name ]; + } + } + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set + // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + var attributeNode = elem.getAttributeNode("tabindex"); + + return attributeNode && attributeNode.specified ? + parseInt( attributeNode.value, 10 ) : + rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? + 0 : + undefined; + } + } + } +}); + +// Hook for boolean attributes +boolHook = { + get: function( elem, name ) { + // Align boolean attributes with corresponding properties + // Fall back to attribute presence where some booleans are not supported + var attrNode, + property = jQuery.prop( elem, name ); + return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? + name.toLowerCase() : + undefined; + }, + set: function( elem, value, name ) { + var propName; + if ( value === false ) { + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else { + // value is true since we know at this point it's type boolean and not false + // Set boolean attributes to the same name and set the DOM property + propName = jQuery.propFix[ name ] || name; + if ( propName in elem ) { + // Only set the IDL specifically if it already exists on the element + elem[ propName ] = true; + } + + elem.setAttribute( name, name.toLowerCase() ); + } + return name; + } +}; + +// IE6/7 do not support getting/setting some attributes with get/setAttribute +if ( !getSetAttribute ) { + + fixSpecified = { + name: true, + id: true, + coords: true + }; + + // Use this for any attribute in IE6/7 + // This fixes almost every IE6/7 issue + nodeHook = jQuery.valHooks.button = { + get: function( elem, name ) { + var ret; + ret = elem.getAttributeNode( name ); + return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ? + ret.value : + undefined; + }, + set: function( elem, value, name ) { + // Set the existing or create a new attribute node + var ret = elem.getAttributeNode( name ); + if ( !ret ) { + ret = document.createAttribute( name ); + elem.setAttributeNode( ret ); + } + return ( ret.value = value + "" ); + } + }; + + // Set width and height to auto instead of 0 on empty string( Bug #8150 ) + // This is for removals + jQuery.each([ "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + set: function( elem, value ) { + if ( value === "" ) { + elem.setAttribute( name, "auto" ); + return value; + } + } + }); + }); + + // Set contenteditable to false on removals(#10429) + // Setting to empty string throws an error as an invalid value + jQuery.attrHooks.contenteditable = { + get: nodeHook.get, + set: function( elem, value, name ) { + if ( value === "" ) { + value = "false"; + } + nodeHook.set( elem, value, name ); + } + }; +} + + +// Some attributes require a special call on IE +if ( !jQuery.support.hrefNormalized ) { + jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { + jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { + get: function( elem ) { + var ret = elem.getAttribute( name, 2 ); + return ret === null ? undefined : ret; + } + }); + }); +} + +if ( !jQuery.support.style ) { + jQuery.attrHooks.style = { + get: function( elem ) { + // Return undefined in the case of empty string + // Normalize to lowercase since IE uppercases css property names + return elem.style.cssText.toLowerCase() || undefined; + }, + set: function( elem, value ) { + return ( elem.style.cssText = value + "" ); + } + }; +} + +// Safari mis-reports the default selected property of an option +// Accessing the parent's selectedIndex property fixes it +if ( !jQuery.support.optSelected ) { + jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { + get: function( elem ) { + var parent = elem.parentNode; + + if ( parent ) { + parent.selectedIndex; + + // Make sure that it also works with optgroups, see #5701 + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + return null; + } + }); +} + +// IE6/7 call enctype encoding +if ( !jQuery.support.enctype ) { + jQuery.propFix.enctype = "encoding"; +} + +// Radios and checkboxes getter/setter +if ( !jQuery.support.checkOn ) { + jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + get: function( elem ) { + // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified + return elem.getAttribute("value") === null ? "on" : elem.value; + } + }; + }); +} +jQuery.each([ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { + set: function( elem, value ) { + if ( jQuery.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); + } + } + }); +}); +var rformElems = /^(?:textarea|input|select)$/i, + rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/, + rhoverHack = /(?:^|\s)hover(\.\S+|)\b/, + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|contextmenu)|click/, + rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + hoverHack = function( events ) { + return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); + }; + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + add: function( elem, types, handler, data, selector ) { + + var elemData, eventHandle, events, + t, tns, type, namespaces, handleObj, + handleObjIn, handlers, special; + + // Don't attach events to noData or text/comment nodes (allow plain objects tho) + if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + events = elemData.events; + if ( !events ) { + elemData.events = events = {}; + } + eventHandle = elemData.handle; + if ( !eventHandle ) { + elemData.handle = eventHandle = function( e ) { + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? + jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : + undefined; + }; + // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events + eventHandle.elem = elem; + } + + // Handle multiple events separated by a space + // jQuery(...).bind("mouseover mouseout", fn); + types = jQuery.trim( hoverHack(types) ).split( " " ); + for ( t = 0; t < types.length; t++ ) { + + tns = rtypenamespace.exec( types[t] ) || []; + type = tns[1]; + namespaces = ( tns[2] || "" ).split( "." ).sort(); + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend({ + type: type, + origType: tns[1], + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join(".") + }, handleObjIn ); + + // Init the event handler queue if we're the first + handlers = events[ type ]; + if ( !handlers ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener/attachEvent if the special events handler returns false + if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + // Bind the global event handler to the element + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle, false ); + + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + // Nullify elem to prevent memory leaks in IE + elem = null; + }, + + global: {}, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + + var t, tns, type, origType, namespaces, origCount, + j, events, special, eventType, handleObj, + elemData = jQuery.hasData( elem ) && jQuery._data( elem ); + + if ( !elemData || !(events = elemData.events) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = jQuery.trim( hoverHack( types || "" ) ).split(" "); + for ( t = 0; t < types.length; t++ ) { + tns = rtypenamespace.exec( types[t] ) || []; + type = origType = tns[1]; + namespaces = tns[2]; + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector? special.delegateType : special.bindType ) || type; + eventType = events[ type ] || []; + origCount = eventType.length; + namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null; + + // Remove matching events + for ( j = 0; j < eventType.length; j++ ) { + handleObj = eventType[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !namespaces || namespaces.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { + eventType.splice( j--, 1 ); + + if ( handleObj.selector ) { + eventType.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( eventType.length === 0 && origCount !== eventType.length ) { + if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + delete elemData.handle; + + // removeData also checks for emptiness and clears the expando if empty + // so use it instead of delete + jQuery.removeData( elem, "events", true ); + } + }, + + // Events that are safe to short-circuit if no handlers are attached. + // Native DOM events should not be added, they may have inline handlers. + customEvent: { + "getData": true, + "setData": true, + "changeData": true + }, + + trigger: function( event, data, elem, onlyHandlers ) { + // Don't do events on text and comment nodes + if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { + return; + } + + // Event object or event type + var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType, + type = event.type || event, + namespaces = []; + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf( "!" ) >= 0 ) { + // Exclusive events trigger only for the exact event (no namespaces) + type = type.slice(0, -1); + exclusive = true; + } + + if ( type.indexOf( "." ) >= 0 ) { + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split("."); + type = namespaces.shift(); + namespaces.sort(); + } + + if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { + // No jQuery handlers for this event type, and it can't have inline handlers + return; + } + + // Caller can pass in an Event, Object, or just an event type string + event = typeof event === "object" ? + // jQuery.Event object + event[ jQuery.expando ] ? event : + // Object literal + new jQuery.Event( type, event ) : + // Just the event type (string) + new jQuery.Event( type ); + + event.type = type; + event.isTrigger = true; + event.exclusive = exclusive; + event.namespace = namespaces.join( "." ); + event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null; + ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; + + // Handle a global trigger + if ( !elem ) { + + // TODO: Stop taunting the data cache; remove global events and always attach to document + cache = jQuery.cache; + for ( i in cache ) { + if ( cache[ i ].events && cache[ i ].events[ type ] ) { + jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); + } + } + return; + } + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data != null ? jQuery.makeArray( data ) : []; + data.unshift( event ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + eventPath = [[ elem, special.bindType || type ]]; + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; + for ( old = elem; cur; cur = cur.parentNode ) { + eventPath.push([ cur, bubbleType ]); + old = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( old === (elem.ownerDocument || document) ) { + eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); + } + } + + // Fire handlers on the event path + for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { + + cur = eventPath[i][0]; + event.type = eventPath[i][1]; + + handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + // Note that this is a bare JS function and not a jQuery handler + handle = ontype && cur[ ontype ]; + if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { + event.preventDefault(); + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && + !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name name as the event. + // Can't use an .isFunction() check here because IE6/7 fails that test. + // Don't do default actions on window, that's where global variables be (#6170) + // IE<9 dies on focus/blur to hidden element (#1486) + if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + old = elem[ ontype ]; + + if ( old ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + elem[ type ](); + jQuery.event.triggered = undefined; + + if ( old ) { + elem[ ontype ] = old; + } + } + } + } + + return event.result; + }, + + dispatch: function( event ) { + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event || window.event ); + + var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related, + handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), + delegateCount = handlers.delegateCount, + args = core_slice.call( arguments ), + run_all = !event.exclusive && !event.namespace, + special = jQuery.event.special[ event.type ] || {}, + handlerQueue = []; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[0] = event; + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } + + // Determine handlers that should run if there are delegated events + // Avoid non-left-click bubbling in Firefox (#3861) + if ( delegateCount && !(event.button && event.type === "click") ) { + + for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { + + // Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.disabled !== true || event.type !== "click" ) { + selMatch = {}; + matches = []; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + sel = handleObj.selector; + + if ( selMatch[ sel ] === undefined ) { + selMatch[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) >= 0 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( selMatch[ sel ] ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push({ elem: cur, matches: matches }); + } + } + } + } + + // Add the remaining (directly-bound) handlers + if ( handlers.length > delegateCount ) { + handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); + } + + // Run delegates first; they may want to stop propagation beneath us + for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { + matched = handlerQueue[ i ]; + event.currentTarget = matched.elem; + + for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { + handleObj = matched.matches[ j ]; + + // Triggered event must either 1) be non-exclusive and have no namespace, or + // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). + if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { + + event.data = handleObj.data; + event.handleObj = handleObj; + + ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) + .apply( matched.elem, args ); + + if ( ret !== undefined ) { + event.result = ret; + if ( ret === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + // Includes some event props shared by KeyEvent and MouseEvent + // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** + props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), + + fixHooks: {}, + + keyHooks: { + props: "char charCode key keyCode".split(" "), + filter: function( event, original ) { + + // Add which for key events + if ( event.which == null ) { + event.which = original.charCode != null ? original.charCode : original.keyCode; + } + + return event; + } + }, + + mouseHooks: { + props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), + filter: function( event, original ) { + var eventDoc, doc, body, + button = original.button, + fromElement = original.fromElement; + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && original.clientX != null ) { + eventDoc = event.target.ownerDocument || document; + doc = eventDoc.documentElement; + body = eventDoc.body; + + event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); + event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); + } + + // Add relatedTarget, if necessary + if ( !event.relatedTarget && fromElement ) { + event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && button !== undefined ) { + event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); + } + + return event; + } + }, + + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } + + // Create a writable copy of the event object and normalize some properties + var i, prop, + originalEvent = event, + fixHook = jQuery.event.fixHooks[ event.type ] || {}, + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + + event = jQuery.Event( originalEvent ); + + for ( i = copy.length; i; ) { + prop = copy[ --i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) + if ( !event.target ) { + event.target = originalEvent.srcElement || document; + } + + // Target should not be a text node (#504, Safari) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + // For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8) + event.metaKey = !!event.metaKey; + + return fixHook.filter? fixHook.filter( event, originalEvent ) : event; + }, + + special: { + load: { + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + + focus: { + delegateType: "focusin" + }, + blur: { + delegateType: "focusout" + }, + + beforeunload: { + setup: function( data, namespaces, eventHandle ) { + // We only want to do this special case on windows + if ( jQuery.isWindow( this ) ) { + this.onbeforeunload = eventHandle; + } + }, + + teardown: function( namespaces, eventHandle ) { + if ( this.onbeforeunload === eventHandle ) { + this.onbeforeunload = null; + } + } + } + }, + + simulate: function( type, elem, event, bubble ) { + // Piggyback on a donor event to simulate a different one. + // Fake originalEvent to avoid donor's stopPropagation, but if the + // simulated event prevents default then we do the same on the donor. + var e = jQuery.extend( + new jQuery.Event(), + event, + { type: type, + isSimulated: true, + originalEvent: {} + } + ); + if ( bubble ) { + jQuery.event.trigger( e, null, elem ); + } else { + jQuery.event.dispatch.call( elem, e ); + } + if ( e.isDefaultPrevented() ) { + event.preventDefault(); + } + } +}; + +// Some plugins are using, but it's undocumented/deprecated and will be removed. +// The 1.7 special event interface should provide all the hooks needed now. +jQuery.event.handle = jQuery.event.dispatch; + +jQuery.removeEvent = document.removeEventListener ? + function( elem, type, handle ) { + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle, false ); + } + } : + function( elem, type, handle ) { + var name = "on" + type; + + if ( elem.detachEvent ) { + + // #8545, #7054, preventing memory leaks for custom events in IE6-8 + // detachEvent needed property on element, by name of that event, to properly expose it to GC + if ( typeof elem[ name ] === "undefined" ) { + elem[ name ] = null; + } + + elem.detachEvent( name, handle ); + } + }; + +jQuery.Event = function( src, props ) { + // Allow instantiation without the 'new' keyword + if ( !(this instanceof jQuery.Event) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || + src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +function returnFalse() { + return false; +} +function returnTrue() { + return true; +} + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + preventDefault: function() { + this.isDefaultPrevented = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + + // if preventDefault exists run it on the original event + if ( e.preventDefault ) { + e.preventDefault(); + + // otherwise set the returnValue property of the original event to false (IE) + } else { + e.returnValue = false; + } + }, + stopPropagation: function() { + this.isPropagationStopped = returnTrue; + + var e = this.originalEvent; + if ( !e ) { + return; + } + // if stopPropagation exists run it on the original event + if ( e.stopPropagation ) { + e.stopPropagation(); + } + // otherwise set the cancelBubble property of the original event to true (IE) + e.cancelBubble = true; + }, + stopImmediatePropagation: function() { + this.isImmediatePropagationStopped = returnTrue; + this.stopPropagation(); + }, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse +}; + +// Create mouseenter/leave events using mouseover/out and event-time checks +jQuery.each({ + mouseenter: "mouseover", + mouseleave: "mouseout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj, + selector = handleObj.selector; + + // For mousenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || (related !== target && !jQuery.contains( target, related )) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +}); + +// IE submit delegation +if ( !jQuery.support.submitBubbles ) { + + jQuery.event.special.submit = { + setup: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Lazy-add a submit handler when a descendant form may potentially be submitted + jQuery.event.add( this, "click._submit keypress._submit", function( e ) { + // Node name check avoids a VML-related crash in IE (#9807) + var elem = e.target, + form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; + if ( form && !jQuery._data( form, "_submit_attached" ) ) { + jQuery.event.add( form, "submit._submit", function( event ) { + event._submit_bubble = true; + }); + jQuery._data( form, "_submit_attached", true ); + } + }); + // return undefined since we don't need an event listener + }, + + postDispatch: function( event ) { + // If form was submitted by the user, bubble the event up the tree + if ( event._submit_bubble ) { + delete event._submit_bubble; + if ( this.parentNode && !event.isTrigger ) { + jQuery.event.simulate( "submit", this.parentNode, event, true ); + } + } + }, + + teardown: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Remove delegated handlers; cleanData eventually reaps submit handlers attached above + jQuery.event.remove( this, "._submit" ); + } + }; +} + +// IE change delegation and checkbox/radio fix +if ( !jQuery.support.changeBubbles ) { + + jQuery.event.special.change = { + + setup: function() { + + if ( rformElems.test( this.nodeName ) ) { + // IE doesn't fire change on a check/radio until blur; trigger it on click + // after a propertychange. Eat the blur-change in special.change.handle. + // This still fires onchange a second time for check/radio after blur. + if ( this.type === "checkbox" || this.type === "radio" ) { + jQuery.event.add( this, "propertychange._change", function( event ) { + if ( event.originalEvent.propertyName === "checked" ) { + this._just_changed = true; + } + }); + jQuery.event.add( this, "click._change", function( event ) { + if ( this._just_changed && !event.isTrigger ) { + this._just_changed = false; + } + // Allow triggered, simulated change events (#11500) + jQuery.event.simulate( "change", this, event, true ); + }); + } + return false; + } + // Delegated event; lazy-add a change handler on descendant inputs + jQuery.event.add( this, "beforeactivate._change", function( e ) { + var elem = e.target; + + if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) { + jQuery.event.add( elem, "change._change", function( event ) { + if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { + jQuery.event.simulate( "change", this.parentNode, event, true ); + } + }); + jQuery._data( elem, "_change_attached", true ); + } + }); + }, + + handle: function( event ) { + var elem = event.target; + + // Swallow native change events from checkbox/radio, we already triggered them above + if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { + return event.handleObj.handler.apply( this, arguments ); + } + }, + + teardown: function() { + jQuery.event.remove( this, "._change" ); + + return !rformElems.test( this.nodeName ); + } + }; +} + +// Create "bubbling" focus and blur events +if ( !jQuery.support.focusinBubbles ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler while someone wants focusin/focusout + var attaches = 0, + handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + if ( attaches++ === 0 ) { + document.addEventListener( orig, handler, true ); + } + }, + teardown: function() { + if ( --attaches === 0 ) { + document.removeEventListener( orig, handler, true ); + } + } + }; + }); +} + +jQuery.fn.extend({ + + on: function( types, selector, data, fn, /*INTERNAL*/ one ) { + var origFn, type; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { // && selector != null + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + this.on( type, selector, data, types[ type ], one ); + } + return this; + } + + if ( data == null && fn == null ) { + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return this; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return this.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + }); + }, + one: function( types, selector, data, fn ) { + return this.on( types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each(function() { + jQuery.event.remove( this, types, fn, selector ); + }); + }, + + bind: function( types, data, fn ) { + return this.on( types, null, data, fn ); + }, + unbind: function( types, fn ) { + return this.off( types, null, fn ); + }, + + live: function( types, data, fn ) { + jQuery( this.context ).on( types, this.selector, data, fn ); + return this; + }, + die: function( types, fn ) { + jQuery( this.context ).off( types, this.selector || "**", fn ); + return this; + }, + + delegate: function( selector, types, data, fn ) { + return this.on( types, selector, data, fn ); + }, + undelegate: function( selector, types, fn ) { + // ( namespace ) or ( selector, types [, fn] ) + return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); + }, + + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + triggerHandler: function( type, data ) { + if ( this[0] ) { + return jQuery.event.trigger( type, data, this[0], true ); + } + }, + + toggle: function( fn ) { + // Save reference to arguments for access in closure + var args = arguments, + guid = fn.guid || jQuery.guid++, + i = 0, + toggler = function( event ) { + // Figure out which function to execute + var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; + jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); + + // Make sure that clicks stop + event.preventDefault(); + + // and execute the function + return args[ lastToggle ].apply( this, arguments ) || false; + }; + + // link all the functions, so any of them can unbind this click handler + toggler.guid = guid; + while ( i < args.length ) { + args[ i++ ].guid = guid; + } + + return this.click( toggler ); + }, + + hover: function( fnOver, fnOut ) { + return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); + } +}); + +jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { + + // Handle event binding + jQuery.fn[ name ] = function( data, fn ) { + if ( fn == null ) { + fn = data; + data = null; + } + + return arguments.length > 0 ? + this.on( name, null, data, fn ) : + this.trigger( name ); + }; + + if ( rkeyEvent.test( name ) ) { + jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; + } + + if ( rmouseEvent.test( name ) ) { + jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; + } +}); +/*! + * Sizzle CSS Selector Engine + * Copyright 2012 jQuery Foundation and other contributors + * Released under the MIT license + * http://sizzlejs.com/ + */ +(function( window, undefined ) { + +var cachedruns, + assertGetIdNotName, + Expr, + getText, + isXML, + contains, + compile, + sortOrder, + hasDuplicate, + outermostContext, + + baseHasDuplicate = true, + strundefined = "undefined", + + expando = ( "sizcache" + Math.random() ).replace( ".", "" ), + + Token = String, + document = window.document, + docElem = document.documentElement, + dirruns = 0, + done = 0, + pop = [].pop, + push = [].push, + slice = [].slice, + // Use a stripped-down indexOf if a native one is unavailable + indexOf = [].indexOf || function( elem ) { + var i = 0, + len = this.length; + for ( ; i < len; i++ ) { + if ( this[i] === elem ) { + return i; + } + } + return -1; + }, + + // Augment a function for special use by Sizzle + markFunction = function( fn, value ) { + fn[ expando ] = value == null || value; + return fn; + }, + + createCache = function() { + var cache = {}, + keys = []; + + return markFunction(function( key, value ) { + // Only keep the most recent entries + if ( keys.push( key ) > Expr.cacheLength ) { + delete cache[ keys.shift() ]; + } + + // Retrieve with (key + " ") to avoid collision with native Object.prototype properties (see Issue #157) + return (cache[ key + " " ] = value); + }, cache ); + }, + + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + + // Regex + + // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + // http://www.w3.org/TR/css3-syntax/#characters + characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+", + + // Loosely modeled on CSS identifier characters + // An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors) + // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier + identifier = characterEncoding.replace( "w", "w#" ), + + // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors + operators = "([*^$|!~]?=)", + attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", + + // Prefer arguments not in parens/brackets, + // then attribute selectors and non-pseudos (denoted by :), + // then anything else + // These preferences are here to reduce the number of selectors + // needing tokenize in the PSEUDO preFilter + pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)", + + // For matchExpr.POS and matchExpr.needsContext + pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), + rpseudo = new RegExp( pseudos ), + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/, + + rnot = /^:not/, + rsibling = /[\x20\t\r\n\f]*[+~]/, + rendsWithNot = /:not\($/, + + rheader = /h\d/i, + rinputs = /input|select|textarea|button/i, + + rbackslash = /\\(?!\\)/g, + + matchExpr = { + "ID": new RegExp( "^#(" + characterEncoding + ")" ), + "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), + "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), + "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "POS": new RegExp( pos, "i" ), + "CHILD": new RegExp( "^:(only|nth|first|last)-child(?:\\(" + whitespace + + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + // For use in libraries implementing .is() + "needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" ) + }, + + // Support + + // Used for testing something on an element + assert = function( fn ) { + var div = document.createElement("div"); + + try { + return fn( div ); + } catch (e) { + return false; + } finally { + // release memory in IE + div = null; + } + }, + + // Check if getElementsByTagName("*") returns only elements + assertTagNameNoComments = assert(function( div ) { + div.appendChild( document.createComment("") ); + return !div.getElementsByTagName("*").length; + }), + + // Check if getAttribute returns normalized href attributes + assertHrefNotNormalized = assert(function( div ) { + div.innerHTML = ""; + return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && + div.firstChild.getAttribute("href") === "#"; + }), + + // Check if attributes should be retrieved by attribute nodes + assertAttributes = assert(function( div ) { + div.innerHTML = ""; + var type = typeof div.lastChild.getAttribute("multiple"); + // IE8 returns a string for some attributes even when not present + return type !== "boolean" && type !== "string"; + }), + + // Check if getElementsByClassName can be trusted + assertUsableClassName = assert(function( div ) { + // Opera can't find a second classname (in 9.6) + div.innerHTML = ""; + if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { + return false; + } + + // Safari 3.2 caches class attributes and doesn't catch changes + div.lastChild.className = "e"; + return div.getElementsByClassName("e").length === 2; + }), + + // Check if getElementById returns elements by name + // Check if getElementsByName privileges form controls or returns elements by ID + assertUsableName = assert(function( div ) { + // Inject content + div.id = expando + 0; + div.innerHTML = "
                              "; + docElem.insertBefore( div, docElem.firstChild ); + + // Test + var pass = document.getElementsByName && + // buggy browsers will return fewer than the correct 2 + document.getElementsByName( expando ).length === 2 + + // buggy browsers will return more than the correct 0 + document.getElementsByName( expando + 0 ).length; + assertGetIdNotName = !document.getElementById( expando ); + + // Cleanup + docElem.removeChild( div ); + + return pass; + }); + +// If slice is not available, provide a backup +try { + slice.call( docElem.childNodes, 0 )[0].nodeType; +} catch ( e ) { + slice = function( i ) { + var elem, + results = []; + for ( ; (elem = this[i]); i++ ) { + results.push( elem ); + } + return results; + }; +} + +function Sizzle( selector, context, results, seed ) { + results = results || []; + context = context || document; + var match, elem, xml, m, + nodeType = context.nodeType; + + if ( !selector || typeof selector !== "string" ) { + return results; + } + + if ( nodeType !== 1 && nodeType !== 9 ) { + return []; + } + + xml = isXML( context ); + + if ( !xml && !seed ) { + if ( (match = rquickExpr.exec( selector )) ) { + // Speed-up: Sizzle("#ID") + if ( (m = match[1]) ) { + if ( nodeType === 9 ) { + elem = context.getElementById( m ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE, Opera, and Webkit return items + // by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + } else { + // Context is not a document + if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && + contains( context, elem ) && elem.id === m ) { + results.push( elem ); + return results; + } + } + + // Speed-up: Sizzle("TAG") + } else if ( match[2] ) { + push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) ); + return results; + + // Speed-up: Sizzle(".CLASS") + } else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) { + push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); + return results; + } + } + } + + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed, xml ); +} + +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); +}; + +Sizzle.matchesSelector = function( elem, expr ) { + return Sizzle( expr, null, null, [ elem ] ).length > 0; +}; + +// Returns a function to use in pseudos for input types +function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; +} + +// Returns a function to use in pseudos for buttons +function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && elem.type === type; + }; +} + +// Returns a function to use in pseudos for positionals +function createPositionalPseudo( fn ) { + return markFunction(function( argument ) { + argument = +argument; + return markFunction(function( seed, matches ) { + var j, + matchIndexes = fn( [], seed.length, argument ), + i = matchIndexes.length; + + // Match elements found at the specified indexes + while ( i-- ) { + if ( seed[ (j = matchIndexes[i]) ] ) { + seed[j] = !(matches[j] = seed[j]); + } + } + }); + }); +} + +/** + * Utility function for retrieving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +getText = Sizzle.getText = function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( nodeType ) { + if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + // Use textContent for elements + // innerText usage removed for consistency of new lines (see #11153) + if ( typeof elem.textContent === "string" ) { + return elem.textContent; + } else { + // Traverse its children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + // Do not include comment or processing instruction nodes + } else { + + // If no nodeType, this is expected to be an array + for ( ; (node = elem[i]); i++ ) { + // Do not traverse comment nodes + ret += getText( node ); + } + } + return ret; +}; + +isXML = Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = elem && (elem.ownerDocument || elem).documentElement; + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +// Element contains another +contains = Sizzle.contains = docElem.contains ? + function( a, b ) { + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b && b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) ); + } : + docElem.compareDocumentPosition ? + function( a, b ) { + return b && !!( a.compareDocumentPosition( b ) & 16 ); + } : + function( a, b ) { + while ( (b = b.parentNode) ) { + if ( b === a ) { + return true; + } + } + return false; + }; + +Sizzle.attr = function( elem, name ) { + var val, + xml = isXML( elem ); + + if ( !xml ) { + name = name.toLowerCase(); + } + if ( (val = Expr.attrHandle[ name ]) ) { + return val( elem ); + } + if ( xml || assertAttributes ) { + return elem.getAttribute( name ); + } + val = elem.getAttributeNode( name ); + return val ? + typeof elem[ name ] === "boolean" ? + elem[ name ] ? name : null : + val.specified ? val.value : null : + null; +}; + +Expr = Sizzle.selectors = { + + // Can be adjusted by the user + cacheLength: 50, + + createPseudo: markFunction, + + match: matchExpr, + + // IE6/7 return a modified href + attrHandle: assertHrefNotNormalized ? + {} : + { + "href": function( elem ) { + return elem.getAttribute( "href", 2 ); + }, + "type": function( elem ) { + return elem.getAttribute("type"); + } + }, + + find: { + "ID": assertGetIdNotName ? + function( id, context, xml ) { + if ( typeof context.getElementById !== strundefined && !xml ) { + var m = context.getElementById( id ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [m] : []; + } + } : + function( id, context, xml ) { + if ( typeof context.getElementById !== strundefined && !xml ) { + var m = context.getElementById( id ); + + return m ? + m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? + [m] : + undefined : + []; + } + }, + + "TAG": assertTagNameNoComments ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== strundefined ) { + return context.getElementsByTagName( tag ); + } + } : + function( tag, context ) { + var results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + var elem, + tmp = [], + i = 0; + + for ( ; (elem = results[i]); i++ ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } + + return tmp; + } + return results; + }, + + "NAME": assertUsableName && function( tag, context ) { + if ( typeof context.getElementsByName !== strundefined ) { + return context.getElementsByName( name ); + } + }, + + "CLASS": assertUsableClassName && function( className, context, xml ) { + if ( typeof context.getElementsByClassName !== strundefined && !xml ) { + return context.getElementsByClassName( className ); + } + } + }, + + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, + + preFilter: { + "ATTR": function( match ) { + match[1] = match[1].replace( rbackslash, "" ); + + // Move the given value to match[3] whether quoted or unquoted + match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" ); + + if ( match[2] === "~=" ) { + match[3] = " " + match[3] + " "; + } + + return match.slice( 0, 4 ); + }, + + "CHILD": function( match ) { + /* matches from matchExpr["CHILD"] + 1 type (only|nth|...) + 2 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 3 xn-component of xn+y argument ([+-]?\d*n|) + 4 sign of xn-component + 5 x of xn-component + 6 sign of y-component + 7 y of y-component + */ + match[1] = match[1].toLowerCase(); + + if ( match[1] === "nth" ) { + // nth-child requires argument + if ( !match[2] ) { + Sizzle.error( match[0] ); + } + + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) ); + match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" ); + + // other types prohibit arguments + } else if ( match[2] ) { + Sizzle.error( match[0] ); + } + + return match; + }, + + "PSEUDO": function( match ) { + var unquoted, excess; + if ( matchExpr["CHILD"].test( match[0] ) ) { + return null; + } + + if ( match[3] ) { + match[2] = match[3]; + } else if ( (unquoted = match[4]) ) { + // Only check arguments that contain a pseudo + if ( rpseudo.test(unquoted) && + // Get excess from tokenize (recursively) + (excess = tokenize( unquoted, true )) && + // advance to the next closing parenthesis + (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { + + // excess is a negative index + unquoted = unquoted.slice( 0, excess ); + match[0] = match[0].slice( 0, excess ); + } + match[2] = unquoted; + } + + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); + } + }, + + filter: { + "ID": assertGetIdNotName ? + function( id ) { + id = id.replace( rbackslash, "" ); + return function( elem ) { + return elem.getAttribute("id") === id; + }; + } : + function( id ) { + id = id.replace( rbackslash, "" ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); + return node && node.value === id; + }; + }, + + "TAG": function( nodeName ) { + if ( nodeName === "*" ) { + return function() { return true; }; + } + nodeName = nodeName.replace( rbackslash, "" ).toLowerCase(); + + return function( elem ) { + return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + }; + }, + + "CLASS": function( className ) { + var pattern = classCache[ expando ][ className + " " ]; + + return pattern || + (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && + classCache( className, function( elem ) { + return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); + }); + }, + + "ATTR": function( name, operator, check ) { + return function( elem, context ) { + var result = Sizzle.attr( elem, name ); + + if ( result == null ) { + return operator === "!="; + } + if ( !operator ) { + return true; + } + + result += ""; + + return operator === "=" ? result === check : + operator === "!=" ? result !== check : + operator === "^=" ? check && result.indexOf( check ) === 0 : + operator === "*=" ? check && result.indexOf( check ) > -1 : + operator === "$=" ? check && result.substr( result.length - check.length ) === check : + operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" : + false; + }; + }, + + "CHILD": function( type, argument, first, last ) { + + if ( type === "nth" ) { + return function( elem ) { + var node, diff, + parent = elem.parentNode; + + if ( first === 1 && last === 0 ) { + return true; + } + + if ( parent ) { + diff = 0; + for ( node = parent.firstChild; node; node = node.nextSibling ) { + if ( node.nodeType === 1 ) { + diff++; + if ( elem === node ) { + break; + } + } + } + } + + // Incorporate the offset (or cast to NaN), then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + }; + } + + return function( elem ) { + var node = elem; + + switch ( type ) { + case "only": + case "first": + while ( (node = node.previousSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + if ( type === "first" ) { + return true; + } + + node = elem; + + /* falls through */ + case "last": + while ( (node = node.nextSibling) ) { + if ( node.nodeType === 1 ) { + return false; + } + } + + return true; + } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction(function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf.call( seed, matched[i] ); + seed[ idx ] = !( matches[ idx ] = matched[i] ); + } + }) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; + } + }, + + pseudos: { + "not": markFunction(function( selector ) { + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction(function( seed, matches, context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( (elem = unmatched[i]) ) { + seed[i] = !(matches[i] = elem); + } + } + }) : + function( elem, context, xml ) { + input[0] = elem; + matcher( input, null, xml, results ); + return !results.pop(); + }; + }), + + "has": markFunction(function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + }), + + "contains": markFunction(function( text ) { + return function( elem ) { + return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + }; + }), + + "enabled": function( elem ) { + return elem.disabled === false; + }, + + "disabled": function( elem ) { + return elem.disabled === true; + }, + + "checked": function( elem ) { + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); + }, + + "selected": function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + "parent": function( elem ) { + return !Expr.pseudos["empty"]( elem ); + }, + + "empty": function( elem ) { + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), + // not comment, processing instructions, or others + // Thanks to Diego Perini for the nodeName shortcut + // Greater than "@" means alpha characters (specifically not starting with "#" or "?") + var nodeType; + elem = elem.firstChild; + while ( elem ) { + if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) { + return false; + } + elem = elem.nextSibling; + } + return true; + }, + + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "text": function( elem ) { + var type, attr; + // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) + // use getAttribute instead to test this case + return elem.nodeName.toLowerCase() === "input" && + (type = elem.type) === "text" && + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type ); + }, + + // Input types + "radio": createInputPseudo("radio"), + "checkbox": createInputPseudo("checkbox"), + "file": createInputPseudo("file"), + "password": createInputPseudo("password"), + "image": createInputPseudo("image"), + + "submit": createButtonPseudo("submit"), + "reset": createButtonPseudo("reset"), + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "focus": function( elem ) { + var doc = elem.ownerDocument; + return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); + }, + + "active": function( elem ) { + return elem === elem.ownerDocument.activeElement; + }, + + // Positional types + "first": createPositionalPseudo(function() { + return [ 0 ]; + }), + + "last": createPositionalPseudo(function( matchIndexes, length ) { + return [ length - 1 ]; + }), + + "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + }), + + "even": createPositionalPseudo(function( matchIndexes, length ) { + for ( var i = 0; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "odd": createPositionalPseudo(function( matchIndexes, length ) { + for ( var i = 1; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { + for ( var i = argument < 0 ? argument + length : argument; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { + for ( var i = argument < 0 ? argument + length : argument; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }) + } +}; + +function siblingCheck( a, b, ret ) { + if ( a === b ) { + return ret; + } + + var cur = a.nextSibling; + + while ( cur ) { + if ( cur === b ) { + return -1; + } + + cur = cur.nextSibling; + } + + return 1; +} + +sortOrder = docElem.compareDocumentPosition ? + function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + return ( !a.compareDocumentPosition || !b.compareDocumentPosition ? + a.compareDocumentPosition : + a.compareDocumentPosition(b) & 4 + ) ? -1 : 1; + } : + function( a, b ) { + // The nodes are identical, we can exit early + if ( a === b ) { + hasDuplicate = true; + return 0; + + // Fallback to using sourceIndex (in IE) if it's available on both nodes + } else if ( a.sourceIndex && b.sourceIndex ) { + return a.sourceIndex - b.sourceIndex; + } + + var al, bl, + ap = [], + bp = [], + aup = a.parentNode, + bup = b.parentNode, + cur = aup; + + // If the nodes are siblings (or identical) we can do a quick check + if ( aup === bup ) { + return siblingCheck( a, b ); + + // If no parents were found then the nodes are disconnected + } else if ( !aup ) { + return -1; + + } else if ( !bup ) { + return 1; + } + + // Otherwise they're somewhere else in the tree so we need + // to build up a full list of the parentNodes for comparison + while ( cur ) { + ap.unshift( cur ); + cur = cur.parentNode; + } + + cur = bup; + + while ( cur ) { + bp.unshift( cur ); + cur = cur.parentNode; + } + + al = ap.length; + bl = bp.length; + + // Start walking down the tree looking for a discrepancy + for ( var i = 0; i < al && i < bl; i++ ) { + if ( ap[i] !== bp[i] ) { + return siblingCheck( ap[i], bp[i] ); + } + } + + // We ended someplace up the tree so do a sibling check + return i === al ? + siblingCheck( a, bp[i], -1 ) : + siblingCheck( ap[i], b, 1 ); + }; + +// Always assume the presence of duplicates if sort doesn't +// pass them to our comparison function (as in Google Chrome). +[0, 0].sort( sortOrder ); +baseHasDuplicate = !hasDuplicate; + +// Document sorting and removing duplicates +Sizzle.uniqueSort = function( results ) { + var elem, + duplicates = [], + i = 1, + j = 0; + + hasDuplicate = baseHasDuplicate; + results.sort( sortOrder ); + + if ( hasDuplicate ) { + for ( ; (elem = results[i]); i++ ) { + if ( elem === results[ i - 1 ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } + + return results; +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +function tokenize( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ expando ][ selector + " " ]; + + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); + } + + soFar = selector; + groups = []; + preFilters = Expr.preFilter; + + while ( soFar ) { + + // Comma and first run + if ( !matched || (match = rcomma.exec( soFar )) ) { + if ( match ) { + // Don't consume trailing commas as valid + soFar = soFar.slice( match[0].length ) || soFar; + } + groups.push( tokens = [] ); + } + + matched = false; + + // Combinators + if ( (match = rcombinators.exec( soFar )) ) { + tokens.push( matched = new Token( match.shift() ) ); + soFar = soFar.slice( matched.length ); + + // Cast descendant combinators to space + matched.type = match[0].replace( rtrim, " " ); + } + + // Filters + for ( type in Expr.filter ) { + if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || + (match = preFilters[ type ]( match ))) ) { + + tokens.push( matched = new Token( match.shift() ) ); + soFar = soFar.slice( matched.length ); + matched.type = type; + matched.matches = match; + } + } + + if ( !matched ) { + break; + } + } + + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + return parseOnly ? + soFar.length : + soFar ? + Sizzle.error( selector ) : + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); +} + +function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + checkNonElements = base && combinator.dir === "parentNode", + doneName = done++; + + return combinator.first ? + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( (elem = elem[ dir ]) ) { + if ( checkNonElements || elem.nodeType === 1 ) { + return matcher( elem, context, xml ); + } + } + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching + if ( !xml ) { + var cache, + dirkey = dirruns + " " + doneName + " ", + cachedkey = dirkey + cachedruns; + while ( (elem = elem[ dir ]) ) { + if ( checkNonElements || elem.nodeType === 1 ) { + if ( (cache = elem[ expando ]) === cachedkey ) { + return elem.sizset; + } else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) { + if ( elem.sizset ) { + return elem; + } + } else { + elem[ expando ] = cachedkey; + if ( matcher( elem, context, xml ) ) { + elem.sizset = true; + return elem; + } + elem.sizset = false; + } + } + } + } else { + while ( (elem = elem[ dir ]) ) { + if ( checkNonElements || elem.nodeType === 1 ) { + if ( matcher( elem, context, xml ) ) { + return elem; + } + } + } + } + }; +} + +function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[i]( elem, context, xml ) ) { + return false; + } + } + return true; + } : + matchers[0]; +} + +function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; + + for ( ; i < len; i++ ) { + if ( (elem = unmatched[i]) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); + } + } + } + } + + return newUnmatched; +} + +function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ expando ] ) { + postFilter = setMatcher( postFilter ); + } + if ( postFinder && !postFinder[ expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction(function( seed, results, context, xml ) { + var temp, i, elem, + preMap = [], + postMap = [], + preexisting = results.length, + + // Get initial elements from seed or context + elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), + + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems, + + matcherOut = matcher ? + // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, + postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + + // ...intermediate processing is necessary + [] : + + // ...otherwise use results directly + results : + matcherIn; + + // Find primary matches + if ( matcher ) { + matcher( matcherIn, matcherOut, context, xml ); + } + + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( (elem = temp[i]) ) { + matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); + } + } + } + + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) ) { + // Restore matcherIn since elem is not yet a final match + temp.push( (matcherIn[i] = elem) ); + } + } + postFinder( null, (matcherOut = []), temp, xml ); + } + + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) && + (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { + + seed[temp] = !(results[temp] = elem); + } + } + } + + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } + } + }); +} + +function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = Expr.relative[ tokens[0].type ], + implicitRelative = leadingRelative || Expr.relative[" "], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf.call( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + (checkContext = context).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + } ]; + + for ( ; i < len; i++ ) { + if ( (matcher = Expr.relative[ tokens[i].type ]) ) { + matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ]; + } else { + matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ expando ] ) { + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( Expr.relative[ tokens[j].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), + j < len && tokens.join("") + ); + } + matchers.push( matcher ); + } + } + + return elementMatcher( matchers ); +} + +function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + var bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, expandContext ) { + var elem, j, matcher, + setMatched = [], + matchedCount = 0, + i = "0", + unmatched = seed && [], + outermost = expandContext != null, + contextBackup = outermostContext, + // We must always have either seed elements or context + elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), + // Nested matchers should use non-integer dirruns + dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E); + + if ( outermost ) { + outermostContext = context !== document && context; + cachedruns = superMatcher.el; + } + + // Add elements passing elementMatchers directly to results + for ( ; (elem = elems[i]) != null; i++ ) { + if ( byElement && elem ) { + for ( j = 0; (matcher = elementMatchers[j]); j++ ) { + if ( matcher( elem, context, xml ) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + cachedruns = ++superMatcher.el; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + // They will have gone through all possible matchers + if ( (elem = !matcher && elem) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // Apply set filters to unmatched elements + matchedCount += i; + if ( bySet && i !== matchedCount ) { + for ( j = 0; (matcher = setMatchers[j]); j++ ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !(unmatched[i] || setMatched[i]) ) { + setMatched[i] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + Sizzle.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + superMatcher.el = 0; + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ expando ][ selector + " " ]; + + if ( !cached ) { + // Generate a function of recursive functions that can be used to check each element + if ( !group ) { + group = tokenize( selector ); + } + i = group.length; + while ( i-- ) { + cached = matcherFromTokens( group[i] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); + } + return cached; +}; + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results ); + } + return results; +} + +function select( selector, context, results, seed, xml ) { + var i, tokens, token, type, find, + match = tokenize( selector ), + j = match.length; + + if ( !seed ) { + // Try to minimize operations if there is only one group + if ( match.length === 1 ) { + + // Take a shortcut and set the context if the root selector is an ID + tokens = match[0] = match[0].slice( 0 ); + if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && + context.nodeType === 9 && !xml && + Expr.relative[ tokens[1].type ] ) { + + context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0]; + if ( !context ) { + return results; + } + + selector = selector.slice( tokens.shift().length ); + } + + // Fetch a seed set for right-to-left matching + for ( i = matchExpr["POS"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) { + token = tokens[i]; + + // Abort if we hit a combinator + if ( Expr.relative[ (type = token.type) ] ) { + break; + } + if ( (find = Expr.find[ type ]) ) { + // Search, expanding context for leading sibling combinators + if ( (seed = find( + token.matches[0].replace( rbackslash, "" ), + rsibling.test( tokens[0].type ) && context.parentNode || context, + xml + )) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && tokens.join(""); + if ( !selector ) { + push.apply( results, slice.call( seed, 0 ) ); + return results; + } + + break; + } + } + } + } + } + + // Compile and execute a filtering function + // Provide `match` to avoid retokenization if we modified the selector above + compile( selector, match )( + seed, + context, + xml, + results, + rsibling.test( selector ) + ); + return results; +} + +if ( document.querySelectorAll ) { + (function() { + var disconnectedMatch, + oldSelect = select, + rescape = /'|\\/g, + rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, + + // qSa(:focus) reports false when true (Chrome 21), no need to also add to buggyMatches since matches checks buggyQSA + // A support test would require too much code (would include document ready) + rbuggyQSA = [ ":focus" ], + + // matchesSelector(:active) reports false when true (IE9/Opera 11.5) + // A support test would require too much code (would include document ready) + // just skip matchesSelector for :active + rbuggyMatches = [ ":active" ], + matches = docElem.matchesSelector || + docElem.mozMatchesSelector || + docElem.webkitMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector; + + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert(function( div ) { + // Select is set to empty string on purpose + // This is to test IE's treatment of not explictly + // setting a boolean content attribute, + // since its presence should be enough + // http://bugs.jquery.com/ticket/12359 + div.innerHTML = ""; + + // IE8 - Some boolean attributes are not treated correctly + if ( !div.querySelectorAll("[selected]").length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); + } + + // Webkit/Opera - :checked should return selected option elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + // IE8 throws error here (do not put tests after this one) + if ( !div.querySelectorAll(":checked").length ) { + rbuggyQSA.push(":checked"); + } + }); + + assert(function( div ) { + + // Opera 10-12/IE9 - ^= $= *= and empty values + // Should not select anything + div.innerHTML = "

                              "; + if ( div.querySelectorAll("[test^='']").length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); + } + + // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) + // IE8 throws error here (do not put tests after this one) + div.innerHTML = ""; + if ( !div.querySelectorAll(":enabled").length ) { + rbuggyQSA.push(":enabled", ":disabled"); + } + }); + + // rbuggyQSA always contains :focus, so no need for a length check + rbuggyQSA = /* rbuggyQSA.length && */ new RegExp( rbuggyQSA.join("|") ); + + select = function( selector, context, results, seed, xml ) { + // Only use querySelectorAll when not filtering, + // when this is not xml, + // and when no QSA bugs apply + if ( !seed && !xml && !rbuggyQSA.test( selector ) ) { + var groups, i, + old = true, + nid = expando, + newContext = context, + newSelector = context.nodeType === 9 && selector; + + // qSA works strangely on Element-rooted queries + // We can work around this by specifying an extra ID on the root + // and working up from there (Thanks to Andrew Dupont for the technique) + // IE 8 doesn't work on object elements + if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { + groups = tokenize( selector ); + + if ( (old = context.getAttribute("id")) ) { + nid = old.replace( rescape, "\\$&" ); + } else { + context.setAttribute( "id", nid ); + } + nid = "[id='" + nid + "'] "; + + i = groups.length; + while ( i-- ) { + groups[i] = nid + groups[i].join(""); + } + newContext = rsibling.test( selector ) && context.parentNode || context; + newSelector = groups.join(","); + } + + if ( newSelector ) { + try { + push.apply( results, slice.call( newContext.querySelectorAll( + newSelector + ), 0 ) ); + return results; + } catch(qsaError) { + } finally { + if ( !old ) { + context.removeAttribute("id"); + } + } + } + } + + return oldSelect( selector, context, results, seed, xml ); + }; + + if ( matches ) { + assert(function( div ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + disconnectedMatch = matches.call( div, "div" ); + + // This should fail with an exception + // Gecko does not error, returns false instead + try { + matches.call( div, "[test!='']:sizzle" ); + rbuggyMatches.push( "!=", pseudos ); + } catch ( e ) {} + }); + + // rbuggyMatches always contains :active and :focus, so no need for a length check + rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") ); + + Sizzle.matchesSelector = function( elem, expr ) { + // Make sure that attribute selectors are quoted + expr = expr.replace( rattributeQuotes, "='$1']" ); + + // rbuggyMatches always contains :active, so no need for an existence check + if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && !rbuggyQSA.test( expr ) ) { + try { + var ret = matches.call( elem, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9 + elem.document && elem.document.nodeType !== 11 ) { + return ret; + } + } catch(e) {} + } + + return Sizzle( expr, null, null, [ elem ] ).length > 0; + }; + } + })(); +} + +// Deprecated +Expr.pseudos["nth"] = Expr.pseudos["eq"]; + +// Back-compat +function setFilters() {} +Expr.filters = setFilters.prototype = Expr.pseudos; +Expr.setFilters = new setFilters(); + +// Override sizzle attribute retrieval +Sizzle.attr = jQuery.attr; +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[":"] = jQuery.expr.pseudos; +jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; + + +})( window ); +var runtil = /Until$/, + rparentsprev = /^(?:parents|prev(?:Until|All))/, + isSimple = /^.[^:#\[\.,]*$/, + rneedsContext = jQuery.expr.match.needsContext, + // methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend({ + find: function( selector ) { + var i, l, length, n, r, ret, + self = this; + + if ( typeof selector !== "string" ) { + return jQuery( selector ).filter(function() { + for ( i = 0, l = self.length; i < l; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + }); + } + + ret = this.pushStack( "", "find", selector ); + + for ( i = 0, l = this.length; i < l; i++ ) { + length = ret.length; + jQuery.find( selector, this[i], ret ); + + if ( i > 0 ) { + // Make sure that the results are unique + for ( n = length; n < ret.length; n++ ) { + for ( r = 0; r < length; r++ ) { + if ( ret[r] === ret[n] ) { + ret.splice(n--, 1); + break; + } + } + } + } + } + + return ret; + }, + + has: function( target ) { + var i, + targets = jQuery( target, this ), + len = targets.length; + + return this.filter(function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { + return true; + } + } + }); + }, + + not: function( selector ) { + return this.pushStack( winnow(this, selector, false), "not", selector); + }, + + filter: function( selector ) { + return this.pushStack( winnow(this, selector, true), "filter", selector ); + }, + + is: function( selector ) { + return !!selector && ( + typeof selector === "string" ? + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + rneedsContext.test( selector ) ? + jQuery( selector, this.context ).index( this[0] ) >= 0 : + jQuery.filter( selector, this ).length > 0 : + this.filter( selector ).length > 0 ); + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + ret = [], + pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; + + for ( ; i < l; i++ ) { + cur = this[i]; + + while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { + if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { + ret.push( cur ); + break; + } + cur = cur.parentNode; + } + } + + ret = ret.length > 1 ? jQuery.unique( ret ) : ret; + + return this.pushStack( ret, "closest", selectors ); + }, + + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1; + } + + // index in selector + if ( typeof elem === "string" ) { + return jQuery.inArray( this[0], jQuery( elem ) ); + } + + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[0] : elem, this ); + }, + + add: function( selector, context ) { + var set = typeof selector === "string" ? + jQuery( selector, context ) : + jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), + all = jQuery.merge( this.get(), set ); + + return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? + all : + jQuery.unique( all ) ); + }, + + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter(selector) + ); + } +}); + +jQuery.fn.andSelf = jQuery.fn.addBack; + +// A painfully simple check to see if an element is disconnected +// from a document (should be improved, where feasible). +function isDisconnected( node ) { + return !node || !node.parentNode || node.parentNode.nodeType === 11; +} + +function sibling( cur, dir ) { + do { + cur = cur[ dir ]; + } while ( cur && cur.nodeType !== 1 ); + + return cur; +} + +jQuery.each({ + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return jQuery.dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return jQuery.dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return jQuery.dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return jQuery.dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return jQuery.dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return jQuery.dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return jQuery.sibling( elem.firstChild ); + }, + contents: function( elem ) { + return jQuery.nodeName( elem, "iframe" ) ? + elem.contentDocument || elem.contentWindow.document : + jQuery.merge( [], elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var ret = jQuery.map( this, fn, until ); + + if ( !runtil.test( name ) ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + ret = jQuery.filter( selector, ret ); + } + + ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; + + if ( this.length > 1 && rparentsprev.test( name ) ) { + ret = ret.reverse(); + } + + return this.pushStack( ret, name, core_slice.call( arguments ).join(",") ); + }; +}); + +jQuery.extend({ + filter: function( expr, elems, not ) { + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 ? + jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : + jQuery.find.matches(expr, elems); + }, + + dir: function( elem, dir, until ) { + var matched = [], + cur = elem[ dir ]; + + while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { + if ( cur.nodeType === 1 ) { + matched.push( cur ); + } + cur = cur[dir]; + } + return matched; + }, + + sibling: function( n, elem ) { + var r = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + r.push( n ); + } + } + + return r; + } +}); + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, keep ) { + + // Can't pass null or undefined to indexOf in Firefox 4 + // Set to 0 to skip string check + qualifier = qualifier || 0; + + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep(elements, function( elem, i ) { + var retVal = !!qualifier.call( elem, i, elem ); + return retVal === keep; + }); + + } else if ( qualifier.nodeType ) { + return jQuery.grep(elements, function( elem, i ) { + return ( elem === qualifier ) === keep; + }); + + } else if ( typeof qualifier === "string" ) { + var filtered = jQuery.grep(elements, function( elem ) { + return elem.nodeType === 1; + }); + + if ( isSimple.test( qualifier ) ) { + return jQuery.filter(qualifier, filtered, !keep); + } else { + qualifier = jQuery.filter( qualifier, filtered ); + } + } + + return jQuery.grep(elements, function( elem, i ) { + return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; + }); +} +function createSafeFragment( document ) { + var list = nodeNames.split( "|" ), + safeFrag = document.createDocumentFragment(); + + if ( safeFrag.createElement ) { + while ( list.length ) { + safeFrag.createElement( + list.pop() + ); + } + } + return safeFrag; +} + +var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", + rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, + rleadingWhitespace = /^\s+/, + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, + rtagName = /<([\w:]+)/, + rtbody = /
                              ", "
                              " ], + tr: [ 2, "", "
                              " ], + td: [ 3, "", "
                              " ], + col: [ 2, "", "
                              " ], + area: [ 1, "", "" ], + _default: [ 0, "", "" ] + }, + safeFragment = createSafeFragment( document ), + fragmentDiv = safeFragment.appendChild( document.createElement("div") ); + +wrapMap.optgroup = wrapMap.option; +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, +// unless wrapped in a div with non-breaking characters in front of it. +if ( !jQuery.support.htmlSerialize ) { + wrapMap._default = [ 1, "X
                              ", "
                              " ]; +} + +jQuery.fn.extend({ + text: function( value ) { + return jQuery.access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); + }, null, value, arguments.length ); + }, + + wrapAll: function( html ) { + if ( jQuery.isFunction( html ) ) { + return this.each(function(i) { + jQuery(this).wrapAll( html.call(this, i) ); + }); + } + + if ( this[0] ) { + // The elements to wrap the target around + var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); + + if ( this[0].parentNode ) { + wrap.insertBefore( this[0] ); + } + + wrap.map(function() { + var elem = this; + + while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { + elem = elem.firstChild; + } + + return elem; + }).append( this ); + } + + return this; + }, + + wrapInner: function( html ) { + if ( jQuery.isFunction( html ) ) { + return this.each(function(i) { + jQuery(this).wrapInner( html.call(this, i) ); + }); + } + + return this.each(function() { + var self = jQuery( this ), + contents = self.contents(); + + if ( contents.length ) { + contents.wrapAll( html ); + + } else { + self.append( html ); + } + }); + }, + + wrap: function( html ) { + var isFunction = jQuery.isFunction( html ); + + return this.each(function(i) { + jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); + }); + }, + + unwrap: function() { + return this.parent().each(function() { + if ( !jQuery.nodeName( this, "body" ) ) { + jQuery( this ).replaceWith( this.childNodes ); + } + }).end(); + }, + + append: function() { + return this.domManip(arguments, true, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 ) { + this.appendChild( elem ); + } + }); + }, + + prepend: function() { + return this.domManip(arguments, true, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 ) { + this.insertBefore( elem, this.firstChild ); + } + }); + }, + + before: function() { + if ( !isDisconnected( this[0] ) ) { + return this.domManip(arguments, false, function( elem ) { + this.parentNode.insertBefore( elem, this ); + }); + } + + if ( arguments.length ) { + var set = jQuery.clean( arguments ); + return this.pushStack( jQuery.merge( set, this ), "before", this.selector ); + } + }, + + after: function() { + if ( !isDisconnected( this[0] ) ) { + return this.domManip(arguments, false, function( elem ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + }); + } + + if ( arguments.length ) { + var set = jQuery.clean( arguments ); + return this.pushStack( jQuery.merge( this, set ), "after", this.selector ); + } + }, + + // keepData is for internal use only--do not document + remove: function( selector, keepData ) { + var elem, + i = 0; + + for ( ; (elem = this[i]) != null; i++ ) { + if ( !selector || jQuery.filter( selector, [ elem ] ).length ) { + if ( !keepData && elem.nodeType === 1 ) { + jQuery.cleanData( elem.getElementsByTagName("*") ); + jQuery.cleanData( [ elem ] ); + } + + if ( elem.parentNode ) { + elem.parentNode.removeChild( elem ); + } + } + } + + return this; + }, + + empty: function() { + var elem, + i = 0; + + for ( ; (elem = this[i]) != null; i++ ) { + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( elem.getElementsByTagName("*") ); + } + + // Remove any remaining nodes + while ( elem.firstChild ) { + elem.removeChild( elem.firstChild ); + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? false : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map( function () { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + }); + }, + + html: function( value ) { + return jQuery.access( this, function( value ) { + var elem = this[0] || {}, + i = 0, + l = this.length; + + if ( value === undefined ) { + return elem.nodeType === 1 ? + elem.innerHTML.replace( rinlinejQuery, "" ) : + undefined; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && + ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && + !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { + + value = value.replace( rxhtmlTag, "<$1>" ); + + try { + for (; i < l; i++ ) { + // Remove element nodes and prevent memory leaks + elem = this[i] || {}; + if ( elem.nodeType === 1 ) { + jQuery.cleanData( elem.getElementsByTagName( "*" ) ); + elem.innerHTML = value; + } + } + + elem = 0; + + // If using innerHTML throws an exception, use the fallback method + } catch(e) {} + } + + if ( elem ) { + this.empty().append( value ); + } + }, null, value, arguments.length ); + }, + + replaceWith: function( value ) { + if ( !isDisconnected( this[0] ) ) { + // Make sure that the elements are removed from the DOM before they are inserted + // this can help fix replacing a parent with child elements + if ( jQuery.isFunction( value ) ) { + return this.each(function(i) { + var self = jQuery(this), old = self.html(); + self.replaceWith( value.call( this, i, old ) ); + }); + } + + if ( typeof value !== "string" ) { + value = jQuery( value ).detach(); + } + + return this.each(function() { + var next = this.nextSibling, + parent = this.parentNode; + + jQuery( this ).remove(); + + if ( next ) { + jQuery(next).before( value ); + } else { + jQuery(parent).append( value ); + } + }); + } + + return this.length ? + this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : + this; + }, + + detach: function( selector ) { + return this.remove( selector, true ); + }, + + domManip: function( args, table, callback ) { + + // Flatten any nested arrays + args = [].concat.apply( [], args ); + + var results, first, fragment, iNoClone, + i = 0, + value = args[0], + scripts = [], + l = this.length; + + // We can't cloneNode fragments that contain checked, in WebKit + if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) { + return this.each(function() { + jQuery(this).domManip( args, table, callback ); + }); + } + + if ( jQuery.isFunction(value) ) { + return this.each(function(i) { + var self = jQuery(this); + args[0] = value.call( this, i, table ? self.html() : undefined ); + self.domManip( args, table, callback ); + }); + } + + if ( this[0] ) { + results = jQuery.buildFragment( args, this, scripts ); + fragment = results.fragment; + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + if ( first ) { + table = table && jQuery.nodeName( first, "tr" ); + + // Use the original fragment for the last item instead of the first because it can end up + // being emptied incorrectly in certain situations (#8070). + // Fragments from the fragment cache must always be cloned and never used in place. + for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) { + callback.call( + table && jQuery.nodeName( this[i], "table" ) ? + findOrAppend( this[i], "tbody" ) : + this[i], + i === iNoClone ? + fragment : + jQuery.clone( fragment, true, true ) + ); + } + } + + // Fix #11809: Avoid leaking memory + fragment = first = null; + + if ( scripts.length ) { + jQuery.each( scripts, function( i, elem ) { + if ( elem.src ) { + if ( jQuery.ajax ) { + jQuery.ajax({ + url: elem.src, + type: "GET", + dataType: "script", + async: false, + global: false, + "throws": true + }); + } else { + jQuery.error("no ajax"); + } + } else { + jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) ); + } + + if ( elem.parentNode ) { + elem.parentNode.removeChild( elem ); + } + }); + } + } + + return this; + } +}); + +function findOrAppend( elem, tag ) { + return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); +} + +function cloneCopyEvent( src, dest ) { + + if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { + return; + } + + var type, i, l, + oldData = jQuery._data( src ), + curData = jQuery._data( dest, oldData ), + events = oldData.events; + + if ( events ) { + delete curData.handle; + curData.events = {}; + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + + // make the cloned public data object a copy from the original + if ( curData.data ) { + curData.data = jQuery.extend( {}, curData.data ); + } +} + +function cloneFixAttributes( src, dest ) { + var nodeName; + + // We do not need to do anything for non-Elements + if ( dest.nodeType !== 1 ) { + return; + } + + // clearAttributes removes the attributes, which we don't want, + // but also removes the attachEvent events, which we *do* want + if ( dest.clearAttributes ) { + dest.clearAttributes(); + } + + // mergeAttributes, in contrast, only merges back on the + // original attributes, not the events + if ( dest.mergeAttributes ) { + dest.mergeAttributes( src ); + } + + nodeName = dest.nodeName.toLowerCase(); + + if ( nodeName === "object" ) { + // IE6-10 improperly clones children of object elements using classid. + // IE10 throws NoModificationAllowedError if parent is null, #12132. + if ( dest.parentNode ) { + dest.outerHTML = src.outerHTML; + } + + // This path appears unavoidable for IE9. When cloning an object + // element in IE9, the outerHTML strategy above is not sufficient. + // If the src has innerHTML and the destination does not, + // copy the src.innerHTML into the dest.innerHTML. #10324 + if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) { + dest.innerHTML = src.innerHTML; + } + + } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { + // IE6-8 fails to persist the checked state of a cloned checkbox + // or radio button. Worse, IE6-7 fail to give the cloned element + // a checked appearance if the defaultChecked value isn't also set + + dest.defaultChecked = dest.checked = src.checked; + + // IE6-7 get confused and end up setting the value of a cloned + // checkbox/radio button to an empty string instead of "on" + if ( dest.value !== src.value ) { + dest.value = src.value; + } + + // IE6-8 fails to return the selected option to the default selected + // state when cloning options + } else if ( nodeName === "option" ) { + dest.selected = src.defaultSelected; + + // IE6-8 fails to set the defaultValue to the correct value when + // cloning other types of input fields + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + + // IE blanks contents when cloning scripts + } else if ( nodeName === "script" && dest.text !== src.text ) { + dest.text = src.text; + } + + // Event data gets referenced instead of copied if the expando + // gets copied too + dest.removeAttribute( jQuery.expando ); +} + +jQuery.buildFragment = function( args, context, scripts ) { + var fragment, cacheable, cachehit, + first = args[ 0 ]; + + // Set context from what may come in as undefined or a jQuery collection or a node + // Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 & + // also doubles as fix for #8950 where plain objects caused createDocumentFragment exception + context = context || document; + context = !context.nodeType && context[0] || context; + context = context.ownerDocument || context; + + // Only cache "small" (1/2 KB) HTML strings that are associated with the main document + // Cloning options loses the selected state, so don't cache them + // IE 6 doesn't like it when you put or elements in a fragment + // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache + // Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501 + if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document && + first.charAt(0) === "<" && !rnocache.test( first ) && + (jQuery.support.checkClone || !rchecked.test( first )) && + (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { + + // Mark cacheable and look for a hit + cacheable = true; + fragment = jQuery.fragments[ first ]; + cachehit = fragment !== undefined; + } + + if ( !fragment ) { + fragment = context.createDocumentFragment(); + jQuery.clean( args, context, fragment, scripts ); + + // Update the cache, but only store false + // unless this is a second parsing of the same content + if ( cacheable ) { + jQuery.fragments[ first ] = cachehit && fragment; + } + } + + return { fragment: fragment, cacheable: cacheable }; +}; + +jQuery.fragments = {}; + +jQuery.each({ + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + i = 0, + ret = [], + insert = jQuery( selector ), + l = insert.length, + parent = this.length === 1 && this[0].parentNode; + + if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) { + insert[ original ]( this[0] ); + return this; + } else { + for ( ; i < l; i++ ) { + elems = ( i > 0 ? this.clone(true) : this ).get(); + jQuery( insert[i] )[ original ]( elems ); + ret = ret.concat( elems ); + } + + return this.pushStack( ret, name, insert.selector ); + } + }; +}); + +function getAll( elem ) { + if ( typeof elem.getElementsByTagName !== "undefined" ) { + return elem.getElementsByTagName( "*" ); + + } else if ( typeof elem.querySelectorAll !== "undefined" ) { + return elem.querySelectorAll( "*" ); + + } else { + return []; + } +} + +// Used in clean, fixes the defaultChecked property +function fixDefaultChecked( elem ) { + if ( rcheckableType.test( elem.type ) ) { + elem.defaultChecked = elem.checked; + } +} + +jQuery.extend({ + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var srcElements, + destElements, + i, + clone; + + if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { + clone = elem.cloneNode( true ); + + // IE<=8 does not properly clone detached, unknown element nodes + } else { + fragmentDiv.innerHTML = elem.outerHTML; + fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); + } + + if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && + (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { + // IE copies events bound via attachEvent when using cloneNode. + // Calling detachEvent on the clone will also remove the events + // from the original. In order to get around this, we use some + // proprietary methods to clear the events. Thanks to MooTools + // guys for this hotness. + + cloneFixAttributes( elem, clone ); + + // Using Sizzle here is crazy slow, so we use getElementsByTagName instead + srcElements = getAll( elem ); + destElements = getAll( clone ); + + // Weird iteration because IE will replace the length property + // with an element if you are cloning the body and one of the + // elements on the page has a name or id of "length" + for ( i = 0; srcElements[i]; ++i ) { + // Ensure that the destination node is not null; Fixes #9587 + if ( destElements[i] ) { + cloneFixAttributes( srcElements[i], destElements[i] ); + } + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + cloneCopyEvent( elem, clone ); + + if ( deepDataAndEvents ) { + srcElements = getAll( elem ); + destElements = getAll( clone ); + + for ( i = 0; srcElements[i]; ++i ) { + cloneCopyEvent( srcElements[i], destElements[i] ); + } + } + } + + srcElements = destElements = null; + + // Return the cloned set + return clone; + }, + + clean: function( elems, context, fragment, scripts ) { + var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags, + safe = context === document && safeFragment, + ret = []; + + // Ensure that context is a document + if ( !context || typeof context.createDocumentFragment === "undefined" ) { + context = document; + } + + // Use the already-created safe fragment if context permits + for ( i = 0; (elem = elems[i]) != null; i++ ) { + if ( typeof elem === "number" ) { + elem += ""; + } + + if ( !elem ) { + continue; + } + + // Convert html string into DOM nodes + if ( typeof elem === "string" ) { + if ( !rhtml.test( elem ) ) { + elem = context.createTextNode( elem ); + } else { + // Ensure a safe container in which to render the html + safe = safe || createSafeFragment( context ); + div = context.createElement("div"); + safe.appendChild( div ); + + // Fix "XHTML"-style tags in all browsers + elem = elem.replace(rxhtmlTag, "<$1>"); + + // Go to html and back, then peel off extra wrappers + tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + depth = wrap[0]; + div.innerHTML = wrap[1] + elem + wrap[2]; + + // Move to the right depth + while ( depth-- ) { + div = div.lastChild; + } + + // Remove IE's autoinserted
                              , *may* have spurious + hasBody = rtbody.test(elem); + tbody = tag === "table" && !hasBody ? + div.firstChild && div.firstChild.childNodes : + + // String was a bare or + wrap[1] === "
                              " && !hasBody ? + div.childNodes : + []; + + for ( j = tbody.length - 1; j >= 0 ; --j ) { + if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { + tbody[ j ].parentNode.removeChild( tbody[ j ] ); + } + } + } + + // IE completely kills leading whitespace when innerHTML is used + if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { + div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); + } + + elem = div.childNodes; + + // Take out of fragment container (we need a fresh div each time) + div.parentNode.removeChild( div ); + } + } + + if ( elem.nodeType ) { + ret.push( elem ); + } else { + jQuery.merge( ret, elem ); + } + } + + // Fix #11356: Clear elements from safeFragment + if ( div ) { + elem = div = safe = null; + } + + // Reset defaultChecked for any radios and checkboxes + // about to be appended to the DOM in IE 6/7 (#8060) + if ( !jQuery.support.appendChecked ) { + for ( i = 0; (elem = ret[i]) != null; i++ ) { + if ( jQuery.nodeName( elem, "input" ) ) { + fixDefaultChecked( elem ); + } else if ( typeof elem.getElementsByTagName !== "undefined" ) { + jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); + } + } + } + + // Append elements to a provided document fragment + if ( fragment ) { + // Special handling of each script element + handleScript = function( elem ) { + // Check if we consider it executable + if ( !elem.type || rscriptType.test( elem.type ) ) { + // Detach the script and store it in the scripts array (if provided) or the fragment + // Return truthy to indicate that it has been handled + return scripts ? + scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) : + fragment.appendChild( elem ); + } + }; + + for ( i = 0; (elem = ret[i]) != null; i++ ) { + // Check if we're done after handling an executable script + if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) { + // Append to fragment and handle embedded scripts + fragment.appendChild( elem ); + if ( typeof elem.getElementsByTagName !== "undefined" ) { + // handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration + jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript ); + + // Splice the scripts into ret after their former ancestor and advance our index beyond them + ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); + i += jsTags.length; + } + } + } + } + + return ret; + }, + + cleanData: function( elems, /* internal */ acceptData ) { + var data, id, elem, type, + i = 0, + internalKey = jQuery.expando, + cache = jQuery.cache, + deleteExpando = jQuery.support.deleteExpando, + special = jQuery.event.special; + + for ( ; (elem = elems[i]) != null; i++ ) { + + if ( acceptData || jQuery.acceptData( elem ) ) { + + id = elem[ internalKey ]; + data = id && cache[ id ]; + + if ( data ) { + if ( data.events ) { + for ( type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + } + + // Remove cache only if it was not already removed by jQuery.event.remove + if ( cache[ id ] ) { + + delete cache[ id ]; + + // IE does not allow us to delete expando properties from nodes, + // nor does it have a removeAttribute function on Document nodes; + // we must handle all of these cases + if ( deleteExpando ) { + delete elem[ internalKey ]; + + } else if ( elem.removeAttribute ) { + elem.removeAttribute( internalKey ); + + } else { + elem[ internalKey ] = null; + } + + jQuery.deletedIds.push( id ); + } + } + } + } + } +}); +// Limit scope pollution from any deprecated API +(function() { + +var matched, browser; + +// Use of jQuery.browser is frowned upon. +// More details: http://api.jquery.com/jQuery.browser +// jQuery.uaMatch maintained for back-compat +jQuery.uaMatch = function( ua ) { + ua = ua.toLowerCase(); + + var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) || + /(webkit)[ \/]([\w.]+)/.exec( ua ) || + /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) || + /(msie) ([\w.]+)/.exec( ua ) || + ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) || + []; + + return { + browser: match[ 1 ] || "", + version: match[ 2 ] || "0" + }; +}; + +matched = jQuery.uaMatch( navigator.userAgent ); +browser = {}; + +if ( matched.browser ) { + browser[ matched.browser ] = true; + browser.version = matched.version; +} + +// Chrome is Webkit, but Webkit is also Safari. +if ( browser.chrome ) { + browser.webkit = true; +} else if ( browser.webkit ) { + browser.safari = true; +} + +jQuery.browser = browser; + +jQuery.sub = function() { + function jQuerySub( selector, context ) { + return new jQuerySub.fn.init( selector, context ); + } + jQuery.extend( true, jQuerySub, this ); + jQuerySub.superclass = this; + jQuerySub.fn = jQuerySub.prototype = this(); + jQuerySub.fn.constructor = jQuerySub; + jQuerySub.sub = this.sub; + jQuerySub.fn.init = function init( selector, context ) { + if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { + context = jQuerySub( context ); + } + + return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); + }; + jQuerySub.fn.init.prototype = jQuerySub.fn; + var rootjQuerySub = jQuerySub(document); + return jQuerySub; +}; + +})(); +var curCSS, iframe, iframeDoc, + ralpha = /alpha\([^)]*\)/i, + ropacity = /opacity=([^)]*)/, + rposition = /^(top|right|bottom|left)$/, + // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" + // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display + rdisplayswap = /^(none|table(?!-c[ea]).+)/, + rmargin = /^margin/, + rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), + rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), + rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ), + elemdisplay = { BODY: "block" }, + + cssShow = { position: "absolute", visibility: "hidden", display: "block" }, + cssNormalTransform = { + letterSpacing: 0, + fontWeight: 400 + }, + + cssExpand = [ "Top", "Right", "Bottom", "Left" ], + cssPrefixes = [ "Webkit", "O", "Moz", "ms" ], + + eventsToggle = jQuery.fn.toggle; + +// return a css property mapped to a potentially vendor prefixed property +function vendorPropName( style, name ) { + + // shortcut for names that are not vendor prefixed + if ( name in style ) { + return name; + } + + // check for vendor prefixed names + var capName = name.charAt(0).toUpperCase() + name.slice(1), + origName = name, + i = cssPrefixes.length; + + while ( i-- ) { + name = cssPrefixes[ i ] + capName; + if ( name in style ) { + return name; + } + } + + return origName; +} + +function isHidden( elem, el ) { + elem = el || elem; + return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); +} + +function showHide( elements, show ) { + var elem, display, + values = [], + index = 0, + length = elements.length; + + for ( ; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + values[ index ] = jQuery._data( elem, "olddisplay" ); + if ( show ) { + // Reset the inline display of this element to learn if it is + // being hidden by cascaded rules or not + if ( !values[ index ] && elem.style.display === "none" ) { + elem.style.display = ""; + } + + // Set elements which have been overridden with display: none + // in a stylesheet to whatever the default browser style is + // for such an element + if ( elem.style.display === "" && isHidden( elem ) ) { + values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); + } + } else { + display = curCSS( elem, "display" ); + + if ( !values[ index ] && display !== "none" ) { + jQuery._data( elem, "olddisplay", display ); + } + } + } + + // Set the display of most of the elements in a second loop + // to avoid the constant reflow + for ( index = 0; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + if ( !show || elem.style.display === "none" || elem.style.display === "" ) { + elem.style.display = show ? values[ index ] || "" : "none"; + } + } + + return elements; +} + +jQuery.fn.extend({ + css: function( name, value ) { + return jQuery.access( this, function( elem, name, value ) { + return value !== undefined ? + jQuery.style( elem, name, value ) : + jQuery.css( elem, name ); + }, name, value, arguments.length > 1 ); + }, + show: function() { + return showHide( this, true ); + }, + hide: function() { + return showHide( this ); + }, + toggle: function( state, fn2 ) { + var bool = typeof state === "boolean"; + + if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) { + return eventsToggle.apply( this, arguments ); + } + + return this.each(function() { + if ( bool ? state : isHidden( this ) ) { + jQuery( this ).show(); + } else { + jQuery( this ).hide(); + } + }); + } +}); + +jQuery.extend({ + // Add in style property hooks for overriding the default + // behavior of getting and setting a style property + cssHooks: { + opacity: { + get: function( elem, computed ) { + if ( computed ) { + // We should always get a number back from opacity + var ret = curCSS( elem, "opacity" ); + return ret === "" ? "1" : ret; + + } + } + } + }, + + // Exclude the following css properties to add px + cssNumber: { + "fillOpacity": true, + "fontWeight": true, + "lineHeight": true, + "opacity": true, + "orphans": true, + "widows": true, + "zIndex": true, + "zoom": true + }, + + // Add in properties whose names you wish to fix before + // setting or getting the value + cssProps: { + // normalize float css property + "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" + }, + + // Get and set the style property on a DOM Node + style: function( elem, name, value, extra ) { + // Don't set styles on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { + return; + } + + // Make sure that we're working with the right name + var ret, type, hooks, + origName = jQuery.camelCase( name ), + style = elem.style; + + name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); + + // gets hook for the prefixed version + // followed by the unprefixed version + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // Check if we're setting a value + if ( value !== undefined ) { + type = typeof value; + + // convert relative number strings (+= or -=) to relative numbers. #7345 + if ( type === "string" && (ret = rrelNum.exec( value )) ) { + value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); + // Fixes bug #9237 + type = "number"; + } + + // Make sure that NaN and null values aren't set. See: #7116 + if ( value == null || type === "number" && isNaN( value ) ) { + return; + } + + // If a number was passed in, add 'px' to the (except for certain CSS properties) + if ( type === "number" && !jQuery.cssNumber[ origName ] ) { + value += "px"; + } + + // If a hook was provided, use that value, otherwise just set the specified value + if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { + // Wrapped to prevent IE from throwing errors when 'invalid' values are provided + // Fixes bug #5509 + try { + style[ name ] = value; + } catch(e) {} + } + + } else { + // If a hook was provided get the non-computed value from there + if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { + return ret; + } + + // Otherwise just get the value from the style object + return style[ name ]; + } + }, + + css: function( elem, name, numeric, extra ) { + var val, num, hooks, + origName = jQuery.camelCase( name ); + + // Make sure that we're working with the right name + name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); + + // gets hook for the prefixed version + // followed by the unprefixed version + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // If a hook was provided get the computed value from there + if ( hooks && "get" in hooks ) { + val = hooks.get( elem, true, extra ); + } + + // Otherwise, if a way to get the computed value exists, use that + if ( val === undefined ) { + val = curCSS( elem, name ); + } + + //convert "normal" to computed value + if ( val === "normal" && name in cssNormalTransform ) { + val = cssNormalTransform[ name ]; + } + + // Return, converting to number if forced or a qualifier was provided and val looks numeric + if ( numeric || extra !== undefined ) { + num = parseFloat( val ); + return numeric || jQuery.isNumeric( num ) ? num || 0 : val; + } + return val; + }, + + // A method for quickly swapping in/out CSS properties to get correct calculations + swap: function( elem, options, callback ) { + var ret, name, + old = {}; + + // Remember the old values, and insert the new ones + for ( name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } + + ret = callback.call( elem ); + + // Revert the old values + for ( name in options ) { + elem.style[ name ] = old[ name ]; + } + + return ret; + } +}); + +// NOTE: To any future maintainer, we've window.getComputedStyle +// because jsdom on node.js will break without it. +if ( window.getComputedStyle ) { + curCSS = function( elem, name ) { + var ret, width, minWidth, maxWidth, + computed = window.getComputedStyle( elem, null ), + style = elem.style; + + if ( computed ) { + + // getPropertyValue is only needed for .css('filter') in IE9, see #12537 + ret = computed.getPropertyValue( name ) || computed[ name ]; + + if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { + ret = jQuery.style( elem, name ); + } + + // A tribute to the "awesome hack by Dean Edwards" + // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right + // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels + // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values + if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { + width = style.width; + minWidth = style.minWidth; + maxWidth = style.maxWidth; + + style.minWidth = style.maxWidth = style.width = ret; + ret = computed.width; + + style.width = width; + style.minWidth = minWidth; + style.maxWidth = maxWidth; + } + } + + return ret; + }; +} else if ( document.documentElement.currentStyle ) { + curCSS = function( elem, name ) { + var left, rsLeft, + ret = elem.currentStyle && elem.currentStyle[ name ], + style = elem.style; + + // Avoid setting ret to empty string here + // so we don't default to auto + if ( ret == null && style && style[ name ] ) { + ret = style[ name ]; + } + + // From the awesome hack by Dean Edwards + // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 + + // If we're not dealing with a regular pixel number + // but a number that has a weird ending, we need to convert it to pixels + // but not position css attributes, as those are proportional to the parent element instead + // and we can't measure the parent instead because it might trigger a "stacking dolls" problem + if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { + + // Remember the original values + left = style.left; + rsLeft = elem.runtimeStyle && elem.runtimeStyle.left; + + // Put in the new values to get a computed value out + if ( rsLeft ) { + elem.runtimeStyle.left = elem.currentStyle.left; + } + style.left = name === "fontSize" ? "1em" : ret; + ret = style.pixelLeft + "px"; + + // Revert the changed values + style.left = left; + if ( rsLeft ) { + elem.runtimeStyle.left = rsLeft; + } + } + + return ret === "" ? "auto" : ret; + }; +} + +function setPositiveNumber( elem, value, subtract ) { + var matches = rnumsplit.exec( value ); + return matches ? + Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : + value; +} + +function augmentWidthOrHeight( elem, name, extra, isBorderBox ) { + var i = extra === ( isBorderBox ? "border" : "content" ) ? + // If we already have the right measurement, avoid augmentation + 4 : + // Otherwise initialize for horizontal or vertical properties + name === "width" ? 1 : 0, + + val = 0; + + for ( ; i < 4; i += 2 ) { + // both box models exclude margin, so add it if we want it + if ( extra === "margin" ) { + // we use jQuery.css instead of curCSS here + // because of the reliableMarginRight CSS hook! + val += jQuery.css( elem, extra + cssExpand[ i ], true ); + } + + // From this point on we use curCSS for maximum performance (relevant in animations) + if ( isBorderBox ) { + // border-box includes padding, so remove it if we want content + if ( extra === "content" ) { + val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; + } + + // at this point, extra isn't border nor margin, so remove border + if ( extra !== "margin" ) { + val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; + } + } else { + // at this point, extra isn't content, so add padding + val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; + + // at this point, extra isn't content nor padding, so add border + if ( extra !== "padding" ) { + val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; + } + } + } + + return val; +} + +function getWidthOrHeight( elem, name, extra ) { + + // Start with offset property, which is equivalent to the border-box value + var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, + valueIsBorderBox = true, + isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"; + + // some non-html elements return undefined for offsetWidth, so check for null/undefined + // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 + // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 + if ( val <= 0 || val == null ) { + // Fall back to computed then uncomputed css if necessary + val = curCSS( elem, name ); + if ( val < 0 || val == null ) { + val = elem.style[ name ]; + } + + // Computed unit is not pixels. Stop here and return. + if ( rnumnonpx.test(val) ) { + return val; + } + + // we need the check for style in case a browser which returns unreliable values + // for getComputedStyle silently falls back to the reliable elem.style + valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); + + // Normalize "", auto, and prepare for extra + val = parseFloat( val ) || 0; + } + + // use the active box-sizing model to add/subtract irrelevant styles + return ( val + + augmentWidthOrHeight( + elem, + name, + extra || ( isBorderBox ? "border" : "content" ), + valueIsBorderBox + ) + ) + "px"; +} + + +// Try to determine the default display value of an element +function css_defaultDisplay( nodeName ) { + if ( elemdisplay[ nodeName ] ) { + return elemdisplay[ nodeName ]; + } + + var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ), + display = elem.css("display"); + elem.remove(); + + // If the simple way fails, + // get element's real default display by attaching it to a temp iframe + if ( display === "none" || display === "" ) { + // Use the already-created iframe if possible + iframe = document.body.appendChild( + iframe || jQuery.extend( document.createElement("iframe"), { + frameBorder: 0, + width: 0, + height: 0 + }) + ); + + // Create a cacheable copy of the iframe document on first call. + // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML + // document to it; WebKit & Firefox won't allow reusing the iframe document. + if ( !iframeDoc || !iframe.createElement ) { + iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; + iframeDoc.write(""); + iframeDoc.close(); + } + + elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) ); + + display = curCSS( elem, "display" ); + document.body.removeChild( iframe ); + } + + // Store the correct default display + elemdisplay[ nodeName ] = display; + + return display; +} + +jQuery.each([ "height", "width" ], function( i, name ) { + jQuery.cssHooks[ name ] = { + get: function( elem, computed, extra ) { + if ( computed ) { + // certain elements can have dimension info if we invisibly show them + // however, it must have a current display style that would benefit from this + if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) { + return jQuery.swap( elem, cssShow, function() { + return getWidthOrHeight( elem, name, extra ); + }); + } else { + return getWidthOrHeight( elem, name, extra ); + } + } + }, + + set: function( elem, value, extra ) { + return setPositiveNumber( elem, value, extra ? + augmentWidthOrHeight( + elem, + name, + extra, + jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box" + ) : 0 + ); + } + }; +}); + +if ( !jQuery.support.opacity ) { + jQuery.cssHooks.opacity = { + get: function( elem, computed ) { + // IE uses filters for opacity + return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? + ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : + computed ? "1" : ""; + }, + + set: function( elem, value ) { + var style = elem.style, + currentStyle = elem.currentStyle, + opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", + filter = currentStyle && currentStyle.filter || style.filter || ""; + + // IE has trouble with opacity if it does not have layout + // Force it by setting the zoom level + style.zoom = 1; + + // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 + if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && + style.removeAttribute ) { + + // Setting style.filter to null, "" & " " still leave "filter:" in the cssText + // if "filter:" is present at all, clearType is disabled, we want to avoid this + // style.removeAttribute is IE Only, but so apparently is this code path... + style.removeAttribute( "filter" ); + + // if there there is no filter style applied in a css rule, we are done + if ( currentStyle && !currentStyle.filter ) { + return; + } + } + + // otherwise, set new filter values + style.filter = ralpha.test( filter ) ? + filter.replace( ralpha, opacity ) : + filter + " " + opacity; + } + }; +} + +// These hooks cannot be added until DOM ready because the support test +// for it is not run until after DOM ready +jQuery(function() { + if ( !jQuery.support.reliableMarginRight ) { + jQuery.cssHooks.marginRight = { + get: function( elem, computed ) { + // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right + // Work around by temporarily setting element display to inline-block + return jQuery.swap( elem, { "display": "inline-block" }, function() { + if ( computed ) { + return curCSS( elem, "marginRight" ); + } + }); + } + }; + } + + // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 + // getComputedStyle returns percent when specified for top/left/bottom/right + // rather than make the css module depend on the offset module, we just check for it here + if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { + jQuery.each( [ "top", "left" ], function( i, prop ) { + jQuery.cssHooks[ prop ] = { + get: function( elem, computed ) { + if ( computed ) { + var ret = curCSS( elem, prop ); + // if curCSS returns percentage, fallback to offset + return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret; + } + } + }; + }); + } + +}); + +if ( jQuery.expr && jQuery.expr.filters ) { + jQuery.expr.filters.hidden = function( elem ) { + return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( elem, "display" )) === "none"); + }; + + jQuery.expr.filters.visible = function( elem ) { + return !jQuery.expr.filters.hidden( elem ); + }; +} + +// These hooks are used by animate to expand properties +jQuery.each({ + margin: "", + padding: "", + border: "Width" +}, function( prefix, suffix ) { + jQuery.cssHooks[ prefix + suffix ] = { + expand: function( value ) { + var i, + + // assumes a single number if not a string + parts = typeof value === "string" ? value.split(" ") : [ value ], + expanded = {}; + + for ( i = 0; i < 4; i++ ) { + expanded[ prefix + cssExpand[ i ] + suffix ] = + parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; + } + + return expanded; + } + }; + + if ( !rmargin.test( prefix ) ) { + jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; + } +}); +var r20 = /%20/g, + rbracket = /\[\]$/, + rCRLF = /\r?\n/g, + rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, + rselectTextarea = /^(?:select|textarea)/i; + +jQuery.fn.extend({ + serialize: function() { + return jQuery.param( this.serializeArray() ); + }, + serializeArray: function() { + return this.map(function(){ + return this.elements ? jQuery.makeArray( this.elements ) : this; + }) + .filter(function(){ + return this.name && !this.disabled && + ( this.checked || rselectTextarea.test( this.nodeName ) || + rinput.test( this.type ) ); + }) + .map(function( i, elem ){ + var val = jQuery( this ).val(); + + return val == null ? + null : + jQuery.isArray( val ) ? + jQuery.map( val, function( val, i ){ + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + }) : + { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + }).get(); + } +}); + +//Serialize an array of form elements or a set of +//key/values into a query string +jQuery.param = function( a, traditional ) { + var prefix, + s = [], + add = function( key, value ) { + // If value is a function, invoke it and return its value + value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); + s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); + }; + + // Set traditional to true for jQuery <= 1.3.2 behavior. + if ( traditional === undefined ) { + traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; + } + + // If an array was passed in, assume that it is an array of form elements. + if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { + // Serialize the form elements + jQuery.each( a, function() { + add( this.name, this.value ); + }); + + } else { + // If traditional, encode the "old" way (the way 1.3.2 or older + // did it), otherwise encode params recursively. + for ( prefix in a ) { + buildParams( prefix, a[ prefix ], traditional, add ); + } + } + + // Return the resulting serialization + return s.join( "&" ).replace( r20, "+" ); +}; + +function buildParams( prefix, obj, traditional, add ) { + var name; + + if ( jQuery.isArray( obj ) ) { + // Serialize array item. + jQuery.each( obj, function( i, v ) { + if ( traditional || rbracket.test( prefix ) ) { + // Treat each array item as a scalar. + add( prefix, v ); + + } else { + // If array item is non-scalar (array or object), encode its + // numeric index to resolve deserialization ambiguity issues. + // Note that rack (as of 1.0.0) can't currently deserialize + // nested arrays properly, and attempting to do so may cause + // a server error. Possible fixes are to modify rack's + // deserialization algorithm or to provide an option or flag + // to force array serialization to be shallow. + buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); + } + }); + + } else if ( !traditional && jQuery.type( obj ) === "object" ) { + // Serialize object item. + for ( name in obj ) { + buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); + } + + } else { + // Serialize scalar item. + add( prefix, obj ); + } +} +var + // Document location + ajaxLocParts, + ajaxLocation, + + rhash = /#.*$/, + rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL + // #7653, #8125, #8152: local protocol detection + rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/, + rnoContent = /^(?:GET|HEAD)$/, + rprotocol = /^\/\//, + rquery = /\?/, + rscript = /)<[^<]*)*<\/script>/gi, + rts = /([?&])_=[^&]*/, + rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, + + // Keep a copy of the old load method + _load = jQuery.fn.load, + + /* Prefilters + * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) + * 2) These are called: + * - BEFORE asking for a transport + * - AFTER param serialization (s.data is a string if s.processData is true) + * 3) key is the dataType + * 4) the catchall symbol "*" can be used + * 5) execution will start with transport dataType and THEN continue down to "*" if needed + */ + prefilters = {}, + + /* Transports bindings + * 1) key is the dataType + * 2) the catchall symbol "*" can be used + * 3) selection will start with transport dataType and THEN go to "*" if needed + */ + transports = {}, + + // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression + allTypes = ["*/"] + ["*"]; + +// #8138, IE may throw an exception when accessing +// a field from window.location if document.domain has been set +try { + ajaxLocation = location.href; +} catch( e ) { + // Use the href attribute of an A element + // since IE will modify it given document.location + ajaxLocation = document.createElement( "a" ); + ajaxLocation.href = ""; + ajaxLocation = ajaxLocation.href; +} + +// Segment location into parts +ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; + +// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport +function addToPrefiltersOrTransports( structure ) { + + // dataTypeExpression is optional and defaults to "*" + return function( dataTypeExpression, func ) { + + if ( typeof dataTypeExpression !== "string" ) { + func = dataTypeExpression; + dataTypeExpression = "*"; + } + + var dataType, list, placeBefore, + dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ), + i = 0, + length = dataTypes.length; + + if ( jQuery.isFunction( func ) ) { + // For each dataType in the dataTypeExpression + for ( ; i < length; i++ ) { + dataType = dataTypes[ i ]; + // We control if we're asked to add before + // any existing element + placeBefore = /^\+/.test( dataType ); + if ( placeBefore ) { + dataType = dataType.substr( 1 ) || "*"; + } + list = structure[ dataType ] = structure[ dataType ] || []; + // then we add to the structure accordingly + list[ placeBefore ? "unshift" : "push" ]( func ); + } + } + }; +} + +// Base inspection function for prefilters and transports +function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, + dataType /* internal */, inspected /* internal */ ) { + + dataType = dataType || options.dataTypes[ 0 ]; + inspected = inspected || {}; + + inspected[ dataType ] = true; + + var selection, + list = structure[ dataType ], + i = 0, + length = list ? list.length : 0, + executeOnly = ( structure === prefilters ); + + for ( ; i < length && ( executeOnly || !selection ); i++ ) { + selection = list[ i ]( options, originalOptions, jqXHR ); + // If we got redirected to another dataType + // we try there if executing only and not done already + if ( typeof selection === "string" ) { + if ( !executeOnly || inspected[ selection ] ) { + selection = undefined; + } else { + options.dataTypes.unshift( selection ); + selection = inspectPrefiltersOrTransports( + structure, options, originalOptions, jqXHR, selection, inspected ); + } + } + } + // If we're only executing or nothing was selected + // we try the catchall dataType if not done already + if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { + selection = inspectPrefiltersOrTransports( + structure, options, originalOptions, jqXHR, "*", inspected ); + } + // unnecessary when only executing (prefilters) + // but it'll be ignored by the caller in that case + return selection; +} + +// A special extend for ajax options +// that takes "flat" options (not to be deep extended) +// Fixes #9887 +function ajaxExtend( target, src ) { + var key, deep, + flatOptions = jQuery.ajaxSettings.flatOptions || {}; + for ( key in src ) { + if ( src[ key ] !== undefined ) { + ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; + } + } + if ( deep ) { + jQuery.extend( true, target, deep ); + } +} + +jQuery.fn.load = function( url, params, callback ) { + if ( typeof url !== "string" && _load ) { + return _load.apply( this, arguments ); + } + + // Don't do a request if no elements are being requested + if ( !this.length ) { + return this; + } + + var selector, type, response, + self = this, + off = url.indexOf(" "); + + if ( off >= 0 ) { + selector = url.slice( off, url.length ); + url = url.slice( 0, off ); + } + + // If it's a function + if ( jQuery.isFunction( params ) ) { + + // We assume that it's the callback + callback = params; + params = undefined; + + // Otherwise, build a param string + } else if ( params && typeof params === "object" ) { + type = "POST"; + } + + // Request the remote document + jQuery.ajax({ + url: url, + + // if "type" variable is undefined, then "GET" method will be used + type: type, + dataType: "html", + data: params, + complete: function( jqXHR, status ) { + if ( callback ) { + self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); + } + } + }).done(function( responseText ) { + + // Save response for use in complete callback + response = arguments; + + // See if a selector was specified + self.html( selector ? + + // Create a dummy div to hold the results + jQuery("
                              ") + + // inject the contents of the document in, removing the scripts + // to avoid any 'Permission Denied' errors in IE + .append( responseText.replace( rscript, "" ) ) + + // Locate the specified elements + .find( selector ) : + + // If not, just inject the full result + responseText ); + + }); + + return this; +}; + +// Attach a bunch of functions for handling common AJAX events +jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ + jQuery.fn[ o ] = function( f ){ + return this.on( o, f ); + }; +}); + +jQuery.each( [ "get", "post" ], function( i, method ) { + jQuery[ method ] = function( url, data, callback, type ) { + // shift arguments if data argument was omitted + if ( jQuery.isFunction( data ) ) { + type = type || callback; + callback = data; + data = undefined; + } + + return jQuery.ajax({ + type: method, + url: url, + data: data, + success: callback, + dataType: type + }); + }; +}); + +jQuery.extend({ + + getScript: function( url, callback ) { + return jQuery.get( url, undefined, callback, "script" ); + }, + + getJSON: function( url, data, callback ) { + return jQuery.get( url, data, callback, "json" ); + }, + + // Creates a full fledged settings object into target + // with both ajaxSettings and settings fields. + // If target is omitted, writes into ajaxSettings. + ajaxSetup: function( target, settings ) { + if ( settings ) { + // Building a settings object + ajaxExtend( target, jQuery.ajaxSettings ); + } else { + // Extending ajaxSettings + settings = target; + target = jQuery.ajaxSettings; + } + ajaxExtend( target, settings ); + return target; + }, + + ajaxSettings: { + url: ajaxLocation, + isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), + global: true, + type: "GET", + contentType: "application/x-www-form-urlencoded; charset=UTF-8", + processData: true, + async: true, + /* + timeout: 0, + data: null, + dataType: null, + username: null, + password: null, + cache: null, + throws: false, + traditional: false, + headers: {}, + */ + + accepts: { + xml: "application/xml, text/xml", + html: "text/html", + text: "text/plain", + json: "application/json, text/javascript", + "*": allTypes + }, + + contents: { + xml: /xml/, + html: /html/, + json: /json/ + }, + + responseFields: { + xml: "responseXML", + text: "responseText" + }, + + // List of data converters + // 1) key format is "source_type destination_type" (a single space in-between) + // 2) the catchall symbol "*" can be used for source_type + converters: { + + // Convert anything to text + "* text": window.String, + + // Text to html (true = no transformation) + "text html": true, + + // Evaluate text as a json expression + "text json": jQuery.parseJSON, + + // Parse text as xml + "text xml": jQuery.parseXML + }, + + // For options that shouldn't be deep extended: + // you can add your own custom options here if + // and when you create one that shouldn't be + // deep extended (see ajaxExtend) + flatOptions: { + context: true, + url: true + } + }, + + ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), + ajaxTransport: addToPrefiltersOrTransports( transports ), + + // Main method + ajax: function( url, options ) { + + // If url is an object, simulate pre-1.5 signature + if ( typeof url === "object" ) { + options = url; + url = undefined; + } + + // Force options to be an object + options = options || {}; + + var // ifModified key + ifModifiedKey, + // Response headers + responseHeadersString, + responseHeaders, + // transport + transport, + // timeout handle + timeoutTimer, + // Cross-domain detection vars + parts, + // To know if global events are to be dispatched + fireGlobals, + // Loop variable + i, + // Create the final options object + s = jQuery.ajaxSetup( {}, options ), + // Callbacks context + callbackContext = s.context || s, + // Context for global events + // It's the callbackContext if one was provided in the options + // and if it's a DOM node or a jQuery collection + globalEventContext = callbackContext !== s && + ( callbackContext.nodeType || callbackContext instanceof jQuery ) ? + jQuery( callbackContext ) : jQuery.event, + // Deferreds + deferred = jQuery.Deferred(), + completeDeferred = jQuery.Callbacks( "once memory" ), + // Status-dependent callbacks + statusCode = s.statusCode || {}, + // Headers (they are sent all at once) + requestHeaders = {}, + requestHeadersNames = {}, + // The jqXHR state + state = 0, + // Default abort message + strAbort = "canceled", + // Fake xhr + jqXHR = { + + readyState: 0, + + // Caches the header + setRequestHeader: function( name, value ) { + if ( !state ) { + var lname = name.toLowerCase(); + name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; + requestHeaders[ name ] = value; + } + return this; + }, + + // Raw string + getAllResponseHeaders: function() { + return state === 2 ? responseHeadersString : null; + }, + + // Builds headers hashtable if needed + getResponseHeader: function( key ) { + var match; + if ( state === 2 ) { + if ( !responseHeaders ) { + responseHeaders = {}; + while( ( match = rheaders.exec( responseHeadersString ) ) ) { + responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; + } + } + match = responseHeaders[ key.toLowerCase() ]; + } + return match === undefined ? null : match; + }, + + // Overrides response content-type header + overrideMimeType: function( type ) { + if ( !state ) { + s.mimeType = type; + } + return this; + }, + + // Cancel the request + abort: function( statusText ) { + statusText = statusText || strAbort; + if ( transport ) { + transport.abort( statusText ); + } + done( 0, statusText ); + return this; + } + }; + + // Callback for when everything is done + // It is defined here because jslint complains if it is declared + // at the end of the function (which would be more logical and readable) + function done( status, nativeStatusText, responses, headers ) { + var isSuccess, success, error, response, modified, + statusText = nativeStatusText; + + // Called once + if ( state === 2 ) { + return; + } + + // State is "done" now + state = 2; + + // Clear timeout if it exists + if ( timeoutTimer ) { + clearTimeout( timeoutTimer ); + } + + // Dereference transport for early garbage collection + // (no matter how long the jqXHR object will be used) + transport = undefined; + + // Cache response headers + responseHeadersString = headers || ""; + + // Set readyState + jqXHR.readyState = status > 0 ? 4 : 0; + + // Get response data + if ( responses ) { + response = ajaxHandleResponses( s, jqXHR, responses ); + } + + // If successful, handle type chaining + if ( status >= 200 && status < 300 || status === 304 ) { + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + + modified = jqXHR.getResponseHeader("Last-Modified"); + if ( modified ) { + jQuery.lastModified[ ifModifiedKey ] = modified; + } + modified = jqXHR.getResponseHeader("Etag"); + if ( modified ) { + jQuery.etag[ ifModifiedKey ] = modified; + } + } + + // If not modified + if ( status === 304 ) { + + statusText = "notmodified"; + isSuccess = true; + + // If we have data + } else { + + isSuccess = ajaxConvert( s, response ); + statusText = isSuccess.state; + success = isSuccess.data; + error = isSuccess.error; + isSuccess = !error; + } + } else { + // We extract error from statusText + // then normalize statusText and status for non-aborts + error = statusText; + if ( !statusText || status ) { + statusText = "error"; + if ( status < 0 ) { + status = 0; + } + } + } + + // Set data for the fake xhr object + jqXHR.status = status; + jqXHR.statusText = ( nativeStatusText || statusText ) + ""; + + // Success/Error + if ( isSuccess ) { + deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); + } else { + deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); + } + + // Status-dependent callbacks + jqXHR.statusCode( statusCode ); + statusCode = undefined; + + if ( fireGlobals ) { + globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ), + [ jqXHR, s, isSuccess ? success : error ] ); + } + + // Complete + completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); + + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); + // Handle the global AJAX counter + if ( !( --jQuery.active ) ) { + jQuery.event.trigger( "ajaxStop" ); + } + } + } + + // Attach deferreds + deferred.promise( jqXHR ); + jqXHR.success = jqXHR.done; + jqXHR.error = jqXHR.fail; + jqXHR.complete = completeDeferred.add; + + // Status-dependent callbacks + jqXHR.statusCode = function( map ) { + if ( map ) { + var tmp; + if ( state < 2 ) { + for ( tmp in map ) { + statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; + } + } else { + tmp = map[ jqXHR.status ]; + jqXHR.always( tmp ); + } + } + return this; + }; + + // Remove hash character (#7531: and string promotion) + // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) + // We also use the url parameter if available + s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); + + // Extract dataTypes list + s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace ); + + // A cross-domain request is in order when we have a protocol:host:port mismatch + if ( s.crossDomain == null ) { + parts = rurl.exec( s.url.toLowerCase() ); + s.crossDomain = !!( parts && + ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || + ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != + ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) + ); + } + + // Convert data if not already a string + if ( s.data && s.processData && typeof s.data !== "string" ) { + s.data = jQuery.param( s.data, s.traditional ); + } + + // Apply prefilters + inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); + + // If request was aborted inside a prefilter, stop there + if ( state === 2 ) { + return jqXHR; + } + + // We can fire global events as of now if asked to + fireGlobals = s.global; + + // Uppercase the type + s.type = s.type.toUpperCase(); + + // Determine if request has content + s.hasContent = !rnoContent.test( s.type ); + + // Watch for a new set of requests + if ( fireGlobals && jQuery.active++ === 0 ) { + jQuery.event.trigger( "ajaxStart" ); + } + + // More options handling for requests with no content + if ( !s.hasContent ) { + + // If data is available, append data to url + if ( s.data ) { + s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; + // #9682: remove data so that it's not used in an eventual retry + delete s.data; + } + + // Get ifModifiedKey before adding the anti-cache parameter + ifModifiedKey = s.url; + + // Add anti-cache in url if needed + if ( s.cache === false ) { + + var ts = jQuery.now(), + // try replacing _= if it is there + ret = s.url.replace( rts, "$1_=" + ts ); + + // if nothing was replaced, add timestamp to the end + s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); + } + } + + // Set the correct header, if data is being sent + if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { + jqXHR.setRequestHeader( "Content-Type", s.contentType ); + } + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + ifModifiedKey = ifModifiedKey || s.url; + if ( jQuery.lastModified[ ifModifiedKey ] ) { + jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); + } + if ( jQuery.etag[ ifModifiedKey ] ) { + jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); + } + } + + // Set the Accepts header for the server, depending on the dataType + jqXHR.setRequestHeader( + "Accept", + s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? + s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : + s.accepts[ "*" ] + ); + + // Check for headers option + for ( i in s.headers ) { + jqXHR.setRequestHeader( i, s.headers[ i ] ); + } + + // Allow custom headers/mimetypes and early abort + if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { + // Abort if not done already and return + return jqXHR.abort(); + + } + + // aborting is no longer a cancellation + strAbort = "abort"; + + // Install callbacks on deferreds + for ( i in { success: 1, error: 1, complete: 1 } ) { + jqXHR[ i ]( s[ i ] ); + } + + // Get transport + transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); + + // If no transport, we auto-abort + if ( !transport ) { + done( -1, "No Transport" ); + } else { + jqXHR.readyState = 1; + // Send global event + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); + } + // Timeout + if ( s.async && s.timeout > 0 ) { + timeoutTimer = setTimeout( function(){ + jqXHR.abort( "timeout" ); + }, s.timeout ); + } + + try { + state = 1; + transport.send( requestHeaders, done ); + } catch (e) { + // Propagate exception as error if not done + if ( state < 2 ) { + done( -1, e ); + // Simply rethrow otherwise + } else { + throw e; + } + } + } + + return jqXHR; + }, + + // Counter for holding the number of active queries + active: 0, + + // Last-Modified header cache for next request + lastModified: {}, + etag: {} + +}); + +/* Handles responses to an ajax request: + * - sets all responseXXX fields accordingly + * - finds the right dataType (mediates between content-type and expected dataType) + * - returns the corresponding response + */ +function ajaxHandleResponses( s, jqXHR, responses ) { + + var ct, type, finalDataType, firstDataType, + contents = s.contents, + dataTypes = s.dataTypes, + responseFields = s.responseFields; + + // Fill responseXXX fields + for ( type in responseFields ) { + if ( type in responses ) { + jqXHR[ responseFields[type] ] = responses[ type ]; + } + } + + // Remove auto dataType and get content-type in the process + while( dataTypes[ 0 ] === "*" ) { + dataTypes.shift(); + if ( ct === undefined ) { + ct = s.mimeType || jqXHR.getResponseHeader( "content-type" ); + } + } + + // Check if we're dealing with a known content-type + if ( ct ) { + for ( type in contents ) { + if ( contents[ type ] && contents[ type ].test( ct ) ) { + dataTypes.unshift( type ); + break; + } + } + } + + // Check to see if we have a response for the expected dataType + if ( dataTypes[ 0 ] in responses ) { + finalDataType = dataTypes[ 0 ]; + } else { + // Try convertible dataTypes + for ( type in responses ) { + if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { + finalDataType = type; + break; + } + if ( !firstDataType ) { + firstDataType = type; + } + } + // Or just use first one + finalDataType = finalDataType || firstDataType; + } + + // If we found a dataType + // We add the dataType to the list if needed + // and return the corresponding response + if ( finalDataType ) { + if ( finalDataType !== dataTypes[ 0 ] ) { + dataTypes.unshift( finalDataType ); + } + return responses[ finalDataType ]; + } +} + +// Chain conversions given the request and the original response +function ajaxConvert( s, response ) { + + var conv, conv2, current, tmp, + // Work with a copy of dataTypes in case we need to modify it for conversion + dataTypes = s.dataTypes.slice(), + prev = dataTypes[ 0 ], + converters = {}, + i = 0; + + // Apply the dataFilter if provided + if ( s.dataFilter ) { + response = s.dataFilter( response, s.dataType ); + } + + // Create converters map with lowercased keys + if ( dataTypes[ 1 ] ) { + for ( conv in s.converters ) { + converters[ conv.toLowerCase() ] = s.converters[ conv ]; + } + } + + // Convert to each sequential dataType, tolerating list modification + for ( ; (current = dataTypes[++i]); ) { + + // There's only work to do if current dataType is non-auto + if ( current !== "*" ) { + + // Convert response if prev dataType is non-auto and differs from current + if ( prev !== "*" && prev !== current ) { + + // Seek a direct converter + conv = converters[ prev + " " + current ] || converters[ "* " + current ]; + + // If none found, seek a pair + if ( !conv ) { + for ( conv2 in converters ) { + + // If conv2 outputs current + tmp = conv2.split(" "); + if ( tmp[ 1 ] === current ) { + + // If prev can be converted to accepted input + conv = converters[ prev + " " + tmp[ 0 ] ] || + converters[ "* " + tmp[ 0 ] ]; + if ( conv ) { + // Condense equivalence converters + if ( conv === true ) { + conv = converters[ conv2 ]; + + // Otherwise, insert the intermediate dataType + } else if ( converters[ conv2 ] !== true ) { + current = tmp[ 0 ]; + dataTypes.splice( i--, 0, current ); + } + + break; + } + } + } + } + + // Apply converter (if not an equivalence) + if ( conv !== true ) { + + // Unless errors are allowed to bubble, catch and return them + if ( conv && s["throws"] ) { + response = conv( response ); + } else { + try { + response = conv( response ); + } catch ( e ) { + return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; + } + } + } + } + + // Update prev for next iteration + prev = current; + } + } + + return { state: "success", data: response }; +} +var oldCallbacks = [], + rquestion = /\?/, + rjsonp = /(=)\?(?=&|$)|\?\?/, + nonce = jQuery.now(); + +// Default jsonp settings +jQuery.ajaxSetup({ + jsonp: "callback", + jsonpCallback: function() { + var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); + this[ callback ] = true; + return callback; + } +}); + +// Detect, normalize options and install callbacks for jsonp requests +jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { + + var callbackName, overwritten, responseContainer, + data = s.data, + url = s.url, + hasCallback = s.jsonp !== false, + replaceInUrl = hasCallback && rjsonp.test( url ), + replaceInData = hasCallback && !replaceInUrl && typeof data === "string" && + !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && + rjsonp.test( data ); + + // Handle iff the expected data type is "jsonp" or we have a parameter to set + if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) { + + // Get callback name, remembering preexisting value associated with it + callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? + s.jsonpCallback() : + s.jsonpCallback; + overwritten = window[ callbackName ]; + + // Insert callback into url or form data + if ( replaceInUrl ) { + s.url = url.replace( rjsonp, "$1" + callbackName ); + } else if ( replaceInData ) { + s.data = data.replace( rjsonp, "$1" + callbackName ); + } else if ( hasCallback ) { + s.url += ( rquestion.test( url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; + } + + // Use data converter to retrieve json after script execution + s.converters["script json"] = function() { + if ( !responseContainer ) { + jQuery.error( callbackName + " was not called" ); + } + return responseContainer[ 0 ]; + }; + + // force json dataType + s.dataTypes[ 0 ] = "json"; + + // Install callback + window[ callbackName ] = function() { + responseContainer = arguments; + }; + + // Clean-up function (fires after converters) + jqXHR.always(function() { + // Restore preexisting value + window[ callbackName ] = overwritten; + + // Save back as free + if ( s[ callbackName ] ) { + // make sure that re-using the options doesn't screw things around + s.jsonpCallback = originalSettings.jsonpCallback; + + // save the callback name for future use + oldCallbacks.push( callbackName ); + } + + // Call if it was a function and we have a response + if ( responseContainer && jQuery.isFunction( overwritten ) ) { + overwritten( responseContainer[ 0 ] ); + } + + responseContainer = overwritten = undefined; + }); + + // Delegate to script + return "script"; + } +}); +// Install script dataType +jQuery.ajaxSetup({ + accepts: { + script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" + }, + contents: { + script: /javascript|ecmascript/ + }, + converters: { + "text script": function( text ) { + jQuery.globalEval( text ); + return text; + } + } +}); + +// Handle cache's special case and global +jQuery.ajaxPrefilter( "script", function( s ) { + if ( s.cache === undefined ) { + s.cache = false; + } + if ( s.crossDomain ) { + s.type = "GET"; + s.global = false; + } +}); + +// Bind script tag hack transport +jQuery.ajaxTransport( "script", function(s) { + + // This transport only deals with cross domain requests + if ( s.crossDomain ) { + + var script, + head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement; + + return { + + send: function( _, callback ) { + + script = document.createElement( "script" ); + + script.async = "async"; + + if ( s.scriptCharset ) { + script.charset = s.scriptCharset; + } + + script.src = s.url; + + // Attach handlers for all browsers + script.onload = script.onreadystatechange = function( _, isAbort ) { + + if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { + + // Handle memory leak in IE + script.onload = script.onreadystatechange = null; + + // Remove the script + if ( head && script.parentNode ) { + head.removeChild( script ); + } + + // Dereference the script + script = undefined; + + // Callback if not abort + if ( !isAbort ) { + callback( 200, "success" ); + } + } + }; + // Use insertBefore instead of appendChild to circumvent an IE6 bug. + // This arises when a base node is used (#2709 and #4378). + head.insertBefore( script, head.firstChild ); + }, + + abort: function() { + if ( script ) { + script.onload( 0, 1 ); + } + } + }; + } +}); +var xhrCallbacks, + // #5280: Internet Explorer will keep connections alive if we don't abort on unload + xhrOnUnloadAbort = window.ActiveXObject ? function() { + // Abort all pending requests + for ( var key in xhrCallbacks ) { + xhrCallbacks[ key ]( 0, 1 ); + } + } : false, + xhrId = 0; + +// Functions to create xhrs +function createStandardXHR() { + try { + return new window.XMLHttpRequest(); + } catch( e ) {} +} + +function createActiveXHR() { + try { + return new window.ActiveXObject( "Microsoft.XMLHTTP" ); + } catch( e ) {} +} + +// Create the request object +// (This is still attached to ajaxSettings for backward compatibility) +jQuery.ajaxSettings.xhr = window.ActiveXObject ? + /* Microsoft failed to properly + * implement the XMLHttpRequest in IE7 (can't request local files), + * so we use the ActiveXObject when it is available + * Additionally XMLHttpRequest can be disabled in IE7/IE8 so + * we need a fallback. + */ + function() { + return !this.isLocal && createStandardXHR() || createActiveXHR(); + } : + // For all other browsers, use the standard XMLHttpRequest object + createStandardXHR; + +// Determine support properties +(function( xhr ) { + jQuery.extend( jQuery.support, { + ajax: !!xhr, + cors: !!xhr && ( "withCredentials" in xhr ) + }); +})( jQuery.ajaxSettings.xhr() ); + +// Create transport if the browser can provide an xhr +if ( jQuery.support.ajax ) { + + jQuery.ajaxTransport(function( s ) { + // Cross domain only allowed if supported through XMLHttpRequest + if ( !s.crossDomain || jQuery.support.cors ) { + + var callback; + + return { + send: function( headers, complete ) { + + // Get a new xhr + var handle, i, + xhr = s.xhr(); + + // Open the socket + // Passing null username, generates a login popup on Opera (#2865) + if ( s.username ) { + xhr.open( s.type, s.url, s.async, s.username, s.password ); + } else { + xhr.open( s.type, s.url, s.async ); + } + + // Apply custom fields if provided + if ( s.xhrFields ) { + for ( i in s.xhrFields ) { + xhr[ i ] = s.xhrFields[ i ]; + } + } + + // Override mime type if needed + if ( s.mimeType && xhr.overrideMimeType ) { + xhr.overrideMimeType( s.mimeType ); + } + + // X-Requested-With header + // For cross-domain requests, seeing as conditions for a preflight are + // akin to a jigsaw puzzle, we simply never set it to be sure. + // (it can always be set on a per-request basis or even using ajaxSetup) + // For same-domain requests, won't change header if already provided. + if ( !s.crossDomain && !headers["X-Requested-With"] ) { + headers[ "X-Requested-With" ] = "XMLHttpRequest"; + } + + // Need an extra try/catch for cross domain requests in Firefox 3 + try { + for ( i in headers ) { + xhr.setRequestHeader( i, headers[ i ] ); + } + } catch( _ ) {} + + // Do send the request + // This may raise an exception which is actually + // handled in jQuery.ajax (so no try/catch here) + xhr.send( ( s.hasContent && s.data ) || null ); + + // Listener + callback = function( _, isAbort ) { + + var status, + statusText, + responseHeaders, + responses, + xml; + + // Firefox throws exceptions when accessing properties + // of an xhr when a network error occurred + // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) + try { + + // Was never called and is aborted or complete + if ( callback && ( isAbort || xhr.readyState === 4 ) ) { + + // Only called once + callback = undefined; + + // Do not keep as active anymore + if ( handle ) { + xhr.onreadystatechange = jQuery.noop; + if ( xhrOnUnloadAbort ) { + delete xhrCallbacks[ handle ]; + } + } + + // If it's an abort + if ( isAbort ) { + // Abort it manually if needed + if ( xhr.readyState !== 4 ) { + xhr.abort(); + } + } else { + status = xhr.status; + responseHeaders = xhr.getAllResponseHeaders(); + responses = {}; + xml = xhr.responseXML; + + // Construct response list + if ( xml && xml.documentElement /* #4958 */ ) { + responses.xml = xml; + } + + // When requesting binary data, IE6-9 will throw an exception + // on any attempt to access responseText (#11426) + try { + responses.text = xhr.responseText; + } catch( e ) { + } + + // Firefox throws an exception when accessing + // statusText for faulty cross-domain requests + try { + statusText = xhr.statusText; + } catch( e ) { + // We normalize with Webkit giving an empty statusText + statusText = ""; + } + + // Filter status for non standard behaviors + + // If the request is local and we have data: assume a success + // (success with no data won't get notified, that's the best we + // can do given current implementations) + if ( !status && s.isLocal && !s.crossDomain ) { + status = responses.text ? 200 : 404; + // IE - #1450: sometimes returns 1223 when it should be 204 + } else if ( status === 1223 ) { + status = 204; + } + } + } + } catch( firefoxAccessException ) { + if ( !isAbort ) { + complete( -1, firefoxAccessException ); + } + } + + // Call complete if needed + if ( responses ) { + complete( status, statusText, responses, responseHeaders ); + } + }; + + if ( !s.async ) { + // if we're in sync mode we fire the callback + callback(); + } else if ( xhr.readyState === 4 ) { + // (IE6 & IE7) if it's in cache and has been + // retrieved directly we need to fire the callback + setTimeout( callback, 0 ); + } else { + handle = ++xhrId; + if ( xhrOnUnloadAbort ) { + // Create the active xhrs callbacks list if needed + // and attach the unload handler + if ( !xhrCallbacks ) { + xhrCallbacks = {}; + jQuery( window ).unload( xhrOnUnloadAbort ); + } + // Add to list of active xhrs callbacks + xhrCallbacks[ handle ] = callback; + } + xhr.onreadystatechange = callback; + } + }, + + abort: function() { + if ( callback ) { + callback(0,1); + } + } + }; + } + }); +} +var fxNow, timerId, + rfxtypes = /^(?:toggle|show|hide)$/, + rfxnum = new RegExp( "^(?:([-+])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), + rrun = /queueHooks$/, + animationPrefilters = [ defaultPrefilter ], + tweeners = { + "*": [function( prop, value ) { + var end, unit, + tween = this.createTween( prop, value ), + parts = rfxnum.exec( value ), + target = tween.cur(), + start = +target || 0, + scale = 1, + maxIterations = 20; + + if ( parts ) { + end = +parts[2]; + unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" ); + + // We need to compute starting value + if ( unit !== "px" && start ) { + // Iteratively approximate from a nonzero starting point + // Prefer the current property, because this process will be trivial if it uses the same units + // Fallback to end or a simple constant + start = jQuery.css( tween.elem, prop, true ) || end || 1; + + do { + // If previous iteration zeroed out, double until we get *something* + // Use a string for doubling factor so we don't accidentally see scale as unchanged below + scale = scale || ".5"; + + // Adjust and apply + start = start / scale; + jQuery.style( tween.elem, prop, start + unit ); + + // Update scale, tolerating zero or NaN from tween.cur() + // And breaking the loop if scale is unchanged or perfect, or if we've just had enough + } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); + } + + tween.unit = unit; + tween.start = start; + // If a +=/-= token was provided, we're doing a relative animation + tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end; + } + return tween; + }] + }; + +// Animations created synchronously will run synchronously +function createFxNow() { + setTimeout(function() { + fxNow = undefined; + }, 0 ); + return ( fxNow = jQuery.now() ); +} + +function createTweens( animation, props ) { + jQuery.each( props, function( prop, value ) { + var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), + index = 0, + length = collection.length; + for ( ; index < length; index++ ) { + if ( collection[ index ].call( animation, prop, value ) ) { + + // we're done with this property + return; + } + } + }); +} + +function Animation( elem, properties, options ) { + var result, + index = 0, + tweenerIndex = 0, + length = animationPrefilters.length, + deferred = jQuery.Deferred().always( function() { + // don't match elem in the :animated selector + delete tick.elem; + }), + tick = function() { + var currentTime = fxNow || createFxNow(), + remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), + // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) + temp = remaining / animation.duration || 0, + percent = 1 - temp, + index = 0, + length = animation.tweens.length; + + for ( ; index < length ; index++ ) { + animation.tweens[ index ].run( percent ); + } + + deferred.notifyWith( elem, [ animation, percent, remaining ]); + + if ( percent < 1 && length ) { + return remaining; + } else { + deferred.resolveWith( elem, [ animation ] ); + return false; + } + }, + animation = deferred.promise({ + elem: elem, + props: jQuery.extend( {}, properties ), + opts: jQuery.extend( true, { specialEasing: {} }, options ), + originalProperties: properties, + originalOptions: options, + startTime: fxNow || createFxNow(), + duration: options.duration, + tweens: [], + createTween: function( prop, end, easing ) { + var tween = jQuery.Tween( elem, animation.opts, prop, end, + animation.opts.specialEasing[ prop ] || animation.opts.easing ); + animation.tweens.push( tween ); + return tween; + }, + stop: function( gotoEnd ) { + var index = 0, + // if we are going to the end, we want to run all the tweens + // otherwise we skip this part + length = gotoEnd ? animation.tweens.length : 0; + + for ( ; index < length ; index++ ) { + animation.tweens[ index ].run( 1 ); + } + + // resolve when we played the last frame + // otherwise, reject + if ( gotoEnd ) { + deferred.resolveWith( elem, [ animation, gotoEnd ] ); + } else { + deferred.rejectWith( elem, [ animation, gotoEnd ] ); + } + return this; + } + }), + props = animation.props; + + propFilter( props, animation.opts.specialEasing ); + + for ( ; index < length ; index++ ) { + result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); + if ( result ) { + return result; + } + } + + createTweens( animation, props ); + + if ( jQuery.isFunction( animation.opts.start ) ) { + animation.opts.start.call( elem, animation ); + } + + jQuery.fx.timer( + jQuery.extend( tick, { + anim: animation, + queue: animation.opts.queue, + elem: elem + }) + ); + + // attach callbacks from options + return animation.progress( animation.opts.progress ) + .done( animation.opts.done, animation.opts.complete ) + .fail( animation.opts.fail ) + .always( animation.opts.always ); +} + +function propFilter( props, specialEasing ) { + var index, name, easing, value, hooks; + + // camelCase, specialEasing and expand cssHook pass + for ( index in props ) { + name = jQuery.camelCase( index ); + easing = specialEasing[ name ]; + value = props[ index ]; + if ( jQuery.isArray( value ) ) { + easing = value[ 1 ]; + value = props[ index ] = value[ 0 ]; + } + + if ( index !== name ) { + props[ name ] = value; + delete props[ index ]; + } + + hooks = jQuery.cssHooks[ name ]; + if ( hooks && "expand" in hooks ) { + value = hooks.expand( value ); + delete props[ name ]; + + // not quite $.extend, this wont overwrite keys already present. + // also - reusing 'index' from above because we have the correct "name" + for ( index in value ) { + if ( !( index in props ) ) { + props[ index ] = value[ index ]; + specialEasing[ index ] = easing; + } + } + } else { + specialEasing[ name ] = easing; + } + } +} + +jQuery.Animation = jQuery.extend( Animation, { + + tweener: function( props, callback ) { + if ( jQuery.isFunction( props ) ) { + callback = props; + props = [ "*" ]; + } else { + props = props.split(" "); + } + + var prop, + index = 0, + length = props.length; + + for ( ; index < length ; index++ ) { + prop = props[ index ]; + tweeners[ prop ] = tweeners[ prop ] || []; + tweeners[ prop ].unshift( callback ); + } + }, + + prefilter: function( callback, prepend ) { + if ( prepend ) { + animationPrefilters.unshift( callback ); + } else { + animationPrefilters.push( callback ); + } + } +}); + +function defaultPrefilter( elem, props, opts ) { + var index, prop, value, length, dataShow, toggle, tween, hooks, oldfire, + anim = this, + style = elem.style, + orig = {}, + handled = [], + hidden = elem.nodeType && isHidden( elem ); + + // handle queue: false promises + if ( !opts.queue ) { + hooks = jQuery._queueHooks( elem, "fx" ); + if ( hooks.unqueued == null ) { + hooks.unqueued = 0; + oldfire = hooks.empty.fire; + hooks.empty.fire = function() { + if ( !hooks.unqueued ) { + oldfire(); + } + }; + } + hooks.unqueued++; + + anim.always(function() { + // doing this makes sure that the complete handler will be called + // before this completes + anim.always(function() { + hooks.unqueued--; + if ( !jQuery.queue( elem, "fx" ).length ) { + hooks.empty.fire(); + } + }); + }); + } + + // height/width overflow pass + if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { + // Make sure that nothing sneaks out + // Record all 3 overflow attributes because IE does not + // change the overflow attribute when overflowX and + // overflowY are set to the same value + opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; + + // Set display property to inline-block for height/width + // animations on inline elements that are having width/height animated + if ( jQuery.css( elem, "display" ) === "inline" && + jQuery.css( elem, "float" ) === "none" ) { + + // inline-level elements accept inline-block; + // block-level elements need to be inline with layout + if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { + style.display = "inline-block"; + + } else { + style.zoom = 1; + } + } + } + + if ( opts.overflow ) { + style.overflow = "hidden"; + if ( !jQuery.support.shrinkWrapBlocks ) { + anim.done(function() { + style.overflow = opts.overflow[ 0 ]; + style.overflowX = opts.overflow[ 1 ]; + style.overflowY = opts.overflow[ 2 ]; + }); + } + } + + + // show/hide pass + for ( index in props ) { + value = props[ index ]; + if ( rfxtypes.exec( value ) ) { + delete props[ index ]; + toggle = toggle || value === "toggle"; + if ( value === ( hidden ? "hide" : "show" ) ) { + continue; + } + handled.push( index ); + } + } + + length = handled.length; + if ( length ) { + dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} ); + if ( "hidden" in dataShow ) { + hidden = dataShow.hidden; + } + + // store state if its toggle - enables .stop().toggle() to "reverse" + if ( toggle ) { + dataShow.hidden = !hidden; + } + if ( hidden ) { + jQuery( elem ).show(); + } else { + anim.done(function() { + jQuery( elem ).hide(); + }); + } + anim.done(function() { + var prop; + jQuery.removeData( elem, "fxshow", true ); + for ( prop in orig ) { + jQuery.style( elem, prop, orig[ prop ] ); + } + }); + for ( index = 0 ; index < length ; index++ ) { + prop = handled[ index ]; + tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 ); + orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop ); + + if ( !( prop in dataShow ) ) { + dataShow[ prop ] = tween.start; + if ( hidden ) { + tween.end = tween.start; + tween.start = prop === "width" || prop === "height" ? 1 : 0; + } + } + } + } +} + +function Tween( elem, options, prop, end, easing ) { + return new Tween.prototype.init( elem, options, prop, end, easing ); +} +jQuery.Tween = Tween; + +Tween.prototype = { + constructor: Tween, + init: function( elem, options, prop, end, easing, unit ) { + this.elem = elem; + this.prop = prop; + this.easing = easing || "swing"; + this.options = options; + this.start = this.now = this.cur(); + this.end = end; + this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); + }, + cur: function() { + var hooks = Tween.propHooks[ this.prop ]; + + return hooks && hooks.get ? + hooks.get( this ) : + Tween.propHooks._default.get( this ); + }, + run: function( percent ) { + var eased, + hooks = Tween.propHooks[ this.prop ]; + + if ( this.options.duration ) { + this.pos = eased = jQuery.easing[ this.easing ]( + percent, this.options.duration * percent, 0, 1, this.options.duration + ); + } else { + this.pos = eased = percent; + } + this.now = ( this.end - this.start ) * eased + this.start; + + if ( this.options.step ) { + this.options.step.call( this.elem, this.now, this ); + } + + if ( hooks && hooks.set ) { + hooks.set( this ); + } else { + Tween.propHooks._default.set( this ); + } + return this; + } +}; + +Tween.prototype.init.prototype = Tween.prototype; + +Tween.propHooks = { + _default: { + get: function( tween ) { + var result; + + if ( tween.elem[ tween.prop ] != null && + (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { + return tween.elem[ tween.prop ]; + } + + // passing any value as a 4th parameter to .css will automatically + // attempt a parseFloat and fallback to a string if the parse fails + // so, simple values such as "10px" are parsed to Float. + // complex values such as "rotate(1rad)" are returned as is. + result = jQuery.css( tween.elem, tween.prop, false, "" ); + // Empty strings, null, undefined and "auto" are converted to 0. + return !result || result === "auto" ? 0 : result; + }, + set: function( tween ) { + // use step hook for back compat - use cssHook if its there - use .style if its + // available and use plain properties where available + if ( jQuery.fx.step[ tween.prop ] ) { + jQuery.fx.step[ tween.prop ]( tween ); + } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { + jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); + } else { + tween.elem[ tween.prop ] = tween.now; + } + } + } +}; + +// Remove in 2.0 - this supports IE8's panic based approach +// to setting things on disconnected nodes + +Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { + set: function( tween ) { + if ( tween.elem.nodeType && tween.elem.parentNode ) { + tween.elem[ tween.prop ] = tween.now; + } + } +}; + +jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { + var cssFn = jQuery.fn[ name ]; + jQuery.fn[ name ] = function( speed, easing, callback ) { + return speed == null || typeof speed === "boolean" || + // special check for .toggle( handler, handler, ... ) + ( !i && jQuery.isFunction( speed ) && jQuery.isFunction( easing ) ) ? + cssFn.apply( this, arguments ) : + this.animate( genFx( name, true ), speed, easing, callback ); + }; +}); + +jQuery.fn.extend({ + fadeTo: function( speed, to, easing, callback ) { + + // show any hidden elements after setting opacity to 0 + return this.filter( isHidden ).css( "opacity", 0 ).show() + + // animate to the value specified + .end().animate({ opacity: to }, speed, easing, callback ); + }, + animate: function( prop, speed, easing, callback ) { + var empty = jQuery.isEmptyObject( prop ), + optall = jQuery.speed( speed, easing, callback ), + doAnimation = function() { + // Operate on a copy of prop so per-property easing won't be lost + var anim = Animation( this, jQuery.extend( {}, prop ), optall ); + + // Empty animations resolve immediately + if ( empty ) { + anim.stop( true ); + } + }; + + return empty || optall.queue === false ? + this.each( doAnimation ) : + this.queue( optall.queue, doAnimation ); + }, + stop: function( type, clearQueue, gotoEnd ) { + var stopQueue = function( hooks ) { + var stop = hooks.stop; + delete hooks.stop; + stop( gotoEnd ); + }; + + if ( typeof type !== "string" ) { + gotoEnd = clearQueue; + clearQueue = type; + type = undefined; + } + if ( clearQueue && type !== false ) { + this.queue( type || "fx", [] ); + } + + return this.each(function() { + var dequeue = true, + index = type != null && type + "queueHooks", + timers = jQuery.timers, + data = jQuery._data( this ); + + if ( index ) { + if ( data[ index ] && data[ index ].stop ) { + stopQueue( data[ index ] ); + } + } else { + for ( index in data ) { + if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { + stopQueue( data[ index ] ); + } + } + } + + for ( index = timers.length; index--; ) { + if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { + timers[ index ].anim.stop( gotoEnd ); + dequeue = false; + timers.splice( index, 1 ); + } + } + + // start the next in the queue if the last step wasn't forced + // timers currently will call their complete callbacks, which will dequeue + // but only if they were gotoEnd + if ( dequeue || !gotoEnd ) { + jQuery.dequeue( this, type ); + } + }); + } +}); + +// Generate parameters to create a standard animation +function genFx( type, includeWidth ) { + var which, + attrs = { height: type }, + i = 0; + + // if we include width, step value is 1 to do all cssExpand values, + // if we don't include width, step value is 2 to skip over Left and Right + includeWidth = includeWidth? 1 : 0; + for( ; i < 4 ; i += 2 - includeWidth ) { + which = cssExpand[ i ]; + attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; + } + + if ( includeWidth ) { + attrs.opacity = attrs.width = type; + } + + return attrs; +} + +// Generate shortcuts for custom animations +jQuery.each({ + slideDown: genFx("show"), + slideUp: genFx("hide"), + slideToggle: genFx("toggle"), + fadeIn: { opacity: "show" }, + fadeOut: { opacity: "hide" }, + fadeToggle: { opacity: "toggle" } +}, function( name, props ) { + jQuery.fn[ name ] = function( speed, easing, callback ) { + return this.animate( props, speed, easing, callback ); + }; +}); + +jQuery.speed = function( speed, easing, fn ) { + var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { + complete: fn || !fn && easing || + jQuery.isFunction( speed ) && speed, + duration: speed, + easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing + }; + + opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : + opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; + + // normalize opt.queue - true/undefined/null -> "fx" + if ( opt.queue == null || opt.queue === true ) { + opt.queue = "fx"; + } + + // Queueing + opt.old = opt.complete; + + opt.complete = function() { + if ( jQuery.isFunction( opt.old ) ) { + opt.old.call( this ); + } + + if ( opt.queue ) { + jQuery.dequeue( this, opt.queue ); + } + }; + + return opt; +}; + +jQuery.easing = { + linear: function( p ) { + return p; + }, + swing: function( p ) { + return 0.5 - Math.cos( p*Math.PI ) / 2; + } +}; + +jQuery.timers = []; +jQuery.fx = Tween.prototype.init; +jQuery.fx.tick = function() { + var timer, + timers = jQuery.timers, + i = 0; + + fxNow = jQuery.now(); + + for ( ; i < timers.length; i++ ) { + timer = timers[ i ]; + // Checks the timer has not already been removed + if ( !timer() && timers[ i ] === timer ) { + timers.splice( i--, 1 ); + } + } + + if ( !timers.length ) { + jQuery.fx.stop(); + } + fxNow = undefined; +}; + +jQuery.fx.timer = function( timer ) { + if ( timer() && jQuery.timers.push( timer ) && !timerId ) { + timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); + } +}; + +jQuery.fx.interval = 13; + +jQuery.fx.stop = function() { + clearInterval( timerId ); + timerId = null; +}; + +jQuery.fx.speeds = { + slow: 600, + fast: 200, + // Default speed + _default: 400 +}; + +// Back Compat <1.8 extension point +jQuery.fx.step = {}; + +if ( jQuery.expr && jQuery.expr.filters ) { + jQuery.expr.filters.animated = function( elem ) { + return jQuery.grep(jQuery.timers, function( fn ) { + return elem === fn.elem; + }).length; + }; +} +var rroot = /^(?:body|html)$/i; + +jQuery.fn.offset = function( options ) { + if ( arguments.length ) { + return options === undefined ? + this : + this.each(function( i ) { + jQuery.offset.setOffset( this, options, i ); + }); + } + + var docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft, + box = { top: 0, left: 0 }, + elem = this[ 0 ], + doc = elem && elem.ownerDocument; + + if ( !doc ) { + return; + } + + if ( (body = doc.body) === elem ) { + return jQuery.offset.bodyOffset( elem ); + } + + docElem = doc.documentElement; + + // Make sure it's not a disconnected DOM node + if ( !jQuery.contains( docElem, elem ) ) { + return box; + } + + // If we don't have gBCR, just use 0,0 rather than error + // BlackBerry 5, iOS 3 (original iPhone) + if ( typeof elem.getBoundingClientRect !== "undefined" ) { + box = elem.getBoundingClientRect(); + } + win = getWindow( doc ); + clientTop = docElem.clientTop || body.clientTop || 0; + clientLeft = docElem.clientLeft || body.clientLeft || 0; + scrollTop = win.pageYOffset || docElem.scrollTop; + scrollLeft = win.pageXOffset || docElem.scrollLeft; + return { + top: box.top + scrollTop - clientTop, + left: box.left + scrollLeft - clientLeft + }; +}; + +jQuery.offset = { + + bodyOffset: function( body ) { + var top = body.offsetTop, + left = body.offsetLeft; + + if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) { + top += parseFloat( jQuery.css(body, "marginTop") ) || 0; + left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; + } + + return { top: top, left: left }; + }, + + setOffset: function( elem, options, i ) { + var position = jQuery.css( elem, "position" ); + + // set position first, in-case top/left are set even on static elem + if ( position === "static" ) { + elem.style.position = "relative"; + } + + var curElem = jQuery( elem ), + curOffset = curElem.offset(), + curCSSTop = jQuery.css( elem, "top" ), + curCSSLeft = jQuery.css( elem, "left" ), + calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, + props = {}, curPosition = {}, curTop, curLeft; + + // need to be able to calculate position if either top or left is auto and position is either absolute or fixed + if ( calculatePosition ) { + curPosition = curElem.position(); + curTop = curPosition.top; + curLeft = curPosition.left; + } else { + curTop = parseFloat( curCSSTop ) || 0; + curLeft = parseFloat( curCSSLeft ) || 0; + } + + if ( jQuery.isFunction( options ) ) { + options = options.call( elem, i, curOffset ); + } + + if ( options.top != null ) { + props.top = ( options.top - curOffset.top ) + curTop; + } + if ( options.left != null ) { + props.left = ( options.left - curOffset.left ) + curLeft; + } + + if ( "using" in options ) { + options.using.call( elem, props ); + } else { + curElem.css( props ); + } + } +}; + + +jQuery.fn.extend({ + + position: function() { + if ( !this[0] ) { + return; + } + + var elem = this[0], + + // Get *real* offsetParent + offsetParent = this.offsetParent(), + + // Get correct offsets + offset = this.offset(), + parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); + + // Subtract element margins + // note: when an element has margin: auto the offsetLeft and marginLeft + // are the same in Safari causing offset.left to incorrectly be 0 + offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; + offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; + + // Add offsetParent borders + parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; + parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; + + // Subtract the two offsets + return { + top: offset.top - parentOffset.top, + left: offset.left - parentOffset.left + }; + }, + + offsetParent: function() { + return this.map(function() { + var offsetParent = this.offsetParent || document.body; + while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { + offsetParent = offsetParent.offsetParent; + } + return offsetParent || document.body; + }); + } +}); + + +// Create scrollLeft and scrollTop methods +jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { + var top = /Y/.test( prop ); + + jQuery.fn[ method ] = function( val ) { + return jQuery.access( this, function( elem, method, val ) { + var win = getWindow( elem ); + + if ( val === undefined ) { + return win ? (prop in win) ? win[ prop ] : + win.document.documentElement[ method ] : + elem[ method ]; + } + + if ( win ) { + win.scrollTo( + !top ? val : jQuery( win ).scrollLeft(), + top ? val : jQuery( win ).scrollTop() + ); + + } else { + elem[ method ] = val; + } + }, method, val, arguments.length, null ); + }; +}); + +function getWindow( elem ) { + return jQuery.isWindow( elem ) ? + elem : + elem.nodeType === 9 ? + elem.defaultView || elem.parentWindow : + false; +} +// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods +jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { + jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { + // margin is only for outerHeight, outerWidth + jQuery.fn[ funcName ] = function( margin, value ) { + var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), + extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); + + return jQuery.access( this, function( elem, type, value ) { + var doc; + + if ( jQuery.isWindow( elem ) ) { + // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there + // isn't a whole lot we can do. See pull request at this URL for discussion: + // https://github.com/jquery/jquery/pull/764 + return elem.document.documentElement[ "client" + name ]; + } + + // Get document width or height + if ( elem.nodeType === 9 ) { + doc = elem.documentElement; + + // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest + // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. + return Math.max( + elem.body[ "scroll" + name ], doc[ "scroll" + name ], + elem.body[ "offset" + name ], doc[ "offset" + name ], + doc[ "client" + name ] + ); + } + + return value === undefined ? + // Get width or height on the element, requesting but not forcing parseFloat + jQuery.css( elem, type, value, extra ) : + + // Set width or height on the element + jQuery.style( elem, type, value, extra ); + }, type, chainable ? margin : undefined, chainable, null ); + }; + }); +}); +// Expose jQuery to the global object +window.jQuery = window.$ = jQuery; + +// Expose jQuery as an AMD module, but only for AMD loaders that +// understand the issues with loading multiple versions of jQuery +// in a page that all might call define(). The loader will indicate +// they have special allowances for multiple jQuery versions by +// specifying define.amd.jQuery = true. Register as a named module, +// since jQuery can be concatenated with other files that may use define, +// but not use a proper concatenation script that understands anonymous +// AMD modules. A named AMD is safest and most robust way to register. +// Lowercase jquery is used because AMD module names are derived from +// file names, and jQuery is normally delivered in a lowercase file name. +// Do this after creating the global so that if an AMD module wants to call +// noConflict to hide this version of jQuery, it will work. +if ( typeof define === "function" && define.amd && define.amd.jQuery ) { + define( "jquery", [], function () { return jQuery; } ); +} + +})( window ); + +/*! ========================================================= + * bootstrap-modal.js v2.2.2 + * http://twitter.github.com/bootstrap/javascript.html#modals + * ========================================================= + * Twitter, Inc. require the following notice to accompany Bootstrap: + * + * Copyright (c) 2012 Twitter, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work + * except in compliance with the License. You may obtain a copy of the License in the LICENSE file, or at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing permissions and limitations under the License. + * + * ========================================================= */ + + +!function ($) { + + "use strict"; // jshint ;_; + + + /* MODAL CLASS DEFINITION + * ====================== */ + + var Modal = function (element, options) { + this.options = options + this.$element = $(element) + .delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this)) + this.options.remote && this.$element.find('.modal-body').load(this.options.remote) + } + + Modal.prototype = { + + constructor: Modal + + , toggle: function () { + return this[!this.isShown ? 'show' : 'hide']() + } + + , show: function () { + var that = this + , e = $.Event('show') + + this.$element.trigger(e) + + if (this.isShown || e.isDefaultPrevented()) return + + this.isShown = true + + this.escape() + + this.backdrop(function () { + var transition = $.support.transition && that.$element.hasClass('fade') + + if (!that.$element.parent().length) { + that.$element.appendTo(document.body) //don't move modals dom position + } + + that.$element + .show() + + if (transition) { + that.$element[0].offsetWidth // force reflow + } + + that.$element + .addClass('in') + .attr('aria-hidden', false) + + that.enforceFocus() + + transition ? + that.$element.one($.support.transition.end, function () { that.$element.focus().trigger('shown') }) : + that.$element.focus().trigger('shown') + + }) + } + + , hide: function (e) { + e && e.preventDefault() + + var that = this + + e = $.Event('hide') + + this.$element.trigger(e) + + if (!this.isShown || e.isDefaultPrevented()) return + + this.isShown = false + + this.escape() + + $(document).off('focusin.modal') + + this.$element + .removeClass('in') + .attr('aria-hidden', true) + + $.support.transition && this.$element.hasClass('fade') ? + this.hideWithTransition() : + this.hideModal() + } + + , enforceFocus: function () { + var that = this + $(document).on('focusin.modal', function (e) { + if (that.$element[0] !== e.target && !that.$element.has(e.target).length) { + that.$element.focus() + } + }) + } + + , escape: function () { + var that = this + if (this.isShown && this.options.keyboard) { + this.$element.on('keyup.dismiss.modal', function ( e ) { + e.which == 27 && that.hide() + }) + } else if (!this.isShown) { + this.$element.off('keyup.dismiss.modal') + } + } + + , hideWithTransition: function () { + var that = this + , timeout = setTimeout(function () { + that.$element.off($.support.transition.end) + that.hideModal() + }, 500) + + this.$element.one($.support.transition.end, function () { + clearTimeout(timeout) + that.hideModal() + }) + } + + , hideModal: function (that) { + this.$element + .hide() + .trigger('hidden') + + this.backdrop() + } + + , removeBackdrop: function () { + this.$backdrop.remove() + this.$backdrop = null + } + + , backdrop: function (callback) { + var that = this + , animate = this.$element.hasClass('fade') ? 'fade' : '' + + if (this.isShown && this.options.backdrop) { + var doAnimate = $.support.transition && animate + + this.$backdrop = $('