code
stringlengths
1
2.08M
language
stringclasses
1 value
/*! * Buttons helper for fancyBox * version: 1.0.5 (Mon, 15 Oct 2012) * @requires fancyBox v2.0 or later * * Usage: * $(".fancybox").fancybox({ * helpers : { * buttons: { * position : 'top' * } * } * }); * */ (function ($) { //Shortcut for fancyBox object var F = $.fancybox; //Add helper object F.helpers.buttons = { defaults : { skipSingle : false, // disables if gallery contains single image position : 'top', // 'top' or 'bottom' tpl : '<div id="fancybox-buttons"><ul><li><a class="btnPrev" title="Previous" href="javascript:;"></a></li><li><a class="btnPlay" title="Start slideshow" href="javascript:;"></a></li><li><a class="btnNext" title="Next" href="javascript:;"></a></li><li><a class="btnToggle" title="Toggle size" href="javascript:;"></a></li><li><a class="btnClose" title="Close" href="javascript:;"></a></li></ul></div>' }, list : null, buttons: null, beforeLoad: function (opts, obj) { //Remove self if gallery do not have at least two items if (opts.skipSingle && obj.group.length < 2) { obj.helpers.buttons = false; obj.closeBtn = true; return; } //Increase top margin to give space for buttons obj.margin[ opts.position === 'bottom' ? 2 : 0 ] += 30; }, onPlayStart: function () { if (this.buttons) { this.buttons.play.attr('title', 'Pause slideshow').addClass('btnPlayOn'); } }, onPlayEnd: function () { if (this.buttons) { this.buttons.play.attr('title', 'Start slideshow').removeClass('btnPlayOn'); } }, afterShow: function (opts, obj) { var buttons = this.buttons; if (!buttons) { this.list = $(opts.tpl).addClass(opts.position).appendTo('body'); buttons = { prev : this.list.find('.btnPrev').click( F.prev ), next : this.list.find('.btnNext').click( F.next ), play : this.list.find('.btnPlay').click( F.play ), toggle : this.list.find('.btnToggle').click( F.toggle ), close : this.list.find('.btnClose').click( F.close ) } } //Prev if (obj.index > 0 || obj.loop) { buttons.prev.removeClass('btnDisabled'); } else { buttons.prev.addClass('btnDisabled'); } //Next / Play if (obj.loop || obj.index < obj.group.length - 1) { buttons.next.removeClass('btnDisabled'); buttons.play.removeClass('btnDisabled'); } else { buttons.next.addClass('btnDisabled'); buttons.play.addClass('btnDisabled'); } this.buttons = buttons; this.onUpdate(opts, obj); }, onUpdate: function (opts, obj) { var toggle; if (!this.buttons) { return; } toggle = this.buttons.toggle.removeClass('btnDisabled btnToggleOn'); //Size toggle button if (obj.canShrink) { toggle.addClass('btnToggleOn'); } else if (!obj.canExpand) { toggle.addClass('btnDisabled'); } }, beforeClose: function () { if (this.list) { this.list.remove(); } this.list = null; this.buttons = null; } }; }(jQuery));
JavaScript
/*! * FullCalendar v2.0.0-beta2 Google Calendar Plugin * Docs & License: http://arshaw.com/fullcalendar/ * (c) 2013 Adam Shaw */ (function(factory) { if (typeof define === 'function' && define.amd) { define([ 'jquery' ], factory); } else { factory(jQuery); } })(function($) { var fc = $.fullCalendar; var applyAll = fc.applyAll; fc.sourceNormalizers.push(function(sourceOptions) { if (sourceOptions.dataType == 'gcal' || sourceOptions.dataType === undefined && (sourceOptions.url || '').match(/^(http|https):\/\/www.google.com\/calendar\/feeds\//)) { sourceOptions.dataType = 'gcal'; if (sourceOptions.editable === undefined) { sourceOptions.editable = false; } } }); fc.sourceFetchers.push(function(sourceOptions, start, end, timezone) { if (sourceOptions.dataType == 'gcal') { return transformOptions(sourceOptions, start, end, timezone); } }); function transformOptions(sourceOptions, start, end, timezone) { var success = sourceOptions.success; var data = $.extend({}, sourceOptions.data || {}, { singleevents: true, 'max-results': 9999 }); return $.extend({}, sourceOptions, { url: sourceOptions.url.replace(/\/basic$/, '/full') + '?alt=json-in-script&callback=?', dataType: 'jsonp', data: data, timezoneParam: 'ctz', startParam: 'start-min', endParam: 'start-max', success: function(data) { var events = []; if (data.feed.entry) { $.each(data.feed.entry, function(i, entry) { var url; $.each(entry.link, function(i, link) { if (link.type == 'text/html') { url = link.href; if (timezone && timezone != 'local') { url += (url.indexOf('?') == -1 ? '?' : '&') + 'ctz=' + encodeURIComponent(timezone); } } }); events.push({ id: entry.gCal$uid.value, title: entry.title.$t, start: entry.gd$when[0].startTime, end: entry.gd$when[0].endTime, url: url, location: entry.gd$where[0].valueString, description: entry.content.$t }); }); } var args = [events].concat(Array.prototype.slice.call(arguments, 1)); var res = applyAll(success, this, args); if ($.isArray(res)) { return res; } return events; } }); } // legacy fc.gcalFeed = function(url, sourceOptions) { return $.extend({}, sourceOptions, { url: url, dataType: 'gcal' }); }; });
JavaScript
/*! * FullCalendar v2.0.0-beta2 * Docs & License: http://arshaw.com/fullcalendar/ * (c) 2013 Adam Shaw */ (function(factory) { if (typeof define === 'function' && define.amd) { define([ 'jquery', 'moment' ], factory); } else { factory(jQuery, moment); } })(function($, moment) { ;; var defaults = { lang: 'en', defaultTimedEventDuration: '02:00:00', defaultAllDayEventDuration: { days: 1 }, forceEventDuration: false, nextDayThreshold: '09:00:00', // 9am // display defaultView: 'month', aspectRatio: 1.35, header: { left: 'title', center: '', right: 'today prev,next' }, weekends: true, weekNumbers: false, weekNumberTitle: 'W', weekNumberCalculation: 'local', //editable: false, // event ajax lazyFetching: true, startParam: 'start', endParam: 'end', timezoneParam: 'timezone', //allDayDefault: undefined, // time formats titleFormat: { month: 'MMMM YYYY', // like "September 1986". each language will override this week: 'll', // like "Sep 4 1986" day: 'LL' // like "September 4 1986" }, columnFormat: { month: 'ddd', // like "Sat" week: generateWeekColumnFormat, day: 'dddd' // like "Saturday" }, timeFormat: { // for event elements 'default': generateShortTimeFormat }, // locale isRTL: false, buttonText: { prev: "prev", next: "next", prevYear: "prev year", nextYear: "next year", today: 'today', month: 'month', week: 'week', day: 'day' }, buttonIcons: { prev: 'left-single-arrow', next: 'right-single-arrow', prevYear: 'left-double-arrow', nextYear: 'right-double-arrow' }, // jquery-ui theming theme: false, themeButtonIcons: { prev: 'circle-triangle-w', next: 'circle-triangle-e', prevYear: 'seek-prev', nextYear: 'seek-next' }, //selectable: false, unselectAuto: true, dropAccept: '*', handleWindowResize: true }; function generateShortTimeFormat(options, langData) { return langData.longDateFormat('LT') .replace(':mm', '(:mm)') .replace(/(\Wmm)$/, '($1)') // like above, but for foreign langs .replace(/\s*a$/i, 't'); // convert to AM/PM/am/pm to lowercase one-letter. remove any spaces beforehand } function generateWeekColumnFormat(options, langData) { var format = langData.longDateFormat('L'); // for the format like "MM/DD/YYYY" format = format.replace(/^Y+[^\w\s]*|[^\w\s]*Y+$/g, ''); // strip the year off the edge, as well as other misc non-whitespace chars if (options.isRTL) { format += ' ddd'; // for RTL, add day-of-week to end } else { format = 'ddd ' + format; // for LTR, add day-of-week to beginning } return format; } var langOptionHash = { en: { columnFormat: { week: 'ddd M/D' // override for english. different from the generated default, which is MM/DD } } }; // right-to-left defaults var rtlDefaults = { header: { left: 'next,prev today', center: '', right: 'title' }, buttonIcons: { prev: 'right-single-arrow', next: 'left-single-arrow', prevYear: 'right-double-arrow', nextYear: 'left-double-arrow' }, themeButtonIcons: { prev: 'circle-triangle-e', next: 'circle-triangle-w', nextYear: 'seek-prev', prevYear: 'seek-next' } }; ;; var fc = $.fullCalendar = { version: "2.0.0-beta2" }; var fcViews = fc.views = {}; $.fn.fullCalendar = function(options) { var args = Array.prototype.slice.call(arguments, 1); // for a possible method call var res = this; // what this function will return (this jQuery object by default) this.each(function(i, _element) { // loop each DOM element involved var element = $(_element); var calendar = element.data('fullCalendar'); // get the existing calendar object (if any) var singleRes; // the returned value of this single method call // a method call if (typeof options === 'string') { if (calendar && $.isFunction(calendar[options])) { singleRes = calendar[options].apply(calendar, args); if (!i) { res = singleRes; // record the first method call result } if (options === 'destroy') { // for the destroy method, must remove Calendar object data element.removeData('fullCalendar'); } } } // a new calendar initialization else if (!calendar) { // don't initialize twice calendar = new Calendar(element, options); element.data('fullCalendar', calendar); calendar.render(); } }); return res; }; // function for adding/overriding defaults function setDefaults(d) { mergeOptions(defaults, d); } // Recursively combines option hash-objects. // Better than `$.extend(true, ...)` because arrays are not traversed/copied. // // called like: // mergeOptions(target, obj1, obj2, ...) // function mergeOptions(target) { function mergeIntoTarget(name, value) { if ($.isPlainObject(value) && $.isPlainObject(target[name]) && !isForcedAtomicOption(name)) { // merge into a new object to avoid destruction target[name] = mergeOptions({}, target[name], value); // combine. `value` object takes precedence } else if (value !== undefined) { // only use values that are set and not undefined target[name] = value; } } for (var i=1; i<arguments.length; i++) { $.each(arguments[i], mergeIntoTarget); } return target; } // overcome sucky view-option-hash and option-merging behavior messing with options it shouldn't function isForcedAtomicOption(name) { // Any option that ends in "Time" or "Duration" is probably a Duration, // and these will commonly be specified as plain objects, which we don't want to mess up. return /(Time|Duration)$/.test(name); } // FIX: find a different solution for view-option-hashes and have a whitelist // for options that can be recursively merged. ;; //var langOptionHash = {}; // initialized in defaults.js fc.langs = langOptionHash; // expose // Initialize jQuery UI Datepicker translations while using some of the translations // for our own purposes. Will set this as the default language for datepicker. // Called from a translation file. fc.datepickerLang = function(langCode, datepickerLangCode, options) { var langOptions = langOptionHash[langCode]; // initialize FullCalendar's lang hash for this language if (!langOptions) { langOptions = langOptionHash[langCode] = {}; } // merge certain Datepicker options into FullCalendar's options mergeOptions(langOptions, { isRTL: options.isRTL, weekNumberTitle: options.weekHeader, titleFormat: { month: options.showMonthAfterYear ? 'YYYY[' + options.yearSuffix + '] MMMM' : 'MMMM YYYY[' + options.yearSuffix + ']' }, buttonText: { // the translations sometimes wrongly contain HTML entities prev: stripHTMLEntities(options.prevText), next: stripHTMLEntities(options.nextText), today: stripHTMLEntities(options.currentText) } }); // is jQuery UI Datepicker is on the page? if ($.datepicker) { // Register the language data. // FullCalendar and MomentJS use language codes like "pt-br" but Datepicker // does it like "pt-BR" or if it doesn't have the language, maybe just "pt". // Make an alias so the language can be referenced either way. $.datepicker.regional[datepickerLangCode] = $.datepicker.regional[langCode] = // alias options; // Alias 'en' to the default language data. Do this every time. $.datepicker.regional.en = $.datepicker.regional['']; // Set as Datepicker's global defaults. $.datepicker.setDefaults(options); } }; // Sets FullCalendar-specific translations. Also sets the language as the global default. // Called from a translation file. fc.lang = function(langCode, options) { var langOptions; if (options) { langOptions = langOptionHash[langCode]; // initialize the hash for this language if (!langOptions) { langOptions = langOptionHash[langCode] = {}; } mergeOptions(langOptions, options || {}); } // set it as the default language for FullCalendar defaults.lang = langCode; }; ;; function Calendar(element, instanceOptions) { var t = this; // Build options object // ----------------------------------------------------------------------------------- // Precedence (lowest to highest): defaults, rtlDefaults, langOptions, instanceOptions instanceOptions = instanceOptions || {}; var options = mergeOptions({}, defaults, instanceOptions); var langOptions; // determine language options if (options.lang in langOptionHash) { langOptions = langOptionHash[options.lang]; } else { langOptions = langOptionHash[defaults.lang]; } if (langOptions) { // if language options exist, rebuild... options = mergeOptions({}, defaults, langOptions, instanceOptions); } if (options.isRTL) { // is isRTL, rebuild... options = mergeOptions({}, defaults, rtlDefaults, langOptions || {}, instanceOptions); } // Exports // ----------------------------------------------------------------------------------- t.options = options; t.render = render; t.destroy = destroy; t.refetchEvents = refetchEvents; t.reportEvents = reportEvents; t.reportEventChange = reportEventChange; t.rerenderEvents = rerenderEvents; t.changeView = changeView; t.select = select; t.unselect = unselect; t.prev = prev; t.next = next; t.prevYear = prevYear; t.nextYear = nextYear; t.today = today; t.gotoDate = gotoDate; t.incrementDate = incrementDate; t.getDate = getDate; t.getCalendar = getCalendar; t.getView = getView; t.option = option; t.trigger = trigger; // Language-data Internals // ----------------------------------------------------------------------------------- // Apply overrides to the current language's data var langData = createObject( // make a cheap clone moment.langData(options.lang) ); if (options.monthNames) { langData._months = options.monthNames; } if (options.monthNamesShort) { langData._monthsShort = options.monthNamesShort; } if (options.dayNames) { langData._weekdays = options.dayNames; } if (options.dayNamesShort) { langData._weekdaysShort = options.dayNamesShort; } if (options.firstDay) { var _week = createObject(langData._week); // _week: { dow: # } _week.dow = options.firstDay; langData._week = _week; } // Calendar-specific Date Utilities // ----------------------------------------------------------------------------------- t.defaultAllDayEventDuration = moment.duration(options.defaultAllDayEventDuration); t.defaultTimedEventDuration = moment.duration(options.defaultTimedEventDuration); // Builds a moment using the settings of the current calendar: timezone and language. // Accepts anything the vanilla moment() constructor accepts. t.moment = function() { var mom; if (options.timezone === 'local') { mom = fc.moment.apply(null, arguments); } else if (options.timezone === 'UTC') { mom = fc.moment.utc.apply(null, arguments); } else { mom = fc.moment.parseZone.apply(null, arguments); } mom._lang = langData; return mom; }; // Returns a boolean about whether or not the calendar knows how to calculate // the timezone offset of arbitrary dates in the current timezone. t.getIsAmbigTimezone = function() { return options.timezone !== 'local' && options.timezone !== 'UTC'; }; // Returns a copy of the given date in the current timezone of it is ambiguously zoned. // This will also give the date an unambiguous time. t.rezoneDate = function(date) { return t.moment(date.toArray()); }; // Returns a moment for the current date, as defined by the client's computer, // or overridden by the `now` option. t.getNow = function() { var now = options.now; if (typeof now === 'function') { now = now(); } return t.moment(now); }; // Calculates the week number for a moment according to the calendar's // `weekNumberCalculation` setting. t.calculateWeekNumber = function(mom) { var calc = options.weekNumberCalculation; if (typeof calc === 'function') { return calc(mom); } else if (calc === 'local') { return mom.week(); } else if (calc.toUpperCase() === 'ISO') { return mom.isoWeek(); } }; // Get an event's normalized end date. If not present, calculate it from the defaults. t.getEventEnd = function(event) { if (event.end) { return event.end.clone(); } else { return t.getDefaultEventEnd(event.allDay, event.start); } }; // Given an event's allDay status and start date, return swhat its fallback end date should be. t.getDefaultEventEnd = function(allDay, start) { // TODO: rename to computeDefaultEventEnd var end = start.clone(); if (allDay) { end.stripTime().add(t.defaultAllDayEventDuration); } else { end.add(t.defaultTimedEventDuration); } if (t.getIsAmbigTimezone()) { end.stripZone(); // we don't know what the tzo should be } return end; }; // Date-formatting Utilities // ----------------------------------------------------------------------------------- // Like the vanilla formatRange, but with calendar-specific settings applied. t.formatRange = function(m1, m2, formatStr) { // a function that returns a formatStr // TODO: in future, precompute this if (typeof formatStr === 'function') { formatStr = formatStr.call(t, options, langData); } return formatRange(m1, m2, formatStr, null, options.isRTL); }; // Like the vanilla formatDate, but with calendar-specific settings applied. t.formatDate = function(mom, formatStr) { // a function that returns a formatStr // TODO: in future, precompute this if (typeof formatStr === 'function') { formatStr = formatStr.call(t, options, langData); } return formatDate(mom, formatStr); }; // Imports // ----------------------------------------------------------------------------------- EventManager.call(t, options); var isFetchNeeded = t.isFetchNeeded; var fetchEvents = t.fetchEvents; // Locals // ----------------------------------------------------------------------------------- var _element = element[0]; var header; var headerElement; var content; var tm; // for making theme classes var currentView; var elementOuterWidth; var suggestedViewHeight; var resizeUID = 0; var ignoreWindowResize = 0; var date; var events = []; var _dragElement; // Main Rendering // ----------------------------------------------------------------------------------- if (options.defaultDate != null) { date = t.moment(options.defaultDate); } else { date = t.getNow(); } function render(inc) { if (!content) { initialRender(); } else if (elementVisible()) { // mainly for the public API calcSize(); _renderView(inc); } } function initialRender() { tm = options.theme ? 'ui' : 'fc'; element.addClass('fc'); if (options.isRTL) { element.addClass('fc-rtl'); } else { element.addClass('fc-ltr'); } if (options.theme) { element.addClass('ui-widget'); } content = $("<div class='fc-content' />") .prependTo(element); header = new Header(t, options); headerElement = header.render(); if (headerElement) { element.prepend(headerElement); } changeView(options.defaultView); if (options.handleWindowResize) { $(window).resize(windowResize); } // needed for IE in a 0x0 iframe, b/c when it is resized, never triggers a windowResize if (!bodyVisible()) { lateRender(); } } // called when we know the calendar couldn't be rendered when it was initialized, // but we think it's ready now function lateRender() { setTimeout(function() { // IE7 needs this so dimensions are calculated correctly if (!currentView.start && bodyVisible()) { // !currentView.start makes sure this never happens more than once renderView(); } },0); } function destroy() { if (currentView) { trigger('viewDestroy', currentView, currentView, currentView.element); currentView.triggerEventDestroy(); } $(window).unbind('resize', windowResize); header.destroy(); content.remove(); element.removeClass('fc fc-rtl ui-widget'); } function elementVisible() { return element.is(':visible'); } function bodyVisible() { return $('body').is(':visible'); } // View Rendering // ----------------------------------------------------------------------------------- function changeView(newViewName) { if (!currentView || newViewName != currentView.name) { _changeView(newViewName); } } function _changeView(newViewName) { ignoreWindowResize++; if (currentView) { trigger('viewDestroy', currentView, currentView, currentView.element); unselect(); currentView.triggerEventDestroy(); // trigger 'eventDestroy' for each event freezeContentHeight(); currentView.element.remove(); header.deactivateButton(currentView.name); } header.activateButton(newViewName); currentView = new fcViews[newViewName]( $("<div class='fc-view fc-view-" + newViewName + "' />") .appendTo(content), t // the calendar object ); renderView(); unfreezeContentHeight(); ignoreWindowResize--; } function renderView(inc) { if ( !currentView.start || // never rendered before inc || // explicit date window change !date.isWithin(currentView.intervalStart, currentView.intervalEnd) // implicit date window change ) { if (elementVisible()) { _renderView(inc); } } } function _renderView(inc) { // assumes elementVisible ignoreWindowResize++; if (currentView.start) { // already been rendered? trigger('viewDestroy', currentView, currentView, currentView.element); unselect(); clearEvents(); } freezeContentHeight(); if (inc) { date = currentView.incrementDate(date, inc); } currentView.render(date.clone()); // the view's render method ONLY renders the skeleton, nothing else setSize(); unfreezeContentHeight(); (currentView.afterRender || noop)(); updateTitle(); updateTodayButton(); trigger('viewRender', currentView, currentView, currentView.element); ignoreWindowResize--; getAndRenderEvents(); } // Resizing // ----------------------------------------------------------------------------------- function updateSize() { if (elementVisible()) { unselect(); clearEvents(); calcSize(); setSize(); renderEvents(); } } function calcSize() { // assumes elementVisible if (options.contentHeight) { suggestedViewHeight = options.contentHeight; } else if (options.height) { suggestedViewHeight = options.height - (headerElement ? headerElement.height() : 0) - vsides(content); } else { suggestedViewHeight = Math.round(content.width() / Math.max(options.aspectRatio, .5)); } } function setSize() { // assumes elementVisible if (suggestedViewHeight === undefined) { calcSize(); // for first time // NOTE: we don't want to recalculate on every renderView because // it could result in oscillating heights due to scrollbars. } ignoreWindowResize++; currentView.setHeight(suggestedViewHeight); currentView.setWidth(content.width()); ignoreWindowResize--; elementOuterWidth = element.outerWidth(); } function windowResize() { if (!ignoreWindowResize) { if (currentView.start) { // view has already been rendered var uid = ++resizeUID; setTimeout(function() { // add a delay if (uid == resizeUID && !ignoreWindowResize && elementVisible()) { if (elementOuterWidth != (elementOuterWidth = element.outerWidth())) { ignoreWindowResize++; // in case the windowResize callback changes the height updateSize(); currentView.trigger('windowResize', _element); ignoreWindowResize--; } } }, 200); }else{ // calendar must have been initialized in a 0x0 iframe that has just been resized lateRender(); } } } /* Event Fetching/Rendering -----------------------------------------------------------------------------*/ // TODO: going forward, most of this stuff should be directly handled by the view function refetchEvents() { // can be called as an API method clearEvents(); fetchAndRenderEvents(); } function rerenderEvents(modifiedEventID) { // can be called as an API method clearEvents(); renderEvents(modifiedEventID); } function renderEvents(modifiedEventID) { // TODO: remove modifiedEventID hack if (elementVisible()) { currentView.renderEvents(events, modifiedEventID); // actually render the DOM elements currentView.trigger('eventAfterAllRender'); } } function clearEvents() { currentView.triggerEventDestroy(); // trigger 'eventDestroy' for each event currentView.clearEvents(); // actually remove the DOM elements currentView.clearEventData(); // for View.js, TODO: unify with clearEvents } function getAndRenderEvents() { if (!options.lazyFetching || isFetchNeeded(currentView.start, currentView.end)) { fetchAndRenderEvents(); } else { renderEvents(); } } function fetchAndRenderEvents() { fetchEvents(currentView.start, currentView.end); // ... will call reportEvents // ... which will call renderEvents } // called when event data arrives function reportEvents(_events) { events = _events; renderEvents(); } // called when a single event's data has been changed function reportEventChange(eventID) { rerenderEvents(eventID); } /* Header Updating -----------------------------------------------------------------------------*/ function updateTitle() { header.updateTitle(currentView.title); } function updateTodayButton() { var now = t.getNow(); if (now.isWithin(currentView.intervalStart, currentView.intervalEnd)) { header.disableButton('today'); } else { header.enableButton('today'); } } /* Selection -----------------------------------------------------------------------------*/ function select(start, end) { currentView.select(start, end); } function unselect() { // safe to be called before renderView if (currentView) { currentView.unselect(); } } /* Date -----------------------------------------------------------------------------*/ function prev() { renderView(-1); } function next() { renderView(1); } function prevYear() { date.add('years', -1); renderView(); } function nextYear() { date.add('years', 1); renderView(); } function today() { date = t.getNow(); renderView(); } function gotoDate(dateInput) { date = t.moment(dateInput); renderView(); } function incrementDate() { date.add.apply(date, arguments); renderView(); } function getDate() { return date.clone(); } /* Height "Freezing" -----------------------------------------------------------------------------*/ function freezeContentHeight() { content.css({ width: '100%', height: content.height(), overflow: 'hidden' }); } function unfreezeContentHeight() { content.css({ width: '', height: '', overflow: '' }); } /* Misc -----------------------------------------------------------------------------*/ function getCalendar() { return t; } function getView() { return currentView; } function option(name, value) { if (value === undefined) { return options[name]; } if (name == 'height' || name == 'contentHeight' || name == 'aspectRatio') { options[name] = value; updateSize(); } } function trigger(name, thisObj) { if (options[name]) { return options[name].apply( thisObj || _element, Array.prototype.slice.call(arguments, 2) ); } } /* External Dragging ------------------------------------------------------------------------*/ if (options.droppable) { // TODO: unbind on destroy $(document) .bind('dragstart', function(ev, ui) { var _e = ev.target; var e = $(_e); if (!e.parents('.fc').length) { // not already inside a calendar var accept = options.dropAccept; if ($.isFunction(accept) ? accept.call(_e, e) : e.is(accept)) { _dragElement = _e; currentView.dragStart(_dragElement, ev, ui); } } }) .bind('dragstop', function(ev, ui) { if (_dragElement) { currentView.dragStop(_dragElement, ev, ui); _dragElement = null; } }); } } ;; function Header(calendar, options) { var t = this; // exports t.render = render; t.destroy = destroy; t.updateTitle = updateTitle; t.activateButton = activateButton; t.deactivateButton = deactivateButton; t.disableButton = disableButton; t.enableButton = enableButton; // locals var element = $([]); var tm; function render() { tm = options.theme ? 'ui' : 'fc'; var sections = options.header; if (sections) { element = $("<table class='fc-header' style='width:100%'/>") .append( $("<tr/>") .append(renderSection('left')) .append(renderSection('center')) .append(renderSection('right')) ); return element; } } function destroy() { element.remove(); } function renderSection(position) { var e = $("<td class='fc-header-" + position + "'/>"); var buttonStr = options.header[position]; if (buttonStr) { $.each(buttonStr.split(' '), function(i) { if (i > 0) { e.append("<span class='fc-header-space'/>"); } var prevButton; $.each(this.split(','), function(j, buttonName) { if (buttonName == 'title') { e.append("<span class='fc-header-title'><h2>&nbsp;</h2></span>"); if (prevButton) { prevButton.addClass(tm + '-corner-right'); } prevButton = null; }else{ var buttonClick; if (calendar[buttonName]) { buttonClick = calendar[buttonName]; // calendar method } else if (fcViews[buttonName]) { buttonClick = function() { button.removeClass(tm + '-state-hover'); // forget why calendar.changeView(buttonName); }; } if (buttonClick) { // smartProperty allows different text per view button (ex: "Agenda Week" vs "Basic Week") var themeIcon = smartProperty(options.themeButtonIcons, buttonName); var normalIcon = smartProperty(options.buttonIcons, buttonName); var text = smartProperty(options.buttonText, buttonName); var html; if (themeIcon && options.theme) { html = "<span class='ui-icon ui-icon-" + themeIcon + "'></span>"; } else if (normalIcon && !options.theme) { html = "<span class='fc-icon fc-icon-" + normalIcon + "'></span>"; } else { html = htmlEscape(text || buttonName); } var button = $( "<span class='fc-button fc-button-" + buttonName + " " + tm + "-state-default'>" + html + "</span>" ) .click(function() { if (!button.hasClass(tm + '-state-disabled')) { buttonClick(); } }) .mousedown(function() { button .not('.' + tm + '-state-active') .not('.' + tm + '-state-disabled') .addClass(tm + '-state-down'); }) .mouseup(function() { button.removeClass(tm + '-state-down'); }) .hover( function() { button .not('.' + tm + '-state-active') .not('.' + tm + '-state-disabled') .addClass(tm + '-state-hover'); }, function() { button .removeClass(tm + '-state-hover') .removeClass(tm + '-state-down'); } ) .appendTo(e); disableTextSelection(button); if (!prevButton) { button.addClass(tm + '-corner-left'); } prevButton = button; } } }); if (prevButton) { prevButton.addClass(tm + '-corner-right'); } }); } return e; } function updateTitle(html) { element.find('h2') .html(html); } function activateButton(buttonName) { element.find('span.fc-button-' + buttonName) .addClass(tm + '-state-active'); } function deactivateButton(buttonName) { element.find('span.fc-button-' + buttonName) .removeClass(tm + '-state-active'); } function disableButton(buttonName) { element.find('span.fc-button-' + buttonName) .addClass(tm + '-state-disabled'); } function enableButton(buttonName) { element.find('span.fc-button-' + buttonName) .removeClass(tm + '-state-disabled'); } } ;; fc.sourceNormalizers = []; fc.sourceFetchers = []; var ajaxDefaults = { dataType: 'json', cache: false }; var eventGUID = 1; function EventManager(options) { // assumed to be a calendar var t = this; // exports t.isFetchNeeded = isFetchNeeded; t.fetchEvents = fetchEvents; t.addEventSource = addEventSource; t.removeEventSource = removeEventSource; t.updateEvent = updateEvent; t.renderEvent = renderEvent; t.removeEvents = removeEvents; t.clientEvents = clientEvents; t.mutateEvent = mutateEvent; // imports var trigger = t.trigger; var getView = t.getView; var reportEvents = t.reportEvents; var getEventEnd = t.getEventEnd; // locals var stickySource = { events: [] }; var sources = [ stickySource ]; var rangeStart, rangeEnd; var currentFetchID = 0; var pendingSourceCnt = 0; var loadingLevel = 0; var cache = []; var _sources = options.eventSources || []; if (options.events) { _sources.push(options.events); } for (var i=0; i<_sources.length; i++) { _addEventSource(_sources[i]); } /* Fetching -----------------------------------------------------------------------------*/ function isFetchNeeded(start, end) { return !rangeStart || // nothing has been fetched yet? // or, a part of the new range is outside of the old range? (after normalizing) start.clone().stripZone() < rangeStart.clone().stripZone() || end.clone().stripZone() > rangeEnd.clone().stripZone(); } function fetchEvents(start, end) { rangeStart = start; rangeEnd = end; cache = []; var fetchID = ++currentFetchID; var len = sources.length; pendingSourceCnt = len; for (var i=0; i<len; i++) { fetchEventSource(sources[i], fetchID); } } function fetchEventSource(source, fetchID) { _fetchEventSource(source, function(events) { if (fetchID == currentFetchID) { if (events) { for (var i=0; i<events.length; i++) { var event = buildEvent(events[i], source); if (event) { cache.push(event); } } } pendingSourceCnt--; if (!pendingSourceCnt) { reportEvents(cache); } } }); } function _fetchEventSource(source, callback) { var i; var fetchers = fc.sourceFetchers; var res; for (i=0; i<fetchers.length; i++) { res = fetchers[i].call( t, // this, the Calendar object source, rangeStart.clone(), rangeEnd.clone(), options.timezone, callback ); if (res === true) { // the fetcher is in charge. made its own async request return; } else if (typeof res == 'object') { // the fetcher returned a new source. process it _fetchEventSource(res, callback); return; } } var events = source.events; if (events) { if ($.isFunction(events)) { pushLoading(); events.call( t, // this, the Calendar object rangeStart.clone(), rangeEnd.clone(), options.timezone, function(events) { callback(events); popLoading(); } ); } else if ($.isArray(events)) { callback(events); } else { callback(); } }else{ var url = source.url; if (url) { var success = source.success; var error = source.error; var complete = source.complete; // retrieve any outbound GET/POST $.ajax data from the options var customData; if ($.isFunction(source.data)) { // supplied as a function that returns a key/value object customData = source.data(); } else { // supplied as a straight key/value object customData = source.data; } // use a copy of the custom data so we can modify the parameters // and not affect the passed-in object. var data = $.extend({}, customData || {}); var startParam = firstDefined(source.startParam, options.startParam); var endParam = firstDefined(source.endParam, options.endParam); var timezoneParam = firstDefined(source.timezoneParam, options.timezoneParam); if (startParam) { data[startParam] = rangeStart.format(); } if (endParam) { data[endParam] = rangeEnd.format(); } if (options.timezone && options.timezone != 'local') { data[timezoneParam] = options.timezone; } pushLoading(); $.ajax($.extend({}, ajaxDefaults, source, { data: data, success: function(events) { events = events || []; var res = applyAll(success, this, arguments); if ($.isArray(res)) { events = res; } callback(events); }, error: function() { applyAll(error, this, arguments); callback(); }, complete: function() { applyAll(complete, this, arguments); popLoading(); } })); }else{ callback(); } } } /* Sources -----------------------------------------------------------------------------*/ function addEventSource(source) { source = _addEventSource(source); if (source) { pendingSourceCnt++; fetchEventSource(source, currentFetchID); // will eventually call reportEvents } } function _addEventSource(source) { if ($.isFunction(source) || $.isArray(source)) { source = { events: source }; } else if (typeof source == 'string') { source = { url: source }; } if (typeof source == 'object') { normalizeSource(source); sources.push(source); return source; } } function removeEventSource(source) { sources = $.grep(sources, function(src) { return !isSourcesEqual(src, source); }); // remove all client events from that source cache = $.grep(cache, function(e) { return !isSourcesEqual(e.source, source); }); reportEvents(cache); } /* Manipulation -----------------------------------------------------------------------------*/ function updateEvent(event) { mutateEvent(event); propagateMiscProperties(event); reportEvents(cache); // reports event modifications (so we can redraw) } var miscCopyableProps = [ 'title', 'url', 'allDay', 'className', 'editable', 'color', 'backgroundColor', 'borderColor', 'textColor' ]; function propagateMiscProperties(event) { var i; var cachedEvent; var j; var prop; for (i=0; i<cache.length; i++) { cachedEvent = cache[i]; if (cachedEvent._id == event._id && cachedEvent !== event) { for (j=0; j<miscCopyableProps.length; j++) { prop = miscCopyableProps[j]; if (event[prop] !== undefined) { cachedEvent[prop] = event[prop]; } } } } } function renderEvent(eventData, stick) { var event = buildEvent(eventData); if (event) { if (!event.source) { if (stick) { stickySource.events.push(event); event.source = stickySource; } cache.push(event); } reportEvents(cache); } } function removeEvents(filter) { var i; if (!filter) { // remove all cache = []; // clear all array sources for (i=0; i<sources.length; i++) { if ($.isArray(sources[i].events)) { sources[i].events = []; } } }else{ if (!$.isFunction(filter)) { // an event ID var id = filter + ''; filter = function(e) { return e._id == id; }; } cache = $.grep(cache, filter, true); // remove events from array sources for (i=0; i<sources.length; i++) { if ($.isArray(sources[i].events)) { sources[i].events = $.grep(sources[i].events, filter, true); } } } reportEvents(cache); } function clientEvents(filter) { if ($.isFunction(filter)) { return $.grep(cache, filter); } else if (filter) { // an event ID filter += ''; return $.grep(cache, function(e) { return e._id == filter; }); } return cache; // else, return all } /* Loading State -----------------------------------------------------------------------------*/ function pushLoading() { if (!(loadingLevel++)) { trigger('loading', null, true, getView()); } } function popLoading() { if (!(--loadingLevel)) { trigger('loading', null, false, getView()); } } /* Event Normalization -----------------------------------------------------------------------------*/ function buildEvent(data, source) { // source may be undefined! var out = {}; var start; var end; var allDay; var allDayDefault; if (options.eventDataTransform) { data = options.eventDataTransform(data); } if (source && source.eventDataTransform) { data = source.eventDataTransform(data); } start = t.moment(data.start || data.date); // "date" is an alias for "start" if (!start.isValid()) { return; } end = null; if (data.end) { end = t.moment(data.end); if (!end.isValid()) { return; } } allDay = data.allDay; if (allDay === undefined) { allDayDefault = firstDefined( source ? source.allDayDefault : undefined, options.allDayDefault ); if (allDayDefault !== undefined) { // use the default allDay = allDayDefault; } else { // all dates need to have ambig time for the event to be considered allDay allDay = !start.hasTime() && (!end || !end.hasTime()); } } // normalize the date based on allDay if (allDay) { // neither date should have a time if (start.hasTime()) { start.stripTime(); } if (end && end.hasTime()) { end.stripTime(); } } else { // force a time/zone up the dates if (!start.hasTime()) { start = t.rezoneDate(start); } if (end && !end.hasTime()) { end = t.rezoneDate(end); } } // Copy all properties over to the resulting object. // The special-case properties will be copied over afterwards. $.extend(out, data); if (source) { out.source = source; } out._id = data._id || (data.id === undefined ? '_fc' + eventGUID++ : data.id + ''); if (data.className) { if (typeof data.className == 'string') { out.className = data.className.split(/\s+/); } else { // assumed to be an array out.className = data.className; } } else { out.className = []; } out.allDay = allDay; out.start = start; out.end = end; if (options.forceEventDuration && !out.end) { out.end = getEventEnd(out); } backupEventDates(out); return out; } /* Event Modification Math -----------------------------------------------------------------------------------------*/ // Modify the date(s) of an event and make this change propagate to all other events with // the same ID (related repeating events). // // If `newStart`/`newEnd` are not specified, the "new" dates are assumed to be `event.start` and `event.end`. // The "old" dates to be compare against are always `event._start` and `event._end` (set by EventManager). // // Returns a function that can be called to undo all the operations. // function mutateEvent(event, newStart, newEnd) { var oldAllDay = event._allDay; var oldStart = event._start; var oldEnd = event._end; var clearEnd = false; var newAllDay; var dateDelta; var durationDelta; // if no new dates were passed in, compare against the event's existing dates if (!newStart && !newEnd) { newStart = event.start; newEnd = event.end; } // NOTE: throughout this function, the initial values of `newStart` and `newEnd` are // preserved. These values may be undefined. // detect new allDay if (event.allDay != oldAllDay) { // if value has changed, use it newAllDay = event.allDay; } else { // otherwise, see if any of the new dates are allDay newAllDay = !(newStart || newEnd).hasTime(); } // normalize the new dates based on allDay if (newAllDay) { if (newStart) { newStart = newStart.clone().stripTime(); } if (newEnd) { newEnd = newEnd.clone().stripTime(); } } // compute dateDelta if (newStart) { if (newAllDay) { dateDelta = dayishDiff(newStart, oldStart.clone().stripTime()); // treat oldStart as allDay } else { dateDelta = dayishDiff(newStart, oldStart); } } if (newAllDay != oldAllDay) { // if allDay has changed, always throw away the end clearEnd = true; } else if (newEnd) { durationDelta = dayishDiff( // new duration newEnd || t.getDefaultEventEnd(newAllDay, newStart || oldStart), newStart || oldStart ).subtract(dayishDiff( // subtract old duration oldEnd || t.getDefaultEventEnd(oldAllDay, oldStart), oldStart )); } return mutateEvents( clientEvents(event._id), // get events with this ID clearEnd, newAllDay, dateDelta, durationDelta ); } // Modifies an array of events in the following ways (operations are in order): // - clear the event's `end` // - convert the event to allDay // - add `dateDelta` to the start and end // - add `durationDelta` to the event's duration // // Returns a function that can be called to undo all the operations. // function mutateEvents(events, clearEnd, forceAllDay, dateDelta, durationDelta) { var isAmbigTimezone = t.getIsAmbigTimezone(); var undoFunctions = []; $.each(events, function(i, event) { var oldAllDay = event._allDay; var oldStart = event._start; var oldEnd = event._end; var newAllDay = forceAllDay != null ? forceAllDay : oldAllDay; var newStart = oldStart.clone(); var newEnd = (!clearEnd && oldEnd) ? oldEnd.clone() : null; // NOTE: this function is responsible for transforming `newStart` and `newEnd`, // which were initialized to the OLD values first. `newEnd` may be null. // normlize newStart/newEnd to be consistent with newAllDay if (newAllDay) { newStart.stripTime(); if (newEnd) { newEnd.stripTime(); } } else { if (!newStart.hasTime()) { newStart = t.rezoneDate(newStart); } if (newEnd && !newEnd.hasTime()) { newEnd = t.rezoneDate(newEnd); } } // ensure we have an end date if necessary if (!newEnd && (options.forceEventDuration || +durationDelta)) { newEnd = t.getDefaultEventEnd(newAllDay, newStart); } // translate the dates newStart.add(dateDelta); if (newEnd) { newEnd.add(dateDelta).add(durationDelta); } // if the dates have changed, and we know it is impossible to recompute the // timezone offsets, strip the zone. if (isAmbigTimezone) { if (+dateDelta) { newStart.stripZone(); } if (newEnd && (+dateDelta || +durationDelta)) { newEnd.stripZone(); } } event.allDay = newAllDay; event.start = newStart; event.end = newEnd; backupEventDates(event); undoFunctions.push(function() { event.allDay = oldAllDay; event.start = oldStart; event.end = oldEnd; backupEventDates(event); }); }); return function() { for (var i=0; i<undoFunctions.length; i++) { undoFunctions[i](); } }; } /* Utils ------------------------------------------------------------------------------*/ function normalizeSource(source) { if (source.className) { // TODO: repeat code, same code for event classNames if (typeof source.className == 'string') { source.className = source.className.split(/\s+/); } }else{ source.className = []; } var normalizers = fc.sourceNormalizers; for (var i=0; i<normalizers.length; i++) { normalizers[i].call(t, source); } } function isSourcesEqual(source1, source2) { return source1 && source2 && getSourcePrimitive(source1) == getSourcePrimitive(source2); } function getSourcePrimitive(source) { return ((typeof source == 'object') ? (source.events || source.url) : '') || source; } } // updates the "backup" properties, which are preserved in order to compute diffs later on. function backupEventDates(event) { event._allDay = event.allDay; event._start = event.start.clone(); event._end = event.end ? event.end.clone() : null; } ;; fc.applyAll = applyAll; // Create an object that has the given prototype. // Just like Object.create function createObject(proto) { var f = function() {}; f.prototype = proto; return new f(); } // copy specifically-owned (non-protoype) properties of `b` onto `a` function extend(a, b) { for (var i in b) { if (b.hasOwnProperty(i)) { a[i] = b[i]; } } } /* Date -----------------------------------------------------------------------------*/ var dayIDs = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']; // diffs the two moments into a Duration where full-days are recorded first, // then the remaining time. function dayishDiff(d1, d0) { return moment.duration({ days: d1.clone().stripTime().diff(d0.clone().stripTime(), 'days'), ms: d1.time() - d0.time() }); } function isNativeDate(input) { return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date; } /* Event Element Binding -----------------------------------------------------------------------------*/ function lazySegBind(container, segs, bindHandlers) { container.unbind('mouseover').mouseover(function(ev) { var parent=ev.target, e, i, seg; while (parent != this) { e = parent; parent = parent.parentNode; } if ((i = e._fci) !== undefined) { e._fci = undefined; seg = segs[i]; bindHandlers(seg.event, seg.element, seg); $(ev.target).trigger(ev); } ev.stopPropagation(); }); } /* Element Dimensions -----------------------------------------------------------------------------*/ function setOuterWidth(element, width, includeMargins) { for (var i=0, e; i<element.length; i++) { e = $(element[i]); e.width(Math.max(0, width - hsides(e, includeMargins))); } } function setOuterHeight(element, height, includeMargins) { for (var i=0, e; i<element.length; i++) { e = $(element[i]); e.height(Math.max(0, height - vsides(e, includeMargins))); } } function hsides(element, includeMargins) { return hpadding(element) + hborders(element) + (includeMargins ? hmargins(element) : 0); } function hpadding(element) { return (parseFloat($.css(element[0], 'paddingLeft', true)) || 0) + (parseFloat($.css(element[0], 'paddingRight', true)) || 0); } function hmargins(element) { return (parseFloat($.css(element[0], 'marginLeft', true)) || 0) + (parseFloat($.css(element[0], 'marginRight', true)) || 0); } function hborders(element) { return (parseFloat($.css(element[0], 'borderLeftWidth', true)) || 0) + (parseFloat($.css(element[0], 'borderRightWidth', true)) || 0); } function vsides(element, includeMargins) { return vpadding(element) + vborders(element) + (includeMargins ? vmargins(element) : 0); } function vpadding(element) { return (parseFloat($.css(element[0], 'paddingTop', true)) || 0) + (parseFloat($.css(element[0], 'paddingBottom', true)) || 0); } function vmargins(element) { return (parseFloat($.css(element[0], 'marginTop', true)) || 0) + (parseFloat($.css(element[0], 'marginBottom', true)) || 0); } function vborders(element) { return (parseFloat($.css(element[0], 'borderTopWidth', true)) || 0) + (parseFloat($.css(element[0], 'borderBottomWidth', true)) || 0); } /* Misc Utils -----------------------------------------------------------------------------*/ //TODO: arraySlice //TODO: isFunction, grep ? function noop() { } function dateCompare(a, b) { // works with moments too return a - b; } function arrayMax(a) { return Math.max.apply(Math, a); } function smartProperty(obj, name) { // get a camel-cased/namespaced property of an object if (obj[name] !== undefined) { return obj[name]; } var parts = name.split(/(?=[A-Z])/), i=parts.length-1, res; for (; i>=0; i--) { res = obj[parts[i].toLowerCase()]; if (res !== undefined) { return res; } } return obj['default']; } function htmlEscape(s) { return (s + '').replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/'/g, '&#039;') .replace(/"/g, '&quot;') .replace(/\n/g, '<br />'); } function stripHTMLEntities(text) { return text.replace(/&.*?;/g, ''); } function disableTextSelection(element) { element .attr('unselectable', 'on') .css('MozUserSelect', 'none') .bind('selectstart.ui', function() { return false; }); } /* function enableTextSelection(element) { element .attr('unselectable', 'off') .css('MozUserSelect', '') .unbind('selectstart.ui'); } */ function markFirstLast(e) { // TODO: use CSS selectors instead e.children() .removeClass('fc-first fc-last') .filter(':first-child') .addClass('fc-first') .end() .filter(':last-child') .addClass('fc-last'); } function getSkinCss(event, opt) { var source = event.source || {}; var eventColor = event.color; var sourceColor = source.color; var optionColor = opt('eventColor'); var backgroundColor = event.backgroundColor || eventColor || source.backgroundColor || sourceColor || opt('eventBackgroundColor') || optionColor; var borderColor = event.borderColor || eventColor || source.borderColor || sourceColor || opt('eventBorderColor') || optionColor; var textColor = event.textColor || source.textColor || opt('eventTextColor'); var statements = []; if (backgroundColor) { statements.push('background-color:' + backgroundColor); } if (borderColor) { statements.push('border-color:' + borderColor); } if (textColor) { statements.push('color:' + textColor); } return statements.join(';'); } function applyAll(functions, thisObj, args) { if ($.isFunction(functions)) { functions = [ functions ]; } if (functions) { var i; var ret; for (i=0; i<functions.length; i++) { ret = functions[i].apply(thisObj, args) || ret; } return ret; } } function firstDefined() { for (var i=0; i<arguments.length; i++) { if (arguments[i] !== undefined) { return arguments[i]; } } } ;; var ambigDateOfMonthRegex = /^\s*\d{4}-\d\d$/; var ambigTimeOrZoneRegex = /^\s*\d{4}-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?)?$/; // Creating // ------------------------------------------------------------------------------------------------- // Creates a moment in the local timezone, similar to the vanilla moment(...) constructor, // but with extra features: // - ambiguous times // - enhanced formatting (TODO) fc.moment = function() { return makeMoment(arguments); }; // Sames as fc.moment, but creates a moment in the UTC timezone. fc.moment.utc = function() { return makeMoment(arguments, true); }; // Creates a moment and preserves the timezone offset of the ISO8601 string, // allowing for ambigous timezones. If the string is not an ISO8601 string, // the moment is processed in UTC-mode (a departure from moment's method). fc.moment.parseZone = function() { return makeMoment(arguments, true, true); }; // when parseZone==true, if can't figure it out, fall back to parseUTC function makeMoment(args, parseUTC, parseZone) { var input = args[0]; var isSingleString = args.length == 1 && typeof input === 'string'; var isAmbigTime = false; var isAmbigZone = false; var ambigMatch; var mom; if (isSingleString) { if (ambigDateOfMonthRegex.test(input)) { // accept strings like '2014-05', but convert to the first of the month input += '-01'; isAmbigTime = true; isAmbigZone = true; } else if ((ambigMatch = ambigTimeOrZoneRegex.exec(input))) { isAmbigTime = !ambigMatch[5]; // no time part? isAmbigZone = true; } } else if ($.isArray(input)) { // arrays have no timezone information, so assume ambiguous zone isAmbigZone = true; } // instantiate a vanilla moment if (parseUTC || parseZone || isAmbigTime) { mom = moment.utc.apply(moment, args); } else { mom = moment.apply(null, args); } if (moment.isMoment(input)) { transferAmbigs(input, mom); } if (isAmbigTime) { mom._ambigTime = true; mom._ambigZone = true; // if ambiguous time, also ambiguous timezone offset } if (parseZone) { if (isAmbigZone) { mom._ambigZone = true; } else if (isSingleString) { mom.zone(input); // if fails, will set it to 0, which it already was } else if (isNativeDate(input) || input === undefined) { // native Date object? // specified with no arguments? // then consider the moment to be local mom.local(); } } return new FCMoment(mom); } // our subclass of Moment. // accepts an object with the internal Moment properties that should be copied over to // this object (most likely another Moment object). function FCMoment(config) { extend(this, config); } // chain the prototype to Moment's FCMoment.prototype = createObject(moment.fn); // we need this because Moment's implementation will not copy of the ambig flags FCMoment.prototype.clone = function() { return makeMoment([ this ]); }; // Time-of-day // ------------------------------------------------------------------------------------------------- // GETTER // Returns a Duration with the hours/minutes/seconds/ms values of the moment. // If the moment has an ambiguous time, a duration of 00:00 will be returned. // // SETTER // You can supply a Duration, a Moment, or a Duration-like argument. // When setting the time, and the moment has an ambiguous time, it then becomes unambiguous. FCMoment.prototype.time = function(time) { if (time == null) { // getter return moment.duration({ hours: this.hours(), minutes: this.minutes(), seconds: this.seconds(), milliseconds: this.milliseconds() }); } else { // setter delete this._ambigTime; // mark that the moment now has a time if (!moment.isDuration(time) && !moment.isMoment(time)) { time = moment.duration(time); } return this.hours(time.hours() + time.days() * 24) // day value will cause overflow (so 24 hours becomes 00:00:00 of next day) .minutes(time.minutes()) .seconds(time.seconds()) .milliseconds(time.milliseconds()); } }; // Converts the moment to UTC, stripping out its time-of-day and timezone offset, // but preserving its YMD. A moment with a stripped time will display no time // nor timezone offset when .format() is called. FCMoment.prototype.stripTime = function() { var a = this.toArray(); // year,month,date,hours,minutes,seconds as an array // set the internal UTC flag moment.fn.utc.call(this); // call the original method, because we don't want to affect _ambigZone this._ambigTime = true; this._ambigZone = true; // if ambiguous time, also ambiguous timezone offset this.year(a[0]) .month(a[1]) .date(a[2]) .hours(0) .minutes(0) .seconds(0) .milliseconds(0); return this; // for chaining }; // Returns if the moment has a non-ambiguous time (boolean) FCMoment.prototype.hasTime = function() { return !this._ambigTime; }; // Timezone // ------------------------------------------------------------------------------------------------- // Converts the moment to UTC, stripping out its timezone offset, but preserving its // YMD and time-of-day. A moment with a stripped timezone offset will display no // timezone offset when .format() is called. FCMoment.prototype.stripZone = function() { var a = this.toArray(); // year,month,date,hours,minutes,seconds as an array // set the internal UTC flag moment.fn.utc.call(this); // call the original method, because we don't want to affect _ambigZone this._ambigZone = true; this.year(a[0]) .month(a[1]) .date(a[2]) .hours(a[3]) .minutes(a[4]) .seconds(a[5]) .milliseconds(a[6]); return this; // for chaining }; // Returns of the moment has a non-ambiguous timezone offset (boolean) FCMoment.prototype.hasZone = function() { return !this._ambigZone; }; // this method implicitly marks a zone FCMoment.prototype.zone = function(tzo) { if (tzo != null) { delete this._ambigZone; } return moment.fn.zone.apply(this, arguments); }; // this method implicitly marks a zone. // we don't need this, because .local internally calls .zone, but we don't want to depend on that. FCMoment.prototype.local = function() { delete this._ambigZone; return moment.fn.local.apply(this, arguments); }; // this method implicitly marks a zone. // we don't need this, because .utc internally calls .zone, but we don't want to depend on that. FCMoment.prototype.utc = function() { delete this._ambigZone; return moment.fn.utc.apply(this, arguments); }; // Formatting // ------------------------------------------------------------------------------------------------- FCMoment.prototype.format = function() { if (arguments[0]) { return formatDate(this, arguments[0]); // our extended formatting } if (this._ambigTime) { return momentFormat(this, 'YYYY-MM-DD'); } if (this._ambigZone) { return momentFormat(this, 'YYYY-MM-DD[T]HH:mm:ss'); } return momentFormat(this); // default moment original formatting }; FCMoment.prototype.toISOString = function() { if (this._ambigTime) { return momentFormat(this, 'YYYY-MM-DD'); } if (this._ambigZone) { return momentFormat(this, 'YYYY-MM-DD[T]HH:mm:ss'); } return moment.fn.toISOString.apply(this, arguments); }; // Querying // ------------------------------------------------------------------------------------------------- // Is the moment within the specified range? `end` is exclusive. FCMoment.prototype.isWithin = function(start, end) { var a = commonlyAmbiguate([ this, start, end ]); return a[0] >= a[1] && a[0] < a[2]; }; // Make these query methods work with ambiguous moments $.each([ 'isBefore', 'isAfter', 'isSame' ], function(i, methodName) { FCMoment.prototype[methodName] = function(input, units) { var a = commonlyAmbiguate([ this, input ]); return moment.fn[methodName].call(a[0], a[1], units); }; }); // Misc Internals // ------------------------------------------------------------------------------------------------- // transfers our internal _ambig properties from one moment to another function transferAmbigs(src, dest) { if (src._ambigTime) { dest._ambigTime = true; } else if (dest._ambigTime) { delete dest._ambigTime; } if (src._ambigZone) { dest._ambigZone = true; } else if (dest._ambigZone) { delete dest._ambigZone; } } // given an array of moment-like inputs, return a parallel array w/ moments similarly ambiguated. // for example, of one moment has ambig time, but not others, all moments will have their time stripped. function commonlyAmbiguate(inputs) { var outputs = []; var anyAmbigTime = false; var anyAmbigZone = false; var i; for (i=0; i<inputs.length; i++) { outputs.push(fc.moment(inputs[i])); anyAmbigTime = anyAmbigTime || outputs[i]._ambigTime; anyAmbigZone = anyAmbigZone || outputs[i]._ambigZone; } for (i=0; i<outputs.length; i++) { if (anyAmbigTime) { outputs[i].stripTime(); } else if (anyAmbigZone) { outputs[i].stripZone(); } } return outputs; } ;; // Single Date Formatting // ------------------------------------------------------------------------------------------------- // call this if you want Moment's original format method to be used function momentFormat(mom, formatStr) { return moment.fn.format.call(mom, formatStr); } // Formats `date` with a Moment formatting string, but allow our non-zero areas and // additional token. function formatDate(date, formatStr) { return formatDateWithChunks(date, getFormatStringChunks(formatStr)); } function formatDateWithChunks(date, chunks) { var s = ''; var i; for (i=0; i<chunks.length; i++) { s += formatDateWithChunk(date, chunks[i]); } return s; } // addition formatting tokens we want recognized var tokenOverrides = { t: function(date) { // "a" or "p" return momentFormat(date, 'a').charAt(0); }, T: function(date) { // "A" or "P" return momentFormat(date, 'A').charAt(0); } }; function formatDateWithChunk(date, chunk) { var token; var maybeStr; if (typeof chunk === 'string') { // a literal string return chunk; } else if ((token = chunk.token)) { // a token, like "YYYY" if (tokenOverrides[token]) { return tokenOverrides[token](date); // use our custom token } return momentFormat(date, token); } else if (chunk.maybe) { // a grouping of other chunks that must be non-zero maybeStr = formatDateWithChunks(date, chunk.maybe); if (maybeStr.match(/[1-9]/)) { return maybeStr; } } return ''; } // Date Range Formatting // ------------------------------------------------------------------------------------------------- // TODO: make it work with timezone offset // Using a formatting string meant for a single date, generate a range string, like // "Sep 2 - 9 2013", that intelligently inserts a separator where the dates differ. // If the dates are the same as far as the format string is concerned, just return a single // rendering of one date, without any separator. function formatRange(date1, date2, formatStr, separator, isRTL) { // Expand localized format strings, like "LL" -> "MMMM D YYYY" formatStr = date1.lang().longDateFormat(formatStr) || formatStr; // BTW, this is not important for `formatDate` because it is impossible to put custom tokens // or non-zero areas in Moment's localized format strings. separator = separator || ' - '; return formatRangeWithChunks( date1, date2, getFormatStringChunks(formatStr), separator, isRTL ); } fc.formatRange = formatRange; // expose function formatRangeWithChunks(date1, date2, chunks, separator, isRTL) { var chunkStr; // the rendering of the chunk var leftI; var leftStr = ''; var rightI; var rightStr = ''; var middleI; var middleStr1 = ''; var middleStr2 = ''; var middleStr = ''; // Start at the leftmost side of the formatting string and continue until you hit a token // that is not the same between dates. for (leftI=0; leftI<chunks.length; leftI++) { chunkStr = formatSimilarChunk(date1, date2, chunks[leftI]); if (chunkStr === false) { break; } leftStr += chunkStr; } // Similarly, start at the rightmost side of the formatting string and move left for (rightI=chunks.length-1; rightI>leftI; rightI--) { chunkStr = formatSimilarChunk(date1, date2, chunks[rightI]); if (chunkStr === false) { break; } rightStr = chunkStr + rightStr; } // The area in the middle is different for both of the dates. // Collect them distinctly so we can jam them together later. for (middleI=leftI; middleI<=rightI; middleI++) { middleStr1 += formatDateWithChunk(date1, chunks[middleI]); middleStr2 += formatDateWithChunk(date2, chunks[middleI]); } if (middleStr1 || middleStr2) { if (isRTL) { middleStr = middleStr2 + separator + middleStr1; } else { middleStr = middleStr1 + separator + middleStr2; } } return leftStr + middleStr + rightStr; } var similarUnitMap = { Y: 'year', M: 'month', D: 'day', // day of month d: 'day' // day of week }; // don't go any further than day, because we don't want to break apart times like "12:30:00" // TODO: week maybe? // Given a formatting chunk, and given that both dates are similar in the regard the // formatting chunk is concerned, format date1 against `chunk`. Otherwise, return `false`. function formatSimilarChunk(date1, date2, chunk) { var token; var unit; if (typeof chunk === 'string') { // a literal string return chunk; } else if ((token = chunk.token)) { unit = similarUnitMap[token.charAt(0)]; // are the dates the same for this unit of measurement? if (unit && date1.isSame(date2, unit)) { return momentFormat(date1, token); // would be the same if we used `date2` // BTW, don't support custom tokens } } return false; // the chunk is NOT the same for the two dates // BTW, don't support splitting on non-zero areas } // Chunking Utils // ------------------------------------------------------------------------------------------------- var formatStringChunkCache = {}; function getFormatStringChunks(formatStr) { if (formatStr in formatStringChunkCache) { return formatStringChunkCache[formatStr]; } return (formatStringChunkCache[formatStr] = chunkFormatString(formatStr)); } // Break the formatting string into an array of chunks function chunkFormatString(formatStr) { var chunks = []; var chunker = /\[([^\]]*)\]|\(([^\)]*)\)|((\w)\4*o?T?)|([^\w\[\(]+)/g; // TODO: more descrimination var match; while ((match = chunker.exec(formatStr))) { if (match[1]) { // a literal string instead [ ... ] chunks.push(match[1]); } else if (match[2]) { // non-zero formatting inside ( ... ) chunks.push({ maybe: chunkFormatString(match[2]) }); } else if (match[3]) { // a formatting token chunks.push({ token: match[3] }); } else if (match[5]) { // an unenclosed literal string chunks.push(match[5]); } } return chunks; } ;; fcViews.month = MonthView; function MonthView(element, calendar) { var t = this; // exports t.incrementDate = incrementDate; t.render = render; // imports BasicView.call(t, element, calendar, 'month'); function incrementDate(date, delta) { return date.clone().stripTime().add('months', delta).startOf('month'); } function render(date) { t.intervalStart = date.clone().stripTime().startOf('month'); t.intervalEnd = t.intervalStart.clone().add('months', 1); t.start = t.intervalStart.clone().startOf('week'); t.start = t.skipHiddenDays(t.start); t.end = t.intervalEnd.clone().add('days', (7 - t.intervalEnd.weekday()) % 7); t.end = t.skipHiddenDays(t.end, -1, true); var rowCnt = Math.ceil( // need to ceil in case there are hidden days t.end.diff(t.start, 'weeks', true) // returnfloat=true ); if (t.opt('weekMode') == 'fixed') { t.end.add('weeks', 6 - rowCnt); rowCnt = 6; } t.title = calendar.formatDate(t.intervalStart, t.opt('titleFormat')); t.renderBasic(rowCnt, t.getCellsPerWeek(), true); } } ;; fcViews.basicWeek = BasicWeekView; function BasicWeekView(element, calendar) { // TODO: do a WeekView mixin var t = this; // exports t.incrementDate = incrementDate; t.render = render; // imports BasicView.call(t, element, calendar, 'basicWeek'); function incrementDate(date, delta) { return date.clone().stripTime().add('weeks', delta).startOf('week'); } function render(date) { t.intervalStart = date.clone().stripTime().startOf('week'); t.intervalEnd = t.intervalStart.clone().add('weeks', 1); t.start = t.skipHiddenDays(t.intervalStart); t.end = t.skipHiddenDays(t.intervalEnd, -1, true); t.title = calendar.formatRange( t.start, t.end.clone().subtract(1), // make inclusive by subtracting 1 ms t.opt('titleFormat'), ' \u2014 ' // emphasized dash ); t.renderBasic(1, t.getCellsPerWeek(), false); } } ;; fcViews.basicDay = BasicDayView; function BasicDayView(element, calendar) { // TODO: make a DayView mixin var t = this; // exports t.incrementDate = incrementDate; t.render = render; // imports BasicView.call(t, element, calendar, 'basicDay'); function incrementDate(date, delta) { var out = date.clone().stripTime().add('days', delta); out = t.skipHiddenDays(out, delta < 0 ? -1 : 1); return out; } function render(date) { t.start = t.intervalStart = date.clone().stripTime(); t.end = t.intervalEnd = t.start.clone().add('days', 1); t.title = calendar.formatDate(t.start, t.opt('titleFormat')); t.renderBasic(1, 1, false); } } ;; setDefaults({ weekMode: 'fixed' }); function BasicView(element, calendar, viewName) { var t = this; // exports t.renderBasic = renderBasic; t.setHeight = setHeight; t.setWidth = setWidth; t.renderDayOverlay = renderDayOverlay; t.defaultSelectionEnd = defaultSelectionEnd; t.renderSelection = renderSelection; t.clearSelection = clearSelection; t.reportDayClick = reportDayClick; // for selection (kinda hacky) t.dragStart = dragStart; t.dragStop = dragStop; t.getHoverListener = function() { return hoverListener; }; t.colLeft = colLeft; t.colRight = colRight; t.colContentLeft = colContentLeft; t.colContentRight = colContentRight; t.getIsCellAllDay = function() { return true; }; t.allDayRow = allDayRow; t.getRowCnt = function() { return rowCnt; }; t.getColCnt = function() { return colCnt; }; t.getColWidth = function() { return colWidth; }; t.getDaySegmentContainer = function() { return daySegmentContainer; }; // imports View.call(t, element, calendar, viewName); OverlayManager.call(t); SelectionManager.call(t); BasicEventRenderer.call(t); var opt = t.opt; var trigger = t.trigger; var renderOverlay = t.renderOverlay; var clearOverlays = t.clearOverlays; var daySelectionMousedown = t.daySelectionMousedown; var cellToDate = t.cellToDate; var dateToCell = t.dateToCell; var rangeToSegments = t.rangeToSegments; var formatDate = calendar.formatDate; var calculateWeekNumber = calendar.calculateWeekNumber; // locals var table; var head; var headCells; var body; var bodyRows; var bodyCells; var bodyFirstCells; var firstRowCellInners; var firstRowCellContentInners; var daySegmentContainer; var viewWidth; var viewHeight; var colWidth; var weekNumberWidth; var rowCnt, colCnt; var showNumbers; var coordinateGrid; var hoverListener; var colPositions; var colContentPositions; var tm; var colFormat; var showWeekNumbers; /* Rendering ------------------------------------------------------------*/ disableTextSelection(element.addClass('fc-grid')); function renderBasic(_rowCnt, _colCnt, _showNumbers) { rowCnt = _rowCnt; colCnt = _colCnt; showNumbers = _showNumbers; updateOptions(); if (!body) { buildEventContainer(); } buildTable(); } function updateOptions() { tm = opt('theme') ? 'ui' : 'fc'; colFormat = opt('columnFormat'); showWeekNumbers = opt('weekNumbers'); } function buildEventContainer() { daySegmentContainer = $("<div class='fc-event-container' style='position:absolute;z-index:8;top:0;left:0'/>") .appendTo(element); } function buildTable() { var html = buildTableHTML(); if (table) { table.remove(); } table = $(html).appendTo(element); head = table.find('thead'); headCells = head.find('.fc-day-header'); body = table.find('tbody'); bodyRows = body.find('tr'); bodyCells = body.find('.fc-day'); bodyFirstCells = bodyRows.find('td:first-child'); firstRowCellInners = bodyRows.eq(0).find('.fc-day > div'); firstRowCellContentInners = bodyRows.eq(0).find('.fc-day-content > div'); markFirstLast(head.add(head.find('tr'))); // marks first+last tr/th's markFirstLast(bodyRows); // marks first+last td's bodyRows.eq(0).addClass('fc-first'); bodyRows.filter(':last').addClass('fc-last'); bodyCells.each(function(i, _cell) { var date = cellToDate( Math.floor(i / colCnt), i % colCnt ); trigger('dayRender', t, date, $(_cell)); }); dayBind(bodyCells); } /* HTML Building -----------------------------------------------------------*/ function buildTableHTML() { var html = "<table class='fc-border-separate' style='width:100%' cellspacing='0'>" + buildHeadHTML() + buildBodyHTML() + "</table>"; return html; } function buildHeadHTML() { var headerClass = tm + "-widget-header"; var html = ''; var col; var date; html += "<thead><tr>"; if (showWeekNumbers) { html += "<th class='fc-week-number " + headerClass + "'>" + htmlEscape(opt('weekNumberTitle')) + "</th>"; } for (col=0; col<colCnt; col++) { date = cellToDate(0, col); html += "<th class='fc-day-header fc-" + dayIDs[date.day()] + " " + headerClass + "'>" + htmlEscape(formatDate(date, colFormat)) + "</th>"; } html += "</tr></thead>"; return html; } function buildBodyHTML() { var contentClass = tm + "-widget-content"; var html = ''; var row; var col; var date; html += "<tbody>"; for (row=0; row<rowCnt; row++) { html += "<tr class='fc-week'>"; if (showWeekNumbers) { date = cellToDate(row, 0); html += "<td class='fc-week-number " + contentClass + "'>" + "<div>" + htmlEscape(calculateWeekNumber(date)) + "</div>" + "</td>"; } for (col=0; col<colCnt; col++) { date = cellToDate(row, col); html += buildCellHTML(date); } html += "</tr>"; } html += "</tbody>"; return html; } function buildCellHTML(date) { // date assumed to have stripped time var month = t.intervalStart.month(); var today = calendar.getNow().stripTime(); var html = ''; var contentClass = tm + "-widget-content"; var classNames = [ 'fc-day', 'fc-' + dayIDs[date.day()], contentClass ]; if (date.month() != month) { classNames.push('fc-other-month'); } if (date.isSame(today, 'day')) { classNames.push( 'fc-today', tm + '-state-highlight' ); } else if (date < today) { classNames.push('fc-past'); } else { classNames.push('fc-future'); } html += "<td" + " class='" + classNames.join(' ') + "'" + " data-date='" + date.format() + "'" + ">" + "<div>"; if (showNumbers) { html += "<div class='fc-day-number'>" + date.date() + "</div>"; } html += "<div class='fc-day-content'>" + "<div style='position:relative'>&nbsp;</div>" + "</div>" + "</div>" + "</td>"; return html; } /* Dimensions -----------------------------------------------------------*/ function setHeight(height) { viewHeight = height; var bodyHeight = Math.max(viewHeight - head.height(), 0); var rowHeight; var rowHeightLast; var cell; if (opt('weekMode') == 'variable') { rowHeight = rowHeightLast = Math.floor(bodyHeight / (rowCnt==1 ? 2 : 6)); }else{ rowHeight = Math.floor(bodyHeight / rowCnt); rowHeightLast = bodyHeight - rowHeight * (rowCnt-1); } bodyFirstCells.each(function(i, _cell) { if (i < rowCnt) { cell = $(_cell); cell.find('> div').css( 'min-height', (i==rowCnt-1 ? rowHeightLast : rowHeight) - vsides(cell) ); } }); } function setWidth(width) { viewWidth = width; colPositions.clear(); colContentPositions.clear(); weekNumberWidth = 0; if (showWeekNumbers) { weekNumberWidth = head.find('th.fc-week-number').outerWidth(); } colWidth = Math.floor((viewWidth - weekNumberWidth) / colCnt); setOuterWidth(headCells.slice(0, -1), colWidth); } /* Day clicking and binding -----------------------------------------------------------*/ function dayBind(days) { days.click(dayClick) .mousedown(daySelectionMousedown); } function dayClick(ev) { if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick var date = calendar.moment($(this).data('date')); trigger('dayClick', this, date, ev); } } /* Semi-transparent Overlay Helpers ------------------------------------------------------*/ // TODO: should be consolidated with AgendaView's methods function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive if (refreshCoordinateGrid) { coordinateGrid.build(); } var segments = rangeToSegments(overlayStart, overlayEnd); for (var i=0; i<segments.length; i++) { var segment = segments[i]; dayBind( renderCellOverlay( segment.row, segment.leftCol, segment.row, segment.rightCol ) ); } } function renderCellOverlay(row0, col0, row1, col1) { // row1,col1 is inclusive var rect = coordinateGrid.rect(row0, col0, row1, col1, element); return renderOverlay(rect, element); } /* Selection -----------------------------------------------------------------------*/ function defaultSelectionEnd(start) { return start.clone().stripTime().add('days', 1); } function renderSelection(start, end) { // end is exclusive renderDayOverlay(start, end, true); // true = rebuild every time } function clearSelection() { clearOverlays(); } function reportDayClick(date, ev) { var cell = dateToCell(date); var _element = bodyCells[cell.row*colCnt + cell.col]; trigger('dayClick', _element, date, ev); } /* External Dragging -----------------------------------------------------------------------*/ function dragStart(_dragElement, ev, ui) { hoverListener.start(function(cell) { clearOverlays(); if (cell) { var d1 = cellToDate(cell); var d2 = d1.clone().add(calendar.defaultAllDayEventDuration); renderDayOverlay(d1, d2); } }, ev); } function dragStop(_dragElement, ev, ui) { var cell = hoverListener.stop(); clearOverlays(); if (cell) { trigger( 'drop', _dragElement, cellToDate(cell), ev, ui ); } } /* Utilities --------------------------------------------------------*/ coordinateGrid = new CoordinateGrid(function(rows, cols) { var e, n, p; headCells.each(function(i, _e) { e = $(_e); n = e.offset().left; if (i) { p[1] = n; } p = [n]; cols[i] = p; }); p[1] = n + e.outerWidth(); bodyRows.each(function(i, _e) { if (i < rowCnt) { e = $(_e); n = e.offset().top; if (i) { p[1] = n; } p = [n]; rows[i] = p; } }); p[1] = n + e.outerHeight(); }); hoverListener = new HoverListener(coordinateGrid); colPositions = new HorizontalPositionCache(function(col) { return firstRowCellInners.eq(col); }); colContentPositions = new HorizontalPositionCache(function(col) { return firstRowCellContentInners.eq(col); }); function colLeft(col) { return colPositions.left(col); } function colRight(col) { return colPositions.right(col); } function colContentLeft(col) { return colContentPositions.left(col); } function colContentRight(col) { return colContentPositions.right(col); } function allDayRow(i) { return bodyRows.eq(i); } } ;; function BasicEventRenderer() { var t = this; // exports t.renderEvents = renderEvents; t.clearEvents = clearEvents; // imports DayEventRenderer.call(t); function renderEvents(events, modifiedEventId) { t.renderDayEvents(events, modifiedEventId); } function clearEvents() { t.getDaySegmentContainer().empty(); } // TODO: have this class (and AgendaEventRenderer) be responsible for creating the event container div } ;; fcViews.agendaWeek = AgendaWeekView; function AgendaWeekView(element, calendar) { // TODO: do a WeekView mixin var t = this; // exports t.incrementDate = incrementDate; t.render = render; // imports AgendaView.call(t, element, calendar, 'agendaWeek'); function incrementDate(date, delta) { return date.clone().stripTime().add('weeks', delta).startOf('week'); } function render(date) { t.intervalStart = date.clone().stripTime().startOf('week'); t.intervalEnd = t.intervalStart.clone().add('weeks', 1); t.start = t.skipHiddenDays(t.intervalStart); t.end = t.skipHiddenDays(t.intervalEnd, -1, true); t.title = calendar.formatRange( t.start, t.end.clone().subtract(1), // make inclusive by subtracting 1 ms t.opt('titleFormat'), ' \u2014 ' // emphasized dash ); t.renderAgenda(t.getCellsPerWeek()); } } ;; fcViews.agendaDay = AgendaDayView; function AgendaDayView(element, calendar) { // TODO: make a DayView mixin var t = this; // exports t.incrementDate = incrementDate; t.render = render; // imports AgendaView.call(t, element, calendar, 'agendaDay'); function incrementDate(date, delta) { var out = date.clone().stripTime().add('days', delta); out = t.skipHiddenDays(out, delta < 0 ? -1 : 1); return out; } function render(date) { t.start = t.intervalStart = date.clone().stripTime(); t.end = t.intervalEnd = t.start.clone().add('days', 1); t.title = calendar.formatDate(t.start, t.opt('titleFormat')); t.renderAgenda(1); } } ;; setDefaults({ allDaySlot: true, allDayText: 'all-day', scrollTime: '06:00:00', slotDuration: '00:30:00', axisFormat: generateAgendaAxisFormat, timeFormat: { agenda: generateAgendaTimeFormat }, dragOpacity: { agenda: .5 }, minTime: '00:00:00', maxTime: '24:00:00', slotEventOverlap: true }); function generateAgendaAxisFormat(options, langData) { return langData.longDateFormat('LT') .replace(':mm', '(:mm)') .replace(/(\Wmm)$/, '($1)') // like above, but for foreign langs .replace(/\s*a$/i, 'a'); // convert AM/PM/am/pm to lowercase. remove any spaces beforehand } function generateAgendaTimeFormat(options, langData) { return langData.longDateFormat('LT') .replace(/\s*a$/i, ''); // remove trailing AM/PM } // TODO: make it work in quirks mode (event corners, all-day height) // TODO: test liquid width, especially in IE6 function AgendaView(element, calendar, viewName) { var t = this; // exports t.renderAgenda = renderAgenda; t.setWidth = setWidth; t.setHeight = setHeight; t.afterRender = afterRender; t.computeDateTop = computeDateTop; t.getIsCellAllDay = getIsCellAllDay; t.allDayRow = function() { return allDayRow; }; // badly named t.getCoordinateGrid = function() { return coordinateGrid; }; // specifically for AgendaEventRenderer t.getHoverListener = function() { return hoverListener; }; t.colLeft = colLeft; t.colRight = colRight; t.colContentLeft = colContentLeft; t.colContentRight = colContentRight; t.getDaySegmentContainer = function() { return daySegmentContainer; }; t.getSlotSegmentContainer = function() { return slotSegmentContainer; }; t.getSlotContainer = function() { return slotContainer; }; t.getRowCnt = function() { return 1; }; t.getColCnt = function() { return colCnt; }; t.getColWidth = function() { return colWidth; }; t.getSnapHeight = function() { return snapHeight; }; t.getSnapDuration = function() { return snapDuration; }; t.getSlotHeight = function() { return slotHeight; }; t.getSlotDuration = function() { return slotDuration; }; t.getMinTime = function() { return minTime; }; t.getMaxTime = function() { return maxTime; }; t.defaultSelectionEnd = defaultSelectionEnd; t.renderDayOverlay = renderDayOverlay; t.renderSelection = renderSelection; t.clearSelection = clearSelection; t.reportDayClick = reportDayClick; // selection mousedown hack t.dragStart = dragStart; t.dragStop = dragStop; // imports View.call(t, element, calendar, viewName); OverlayManager.call(t); SelectionManager.call(t); AgendaEventRenderer.call(t); var opt = t.opt; var trigger = t.trigger; var renderOverlay = t.renderOverlay; var clearOverlays = t.clearOverlays; var reportSelection = t.reportSelection; var unselect = t.unselect; var daySelectionMousedown = t.daySelectionMousedown; var slotSegHtml = t.slotSegHtml; var cellToDate = t.cellToDate; var dateToCell = t.dateToCell; var rangeToSegments = t.rangeToSegments; var formatDate = calendar.formatDate; var calculateWeekNumber = calendar.calculateWeekNumber; // locals var dayTable; var dayHead; var dayHeadCells; var dayBody; var dayBodyCells; var dayBodyCellInners; var dayBodyCellContentInners; var dayBodyFirstCell; var dayBodyFirstCellStretcher; var slotLayer; var daySegmentContainer; var allDayTable; var allDayRow; var slotScroller; var slotContainer; var slotSegmentContainer; var slotTable; var selectionHelper; var viewWidth; var viewHeight; var axisWidth; var colWidth; var gutterWidth; var slotDuration; var slotHeight; // TODO: what if slotHeight changes? (see issue 650) var snapDuration; var snapRatio; // ratio of number of "selection" slots to normal slots. (ex: 1, 2, 4) var snapHeight; // holds the pixel hight of a "selection" slot var colCnt; var slotCnt; var coordinateGrid; var hoverListener; var colPositions; var colContentPositions; var slotTopCache = {}; var tm; var rtl; var minTime; var maxTime; var colFormat; /* Rendering -----------------------------------------------------------------------------*/ disableTextSelection(element.addClass('fc-agenda')); function renderAgenda(c) { colCnt = c; updateOptions(); if (!dayTable) { // first time rendering? buildSkeleton(); // builds day table, slot area, events containers } else { buildDayTable(); // rebuilds day table } } function updateOptions() { tm = opt('theme') ? 'ui' : 'fc'; rtl = opt('isRTL'); colFormat = opt('columnFormat'); minTime = moment.duration(opt('minTime')); maxTime = moment.duration(opt('maxTime')); slotDuration = moment.duration(opt('slotDuration')); snapDuration = opt('snapDuration'); snapDuration = snapDuration ? moment.duration(snapDuration) : slotDuration; } /* Build DOM -----------------------------------------------------------------------*/ function buildSkeleton() { var s; var headerClass = tm + "-widget-header"; var contentClass = tm + "-widget-content"; var slotTime; var slotDate; var minutes; var slotNormal = slotDuration.asMinutes() % 15 === 0; buildDayTable(); slotLayer = $("<div style='position:absolute;z-index:2;left:0;width:100%'/>") .appendTo(element); if (opt('allDaySlot')) { daySegmentContainer = $("<div class='fc-event-container' style='position:absolute;z-index:8;top:0;left:0'/>") .appendTo(slotLayer); s = "<table style='width:100%' class='fc-agenda-allday' cellspacing='0'>" + "<tr>" + "<th class='" + headerClass + " fc-agenda-axis'>" + ( opt('allDayHTML') || htmlEscape(opt('allDayText')) ) + "</th>" + "<td>" + "<div class='fc-day-content'><div style='position:relative'/></div>" + "</td>" + "<th class='" + headerClass + " fc-agenda-gutter'>&nbsp;</th>" + "</tr>" + "</table>"; allDayTable = $(s).appendTo(slotLayer); allDayRow = allDayTable.find('tr'); dayBind(allDayRow.find('td')); slotLayer.append( "<div class='fc-agenda-divider " + headerClass + "'>" + "<div class='fc-agenda-divider-inner'/>" + "</div>" ); }else{ daySegmentContainer = $([]); // in jQuery 1.4, we can just do $() } slotScroller = $("<div style='position:absolute;width:100%;overflow-x:hidden;overflow-y:auto'/>") .appendTo(slotLayer); slotContainer = $("<div style='position:relative;width:100%;overflow:hidden'/>") .appendTo(slotScroller); slotSegmentContainer = $("<div class='fc-event-container' style='position:absolute;z-index:8;top:0;left:0'/>") .appendTo(slotContainer); s = "<table class='fc-agenda-slots' style='width:100%' cellspacing='0'>" + "<tbody>"; slotTime = moment.duration(+minTime); // i wish there was .clone() for durations slotCnt = 0; while (slotTime < maxTime) { slotDate = t.start.clone().time(slotTime); // will be in UTC but that's good. to avoid DST issues minutes = slotDate.minutes(); s += "<tr class='fc-slot" + slotCnt + ' ' + (!minutes ? '' : 'fc-minor') + "'>" + "<th class='fc-agenda-axis " + headerClass + "'>" + ((!slotNormal || !minutes) ? htmlEscape(formatDate(slotDate, opt('axisFormat'))) : '&nbsp;' ) + "</th>" + "<td class='" + contentClass + "'>" + "<div style='position:relative'>&nbsp;</div>" + "</td>" + "</tr>"; slotTime.add(slotDuration); slotCnt++; } s += "</tbody>" + "</table>"; slotTable = $(s).appendTo(slotContainer); slotBind(slotTable.find('td')); } /* Build Day Table -----------------------------------------------------------------------*/ function buildDayTable() { var html = buildDayTableHTML(); if (dayTable) { dayTable.remove(); } dayTable = $(html).appendTo(element); dayHead = dayTable.find('thead'); dayHeadCells = dayHead.find('th').slice(1, -1); // exclude gutter dayBody = dayTable.find('tbody'); dayBodyCells = dayBody.find('td').slice(0, -1); // exclude gutter dayBodyCellInners = dayBodyCells.find('> div'); dayBodyCellContentInners = dayBodyCells.find('.fc-day-content > div'); dayBodyFirstCell = dayBodyCells.eq(0); dayBodyFirstCellStretcher = dayBodyCellInners.eq(0); markFirstLast(dayHead.add(dayHead.find('tr'))); markFirstLast(dayBody.add(dayBody.find('tr'))); // TODO: now that we rebuild the cells every time, we should call dayRender } function buildDayTableHTML() { var html = "<table style='width:100%' class='fc-agenda-days fc-border-separate' cellspacing='0'>" + buildDayTableHeadHTML() + buildDayTableBodyHTML() + "</table>"; return html; } function buildDayTableHeadHTML() { var headerClass = tm + "-widget-header"; var date; var html = ''; var weekText; var col; html += "<thead>" + "<tr>"; if (opt('weekNumbers')) { date = cellToDate(0, 0); weekText = calculateWeekNumber(date); if (rtl) { weekText += opt('weekNumberTitle'); } else { weekText = opt('weekNumberTitle') + weekText; } html += "<th class='fc-agenda-axis fc-week-number " + headerClass + "'>" + htmlEscape(weekText) + "</th>"; } else { html += "<th class='fc-agenda-axis " + headerClass + "'>&nbsp;</th>"; } for (col=0; col<colCnt; col++) { date = cellToDate(0, col); html += "<th class='fc-" + dayIDs[date.day()] + " fc-col" + col + ' ' + headerClass + "'>" + htmlEscape(formatDate(date, colFormat)) + "</th>"; } html += "<th class='fc-agenda-gutter " + headerClass + "'>&nbsp;</th>" + "</tr>" + "</thead>"; return html; } function buildDayTableBodyHTML() { var headerClass = tm + "-widget-header"; // TODO: make these when updateOptions() called var contentClass = tm + "-widget-content"; var date; var today = calendar.getNow().stripTime(); var col; var cellsHTML; var cellHTML; var classNames; var html = ''; html += "<tbody>" + "<tr>" + "<th class='fc-agenda-axis " + headerClass + "'>&nbsp;</th>"; cellsHTML = ''; for (col=0; col<colCnt; col++) { date = cellToDate(0, col); classNames = [ 'fc-col' + col, 'fc-' + dayIDs[date.day()], contentClass ]; if (date.isSame(today, 'day')) { classNames.push( tm + '-state-highlight', 'fc-today' ); } else if (date < today) { classNames.push('fc-past'); } else { classNames.push('fc-future'); } cellHTML = "<td class='" + classNames.join(' ') + "'>" + "<div>" + "<div class='fc-day-content'>" + "<div style='position:relative'>&nbsp;</div>" + "</div>" + "</div>" + "</td>"; cellsHTML += cellHTML; } html += cellsHTML; html += "<td class='fc-agenda-gutter " + contentClass + "'>&nbsp;</td>" + "</tr>" + "</tbody>"; return html; } // TODO: data-date on the cells /* Dimensions -----------------------------------------------------------------------*/ function setHeight(height) { if (height === undefined) { height = viewHeight; } viewHeight = height; slotTopCache = {}; var headHeight = dayBody.position().top; var allDayHeight = slotScroller.position().top; // including divider var bodyHeight = Math.min( // total body height, including borders height - headHeight, // when scrollbars slotTable.height() + allDayHeight + 1 // when no scrollbars. +1 for bottom border ); dayBodyFirstCellStretcher .height(bodyHeight - vsides(dayBodyFirstCell)); slotLayer.css('top', headHeight); slotScroller.height(bodyHeight - allDayHeight - 1); // the stylesheet guarantees that the first row has no border. // this allows .height() to work well cross-browser. var slotHeight0 = slotTable.find('tr:first').height() + 1; // +1 for bottom border var slotHeight1 = slotTable.find('tr:eq(1)').height(); // HACK: i forget why we do this, but i think a cross-browser issue slotHeight = (slotHeight0 + slotHeight1) / 2; snapRatio = slotDuration / snapDuration; snapHeight = slotHeight / snapRatio; } function setWidth(width) { viewWidth = width; colPositions.clear(); colContentPositions.clear(); var axisFirstCells = dayHead.find('th:first'); if (allDayTable) { axisFirstCells = axisFirstCells.add(allDayTable.find('th:first')); } axisFirstCells = axisFirstCells.add(slotTable.find('th:first')); axisWidth = 0; setOuterWidth( axisFirstCells .width('') .each(function(i, _cell) { axisWidth = Math.max(axisWidth, $(_cell).outerWidth()); }), axisWidth ); var gutterCells = dayTable.find('.fc-agenda-gutter'); if (allDayTable) { gutterCells = gutterCells.add(allDayTable.find('th.fc-agenda-gutter')); } var slotTableWidth = slotScroller[0].clientWidth; // needs to be done after axisWidth (for IE7) gutterWidth = slotScroller.width() - slotTableWidth; if (gutterWidth) { setOuterWidth(gutterCells, gutterWidth); gutterCells .show() .prev() .removeClass('fc-last'); }else{ gutterCells .hide() .prev() .addClass('fc-last'); } colWidth = Math.floor((slotTableWidth - axisWidth) / colCnt); setOuterWidth(dayHeadCells.slice(0, -1), colWidth); } /* Scrolling -----------------------------------------------------------------------*/ function resetScroll() { var top = computeTimeTop( moment.duration(opt('scrollTime')) ) + 1; // +1 for the border function scroll() { slotScroller.scrollTop(top); } scroll(); setTimeout(scroll, 0); // overrides any previous scroll state made by the browser } function afterRender() { // after the view has been freshly rendered and sized resetScroll(); } /* Slot/Day clicking and binding -----------------------------------------------------------------------*/ function dayBind(cells) { cells.click(slotClick) .mousedown(daySelectionMousedown); } function slotBind(cells) { cells.click(slotClick) .mousedown(slotSelectionMousedown); } function slotClick(ev) { if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick var col = Math.min(colCnt-1, Math.floor((ev.pageX - dayTable.offset().left - axisWidth) / colWidth)); var date = cellToDate(0, col); var match = this.parentNode.className.match(/fc-slot(\d+)/); // TODO: maybe use data if (match) { var slotIndex = parseInt(match[1]); date.add(minTime + slotIndex * slotDuration); date = calendar.rezoneDate(date); trigger( 'dayClick', dayBodyCells[col], date, ev ); }else{ trigger( 'dayClick', dayBodyCells[col], date, ev ); } } } /* Semi-transparent Overlay Helpers -----------------------------------------------------*/ // TODO: should be consolidated with BasicView's methods function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive if (refreshCoordinateGrid) { coordinateGrid.build(); } var segments = rangeToSegments(overlayStart, overlayEnd); for (var i=0; i<segments.length; i++) { var segment = segments[i]; dayBind( renderCellOverlay( segment.row, segment.leftCol, segment.row, segment.rightCol ) ); } } function renderCellOverlay(row0, col0, row1, col1) { // only for all-day? var rect = coordinateGrid.rect(row0, col0, row1, col1, slotLayer); return renderOverlay(rect, slotLayer); } function renderSlotOverlay(overlayStart, overlayEnd) { // normalize, because dayStart/dayEnd have stripped time+zone overlayStart = overlayStart.clone().stripZone(); overlayEnd = overlayEnd.clone().stripZone(); for (var i=0; i<colCnt; i++) { // loop through the day columns var dayStart = cellToDate(0, i); var dayEnd = dayStart.clone().add('days', 1); var stretchStart = dayStart < overlayStart ? overlayStart : dayStart; // the max of the two var stretchEnd = dayEnd < overlayEnd ? dayEnd : overlayEnd; // the min of the two if (stretchStart < stretchEnd) { var rect = coordinateGrid.rect(0, i, 0, i, slotContainer); // only use it for horizontal coords var top = computeDateTop(stretchStart, dayStart); var bottom = computeDateTop(stretchEnd, dayStart); rect.top = top; rect.height = bottom - top; slotBind( renderOverlay(rect, slotContainer) ); } } } /* Coordinate Utilities -----------------------------------------------------------------------------*/ coordinateGrid = new CoordinateGrid(function(rows, cols) { var e, n, p; dayHeadCells.each(function(i, _e) { e = $(_e); n = e.offset().left; if (i) { p[1] = n; } p = [n]; cols[i] = p; }); p[1] = n + e.outerWidth(); if (opt('allDaySlot')) { e = allDayRow; n = e.offset().top; rows[0] = [n, n+e.outerHeight()]; } var slotTableTop = slotContainer.offset().top; var slotScrollerTop = slotScroller.offset().top; var slotScrollerBottom = slotScrollerTop + slotScroller.outerHeight(); function constrain(n) { return Math.max(slotScrollerTop, Math.min(slotScrollerBottom, n)); } for (var i=0; i<slotCnt*snapRatio; i++) { // adapt slot count to increased/decreased selection slot count rows.push([ constrain(slotTableTop + snapHeight*i), constrain(slotTableTop + snapHeight*(i+1)) ]); } }); hoverListener = new HoverListener(coordinateGrid); colPositions = new HorizontalPositionCache(function(col) { return dayBodyCellInners.eq(col); }); colContentPositions = new HorizontalPositionCache(function(col) { return dayBodyCellContentInners.eq(col); }); function colLeft(col) { return colPositions.left(col); } function colContentLeft(col) { return colContentPositions.left(col); } function colRight(col) { return colPositions.right(col); } function colContentRight(col) { return colContentPositions.right(col); } function getIsCellAllDay(cell) { // TODO: remove because mom.hasTime() from realCellToDate() is better return opt('allDaySlot') && !cell.row; } function realCellToDate(cell) { // ugh "real" ... but blame it on our abuse of the "cell" system var date = cellToDate(0, cell.col); var slotIndex = cell.row; if (opt('allDaySlot')) { slotIndex--; } if (slotIndex >= 0) { date.time(moment.duration(minTime + slotIndex * slotDuration)); date = calendar.rezoneDate(date); } return date; } function computeDateTop(date, startOfDayDate) { return computeTimeTop( moment.duration( date.clone().stripZone() - startOfDayDate.clone().stripTime() ) ); } function computeTimeTop(time) { // time is a duration if (time < minTime) { return 0; } if (time >= maxTime) { return slotTable.height(); } var slots = (time - minTime) / slotDuration; var slotIndex = Math.floor(slots); var slotPartial = slots - slotIndex; var slotTop = slotTopCache[slotIndex]; // find the position of the corresponding <tr> // need to use this tecnhique because not all rows are rendered at same height sometimes. if (slotTop === undefined) { slotTop = slotTopCache[slotIndex] = slotTable.find('tr').eq(slotIndex).find('td div')[0].offsetTop; // .eq() is faster than ":eq()" selector // [0].offsetTop is faster than .position().top (do we really need this optimization?) // a better optimization would be to cache all these divs } var top = slotTop - 1 + // because first row doesn't have a top border slotPartial * slotHeight; // part-way through the row top = Math.max(top, 0); return top; } /* Selection ---------------------------------------------------------------------------------*/ function defaultSelectionEnd(start) { if (start.hasTime()) { return start.clone().add(slotDuration); } else { return start.clone().add('days', 1); } } function renderSelection(start, end) { if (start.hasTime() || end.hasTime()) { renderSlotSelection(start, end); } else if (opt('allDaySlot')) { renderDayOverlay(start, end, true); // true for refreshing coordinate grid } } function renderSlotSelection(startDate, endDate) { var helperOption = opt('selectHelper'); coordinateGrid.build(); if (helperOption) { var col = dateToCell(startDate).col; if (col >= 0 && col < colCnt) { // only works when times are on same day var rect = coordinateGrid.rect(0, col, 0, col, slotContainer); // only for horizontal coords var top = computeDateTop(startDate, startDate); var bottom = computeDateTop(endDate, startDate); if (bottom > top) { // protect against selections that are entirely before or after visible range rect.top = top; rect.height = bottom - top; rect.left += 2; rect.width -= 5; if ($.isFunction(helperOption)) { var helperRes = helperOption(startDate, endDate); if (helperRes) { rect.position = 'absolute'; selectionHelper = $(helperRes) .css(rect) .appendTo(slotContainer); } }else{ rect.isStart = true; // conside rect a "seg" now rect.isEnd = true; // selectionHelper = $(slotSegHtml( { title: '', start: startDate, end: endDate, className: ['fc-select-helper'], editable: false }, rect )); selectionHelper.css('opacity', opt('dragOpacity')); } if (selectionHelper) { slotBind(selectionHelper); slotContainer.append(selectionHelper); setOuterWidth(selectionHelper, rect.width, true); // needs to be after appended setOuterHeight(selectionHelper, rect.height, true); } } } }else{ renderSlotOverlay(startDate, endDate); } } function clearSelection() { clearOverlays(); if (selectionHelper) { selectionHelper.remove(); selectionHelper = null; } } function slotSelectionMousedown(ev) { if (ev.which == 1 && opt('selectable')) { // ev.which==1 means left mouse button unselect(ev); var dates; hoverListener.start(function(cell, origCell) { clearSelection(); if (cell && cell.col == origCell.col && !getIsCellAllDay(cell)) { var d1 = realCellToDate(origCell); var d2 = realCellToDate(cell); dates = [ d1, d1.clone().add(snapDuration), // calculate minutes depending on selection slot minutes d2, d2.clone().add(snapDuration) ].sort(dateCompare); renderSlotSelection(dates[0], dates[3]); }else{ dates = null; } }, ev); $(document).one('mouseup', function(ev) { hoverListener.stop(); if (dates) { if (+dates[0] == +dates[1]) { reportDayClick(dates[0], ev); } reportSelection(dates[0], dates[3], ev); } }); } } function reportDayClick(date, ev) { trigger('dayClick', dayBodyCells[dateToCell(date).col], date, ev); } /* External Dragging --------------------------------------------------------------------------------*/ function dragStart(_dragElement, ev, ui) { hoverListener.start(function(cell) { clearOverlays(); if (cell) { var d1 = realCellToDate(cell); var d2 = d1.clone(); if (d1.hasTime()) { d2.add(calendar.defaultTimedEventDuration); renderSlotOverlay(d1, d2); } else { d2.add(calendar.defaultAllDayEventDuration); renderDayOverlay(d1, d2); } } }, ev); } function dragStop(_dragElement, ev, ui) { var cell = hoverListener.stop(); clearOverlays(); if (cell) { trigger( 'drop', _dragElement, realCellToDate(cell), ev, ui ); } } } ;; function AgendaEventRenderer() { var t = this; // exports t.renderEvents = renderEvents; t.clearEvents = clearEvents; t.slotSegHtml = slotSegHtml; // imports DayEventRenderer.call(t); var opt = t.opt; var trigger = t.trigger; var isEventDraggable = t.isEventDraggable; var isEventResizable = t.isEventResizable; var eventElementHandlers = t.eventElementHandlers; var setHeight = t.setHeight; var getDaySegmentContainer = t.getDaySegmentContainer; var getSlotSegmentContainer = t.getSlotSegmentContainer; var getHoverListener = t.getHoverListener; var computeDateTop = t.computeDateTop; var getIsCellAllDay = t.getIsCellAllDay; var colContentLeft = t.colContentLeft; var colContentRight = t.colContentRight; var cellToDate = t.cellToDate; var getColCnt = t.getColCnt; var getColWidth = t.getColWidth; var getSnapHeight = t.getSnapHeight; var getSnapDuration = t.getSnapDuration; var getSlotHeight = t.getSlotHeight; var getSlotDuration = t.getSlotDuration; var getSlotContainer = t.getSlotContainer; var reportEventElement = t.reportEventElement; var showEvents = t.showEvents; var hideEvents = t.hideEvents; var eventDrop = t.eventDrop; var eventResize = t.eventResize; var renderDayOverlay = t.renderDayOverlay; var clearOverlays = t.clearOverlays; var renderDayEvents = t.renderDayEvents; var getMinTime = t.getMinTime; var getMaxTime = t.getMaxTime; var calendar = t.calendar; var formatDate = calendar.formatDate; var formatRange = calendar.formatRange; var getEventEnd = calendar.getEventEnd; // overrides t.draggableDayEvent = draggableDayEvent; /* Rendering ----------------------------------------------------------------------------*/ function renderEvents(events, modifiedEventId) { var i, len=events.length, dayEvents=[], slotEvents=[]; for (i=0; i<len; i++) { if (events[i].allDay) { dayEvents.push(events[i]); }else{ slotEvents.push(events[i]); } } if (opt('allDaySlot')) { renderDayEvents(dayEvents, modifiedEventId); setHeight(); // no params means set to viewHeight } renderSlotSegs(compileSlotSegs(slotEvents), modifiedEventId); } function clearEvents() { getDaySegmentContainer().empty(); getSlotSegmentContainer().empty(); } function compileSlotSegs(events) { var colCnt = getColCnt(), minTime = getMinTime(), maxTime = getMaxTime(), cellDate, i, j, seg, colSegs, segs = []; for (i=0; i<colCnt; i++) { cellDate = cellToDate(0, i); colSegs = sliceSegs( events, cellDate.clone().time(minTime), cellDate.clone().time(maxTime) ); colSegs = placeSlotSegs(colSegs); // returns a new order for (j=0; j<colSegs.length; j++) { seg = colSegs[j]; seg.col = i; segs.push(seg); } } return segs; } function sliceSegs(events, rangeStart, rangeEnd) { // normalize, because all dates will be compared w/o zones rangeStart = rangeStart.clone().stripZone(); rangeEnd = rangeEnd.clone().stripZone(); var segs = [], i, len=events.length, event, eventStart, eventEnd, segStart, segEnd, isStart, isEnd; for (i=0; i<len; i++) { event = events[i]; // get dates, make copies, then strip zone to normalize eventStart = event.start.clone().stripZone(); eventEnd = getEventEnd(event).stripZone(); if (eventEnd > rangeStart && eventStart < rangeEnd) { if (eventStart < rangeStart) { segStart = rangeStart.clone(); isStart = false; } else { segStart = eventStart; isStart = true; } if (eventEnd > rangeEnd) { segEnd = rangeEnd.clone(); isEnd = false; } else { segEnd = eventEnd; isEnd = true; } segs.push({ event: event, start: segStart, end: segEnd, isStart: isStart, isEnd: isEnd }); } } return segs.sort(compareSlotSegs); } // renders events in the 'time slots' at the bottom // TODO: when we refactor this, when user returns `false` eventRender, don't have empty space // TODO: refactor will include using pixels to detect collisions instead of dates (handy for seg cmp) function renderSlotSegs(segs, modifiedEventId) { var i, segCnt=segs.length, seg, event, top, bottom, columnLeft, columnRight, columnWidth, width, left, right, html = '', eventElements, eventElement, triggerRes, titleElement, height, slotSegmentContainer = getSlotSegmentContainer(), isRTL = opt('isRTL'); // calculate position/dimensions, create html for (i=0; i<segCnt; i++) { seg = segs[i]; event = seg.event; top = computeDateTop(seg.start, seg.start); bottom = computeDateTop(seg.end, seg.start); columnLeft = colContentLeft(seg.col); columnRight = colContentRight(seg.col); columnWidth = columnRight - columnLeft; // shave off space on right near scrollbars (2.5%) // TODO: move this to CSS somehow columnRight -= columnWidth * .025; columnWidth = columnRight - columnLeft; width = columnWidth * (seg.forwardCoord - seg.backwardCoord); if (opt('slotEventOverlap')) { // double the width while making sure resize handle is visible // (assumed to be 20px wide) width = Math.max( (width - (20/2)) * 2, width // narrow columns will want to make the segment smaller than // the natural width. don't allow it ); } if (isRTL) { right = columnRight - seg.backwardCoord * columnWidth; left = right - width; } else { left = columnLeft + seg.backwardCoord * columnWidth; right = left + width; } // make sure horizontal coordinates are in bounds left = Math.max(left, columnLeft); right = Math.min(right, columnRight); width = right - left; seg.top = top; seg.left = left; seg.outerWidth = width; seg.outerHeight = bottom - top; html += slotSegHtml(event, seg); } slotSegmentContainer[0].innerHTML = html; // faster than html() eventElements = slotSegmentContainer.children(); // retrieve elements, run through eventRender callback, bind event handlers for (i=0; i<segCnt; i++) { seg = segs[i]; event = seg.event; eventElement = $(eventElements[i]); // faster than eq() triggerRes = trigger('eventRender', event, event, eventElement); if (triggerRes === false) { eventElement.remove(); }else{ if (triggerRes && triggerRes !== true) { eventElement.remove(); eventElement = $(triggerRes) .css({ position: 'absolute', top: seg.top, left: seg.left }) .appendTo(slotSegmentContainer); } seg.element = eventElement; if (event._id === modifiedEventId) { bindSlotSeg(event, eventElement, seg); }else{ eventElement[0]._fci = i; // for lazySegBind } reportEventElement(event, eventElement); } } lazySegBind(slotSegmentContainer, segs, bindSlotSeg); // record event sides and title positions for (i=0; i<segCnt; i++) { seg = segs[i]; if ((eventElement = seg.element)) { seg.vsides = vsides(eventElement, true); seg.hsides = hsides(eventElement, true); titleElement = eventElement.find('.fc-event-title'); if (titleElement.length) { seg.contentTop = titleElement[0].offsetTop; } } } // set all positions/dimensions at once for (i=0; i<segCnt; i++) { seg = segs[i]; if ((eventElement = seg.element)) { eventElement[0].style.width = Math.max(0, seg.outerWidth - seg.hsides) + 'px'; height = Math.max(0, seg.outerHeight - seg.vsides); eventElement[0].style.height = height + 'px'; event = seg.event; if (seg.contentTop !== undefined && height - seg.contentTop < 10) { // not enough room for title, put it in the time (TODO: maybe make both display:inline instead) eventElement.find('div.fc-event-time') .text( formatDate(event.start, opt('timeFormat')) + ' - ' + event.title ); eventElement.find('div.fc-event-title') .remove(); } trigger('eventAfterRender', event, event, eventElement); } } } function slotSegHtml(event, seg) { var html = "<"; var url = event.url; var skinCss = getSkinCss(event, opt); var classes = ['fc-event', 'fc-event-vert']; if (isEventDraggable(event)) { classes.push('fc-event-draggable'); } if (seg.isStart) { classes.push('fc-event-start'); } if (seg.isEnd) { classes.push('fc-event-end'); } classes = classes.concat(event.className); if (event.source) { classes = classes.concat(event.source.className || []); } if (url) { html += "a href='" + htmlEscape(event.url) + "'"; }else{ html += "div"; } html += " class='" + classes.join(' ') + "'" + " style=" + "'" + "position:absolute;" + "top:" + seg.top + "px;" + "left:" + seg.left + "px;" + skinCss + "'" + ">" + "<div class='fc-event-inner'>" + "<div class='fc-event-time'>"; if (event.end) { html += htmlEscape(formatRange(event.start, event.end, opt('timeFormat'))); }else{ html += htmlEscape(formatDate(event.start, opt('timeFormat'))); } html += "</div>" + "<div class='fc-event-title'>" + htmlEscape(event.title || '') + "</div>" + "</div>" + "<div class='fc-event-bg'></div>"; if (seg.isEnd && isEventResizable(event)) { html += "<div class='ui-resizable-handle ui-resizable-s'>=</div>"; } html += "</" + (url ? "a" : "div") + ">"; return html; } function bindSlotSeg(event, eventElement, seg) { var timeElement = eventElement.find('div.fc-event-time'); if (isEventDraggable(event)) { draggableSlotEvent(event, eventElement, timeElement); } if (seg.isEnd && isEventResizable(event)) { resizableSlotEvent(event, eventElement, timeElement); } eventElementHandlers(event, eventElement); } /* Dragging -----------------------------------------------------------------------------------*/ // when event starts out FULL-DAY // overrides DayEventRenderer's version because it needs to account for dragging elements // to and from the slot area. function draggableDayEvent(event, eventElement, seg) { var isStart = seg.isStart; var origWidth; var revert; var allDay = true; var dayDelta; var hoverListener = getHoverListener(); var colWidth = getColWidth(); var minTime = getMinTime(); var slotDuration = getSlotDuration(); var slotHeight = getSlotHeight(); var snapDuration = getSnapDuration(); var snapHeight = getSnapHeight(); eventElement.draggable({ opacity: opt('dragOpacity', 'month'), // use whatever the month view was using revertDuration: opt('dragRevertDuration'), start: function(ev, ui) { trigger('eventDragStart', eventElement, event, ev, ui); hideEvents(event, eventElement); origWidth = eventElement.width(); hoverListener.start(function(cell, origCell) { clearOverlays(); if (cell) { revert = false; var origDate = cellToDate(0, origCell.col); var date = cellToDate(0, cell.col); dayDelta = date.diff(origDate, 'days'); if (!cell.row) { // on full-days renderDayOverlay( event.start.clone().add('days', dayDelta), getEventEnd(event).add('days', dayDelta) ); resetElement(); } else { // mouse is over bottom slots if (isStart) { if (allDay) { // convert event to temporary slot-event eventElement.width(colWidth - 10); // don't use entire width setOuterHeight(eventElement, calendar.defaultTimedEventDuration / slotDuration * slotHeight); // the default height eventElement.draggable('option', 'grid', [ colWidth, 1 ]); allDay = false; } } else { revert = true; } } revert = revert || (allDay && !dayDelta); } else { resetElement(); revert = true; } eventElement.draggable('option', 'revert', revert); }, ev, 'drag'); }, stop: function(ev, ui) { hoverListener.stop(); clearOverlays(); trigger('eventDragStop', eventElement, event, ev, ui); if (revert) { // hasn't moved or is out of bounds (draggable has already reverted) resetElement(); eventElement.css('filter', ''); // clear IE opacity side-effects showEvents(event, eventElement); } else { // changed! var eventStart = event.start.clone().add('days', dayDelta); // already assumed to have a stripped time var snapTime; var snapIndex; if (!allDay) { snapIndex = Math.round((eventElement.offset().top - getSlotContainer().offset().top) / snapHeight); // why not use ui.offset.top? snapTime = moment.duration(minTime + snapIndex * snapDuration); eventStart = calendar.rezoneDate(eventStart.clone().time(snapTime)); } eventDrop( this, // el event, eventStart, ev, ui ); } } }); function resetElement() { if (!allDay) { eventElement .width(origWidth) .height('') .draggable('option', 'grid', null); allDay = true; } } } // when event starts out IN TIMESLOTS function draggableSlotEvent(event, eventElement, timeElement) { var coordinateGrid = t.getCoordinateGrid(); var colCnt = getColCnt(); var colWidth = getColWidth(); var snapHeight = getSnapHeight(); var snapDuration = getSnapDuration(); // states var origPosition; // original position of the element, not the mouse var origCell; var isInBounds, prevIsInBounds; var isAllDay, prevIsAllDay; var colDelta, prevColDelta; var dayDelta; // derived from colDelta var snapDelta, prevSnapDelta; // the number of snaps away from the original position // newly computed var eventStart, eventEnd; eventElement.draggable({ scroll: false, grid: [ colWidth, snapHeight ], axis: colCnt==1 ? 'y' : false, opacity: opt('dragOpacity'), revertDuration: opt('dragRevertDuration'), start: function(ev, ui) { trigger('eventDragStart', eventElement, event, ev, ui); hideEvents(event, eventElement); coordinateGrid.build(); // initialize states origPosition = eventElement.position(); origCell = coordinateGrid.cell(ev.pageX, ev.pageY); isInBounds = prevIsInBounds = true; isAllDay = prevIsAllDay = getIsCellAllDay(origCell); colDelta = prevColDelta = 0; dayDelta = 0; snapDelta = prevSnapDelta = 0; eventStart = null; eventEnd = null; }, drag: function(ev, ui) { // NOTE: this `cell` value is only useful for determining in-bounds and all-day. // Bad for anything else due to the discrepancy between the mouse position and the // element position while snapping. (problem revealed in PR #55) // // PS- the problem exists for draggableDayEvent() when dragging an all-day event to a slot event. // We should overhaul the dragging system and stop relying on jQuery UI. var cell = coordinateGrid.cell(ev.pageX, ev.pageY); // update states isInBounds = !!cell; if (isInBounds) { isAllDay = getIsCellAllDay(cell); // calculate column delta colDelta = Math.round((ui.position.left - origPosition.left) / colWidth); if (colDelta != prevColDelta) { // calculate the day delta based off of the original clicked column and the column delta var origDate = cellToDate(0, origCell.col); var col = origCell.col + colDelta; col = Math.max(0, col); col = Math.min(colCnt-1, col); var date = cellToDate(0, col); dayDelta = date.diff(origDate, 'days'); } // calculate minute delta (only if over slots) if (!isAllDay) { snapDelta = Math.round((ui.position.top - origPosition.top) / snapHeight); } } // any state changes? if ( isInBounds != prevIsInBounds || isAllDay != prevIsAllDay || colDelta != prevColDelta || snapDelta != prevSnapDelta ) { // compute new dates if (isAllDay) { eventStart = event.start.clone().stripTime().add('days', dayDelta); eventEnd = eventStart.clone().add(calendar.defaultAllDayEventDuration); } else { eventStart = event.start.clone().add(snapDelta * snapDuration).add('days', dayDelta); eventEnd = getEventEnd(event).add(snapDelta * snapDuration).add('days', dayDelta); } updateUI(); // update previous states for next time prevIsInBounds = isInBounds; prevIsAllDay = isAllDay; prevColDelta = colDelta; prevSnapDelta = snapDelta; } // if out-of-bounds, revert when done, and vice versa. eventElement.draggable('option', 'revert', !isInBounds); }, stop: function(ev, ui) { clearOverlays(); trigger('eventDragStop', eventElement, event, ev, ui); if (isInBounds && (isAllDay || dayDelta || snapDelta)) { // changed! eventDrop( this, // el event, eventStart, ev, ui ); } else { // either no change or out-of-bounds (draggable has already reverted) // reset states for next time, and for updateUI() isInBounds = true; isAllDay = false; colDelta = 0; dayDelta = 0; snapDelta = 0; updateUI(); eventElement.css('filter', ''); // clear IE opacity side-effects // sometimes fast drags make event revert to wrong position, so reset. // also, if we dragged the element out of the area because of snapping, // but the *mouse* is still in bounds, we need to reset the position. eventElement.css(origPosition); showEvents(event, eventElement); } } }); function updateUI() { clearOverlays(); if (isInBounds) { if (isAllDay) { timeElement.hide(); eventElement.draggable('option', 'grid', null); // disable grid snapping renderDayOverlay(eventStart, eventEnd); } else { updateTimeText(); timeElement.css('display', ''); // show() was causing display=inline eventElement.draggable('option', 'grid', [colWidth, snapHeight]); // re-enable grid snapping } } } function updateTimeText() { var text; if (eventStart) { // must of had a state change if (event.end) { text = formatRange(eventStart, eventEnd, opt('timeFormat')); } else { text = formatDate(eventStart, opt('timeFormat')); } timeElement.text(text); } } } /* Resizing --------------------------------------------------------------------------------------*/ function resizableSlotEvent(event, eventElement, timeElement) { var snapDelta, prevSnapDelta; var snapHeight = getSnapHeight(); var snapDuration = getSnapDuration(); var eventEnd; eventElement.resizable({ handles: { s: '.ui-resizable-handle' }, grid: snapHeight, start: function(ev, ui) { snapDelta = prevSnapDelta = 0; hideEvents(event, eventElement); trigger('eventResizeStart', this, event, ev, ui); }, resize: function(ev, ui) { // don't rely on ui.size.height, doesn't take grid into account snapDelta = Math.round((Math.max(snapHeight, eventElement.height()) - ui.originalSize.height) / snapHeight); if (snapDelta != prevSnapDelta) { eventEnd = getEventEnd(event).add(snapDuration * snapDelta); var text; if (snapDelta || event.end) { text = formatRange( event.start, eventEnd, opt('timeFormat') ); } else { text = formatDate(event.start, opt('timeFormat')); } timeElement.text(text); prevSnapDelta = snapDelta; } }, stop: function(ev, ui) { trigger('eventResizeStop', this, event, ev, ui); if (snapDelta) { eventResize( this, event, eventEnd, ev, ui ); } else { showEvents(event, eventElement); // BUG: if event was really short, need to put title back in span } } }); } } /* Agenda Event Segment Utilities -----------------------------------------------------------------------------*/ // Sets the seg.backwardCoord and seg.forwardCoord on each segment and returns a new // list in the order they should be placed into the DOM (an implicit z-index). function placeSlotSegs(segs) { var levels = buildSlotSegLevels(segs); var level0 = levels[0]; var i; computeForwardSlotSegs(levels); if (level0) { for (i=0; i<level0.length; i++) { computeSlotSegPressures(level0[i]); } for (i=0; i<level0.length; i++) { computeSlotSegCoords(level0[i], 0, 0); } } return flattenSlotSegLevels(levels); } // Builds an array of segments "levels". The first level will be the leftmost tier of segments // if the calendar is left-to-right, or the rightmost if the calendar is right-to-left. function buildSlotSegLevels(segs) { var levels = []; var i, seg; var j; for (i=0; i<segs.length; i++) { seg = segs[i]; // go through all the levels and stop on the first level where there are no collisions for (j=0; j<levels.length; j++) { if (!computeSlotSegCollisions(seg, levels[j]).length) { break; } } (levels[j] || (levels[j] = [])).push(seg); } return levels; } // For every segment, figure out the other segments that are in subsequent // levels that also occupy the same vertical space. Accumulate in seg.forwardSegs function computeForwardSlotSegs(levels) { var i, level; var j, seg; var k; for (i=0; i<levels.length; i++) { level = levels[i]; for (j=0; j<level.length; j++) { seg = level[j]; seg.forwardSegs = []; for (k=i+1; k<levels.length; k++) { computeSlotSegCollisions(seg, levels[k], seg.forwardSegs); } } } } // Figure out which path forward (via seg.forwardSegs) results in the longest path until // the furthest edge is reached. The number of segments in this path will be seg.forwardPressure function computeSlotSegPressures(seg) { var forwardSegs = seg.forwardSegs; var forwardPressure = 0; var i, forwardSeg; if (seg.forwardPressure === undefined) { // not already computed for (i=0; i<forwardSegs.length; i++) { forwardSeg = forwardSegs[i]; // figure out the child's maximum forward path computeSlotSegPressures(forwardSeg); // either use the existing maximum, or use the child's forward pressure // plus one (for the forwardSeg itself) forwardPressure = Math.max( forwardPressure, 1 + forwardSeg.forwardPressure ); } seg.forwardPressure = forwardPressure; } } // Calculate seg.forwardCoord and seg.backwardCoord for the segment, where both values range // from 0 to 1. If the calendar is left-to-right, the seg.backwardCoord maps to "left" and // seg.forwardCoord maps to "right" (via percentage). Vice-versa if the calendar is right-to-left. // // The segment might be part of a "series", which means consecutive segments with the same pressure // who's width is unknown until an edge has been hit. `seriesBackwardPressure` is the number of // segments behind this one in the current series, and `seriesBackwardCoord` is the starting // coordinate of the first segment in the series. function computeSlotSegCoords(seg, seriesBackwardPressure, seriesBackwardCoord) { var forwardSegs = seg.forwardSegs; var i; if (seg.forwardCoord === undefined) { // not already computed if (!forwardSegs.length) { // if there are no forward segments, this segment should butt up against the edge seg.forwardCoord = 1; } else { // sort highest pressure first forwardSegs.sort(compareForwardSlotSegs); // this segment's forwardCoord will be calculated from the backwardCoord of the // highest-pressure forward segment. computeSlotSegCoords(forwardSegs[0], seriesBackwardPressure + 1, seriesBackwardCoord); seg.forwardCoord = forwardSegs[0].backwardCoord; } // calculate the backwardCoord from the forwardCoord. consider the series seg.backwardCoord = seg.forwardCoord - (seg.forwardCoord - seriesBackwardCoord) / // available width for series (seriesBackwardPressure + 1); // # of segments in the series // use this segment's coordinates to computed the coordinates of the less-pressurized // forward segments for (i=0; i<forwardSegs.length; i++) { computeSlotSegCoords(forwardSegs[i], 0, seg.forwardCoord); } } } // Outputs a flat array of segments, from lowest to highest level function flattenSlotSegLevels(levels) { var segs = []; var i, level; var j; for (i=0; i<levels.length; i++) { level = levels[i]; for (j=0; j<level.length; j++) { segs.push(level[j]); } } return segs; } // Find all the segments in `otherSegs` that vertically collide with `seg`. // Append into an optionally-supplied `results` array and return. function computeSlotSegCollisions(seg, otherSegs, results) { results = results || []; for (var i=0; i<otherSegs.length; i++) { if (isSlotSegCollision(seg, otherSegs[i])) { results.push(otherSegs[i]); } } return results; } // Do these segments occupy the same vertical space? function isSlotSegCollision(seg1, seg2) { return seg1.end > seg2.start && seg1.start < seg2.end; } // A cmp function for determining which forward segment to rely on more when computing coordinates. function compareForwardSlotSegs(seg1, seg2) { // put higher-pressure first return seg2.forwardPressure - seg1.forwardPressure || // put segments that are closer to initial edge first (and favor ones with no coords yet) (seg1.backwardCoord || 0) - (seg2.backwardCoord || 0) || // do normal sorting... compareSlotSegs(seg1, seg2); } // A cmp function for determining which segment should be closer to the initial edge // (the left edge on a left-to-right calendar). function compareSlotSegs(seg1, seg2) { return seg1.start - seg2.start || // earlier start time goes first (seg2.end - seg2.start) - (seg1.end - seg1.start) || // tie? longer-duration goes first (seg1.event.title || '').localeCompare(seg2.event.title); // tie? alphabetically by title } ;; function View(element, calendar, viewName) { var t = this; // exports t.element = element; t.calendar = calendar; t.name = viewName; t.opt = opt; t.trigger = trigger; t.isEventDraggable = isEventDraggable; t.isEventResizable = isEventResizable; t.clearEventData = clearEventData; t.reportEventElement = reportEventElement; t.triggerEventDestroy = triggerEventDestroy; t.eventElementHandlers = eventElementHandlers; t.showEvents = showEvents; t.hideEvents = hideEvents; t.eventDrop = eventDrop; t.eventResize = eventResize; // t.start, t.end // moments with ambiguous-time // t.intervalStart, t.intervalEnd // moments with ambiguous-time // imports var reportEventChange = calendar.reportEventChange; // locals var eventElementsByID = {}; // eventID mapped to array of jQuery elements var eventElementCouples = []; // array of objects, { event, element } // TODO: unify with segment system var options = calendar.options; var nextDayThreshold = moment.duration(options.nextDayThreshold); function opt(name, viewNameOverride) { var v = options[name]; if ($.isPlainObject(v) && !isForcedAtomicOption(name)) { return smartProperty(v, viewNameOverride || viewName); } return v; } function trigger(name, thisObj) { return calendar.trigger.apply( calendar, [name, thisObj || t].concat(Array.prototype.slice.call(arguments, 2), [t]) ); } /* Event Editable Boolean Calculations ------------------------------------------------------------------------------*/ function isEventDraggable(event) { var source = event.source || {}; return firstDefined( event.startEditable, source.startEditable, opt('eventStartEditable'), event.editable, source.editable, opt('editable') ); } function isEventResizable(event) { // but also need to make sure the seg.isEnd == true var source = event.source || {}; return firstDefined( event.durationEditable, source.durationEditable, opt('eventDurationEditable'), event.editable, source.editable, opt('editable') ); } /* Event Data ------------------------------------------------------------------------------*/ function clearEventData() { eventElementsByID = {}; eventElementCouples = []; } /* Event Elements ------------------------------------------------------------------------------*/ // report when view creates an element for an event function reportEventElement(event, element) { eventElementCouples.push({ event: event, element: element }); if (eventElementsByID[event._id]) { eventElementsByID[event._id].push(element); }else{ eventElementsByID[event._id] = [element]; } } function triggerEventDestroy() { $.each(eventElementCouples, function(i, couple) { t.trigger('eventDestroy', couple.event, couple.event, couple.element); }); } // attaches eventClick, eventMouseover, eventMouseout function eventElementHandlers(event, eventElement) { eventElement .click(function(ev) { if (!eventElement.hasClass('ui-draggable-dragging') && !eventElement.hasClass('ui-resizable-resizing')) { return trigger('eventClick', this, event, ev); } }) .hover( function(ev) { trigger('eventMouseover', this, event, ev); }, function(ev) { trigger('eventMouseout', this, event, ev); } ); // TODO: don't fire eventMouseover/eventMouseout *while* dragging is occuring (on subject element) // TODO: same for resizing } function showEvents(event, exceptElement) { eachEventElement(event, exceptElement, 'show'); } function hideEvents(event, exceptElement) { eachEventElement(event, exceptElement, 'hide'); } function eachEventElement(event, exceptElement, funcName) { // NOTE: there may be multiple events per ID (repeating events) // and multiple segments per event var elements = eventElementsByID[event._id], i, len = elements.length; for (i=0; i<len; i++) { if (!exceptElement || elements[i][0] != exceptElement[0]) { elements[i][funcName](); } } } /* Event Modification Reporting ---------------------------------------------------------------------------------*/ function eventDrop(el, event, newStart, ev, ui) { var undoMutation = calendar.mutateEvent(event, newStart, null); trigger( 'eventDrop', el, event, function() { undoMutation(); reportEventChange(event._id); }, ev, ui ); reportEventChange(event._id); } function eventResize(el, event, newEnd, ev, ui) { var undoMutation = calendar.mutateEvent(event, null, newEnd); trigger( 'eventResize', el, event, function() { undoMutation(); reportEventChange(event._id); }, ev, ui ); reportEventChange(event._id); } // ==================================================================================================== // Utilities for day "cells" // ==================================================================================================== // The "basic" views are completely made up of day cells. // The "agenda" views have day cells at the top "all day" slot. // This was the obvious common place to put these utilities, but they should be abstracted out into // a more meaningful class (like DayEventRenderer). // ==================================================================================================== // For determining how a given "cell" translates into a "date": // // 1. Convert the "cell" (row and column) into a "cell offset" (the # of the cell, cronologically from the first). // Keep in mind that column indices are inverted with isRTL. This is taken into account. // // 2. Convert the "cell offset" to a "day offset" (the # of days since the first visible day in the view). // // 3. Convert the "day offset" into a "date" (a Moment). // // The reverse transformation happens when transforming a date into a cell. // exports t.isHiddenDay = isHiddenDay; t.skipHiddenDays = skipHiddenDays; t.getCellsPerWeek = getCellsPerWeek; t.dateToCell = dateToCell; t.dateToDayOffset = dateToDayOffset; t.dayOffsetToCellOffset = dayOffsetToCellOffset; t.cellOffsetToCell = cellOffsetToCell; t.cellToDate = cellToDate; t.cellToCellOffset = cellToCellOffset; t.cellOffsetToDayOffset = cellOffsetToDayOffset; t.dayOffsetToDate = dayOffsetToDate; t.rangeToSegments = rangeToSegments; // internals var hiddenDays = opt('hiddenDays') || []; // array of day-of-week indices that are hidden var isHiddenDayHash = []; // is the day-of-week hidden? (hash with day-of-week-index -> bool) var cellsPerWeek; var dayToCellMap = []; // hash from dayIndex -> cellIndex, for one week var cellToDayMap = []; // hash from cellIndex -> dayIndex, for one week var isRTL = opt('isRTL'); // initialize important internal variables (function() { if (opt('weekends') === false) { hiddenDays.push(0, 6); // 0=sunday, 6=saturday } // Loop through a hypothetical week and determine which // days-of-week are hidden. Record in both hashes (one is the reverse of the other). for (var dayIndex=0, cellIndex=0; dayIndex<7; dayIndex++) { dayToCellMap[dayIndex] = cellIndex; isHiddenDayHash[dayIndex] = $.inArray(dayIndex, hiddenDays) != -1; if (!isHiddenDayHash[dayIndex]) { cellToDayMap[cellIndex] = dayIndex; cellIndex++; } } cellsPerWeek = cellIndex; if (!cellsPerWeek) { throw 'invalid hiddenDays'; // all days were hidden? bad. } })(); // Is the current day hidden? // `day` is a day-of-week index (0-6), or a Moment function isHiddenDay(day) { if (moment.isMoment(day)) { day = day.day(); } return isHiddenDayHash[day]; } function getCellsPerWeek() { return cellsPerWeek; } // Incrementing the current day until it is no longer a hidden day, returning a copy. // If the initial value of `date` is not a hidden day, don't do anything. // Pass `isExclusive` as `true` if you are dealing with an end date. // `inc` defaults to `1` (increment one day forward each time) function skipHiddenDays(date, inc, isExclusive) { var out = date.clone(); inc = inc || 1; while ( isHiddenDayHash[(out.day() + (isExclusive ? inc : 0) + 7) % 7] ) { out.add('days', inc); } return out; } // // TRANSFORMATIONS: cell -> cell offset -> day offset -> date // // cell -> date (combines all transformations) // Possible arguments: // - row, col // - { row:#, col: # } function cellToDate() { var cellOffset = cellToCellOffset.apply(null, arguments); var dayOffset = cellOffsetToDayOffset(cellOffset); var date = dayOffsetToDate(dayOffset); return date; } // cell -> cell offset // Possible arguments: // - row, col // - { row:#, col:# } function cellToCellOffset(row, col) { var colCnt = t.getColCnt(); // rtl variables. wish we could pre-populate these. but where? var dis = isRTL ? -1 : 1; var dit = isRTL ? colCnt - 1 : 0; if (typeof row == 'object') { col = row.col; row = row.row; } var cellOffset = row * colCnt + (col * dis + dit); // column, adjusted for RTL (dis & dit) return cellOffset; } // cell offset -> day offset function cellOffsetToDayOffset(cellOffset) { var day0 = t.start.day(); // first date's day of week cellOffset += dayToCellMap[day0]; // normlize cellOffset to beginning-of-week return Math.floor(cellOffset / cellsPerWeek) * 7 + // # of days from full weeks cellToDayMap[ // # of days from partial last week (cellOffset % cellsPerWeek + cellsPerWeek) % cellsPerWeek // crazy math to handle negative cellOffsets ] - day0; // adjustment for beginning-of-week normalization } // day offset -> date function dayOffsetToDate(dayOffset) { return t.start.clone().add('days', dayOffset); } // // TRANSFORMATIONS: date -> day offset -> cell offset -> cell // // date -> cell (combines all transformations) function dateToCell(date) { var dayOffset = dateToDayOffset(date); var cellOffset = dayOffsetToCellOffset(dayOffset); var cell = cellOffsetToCell(cellOffset); return cell; } // date -> day offset function dateToDayOffset(date) { return date.clone().stripTime().diff(t.start, 'days'); } // day offset -> cell offset function dayOffsetToCellOffset(dayOffset) { var day0 = t.start.day(); // first date's day of week dayOffset += day0; // normalize dayOffset to beginning-of-week return Math.floor(dayOffset / 7) * cellsPerWeek + // # of cells from full weeks dayToCellMap[ // # of cells from partial last week (dayOffset % 7 + 7) % 7 // crazy math to handle negative dayOffsets ] - dayToCellMap[day0]; // adjustment for beginning-of-week normalization } // cell offset -> cell (object with row & col keys) function cellOffsetToCell(cellOffset) { var colCnt = t.getColCnt(); // rtl variables. wish we could pre-populate these. but where? var dis = isRTL ? -1 : 1; var dit = isRTL ? colCnt - 1 : 0; var row = Math.floor(cellOffset / colCnt); var col = ((cellOffset % colCnt + colCnt) % colCnt) * dis + dit; // column, adjusted for RTL (dis & dit) return { row: row, col: col }; } // // Converts a date range into an array of segment objects. // "Segments" are horizontal stretches of time, sliced up by row. // A segment object has the following properties: // - row // - cols // - isStart // - isEnd // function rangeToSegments(start, end) { var rowCnt = t.getRowCnt(); var colCnt = t.getColCnt(); var segments = []; // array of segments to return // day offset for given date range var rangeDayOffsetStart = dateToDayOffset(start); var rangeDayOffsetEnd = dateToDayOffset(end); // an exclusive value var endTimeMS = +end.time(); if (endTimeMS && endTimeMS >= nextDayThreshold) { rangeDayOffsetEnd++; } rangeDayOffsetEnd = Math.max(rangeDayOffsetEnd, rangeDayOffsetStart + 1); // first and last cell offset for the given date range // "last" implies inclusivity var rangeCellOffsetFirst = dayOffsetToCellOffset(rangeDayOffsetStart); var rangeCellOffsetLast = dayOffsetToCellOffset(rangeDayOffsetEnd) - 1; // loop through all the rows in the view for (var row=0; row<rowCnt; row++) { // first and last cell offset for the row var rowCellOffsetFirst = row * colCnt; var rowCellOffsetLast = rowCellOffsetFirst + colCnt - 1; // get the segment's cell offsets by constraining the range's cell offsets to the bounds of the row var segmentCellOffsetFirst = Math.max(rangeCellOffsetFirst, rowCellOffsetFirst); var segmentCellOffsetLast = Math.min(rangeCellOffsetLast, rowCellOffsetLast); // make sure segment's offsets are valid and in view if (segmentCellOffsetFirst <= segmentCellOffsetLast) { // translate to cells var segmentCellFirst = cellOffsetToCell(segmentCellOffsetFirst); var segmentCellLast = cellOffsetToCell(segmentCellOffsetLast); // view might be RTL, so order by leftmost column var cols = [ segmentCellFirst.col, segmentCellLast.col ].sort(); // Determine if segment's first/last cell is the beginning/end of the date range. // We need to compare "day offset" because "cell offsets" are often ambiguous and // can translate to multiple days, and an edge case reveals itself when we the // range's first cell is hidden (we don't want isStart to be true). var isStart = cellOffsetToDayOffset(segmentCellOffsetFirst) == rangeDayOffsetStart; var isEnd = cellOffsetToDayOffset(segmentCellOffsetLast) + 1 == rangeDayOffsetEnd; // +1 for comparing exclusively segments.push({ row: row, leftCol: cols[0], rightCol: cols[1], isStart: isStart, isEnd: isEnd }); } } return segments; } } ;; function DayEventRenderer() { var t = this; // exports t.renderDayEvents = renderDayEvents; t.draggableDayEvent = draggableDayEvent; // made public so that subclasses can override t.resizableDayEvent = resizableDayEvent; // " // imports var opt = t.opt; var trigger = t.trigger; var isEventDraggable = t.isEventDraggable; var isEventResizable = t.isEventResizable; var reportEventElement = t.reportEventElement; var eventElementHandlers = t.eventElementHandlers; var showEvents = t.showEvents; var hideEvents = t.hideEvents; var eventDrop = t.eventDrop; var eventResize = t.eventResize; var getRowCnt = t.getRowCnt; var getColCnt = t.getColCnt; var allDayRow = t.allDayRow; // TODO: rename var colLeft = t.colLeft; var colRight = t.colRight; var colContentLeft = t.colContentLeft; var colContentRight = t.colContentRight; var getDaySegmentContainer = t.getDaySegmentContainer; var renderDayOverlay = t.renderDayOverlay; var clearOverlays = t.clearOverlays; var clearSelection = t.clearSelection; var getHoverListener = t.getHoverListener; var rangeToSegments = t.rangeToSegments; var cellToDate = t.cellToDate; var cellToCellOffset = t.cellToCellOffset; var cellOffsetToDayOffset = t.cellOffsetToDayOffset; var dateToDayOffset = t.dateToDayOffset; var dayOffsetToCellOffset = t.dayOffsetToCellOffset; var calendar = t.calendar; var getEventEnd = calendar.getEventEnd; var formatDate = calendar.formatDate; // Render `events` onto the calendar, attach mouse event handlers, and call the `eventAfterRender` callback for each. // Mouse event will be lazily applied, except if the event has an ID of `modifiedEventId`. // Can only be called when the event container is empty (because it wipes out all innerHTML). function renderDayEvents(events, modifiedEventId) { // do the actual rendering. Receive the intermediate "segment" data structures. var segments = _renderDayEvents( events, false, // don't append event elements true // set the heights of the rows ); // report the elements to the View, for general drag/resize utilities segmentElementEach(segments, function(segment, element) { reportEventElement(segment.event, element); }); // attach mouse handlers attachHandlers(segments, modifiedEventId); // call `eventAfterRender` callback for each event segmentElementEach(segments, function(segment, element) { trigger('eventAfterRender', segment.event, segment.event, element); }); } // Render an event on the calendar, but don't report them anywhere, and don't attach mouse handlers. // Append this event element to the event container, which might already be populated with events. // If an event's segment will have row equal to `adjustRow`, then explicitly set its top coordinate to `adjustTop`. // This hack is used to maintain continuity when user is manually resizing an event. // Returns an array of DOM elements for the event. function renderTempDayEvent(event, adjustRow, adjustTop) { // actually render the event. `true` for appending element to container. // Recieve the intermediate "segment" data structures. var segments = _renderDayEvents( [ event ], true, // append event elements false // don't set the heights of the rows ); var elements = []; // Adjust certain elements' top coordinates segmentElementEach(segments, function(segment, element) { if (segment.row === adjustRow) { element.css('top', adjustTop); } elements.push(element[0]); // accumulate DOM nodes }); return elements; } // Render events onto the calendar. Only responsible for the VISUAL aspect. // Not responsible for attaching handlers or calling callbacks. // Set `doAppend` to `true` for rendering elements without clearing the existing container. // Set `doRowHeights` to allow setting the height of each row, to compensate for vertical event overflow. function _renderDayEvents(events, doAppend, doRowHeights) { // where the DOM nodes will eventually end up var finalContainer = getDaySegmentContainer(); // the container where the initial HTML will be rendered. // If `doAppend`==true, uses a temporary container. var renderContainer = doAppend ? $("<div/>") : finalContainer; var segments = buildSegments(events); var html; var elements; // calculate the desired `left` and `width` properties on each segment object calculateHorizontals(segments); // build the HTML string. relies on `left` property html = buildHTML(segments); // render the HTML. innerHTML is considerably faster than jQuery's .html() renderContainer[0].innerHTML = html; // retrieve the individual elements elements = renderContainer.children(); // if we were appending, and thus using a temporary container, // re-attach elements to the real container. if (doAppend) { finalContainer.append(elements); } // assigns each element to `segment.event`, after filtering them through user callbacks resolveElements(segments, elements); // Calculate the left and right padding+margin for each element. // We need this for setting each element's desired outer width, because of the W3C box model. // It's important we do this in a separate pass from acually setting the width on the DOM elements // because alternating reading/writing dimensions causes reflow for every iteration. segmentElementEach(segments, function(segment, element) { segment.hsides = hsides(element, true); // include margins = `true` }); // Set the width of each element segmentElementEach(segments, function(segment, element) { element.width( Math.max(0, segment.outerWidth - segment.hsides) ); }); // Grab each element's outerHeight (setVerticals uses this). // To get an accurate reading, it's important to have each element's width explicitly set already. segmentElementEach(segments, function(segment, element) { segment.outerHeight = element.outerHeight(true); // include margins = `true` }); // Set the top coordinate on each element (requires segment.outerHeight) setVerticals(segments, doRowHeights); return segments; } // Generate an array of "segments" for all events. function buildSegments(events) { var segments = []; for (var i=0; i<events.length; i++) { var eventSegments = buildSegmentsForEvent(events[i]); segments.push.apply(segments, eventSegments); // append an array to an array } return segments; } // Generate an array of segments for a single event. // A "segment" is the same data structure that View.rangeToSegments produces, // with the addition of the `event` property being set to reference the original event. function buildSegmentsForEvent(event) { var segments = rangeToSegments(event.start, getEventEnd(event)); for (var i=0; i<segments.length; i++) { segments[i].event = event; } return segments; } // Sets the `left` and `outerWidth` property of each segment. // These values are the desired dimensions for the eventual DOM elements. function calculateHorizontals(segments) { var isRTL = opt('isRTL'); for (var i=0; i<segments.length; i++) { var segment = segments[i]; // Determine functions used for calulating the elements left/right coordinates, // depending on whether the view is RTL or not. // NOTE: // colLeft/colRight returns the coordinate butting up the edge of the cell. // colContentLeft/colContentRight is indented a little bit from the edge. var leftFunc = (isRTL ? segment.isEnd : segment.isStart) ? colContentLeft : colLeft; var rightFunc = (isRTL ? segment.isStart : segment.isEnd) ? colContentRight : colRight; var left = leftFunc(segment.leftCol); var right = rightFunc(segment.rightCol); segment.left = left; segment.outerWidth = right - left; } } // Build a concatenated HTML string for an array of segments function buildHTML(segments) { var html = ''; for (var i=0; i<segments.length; i++) { html += buildHTMLForSegment(segments[i]); } return html; } // Build an HTML string for a single segment. // Relies on the following properties: // - `segment.event` (from `buildSegmentsForEvent`) // - `segment.left` (from `calculateHorizontals`) function buildHTMLForSegment(segment) { var html = ''; var isRTL = opt('isRTL'); var event = segment.event; var url = event.url; // generate the list of CSS classNames var classNames = [ 'fc-event', 'fc-event-hori' ]; if (isEventDraggable(event)) { classNames.push('fc-event-draggable'); } if (segment.isStart) { classNames.push('fc-event-start'); } if (segment.isEnd) { classNames.push('fc-event-end'); } // use the event's configured classNames // guaranteed to be an array via `buildEvent` classNames = classNames.concat(event.className); if (event.source) { // use the event's source's classNames, if specified classNames = classNames.concat(event.source.className || []); } // generate a semicolon delimited CSS string for any of the "skin" properties // of the event object (`backgroundColor`, `borderColor` and such) var skinCss = getSkinCss(event, opt); if (url) { html += "<a href='" + htmlEscape(url) + "'"; }else{ html += "<div"; } html += " class='" + classNames.join(' ') + "'" + " style=" + "'" + "position:absolute;" + "left:" + segment.left + "px;" + skinCss + "'" + ">" + "<div class='fc-event-inner'>"; if (!event.allDay && segment.isStart) { html += "<span class='fc-event-time'>" + htmlEscape( formatDate(event.start, opt('timeFormat')) ) + "</span>"; } html += "<span class='fc-event-title'>" + htmlEscape(event.title || '') + "</span>" + "</div>"; if (event.allDay && segment.isEnd && isEventResizable(event)) { html += "<div class='ui-resizable-handle ui-resizable-" + (isRTL ? 'w' : 'e') + "'>" + "&nbsp;&nbsp;&nbsp;" + // makes hit area a lot better for IE6/7 "</div>"; } html += "</" + (url ? "a" : "div") + ">"; // TODO: // When these elements are initially rendered, they will be briefly visibile on the screen, // even though their widths/heights are not set. // SOLUTION: initially set them as visibility:hidden ? return html; } // Associate each segment (an object) with an element (a jQuery object), // by setting each `segment.element`. // Run each element through the `eventRender` filter, which allows developers to // modify an existing element, supply a new one, or cancel rendering. function resolveElements(segments, elements) { for (var i=0; i<segments.length; i++) { var segment = segments[i]; var event = segment.event; var element = elements.eq(i); // call the trigger with the original element var triggerRes = trigger('eventRender', event, event, element); if (triggerRes === false) { // if `false`, remove the event from the DOM and don't assign it to `segment.event` element.remove(); } else { if (triggerRes && triggerRes !== true) { // the trigger returned a new element, but not `true` (which means keep the existing element) // re-assign the important CSS dimension properties that were already assigned in `buildHTMLForSegment` triggerRes = $(triggerRes) .css({ position: 'absolute', left: segment.left }); element.replaceWith(triggerRes); element = triggerRes; } segment.element = element; } } } /* Top-coordinate Methods -------------------------------------------------------------------------------------------------*/ // Sets the "top" CSS property for each element. // If `doRowHeights` is `true`, also sets each row's first cell to an explicit height, // so that if elements vertically overflow, the cell expands vertically to compensate. function setVerticals(segments, doRowHeights) { var rowContentHeights = calculateVerticals(segments); // also sets segment.top var rowContentElements = getRowContentElements(); // returns 1 inner div per row var rowContentTops = []; var i; // Set each row's height by setting height of first inner div if (doRowHeights) { for (i=0; i<rowContentElements.length; i++) { rowContentElements[i].height(rowContentHeights[i]); } } // Get each row's top, relative to the views's origin. // Important to do this after setting each row's height. for (i=0; i<rowContentElements.length; i++) { rowContentTops.push( rowContentElements[i].position().top ); } // Set each segment element's CSS "top" property. // Each segment object has a "top" property, which is relative to the row's top, but... segmentElementEach(segments, function(segment, element) { element.css( 'top', rowContentTops[segment.row] + segment.top // ...now, relative to views's origin ); }); } // Calculate the "top" coordinate for each segment, relative to the "top" of the row. // Also, return an array that contains the "content" height for each row // (the height displaced by the vertically stacked events in the row). // Requires segments to have their `outerHeight` property already set. function calculateVerticals(segments) { var rowCnt = getRowCnt(); var colCnt = getColCnt(); var rowContentHeights = []; // content height for each row var segmentRows = buildSegmentRows(segments); // an array of segment arrays, one for each row var colI; for (var rowI=0; rowI<rowCnt; rowI++) { var segmentRow = segmentRows[rowI]; // an array of running total heights for each column. // initialize with all zeros. var colHeights = []; for (colI=0; colI<colCnt; colI++) { colHeights.push(0); } // loop through every segment for (var segmentI=0; segmentI<segmentRow.length; segmentI++) { var segment = segmentRow[segmentI]; // find the segment's top coordinate by looking at the max height // of all the columns the segment will be in. segment.top = arrayMax( colHeights.slice( segment.leftCol, segment.rightCol + 1 // make exclusive for slice ) ); // adjust the columns to account for the segment's height for (colI=segment.leftCol; colI<=segment.rightCol; colI++) { colHeights[colI] = segment.top + segment.outerHeight; } } // the tallest column in the row should be the "content height" rowContentHeights.push(arrayMax(colHeights)); } return rowContentHeights; } // Build an array of segment arrays, each representing the segments that will // be in a row of the grid, sorted by which event should be closest to the top. function buildSegmentRows(segments) { var rowCnt = getRowCnt(); var segmentRows = []; var segmentI; var segment; var rowI; // group segments by row for (segmentI=0; segmentI<segments.length; segmentI++) { segment = segments[segmentI]; rowI = segment.row; if (segment.element) { // was rendered? if (segmentRows[rowI]) { // already other segments. append to array segmentRows[rowI].push(segment); } else { // first segment in row. create new array segmentRows[rowI] = [ segment ]; } } } // sort each row for (rowI=0; rowI<rowCnt; rowI++) { segmentRows[rowI] = sortSegmentRow( segmentRows[rowI] || [] // guarantee an array, even if no segments ); } return segmentRows; } // Sort an array of segments according to which segment should appear closest to the top function sortSegmentRow(segments) { var sortedSegments = []; // build the subrow array var subrows = buildSegmentSubrows(segments); // flatten it for (var i=0; i<subrows.length; i++) { sortedSegments.push.apply(sortedSegments, subrows[i]); // append an array to an array } return sortedSegments; } // Take an array of segments, which are all assumed to be in the same row, // and sort into subrows. function buildSegmentSubrows(segments) { // Give preference to elements with certain criteria, so they have // a chance to be closer to the top. segments.sort(compareDaySegments); var subrows = []; for (var i=0; i<segments.length; i++) { var segment = segments[i]; // loop through subrows, starting with the topmost, until the segment // doesn't collide with other segments. for (var j=0; j<subrows.length; j++) { if (!isDaySegmentCollision(segment, subrows[j])) { break; } } // `j` now holds the desired subrow index if (subrows[j]) { subrows[j].push(segment); } else { subrows[j] = [ segment ]; } } return subrows; } // Return an array of jQuery objects for the placeholder content containers of each row. // The content containers don't actually contain anything, but their dimensions should match // the events that are overlaid on top. function getRowContentElements() { var i; var rowCnt = getRowCnt(); var rowDivs = []; for (i=0; i<rowCnt; i++) { rowDivs[i] = allDayRow(i) .find('div.fc-day-content > div'); } return rowDivs; } /* Mouse Handlers ---------------------------------------------------------------------------------------------------*/ // TODO: better documentation! function attachHandlers(segments, modifiedEventId) { var segmentContainer = getDaySegmentContainer(); segmentElementEach(segments, function(segment, element, i) { var event = segment.event; if (event._id === modifiedEventId) { bindDaySeg(event, element, segment); }else{ element[0]._fci = i; // for lazySegBind } }); lazySegBind(segmentContainer, segments, bindDaySeg); } function bindDaySeg(event, eventElement, segment) { if (isEventDraggable(event)) { t.draggableDayEvent(event, eventElement, segment); // use `t` so subclasses can override } if ( event.allDay && segment.isEnd && // only allow resizing on the final segment for an event isEventResizable(event) ) { t.resizableDayEvent(event, eventElement, segment); // use `t` so subclasses can override } // attach all other handlers. // needs to be after, because resizableDayEvent might stopImmediatePropagation on click eventElementHandlers(event, eventElement); } function draggableDayEvent(event, eventElement) { var hoverListener = getHoverListener(); var dayDelta; var eventStart; eventElement.draggable({ delay: 50, opacity: opt('dragOpacity'), revertDuration: opt('dragRevertDuration'), start: function(ev, ui) { trigger('eventDragStart', eventElement, event, ev, ui); hideEvents(event, eventElement); hoverListener.start(function(cell, origCell, rowDelta, colDelta) { eventElement.draggable('option', 'revert', !cell || !rowDelta && !colDelta); clearOverlays(); if (cell) { var origCellDate = cellToDate(origCell); var cellDate = cellToDate(cell); dayDelta = cellDate.diff(origCellDate, 'days'); eventStart = event.start.clone().add('days', dayDelta); renderDayOverlay( eventStart, getEventEnd(event).add('days', dayDelta) ); } else { dayDelta = 0; } }, ev, 'drag'); }, stop: function(ev, ui) { hoverListener.stop(); clearOverlays(); trigger('eventDragStop', eventElement, event, ev, ui); if (dayDelta) { eventDrop( this, // el event, eventStart, ev, ui ); } else { eventElement.css('filter', ''); // clear IE opacity side-effects showEvents(event, eventElement); } } }); } function resizableDayEvent(event, element, segment) { var isRTL = opt('isRTL'); var direction = isRTL ? 'w' : 'e'; var handle = element.find('.ui-resizable-' + direction); // TODO: stop using this class because we aren't using jqui for this var isResizing = false; // TODO: look into using jquery-ui mouse widget for this stuff disableTextSelection(element); // prevent native <a> selection for IE element .mousedown(function(ev) { // prevent native <a> selection for others ev.preventDefault(); }) .click(function(ev) { if (isResizing) { ev.preventDefault(); // prevent link from being visited (only method that worked in IE6) ev.stopImmediatePropagation(); // prevent fullcalendar eventClick handler from being called // (eventElementHandlers needs to be bound after resizableDayEvent) } }); handle.mousedown(function(ev) { if (ev.which != 1) { return; // needs to be left mouse button } isResizing = true; var hoverListener = getHoverListener(); var elementTop = element.css('top'); var dayDelta; var eventEnd; var helpers; var eventCopy = $.extend({}, event); var minCellOffset = dayOffsetToCellOffset(dateToDayOffset(event.start)); clearSelection(); $('body') .css('cursor', direction + '-resize') .one('mouseup', mouseup); trigger('eventResizeStart', this, event, ev); hoverListener.start(function(cell, origCell) { if (cell) { var origCellOffset = cellToCellOffset(origCell); var cellOffset = cellToCellOffset(cell); // don't let resizing move earlier than start date cell cellOffset = Math.max(cellOffset, minCellOffset); dayDelta = cellOffsetToDayOffset(cellOffset) - cellOffsetToDayOffset(origCellOffset); eventEnd = getEventEnd(event).add('days', dayDelta); // assumed to already have a stripped time if (dayDelta) { eventCopy.end = eventEnd; var oldHelpers = helpers; helpers = renderTempDayEvent(eventCopy, segment.row, elementTop); helpers = $(helpers); // turn array into a jQuery object helpers.find('*').css('cursor', direction + '-resize'); if (oldHelpers) { oldHelpers.remove(); } hideEvents(event); } else { if (helpers) { showEvents(event); helpers.remove(); helpers = null; } } clearOverlays(); renderDayOverlay( // coordinate grid already rebuilt with hoverListener.start() event.start, eventEnd // TODO: instead of calling renderDayOverlay() with dates, // call _renderDayOverlay (or whatever) with cell offsets. ); } }, ev); function mouseup(ev) { trigger('eventResizeStop', this, event, ev); $('body').css('cursor', ''); hoverListener.stop(); clearOverlays(); if (dayDelta) { eventResize( this, // el event, eventEnd, ev ); // event redraw will clear helpers } // otherwise, the drag handler already restored the old events setTimeout(function() { // make this happen after the element's click event isResizing = false; },0); } }); } } /* Generalized Segment Utilities -------------------------------------------------------------------------------------------------*/ function isDaySegmentCollision(segment, otherSegments) { for (var i=0; i<otherSegments.length; i++) { var otherSegment = otherSegments[i]; if ( otherSegment.leftCol <= segment.rightCol && otherSegment.rightCol >= segment.leftCol ) { return true; } } return false; } function segmentElementEach(segments, callback) { // TODO: use in AgendaView? for (var i=0; i<segments.length; i++) { var segment = segments[i]; var element = segment.element; if (element) { callback(segment, element, i); } } } // A cmp function for determining which segments should appear higher up function compareDaySegments(a, b) { return (b.rightCol - b.leftCol) - (a.rightCol - a.leftCol) || // put wider events first b.event.allDay - a.event.allDay || // if tie, put all-day events first (booleans cast to 0/1) a.event.start - b.event.start || // if a tie, sort by event start date (a.event.title || '').localeCompare(b.event.title); // if a tie, sort by event title } ;; //BUG: unselect needs to be triggered when events are dragged+dropped function SelectionManager() { var t = this; // exports t.select = select; t.unselect = unselect; t.reportSelection = reportSelection; t.daySelectionMousedown = daySelectionMousedown; // imports var calendar = t.calendar; var opt = t.opt; var trigger = t.trigger; var defaultSelectionEnd = t.defaultSelectionEnd; var renderSelection = t.renderSelection; var clearSelection = t.clearSelection; // locals var selected = false; // unselectAuto if (opt('selectable') && opt('unselectAuto')) { // TODO: unbind on destroy $(document).mousedown(function(ev) { var ignore = opt('unselectCancel'); if (ignore) { if ($(ev.target).parents(ignore).length) { // could be optimized to stop after first match return; } } unselect(ev); }); } function select(start, end) { unselect(); start = calendar.moment(start); if (end) { end = calendar.moment(end); } else { end = defaultSelectionEnd(start); } renderSelection(start, end); reportSelection(start, end); } function unselect(ev) { if (selected) { selected = false; clearSelection(); trigger('unselect', null, ev); } } function reportSelection(start, end, ev) { selected = true; trigger('select', null, start, end, ev); } function daySelectionMousedown(ev) { // not really a generic manager method, oh well var cellToDate = t.cellToDate; var getIsCellAllDay = t.getIsCellAllDay; var hoverListener = t.getHoverListener(); var reportDayClick = t.reportDayClick; // this is hacky and sort of weird if (ev.which == 1 && opt('selectable')) { // which==1 means left mouse button unselect(ev); var dates; hoverListener.start(function(cell, origCell) { // TODO: maybe put cellToDate/getIsCellAllDay info in cell clearSelection(); if (cell && getIsCellAllDay(cell)) { dates = [ cellToDate(origCell), cellToDate(cell) ].sort(dateCompare); renderSelection( dates[0], dates[1].clone().add('days', 1) // make exclusive ); }else{ dates = null; } }, ev); $(document).one('mouseup', function(ev) { hoverListener.stop(); if (dates) { if (+dates[0] == +dates[1]) { reportDayClick(dates[0], ev); } reportSelection( dates[0], dates[1].clone().add('days', 1), // make exclusive ev ); } }); } } } ;; function OverlayManager() { var t = this; // exports t.renderOverlay = renderOverlay; t.clearOverlays = clearOverlays; // locals var usedOverlays = []; var unusedOverlays = []; function renderOverlay(rect, parent) { var e = unusedOverlays.shift(); if (!e) { e = $("<div class='fc-cell-overlay' style='position:absolute;z-index:3'/>"); } if (e[0].parentNode != parent[0]) { e.appendTo(parent); } usedOverlays.push(e.css(rect).show()); return e; } function clearOverlays() { var e; while ((e = usedOverlays.shift())) { unusedOverlays.push(e.hide().unbind()); } } } ;; function CoordinateGrid(buildFunc) { var t = this; var rows; var cols; t.build = function() { rows = []; cols = []; buildFunc(rows, cols); }; t.cell = function(x, y) { var rowCnt = rows.length; var colCnt = cols.length; var i, r=-1, c=-1; for (i=0; i<rowCnt; i++) { if (y >= rows[i][0] && y < rows[i][1]) { r = i; break; } } for (i=0; i<colCnt; i++) { if (x >= cols[i][0] && x < cols[i][1]) { c = i; break; } } return (r>=0 && c>=0) ? { row: r, col: c } : null; }; t.rect = function(row0, col0, row1, col1, originElement) { // row1,col1 is inclusive var origin = originElement.offset(); return { top: rows[row0][0] - origin.top, left: cols[col0][0] - origin.left, width: cols[col1][1] - cols[col0][0], height: rows[row1][1] - rows[row0][0] }; }; } ;; function HoverListener(coordinateGrid) { var t = this; var bindType; var change; var firstCell; var cell; t.start = function(_change, ev, _bindType) { change = _change; firstCell = cell = null; coordinateGrid.build(); mouse(ev); bindType = _bindType || 'mousemove'; $(document).bind(bindType, mouse); }; function mouse(ev) { _fixUIEvent(ev); // see below var newCell = coordinateGrid.cell(ev.pageX, ev.pageY); if ( Boolean(newCell) !== Boolean(cell) || newCell && (newCell.row != cell.row || newCell.col != cell.col) ) { if (newCell) { if (!firstCell) { firstCell = newCell; } change(newCell, firstCell, newCell.row-firstCell.row, newCell.col-firstCell.col); }else{ change(newCell, firstCell); } cell = newCell; } } t.stop = function() { $(document).unbind(bindType, mouse); return cell; }; } // this fix was only necessary for jQuery UI 1.8.16 (and jQuery 1.7 or 1.7.1) // upgrading to jQuery UI 1.8.17 (and using either jQuery 1.7 or 1.7.1) fixed the problem // but keep this in here for 1.8.16 users // and maybe remove it down the line function _fixUIEvent(event) { // for issue 1168 if (event.pageX === undefined) { event.pageX = event.originalEvent.pageX; event.pageY = event.originalEvent.pageY; } } ;; function HorizontalPositionCache(getElement) { var t = this, elements = {}, lefts = {}, rights = {}; function e(i) { return (elements[i] = (elements[i] || getElement(i))); } t.left = function(i) { return (lefts[i] = (lefts[i] === undefined ? e(i).position().left : lefts[i])); }; t.right = function(i) { return (rights[i] = (rights[i] === undefined ? t.left(i) + e(i).width() : rights[i])); }; t.clear = function() { elements = {}; lefts = {}; rights = {}; }; } ;; });
JavaScript
/* * File: TableTools.js * Version: 2.1.4 * Description: Tools and buttons for DataTables * Author: Allan Jardine (www.sprymedia.co.uk) * Language: Javascript * License: GPL v2 or BSD 3 point style * Project: DataTables * * Copyright 2009-2012 Allan Jardine, all rights reserved. * * This source file is free software, under either the GPL v2 license or a * BSD style license, available at: * http://datatables.net/license_gpl2 * http://datatables.net/license_bsd */ /* Global scope for TableTools */ var TableTools; (function($, window, document) { /** * TableTools provides flexible buttons and other tools for a DataTables enhanced table * @class TableTools * @constructor * @param {Object} oDT DataTables instance * @param {Object} oOpts TableTools options * @param {String} oOpts.sSwfPath ZeroClipboard SWF path * @param {String} oOpts.sRowSelect Row selection options - 'none', 'single' or 'multi' * @param {Function} oOpts.fnPreRowSelect Callback function just prior to row selection * @param {Function} oOpts.fnRowSelected Callback function just after row selection * @param {Function} oOpts.fnRowDeselected Callback function when row is deselected * @param {Array} oOpts.aButtons List of buttons to be used */ TableTools = function( oDT, oOpts ) { /* Santiy check that we are a new instance */ if ( ! this instanceof TableTools ) { alert( "Warning: TableTools must be initialised with the keyword 'new'" ); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public class variables * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * @namespace Settings object which contains customisable information for TableTools instance */ this.s = { /** * Store 'this' so the instance can be retrieved from the settings object * @property that * @type object * @default this */ "that": this, /** * DataTables settings objects * @property dt * @type object * @default <i>From the oDT init option</i> */ "dt": oDT.fnSettings(), /** * @namespace Print specific information */ "print": { /** * DataTables draw 'start' point before the printing display was shown * @property saveStart * @type int * @default -1 */ "saveStart": -1, /** * DataTables draw 'length' point before the printing display was shown * @property saveLength * @type int * @default -1 */ "saveLength": -1, /** * Page scrolling point before the printing display was shown so it can be restored * @property saveScroll * @type int * @default -1 */ "saveScroll": -1, /** * Wrapped function to end the print display (to maintain scope) * @property funcEnd * @type Function * @default function () {} */ "funcEnd": function () {} }, /** * A unique ID is assigned to each button in each instance * @property buttonCounter * @type int * @default 0 */ "buttonCounter": 0, /** * @namespace Select rows specific information */ "select": { /** * Select type - can be 'none', 'single' or 'multi' * @property type * @type string * @default "" */ "type": "", /** * Array of nodes which are currently selected * @property selected * @type array * @default [] */ "selected": [], /** * Function to run before the selection can take place. Will cancel the select if the * function returns false * @property preRowSelect * @type Function * @default null */ "preRowSelect": null, /** * Function to run when a row is selected * @property postSelected * @type Function * @default null */ "postSelected": null, /** * Function to run when a row is deselected * @property postDeselected * @type Function * @default null */ "postDeselected": null, /** * Indicate if all rows are selected (needed for server-side processing) * @property all * @type boolean * @default false */ "all": false, /** * Class name to add to selected TR nodes * @property selectedClass * @type String * @default "" */ "selectedClass": "" }, /** * Store of the user input customisation object * @property custom * @type object * @default {} */ "custom": {}, /** * SWF movie path * @property swfPath * @type string * @default "" */ "swfPath": "", /** * Default button set * @property buttonSet * @type array * @default [] */ "buttonSet": [], /** * When there is more than one TableTools instance for a DataTable, there must be a * master which controls events (row selection etc) * @property master * @type boolean * @default false */ "master": false, /** * Tag names that are used for creating collections and buttons * @namesapce */ "tags": {} }; /** * @namespace Common and useful DOM elements for the class instance */ this.dom = { /** * DIV element that is create and all TableTools buttons (and their children) put into * @property container * @type node * @default null */ "container": null, /** * The table node to which TableTools will be applied * @property table * @type node * @default null */ "table": null, /** * @namespace Nodes used for the print display */ "print": { /** * Nodes which have been removed from the display by setting them to display none * @property hidden * @type array * @default [] */ "hidden": [], /** * The information display saying telling the user about the print display * @property message * @type node * @default null */ "message": null }, /** * @namespace Nodes used for a collection display. This contains the currently used collection */ "collection": { /** * The div wrapper containing the buttons in the collection (i.e. the menu) * @property collection * @type node * @default null */ "collection": null, /** * Background display to provide focus and capture events * @property background * @type node * @default null */ "background": null } }; /** * @namespace Name space for the classes that this TableTools instance will use * @extends TableTools.classes */ this.classes = $.extend( true, {}, TableTools.classes ); if ( this.s.dt.bJUI ) { $.extend( true, this.classes, TableTools.classes_themeroller ); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public class methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Retreieve the settings object from an instance * @method fnSettings * @returns {object} TableTools settings object */ this.fnSettings = function () { return this.s; }; /* Constructor logic */ if ( typeof oOpts == 'undefined' ) { oOpts = {}; } this._fnConstruct( oOpts ); return this; }; TableTools.prototype = { /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Retreieve the settings object from an instance * @returns {array} List of TR nodes which are currently selected * @param {boolean} [filtered=false] Get only selected rows which are * available given the filtering applied to the table. By default * this is false - i.e. all rows, regardless of filtering are selected. */ "fnGetSelected": function ( filtered ) { var out = [], data = this.s.dt.aoData, displayed = this.s.dt.aiDisplay, i, iLen; if ( filtered ) { // Only consider filtered rows for ( i=0, iLen=displayed.length ; i<iLen ; i++ ) { if ( data[ displayed[i] ]._DTTT_selected ) { out.push( data[ displayed[i] ].nTr ); } } } else { // Use all rows for ( i=0, iLen=data.length ; i<iLen ; i++ ) { if ( data[i]._DTTT_selected ) { out.push( data[i].nTr ); } } } return out; }, /** * Get the data source objects/arrays from DataTables for the selected rows (same as * fnGetSelected followed by fnGetData on each row from the table) * @returns {array} Data from the TR nodes which are currently selected */ "fnGetSelectedData": function () { var out = []; var data=this.s.dt.aoData; var i, iLen; for ( i=0, iLen=data.length ; i<iLen ; i++ ) { if ( data[i]._DTTT_selected ) { out.push( this.s.dt.oInstance.fnGetData(i) ); } } return out; }, /** * Check to see if a current row is selected or not * @param {Node} n TR node to check if it is currently selected or not * @returns {Boolean} true if select, false otherwise */ "fnIsSelected": function ( n ) { var pos = this.s.dt.oInstance.fnGetPosition( n ); return (this.s.dt.aoData[pos]._DTTT_selected===true) ? true : false; }, /** * Select all rows in the table * @param {boolean} [filtered=false] Select only rows which are available * given the filtering applied to the table. By default this is false - * i.e. all rows, regardless of filtering are selected. */ "fnSelectAll": function ( filtered ) { var s = this._fnGetMasterSettings(); this._fnRowSelect( (filtered === true) ? s.dt.aiDisplay : s.dt.aoData ); }, /** * Deselect all rows in the table * @param {boolean} [filtered=false] Deselect only rows which are available * given the filtering applied to the table. By default this is false - * i.e. all rows, regardless of filtering are deselected. */ "fnSelectNone": function ( filtered ) { var s = this._fnGetMasterSettings(); this._fnRowDeselect( this.fnGetSelected(filtered) ); }, /** * Select row(s) * @param {node|object|array} n The row(s) to select. Can be a single DOM * TR node, an array of TR nodes or a jQuery object. */ "fnSelect": function ( n ) { if ( this.s.select.type == "single" ) { this.fnSelectNone(); this._fnRowSelect( n ); } else if ( this.s.select.type == "multi" ) { this._fnRowSelect( n ); } }, /** * Deselect row(s) * @param {node|object|array} n The row(s) to deselect. Can be a single DOM * TR node, an array of TR nodes or a jQuery object. */ "fnDeselect": function ( n ) { this._fnRowDeselect( n ); }, /** * Get the title of the document - useful for file names. The title is retrieved from either * the configuration object's 'title' parameter, or the HTML document title * @param {Object} oConfig Button configuration object * @returns {String} Button title */ "fnGetTitle": function( oConfig ) { var sTitle = ""; if ( typeof oConfig.sTitle != 'undefined' && oConfig.sTitle !== "" ) { sTitle = oConfig.sTitle; } else { var anTitle = document.getElementsByTagName('title'); if ( anTitle.length > 0 ) { sTitle = anTitle[0].innerHTML; } } /* Strip characters which the OS will object to - checking for UTF8 support in the scripting * engine */ if ( "\u00A1".toString().length < 4 ) { return sTitle.replace(/[^a-zA-Z0-9_\u00A1-\uFFFF\.,\-_ !\(\)]/g, ""); } else { return sTitle.replace(/[^a-zA-Z0-9_\.,\-_ !\(\)]/g, ""); } }, /** * Calculate a unity array with the column width by proportion for a set of columns to be * included for a button. This is particularly useful for PDF creation, where we can use the * column widths calculated by the browser to size the columns in the PDF. * @param {Object} oConfig Button configuration object * @returns {Array} Unity array of column ratios */ "fnCalcColRatios": function ( oConfig ) { var aoCols = this.s.dt.aoColumns, aColumnsInc = this._fnColumnTargets( oConfig.mColumns ), aColWidths = [], iWidth = 0, iTotal = 0, i, iLen; for ( i=0, iLen=aColumnsInc.length ; i<iLen ; i++ ) { if ( aColumnsInc[i] ) { iWidth = aoCols[i].nTh.offsetWidth; iTotal += iWidth; aColWidths.push( iWidth ); } } for ( i=0, iLen=aColWidths.length ; i<iLen ; i++ ) { aColWidths[i] = aColWidths[i] / iTotal; } return aColWidths.join('\t'); }, /** * Get the information contained in a table as a string * @param {Object} oConfig Button configuration object * @returns {String} Table data as a string */ "fnGetTableData": function ( oConfig ) { /* In future this could be used to get data from a plain HTML source as well as DataTables */ if ( this.s.dt ) { return this._fnGetDataTablesData( oConfig ); } }, /** * Pass text to a flash button instance, which will be used on the button's click handler * @param {Object} clip Flash button object * @param {String} text Text to set */ "fnSetText": function ( clip, text ) { this._fnFlashSetText( clip, text ); }, /** * Resize the flash elements of the buttons attached to this TableTools instance - this is * useful for when initialising TableTools when it is hidden (display:none) since sizes can't * be calculated at that time. */ "fnResizeButtons": function () { for ( var cli in ZeroClipboard_TableTools.clients ) { if ( cli ) { var client = ZeroClipboard_TableTools.clients[cli]; if ( typeof client.domElement != 'undefined' && client.domElement.parentNode ) { client.positionElement(); } } } }, /** * Check to see if any of the ZeroClipboard client's attached need to be resized */ "fnResizeRequired": function () { for ( var cli in ZeroClipboard_TableTools.clients ) { if ( cli ) { var client = ZeroClipboard_TableTools.clients[cli]; if ( typeof client.domElement != 'undefined' && client.domElement.parentNode == this.dom.container && client.sized === false ) { return true; } } } return false; }, /** * Programmatically enable or disable the print view * @param {boolean} [bView=true] Show the print view if true or not given. If false, then * terminate the print view and return to normal. * @param {object} [oConfig={}] Configuration for the print view * @param {boolean} [oConfig.bShowAll=false] Show all rows in the table if true * @param {string} [oConfig.sInfo] Information message, displayed as an overlay to the * user to let them know what the print view is. * @param {string} [oConfig.sMessage] HTML string to show at the top of the document - will * be included in the printed document. */ "fnPrint": function ( bView, oConfig ) { if ( oConfig === undefined ) { oConfig = {}; } if ( bView === undefined || bView ) { this._fnPrintStart( oConfig ); } else { this._fnPrintEnd(); } }, /** * Show a message to the end user which is nicely styled * @param {string} message The HTML string to show to the user * @param {int} time The duration the message is to be shown on screen for (mS) */ "fnInfo": function ( message, time ) { var nInfo = document.createElement( "div" ); nInfo.className = this.classes.print.info; nInfo.innerHTML = message; document.body.appendChild( nInfo ); setTimeout( function() { $(nInfo).fadeOut( "normal", function() { document.body.removeChild( nInfo ); } ); }, time ); }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Private methods (they are of course public in JS, but recommended as private) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Constructor logic * @method _fnConstruct * @param {Object} oOpts Same as TableTools constructor * @returns void * @private */ "_fnConstruct": function ( oOpts ) { var that = this; this._fnCustomiseSettings( oOpts ); /* Container element */ this.dom.container = document.createElement( this.s.tags.container ); this.dom.container.className = this.classes.container; /* Row selection config */ if ( this.s.select.type != 'none' ) { this._fnRowSelectConfig(); } /* Buttons */ this._fnButtonDefinations( this.s.buttonSet, this.dom.container ); /* Destructor - need to wipe the DOM for IE's garbage collector */ this.s.dt.aoDestroyCallback.push( { "sName": "TableTools", "fn": function () { that.dom.container.innerHTML = ""; } } ); }, /** * Take the user defined settings and the default settings and combine them. * @method _fnCustomiseSettings * @param {Object} oOpts Same as TableTools constructor * @returns void * @private */ "_fnCustomiseSettings": function ( oOpts ) { /* Is this the master control instance or not? */ if ( typeof this.s.dt._TableToolsInit == 'undefined' ) { this.s.master = true; this.s.dt._TableToolsInit = true; } /* We can use the table node from comparisons to group controls */ this.dom.table = this.s.dt.nTable; /* Clone the defaults and then the user options */ this.s.custom = $.extend( {}, TableTools.DEFAULTS, oOpts ); /* Flash file location */ this.s.swfPath = this.s.custom.sSwfPath; if ( typeof ZeroClipboard_TableTools != 'undefined' ) { ZeroClipboard_TableTools.moviePath = this.s.swfPath; } /* Table row selecting */ this.s.select.type = this.s.custom.sRowSelect; this.s.select.preRowSelect = this.s.custom.fnPreRowSelect; this.s.select.postSelected = this.s.custom.fnRowSelected; this.s.select.postDeselected = this.s.custom.fnRowDeselected; // Backwards compatibility - allow the user to specify a custom class in the initialiser if ( this.s.custom.sSelectedClass ) { this.classes.select.row = this.s.custom.sSelectedClass; } this.s.tags = this.s.custom.oTags; /* Button set */ this.s.buttonSet = this.s.custom.aButtons; }, /** * Take the user input arrays and expand them to be fully defined, and then add them to a given * DOM element * @method _fnButtonDefinations * @param {array} buttonSet Set of user defined buttons * @param {node} wrapper Node to add the created buttons to * @returns void * @private */ "_fnButtonDefinations": function ( buttonSet, wrapper ) { var buttonDef; for ( var i=0, iLen=buttonSet.length ; i<iLen ; i++ ) { if ( typeof buttonSet[i] == "string" ) { if ( typeof TableTools.BUTTONS[ buttonSet[i] ] == 'undefined' ) { alert( "TableTools: Warning - unknown button type: "+buttonSet[i] ); continue; } buttonDef = $.extend( {}, TableTools.BUTTONS[ buttonSet[i] ], true ); } else { if ( typeof TableTools.BUTTONS[ buttonSet[i].sExtends ] == 'undefined' ) { alert( "TableTools: Warning - unknown button type: "+buttonSet[i].sExtends ); continue; } var o = $.extend( {}, TableTools.BUTTONS[ buttonSet[i].sExtends ], true ); buttonDef = $.extend( o, buttonSet[i], true ); } wrapper.appendChild( this._fnCreateButton( buttonDef, $(wrapper).hasClass(this.classes.collection.container) ) ); } }, /** * Create and configure a TableTools button * @method _fnCreateButton * @param {Object} oConfig Button configuration object * @returns {Node} Button element * @private */ "_fnCreateButton": function ( oConfig, bCollectionButton ) { var nButton = this._fnButtonBase( oConfig, bCollectionButton ); if ( oConfig.sAction.match(/flash/) ) { this._fnFlashConfig( nButton, oConfig ); } else if ( oConfig.sAction == "text" ) { this._fnTextConfig( nButton, oConfig ); } else if ( oConfig.sAction == "div" ) { this._fnTextConfig( nButton, oConfig ); } else if ( oConfig.sAction == "collection" ) { this._fnTextConfig( nButton, oConfig ); this._fnCollectionConfig( nButton, oConfig ); } return nButton; }, /** * Create the DOM needed for the button and apply some base properties. All buttons start here * @method _fnButtonBase * @param {o} oConfig Button configuration object * @returns {Node} DIV element for the button * @private */ "_fnButtonBase": function ( o, bCollectionButton ) { var sTag, sLiner, sClass; if ( bCollectionButton ) { sTag = o.sTag !== "default" ? o.sTag : this.s.tags.collection.button; sLiner = o.sLinerTag !== "default" ? o.sLiner : this.s.tags.collection.liner; sClass = this.classes.collection.buttons.normal; } else { sTag = o.sTag !== "default" ? o.sTag : this.s.tags.button; sLiner = o.sLinerTag !== "default" ? o.sLiner : this.s.tags.liner; sClass = this.classes.buttons.normal; } var nButton = document.createElement( sTag ), nSpan = document.createElement( sLiner ), masterS = this._fnGetMasterSettings(); nButton.className = sClass+" "+o.sButtonClass; nButton.setAttribute('id', "ToolTables_"+this.s.dt.sInstance+"_"+masterS.buttonCounter ); nButton.appendChild( nSpan ); nSpan.innerHTML = o.sButtonText; masterS.buttonCounter++; return nButton; }, /** * Get the settings object for the master instance. When more than one TableTools instance is * assigned to a DataTable, only one of them can be the 'master' (for the select rows). As such, * we will typically want to interact with that master for global properties. * @method _fnGetMasterSettings * @returns {Object} TableTools settings object * @private */ "_fnGetMasterSettings": function () { if ( this.s.master ) { return this.s; } else { /* Look for the master which has the same DT as this one */ var instances = TableTools._aInstances; for ( var i=0, iLen=instances.length ; i<iLen ; i++ ) { if ( this.dom.table == instances[i].s.dt.nTable ) { return instances[i].s; } } } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Button collection functions */ /** * Create a collection button, when activated will present a drop down list of other buttons * @param {Node} nButton Button to use for the collection activation * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnCollectionConfig": function ( nButton, oConfig ) { var nHidden = document.createElement( this.s.tags.collection.container ); nHidden.style.display = "none"; nHidden.className = this.classes.collection.container; oConfig._collection = nHidden; document.body.appendChild( nHidden ); this._fnButtonDefinations( oConfig.aButtons, nHidden ); }, /** * Show a button collection * @param {Node} nButton Button to use for the collection * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnCollectionShow": function ( nButton, oConfig ) { var that = this, oPos = $(nButton).offset(), nHidden = oConfig._collection, iDivX = oPos.left, iDivY = oPos.top + $(nButton).outerHeight(), iWinHeight = $(window).height(), iDocHeight = $(document).height(), iWinWidth = $(window).width(), iDocWidth = $(document).width(); nHidden.style.position = "absolute"; nHidden.style.left = iDivX+"px"; nHidden.style.top = iDivY+"px"; nHidden.style.display = "block"; $(nHidden).css('opacity',0); var nBackground = document.createElement('div'); nBackground.style.position = "absolute"; nBackground.style.left = "0px"; nBackground.style.top = "0px"; nBackground.style.height = ((iWinHeight>iDocHeight)? iWinHeight : iDocHeight) +"px"; nBackground.style.width = ((iWinWidth>iDocWidth)? iWinWidth : iDocWidth) +"px"; nBackground.className = this.classes.collection.background; $(nBackground).css('opacity',0); document.body.appendChild( nBackground ); document.body.appendChild( nHidden ); /* Visual corrections to try and keep the collection visible */ var iDivWidth = $(nHidden).outerWidth(); var iDivHeight = $(nHidden).outerHeight(); if ( iDivX + iDivWidth > iDocWidth ) { nHidden.style.left = (iDocWidth-iDivWidth)+"px"; } if ( iDivY + iDivHeight > iDocHeight ) { nHidden.style.top = (iDivY-iDivHeight-$(nButton).outerHeight())+"px"; } this.dom.collection.collection = nHidden; this.dom.collection.background = nBackground; /* This results in a very small delay for the end user but it allows the animation to be * much smoother. If you don't want the animation, then the setTimeout can be removed */ setTimeout( function () { $(nHidden).animate({"opacity": 1}, 500); $(nBackground).animate({"opacity": 0.25}, 500); }, 10 ); /* Resize the buttons to the Flash contents fit */ this.fnResizeButtons(); /* Event handler to remove the collection display */ $(nBackground).click( function () { that._fnCollectionHide.call( that, null, null ); } ); }, /** * Hide a button collection * @param {Node} nButton Button to use for the collection * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnCollectionHide": function ( nButton, oConfig ) { if ( oConfig !== null && oConfig.sExtends == 'collection' ) { return; } if ( this.dom.collection.collection !== null ) { $(this.dom.collection.collection).animate({"opacity": 0}, 500, function (e) { this.style.display = "none"; } ); $(this.dom.collection.background).animate({"opacity": 0}, 500, function (e) { this.parentNode.removeChild( this ); } ); this.dom.collection.collection = null; this.dom.collection.background = null; } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Row selection functions */ /** * Add event handlers to a table to allow for row selection * @method _fnRowSelectConfig * @returns void * @private */ "_fnRowSelectConfig": function () { if ( this.s.master ) { var that = this, i, iLen, dt = this.s.dt, aoOpenRows = this.s.dt.aoOpenRows; $(dt.nTable).addClass( this.classes.select.table ); $('tr', dt.nTBody).live( 'click', function(e) { /* Sub-table must be ignored (odd that the selector won't do this with >) */ if ( this.parentNode != dt.nTBody ) { return; } /* Check that we are actually working with a DataTables controlled row */ if ( dt.oInstance.fnGetData(this) === null ) { return; } if ( that.fnIsSelected( this ) ) { that._fnRowDeselect( this, e ); } else if ( that.s.select.type == "single" ) { that.fnSelectNone(); that._fnRowSelect( this, e ); } else if ( that.s.select.type == "multi" ) { that._fnRowSelect( this, e ); } } ); // Bind a listener to the DataTable for when new rows are created. // This allows rows to be visually selected when they should be and // deferred rendering is used. dt.oApi._fnCallbackReg( dt, 'aoRowCreatedCallback', function (tr, data, index) { if ( dt.aoData[index]._DTTT_selected ) { $(tr).addClass( that.classes.select.row ); } }, 'TableTools-SelectAll' ); } }, /** * Select rows * @param {*} src Rows to select - see _fnSelectData for a description of valid inputs * @private */ "_fnRowSelect": function ( src, e ) { var that = this, data = this._fnSelectData( src ), firstTr = data.length===0 ? null : data[0].nTr, anSelected = [], i, len; // Get all the rows that will be selected for ( i=0, len=data.length ; i<len ; i++ ) { if ( data[i].nTr ) { anSelected.push( data[i].nTr ); } } // User defined pre-selection function if ( this.s.select.preRowSelect !== null && !this.s.select.preRowSelect.call(this, e, anSelected, true) ) { return; } // Mark them as selected for ( i=0, len=data.length ; i<len ; i++ ) { data[i]._DTTT_selected = true; if ( data[i].nTr ) { $(data[i].nTr).addClass( that.classes.select.row ); } } // Post-selection function if ( this.s.select.postSelected !== null ) { this.s.select.postSelected.call( this, anSelected ); } TableTools._fnEventDispatch( this, 'select', anSelected, true ); }, /** * Deselect rows * @param {*} src Rows to deselect - see _fnSelectData for a description of valid inputs * @private */ "_fnRowDeselect": function ( src, e ) { var that = this, data = this._fnSelectData( src ), firstTr = data.length===0 ? null : data[0].nTr, anDeselectedTrs = [], i, len; // Get all the rows that will be deselected for ( i=0, len=data.length ; i<len ; i++ ) { if ( data[i].nTr ) { anDeselectedTrs.push( data[i].nTr ); } } // User defined pre-selection function if ( this.s.select.preRowSelect !== null && !this.s.select.preRowSelect.call(this, e, anDeselectedTrs, false) ) { return; } // Mark them as deselected for ( i=0, len=data.length ; i<len ; i++ ) { data[i]._DTTT_selected = false; if ( data[i].nTr ) { $(data[i].nTr).removeClass( that.classes.select.row ); } } // Post-deselection function if ( this.s.select.postDeselected !== null ) { this.s.select.postDeselected.call( this, anDeselectedTrs ); } TableTools._fnEventDispatch( this, 'select', anDeselectedTrs, false ); }, /** * Take a data source for row selection and convert it into aoData points for the DT * @param {*} src Can be a single DOM TR node, an array of TR nodes (including a * a jQuery object), a single aoData point from DataTables, an array of aoData * points or an array of aoData indexes * @returns {array} An array of aoData points */ "_fnSelectData": function ( src ) { var out = [], pos, i, iLen; if ( src.nodeName ) { // Single node pos = this.s.dt.oInstance.fnGetPosition( src ); out.push( this.s.dt.aoData[pos] ); } else if ( typeof src.length !== 'undefined' ) { // jQuery object or an array of nodes, or aoData points for ( i=0, iLen=src.length ; i<iLen ; i++ ) { if ( src[i].nodeName ) { pos = this.s.dt.oInstance.fnGetPosition( src[i] ); out.push( this.s.dt.aoData[pos] ); } else if ( typeof src[i] === 'number' ) { out.push( this.s.dt.aoData[ src[i] ] ); } else { out.push( src[i] ); } } return out; } else { // A single aoData point out.push( src ); } return out; }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Text button functions */ /** * Configure a text based button for interaction events * @method _fnTextConfig * @param {Node} nButton Button element which is being considered * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnTextConfig": function ( nButton, oConfig ) { var that = this; if ( oConfig.fnInit !== null ) { oConfig.fnInit.call( this, nButton, oConfig ); } if ( oConfig.sToolTip !== "" ) { nButton.title = oConfig.sToolTip; } $(nButton).hover( function () { if ( oConfig.fnMouseover !== null ) { oConfig.fnMouseover.call( this, nButton, oConfig, null ); } }, function () { if ( oConfig.fnMouseout !== null ) { oConfig.fnMouseout.call( this, nButton, oConfig, null ); } } ); if ( oConfig.fnSelect !== null ) { TableTools._fnEventListen( this, 'select', function (n) { oConfig.fnSelect.call( that, nButton, oConfig, n ); } ); } $(nButton).click( function (e) { //e.preventDefault(); if ( oConfig.fnClick !== null ) { oConfig.fnClick.call( that, nButton, oConfig, null ); } /* Provide a complete function to match the behaviour of the flash elements */ if ( oConfig.fnComplete !== null ) { oConfig.fnComplete.call( that, nButton, oConfig, null, null ); } that._fnCollectionHide( nButton, oConfig ); } ); }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Flash button functions */ /** * Configure a flash based button for interaction events * @method _fnFlashConfig * @param {Node} nButton Button element which is being considered * @param {o} oConfig Button configuration object * @returns void * @private */ "_fnFlashConfig": function ( nButton, oConfig ) { var that = this; var flash = new ZeroClipboard_TableTools.Client(); if ( oConfig.fnInit !== null ) { oConfig.fnInit.call( this, nButton, oConfig ); } flash.setHandCursor( true ); if ( oConfig.sAction == "flash_save" ) { flash.setAction( 'save' ); flash.setCharSet( (oConfig.sCharSet=="utf16le") ? 'UTF16LE' : 'UTF8' ); flash.setBomInc( oConfig.bBomInc ); flash.setFileName( oConfig.sFileName.replace('*', this.fnGetTitle(oConfig)) ); } else if ( oConfig.sAction == "flash_pdf" ) { flash.setAction( 'pdf' ); flash.setFileName( oConfig.sFileName.replace('*', this.fnGetTitle(oConfig)) ); } else { flash.setAction( 'copy' ); } flash.addEventListener('mouseOver', function(client) { if ( oConfig.fnMouseover !== null ) { oConfig.fnMouseover.call( that, nButton, oConfig, flash ); } } ); flash.addEventListener('mouseOut', function(client) { if ( oConfig.fnMouseout !== null ) { oConfig.fnMouseout.call( that, nButton, oConfig, flash ); } } ); flash.addEventListener('mouseDown', function(client) { if ( oConfig.fnClick !== null ) { oConfig.fnClick.call( that, nButton, oConfig, flash ); } } ); flash.addEventListener('complete', function (client, text) { if ( oConfig.fnComplete !== null ) { oConfig.fnComplete.call( that, nButton, oConfig, flash, text ); } that._fnCollectionHide( nButton, oConfig ); } ); this._fnFlashGlue( flash, nButton, oConfig.sToolTip ); }, /** * Wait until the id is in the DOM before we "glue" the swf. Note that this function will call * itself (using setTimeout) until it completes successfully * @method _fnFlashGlue * @param {Object} clip Zero clipboard object * @param {Node} node node to glue swf to * @param {String} text title of the flash movie * @returns void * @private */ "_fnFlashGlue": function ( flash, node, text ) { var that = this; var id = node.getAttribute('id'); if ( document.getElementById(id) ) { flash.glue( node, text ); } else { setTimeout( function () { that._fnFlashGlue( flash, node, text ); }, 100 ); } }, /** * Set the text for the flash clip to deal with * * This function is required for large information sets. There is a limit on the * amount of data that can be transferred between Javascript and Flash in a single call, so * we use this method to build up the text in Flash by sending over chunks. It is estimated * that the data limit is around 64k, although it is undocumented, and appears to be different * between different flash versions. We chunk at 8KiB. * @method _fnFlashSetText * @param {Object} clip the ZeroClipboard object * @param {String} sData the data to be set * @returns void * @private */ "_fnFlashSetText": function ( clip, sData ) { var asData = this._fnChunkData( sData, 8192 ); clip.clearText(); for ( var i=0, iLen=asData.length ; i<iLen ; i++ ) { clip.appendText( asData[i] ); } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Data retrieval functions */ /** * Convert the mixed columns variable into a boolean array the same size as the columns, which * indicates which columns we want to include * @method _fnColumnTargets * @param {String|Array} mColumns The columns to be included in data retrieval. If a string * then it can take the value of "visible" or "hidden" (to include all visible or * hidden columns respectively). Or an array of column indexes * @returns {Array} A boolean array the length of the columns of the table, which each value * indicating if the column is to be included or not * @private */ "_fnColumnTargets": function ( mColumns ) { var aColumns = []; var dt = this.s.dt; if ( typeof mColumns == "object" ) { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( false ); } for ( i=0, iLen=mColumns.length ; i<iLen ; i++ ) { aColumns[ mColumns[i] ] = true; } } else if ( mColumns == "visible" ) { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( dt.aoColumns[i].bVisible ? true : false ); } } else if ( mColumns == "hidden" ) { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( dt.aoColumns[i].bVisible ? false : true ); } } else if ( mColumns == "sortable" ) { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( dt.aoColumns[i].bSortable ? true : false ); } } else /* all */ { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( true ); } } return aColumns; }, /** * New line character(s) depend on the platforms * @method method * @param {Object} oConfig Button configuration object - only interested in oConfig.sNewLine * @returns {String} Newline character */ "_fnNewline": function ( oConfig ) { if ( oConfig.sNewLine == "auto" ) { return navigator.userAgent.match(/Windows/) ? "\r\n" : "\n"; } else { return oConfig.sNewLine; } }, /** * Get data from DataTables' internals and format it for output * @method _fnGetDataTablesData * @param {Object} oConfig Button configuration object * @param {String} oConfig.sFieldBoundary Field boundary for the data cells in the string * @param {String} oConfig.sFieldSeperator Field separator for the data cells * @param {String} oConfig.sNewline New line options * @param {Mixed} oConfig.mColumns Which columns should be included in the output * @param {Boolean} oConfig.bHeader Include the header * @param {Boolean} oConfig.bFooter Include the footer * @param {Boolean} oConfig.bSelectedOnly Include only the selected rows in the output * @returns {String} Concatenated string of data * @private */ "_fnGetDataTablesData": function ( oConfig ) { var i, iLen, j, jLen; var aRow, aData=[], sLoopData='', arr; var dt = this.s.dt, tr, child; var regex = new RegExp(oConfig.sFieldBoundary, "g"); /* Do it here for speed */ var aColumnsInc = this._fnColumnTargets( oConfig.mColumns ); var bSelectedOnly = (typeof oConfig.bSelectedOnly != 'undefined') ? oConfig.bSelectedOnly : false; /* * Header */ if ( oConfig.bHeader ) { aRow = []; for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { if ( aColumnsInc[i] ) { sLoopData = dt.aoColumns[i].sTitle.replace(/\n/g," ").replace( /<.*?>/g, "" ).replace(/^\s+|\s+$/g,""); sLoopData = this._fnHtmlDecode( sLoopData ); aRow.push( this._fnBoundData( sLoopData, oConfig.sFieldBoundary, regex ) ); } } aData.push( aRow.join(oConfig.sFieldSeperator) ); } /* * Body */ var aDataIndex = dt.aiDisplay; var aSelected = this.fnGetSelected(); if ( this.s.select.type !== "none" && bSelectedOnly && aSelected.length !== 0 ) { aDataIndex = []; for ( i=0, iLen=aSelected.length ; i<iLen ; i++ ) { aDataIndex.push( dt.oInstance.fnGetPosition( aSelected[i] ) ); } } for ( j=0, jLen=aDataIndex.length ; j<jLen ; j++ ) { tr = dt.aoData[ aDataIndex[j] ].nTr; aRow = []; /* Columns */ for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { if ( aColumnsInc[i] ) { /* Convert to strings (with small optimisation) */ var mTypeData = dt.oApi._fnGetCellData( dt, aDataIndex[j], i, 'display' ); if ( oConfig.fnCellRender ) { sLoopData = oConfig.fnCellRender( mTypeData, i, tr, aDataIndex[j] )+""; } else if ( typeof mTypeData == "string" ) { /* Strip newlines, replace img tags with alt attr. and finally strip html... */ sLoopData = mTypeData.replace(/\n/g," "); sLoopData = sLoopData.replace(/<img.*?\s+alt\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+)).*?>/gi, '$1$2$3'); sLoopData = sLoopData.replace( /<.*?>/g, "" ); } else { sLoopData = mTypeData+""; } /* Trim and clean the data */ sLoopData = sLoopData.replace(/^\s+/, '').replace(/\s+$/, ''); sLoopData = this._fnHtmlDecode( sLoopData ); /* Bound it and add it to the total data */ aRow.push( this._fnBoundData( sLoopData, oConfig.sFieldBoundary, regex ) ); } } aData.push( aRow.join(oConfig.sFieldSeperator) ); /* Details rows from fnOpen */ if ( oConfig.bOpenRows ) { arr = $.grep(dt.aoOpenRows, function(o) { return o.nParent === tr; }); if ( arr.length === 1 ) { sLoopData = this._fnBoundData( $('td', arr[0].nTr).html(), oConfig.sFieldBoundary, regex ); aData.push( sLoopData ); } } } /* * Footer */ if ( oConfig.bFooter && dt.nTFoot !== null ) { aRow = []; for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { if ( aColumnsInc[i] && dt.aoColumns[i].nTf !== null ) { sLoopData = dt.aoColumns[i].nTf.innerHTML.replace(/\n/g," ").replace( /<.*?>/g, "" ); sLoopData = this._fnHtmlDecode( sLoopData ); aRow.push( this._fnBoundData( sLoopData, oConfig.sFieldBoundary, regex ) ); } } aData.push( aRow.join(oConfig.sFieldSeperator) ); } _sLastData = aData.join( this._fnNewline(oConfig) ); return _sLastData; }, /** * Wrap data up with a boundary string * @method _fnBoundData * @param {String} sData data to bound * @param {String} sBoundary bounding char(s) * @param {RegExp} regex search for the bounding chars - constructed outside for efficiency * in the loop * @returns {String} bound data * @private */ "_fnBoundData": function ( sData, sBoundary, regex ) { if ( sBoundary === "" ) { return sData; } else { return sBoundary + sData.replace(regex, sBoundary+sBoundary) + sBoundary; } }, /** * Break a string up into an array of smaller strings * @method _fnChunkData * @param {String} sData data to be broken up * @param {Int} iSize chunk size * @returns {Array} String array of broken up text * @private */ "_fnChunkData": function ( sData, iSize ) { var asReturn = []; var iStrlen = sData.length; for ( var i=0 ; i<iStrlen ; i+=iSize ) { if ( i+iSize < iStrlen ) { asReturn.push( sData.substring( i, i+iSize ) ); } else { asReturn.push( sData.substring( i, iStrlen ) ); } } return asReturn; }, /** * Decode HTML entities * @method _fnHtmlDecode * @param {String} sData encoded string * @returns {String} decoded string * @private */ "_fnHtmlDecode": function ( sData ) { if ( sData.indexOf('&') === -1 ) { return sData; } var n = document.createElement('div'); return sData.replace( /&([^\s]*);/g, function( match, match2 ) { if ( match.substr(1, 1) === '#' ) { return String.fromCharCode( Number(match2.substr(1)) ); } else { n.innerHTML = match; return n.childNodes[0].nodeValue; } } ); }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Printing functions */ /** * Show print display * @method _fnPrintStart * @param {Event} e Event object * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnPrintStart": function ( oConfig ) { var that = this; var oSetDT = this.s.dt; /* Parse through the DOM hiding everything that isn't needed for the table */ this._fnPrintHideNodes( oSetDT.nTable ); /* Show the whole table */ this.s.print.saveStart = oSetDT._iDisplayStart; this.s.print.saveLength = oSetDT._iDisplayLength; if ( oConfig.bShowAll ) { oSetDT._iDisplayStart = 0; oSetDT._iDisplayLength = -1; oSetDT.oApi._fnCalculateEnd( oSetDT ); oSetDT.oApi._fnDraw( oSetDT ); } /* Adjust the display for scrolling which might be done by DataTables */ if ( oSetDT.oScroll.sX !== "" || oSetDT.oScroll.sY !== "" ) { this._fnPrintScrollStart( oSetDT ); // If the table redraws while in print view, the DataTables scrolling // setup would hide the header, so we need to readd it on draw $(this.s.dt.nTable).bind('draw.DTTT_Print', function () { that._fnPrintScrollStart( oSetDT ); } ); } /* Remove the other DataTables feature nodes - but leave the table! and info div */ var anFeature = oSetDT.aanFeatures; for ( var cFeature in anFeature ) { if ( cFeature != 'i' && cFeature != 't' && cFeature.length == 1 ) { for ( var i=0, iLen=anFeature[cFeature].length ; i<iLen ; i++ ) { this.dom.print.hidden.push( { "node": anFeature[cFeature][i], "display": "block" } ); anFeature[cFeature][i].style.display = "none"; } } } /* Print class can be used for styling */ $(document.body).addClass( this.classes.print.body ); /* Show information message to let the user know what is happening */ if ( oConfig.sInfo !== "" ) { this.fnInfo( oConfig.sInfo, 3000 ); } /* Add a message at the top of the page */ if ( oConfig.sMessage ) { this.dom.print.message = document.createElement( "div" ); this.dom.print.message.className = this.classes.print.message; this.dom.print.message.innerHTML = oConfig.sMessage; document.body.insertBefore( this.dom.print.message, document.body.childNodes[0] ); } /* Cache the scrolling and the jump to the top of the page */ this.s.print.saveScroll = $(window).scrollTop(); window.scrollTo( 0, 0 ); /* Bind a key event listener to the document for the escape key - * it is removed in the callback */ $(document).bind( "keydown.DTTT", function(e) { /* Only interested in the escape key */ if ( e.keyCode == 27 ) { e.preventDefault(); that._fnPrintEnd.call( that, e ); } } ); }, /** * Printing is finished, resume normal display * @method _fnPrintEnd * @param {Event} e Event object * @returns void * @private */ "_fnPrintEnd": function ( e ) { var that = this; var oSetDT = this.s.dt; var oSetPrint = this.s.print; var oDomPrint = this.dom.print; /* Show all hidden nodes */ this._fnPrintShowNodes(); /* Restore DataTables' scrolling */ if ( oSetDT.oScroll.sX !== "" || oSetDT.oScroll.sY !== "" ) { $(this.s.dt.nTable).unbind('draw.DTTT_Print'); this._fnPrintScrollEnd(); } /* Restore the scroll */ window.scrollTo( 0, oSetPrint.saveScroll ); /* Drop the print message */ if ( oDomPrint.message !== null ) { document.body.removeChild( oDomPrint.message ); oDomPrint.message = null; } /* Styling class */ $(document.body).removeClass( 'DTTT_Print' ); /* Restore the table length */ oSetDT._iDisplayStart = oSetPrint.saveStart; oSetDT._iDisplayLength = oSetPrint.saveLength; oSetDT.oApi._fnCalculateEnd( oSetDT ); oSetDT.oApi._fnDraw( oSetDT ); $(document).unbind( "keydown.DTTT" ); }, /** * Take account of scrolling in DataTables by showing the full table * @returns void * @private */ "_fnPrintScrollStart": function () { var oSetDT = this.s.dt, nScrollHeadInner = oSetDT.nScrollHead.getElementsByTagName('div')[0], nScrollHeadTable = nScrollHeadInner.getElementsByTagName('table')[0], nScrollBody = oSetDT.nTable.parentNode; /* Copy the header in the thead in the body table, this way we show one single table when * in print view. Note that this section of code is more or less verbatim from DT 1.7.0 */ var nTheadSize = oSetDT.nTable.getElementsByTagName('thead'); if ( nTheadSize.length > 0 ) { oSetDT.nTable.removeChild( nTheadSize[0] ); } if ( oSetDT.nTFoot !== null ) { var nTfootSize = oSetDT.nTable.getElementsByTagName('tfoot'); if ( nTfootSize.length > 0 ) { oSetDT.nTable.removeChild( nTfootSize[0] ); } } nTheadSize = oSetDT.nTHead.cloneNode(true); oSetDT.nTable.insertBefore( nTheadSize, oSetDT.nTable.childNodes[0] ); if ( oSetDT.nTFoot !== null ) { nTfootSize = oSetDT.nTFoot.cloneNode(true); oSetDT.nTable.insertBefore( nTfootSize, oSetDT.nTable.childNodes[1] ); } /* Now adjust the table's viewport so we can actually see it */ if ( oSetDT.oScroll.sX !== "" ) { oSetDT.nTable.style.width = $(oSetDT.nTable).outerWidth()+"px"; nScrollBody.style.width = $(oSetDT.nTable).outerWidth()+"px"; nScrollBody.style.overflow = "visible"; } if ( oSetDT.oScroll.sY !== "" ) { nScrollBody.style.height = $(oSetDT.nTable).outerHeight()+"px"; nScrollBody.style.overflow = "visible"; } }, /** * Take account of scrolling in DataTables by showing the full table. Note that the redraw of * the DataTable that we do will actually deal with the majority of the hard work here * @returns void * @private */ "_fnPrintScrollEnd": function () { var oSetDT = this.s.dt, nScrollBody = oSetDT.nTable.parentNode; if ( oSetDT.oScroll.sX !== "" ) { nScrollBody.style.width = oSetDT.oApi._fnStringToCss( oSetDT.oScroll.sX ); nScrollBody.style.overflow = "auto"; } if ( oSetDT.oScroll.sY !== "" ) { nScrollBody.style.height = oSetDT.oApi._fnStringToCss( oSetDT.oScroll.sY ); nScrollBody.style.overflow = "auto"; } }, /** * Resume the display of all TableTools hidden nodes * @method _fnPrintShowNodes * @returns void * @private */ "_fnPrintShowNodes": function ( ) { var anHidden = this.dom.print.hidden; for ( var i=0, iLen=anHidden.length ; i<iLen ; i++ ) { anHidden[i].node.style.display = anHidden[i].display; } anHidden.splice( 0, anHidden.length ); }, /** * Hide nodes which are not needed in order to display the table. Note that this function is * recursive * @method _fnPrintHideNodes * @param {Node} nNode Element which should be showing in a 'print' display * @returns void * @private */ "_fnPrintHideNodes": function ( nNode ) { var anHidden = this.dom.print.hidden; var nParent = nNode.parentNode; var nChildren = nParent.childNodes; for ( var i=0, iLen=nChildren.length ; i<iLen ; i++ ) { if ( nChildren[i] != nNode && nChildren[i].nodeType == 1 ) { /* If our node is shown (don't want to show nodes which were previously hidden) */ var sDisplay = $(nChildren[i]).css("display"); if ( sDisplay != "none" ) { /* Cache the node and it's previous state so we can restore it */ anHidden.push( { "node": nChildren[i], "display": sDisplay } ); nChildren[i].style.display = "none"; } } } if ( nParent.nodeName != "BODY" ) { this._fnPrintHideNodes( nParent ); } } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static variables * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Store of all instances that have been created of TableTools, so one can look up other (when * there is need of a master) * @property _aInstances * @type Array * @default [] * @private */ TableTools._aInstances = []; /** * Store of all listeners and their callback functions * @property _aListeners * @type Array * @default [] */ TableTools._aListeners = []; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Get an array of all the master instances * @method fnGetMasters * @returns {Array} List of master TableTools instances * @static */ TableTools.fnGetMasters = function () { var a = []; for ( var i=0, iLen=TableTools._aInstances.length ; i<iLen ; i++ ) { if ( TableTools._aInstances[i].s.master ) { a.push( TableTools._aInstances[i] ); } } return a; }; /** * Get the master instance for a table node (or id if a string is given) * @method fnGetInstance * @returns {Object} ID of table OR table node, for which we want the TableTools instance * @static */ TableTools.fnGetInstance = function ( node ) { if ( typeof node != 'object' ) { node = document.getElementById(node); } for ( var i=0, iLen=TableTools._aInstances.length ; i<iLen ; i++ ) { if ( TableTools._aInstances[i].s.master && TableTools._aInstances[i].dom.table == node ) { return TableTools._aInstances[i]; } } return null; }; /** * Add a listener for a specific event * @method _fnEventListen * @param {Object} that Scope of the listening function (i.e. 'this' in the caller) * @param {String} type Event type * @param {Function} fn Function * @returns void * @private * @static */ TableTools._fnEventListen = function ( that, type, fn ) { TableTools._aListeners.push( { "that": that, "type": type, "fn": fn } ); }; /** * An event has occurred - look up every listener and fire it off. We check that the event we are * going to fire is attached to the same table (using the table node as reference) before firing * @method _fnEventDispatch * @param {Object} that Scope of the listening function (i.e. 'this' in the caller) * @param {String} type Event type * @param {Node} node Element that the event occurred on (may be null) * @param {boolean} [selected] Indicate if the node was selected (true) or deselected (false) * @returns void * @private * @static */ TableTools._fnEventDispatch = function ( that, type, node, selected ) { var listeners = TableTools._aListeners; for ( var i=0, iLen=listeners.length ; i<iLen ; i++ ) { if ( that.dom.table == listeners[i].that.dom.table && listeners[i].type == type ) { listeners[i].fn( node, selected ); } } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Constants * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ TableTools.buttonBase = { // Button base "sAction": "text", "sTag": "default", "sLinerTag": "default", "sButtonClass": "DTTT_button_text", "sButtonText": "Button text", "sTitle": "", "sToolTip": "", // Common button specific options "sCharSet": "utf8", "bBomInc": false, "sFileName": "*.csv", "sFieldBoundary": "", "sFieldSeperator": "\t", "sNewLine": "auto", "mColumns": "all", /* "all", "visible", "hidden" or array of column integers */ "bHeader": true, "bFooter": true, "bOpenRows": false, "bSelectedOnly": false, // Callbacks "fnMouseover": null, "fnMouseout": null, "fnClick": null, "fnSelect": null, "fnComplete": null, "fnInit": null, "fnCellRender": null }; /** * @namespace Default button configurations */ TableTools.BUTTONS = { "csv": $.extend( {}, TableTools.buttonBase, { "sAction": "flash_save", "sButtonClass": "DTTT_button_csv", "sButtonText": "CSV", "sFieldBoundary": '"', "sFieldSeperator": ",", "fnClick": function( nButton, oConfig, flash ) { this.fnSetText( flash, this.fnGetTableData(oConfig) ); } } ), "xls": $.extend( {}, TableTools.buttonBase, { "sAction": "flash_save", "sCharSet": "utf16le", "bBomInc": true, "sButtonClass": "DTTT_button_xls", "sButtonText": "Excel", "fnClick": function( nButton, oConfig, flash ) { this.fnSetText( flash, this.fnGetTableData(oConfig) ); } } ), "copy": $.extend( {}, TableTools.buttonBase, { "sAction": "flash_copy", "sButtonClass": "DTTT_button_copy", "sButtonText": "Copy", "fnClick": function( nButton, oConfig, flash ) { this.fnSetText( flash, this.fnGetTableData(oConfig) ); }, "fnComplete": function(nButton, oConfig, flash, text) { var lines = text.split('\n').length, len = this.s.dt.nTFoot === null ? lines-1 : lines-2, plural = (len==1) ? "" : "s"; this.fnInfo( '<h6>Table copied</h6>'+ '<p>Copied '+len+' row'+plural+' to the clipboard.</p>', 1500 ); } } ), "pdf": $.extend( {}, TableTools.buttonBase, { "sAction": "flash_pdf", "sNewLine": "\n", "sFileName": "*.pdf", "sButtonClass": "DTTT_button_pdf", "sButtonText": "PDF", "sPdfOrientation": "portrait", "sPdfSize": "A4", "sPdfMessage": "", "fnClick": function( nButton, oConfig, flash ) { this.fnSetText( flash, "title:"+ this.fnGetTitle(oConfig) +"\n"+ "message:"+ oConfig.sPdfMessage +"\n"+ "colWidth:"+ this.fnCalcColRatios(oConfig) +"\n"+ "orientation:"+ oConfig.sPdfOrientation +"\n"+ "size:"+ oConfig.sPdfSize +"\n"+ "--/TableToolsOpts--\n" + this.fnGetTableData(oConfig) ); } } ), "print": $.extend( {}, TableTools.buttonBase, { "sInfo": "<h6>Print view</h6><p>Please use your browser's print function to "+ "print this table. Press escape when finished.", "sMessage": null, "bShowAll": true, "sToolTip": "View print view", "sButtonClass": "DTTT_button_print", "sButtonText": "Print", "fnClick": function ( nButton, oConfig ) { this.fnPrint( true, oConfig ); } } ), "text": $.extend( {}, TableTools.buttonBase ), "select": $.extend( {}, TableTools.buttonBase, { "sButtonText": "Select button", "fnSelect": function( nButton, oConfig ) { if ( this.fnGetSelected().length !== 0 ) { $(nButton).removeClass( this.classes.buttons.disabled ); } else { $(nButton).addClass( this.classes.buttons.disabled ); } }, "fnInit": function( nButton, oConfig ) { $(nButton).addClass( this.classes.buttons.disabled ); } } ), "select_single": $.extend( {}, TableTools.buttonBase, { "sButtonText": "Select button", "fnSelect": function( nButton, oConfig ) { var iSelected = this.fnGetSelected().length; if ( iSelected == 1 ) { $(nButton).removeClass( this.classes.buttons.disabled ); } else { $(nButton).addClass( this.classes.buttons.disabled ); } }, "fnInit": function( nButton, oConfig ) { $(nButton).addClass( this.classes.buttons.disabled ); } } ), "select_all": $.extend( {}, TableTools.buttonBase, { "sButtonText": "Select all", "fnClick": function( nButton, oConfig ) { this.fnSelectAll(); }, "fnSelect": function( nButton, oConfig ) { if ( this.fnGetSelected().length == this.s.dt.fnRecordsDisplay() ) { $(nButton).addClass( this.classes.buttons.disabled ); } else { $(nButton).removeClass( this.classes.buttons.disabled ); } } } ), "select_none": $.extend( {}, TableTools.buttonBase, { "sButtonText": "Deselect all", "fnClick": function( nButton, oConfig ) { this.fnSelectNone(); }, "fnSelect": function( nButton, oConfig ) { if ( this.fnGetSelected().length !== 0 ) { $(nButton).removeClass( this.classes.buttons.disabled ); } else { $(nButton).addClass( this.classes.buttons.disabled ); } }, "fnInit": function( nButton, oConfig ) { $(nButton).addClass( this.classes.buttons.disabled ); } } ), "ajax": $.extend( {}, TableTools.buttonBase, { "sAjaxUrl": "/xhr.php", "sButtonText": "Ajax button", "fnClick": function( nButton, oConfig ) { var sData = this.fnGetTableData(oConfig); $.ajax( { "url": oConfig.sAjaxUrl, "data": [ { "name": "tableData", "value": sData } ], "success": oConfig.fnAjaxComplete, "dataType": "json", "type": "POST", "cache": false, "error": function () { alert( "Error detected when sending table data to server" ); } } ); }, "fnAjaxComplete": function( json ) { alert( 'Ajax complete' ); } } ), "div": $.extend( {}, TableTools.buttonBase, { "sAction": "div", "sTag": "div", "sButtonClass": "DTTT_nonbutton", "sButtonText": "Text button" } ), "collection": $.extend( {}, TableTools.buttonBase, { "sAction": "collection", "sButtonClass": "DTTT_button_collection", "sButtonText": "Collection", "fnClick": function( nButton, oConfig ) { this._fnCollectionShow(nButton, oConfig); } } ) }; /* * on* callback parameters: * 1. node - button element * 2. object - configuration object for this button * 3. object - ZeroClipboard reference (flash button only) * 4. string - Returned string from Flash (flash button only - and only on 'complete') */ /** * @namespace Classes used by TableTools - allows the styles to be override easily. * Note that when TableTools initialises it will take a copy of the classes object * and will use its internal copy for the remainder of its run time. */ TableTools.classes = { "container": "DTTT_container", "buttons": { "normal": "DTTT_button", "disabled": "DTTT_disabled" }, "collection": { "container": "DTTT_collection", "background": "DTTT_collection_background", "buttons": { "normal": "DTTT_button", "disabled": "DTTT_disabled" } }, "select": { "table": "DTTT_selectable", "row": "DTTT_selected" }, "print": { "body": "DTTT_Print", "info": "DTTT_print_info", "message": "DTTT_PrintMessage" } }; /** * @namespace ThemeRoller classes - built in for compatibility with DataTables' * bJQueryUI option. */ TableTools.classes_themeroller = { "container": "DTTT_container ui-buttonset ui-buttonset-multi", "buttons": { "normal": "DTTT_button ui-button ui-state-default" }, "collection": { "container": "DTTT_collection ui-buttonset ui-buttonset-multi" } }; /** * @namespace TableTools default settings for initialisation */ TableTools.DEFAULTS = { "sSwfPath": "media/swf/copy_csv_xls_pdf.swf", "sRowSelect": "none", "sSelectedClass": null, "fnPreRowSelect": null, "fnRowSelected": null, "fnRowDeselected": null, "aButtons": [ "copy", "csv", "xls", "pdf", "print" ], "oTags": { "container": "div", "button": "a", // We really want to use buttons here, but Firefox and IE ignore the // click on the Flash element in the button (but not mouse[in|out]). "liner": "span", "collection": { "container": "div", "button": "a", "liner": "span" } } }; /** * Name of this class * @constant CLASS * @type String * @default TableTools */ TableTools.prototype.CLASS = "TableTools"; /** * TableTools version * @constant VERSION * @type String * @default See code */ TableTools.VERSION = "2.1.4"; TableTools.prototype.VERSION = TableTools.VERSION; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Initialisation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Register a new feature with DataTables */ if ( typeof $.fn.dataTable == "function" && typeof $.fn.dataTableExt.fnVersionCheck == "function" && $.fn.dataTableExt.fnVersionCheck('1.9.0') ) { $.fn.dataTableExt.aoFeatures.push( { "fnInit": function( oDTSettings ) { var oOpts = typeof oDTSettings.oInit.oTableTools != 'undefined' ? oDTSettings.oInit.oTableTools : {}; var oTT = new TableTools( oDTSettings.oInstance, oOpts ); TableTools._aInstances.push( oTT ); return oTT.dom.container; }, "cFeature": "T", "sFeature": "TableTools" } ); } else { alert( "Warning: TableTools 2 requires DataTables 1.9.0 or newer - www.datatables.net/download"); } $.fn.DataTable.TableTools = TableTools; })(jQuery, window, document);
JavaScript
// Simple Set Clipboard System // Author: Joseph Huckaby var ZeroClipboard_TableTools = { version: "1.0.4-TableTools2", clients: {}, // registered upload clients on page, indexed by id moviePath: '', // URL to movie nextId: 1, // ID of next movie $: function(thingy) { // simple DOM lookup utility function if (typeof(thingy) == 'string') thingy = document.getElementById(thingy); if (!thingy.addClass) { // extend element with a few useful methods thingy.hide = function() { this.style.display = 'none'; }; thingy.show = function() { this.style.display = ''; }; thingy.addClass = function(name) { this.removeClass(name); this.className += ' ' + name; }; thingy.removeClass = function(name) { this.className = this.className.replace( new RegExp("\\s*" + name + "\\s*"), " ").replace(/^\s+/, '').replace(/\s+$/, ''); }; thingy.hasClass = function(name) { return !!this.className.match( new RegExp("\\s*" + name + "\\s*") ); } } return thingy; }, setMoviePath: function(path) { // set path to ZeroClipboard.swf this.moviePath = path; }, dispatch: function(id, eventName, args) { // receive event from flash movie, send to client var client = this.clients[id]; if (client) { client.receiveEvent(eventName, args); } }, register: function(id, client) { // register new client to receive events this.clients[id] = client; }, getDOMObjectPosition: function(obj) { // get absolute coordinates for dom element var info = { left: 0, top: 0, width: obj.width ? obj.width : obj.offsetWidth, height: obj.height ? obj.height : obj.offsetHeight }; if ( obj.style.width != "" ) info.width = obj.style.width.replace("px",""); if ( obj.style.height != "" ) info.height = obj.style.height.replace("px",""); while (obj) { info.left += obj.offsetLeft; info.top += obj.offsetTop; obj = obj.offsetParent; } return info; }, Client: function(elem) { // constructor for new simple upload client this.handlers = {}; // unique ID this.id = ZeroClipboard_TableTools.nextId++; this.movieId = 'ZeroClipboard_TableToolsMovie_' + this.id; // register client with singleton to receive flash events ZeroClipboard_TableTools.register(this.id, this); // create movie if (elem) this.glue(elem); } }; ZeroClipboard_TableTools.Client.prototype = { id: 0, // unique ID for us ready: false, // whether movie is ready to receive events or not movie: null, // reference to movie object clipText: '', // text to copy to clipboard fileName: '', // default file save name action: 'copy', // action to perform handCursorEnabled: true, // whether to show hand cursor, or default pointer cursor cssEffects: true, // enable CSS mouse effects on dom container handlers: null, // user event handlers sized: false, glue: function(elem, title) { // glue to DOM element // elem can be ID or actual DOM element object this.domElement = ZeroClipboard_TableTools.$(elem); // float just above object, or zIndex 99 if dom element isn't set var zIndex = 99; if (this.domElement.style.zIndex) { zIndex = parseInt(this.domElement.style.zIndex) + 1; } // find X/Y position of domElement var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement); // create floating DIV above element this.div = document.createElement('div'); var style = this.div.style; style.position = 'absolute'; style.left = '0px'; style.top = '0px'; style.width = (box.width) + 'px'; style.height = box.height + 'px'; style.zIndex = zIndex; if ( typeof title != "undefined" && title != "" ) { this.div.title = title; } if ( box.width != 0 && box.height != 0 ) { this.sized = true; } // style.backgroundColor = '#f00'; // debug if ( this.domElement ) { this.domElement.appendChild(this.div); this.div.innerHTML = this.getHTML( box.width, box.height ); } }, positionElement: function() { var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement); var style = this.div.style; style.position = 'absolute'; //style.left = (this.domElement.offsetLeft)+'px'; //style.top = this.domElement.offsetTop+'px'; style.width = box.width + 'px'; style.height = box.height + 'px'; if ( box.width != 0 && box.height != 0 ) { this.sized = true; } else { return; } var flash = this.div.childNodes[0]; flash.width = box.width; flash.height = box.height; }, getHTML: function(width, height) { // return HTML for movie var html = ''; var flashvars = 'id=' + this.id + '&width=' + width + '&height=' + height; if (navigator.userAgent.match(/MSIE/)) { // IE gets an OBJECT tag var protocol = location.href.match(/^https/i) ? 'https://' : 'http://'; html += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="'+protocol+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="'+width+'" height="'+height+'" id="'+this.movieId+'" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+ZeroClipboard_TableTools.moviePath+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+flashvars+'"/><param name="wmode" value="transparent"/></object>'; } else { // all other browsers get an EMBED tag html += '<embed id="'+this.movieId+'" src="'+ZeroClipboard_TableTools.moviePath+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="'+this.movieId+'" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'" wmode="transparent" />'; } return html; }, hide: function() { // temporarily hide floater offscreen if (this.div) { this.div.style.left = '-2000px'; } }, show: function() { // show ourselves after a call to hide() this.reposition(); }, destroy: function() { // destroy control and floater if (this.domElement && this.div) { this.hide(); this.div.innerHTML = ''; var body = document.getElementsByTagName('body')[0]; try { body.removeChild( this.div ); } catch(e) {;} this.domElement = null; this.div = null; } }, reposition: function(elem) { // reposition our floating div, optionally to new container // warning: container CANNOT change size, only position if (elem) { this.domElement = ZeroClipboard_TableTools.$(elem); if (!this.domElement) this.hide(); } if (this.domElement && this.div) { var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement); var style = this.div.style; style.left = '' + box.left + 'px'; style.top = '' + box.top + 'px'; } }, clearText: function() { // clear the text to be copy / saved this.clipText = ''; if (this.ready) this.movie.clearText(); }, appendText: function(newText) { // append text to that which is to be copied / saved this.clipText += newText; if (this.ready) { this.movie.appendText(newText) ;} }, setText: function(newText) { // set text to be copied to be copied / saved this.clipText = newText; if (this.ready) { this.movie.setText(newText) ;} }, setCharSet: function(charSet) { // set the character set (UTF16LE or UTF8) this.charSet = charSet; if (this.ready) { this.movie.setCharSet(charSet) ;} }, setBomInc: function(bomInc) { // set if the BOM should be included or not this.incBom = bomInc; if (this.ready) { this.movie.setBomInc(bomInc) ;} }, setFileName: function(newText) { // set the file name this.fileName = newText; if (this.ready) this.movie.setFileName(newText); }, setAction: function(newText) { // set action (save or copy) this.action = newText; if (this.ready) this.movie.setAction(newText); }, addEventListener: function(eventName, func) { // add user event listener for event // event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel eventName = eventName.toString().toLowerCase().replace(/^on/, ''); if (!this.handlers[eventName]) this.handlers[eventName] = []; this.handlers[eventName].push(func); }, setHandCursor: function(enabled) { // enable hand cursor (true), or default arrow cursor (false) this.handCursorEnabled = enabled; if (this.ready) this.movie.setHandCursor(enabled); }, setCSSEffects: function(enabled) { // enable or disable CSS effects on DOM container this.cssEffects = !!enabled; }, receiveEvent: function(eventName, args) { // receive event from flash eventName = eventName.toString().toLowerCase().replace(/^on/, ''); // special behavior for certain events switch (eventName) { case 'load': // movie claims it is ready, but in IE this isn't always the case... // bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function this.movie = document.getElementById(this.movieId); if (!this.movie) { var self = this; setTimeout( function() { self.receiveEvent('load', null); }, 1 ); return; } // firefox on pc needs a "kick" in order to set these in certain cases if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) { var self = this; setTimeout( function() { self.receiveEvent('load', null); }, 100 ); this.ready = true; return; } this.ready = true; this.movie.clearText(); this.movie.appendText( this.clipText ); this.movie.setFileName( this.fileName ); this.movie.setAction( this.action ); this.movie.setCharSet( this.charSet ); this.movie.setBomInc( this.incBom ); this.movie.setHandCursor( this.handCursorEnabled ); break; case 'mouseover': if (this.domElement && this.cssEffects) { //this.domElement.addClass('hover'); if (this.recoverActive) this.domElement.addClass('active'); } break; case 'mouseout': if (this.domElement && this.cssEffects) { this.recoverActive = false; if (this.domElement.hasClass('active')) { this.domElement.removeClass('active'); this.recoverActive = true; } //this.domElement.removeClass('hover'); } break; case 'mousedown': if (this.domElement && this.cssEffects) { this.domElement.addClass('active'); } break; case 'mouseup': if (this.domElement && this.cssEffects) { this.domElement.removeClass('active'); this.recoverActive = false; } break; } // switch eventName if (this.handlers[eventName]) { for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) { var func = this.handlers[eventName][idx]; if (typeof(func) == 'function') { // actual function reference func(this, args); } else if ((typeof(func) == 'object') && (func.length == 2)) { // PHP style object + method, i.e. [myObject, 'myMethod'] func[0][ func[1] ](this, args); } else if (typeof(func) == 'string') { // name of function window[func](this, args); } } // foreach event handler defined } // user defined handler for event } };
JavaScript
/* Set the defaults for DataTables initialisation */ $.extend( true, $.fn.dataTable.defaults, { "sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>", "sPaginationType": "bootstrap", "oLanguage": { "sLengthMenu": "_MENU_ records per page" } } ); /* Default class modification */ $.extend( $.fn.dataTableExt.oStdClasses, { "sWrapper": "dataTables_wrapper form-inline" } ); /* API method to get paging information */ $.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings ) { return { "iStart": oSettings._iDisplayStart, "iEnd": oSettings.fnDisplayEnd(), "iLength": oSettings._iDisplayLength, "iTotal": oSettings.fnRecordsTotal(), "iFilteredTotal": oSettings.fnRecordsDisplay(), "iPage": oSettings._iDisplayLength === -1 ? 0 : Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ), "iTotalPages": oSettings._iDisplayLength === -1 ? 0 : Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength ) }; }; /* Bootstrap style pagination control */ $.extend( $.fn.dataTableExt.oPagination, { "bootstrap": { "fnInit": function( oSettings, nPaging, fnDraw ) { var oLang = oSettings.oLanguage.oPaginate; var fnClickHandler = function ( e ) { e.preventDefault(); if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) { fnDraw( oSettings ); } }; $(nPaging).append( '<ul class="pagination">'+ '<li class="prev disabled"><a href="#">&larr; '+oLang.sPrevious+'</a></li>'+ '<li class="next disabled"><a href="#">'+oLang.sNext+' &rarr; </a></li>'+ '</ul>' ); var els = $('a', nPaging); $(els[0]).bind( 'click.DT', { action: "previous" }, fnClickHandler ); $(els[1]).bind( 'click.DT', { action: "next" }, fnClickHandler ); }, "fnUpdate": function ( oSettings, fnDraw ) { var iListLength = 5; var oPaging = oSettings.oInstance.fnPagingInfo(); var an = oSettings.aanFeatures.p; var i, ien, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2); if ( oPaging.iTotalPages < iListLength) { iStart = 1; iEnd = oPaging.iTotalPages; } else if ( oPaging.iPage <= iHalf ) { iStart = 1; iEnd = iListLength; } else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) { iStart = oPaging.iTotalPages - iListLength + 1; iEnd = oPaging.iTotalPages; } else { iStart = oPaging.iPage - iHalf + 1; iEnd = iStart + iListLength - 1; } for ( i=0, ien=an.length ; i<ien ; i++ ) { // Remove the middle elements $('li:gt(0)', an[i]).filter(':not(:last)').remove(); // Add the new list items and their event handlers for ( j=iStart ; j<=iEnd ; j++ ) { sClass = (j==oPaging.iPage+1) ? 'class="active"' : ''; $('<li '+sClass+'><a href="#">'+j+'</a></li>') .insertBefore( $('li:last', an[i])[0] ) .bind('click', function (e) { e.preventDefault(); oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength; fnDraw( oSettings ); } ); } // Add / remove disabled classes from the static elements if ( oPaging.iPage === 0 ) { $('li:first', an[i]).addClass('disabled'); } else { $('li:first', an[i]).removeClass('disabled'); } if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) { $('li:last', an[i]).addClass('disabled'); } else { $('li:last', an[i]).removeClass('disabled'); } } } } } ); /* * TableTools Bootstrap compatibility * Required TableTools 2.1+ */ if ( $.fn.DataTable.TableTools ) { // Set the classes that TableTools uses to something suitable for Bootstrap $.extend( true, $.fn.DataTable.TableTools.classes, { "container": "DTTT btn-group", "buttons": { "normal": "btn", "disabled": "disabled" }, "collection": { "container": "DTTT_dropdown dropdown-menu", "buttons": { "normal": "", "disabled": "disabled" } }, "print": { "info": "DTTT_print_info modal" }, "select": { "row": "active" } } ); // Have the collection use a bootstrap compatible dropdown $.extend( true, $.fn.DataTable.TableTools.DEFAULTS.oTags, { "collection": { "container": "ul", "button": "li", "liner": "a" } } ); }
JavaScript
/* * File: TableTools.js * Version: 2.1.4 * Description: Tools and buttons for DataTables * Author: Allan Jardine (www.sprymedia.co.uk) * Language: Javascript * License: GPL v2 or BSD 3 point style * Project: DataTables * * Copyright 2009-2012 Allan Jardine, all rights reserved. * * This source file is free software, under either the GPL v2 license or a * BSD style license, available at: * http://datatables.net/license_gpl2 * http://datatables.net/license_bsd */ /* Global scope for TableTools */ var TableTools; (function($, window, document) { /** * TableTools provides flexible buttons and other tools for a DataTables enhanced table * @class TableTools * @constructor * @param {Object} oDT DataTables instance * @param {Object} oOpts TableTools options * @param {String} oOpts.sSwfPath ZeroClipboard SWF path * @param {String} oOpts.sRowSelect Row selection options - 'none', 'single' or 'multi' * @param {Function} oOpts.fnPreRowSelect Callback function just prior to row selection * @param {Function} oOpts.fnRowSelected Callback function just after row selection * @param {Function} oOpts.fnRowDeselected Callback function when row is deselected * @param {Array} oOpts.aButtons List of buttons to be used */ TableTools = function( oDT, oOpts ) { /* Santiy check that we are a new instance */ if ( ! this instanceof TableTools ) { alert( "Warning: TableTools must be initialised with the keyword 'new'" ); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public class variables * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * @namespace Settings object which contains customisable information for TableTools instance */ this.s = { /** * Store 'this' so the instance can be retrieved from the settings object * @property that * @type object * @default this */ "that": this, /** * DataTables settings objects * @property dt * @type object * @default <i>From the oDT init option</i> */ "dt": oDT.fnSettings(), /** * @namespace Print specific information */ "print": { /** * DataTables draw 'start' point before the printing display was shown * @property saveStart * @type int * @default -1 */ "saveStart": -1, /** * DataTables draw 'length' point before the printing display was shown * @property saveLength * @type int * @default -1 */ "saveLength": -1, /** * Page scrolling point before the printing display was shown so it can be restored * @property saveScroll * @type int * @default -1 */ "saveScroll": -1, /** * Wrapped function to end the print display (to maintain scope) * @property funcEnd * @type Function * @default function () {} */ "funcEnd": function () {} }, /** * A unique ID is assigned to each button in each instance * @property buttonCounter * @type int * @default 0 */ "buttonCounter": 0, /** * @namespace Select rows specific information */ "select": { /** * Select type - can be 'none', 'single' or 'multi' * @property type * @type string * @default "" */ "type": "", /** * Array of nodes which are currently selected * @property selected * @type array * @default [] */ "selected": [], /** * Function to run before the selection can take place. Will cancel the select if the * function returns false * @property preRowSelect * @type Function * @default null */ "preRowSelect": null, /** * Function to run when a row is selected * @property postSelected * @type Function * @default null */ "postSelected": null, /** * Function to run when a row is deselected * @property postDeselected * @type Function * @default null */ "postDeselected": null, /** * Indicate if all rows are selected (needed for server-side processing) * @property all * @type boolean * @default false */ "all": false, /** * Class name to add to selected TR nodes * @property selectedClass * @type String * @default "" */ "selectedClass": "" }, /** * Store of the user input customisation object * @property custom * @type object * @default {} */ "custom": {}, /** * SWF movie path * @property swfPath * @type string * @default "" */ "swfPath": "", /** * Default button set * @property buttonSet * @type array * @default [] */ "buttonSet": [], /** * When there is more than one TableTools instance for a DataTable, there must be a * master which controls events (row selection etc) * @property master * @type boolean * @default false */ "master": false, /** * Tag names that are used for creating collections and buttons * @namesapce */ "tags": {} }; /** * @namespace Common and useful DOM elements for the class instance */ this.dom = { /** * DIV element that is create and all TableTools buttons (and their children) put into * @property container * @type node * @default null */ "container": null, /** * The table node to which TableTools will be applied * @property table * @type node * @default null */ "table": null, /** * @namespace Nodes used for the print display */ "print": { /** * Nodes which have been removed from the display by setting them to display none * @property hidden * @type array * @default [] */ "hidden": [], /** * The information display saying telling the user about the print display * @property message * @type node * @default null */ "message": null }, /** * @namespace Nodes used for a collection display. This contains the currently used collection */ "collection": { /** * The div wrapper containing the buttons in the collection (i.e. the menu) * @property collection * @type node * @default null */ "collection": null, /** * Background display to provide focus and capture events * @property background * @type node * @default null */ "background": null } }; /** * @namespace Name space for the classes that this TableTools instance will use * @extends TableTools.classes */ this.classes = $.extend( true, {}, TableTools.classes ); if ( this.s.dt.bJUI ) { $.extend( true, this.classes, TableTools.classes_themeroller ); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public class methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Retreieve the settings object from an instance * @method fnSettings * @returns {object} TableTools settings object */ this.fnSettings = function () { return this.s; }; /* Constructor logic */ if ( typeof oOpts == 'undefined' ) { oOpts = {}; } this._fnConstruct( oOpts ); return this; }; TableTools.prototype = { /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Retreieve the settings object from an instance * @returns {array} List of TR nodes which are currently selected * @param {boolean} [filtered=false] Get only selected rows which are * available given the filtering applied to the table. By default * this is false - i.e. all rows, regardless of filtering are selected. */ "fnGetSelected": function ( filtered ) { var out = [], data = this.s.dt.aoData, displayed = this.s.dt.aiDisplay, i, iLen; if ( filtered ) { // Only consider filtered rows for ( i=0, iLen=displayed.length ; i<iLen ; i++ ) { if ( data[ displayed[i] ]._DTTT_selected ) { out.push( data[ displayed[i] ].nTr ); } } } else { // Use all rows for ( i=0, iLen=data.length ; i<iLen ; i++ ) { if ( data[i]._DTTT_selected ) { out.push( data[i].nTr ); } } } return out; }, /** * Get the data source objects/arrays from DataTables for the selected rows (same as * fnGetSelected followed by fnGetData on each row from the table) * @returns {array} Data from the TR nodes which are currently selected */ "fnGetSelectedData": function () { var out = []; var data=this.s.dt.aoData; var i, iLen; for ( i=0, iLen=data.length ; i<iLen ; i++ ) { if ( data[i]._DTTT_selected ) { out.push( this.s.dt.oInstance.fnGetData(i) ); } } return out; }, /** * Check to see if a current row is selected or not * @param {Node} n TR node to check if it is currently selected or not * @returns {Boolean} true if select, false otherwise */ "fnIsSelected": function ( n ) { var pos = this.s.dt.oInstance.fnGetPosition( n ); return (this.s.dt.aoData[pos]._DTTT_selected===true) ? true : false; }, /** * Select all rows in the table * @param {boolean} [filtered=false] Select only rows which are available * given the filtering applied to the table. By default this is false - * i.e. all rows, regardless of filtering are selected. */ "fnSelectAll": function ( filtered ) { var s = this._fnGetMasterSettings(); this._fnRowSelect( (filtered === true) ? s.dt.aiDisplay : s.dt.aoData ); }, /** * Deselect all rows in the table * @param {boolean} [filtered=false] Deselect only rows which are available * given the filtering applied to the table. By default this is false - * i.e. all rows, regardless of filtering are deselected. */ "fnSelectNone": function ( filtered ) { var s = this._fnGetMasterSettings(); this._fnRowDeselect( this.fnGetSelected(filtered) ); }, /** * Select row(s) * @param {node|object|array} n The row(s) to select. Can be a single DOM * TR node, an array of TR nodes or a jQuery object. */ "fnSelect": function ( n ) { if ( this.s.select.type == "single" ) { this.fnSelectNone(); this._fnRowSelect( n ); } else if ( this.s.select.type == "multi" ) { this._fnRowSelect( n ); } }, /** * Deselect row(s) * @param {node|object|array} n The row(s) to deselect. Can be a single DOM * TR node, an array of TR nodes or a jQuery object. */ "fnDeselect": function ( n ) { this._fnRowDeselect( n ); }, /** * Get the title of the document - useful for file names. The title is retrieved from either * the configuration object's 'title' parameter, or the HTML document title * @param {Object} oConfig Button configuration object * @returns {String} Button title */ "fnGetTitle": function( oConfig ) { var sTitle = ""; if ( typeof oConfig.sTitle != 'undefined' && oConfig.sTitle !== "" ) { sTitle = oConfig.sTitle; } else { var anTitle = document.getElementsByTagName('title'); if ( anTitle.length > 0 ) { sTitle = anTitle[0].innerHTML; } } /* Strip characters which the OS will object to - checking for UTF8 support in the scripting * engine */ if ( "\u00A1".toString().length < 4 ) { return sTitle.replace(/[^a-zA-Z0-9_\u00A1-\uFFFF\.,\-_ !\(\)]/g, ""); } else { return sTitle.replace(/[^a-zA-Z0-9_\.,\-_ !\(\)]/g, ""); } }, /** * Calculate a unity array with the column width by proportion for a set of columns to be * included for a button. This is particularly useful for PDF creation, where we can use the * column widths calculated by the browser to size the columns in the PDF. * @param {Object} oConfig Button configuration object * @returns {Array} Unity array of column ratios */ "fnCalcColRatios": function ( oConfig ) { var aoCols = this.s.dt.aoColumns, aColumnsInc = this._fnColumnTargets( oConfig.mColumns ), aColWidths = [], iWidth = 0, iTotal = 0, i, iLen; for ( i=0, iLen=aColumnsInc.length ; i<iLen ; i++ ) { if ( aColumnsInc[i] ) { iWidth = aoCols[i].nTh.offsetWidth; iTotal += iWidth; aColWidths.push( iWidth ); } } for ( i=0, iLen=aColWidths.length ; i<iLen ; i++ ) { aColWidths[i] = aColWidths[i] / iTotal; } return aColWidths.join('\t'); }, /** * Get the information contained in a table as a string * @param {Object} oConfig Button configuration object * @returns {String} Table data as a string */ "fnGetTableData": function ( oConfig ) { /* In future this could be used to get data from a plain HTML source as well as DataTables */ if ( this.s.dt ) { return this._fnGetDataTablesData( oConfig ); } }, /** * Pass text to a flash button instance, which will be used on the button's click handler * @param {Object} clip Flash button object * @param {String} text Text to set */ "fnSetText": function ( clip, text ) { this._fnFlashSetText( clip, text ); }, /** * Resize the flash elements of the buttons attached to this TableTools instance - this is * useful for when initialising TableTools when it is hidden (display:none) since sizes can't * be calculated at that time. */ "fnResizeButtons": function () { for ( var cli in ZeroClipboard_TableTools.clients ) { if ( cli ) { var client = ZeroClipboard_TableTools.clients[cli]; if ( typeof client.domElement != 'undefined' && client.domElement.parentNode ) { client.positionElement(); } } } }, /** * Check to see if any of the ZeroClipboard client's attached need to be resized */ "fnResizeRequired": function () { for ( var cli in ZeroClipboard_TableTools.clients ) { if ( cli ) { var client = ZeroClipboard_TableTools.clients[cli]; if ( typeof client.domElement != 'undefined' && client.domElement.parentNode == this.dom.container && client.sized === false ) { return true; } } } return false; }, /** * Programmatically enable or disable the print view * @param {boolean} [bView=true] Show the print view if true or not given. If false, then * terminate the print view and return to normal. * @param {object} [oConfig={}] Configuration for the print view * @param {boolean} [oConfig.bShowAll=false] Show all rows in the table if true * @param {string} [oConfig.sInfo] Information message, displayed as an overlay to the * user to let them know what the print view is. * @param {string} [oConfig.sMessage] HTML string to show at the top of the document - will * be included in the printed document. */ "fnPrint": function ( bView, oConfig ) { if ( oConfig === undefined ) { oConfig = {}; } if ( bView === undefined || bView ) { this._fnPrintStart( oConfig ); } else { this._fnPrintEnd(); } }, /** * Show a message to the end user which is nicely styled * @param {string} message The HTML string to show to the user * @param {int} time The duration the message is to be shown on screen for (mS) */ "fnInfo": function ( message, time ) { var nInfo = document.createElement( "div" ); nInfo.className = this.classes.print.info; nInfo.innerHTML = message; document.body.appendChild( nInfo ); setTimeout( function() { $(nInfo).fadeOut( "normal", function() { document.body.removeChild( nInfo ); } ); }, time ); }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Private methods (they are of course public in JS, but recommended as private) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Constructor logic * @method _fnConstruct * @param {Object} oOpts Same as TableTools constructor * @returns void * @private */ "_fnConstruct": function ( oOpts ) { var that = this; this._fnCustomiseSettings( oOpts ); /* Container element */ this.dom.container = document.createElement( this.s.tags.container ); this.dom.container.className = this.classes.container; /* Row selection config */ if ( this.s.select.type != 'none' ) { this._fnRowSelectConfig(); } /* Buttons */ this._fnButtonDefinations( this.s.buttonSet, this.dom.container ); /* Destructor - need to wipe the DOM for IE's garbage collector */ this.s.dt.aoDestroyCallback.push( { "sName": "TableTools", "fn": function () { that.dom.container.innerHTML = ""; } } ); }, /** * Take the user defined settings and the default settings and combine them. * @method _fnCustomiseSettings * @param {Object} oOpts Same as TableTools constructor * @returns void * @private */ "_fnCustomiseSettings": function ( oOpts ) { /* Is this the master control instance or not? */ if ( typeof this.s.dt._TableToolsInit == 'undefined' ) { this.s.master = true; this.s.dt._TableToolsInit = true; } /* We can use the table node from comparisons to group controls */ this.dom.table = this.s.dt.nTable; /* Clone the defaults and then the user options */ this.s.custom = $.extend( {}, TableTools.DEFAULTS, oOpts ); /* Flash file location */ this.s.swfPath = this.s.custom.sSwfPath; if ( typeof ZeroClipboard_TableTools != 'undefined' ) { ZeroClipboard_TableTools.moviePath = this.s.swfPath; } /* Table row selecting */ this.s.select.type = this.s.custom.sRowSelect; this.s.select.preRowSelect = this.s.custom.fnPreRowSelect; this.s.select.postSelected = this.s.custom.fnRowSelected; this.s.select.postDeselected = this.s.custom.fnRowDeselected; // Backwards compatibility - allow the user to specify a custom class in the initialiser if ( this.s.custom.sSelectedClass ) { this.classes.select.row = this.s.custom.sSelectedClass; } this.s.tags = this.s.custom.oTags; /* Button set */ this.s.buttonSet = this.s.custom.aButtons; }, /** * Take the user input arrays and expand them to be fully defined, and then add them to a given * DOM element * @method _fnButtonDefinations * @param {array} buttonSet Set of user defined buttons * @param {node} wrapper Node to add the created buttons to * @returns void * @private */ "_fnButtonDefinations": function ( buttonSet, wrapper ) { var buttonDef; for ( var i=0, iLen=buttonSet.length ; i<iLen ; i++ ) { if ( typeof buttonSet[i] == "string" ) { if ( typeof TableTools.BUTTONS[ buttonSet[i] ] == 'undefined' ) { alert( "TableTools: Warning - unknown button type: "+buttonSet[i] ); continue; } buttonDef = $.extend( {}, TableTools.BUTTONS[ buttonSet[i] ], true ); } else { if ( typeof TableTools.BUTTONS[ buttonSet[i].sExtends ] == 'undefined' ) { alert( "TableTools: Warning - unknown button type: "+buttonSet[i].sExtends ); continue; } var o = $.extend( {}, TableTools.BUTTONS[ buttonSet[i].sExtends ], true ); buttonDef = $.extend( o, buttonSet[i], true ); } wrapper.appendChild( this._fnCreateButton( buttonDef, $(wrapper).hasClass(this.classes.collection.container) ) ); } }, /** * Create and configure a TableTools button * @method _fnCreateButton * @param {Object} oConfig Button configuration object * @returns {Node} Button element * @private */ "_fnCreateButton": function ( oConfig, bCollectionButton ) { var nButton = this._fnButtonBase( oConfig, bCollectionButton ); if ( oConfig.sAction.match(/flash/) ) { this._fnFlashConfig( nButton, oConfig ); } else if ( oConfig.sAction == "text" ) { this._fnTextConfig( nButton, oConfig ); } else if ( oConfig.sAction == "div" ) { this._fnTextConfig( nButton, oConfig ); } else if ( oConfig.sAction == "collection" ) { this._fnTextConfig( nButton, oConfig ); this._fnCollectionConfig( nButton, oConfig ); } return nButton; }, /** * Create the DOM needed for the button and apply some base properties. All buttons start here * @method _fnButtonBase * @param {o} oConfig Button configuration object * @returns {Node} DIV element for the button * @private */ "_fnButtonBase": function ( o, bCollectionButton ) { var sTag, sLiner, sClass; if ( bCollectionButton ) { sTag = o.sTag !== "default" ? o.sTag : this.s.tags.collection.button; sLiner = o.sLinerTag !== "default" ? o.sLiner : this.s.tags.collection.liner; sClass = this.classes.collection.buttons.normal; } else { sTag = o.sTag !== "default" ? o.sTag : this.s.tags.button; sLiner = o.sLinerTag !== "default" ? o.sLiner : this.s.tags.liner; sClass = this.classes.buttons.normal; } var nButton = document.createElement( sTag ), nSpan = document.createElement( sLiner ), masterS = this._fnGetMasterSettings(); nButton.className = sClass+" "+o.sButtonClass; nButton.setAttribute('id', "ToolTables_"+this.s.dt.sInstance+"_"+masterS.buttonCounter ); nButton.appendChild( nSpan ); nSpan.innerHTML = o.sButtonText; masterS.buttonCounter++; return nButton; }, /** * Get the settings object for the master instance. When more than one TableTools instance is * assigned to a DataTable, only one of them can be the 'master' (for the select rows). As such, * we will typically want to interact with that master for global properties. * @method _fnGetMasterSettings * @returns {Object} TableTools settings object * @private */ "_fnGetMasterSettings": function () { if ( this.s.master ) { return this.s; } else { /* Look for the master which has the same DT as this one */ var instances = TableTools._aInstances; for ( var i=0, iLen=instances.length ; i<iLen ; i++ ) { if ( this.dom.table == instances[i].s.dt.nTable ) { return instances[i].s; } } } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Button collection functions */ /** * Create a collection button, when activated will present a drop down list of other buttons * @param {Node} nButton Button to use for the collection activation * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnCollectionConfig": function ( nButton, oConfig ) { var nHidden = document.createElement( this.s.tags.collection.container ); nHidden.style.display = "none"; nHidden.className = this.classes.collection.container; oConfig._collection = nHidden; document.body.appendChild( nHidden ); this._fnButtonDefinations( oConfig.aButtons, nHidden ); }, /** * Show a button collection * @param {Node} nButton Button to use for the collection * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnCollectionShow": function ( nButton, oConfig ) { var that = this, oPos = $(nButton).offset(), nHidden = oConfig._collection, iDivX = oPos.left, iDivY = oPos.top + $(nButton).outerHeight(), iWinHeight = $(window).height(), iDocHeight = $(document).height(), iWinWidth = $(window).width(), iDocWidth = $(document).width(); nHidden.style.position = "absolute"; nHidden.style.left = iDivX+"px"; nHidden.style.top = iDivY+"px"; nHidden.style.display = "block"; $(nHidden).css('opacity',0); var nBackground = document.createElement('div'); nBackground.style.position = "absolute"; nBackground.style.left = "0px"; nBackground.style.top = "0px"; nBackground.style.height = ((iWinHeight>iDocHeight)? iWinHeight : iDocHeight) +"px"; nBackground.style.width = ((iWinWidth>iDocWidth)? iWinWidth : iDocWidth) +"px"; nBackground.className = this.classes.collection.background; $(nBackground).css('opacity',0); document.body.appendChild( nBackground ); document.body.appendChild( nHidden ); /* Visual corrections to try and keep the collection visible */ var iDivWidth = $(nHidden).outerWidth(); var iDivHeight = $(nHidden).outerHeight(); if ( iDivX + iDivWidth > iDocWidth ) { nHidden.style.left = (iDocWidth-iDivWidth)+"px"; } if ( iDivY + iDivHeight > iDocHeight ) { nHidden.style.top = (iDivY-iDivHeight-$(nButton).outerHeight())+"px"; } this.dom.collection.collection = nHidden; this.dom.collection.background = nBackground; /* This results in a very small delay for the end user but it allows the animation to be * much smoother. If you don't want the animation, then the setTimeout can be removed */ setTimeout( function () { $(nHidden).animate({"opacity": 1}, 500); $(nBackground).animate({"opacity": 0.25}, 500); }, 10 ); /* Resize the buttons to the Flash contents fit */ this.fnResizeButtons(); /* Event handler to remove the collection display */ $(nBackground).click( function () { that._fnCollectionHide.call( that, null, null ); } ); }, /** * Hide a button collection * @param {Node} nButton Button to use for the collection * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnCollectionHide": function ( nButton, oConfig ) { if ( oConfig !== null && oConfig.sExtends == 'collection' ) { return; } if ( this.dom.collection.collection !== null ) { $(this.dom.collection.collection).animate({"opacity": 0}, 500, function (e) { this.style.display = "none"; } ); $(this.dom.collection.background).animate({"opacity": 0}, 500, function (e) { this.parentNode.removeChild( this ); } ); this.dom.collection.collection = null; this.dom.collection.background = null; } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Row selection functions */ /** * Add event handlers to a table to allow for row selection * @method _fnRowSelectConfig * @returns void * @private */ "_fnRowSelectConfig": function () { if ( this.s.master ) { var that = this, i, iLen, dt = this.s.dt, aoOpenRows = this.s.dt.aoOpenRows; $(dt.nTable).addClass( this.classes.select.table ); $('tr', dt.nTBody).live( 'click', function(e) { /* Sub-table must be ignored (odd that the selector won't do this with >) */ if ( this.parentNode != dt.nTBody ) { return; } /* Check that we are actually working with a DataTables controlled row */ if ( dt.oInstance.fnGetData(this) === null ) { return; } if ( that.fnIsSelected( this ) ) { that._fnRowDeselect( this, e ); } else if ( that.s.select.type == "single" ) { that.fnSelectNone(); that._fnRowSelect( this, e ); } else if ( that.s.select.type == "multi" ) { that._fnRowSelect( this, e ); } } ); // Bind a listener to the DataTable for when new rows are created. // This allows rows to be visually selected when they should be and // deferred rendering is used. dt.oApi._fnCallbackReg( dt, 'aoRowCreatedCallback', function (tr, data, index) { if ( dt.aoData[index]._DTTT_selected ) { $(tr).addClass( that.classes.select.row ); } }, 'TableTools-SelectAll' ); } }, /** * Select rows * @param {*} src Rows to select - see _fnSelectData for a description of valid inputs * @private */ "_fnRowSelect": function ( src, e ) { var that = this, data = this._fnSelectData( src ), firstTr = data.length===0 ? null : data[0].nTr, anSelected = [], i, len; // Get all the rows that will be selected for ( i=0, len=data.length ; i<len ; i++ ) { if ( data[i].nTr ) { anSelected.push( data[i].nTr ); } } // User defined pre-selection function if ( this.s.select.preRowSelect !== null && !this.s.select.preRowSelect.call(this, e, anSelected, true) ) { return; } // Mark them as selected for ( i=0, len=data.length ; i<len ; i++ ) { data[i]._DTTT_selected = true; if ( data[i].nTr ) { $(data[i].nTr).addClass( that.classes.select.row ); } } // Post-selection function if ( this.s.select.postSelected !== null ) { this.s.select.postSelected.call( this, anSelected ); } TableTools._fnEventDispatch( this, 'select', anSelected, true ); }, /** * Deselect rows * @param {*} src Rows to deselect - see _fnSelectData for a description of valid inputs * @private */ "_fnRowDeselect": function ( src, e ) { var that = this, data = this._fnSelectData( src ), firstTr = data.length===0 ? null : data[0].nTr, anDeselectedTrs = [], i, len; // Get all the rows that will be deselected for ( i=0, len=data.length ; i<len ; i++ ) { if ( data[i].nTr ) { anDeselectedTrs.push( data[i].nTr ); } } // User defined pre-selection function if ( this.s.select.preRowSelect !== null && !this.s.select.preRowSelect.call(this, e, anDeselectedTrs, false) ) { return; } // Mark them as deselected for ( i=0, len=data.length ; i<len ; i++ ) { data[i]._DTTT_selected = false; if ( data[i].nTr ) { $(data[i].nTr).removeClass( that.classes.select.row ); } } // Post-deselection function if ( this.s.select.postDeselected !== null ) { this.s.select.postDeselected.call( this, anDeselectedTrs ); } TableTools._fnEventDispatch( this, 'select', anDeselectedTrs, false ); }, /** * Take a data source for row selection and convert it into aoData points for the DT * @param {*} src Can be a single DOM TR node, an array of TR nodes (including a * a jQuery object), a single aoData point from DataTables, an array of aoData * points or an array of aoData indexes * @returns {array} An array of aoData points */ "_fnSelectData": function ( src ) { var out = [], pos, i, iLen; if ( src.nodeName ) { // Single node pos = this.s.dt.oInstance.fnGetPosition( src ); out.push( this.s.dt.aoData[pos] ); } else if ( typeof src.length !== 'undefined' ) { // jQuery object or an array of nodes, or aoData points for ( i=0, iLen=src.length ; i<iLen ; i++ ) { if ( src[i].nodeName ) { pos = this.s.dt.oInstance.fnGetPosition( src[i] ); out.push( this.s.dt.aoData[pos] ); } else if ( typeof src[i] === 'number' ) { out.push( this.s.dt.aoData[ src[i] ] ); } else { out.push( src[i] ); } } return out; } else { // A single aoData point out.push( src ); } return out; }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Text button functions */ /** * Configure a text based button for interaction events * @method _fnTextConfig * @param {Node} nButton Button element which is being considered * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnTextConfig": function ( nButton, oConfig ) { var that = this; if ( oConfig.fnInit !== null ) { oConfig.fnInit.call( this, nButton, oConfig ); } if ( oConfig.sToolTip !== "" ) { nButton.title = oConfig.sToolTip; } $(nButton).hover( function () { if ( oConfig.fnMouseover !== null ) { oConfig.fnMouseover.call( this, nButton, oConfig, null ); } }, function () { if ( oConfig.fnMouseout !== null ) { oConfig.fnMouseout.call( this, nButton, oConfig, null ); } } ); if ( oConfig.fnSelect !== null ) { TableTools._fnEventListen( this, 'select', function (n) { oConfig.fnSelect.call( that, nButton, oConfig, n ); } ); } $(nButton).click( function (e) { //e.preventDefault(); if ( oConfig.fnClick !== null ) { oConfig.fnClick.call( that, nButton, oConfig, null ); } /* Provide a complete function to match the behaviour of the flash elements */ if ( oConfig.fnComplete !== null ) { oConfig.fnComplete.call( that, nButton, oConfig, null, null ); } that._fnCollectionHide( nButton, oConfig ); } ); }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Flash button functions */ /** * Configure a flash based button for interaction events * @method _fnFlashConfig * @param {Node} nButton Button element which is being considered * @param {o} oConfig Button configuration object * @returns void * @private */ "_fnFlashConfig": function ( nButton, oConfig ) { var that = this; var flash = new ZeroClipboard_TableTools.Client(); if ( oConfig.fnInit !== null ) { oConfig.fnInit.call( this, nButton, oConfig ); } flash.setHandCursor( true ); if ( oConfig.sAction == "flash_save" ) { flash.setAction( 'save' ); flash.setCharSet( (oConfig.sCharSet=="utf16le") ? 'UTF16LE' : 'UTF8' ); flash.setBomInc( oConfig.bBomInc ); flash.setFileName( oConfig.sFileName.replace('*', this.fnGetTitle(oConfig)) ); } else if ( oConfig.sAction == "flash_pdf" ) { flash.setAction( 'pdf' ); flash.setFileName( oConfig.sFileName.replace('*', this.fnGetTitle(oConfig)) ); } else { flash.setAction( 'copy' ); } flash.addEventListener('mouseOver', function(client) { if ( oConfig.fnMouseover !== null ) { oConfig.fnMouseover.call( that, nButton, oConfig, flash ); } } ); flash.addEventListener('mouseOut', function(client) { if ( oConfig.fnMouseout !== null ) { oConfig.fnMouseout.call( that, nButton, oConfig, flash ); } } ); flash.addEventListener('mouseDown', function(client) { if ( oConfig.fnClick !== null ) { oConfig.fnClick.call( that, nButton, oConfig, flash ); } } ); flash.addEventListener('complete', function (client, text) { if ( oConfig.fnComplete !== null ) { oConfig.fnComplete.call( that, nButton, oConfig, flash, text ); } that._fnCollectionHide( nButton, oConfig ); } ); this._fnFlashGlue( flash, nButton, oConfig.sToolTip ); }, /** * Wait until the id is in the DOM before we "glue" the swf. Note that this function will call * itself (using setTimeout) until it completes successfully * @method _fnFlashGlue * @param {Object} clip Zero clipboard object * @param {Node} node node to glue swf to * @param {String} text title of the flash movie * @returns void * @private */ "_fnFlashGlue": function ( flash, node, text ) { var that = this; var id = node.getAttribute('id'); if ( document.getElementById(id) ) { flash.glue( node, text ); } else { setTimeout( function () { that._fnFlashGlue( flash, node, text ); }, 100 ); } }, /** * Set the text for the flash clip to deal with * * This function is required for large information sets. There is a limit on the * amount of data that can be transferred between Javascript and Flash in a single call, so * we use this method to build up the text in Flash by sending over chunks. It is estimated * that the data limit is around 64k, although it is undocumented, and appears to be different * between different flash versions. We chunk at 8KiB. * @method _fnFlashSetText * @param {Object} clip the ZeroClipboard object * @param {String} sData the data to be set * @returns void * @private */ "_fnFlashSetText": function ( clip, sData ) { var asData = this._fnChunkData( sData, 8192 ); clip.clearText(); for ( var i=0, iLen=asData.length ; i<iLen ; i++ ) { clip.appendText( asData[i] ); } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Data retrieval functions */ /** * Convert the mixed columns variable into a boolean array the same size as the columns, which * indicates which columns we want to include * @method _fnColumnTargets * @param {String|Array} mColumns The columns to be included in data retrieval. If a string * then it can take the value of "visible" or "hidden" (to include all visible or * hidden columns respectively). Or an array of column indexes * @returns {Array} A boolean array the length of the columns of the table, which each value * indicating if the column is to be included or not * @private */ "_fnColumnTargets": function ( mColumns ) { var aColumns = []; var dt = this.s.dt; if ( typeof mColumns == "object" ) { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( false ); } for ( i=0, iLen=mColumns.length ; i<iLen ; i++ ) { aColumns[ mColumns[i] ] = true; } } else if ( mColumns == "visible" ) { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( dt.aoColumns[i].bVisible ? true : false ); } } else if ( mColumns == "hidden" ) { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( dt.aoColumns[i].bVisible ? false : true ); } } else if ( mColumns == "sortable" ) { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( dt.aoColumns[i].bSortable ? true : false ); } } else /* all */ { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( true ); } } return aColumns; }, /** * New line character(s) depend on the platforms * @method method * @param {Object} oConfig Button configuration object - only interested in oConfig.sNewLine * @returns {String} Newline character */ "_fnNewline": function ( oConfig ) { if ( oConfig.sNewLine == "auto" ) { return navigator.userAgent.match(/Windows/) ? "\r\n" : "\n"; } else { return oConfig.sNewLine; } }, /** * Get data from DataTables' internals and format it for output * @method _fnGetDataTablesData * @param {Object} oConfig Button configuration object * @param {String} oConfig.sFieldBoundary Field boundary for the data cells in the string * @param {String} oConfig.sFieldSeperator Field separator for the data cells * @param {String} oConfig.sNewline New line options * @param {Mixed} oConfig.mColumns Which columns should be included in the output * @param {Boolean} oConfig.bHeader Include the header * @param {Boolean} oConfig.bFooter Include the footer * @param {Boolean} oConfig.bSelectedOnly Include only the selected rows in the output * @returns {String} Concatenated string of data * @private */ "_fnGetDataTablesData": function ( oConfig ) { var i, iLen, j, jLen; var aRow, aData=[], sLoopData='', arr; var dt = this.s.dt, tr, child; var regex = new RegExp(oConfig.sFieldBoundary, "g"); /* Do it here for speed */ var aColumnsInc = this._fnColumnTargets( oConfig.mColumns ); var bSelectedOnly = (typeof oConfig.bSelectedOnly != 'undefined') ? oConfig.bSelectedOnly : false; /* * Header */ if ( oConfig.bHeader ) { aRow = []; for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { if ( aColumnsInc[i] ) { sLoopData = dt.aoColumns[i].sTitle.replace(/\n/g," ").replace( /<.*?>/g, "" ).replace(/^\s+|\s+$/g,""); sLoopData = this._fnHtmlDecode( sLoopData ); aRow.push( this._fnBoundData( sLoopData, oConfig.sFieldBoundary, regex ) ); } } aData.push( aRow.join(oConfig.sFieldSeperator) ); } /* * Body */ var aDataIndex = dt.aiDisplay; var aSelected = this.fnGetSelected(); if ( this.s.select.type !== "none" && bSelectedOnly && aSelected.length !== 0 ) { aDataIndex = []; for ( i=0, iLen=aSelected.length ; i<iLen ; i++ ) { aDataIndex.push( dt.oInstance.fnGetPosition( aSelected[i] ) ); } } for ( j=0, jLen=aDataIndex.length ; j<jLen ; j++ ) { tr = dt.aoData[ aDataIndex[j] ].nTr; aRow = []; /* Columns */ for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { if ( aColumnsInc[i] ) { /* Convert to strings (with small optimisation) */ var mTypeData = dt.oApi._fnGetCellData( dt, aDataIndex[j], i, 'display' ); if ( oConfig.fnCellRender ) { sLoopData = oConfig.fnCellRender( mTypeData, i, tr, aDataIndex[j] )+""; } else if ( typeof mTypeData == "string" ) { /* Strip newlines, replace img tags with alt attr. and finally strip html... */ sLoopData = mTypeData.replace(/\n/g," "); sLoopData = sLoopData.replace(/<img.*?\s+alt\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+)).*?>/gi, '$1$2$3'); sLoopData = sLoopData.replace( /<.*?>/g, "" ); } else { sLoopData = mTypeData+""; } /* Trim and clean the data */ sLoopData = sLoopData.replace(/^\s+/, '').replace(/\s+$/, ''); sLoopData = this._fnHtmlDecode( sLoopData ); /* Bound it and add it to the total data */ aRow.push( this._fnBoundData( sLoopData, oConfig.sFieldBoundary, regex ) ); } } aData.push( aRow.join(oConfig.sFieldSeperator) ); /* Details rows from fnOpen */ if ( oConfig.bOpenRows ) { arr = $.grep(dt.aoOpenRows, function(o) { return o.nParent === tr; }); if ( arr.length === 1 ) { sLoopData = this._fnBoundData( $('td', arr[0].nTr).html(), oConfig.sFieldBoundary, regex ); aData.push( sLoopData ); } } } /* * Footer */ if ( oConfig.bFooter && dt.nTFoot !== null ) { aRow = []; for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { if ( aColumnsInc[i] && dt.aoColumns[i].nTf !== null ) { sLoopData = dt.aoColumns[i].nTf.innerHTML.replace(/\n/g," ").replace( /<.*?>/g, "" ); sLoopData = this._fnHtmlDecode( sLoopData ); aRow.push( this._fnBoundData( sLoopData, oConfig.sFieldBoundary, regex ) ); } } aData.push( aRow.join(oConfig.sFieldSeperator) ); } _sLastData = aData.join( this._fnNewline(oConfig) ); return _sLastData; }, /** * Wrap data up with a boundary string * @method _fnBoundData * @param {String} sData data to bound * @param {String} sBoundary bounding char(s) * @param {RegExp} regex search for the bounding chars - constructed outside for efficiency * in the loop * @returns {String} bound data * @private */ "_fnBoundData": function ( sData, sBoundary, regex ) { if ( sBoundary === "" ) { return sData; } else { return sBoundary + sData.replace(regex, sBoundary+sBoundary) + sBoundary; } }, /** * Break a string up into an array of smaller strings * @method _fnChunkData * @param {String} sData data to be broken up * @param {Int} iSize chunk size * @returns {Array} String array of broken up text * @private */ "_fnChunkData": function ( sData, iSize ) { var asReturn = []; var iStrlen = sData.length; for ( var i=0 ; i<iStrlen ; i+=iSize ) { if ( i+iSize < iStrlen ) { asReturn.push( sData.substring( i, i+iSize ) ); } else { asReturn.push( sData.substring( i, iStrlen ) ); } } return asReturn; }, /** * Decode HTML entities * @method _fnHtmlDecode * @param {String} sData encoded string * @returns {String} decoded string * @private */ "_fnHtmlDecode": function ( sData ) { if ( sData.indexOf('&') === -1 ) { return sData; } var n = document.createElement('div'); return sData.replace( /&([^\s]*);/g, function( match, match2 ) { if ( match.substr(1, 1) === '#' ) { return String.fromCharCode( Number(match2.substr(1)) ); } else { n.innerHTML = match; return n.childNodes[0].nodeValue; } } ); }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Printing functions */ /** * Show print display * @method _fnPrintStart * @param {Event} e Event object * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnPrintStart": function ( oConfig ) { var that = this; var oSetDT = this.s.dt; /* Parse through the DOM hiding everything that isn't needed for the table */ this._fnPrintHideNodes( oSetDT.nTable ); /* Show the whole table */ this.s.print.saveStart = oSetDT._iDisplayStart; this.s.print.saveLength = oSetDT._iDisplayLength; if ( oConfig.bShowAll ) { oSetDT._iDisplayStart = 0; oSetDT._iDisplayLength = -1; oSetDT.oApi._fnCalculateEnd( oSetDT ); oSetDT.oApi._fnDraw( oSetDT ); } /* Adjust the display for scrolling which might be done by DataTables */ if ( oSetDT.oScroll.sX !== "" || oSetDT.oScroll.sY !== "" ) { this._fnPrintScrollStart( oSetDT ); // If the table redraws while in print view, the DataTables scrolling // setup would hide the header, so we need to readd it on draw $(this.s.dt.nTable).bind('draw.DTTT_Print', function () { that._fnPrintScrollStart( oSetDT ); } ); } /* Remove the other DataTables feature nodes - but leave the table! and info div */ var anFeature = oSetDT.aanFeatures; for ( var cFeature in anFeature ) { if ( cFeature != 'i' && cFeature != 't' && cFeature.length == 1 ) { for ( var i=0, iLen=anFeature[cFeature].length ; i<iLen ; i++ ) { this.dom.print.hidden.push( { "node": anFeature[cFeature][i], "display": "block" } ); anFeature[cFeature][i].style.display = "none"; } } } /* Print class can be used for styling */ $(document.body).addClass( this.classes.print.body ); /* Show information message to let the user know what is happening */ if ( oConfig.sInfo !== "" ) { this.fnInfo( oConfig.sInfo, 3000 ); } /* Add a message at the top of the page */ if ( oConfig.sMessage ) { this.dom.print.message = document.createElement( "div" ); this.dom.print.message.className = this.classes.print.message; this.dom.print.message.innerHTML = oConfig.sMessage; document.body.insertBefore( this.dom.print.message, document.body.childNodes[0] ); } /* Cache the scrolling and the jump to the top of the page */ this.s.print.saveScroll = $(window).scrollTop(); window.scrollTo( 0, 0 ); /* Bind a key event listener to the document for the escape key - * it is removed in the callback */ $(document).bind( "keydown.DTTT", function(e) { /* Only interested in the escape key */ if ( e.keyCode == 27 ) { e.preventDefault(); that._fnPrintEnd.call( that, e ); } } ); }, /** * Printing is finished, resume normal display * @method _fnPrintEnd * @param {Event} e Event object * @returns void * @private */ "_fnPrintEnd": function ( e ) { var that = this; var oSetDT = this.s.dt; var oSetPrint = this.s.print; var oDomPrint = this.dom.print; /* Show all hidden nodes */ this._fnPrintShowNodes(); /* Restore DataTables' scrolling */ if ( oSetDT.oScroll.sX !== "" || oSetDT.oScroll.sY !== "" ) { $(this.s.dt.nTable).unbind('draw.DTTT_Print'); this._fnPrintScrollEnd(); } /* Restore the scroll */ window.scrollTo( 0, oSetPrint.saveScroll ); /* Drop the print message */ if ( oDomPrint.message !== null ) { document.body.removeChild( oDomPrint.message ); oDomPrint.message = null; } /* Styling class */ $(document.body).removeClass( 'DTTT_Print' ); /* Restore the table length */ oSetDT._iDisplayStart = oSetPrint.saveStart; oSetDT._iDisplayLength = oSetPrint.saveLength; oSetDT.oApi._fnCalculateEnd( oSetDT ); oSetDT.oApi._fnDraw( oSetDT ); $(document).unbind( "keydown.DTTT" ); }, /** * Take account of scrolling in DataTables by showing the full table * @returns void * @private */ "_fnPrintScrollStart": function () { var oSetDT = this.s.dt, nScrollHeadInner = oSetDT.nScrollHead.getElementsByTagName('div')[0], nScrollHeadTable = nScrollHeadInner.getElementsByTagName('table')[0], nScrollBody = oSetDT.nTable.parentNode; /* Copy the header in the thead in the body table, this way we show one single table when * in print view. Note that this section of code is more or less verbatim from DT 1.7.0 */ var nTheadSize = oSetDT.nTable.getElementsByTagName('thead'); if ( nTheadSize.length > 0 ) { oSetDT.nTable.removeChild( nTheadSize[0] ); } if ( oSetDT.nTFoot !== null ) { var nTfootSize = oSetDT.nTable.getElementsByTagName('tfoot'); if ( nTfootSize.length > 0 ) { oSetDT.nTable.removeChild( nTfootSize[0] ); } } nTheadSize = oSetDT.nTHead.cloneNode(true); oSetDT.nTable.insertBefore( nTheadSize, oSetDT.nTable.childNodes[0] ); if ( oSetDT.nTFoot !== null ) { nTfootSize = oSetDT.nTFoot.cloneNode(true); oSetDT.nTable.insertBefore( nTfootSize, oSetDT.nTable.childNodes[1] ); } /* Now adjust the table's viewport so we can actually see it */ if ( oSetDT.oScroll.sX !== "" ) { oSetDT.nTable.style.width = $(oSetDT.nTable).outerWidth()+"px"; nScrollBody.style.width = $(oSetDT.nTable).outerWidth()+"px"; nScrollBody.style.overflow = "visible"; } if ( oSetDT.oScroll.sY !== "" ) { nScrollBody.style.height = $(oSetDT.nTable).outerHeight()+"px"; nScrollBody.style.overflow = "visible"; } }, /** * Take account of scrolling in DataTables by showing the full table. Note that the redraw of * the DataTable that we do will actually deal with the majority of the hard work here * @returns void * @private */ "_fnPrintScrollEnd": function () { var oSetDT = this.s.dt, nScrollBody = oSetDT.nTable.parentNode; if ( oSetDT.oScroll.sX !== "" ) { nScrollBody.style.width = oSetDT.oApi._fnStringToCss( oSetDT.oScroll.sX ); nScrollBody.style.overflow = "auto"; } if ( oSetDT.oScroll.sY !== "" ) { nScrollBody.style.height = oSetDT.oApi._fnStringToCss( oSetDT.oScroll.sY ); nScrollBody.style.overflow = "auto"; } }, /** * Resume the display of all TableTools hidden nodes * @method _fnPrintShowNodes * @returns void * @private */ "_fnPrintShowNodes": function ( ) { var anHidden = this.dom.print.hidden; for ( var i=0, iLen=anHidden.length ; i<iLen ; i++ ) { anHidden[i].node.style.display = anHidden[i].display; } anHidden.splice( 0, anHidden.length ); }, /** * Hide nodes which are not needed in order to display the table. Note that this function is * recursive * @method _fnPrintHideNodes * @param {Node} nNode Element which should be showing in a 'print' display * @returns void * @private */ "_fnPrintHideNodes": function ( nNode ) { var anHidden = this.dom.print.hidden; var nParent = nNode.parentNode; var nChildren = nParent.childNodes; for ( var i=0, iLen=nChildren.length ; i<iLen ; i++ ) { if ( nChildren[i] != nNode && nChildren[i].nodeType == 1 ) { /* If our node is shown (don't want to show nodes which were previously hidden) */ var sDisplay = $(nChildren[i]).css("display"); if ( sDisplay != "none" ) { /* Cache the node and it's previous state so we can restore it */ anHidden.push( { "node": nChildren[i], "display": sDisplay } ); nChildren[i].style.display = "none"; } } } if ( nParent.nodeName != "BODY" ) { this._fnPrintHideNodes( nParent ); } } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static variables * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Store of all instances that have been created of TableTools, so one can look up other (when * there is need of a master) * @property _aInstances * @type Array * @default [] * @private */ TableTools._aInstances = []; /** * Store of all listeners and their callback functions * @property _aListeners * @type Array * @default [] */ TableTools._aListeners = []; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Get an array of all the master instances * @method fnGetMasters * @returns {Array} List of master TableTools instances * @static */ TableTools.fnGetMasters = function () { var a = []; for ( var i=0, iLen=TableTools._aInstances.length ; i<iLen ; i++ ) { if ( TableTools._aInstances[i].s.master ) { a.push( TableTools._aInstances[i] ); } } return a; }; /** * Get the master instance for a table node (or id if a string is given) * @method fnGetInstance * @returns {Object} ID of table OR table node, for which we want the TableTools instance * @static */ TableTools.fnGetInstance = function ( node ) { if ( typeof node != 'object' ) { node = document.getElementById(node); } for ( var i=0, iLen=TableTools._aInstances.length ; i<iLen ; i++ ) { if ( TableTools._aInstances[i].s.master && TableTools._aInstances[i].dom.table == node ) { return TableTools._aInstances[i]; } } return null; }; /** * Add a listener for a specific event * @method _fnEventListen * @param {Object} that Scope of the listening function (i.e. 'this' in the caller) * @param {String} type Event type * @param {Function} fn Function * @returns void * @private * @static */ TableTools._fnEventListen = function ( that, type, fn ) { TableTools._aListeners.push( { "that": that, "type": type, "fn": fn } ); }; /** * An event has occurred - look up every listener and fire it off. We check that the event we are * going to fire is attached to the same table (using the table node as reference) before firing * @method _fnEventDispatch * @param {Object} that Scope of the listening function (i.e. 'this' in the caller) * @param {String} type Event type * @param {Node} node Element that the event occurred on (may be null) * @param {boolean} [selected] Indicate if the node was selected (true) or deselected (false) * @returns void * @private * @static */ TableTools._fnEventDispatch = function ( that, type, node, selected ) { var listeners = TableTools._aListeners; for ( var i=0, iLen=listeners.length ; i<iLen ; i++ ) { if ( that.dom.table == listeners[i].that.dom.table && listeners[i].type == type ) { listeners[i].fn( node, selected ); } } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Constants * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ TableTools.buttonBase = { // Button base "sAction": "text", "sTag": "default", "sLinerTag": "default", "sButtonClass": "DTTT_button_text", "sButtonText": "Button text", "sTitle": "", "sToolTip": "", // Common button specific options "sCharSet": "utf8", "bBomInc": false, "sFileName": "*.csv", "sFieldBoundary": "", "sFieldSeperator": "\t", "sNewLine": "auto", "mColumns": "all", /* "all", "visible", "hidden" or array of column integers */ "bHeader": true, "bFooter": true, "bOpenRows": false, "bSelectedOnly": false, // Callbacks "fnMouseover": null, "fnMouseout": null, "fnClick": null, "fnSelect": null, "fnComplete": null, "fnInit": null, "fnCellRender": null }; /** * @namespace Default button configurations */ TableTools.BUTTONS = { "csv": $.extend( {}, TableTools.buttonBase, { "sAction": "flash_save", "sButtonClass": "DTTT_button_csv", "sButtonText": "CSV", "sFieldBoundary": '"', "sFieldSeperator": ",", "fnClick": function( nButton, oConfig, flash ) { this.fnSetText( flash, this.fnGetTableData(oConfig) ); } } ), "xls": $.extend( {}, TableTools.buttonBase, { "sAction": "flash_save", "sCharSet": "utf16le", "bBomInc": true, "sButtonClass": "DTTT_button_xls", "sButtonText": "Excel", "fnClick": function( nButton, oConfig, flash ) { this.fnSetText( flash, this.fnGetTableData(oConfig) ); } } ), "copy": $.extend( {}, TableTools.buttonBase, { "sAction": "flash_copy", "sButtonClass": "DTTT_button_copy", "sButtonText": "Copy", "fnClick": function( nButton, oConfig, flash ) { this.fnSetText( flash, this.fnGetTableData(oConfig) ); }, "fnComplete": function(nButton, oConfig, flash, text) { var lines = text.split('\n').length, len = this.s.dt.nTFoot === null ? lines-1 : lines-2, plural = (len==1) ? "" : "s"; this.fnInfo( '<h6>Table copied</h6>'+ '<p>Copied '+len+' row'+plural+' to the clipboard.</p>', 1500 ); } } ), "pdf": $.extend( {}, TableTools.buttonBase, { "sAction": "flash_pdf", "sNewLine": "\n", "sFileName": "*.pdf", "sButtonClass": "DTTT_button_pdf", "sButtonText": "PDF", "sPdfOrientation": "portrait", "sPdfSize": "A4", "sPdfMessage": "", "fnClick": function( nButton, oConfig, flash ) { this.fnSetText( flash, "title:"+ this.fnGetTitle(oConfig) +"\n"+ "message:"+ oConfig.sPdfMessage +"\n"+ "colWidth:"+ this.fnCalcColRatios(oConfig) +"\n"+ "orientation:"+ oConfig.sPdfOrientation +"\n"+ "size:"+ oConfig.sPdfSize +"\n"+ "--/TableToolsOpts--\n" + this.fnGetTableData(oConfig) ); } } ), "print": $.extend( {}, TableTools.buttonBase, { "sInfo": "<h6>Print view</h6><p>Please use your browser's print function to "+ "print this table. Press escape when finished.", "sMessage": null, "bShowAll": true, "sToolTip": "View print view", "sButtonClass": "DTTT_button_print", "sButtonText": "Print", "fnClick": function ( nButton, oConfig ) { this.fnPrint( true, oConfig ); } } ), "text": $.extend( {}, TableTools.buttonBase ), "select": $.extend( {}, TableTools.buttonBase, { "sButtonText": "Select button", "fnSelect": function( nButton, oConfig ) { if ( this.fnGetSelected().length !== 0 ) { $(nButton).removeClass( this.classes.buttons.disabled ); } else { $(nButton).addClass( this.classes.buttons.disabled ); } }, "fnInit": function( nButton, oConfig ) { $(nButton).addClass( this.classes.buttons.disabled ); } } ), "select_single": $.extend( {}, TableTools.buttonBase, { "sButtonText": "Select button", "fnSelect": function( nButton, oConfig ) { var iSelected = this.fnGetSelected().length; if ( iSelected == 1 ) { $(nButton).removeClass( this.classes.buttons.disabled ); } else { $(nButton).addClass( this.classes.buttons.disabled ); } }, "fnInit": function( nButton, oConfig ) { $(nButton).addClass( this.classes.buttons.disabled ); } } ), "select_all": $.extend( {}, TableTools.buttonBase, { "sButtonText": "Select all", "fnClick": function( nButton, oConfig ) { this.fnSelectAll(); }, "fnSelect": function( nButton, oConfig ) { if ( this.fnGetSelected().length == this.s.dt.fnRecordsDisplay() ) { $(nButton).addClass( this.classes.buttons.disabled ); } else { $(nButton).removeClass( this.classes.buttons.disabled ); } } } ), "select_none": $.extend( {}, TableTools.buttonBase, { "sButtonText": "Deselect all", "fnClick": function( nButton, oConfig ) { this.fnSelectNone(); }, "fnSelect": function( nButton, oConfig ) { if ( this.fnGetSelected().length !== 0 ) { $(nButton).removeClass( this.classes.buttons.disabled ); } else { $(nButton).addClass( this.classes.buttons.disabled ); } }, "fnInit": function( nButton, oConfig ) { $(nButton).addClass( this.classes.buttons.disabled ); } } ), "ajax": $.extend( {}, TableTools.buttonBase, { "sAjaxUrl": "/xhr.php", "sButtonText": "Ajax button", "fnClick": function( nButton, oConfig ) { var sData = this.fnGetTableData(oConfig); $.ajax( { "url": oConfig.sAjaxUrl, "data": [ { "name": "tableData", "value": sData } ], "success": oConfig.fnAjaxComplete, "dataType": "json", "type": "POST", "cache": false, "error": function () { alert( "Error detected when sending table data to server" ); } } ); }, "fnAjaxComplete": function( json ) { alert( 'Ajax complete' ); } } ), "div": $.extend( {}, TableTools.buttonBase, { "sAction": "div", "sTag": "div", "sButtonClass": "DTTT_nonbutton", "sButtonText": "Text button" } ), "collection": $.extend( {}, TableTools.buttonBase, { "sAction": "collection", "sButtonClass": "DTTT_button_collection", "sButtonText": "Collection", "fnClick": function( nButton, oConfig ) { this._fnCollectionShow(nButton, oConfig); } } ) }; /* * on* callback parameters: * 1. node - button element * 2. object - configuration object for this button * 3. object - ZeroClipboard reference (flash button only) * 4. string - Returned string from Flash (flash button only - and only on 'complete') */ /** * @namespace Classes used by TableTools - allows the styles to be override easily. * Note that when TableTools initialises it will take a copy of the classes object * and will use its internal copy for the remainder of its run time. */ TableTools.classes = { "container": "DTTT_container", "buttons": { "normal": "DTTT_button", "disabled": "DTTT_disabled" }, "collection": { "container": "DTTT_collection", "background": "DTTT_collection_background", "buttons": { "normal": "DTTT_button", "disabled": "DTTT_disabled" } }, "select": { "table": "DTTT_selectable", "row": "DTTT_selected" }, "print": { "body": "DTTT_Print", "info": "DTTT_print_info", "message": "DTTT_PrintMessage" } }; /** * @namespace ThemeRoller classes - built in for compatibility with DataTables' * bJQueryUI option. */ TableTools.classes_themeroller = { "container": "DTTT_container ui-buttonset ui-buttonset-multi", "buttons": { "normal": "DTTT_button ui-button ui-state-default" }, "collection": { "container": "DTTT_collection ui-buttonset ui-buttonset-multi" } }; /** * @namespace TableTools default settings for initialisation */ TableTools.DEFAULTS = { "sSwfPath": "media/swf/copy_csv_xls_pdf.swf", "sRowSelect": "none", "sSelectedClass": null, "fnPreRowSelect": null, "fnRowSelected": null, "fnRowDeselected": null, "aButtons": [ "copy", "csv", "xls", "pdf", "print" ], "oTags": { "container": "div", "button": "a", // We really want to use buttons here, but Firefox and IE ignore the // click on the Flash element in the button (but not mouse[in|out]). "liner": "span", "collection": { "container": "div", "button": "a", "liner": "span" } } }; /** * Name of this class * @constant CLASS * @type String * @default TableTools */ TableTools.prototype.CLASS = "TableTools"; /** * TableTools version * @constant VERSION * @type String * @default See code */ TableTools.VERSION = "2.1.4"; TableTools.prototype.VERSION = TableTools.VERSION; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Initialisation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Register a new feature with DataTables */ if ( typeof $.fn.dataTable == "function" && typeof $.fn.dataTableExt.fnVersionCheck == "function" && $.fn.dataTableExt.fnVersionCheck('1.9.0') ) { $.fn.dataTableExt.aoFeatures.push( { "fnInit": function( oDTSettings ) { var oOpts = typeof oDTSettings.oInit.oTableTools != 'undefined' ? oDTSettings.oInit.oTableTools : {}; var oTT = new TableTools( oDTSettings.oInstance, oOpts ); TableTools._aInstances.push( oTT ); return oTT.dom.container; }, "cFeature": "T", "sFeature": "TableTools" } ); } else { alert( "Warning: TableTools 2 requires DataTables 1.9.0 or newer - www.datatables.net/download"); } $.fn.DataTable.TableTools = TableTools; })(jQuery, window, document);
JavaScript
(function() { "use strict"; var match = /(\{.*\})/.exec(document.body.innerHTML); if (match) { parent.postMessage(match[1], "*"); } }());
JavaScript
/*! * Fine Uploader * * Copyright 2013, Widen Enterprises, Inc. info@fineuploader.com * * Version: 4.3.1 * * Homepage: http://fineuploader.com * * Repository: git://github.com/Widen/fine-uploader.git * * Licensed under GNU GPL v3, see LICENSE */ /*globals window, navigator, document, FormData, File, HTMLInputElement, XMLHttpRequest, Blob, Storage, ActiveXObject */ var qq = function(element) { "use strict"; return { hide: function() { element.style.display = "none"; return this; }, /** Returns the function which detaches attached event */ attach: function(type, fn) { if (element.addEventListener){ element.addEventListener(type, fn, false); } else if (element.attachEvent){ element.attachEvent("on" + type, fn); } return function() { qq(element).detach(type, fn); }; }, detach: function(type, fn) { if (element.removeEventListener){ element.removeEventListener(type, fn, false); } else if (element.attachEvent){ element.detachEvent("on" + type, fn); } return this; }, contains: function(descendant) { // The [W3C spec](http://www.w3.org/TR/domcore/#dom-node-contains) // says a `null` (or ostensibly `undefined`) parameter // passed into `Node.contains` should result in a false return value. // IE7 throws an exception if the parameter is `undefined` though. if (!descendant) { return false; } // compareposition returns false in this case if (element === descendant) { return true; } if (element.contains){ return element.contains(descendant); } else { /*jslint bitwise: true*/ return !!(descendant.compareDocumentPosition(element) & 8); } }, /** * Insert this element before elementB. */ insertBefore: function(elementB) { elementB.parentNode.insertBefore(element, elementB); return this; }, remove: function() { element.parentNode.removeChild(element); return this; }, /** * Sets styles for an element. * Fixes opacity in IE6-8. */ css: function(styles) { /*jshint eqnull: true*/ if (element.style == null) { throw new qq.Error("Can't apply style to node as it is not on the HTMLElement prototype chain!"); } /*jshint -W116*/ if (styles.opacity != null){ if (typeof element.style.opacity !== "string" && typeof(element.filters) !== "undefined"){ styles.filter = "alpha(opacity=" + Math.round(100 * styles.opacity) + ")"; } } qq.extend(element.style, styles); return this; }, hasClass: function(name) { var re = new RegExp("(^| )" + name + "( |$)"); return re.test(element.className); }, addClass: function(name) { if (!qq(element).hasClass(name)){ element.className += " " + name; } return this; }, removeClass: function(name) { var re = new RegExp("(^| )" + name + "( |$)"); element.className = element.className.replace(re, " ").replace(/^\s+|\s+$/g, ""); return this; }, getByClass: function(className) { var candidates, result = []; if (element.querySelectorAll){ return element.querySelectorAll("." + className); } candidates = element.getElementsByTagName("*"); qq.each(candidates, function(idx, val) { if (qq(val).hasClass(className)){ result.push(val); } }); return result; }, children: function() { var children = [], child = element.firstChild; while (child){ if (child.nodeType === 1){ children.push(child); } child = child.nextSibling; } return children; }, setText: function(text) { element.innerText = text; element.textContent = text; return this; }, clearText: function() { return qq(element).setText(""); }, // Returns true if the attribute exists on the element // AND the value of the attribute is NOT "false" (case-insensitive) hasAttribute: function(attrName) { var attrVal; if (element.hasAttribute) { if (!element.hasAttribute(attrName)) { return false; } /*jshint -W116*/ return (/^false$/i).exec(element.getAttribute(attrName)) == null; } else { attrVal = element[attrName]; if (attrVal === undefined) { return false; } /*jshint -W116*/ return (/^false$/i).exec(attrVal) == null; } } }; }; (function(){ "use strict"; qq.log = function(message, level) { if (window.console) { if (!level || level === "info") { window.console.log(message); } else { if (window.console[level]) { window.console[level](message); } else { window.console.log("<" + level + "> " + message); } } } }; qq.isObject = function(variable) { return variable && !variable.nodeType && Object.prototype.toString.call(variable) === "[object Object]"; }; qq.isFunction = function(variable) { return typeof(variable) === "function"; }; /** * Check the type of a value. Is it an "array"? * * @param value value to test. * @returns true if the value is an array or associated with an `ArrayBuffer` */ qq.isArray = function(value) { return Object.prototype.toString.call(value) === "[object Array]" || (value && window.ArrayBuffer && value.buffer && value.buffer.constructor === ArrayBuffer); }; // Looks for an object on a `DataTransfer` object that is associated with drop events when utilizing the Filesystem API. qq.isItemList = function(maybeItemList) { return Object.prototype.toString.call(maybeItemList) === "[object DataTransferItemList]"; }; // Looks for an object on a `NodeList` or an `HTMLCollection`|`HTMLFormElement`|`HTMLSelectElement` // object that is associated with collections of Nodes. qq.isNodeList = function(maybeNodeList) { return Object.prototype.toString.call(maybeNodeList) === "[object NodeList]" || // If `HTMLCollection` is the actual type of the object, we must determine this // by checking for expected properties/methods on the object (maybeNodeList.item && maybeNodeList.namedItem); }; qq.isString = function(maybeString) { return Object.prototype.toString.call(maybeString) === "[object String]"; }; qq.trimStr = function(string) { if (String.prototype.trim) { return string.trim(); } return string.replace(/^\s+|\s+$/g,""); }; /** * @param str String to format. * @returns {string} A string, swapping argument values with the associated occurrence of {} in the passed string. */ qq.format = function(str) { var args = Array.prototype.slice.call(arguments, 1), newStr = str, nextIdxToReplace = newStr.indexOf("{}"); qq.each(args, function(idx, val) { var strBefore = newStr.substring(0, nextIdxToReplace), strAfter = newStr.substring(nextIdxToReplace+2); newStr = strBefore + val + strAfter; nextIdxToReplace = newStr.indexOf("{}", nextIdxToReplace + val.length); // End the loop if we have run out of tokens (when the arguments exceed the # of tokens) if (nextIdxToReplace < 0) { return false; } }); return newStr; }; qq.isFile = function(maybeFile) { return window.File && Object.prototype.toString.call(maybeFile) === "[object File]"; }; qq.isFileList = function(maybeFileList) { return window.FileList && Object.prototype.toString.call(maybeFileList) === "[object FileList]"; }; qq.isFileOrInput = function(maybeFileOrInput) { return qq.isFile(maybeFileOrInput) || qq.isInput(maybeFileOrInput); }; qq.isInput = function(maybeInput, notFile) { var evaluateType = function(type) { var normalizedType = type.toLowerCase(); if (notFile) { return normalizedType !== "file"; } return normalizedType === "file"; }; if (window.HTMLInputElement) { if (Object.prototype.toString.call(maybeInput) === "[object HTMLInputElement]") { if (maybeInput.type && evaluateType(maybeInput.type)) { return true; } } } if (maybeInput.tagName) { if (maybeInput.tagName.toLowerCase() === "input") { if (maybeInput.type && evaluateType(maybeInput.type)) { return true; } } } return false; }; qq.isBlob = function(maybeBlob) { return window.Blob && Object.prototype.toString.call(maybeBlob) === "[object Blob]"; }; qq.isXhrUploadSupported = function() { var input = document.createElement("input"); input.type = "file"; return ( input.multiple !== undefined && typeof File !== "undefined" && typeof FormData !== "undefined" && typeof (qq.createXhrInstance()).upload !== "undefined" ); }; // Fall back to ActiveX is native XHR is disabled (possible in any version of IE). qq.createXhrInstance = function() { if (window.XMLHttpRequest) { return new XMLHttpRequest(); } try { return new ActiveXObject("MSXML2.XMLHTTP.3.0"); } catch(error) { qq.log("Neither XHR or ActiveX are supported!", "error"); return null; } }; qq.isFolderDropSupported = function(dataTransfer) { return (dataTransfer.items && dataTransfer.items[0].webkitGetAsEntry); }; qq.isFileChunkingSupported = function() { return !qq.android() && //android's impl of Blob.slice is broken qq.isXhrUploadSupported() && (File.prototype.slice !== undefined || File.prototype.webkitSlice !== undefined || File.prototype.mozSlice !== undefined); }; qq.sliceBlob = function(fileOrBlob, start, end) { var slicer = fileOrBlob.slice || fileOrBlob.mozSlice || fileOrBlob.webkitSlice; return slicer.call(fileOrBlob, start, end); }; qq.arrayBufferToHex = function(buffer) { var bytesAsHex = "", bytes = new Uint8Array(buffer); qq.each(bytes, function(idx, byte) { var byteAsHexStr = byte.toString(16); if (byteAsHexStr.length < 2) { byteAsHexStr = "0" + byteAsHexStr; } bytesAsHex += byteAsHexStr; }); return bytesAsHex; }; qq.readBlobToHex = function(blob, startOffset, length) { var initialBlob = qq.sliceBlob(blob, startOffset, startOffset + length), fileReader = new FileReader(), promise = new qq.Promise(); fileReader.onload = function() { promise.success(qq.arrayBufferToHex(fileReader.result)); }; fileReader.readAsArrayBuffer(initialBlob); return promise; }; qq.extend = function(first, second, extendNested) { qq.each(second, function(prop, val) { if (extendNested && qq.isObject(val)) { if (first[prop] === undefined) { first[prop] = {}; } qq.extend(first[prop], val, true); } else { first[prop] = val; } }); return first; }; /** * Allow properties in one object to override properties in another, * keeping track of the original values from the target object. * * Note that the pre-overriden properties to be overriden by the source will be passed into the `sourceFn` when it is invoked. * * @param target Update properties in this object from some source * @param sourceFn A function that, when invoked, will return properties that will replace properties with the same name in the target. * @returns {object} The target object */ qq.override = function(target, sourceFn) { var super_ = {}, source = sourceFn(super_); qq.each(source, function(srcPropName, srcPropVal) { if (target[srcPropName] !== undefined) { super_[srcPropName] = target[srcPropName]; } target[srcPropName] = srcPropVal; }); return target; }; /** * Searches for a given element in the array, returns -1 if it is not present. * @param {Number} [from] The index at which to begin the search */ qq.indexOf = function(arr, elt, from){ if (arr.indexOf) { return arr.indexOf(elt, from); } from = from || 0; var len = arr.length; if (from < 0) { from += len; } for (; from < len; from+=1){ if (arr.hasOwnProperty(from) && arr[from] === elt){ return from; } } return -1; }; //this is a version 4 UUID qq.getUniqueId = function(){ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) { /*jslint eqeq: true, bitwise: true*/ var r = Math.random()*16|0, v = c == "x" ? r : (r&0x3|0x8); return v.toString(16); }); }; // // Browsers and platforms detection qq.ie = function(){ return navigator.userAgent.indexOf("MSIE") !== -1; }; qq.ie7 = function(){ return navigator.userAgent.indexOf("MSIE 7") !== -1; }; qq.ie10 = function(){ return navigator.userAgent.indexOf("MSIE 10") !== -1; }; qq.ie11 = function(){ return (navigator.userAgent.indexOf("Trident") !== -1 && navigator.userAgent.indexOf("rv:11") !== -1); }; qq.safari = function(){ return navigator.vendor !== undefined && navigator.vendor.indexOf("Apple") !== -1; }; qq.chrome = function(){ return navigator.vendor !== undefined && navigator.vendor.indexOf("Google") !== -1; }; qq.opera = function(){ return navigator.vendor !== undefined && navigator.vendor.indexOf("Opera") !== -1; }; qq.firefox = function(){ return (!qq.ie11() && navigator.userAgent.indexOf("Mozilla") !== -1 && navigator.vendor !== undefined && navigator.vendor === ""); }; qq.windows = function(){ return navigator.platform === "Win32"; }; qq.android = function(){ return navigator.userAgent.toLowerCase().indexOf("android") !== -1; }; qq.ios7 = function() { return qq.ios() && navigator.userAgent.indexOf(" OS 7_") !== -1; }; qq.ios = function() { /*jshint -W014 */ return navigator.userAgent.indexOf("iPad") !== -1 || navigator.userAgent.indexOf("iPod") !== -1 || navigator.userAgent.indexOf("iPhone") !== -1; }; // // Events qq.preventDefault = function(e){ if (e.preventDefault){ e.preventDefault(); } else{ e.returnValue = false; } }; /** * Creates and returns element from html string * Uses innerHTML to create an element */ qq.toElement = (function(){ var div = document.createElement("div"); return function(html){ div.innerHTML = html; var element = div.firstChild; div.removeChild(element); return element; }; }()); //key and value are passed to callback for each entry in the iterable item qq.each = function(iterableItem, callback) { var keyOrIndex, retVal; if (iterableItem) { // Iterate through [`Storage`](http://www.w3.org/TR/webstorage/#the-storage-interface) items if (window.Storage && iterableItem.constructor === window.Storage) { for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) { retVal = callback(iterableItem.key(keyOrIndex), iterableItem.getItem(iterableItem.key(keyOrIndex))); if (retVal === false) { break; } } } // `DataTransferItemList` & `NodeList` objects are array-like and should be treated as arrays // when iterating over items inside the object. else if (qq.isArray(iterableItem) || qq.isItemList(iterableItem) || qq.isNodeList(iterableItem)) { for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) { retVal = callback(keyOrIndex, iterableItem[keyOrIndex]); if (retVal === false) { break; } } } else if (qq.isString(iterableItem)) { for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) { retVal = callback(keyOrIndex, iterableItem.charAt(keyOrIndex)); if (retVal === false) { break; } } } else { for (keyOrIndex in iterableItem) { if (Object.prototype.hasOwnProperty.call(iterableItem, keyOrIndex)) { retVal = callback(keyOrIndex, iterableItem[keyOrIndex]); if (retVal === false) { break; } } } } } }; //include any args that should be passed to the new function after the context arg qq.bind = function(oldFunc, context) { if (qq.isFunction(oldFunc)) { var args = Array.prototype.slice.call(arguments, 2); return function() { var newArgs = qq.extend([], args); if (arguments.length) { newArgs = newArgs.concat(Array.prototype.slice.call(arguments)); } return oldFunc.apply(context, newArgs); }; } throw new Error("first parameter must be a function!"); }; /** * obj2url() takes a json-object as argument and generates * a querystring. pretty much like jQuery.param() * * how to use: * * `qq.obj2url({a:'b',c:'d'},'http://any.url/upload?otherParam=value');` * * will result in: * * `http://any.url/upload?otherParam=value&a=b&c=d` * * @param Object JSON-Object * @param String current querystring-part * @return String encoded querystring */ qq.obj2url = function(obj, temp, prefixDone){ /*jshint laxbreak: true*/ var uristrings = [], prefix = "&", add = function(nextObj, i){ var nextTemp = temp ? (/\[\]$/.test(temp)) // prevent double-encoding ? temp : temp+"["+i+"]" : i; if ((nextTemp !== "undefined") && (i !== "undefined")) { uristrings.push( (typeof nextObj === "object") ? qq.obj2url(nextObj, nextTemp, true) : (Object.prototype.toString.call(nextObj) === "[object Function]") ? encodeURIComponent(nextTemp) + "=" + encodeURIComponent(nextObj()) : encodeURIComponent(nextTemp) + "=" + encodeURIComponent(nextObj) ); } }; if (!prefixDone && temp) { prefix = (/\?/.test(temp)) ? (/\?$/.test(temp)) ? "" : "&" : "?"; uristrings.push(temp); uristrings.push(qq.obj2url(obj)); } else if ((Object.prototype.toString.call(obj) === "[object Array]") && (typeof obj !== "undefined") ) { qq.each(obj, function(idx, val) { add(val, idx); }); } else if ((typeof obj !== "undefined") && (obj !== null) && (typeof obj === "object")){ qq.each(obj, function(prop, val) { add(val, prop); }); } else { uristrings.push(encodeURIComponent(temp) + "=" + encodeURIComponent(obj)); } if (temp) { return uristrings.join(prefix); } else { return uristrings.join(prefix) .replace(/^&/, "") .replace(/%20/g, "+"); } }; qq.obj2FormData = function(obj, formData, arrayKeyName) { if (!formData) { formData = new FormData(); } qq.each(obj, function(key, val) { key = arrayKeyName ? arrayKeyName + "[" + key + "]" : key; if (qq.isObject(val)) { qq.obj2FormData(val, formData, key); } else if (qq.isFunction(val)) { formData.append(key, val()); } else { formData.append(key, val); } }); return formData; }; qq.obj2Inputs = function(obj, form) { var input; if (!form) { form = document.createElement("form"); } qq.obj2FormData(obj, { append: function(key, val) { input = document.createElement("input"); input.setAttribute("name", key); input.setAttribute("value", val); form.appendChild(input); } }); return form; }; qq.setCookie = function(name, value, days) { var date = new Date(), expires = ""; if (days) { date.setTime(date.getTime()+(days*24*60*60*1000)); expires = "; expires="+date.toGMTString(); } document.cookie = name+"="+value+expires+"; path=/"; }; qq.getCookie = function(name) { var nameEQ = name + "=", ca = document.cookie.split(";"), cookie; qq.each(ca, function(idx, part) { /*jshint -W116 */ var cookiePart = part; while (cookiePart.charAt(0) == " ") { cookiePart = cookiePart.substring(1, cookiePart.length); } if (cookiePart.indexOf(nameEQ) === 0) { cookie = cookiePart.substring(nameEQ.length, cookiePart.length); return false; } }); return cookie; }; qq.getCookieNames = function(regexp) { var cookies = document.cookie.split(";"), cookieNames = []; qq.each(cookies, function(idx, cookie) { cookie = qq.trimStr(cookie); var equalsIdx = cookie.indexOf("="); if (cookie.match(regexp)) { cookieNames.push(cookie.substr(0, equalsIdx)); } }); return cookieNames; }; qq.deleteCookie = function(name) { qq.setCookie(name, "", -1); }; qq.areCookiesEnabled = function() { var randNum = Math.random() * 100000, name = "qqCookieTest:" + randNum; qq.setCookie(name, 1); if (qq.getCookie(name)) { qq.deleteCookie(name); return true; } return false; }; /** * Not recommended for use outside of Fine Uploader since this falls back to an unchecked eval if JSON.parse is not * implemented. For a more secure JSON.parse polyfill, use Douglas Crockford's json2.js. */ qq.parseJson = function(json) { /*jshint evil: true*/ if (window.JSON && qq.isFunction(JSON.parse)) { return JSON.parse(json); } else { return eval("(" + json + ")"); } }; /** * Retrieve the extension of a file, if it exists. * * @param filename * @returns {string || undefined} */ qq.getExtension = function(filename) { var extIdx = filename.lastIndexOf(".") + 1; if (extIdx > 0) { return filename.substr(extIdx, filename.length - extIdx); } }; qq.getFilename = function(blobOrFileInput) { /*jslint regexp: true*/ if (qq.isInput(blobOrFileInput)) { // get input value and remove path to normalize return blobOrFileInput.value.replace(/.*(\/|\\)/, ""); } else if (qq.isFile(blobOrFileInput)) { if (blobOrFileInput.fileName !== null && blobOrFileInput.fileName !== undefined) { return blobOrFileInput.fileName; } } return blobOrFileInput.name; }; /** * A generic module which supports object disposing in dispose() method. * */ qq.DisposeSupport = function() { var disposers = []; return { /** Run all registered disposers */ dispose: function() { var disposer; do { disposer = disposers.shift(); if (disposer) { disposer(); } } while (disposer); }, /** Attach event handler and register de-attacher as a disposer */ attach: function() { var args = arguments; /*jslint undef:true*/ this.addDisposer(qq(args[0]).attach.apply(this, Array.prototype.slice.call(arguments, 1))); }, /** Add disposer to the collection */ addDisposer: function(disposeFunction) { disposers.push(disposeFunction); } }; }; }()); /* globals qq */ /** * Fine Uploader top-level Error container. Inherits from `Error`. */ (function() { "use strict"; qq.Error = function(message) { this.message = "[Fine Uploader " + qq.version + "] " + message; }; qq.Error.prototype = new Error(); }()); /*global qq */ qq.version="4.3.1"; /* globals qq */ qq.supportedFeatures = (function () { "use strict"; var supportsUploading, supportsAjaxFileUploading, supportsFolderDrop, supportsChunking, supportsResume, supportsUploadViaPaste, supportsUploadCors, supportsDeleteFileXdr, supportsDeleteFileCorsXhr, supportsDeleteFileCors, supportsFolderSelection, supportsImagePreviews; function testSupportsFileInputElement() { var supported = true, tempInput; try { tempInput = document.createElement("input"); tempInput.type = "file"; qq(tempInput).hide(); if (tempInput.disabled) { supported = false; } } catch (ex) { supported = false; } return supported; } //only way to test for Filesystem API support since webkit does not expose the DataTransfer interface function isChrome21OrHigher() { return (qq.chrome() || qq.opera()) && navigator.userAgent.match(/Chrome\/[2][1-9]|Chrome\/[3-9][0-9]/) !== undefined; } //only way to test for complete Clipboard API support at this time function isChrome14OrHigher() { return (qq.chrome() || qq.opera()) && navigator.userAgent.match(/Chrome\/[1][4-9]|Chrome\/[2-9][0-9]/) !== undefined; } //Ensure we can send cross-origin `XMLHttpRequest`s function isCrossOriginXhrSupported() { if (window.XMLHttpRequest) { var xhr = qq.createXhrInstance(); //Commonly accepted test for XHR CORS support. return xhr.withCredentials !== undefined; } return false; } //Test for (terrible) cross-origin ajax transport fallback for IE9 and IE8 function isXdrSupported() { return window.XDomainRequest !== undefined; } // CORS Ajax requests are supported if it is either possible to send credentialed `XMLHttpRequest`s, // or if `XDomainRequest` is an available alternative. function isCrossOriginAjaxSupported() { if (isCrossOriginXhrSupported()) { return true; } return isXdrSupported(); } function isFolderSelectionSupported() { // We know that folder selection is only supported in Chrome via this proprietary attribute for now return document.createElement("input").webkitdirectory !== undefined; } supportsUploading = testSupportsFileInputElement(); supportsAjaxFileUploading = supportsUploading && qq.isXhrUploadSupported(); supportsFolderDrop = supportsAjaxFileUploading && isChrome21OrHigher(); supportsChunking = supportsAjaxFileUploading && qq.isFileChunkingSupported(); supportsResume = supportsAjaxFileUploading && supportsChunking && qq.areCookiesEnabled(); supportsUploadViaPaste = supportsAjaxFileUploading && isChrome14OrHigher(); supportsUploadCors = supportsUploading && (window.postMessage !== undefined || supportsAjaxFileUploading); supportsDeleteFileCorsXhr = isCrossOriginXhrSupported(); supportsDeleteFileXdr = isXdrSupported(); supportsDeleteFileCors = isCrossOriginAjaxSupported(); supportsFolderSelection = isFolderSelectionSupported(); supportsImagePreviews = supportsAjaxFileUploading && window.FileReader !== undefined; return { uploading: supportsUploading, ajaxUploading: supportsAjaxFileUploading, fileDrop: supportsAjaxFileUploading, //NOTE: will also return true for touch-only devices. It's not currently possible to accurately test for touch-only devices folderDrop: supportsFolderDrop, chunking: supportsChunking, resume: supportsResume, uploadCustomHeaders: supportsAjaxFileUploading, uploadNonMultipart: supportsAjaxFileUploading, itemSizeValidation: supportsAjaxFileUploading, uploadViaPaste: supportsUploadViaPaste, progressBar: supportsAjaxFileUploading, uploadCors: supportsUploadCors, deleteFileCorsXhr: supportsDeleteFileCorsXhr, deleteFileCorsXdr: supportsDeleteFileXdr, //NOTE: will also return true in IE10, where XDR is also supported deleteFileCors: supportsDeleteFileCors, canDetermineSize: supportsAjaxFileUploading, folderSelection: supportsFolderSelection, imagePreviews: supportsImagePreviews, imageValidation: supportsImagePreviews, pause: supportsChunking }; }()); /*globals qq*/ qq.Promise = function() { "use strict"; var successArgs, failureArgs, successCallbacks = [], failureCallbacks = [], doneCallbacks = [], state = 0; qq.extend(this, { then: function(onSuccess, onFailure) { if (state === 0) { if (onSuccess) { successCallbacks.push(onSuccess); } if (onFailure) { failureCallbacks.push(onFailure); } } else if (state === -1) { onFailure && onFailure.apply(null, failureArgs); } else if (onSuccess) { onSuccess.apply(null,successArgs); } return this; }, done: function(callback) { if (state === 0) { doneCallbacks.push(callback); } else { callback.apply(null, failureArgs === undefined ? successArgs : failureArgs); } return this; }, success: function() { state = 1; successArgs = arguments; if (successCallbacks.length) { qq.each(successCallbacks, function(idx, callback) { callback.apply(null, successArgs); }); } if(doneCallbacks.length) { qq.each(doneCallbacks, function(idx, callback) { callback.apply(null, successArgs); }); } return this; }, failure: function() { state = -1; failureArgs = arguments; if (failureCallbacks.length) { qq.each(failureCallbacks, function(idx, callback) { callback.apply(null, failureArgs); }); } if(doneCallbacks.length) { qq.each(doneCallbacks, function(idx, callback) { callback.apply(null, failureArgs); }); } return this; } }); }; /*globals qq*/ /** * This module represents an upload or "Select File(s)" button. It's job is to embed an opaque `<input type="file">` * element as a child of a provided "container" element. This "container" element (`options.element`) is used to provide * a custom style for the `<input type="file">` element. The ability to change the style of the container element is also * provided here by adding CSS classes to the container on hover/focus. * * TODO Eliminate the mouseover and mouseout event handlers since the :hover CSS pseudo-class should now be * available on all supported browsers. * * @param o Options to override the default values */ qq.UploadButton = function(o) { "use strict"; var disposeSupport = new qq.DisposeSupport(), options = { // "Container" element element: null, // If true adds `multiple` attribute to `<input type="file">` multiple: false, // Corresponds to the `accept` attribute on the associated `<input type="file">` acceptFiles: null, // A true value allows folders to be selected, if supported by the UA folders: false, // `name` attribute of `<input type="file">` name: "qqfile", // Called when the browser invokes the onchange handler on the `<input type="file">` onChange: function(input) {}, // **This option will be removed** in the future as the :hover CSS pseudo-class is available on all supported browsers hoverClass: "qq-upload-button-hover", focusClass: "qq-upload-button-focus" }, input, buttonId; // Overrides any of the default option values with any option values passed in during construction. qq.extend(options, o); buttonId = qq.getUniqueId(); // Embed an opaque `<input type="file">` element as a child of `options.element`. function createInput() { var input = document.createElement("input"); input.setAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME, buttonId); if (options.multiple) { input.setAttribute("multiple", ""); } if (options.folders && qq.supportedFeatures.folderSelection) { // selecting directories is only possible in Chrome now, via a vendor-specific prefixed attribute input.setAttribute("webkitdirectory", ""); } if (options.acceptFiles) { input.setAttribute("accept", options.acceptFiles); } input.setAttribute("type", "file"); input.setAttribute("name", options.name); qq(input).css({ position: "absolute", // in Opera only 'browse' button // is clickable and it is located at // the right side of the input right: 0, top: 0, fontFamily: "Arial", // 4 persons reported this, the max values that worked for them were 243, 236, 236, 118 fontSize: "118px", margin: 0, padding: 0, cursor: "pointer", opacity: 0 }); options.element.appendChild(input); disposeSupport.attach(input, "change", function(){ options.onChange(input); }); // **These event handlers will be removed** in the future as the :hover CSS pseudo-class is available on all supported browsers disposeSupport.attach(input, "mouseover", function(){ qq(options.element).addClass(options.hoverClass); }); disposeSupport.attach(input, "mouseout", function(){ qq(options.element).removeClass(options.hoverClass); }); disposeSupport.attach(input, "focus", function(){ qq(options.element).addClass(options.focusClass); }); disposeSupport.attach(input, "blur", function(){ qq(options.element).removeClass(options.focusClass); }); // IE and Opera, unfortunately have 2 tab stops on file input // which is unacceptable in our case, disable keyboard access if (window.attachEvent) { // it is IE or Opera input.setAttribute("tabIndex", "-1"); } return input; } // Make button suitable container for input qq(options.element).css({ position: "relative", overflow: "hidden", // Make sure browse button is in the right side in Internet Explorer direction: "ltr" }); input = createInput(); // Exposed API qq.extend(this, { getInput: function() { return input; }, getButtonId: function() { return buttonId; }, setMultiple: function(isMultiple) { if (isMultiple !== options.multiple) { if (isMultiple) { input.setAttribute("multiple", ""); } else { input.removeAttribute("multiple"); } } }, setAcceptFiles: function(acceptFiles) { if (acceptFiles !== options.acceptFiles) { input.setAttribute("accept", acceptFiles); } }, reset: function(){ if (input.parentNode){ qq(input).remove(); } qq(options.element).removeClass(options.focusClass); input = createInput(); } }); }; qq.UploadButton.BUTTON_ID_ATTR_NAME = "qq-button-id"; /*globals qq */ qq.UploadData = function(uploaderProxy) { "use strict"; var data = [], byUuid = {}, byStatus = {}; function getDataByIds(idOrIds) { if (qq.isArray(idOrIds)) { var entries = []; qq.each(idOrIds, function(idx, id) { entries.push(data[id]); }); return entries; } return data[idOrIds]; } function getDataByUuids(uuids) { if (qq.isArray(uuids)) { var entries = []; qq.each(uuids, function(idx, uuid) { entries.push(data[byUuid[uuid]]); }); return entries; } return data[byUuid[uuids]]; } function getDataByStatus(status) { var statusResults = [], statuses = [].concat(status); qq.each(statuses, function(index, statusEnum) { var statusResultIndexes = byStatus[statusEnum]; if (statusResultIndexes !== undefined) { qq.each(statusResultIndexes, function(i, dataIndex) { statusResults.push(data[dataIndex]); }); } }); return statusResults; } qq.extend(this, { /** * Adds a new file to the data cache for tracking purposes. * * @param uuid Initial UUID for this file. * @param name Initial name of this file. * @param size Size of this file, -1 if this cannot be determined * @param status Initial `qq.status` for this file. If null/undefined, `qq.status.SUBMITTING`. * @returns {number} Internal ID for this file. */ addFile: function(uuid, name, size, status) { status = status || qq.status.SUBMITTING; var id = data.push({ name: name, originalName: name, uuid: uuid, size: size, status: status }) - 1; data[id].id = id; byUuid[uuid] = id; if (byStatus[status] === undefined) { byStatus[status] = []; } byStatus[status].push(id); uploaderProxy.onStatusChange(id, null, status); return id; }, retrieve: function(optionalFilter) { if (qq.isObject(optionalFilter) && data.length) { if (optionalFilter.id !== undefined) { return getDataByIds(optionalFilter.id); } else if (optionalFilter.uuid !== undefined) { return getDataByUuids(optionalFilter.uuid); } else if (optionalFilter.status) { return getDataByStatus(optionalFilter.status); } } else { return qq.extend([], data, true); } }, reset: function() { data = []; byUuid = {}; byStatus = {}; }, setStatus: function(id, newStatus) { var oldStatus = data[id].status, byStatusOldStatusIndex = qq.indexOf(byStatus[oldStatus], id); byStatus[oldStatus].splice(byStatusOldStatusIndex, 1); data[id].status = newStatus; if (byStatus[newStatus] === undefined) { byStatus[newStatus] = []; } byStatus[newStatus].push(id); uploaderProxy.onStatusChange(id, oldStatus, newStatus); }, uuidChanged: function(id, newUuid) { var oldUuid = data[id].uuid; data[id].uuid = newUuid; byUuid[newUuid] = id; delete byUuid[oldUuid]; }, updateName: function(id, newName) { data[id].name = newName; } }); }; qq.status = { SUBMITTING: "submitting", SUBMITTED: "submitted", REJECTED: "rejected", QUEUED: "queued", CANCELED: "canceled", PAUSED: "paused", UPLOADING: "uploading", UPLOAD_RETRYING: "retrying upload", UPLOAD_SUCCESSFUL: "upload successful", UPLOAD_FAILED: "upload failed", DELETE_FAILED: "delete failed", DELETING: "deleting", DELETED: "deleted" }; /*globals qq*/ /** * Defines the public API for FineUploaderBasic mode. */ (function(){ "use strict"; qq.basePublicApi = { log: function(str, level) { if (this._options.debug && (!level || level === "info")) { qq.log("[Fine Uploader " + qq.version + "] " + str); } else if (level && level !== "info") { qq.log("[Fine Uploader " + qq.version + "] " + str, level); } }, setParams: function(params, id) { this._paramsStore.set(params, id); }, setDeleteFileParams: function(params, id) { this._deleteFileParamsStore.set(params, id); }, // Re-sets the default endpoint, an endpoint for a specific file, or an endpoint for a specific button setEndpoint: function(endpoint, id) { this._endpointStore.set(endpoint, id); }, getInProgress: function() { return this._uploadData.retrieve({ status: [ qq.status.UPLOADING, qq.status.UPLOAD_RETRYING, qq.status.QUEUED ] }).length; }, getNetUploads: function() { return this._netUploaded; }, uploadStoredFiles: function() { var idToUpload; if (this._storedIds.length === 0) { this._itemError("noFilesError"); } else { while (this._storedIds.length) { idToUpload = this._storedIds.shift(); this._uploadFile(idToUpload); } } }, clearStoredFiles: function(){ this._storedIds = []; }, retry: function(id) { return this._manualRetry(id); }, cancel: function(id) { this._handler.cancel(id); }, cancelAll: function() { var storedIdsCopy = [], self = this; qq.extend(storedIdsCopy, this._storedIds); qq.each(storedIdsCopy, function(idx, storedFileId) { self.cancel(storedFileId); }); this._handler.cancelAll(); }, reset: function() { this.log("Resetting uploader..."); this._handler.reset(); this._storedIds = []; this._autoRetries = []; this._retryTimeouts = []; this._preventRetries = []; this._thumbnailUrls = []; qq.each(this._buttons, function(idx, button) { button.reset(); }); this._paramsStore.reset(); this._endpointStore.reset(); this._netUploadedOrQueued = 0; this._netUploaded = 0; this._uploadData.reset(); this._buttonIdsForFileIds = []; this._pasteHandler && this._pasteHandler.reset(); this._options.session.refreshOnReset && this._refreshSessionData(); this._succeededSinceLastAllComplete = []; this._failedSinceLastAllComplete = []; }, addFiles: function(filesOrInputs, params, endpoint) { var verifiedFilesOrInputs = [], fileOrInputIndex, fileOrInput, fileIndex; if (filesOrInputs) { if (!qq.isFileList(filesOrInputs)) { filesOrInputs = [].concat(filesOrInputs); } for (fileOrInputIndex = 0; fileOrInputIndex < filesOrInputs.length; fileOrInputIndex+=1) { fileOrInput = filesOrInputs[fileOrInputIndex]; if (qq.isFileOrInput(fileOrInput)) { if (qq.isInput(fileOrInput) && qq.supportedFeatures.ajaxUploading) { for (fileIndex = 0; fileIndex < fileOrInput.files.length; fileIndex++) { this._handleNewFile(fileOrInput.files[fileIndex], verifiedFilesOrInputs); } } else { this._handleNewFile(fileOrInput, verifiedFilesOrInputs); } } else { this.log(fileOrInput + " is not a File or INPUT element! Ignoring!", "warn"); } } this.log("Received " + verifiedFilesOrInputs.length + " files or inputs."); this._prepareItemsForUpload(verifiedFilesOrInputs, params, endpoint); } }, addBlobs: function(blobDataOrArray, params, endpoint) { if (blobDataOrArray) { var blobDataArray = [].concat(blobDataOrArray), verifiedBlobDataList = [], self = this; qq.each(blobDataArray, function(idx, blobData) { var blobOrBlobData; if (qq.isBlob(blobData) && !qq.isFileOrInput(blobData)) { blobOrBlobData = { blob: blobData, name: self._options.blobs.defaultName }; } else if (qq.isObject(blobData) && blobData.blob && blobData.name) { blobOrBlobData = blobData; } else { self.log("addBlobs: entry at index " + idx + " is not a Blob or a BlobData object", "error"); } blobOrBlobData && self._handleNewFile(blobOrBlobData, verifiedBlobDataList); }); this._prepareItemsForUpload(verifiedBlobDataList, params, endpoint); } else { this.log("undefined or non-array parameter passed into addBlobs", "error"); } }, getUuid: function(id) { return this._uploadData.retrieve({id: id}).uuid; }, setUuid: function(id, newUuid) { return this._uploadData.uuidChanged(id, newUuid); }, getResumableFilesData: function() { return this._handler.getResumableFilesData(); }, getSize: function(id) { return this._uploadData.retrieve({id: id}).size; }, getName: function(id) { return this._uploadData.retrieve({id: id}).name; }, setName: function(id, newName) { this._uploadData.updateName(id, newName); }, getFile: function(fileOrBlobId) { return this._handler.getFile(fileOrBlobId); }, deleteFile: function(id) { return this._onSubmitDelete(id); }, setDeleteFileEndpoint: function(endpoint, id) { this._deleteFileEndpointStore.set(endpoint, id); }, doesExist: function(fileOrBlobId) { return this._handler.isValid(fileOrBlobId); }, getUploads: function(optionalFilter) { return this._uploadData.retrieve(optionalFilter); }, getButton: function(fileId) { return this._getButton(this._buttonIdsForFileIds[fileId]); }, // Generate a variable size thumbnail on an img or canvas, // returning a promise that is fulfilled when the attempt completes. // Thumbnail can either be based off of a URL for an image returned // by the server in the upload response, or the associated `Blob`. drawThumbnail: function(fileId, imgOrCanvas, maxSize, fromServer) { if (this._imageGenerator) { var fileOrUrl = this._thumbnailUrls[fileId], options = { scale: maxSize > 0, maxSize: maxSize > 0 ? maxSize : null }; // If client-side preview generation is possible // and we are not specifically looking for the image URl returned by the server... if (!fromServer && qq.supportedFeatures.imagePreviews) { fileOrUrl = this.getFile(fileId); } /* jshint eqeqeq:false,eqnull:true */ if (fileOrUrl == null) { return new qq.Promise().failure(imgOrCanvas, "File or URL not found."); } return this._imageGenerator.generate(fileOrUrl, imgOrCanvas, options); } }, pauseUpload: function(id) { var uploadData = this._uploadData.retrieve({id: id}); if (!qq.supportedFeatures.pause || !this._options.chunking.enabled) { return false; } // Pause only really makes sense if the file is uploading or retrying if (qq.indexOf([qq.status.UPLOADING, qq.status.UPLOAD_RETRYING], uploadData.status) >= 0) { if (this._handler.pause(id)) { this._uploadData.setStatus(id, qq.status.PAUSED); return true; } else { qq.log(qq.format("Unable to pause file ID {} ({}).", id, this.getName(id)), "error"); } } else { qq.log(qq.format("Ignoring pause for file ID {} ({}). Not in progress.", id, this.getName(id)), "error"); } return false; }, continueUpload: function(id) { var uploadData = this._uploadData.retrieve({id: id}); if (!qq.supportedFeatures.pause || !this._options.chunking.enabled) { return false; } if (uploadData.status === qq.status.PAUSED) { qq.log(qq.format("Paused file ID {} ({}) will be continued. Not paused.", id, this.getName(id))); this._uploadFile(id); return true; } else { qq.log(qq.format("Ignoring continue for file ID {} ({}). Not paused.", id, this.getName(id)), "error"); } return false; }, getRemainingAllowedItems: function() { var allowedItems = this._options.validation.itemLimit; if (allowedItems > 0) { return this._options.validation.itemLimit - this._netUploadedOrQueued; } return null; } }; /** * Defines the private (internal) API for FineUploaderBasic mode. */ qq.basePrivateApi = { _initFormSupportAndParams: function() { this._formSupport = qq.FormSupport && new qq.FormSupport( this._options.form, qq.bind(this.uploadStoredFiles, this), qq.bind(this.log, this) ); if (this._formSupport && this._formSupport.attachedToForm) { this._paramsStore = this._createStore( this._options.request.params, this._formSupport.getFormInputsAsObject ); this._options.autoUpload = this._formSupport.newAutoUpload; if (this._formSupport.newEndpoint) { this._options.request.endpoint = this._formSupport.newEndpoint; } } else { this._paramsStore = this._createStore(this._options.request.params); } }, _uploadFile: function(id) { if (!this._handler.upload(id)) { this._uploadData.setStatus(id, qq.status.QUEUED); } }, // Attempts to refresh session data only if the `qq.Session` module exists // and a session endpoint has been specified. The `onSessionRequestComplete` // callback will be invoked once the refresh is complete. _refreshSessionData: function() { var self = this, options = this._options.session; /* jshint eqnull:true */ if (qq.Session && this._options.session.endpoint != null) { if (!this._session) { qq.extend(options, this._options.cors); options.log = qq.bind(this.log, this); options.addFileRecord = qq.bind(this._addCannedFile, this); this._session = new qq.Session(options); } setTimeout(function() { self._session.refresh().then(function(response, xhrOrXdr) { self._options.callbacks.onSessionRequestComplete(response, true, xhrOrXdr); }, function(response, xhrOrXdr) { self._options.callbacks.onSessionRequestComplete(response, false, xhrOrXdr); }); }, 0); } }, // Updates internal state with a file record (not backed by a live file). Returns the assigned ID. _addCannedFile: function(sessionData) { var id = this._uploadData.addFile(sessionData.uuid, sessionData.name, sessionData.size, qq.status.UPLOAD_SUCCESSFUL); sessionData.deleteFileEndpoint && this.setDeleteFileEndpoint(sessionData.deleteFileEndpoint, id); sessionData.deleteFileParams && this.setDeleteFileParams(sessionData.deleteFileParams, id); if (sessionData.thumbnailUrl) { this._thumbnailUrls[id] = sessionData.thumbnailUrl; } this._netUploaded++; this._netUploadedOrQueued++; return id; }, // Updates internal state when a new file has been received, and adds it along with its ID to a passed array. _handleNewFile: function(file, newFileWrapperList) { var size = -1, uuid = qq.getUniqueId(), name = qq.getFilename(file), id; if (file.size >= 0) { size = file.size; } else if (file.blob) { size = file.blob.size; } id = this._uploadData.addFile(uuid, name, size); this._handler.add(id, file); this._trackButton(id); this._netUploadedOrQueued++; newFileWrapperList.push({id: id, file: file}); }, // Maps a file with the button that was used to select it. _trackButton: function(id) { var buttonId; if (qq.supportedFeatures.ajaxUploading) { buttonId = this._handler.getFile(id).qqButtonId; } else { buttonId = this._getButtonId(this._handler.getInput(id)); } if (buttonId) { this._buttonIdsForFileIds[id] = buttonId; } }, // Creates an internal object that tracks various properties of each extra button, // and then actually creates the extra button. _generateExtraButtonSpecs: function() { var self = this; this._extraButtonSpecs = {}; qq.each(this._options.extraButtons, function(idx, extraButtonOptionEntry) { var multiple = extraButtonOptionEntry.multiple, validation = qq.extend({}, self._options.validation, true), extraButtonSpec = qq.extend({}, extraButtonOptionEntry); if (multiple === undefined) { multiple = self._options.multiple; } if (extraButtonSpec.validation) { qq.extend(validation, extraButtonOptionEntry.validation, true); } qq.extend(extraButtonSpec, { multiple: multiple, validation: validation }, true); self._initExtraButton(extraButtonSpec); }); }, // Creates an extra button element _initExtraButton: function(spec) { var button = this._createUploadButton({ element: spec.element, multiple: spec.multiple, accept: spec.validation.acceptFiles, folders: spec.folders, allowedExtensions: spec.validation.allowedExtensions }); this._extraButtonSpecs[button.getButtonId()] = spec; }, /** * Gets the internally used tracking ID for a button. * * @param buttonOrFileInputOrFile `File`, `<input type="file">`, or a button container element * @returns {*} The button's ID, or undefined if no ID is recoverable * @private */ _getButtonId: function(buttonOrFileInputOrFile) { var inputs, fileInput; // If the item is a `Blob` it will never be associated with a button or drop zone. if (buttonOrFileInputOrFile && !buttonOrFileInputOrFile.blob && !qq.isBlob(buttonOrFileInputOrFile)) { if (qq.isFile(buttonOrFileInputOrFile)) { return buttonOrFileInputOrFile.qqButtonId; } else if (buttonOrFileInputOrFile.tagName.toLowerCase() === "input" && buttonOrFileInputOrFile.type.toLowerCase() === "file") { return buttonOrFileInputOrFile.getAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME); } inputs = buttonOrFileInputOrFile.getElementsByTagName("input"); qq.each(inputs, function(idx, input) { if (input.getAttribute("type") === "file") { fileInput = input; return false; } }); if (fileInput) { return fileInput.getAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME); } } }, _annotateWithButtonId: function(file, associatedInput) { if (qq.isFile(file)) { file.qqButtonId = this._getButtonId(associatedInput); } }, _getButton: function(buttonId) { var extraButtonsSpec = this._extraButtonSpecs[buttonId]; if (extraButtonsSpec) { return extraButtonsSpec.element; } else if (buttonId === this._defaultButtonId) { return this._options.button; } }, _handleCheckedCallback: function(details) { var self = this, callbackRetVal = details.callback(); if (callbackRetVal instanceof qq.Promise) { this.log(details.name + " - waiting for " + details.name + " promise to be fulfilled for " + details.identifier); return callbackRetVal.then( function(successParam) { self.log(details.name + " promise success for " + details.identifier); details.onSuccess(successParam); }, function() { if (details.onFailure) { self.log(details.name + " promise failure for " + details.identifier); details.onFailure(); } else { self.log(details.name + " promise failure for " + details.identifier); } }); } if (callbackRetVal !== false) { details.onSuccess(callbackRetVal); } else { if (details.onFailure) { this.log(details.name + " - return value was 'false' for " + details.identifier + ". Invoking failure callback."); details.onFailure(); } else { this.log(details.name + " - return value was 'false' for " + details.identifier + ". Will not proceed."); } } return callbackRetVal; }, /** * Generate a tracked upload button. * * @param spec Object containing a required `element` property * along with optional `multiple`, `accept`, and `folders`. * @returns {qq.UploadButton} * @private */ _createUploadButton: function(spec) { var self = this, acceptFiles = spec.accept || this._options.validation.acceptFiles, allowedExtensions = spec.allowedExtensions || this._options.validation.allowedExtensions; function allowMultiple() { if (qq.supportedFeatures.ajaxUploading) { // Workaround for bug in iOS7 (see #1039) if (qq.ios7() && self._isAllowedExtension(allowedExtensions, ".mov")) { return false; } if (spec.multiple === undefined) { return self._options.multiple; } return spec.multiple; } return false; } var button = new qq.UploadButton({ element: spec.element, folders: spec.folders, name: this._options.request.inputName, multiple: allowMultiple(), acceptFiles: acceptFiles, onChange: function(input) { self._onInputChange(input); }, hoverClass: this._options.classes.buttonHover, focusClass: this._options.classes.buttonFocus }); this._disposeSupport.addDisposer(function() { button.dispose(); }); self._buttons.push(button); return button; }, _createUploadHandler: function(additionalOptions, namespace) { var self = this, options = { debug: this._options.debug, maxConnections: this._options.maxConnections, cors: this._options.cors, demoMode: this._options.demoMode, paramsStore: this._paramsStore, endpointStore: this._endpointStore, chunking: this._options.chunking, resume: this._options.resume, blobs: this._options.blobs, log: qq.bind(self.log, self), onProgress: function(id, name, loaded, total){ self._onProgress(id, name, loaded, total); self._options.callbacks.onProgress(id, name, loaded, total); }, onComplete: function(id, name, result, xhr){ var retVal = self._onComplete(id, name, result, xhr); // If the internal `_onComplete` handler returns a promise, don't invoke the `onComplete` callback // until the promise has been fulfilled. if (retVal instanceof qq.Promise) { retVal.done(function() { self._options.callbacks.onComplete(id, name, result, xhr); }); } else { self._options.callbacks.onComplete(id, name, result, xhr); } }, onCancel: function(id, name) { return self._handleCheckedCallback({ name: "onCancel", callback: qq.bind(self._options.callbacks.onCancel, self, id, name), onSuccess: qq.bind(self._onCancel, self, id, name), identifier: id }); }, onUpload: function(id, name) { self._onUpload(id, name); self._options.callbacks.onUpload(id, name); }, onUploadChunk: function(id, name, chunkData) { self._onUploadChunk(id, chunkData); self._options.callbacks.onUploadChunk(id, name, chunkData); }, onUploadChunkSuccess: function(id, chunkData, result, xhr) { self._options.callbacks.onUploadChunkSuccess.apply(self, arguments); }, onResume: function(id, name, chunkData) { return self._options.callbacks.onResume(id, name, chunkData); }, onAutoRetry: function(id, name, responseJSON, xhr) { return self._onAutoRetry.apply(self, arguments); }, onUuidChanged: function(id, newUuid) { self.log("Server requested UUID change from '" + self.getUuid(id) + "' to '" + newUuid + "'"); self.setUuid(id, newUuid); }, getName: qq.bind(self.getName, self), getUuid: qq.bind(self.getUuid, self), getSize: qq.bind(self.getSize, self) }; qq.each(this._options.request, function(prop, val) { options[prop] = val; }); if (additionalOptions) { qq.each(additionalOptions, function(key, val) { options[key] = val; }); } return new qq.UploadHandler(options, namespace); }, _createDeleteHandler: function() { var self = this; return new qq.DeleteFileAjaxRequester({ method: this._options.deleteFile.method.toUpperCase(), maxConnections: this._options.maxConnections, uuidParamName: this._options.request.uuidName, customHeaders: this._options.deleteFile.customHeaders, paramsStore: this._deleteFileParamsStore, endpointStore: this._deleteFileEndpointStore, demoMode: this._options.demoMode, cors: this._options.cors, log: qq.bind(self.log, self), onDelete: function(id) { self._onDelete(id); self._options.callbacks.onDelete(id); }, onDeleteComplete: function(id, xhrOrXdr, isError) { self._onDeleteComplete(id, xhrOrXdr, isError); self._options.callbacks.onDeleteComplete(id, xhrOrXdr, isError); } }); }, _createPasteHandler: function() { var self = this; return new qq.PasteSupport({ targetElement: this._options.paste.targetElement, callbacks: { log: qq.bind(self.log, self), pasteReceived: function(blob) { self._handleCheckedCallback({ name: "onPasteReceived", callback: qq.bind(self._options.callbacks.onPasteReceived, self, blob), onSuccess: qq.bind(self._handlePasteSuccess, self, blob), identifier: "pasted image" }); } } }); }, _createUploadDataTracker: function() { var self = this; return new qq.UploadData({ getName: function(id) { return self.getName(id); }, getUuid: function(id) { return self.getUuid(id); }, getSize: function(id) { return self.getSize(id); }, onStatusChange: function(id, oldStatus, newStatus) { self._onUploadStatusChange(id, oldStatus, newStatus); self._options.callbacks.onStatusChange(id, oldStatus, newStatus); self._maybeAllComplete(id, newStatus); } }); }, _onUploadStatusChange: function(id, oldStatus, newStatus) { // Make sure a "queued" retry attempt is canceled if the upload has been paused if (newStatus === qq.status.PAUSED) { clearTimeout(this._retryTimeouts[id]); } }, _handlePasteSuccess: function(blob, extSuppliedName) { var extension = blob.type.split("/")[1], name = extSuppliedName; /*jshint eqeqeq: true, eqnull: true*/ if (name == null) { name = this._options.paste.defaultName; } name += "." + extension; this.addBlobs({ name: name, blob: blob }); }, _preventLeaveInProgress: function(){ var self = this; this._disposeSupport.attach(window, "beforeunload", function(e){ if (self.getInProgress()) { e = e || window.event; // for ie, ff e.returnValue = self._options.messages.onLeave; // for webkit return self._options.messages.onLeave; } }); }, _onSubmit: function(id, name) { //nothing to do yet in core uploader }, _onProgress: function(id, name, loaded, total) { //nothing to do yet in core uploader }, _onComplete: function(id, name, result, xhr) { if (!result.success) { this._netUploadedOrQueued--; this._uploadData.setStatus(id, qq.status.UPLOAD_FAILED); } else { if (result.thumbnailUrl) { this._thumbnailUrls[id] = result.thumbnailUrl; } this._netUploaded++; this._uploadData.setStatus(id, qq.status.UPLOAD_SUCCESSFUL); } this._maybeParseAndSendUploadError(id, name, result, xhr); return result.success ? true : false; }, _maybeAllComplete: function(id, status) { var self = this, notFinished = this._uploadData.retrieve({ status: [ qq.status.UPLOADING, qq.status.UPLOAD_RETRYING, qq.status.QUEUED, qq.status.SUBMITTING, qq.status.SUBMITTED, qq.status.PAUSED, ] }).length; if (status === qq.status.UPLOAD_SUCCESSFUL) { this._succeededSinceLastAllComplete.push(id); } else if (status === qq.status.UPLOAD_FAILED) { this._failedSinceLastAllComplete.push(id); } if (notFinished === 0 && (this._succeededSinceLastAllComplete.length || this._failedSinceLastAllComplete.length)) { // Attempt to ensure onAllComplete is not invoked before other callbacks, such as onCancel & onComplete setTimeout(function() { self._options.callbacks.onAllComplete( qq.extend([], self._succeededSinceLastAllComplete), qq.extend([], self._failedSinceLastAllComplete) ); self._succeededSinceLastAllComplete = []; self._failedSinceLastAllComplete = []; }, 0); } }, _onCancel: function(id, name) { this._netUploadedOrQueued--; clearTimeout(this._retryTimeouts[id]); var storedItemIndex = qq.indexOf(this._storedIds, id); if (!this._options.autoUpload && storedItemIndex >= 0) { this._storedIds.splice(storedItemIndex, 1); } this._uploadData.setStatus(id, qq.status.CANCELED); }, _isDeletePossible: function() { if (!qq.DeleteFileAjaxRequester || !this._options.deleteFile.enabled) { return false; } if (this._options.cors.expected) { if (qq.supportedFeatures.deleteFileCorsXhr) { return true; } if (qq.supportedFeatures.deleteFileCorsXdr && this._options.cors.allowXdr) { return true; } return false; } return true; }, _onSubmitDelete: function(id, onSuccessCallback, additionalMandatedParams) { var uuid = this.getUuid(id), adjustedOnSuccessCallback; if (onSuccessCallback) { adjustedOnSuccessCallback = qq.bind(onSuccessCallback, this, id, uuid, additionalMandatedParams); } if (this._isDeletePossible()) { this._handleCheckedCallback({ name: "onSubmitDelete", callback: qq.bind(this._options.callbacks.onSubmitDelete, this, id), onSuccess: adjustedOnSuccessCallback || qq.bind(this._deleteHandler.sendDelete, this, id, uuid, additionalMandatedParams), identifier: id }); return true; } else { this.log("Delete request ignored for ID " + id + ", delete feature is disabled or request not possible " + "due to CORS on a user agent that does not support pre-flighting.", "warn"); return false; } }, _onDelete: function(id) { this._uploadData.setStatus(id, qq.status.DELETING); }, _onDeleteComplete: function(id, xhrOrXdr, isError) { var name = this.getName(id); if (isError) { this._uploadData.setStatus(id, qq.status.DELETE_FAILED); this.log("Delete request for '" + name + "' has failed.", "error"); // For error reporing, we only have accesss to the response status if this is not // an `XDomainRequest`. if (xhrOrXdr.withCredentials === undefined) { this._options.callbacks.onError(id, name, "Delete request failed", xhrOrXdr); } else { this._options.callbacks.onError(id, name, "Delete request failed with response code " + xhrOrXdr.status, xhrOrXdr); } } else { this._netUploadedOrQueued--; this._netUploaded--; this._handler.expunge(id); this._uploadData.setStatus(id, qq.status.DELETED); this.log("Delete request for '" + name + "' has succeeded."); } }, _onUpload: function(id, name) { this._uploadData.setStatus(id, qq.status.UPLOADING); }, _onUploadChunk: function(id, chunkData) { //nothing to do in the base uploader }, _onInputChange: function(input) { var fileIndex; if (qq.supportedFeatures.ajaxUploading) { for (fileIndex = 0; fileIndex < input.files.length; fileIndex++) { this._annotateWithButtonId(input.files[fileIndex], input); } this.addFiles(input.files); } // Android 2.3.x will fire `onchange` even if no file has been selected else if (input.value.length > 0) { this.addFiles(input); } qq.each(this._buttons, function(idx, button) { button.reset(); }); }, _onBeforeAutoRetry: function(id, name) { this.log("Waiting " + this._options.retry.autoAttemptDelay + " seconds before retrying " + name + "..."); }, /** * Attempt to automatically retry a failed upload. * * @param id The file ID of the failed upload * @param name The name of the file associated with the failed upload * @param responseJSON Response from the server, parsed into a javascript object * @param xhr Ajax transport used to send the failed request * @param callback Optional callback to be invoked if a retry is prudent. * Invoked in lieu of asking the upload handler to retry. * @returns {boolean} true if an auto-retry will occur * @private */ _onAutoRetry: function(id, name, responseJSON, xhr, callback) { var self = this; self._preventRetries[id] = responseJSON[self._options.retry.preventRetryResponseProperty]; if (self._shouldAutoRetry(id, name, responseJSON)) { self._maybeParseAndSendUploadError.apply(self, arguments); self._options.callbacks.onAutoRetry(id, name, self._autoRetries[id] + 1); self._onBeforeAutoRetry(id, name); self._retryTimeouts[id] = setTimeout(function() { self.log("Retrying " + name + "..."); self._autoRetries[id]++; self._uploadData.setStatus(id, qq.status.UPLOAD_RETRYING); if (callback) { callback(id); } else { self._handler.retry(id); } }, self._options.retry.autoAttemptDelay * 1000); return true; } }, _shouldAutoRetry: function(id, name, responseJSON) { var uploadData = this._uploadData.retrieve({id: id}); /*jshint laxbreak: true */ if (!this._preventRetries[id] && this._options.retry.enableAuto && uploadData.status !== qq.status.PAUSED) { if (this._autoRetries[id] === undefined) { this._autoRetries[id] = 0; } return this._autoRetries[id] < this._options.retry.maxAutoAttempts; } return false; }, //return false if we should not attempt the requested retry _onBeforeManualRetry: function(id) { var itemLimit = this._options.validation.itemLimit; if (this._preventRetries[id]) { this.log("Retries are forbidden for id " + id, "warn"); return false; } else if (this._handler.isValid(id)) { var fileName = this.getName(id); if (this._options.callbacks.onManualRetry(id, fileName) === false) { return false; } if (itemLimit > 0 && this._netUploadedOrQueued+1 > itemLimit) { this._itemError("retryFailTooManyItems"); return false; } this.log("Retrying upload for '" + fileName + "' (id: " + id + ")..."); return true; } else { this.log("'" + id + "' is not a valid file ID", "error"); return false; } }, /** * Conditionally orders a manual retry of a failed upload. * * @param id File ID of the failed upload * @param callback Optional callback to invoke if a retry is prudent. * In lieu of asking the upload handler to retry. * @returns {boolean} true if a manual retry will occur * @private */ _manualRetry: function(id, callback) { if (this._onBeforeManualRetry(id)) { this._netUploadedOrQueued++; this._uploadData.setStatus(id, qq.status.UPLOAD_RETRYING); if (callback) { callback(id); } else { this._handler.retry(id); } return true; } }, _maybeParseAndSendUploadError: function(id, name, response, xhr) { // Assuming no one will actually set the response code to something other than 200 // and still set 'success' to true... if (!response.success){ if (xhr && xhr.status !== 200 && !response.error) { this._options.callbacks.onError(id, name, "XHR returned response code " + xhr.status, xhr); } else { var errorReason = response.error ? response.error : this._options.text.defaultResponseError; this._options.callbacks.onError(id, name, errorReason, xhr); } } }, _prepareItemsForUpload: function(items, params, endpoint) { if (items.length === 0) { this._itemError("noFilesError"); return; } var validationDescriptors = this._getValidationDescriptors(items), buttonId = this._getButtonId(items[0].file), button = this._getButton(buttonId); this._handleCheckedCallback({ name: "onValidateBatch", callback: qq.bind(this._options.callbacks.onValidateBatch, this, validationDescriptors, button), onSuccess: qq.bind(this._onValidateBatchCallbackSuccess, this, validationDescriptors, items, params, endpoint, button), onFailure: qq.bind(this._onValidateBatchCallbackFailure, this, items), identifier: "batch validation" }); }, _upload: function(id, params, endpoint) { var name = this.getName(id); if (params) { this.setParams(params, id); } if (endpoint) { this.setEndpoint(endpoint, id); } this._handleCheckedCallback({ name: "onSubmit", callback: qq.bind(this._options.callbacks.onSubmit, this, id, name), onSuccess: qq.bind(this._onSubmitCallbackSuccess, this, id, name), onFailure: qq.bind(this._fileOrBlobRejected, this, id, name), identifier: id }); }, _onSubmitCallbackSuccess: function(id, name) { this._onSubmit.apply(this, arguments); this._uploadData.setStatus(id, qq.status.SUBMITTED); this._onSubmitted.apply(this, arguments); this._options.callbacks.onSubmitted.apply(this, arguments); if (this._options.autoUpload) { this._uploadFile(id); } else { this._storeForLater(id); } }, _onSubmitted: function(id) { //nothing to do in the base uploader }, _storeForLater: function(id) { this._storedIds.push(id); }, _onValidateBatchCallbackSuccess: function(validationDescriptors, items, params, endpoint, button) { var errorMessage, itemLimit = this._options.validation.itemLimit, proposedNetFilesUploadedOrQueued = this._netUploadedOrQueued; if (itemLimit === 0 || proposedNetFilesUploadedOrQueued <= itemLimit) { if (items.length > 0) { this._handleCheckedCallback({ name: "onValidate", callback: qq.bind(this._options.callbacks.onValidate, this, validationDescriptors[0], button), onSuccess: qq.bind(this._onValidateCallbackSuccess, this, items, 0, params, endpoint), onFailure: qq.bind(this._onValidateCallbackFailure, this, items, 0, params, endpoint), identifier: "Item '" + items[0].file.name + "', size: " + items[0].file.size }); } else { this._itemError("noFilesError"); } } else { this._onValidateBatchCallbackFailure(items); errorMessage = this._options.messages.tooManyItemsError .replace(/\{netItems\}/g, proposedNetFilesUploadedOrQueued) .replace(/\{itemLimit\}/g, itemLimit); this._batchError(errorMessage); } }, _onValidateBatchCallbackFailure: function(fileWrappers) { var self = this; qq.each(fileWrappers, function(idx, fileWrapper) { self._fileOrBlobRejected(fileWrapper.id); }); }, _onValidateCallbackSuccess: function(items, index, params, endpoint) { var self = this, nextIndex = index+1, validationDescriptor = this._getValidationDescriptor(items[index].file); this._validateFileOrBlobData(items[index], validationDescriptor) .then( function() { self._upload(items[index].id, params, endpoint); self._maybeProcessNextItemAfterOnValidateCallback(true, items, nextIndex, params, endpoint); }, function() { self._maybeProcessNextItemAfterOnValidateCallback(false, items, nextIndex, params, endpoint); } ); }, _onValidateCallbackFailure: function(items, index, params, endpoint) { var nextIndex = index+ 1; this._fileOrBlobRejected(items[0].id, items[0].file.name); this._maybeProcessNextItemAfterOnValidateCallback(false, items, nextIndex, params, endpoint); }, _maybeProcessNextItemAfterOnValidateCallback: function(validItem, items, index, params, endpoint) { var self = this; if (items.length > index) { if (validItem || !this._options.validation.stopOnFirstInvalidFile) { //use setTimeout to prevent a stack overflow with a large number of files in the batch & non-promissory callbacks setTimeout(function() { var validationDescriptor = self._getValidationDescriptor(items[index].file); self._handleCheckedCallback({ name: "onValidate", callback: qq.bind(self._options.callbacks.onValidate, self, items[index].file), onSuccess: qq.bind(self._onValidateCallbackSuccess, self, items, index, params, endpoint), onFailure: qq.bind(self._onValidateCallbackFailure, self, items, index, params, endpoint), identifier: "Item '" + validationDescriptor.name + "', size: " + validationDescriptor.size }); }, 0); } else if (!validItem) { for (; index < items.length; index++) { self._fileOrBlobRejected(items[index].id); } } } }, /** * Performs some internal validation checks on an item, defined in the `validation` option. * * @param fileWrapper Wrapper containing a `file` along with an `id` * @param validationDescriptor Normalized information about the item (`size`, `name`). * @returns qq.Promise with appropriate callbacks invoked depending on the validity of the file * @private */ _validateFileOrBlobData: function(fileWrapper, validationDescriptor) { var self = this, file = fileWrapper.file, name = validationDescriptor.name, size = validationDescriptor.size, buttonId = this._getButtonId(file), validationBase = this._getValidationBase(buttonId), validityChecker = new qq.Promise(); validityChecker.then( function() {}, function() { self._fileOrBlobRejected(fileWrapper.id, name); }); if (qq.isFileOrInput(file) && !this._isAllowedExtension(validationBase.allowedExtensions, name)) { this._itemError("typeError", name, file); return validityChecker.failure(); } if (size === 0) { this._itemError("emptyError", name, file); return validityChecker.failure(); } if (size && validationBase.sizeLimit && size > validationBase.sizeLimit) { this._itemError("sizeError", name, file); return validityChecker.failure(); } if (size && size < validationBase.minSizeLimit) { this._itemError("minSizeError", name, file); return validityChecker.failure(); } if (qq.ImageValidation && qq.supportedFeatures.imagePreviews && qq.isFile(file)) { new qq.ImageValidation(file, qq.bind(self.log, self)).validate(validationBase.image).then( validityChecker.success, function(errorCode) { self._itemError(errorCode + "ImageError", name, file); validityChecker.failure(); } ); } else { validityChecker.success(); } return validityChecker; }, _fileOrBlobRejected: function(id) { this._netUploadedOrQueued--; this._uploadData.setStatus(id, qq.status.REJECTED); }, /** * Constructs and returns a message that describes an item/file error. Also calls `onError` callback. * * @param code REQUIRED - a code that corresponds to a stock message describing this type of error * @param maybeNameOrNames names of the items that have failed, if applicable * @param item `File`, `Blob`, or `<input type="file">` * @private */ _itemError: function(code, maybeNameOrNames, item) { var message = this._options.messages[code], allowedExtensions = [], names = [].concat(maybeNameOrNames), name = names[0], buttonId = this._getButtonId(item), validationBase = this._getValidationBase(buttonId), extensionsForMessage, placeholderMatch; function r(name, replacement){ message = message.replace(name, replacement); } qq.each(validationBase.allowedExtensions, function(idx, allowedExtension) { /** * If an argument is not a string, ignore it. Added when a possible issue with MooTools hijacking the * `allowedExtensions` array was discovered. See case #735 in the issue tracker for more details. */ if (qq.isString(allowedExtension)) { allowedExtensions.push(allowedExtension); } }); extensionsForMessage = allowedExtensions.join(", ").toLowerCase(); r("{file}", this._options.formatFileName(name)); r("{extensions}", extensionsForMessage); r("{sizeLimit}", this._formatSize(validationBase.sizeLimit)); r("{minSizeLimit}", this._formatSize(validationBase.minSizeLimit)); placeholderMatch = message.match(/(\{\w+\})/g); if (placeholderMatch !== null) { qq.each(placeholderMatch, function(idx, placeholder) { r(placeholder, names[idx]); }); } this._options.callbacks.onError(null, name, message, undefined); return message; }, _batchError: function(message) { this._options.callbacks.onError(null, null, message, undefined); }, _isAllowedExtension: function(allowed, fileName) { var valid = false; if (!allowed.length) { return true; } qq.each(allowed, function(idx, allowedExt) { /** * If an argument is not a string, ignore it. Added when a possible issue with MooTools hijacking the * `allowedExtensions` array was discovered. See case #735 in the issue tracker for more details. */ if (qq.isString(allowedExt)) { /*jshint eqeqeq: true, eqnull: true*/ var extRegex = new RegExp("\\." + allowedExt + "$", "i"); if (fileName.match(extRegex) != null) { valid = true; return false; } } }); return valid; }, _formatSize: function(bytes){ var i = -1; do { bytes = bytes / 1000; i++; } while (bytes > 999); return Math.max(bytes, 0.1).toFixed(1) + this._options.text.sizeSymbols[i]; }, _wrapCallbacks: function() { var self, safeCallback; self = this; safeCallback = function(name, callback, args) { var errorMsg; try { return callback.apply(self, args); } catch (exception) { errorMsg = exception.message || exception.toString(); self.log("Caught exception in '" + name + "' callback - " + errorMsg, "error"); } }; /* jshint forin: false, loopfunc: true */ for (var prop in this._options.callbacks) { (function() { var callbackName, callbackFunc; callbackName = prop; callbackFunc = self._options.callbacks[callbackName]; self._options.callbacks[callbackName] = function() { return safeCallback(callbackName, callbackFunc, arguments); }; }()); } }, _parseFileOrBlobDataName: function(fileOrBlobData) { var name; if (qq.isFileOrInput(fileOrBlobData)) { if (fileOrBlobData.value) { // it is a file input // get input value and remove path to normalize name = fileOrBlobData.value.replace(/.*(\/|\\)/, ""); } else { // fix missing properties in Safari 4 and firefox 11.0a2 name = (fileOrBlobData.fileName !== null && fileOrBlobData.fileName !== undefined) ? fileOrBlobData.fileName : fileOrBlobData.name; } } else { name = fileOrBlobData.name; } return name; }, _parseFileOrBlobDataSize: function(fileOrBlobData) { var size; if (qq.isFileOrInput(fileOrBlobData)) { if (fileOrBlobData.value === undefined) { // fix missing properties in Safari 4 and firefox 11.0a2 size = (fileOrBlobData.fileSize !== null && fileOrBlobData.fileSize !== undefined) ? fileOrBlobData.fileSize : fileOrBlobData.size; } } else { size = fileOrBlobData.blob.size; } return size; }, _getValidationDescriptor: function(fileOrBlobData) { var fileDescriptor = {}, name = this._parseFileOrBlobDataName(fileOrBlobData), size = this._parseFileOrBlobDataSize(fileOrBlobData); fileDescriptor.name = name; if (size !== undefined) { fileDescriptor.size = size; } return fileDescriptor; }, _getValidationDescriptors: function(fileWrappers) { var self = this, fileDescriptors = []; qq.each(fileWrappers, function(idx, fileWrapper) { fileDescriptors.push(self._getValidationDescriptor(fileWrapper.file)); }); return fileDescriptors; }, _createStore: function(initialValue, readOnlyValues) { var store = {}, catchall = initialValue, copy = function(orig) { if (qq.isObject(orig)) { return qq.extend({}, orig); } return orig; }, getReadOnlyValues = function() { if (qq.isFunction(readOnlyValues)) { return readOnlyValues(); } return readOnlyValues; }, includeReadOnlyValues = function(existing) { if (readOnlyValues && qq.isObject(existing)) { qq.extend(existing, getReadOnlyValues()); } }; return { set: function(val, id) { /*jshint eqeqeq: true, eqnull: true*/ if (id == null) { store = {}; catchall = copy(val); } else { store[id] = copy(val); } }, get: function(id) { var values; /*jshint eqeqeq: true, eqnull: true*/ if (id != null && store[id]) { values = store[id]; } else { values = catchall; } includeReadOnlyValues(values); return copy(values); }, remove: function(fileId) { return delete store[fileId]; }, reset: function() { store = {}; catchall = initialValue; } }; }, // Allows camera access on either the default or an extra button for iOS devices. _handleCameraAccess: function() { if (this._options.camera.ios && qq.ios()) { var acceptIosCamera = "image/*;capture=camera", button = this._options.camera.button, buttonId = button ? this._getButtonId(button) : this._defaultButtonId, optionRoot = this._options; // If we are not targeting the default button, it is an "extra" button if (buttonId && buttonId !== this._defaultButtonId) { optionRoot = this._extraButtonSpecs[buttonId]; } // Camera access won't work in iOS if the `multiple` attribute is present on the file input optionRoot.multiple = false; // update the options if (optionRoot.validation.acceptFiles === null) { optionRoot.validation.acceptFiles = acceptIosCamera; } else { optionRoot.validation.acceptFiles += "," + acceptIosCamera; } // update the already-created button qq.each(this._buttons, function(idx, button) { if (button.getButtonId() === buttonId) { button.setMultiple(optionRoot.multiple); button.setAcceptFiles(optionRoot.acceptFiles); return false; } }); } }, // Get the validation options for this button. Could be the default validation option // or a specific one assigned to this particular button. _getValidationBase: function(buttonId) { var extraButtonSpec = this._extraButtonSpecs[buttonId]; return extraButtonSpec ? extraButtonSpec.validation : this._options.validation; } }; }()); /*globals qq*/ (function(){ "use strict"; qq.FineUploaderBasic = function(o) { // These options define FineUploaderBasic mode. this._options = { debug: false, button: null, multiple: true, maxConnections: 3, disableCancelForFormUploads: false, autoUpload: true, request: { endpoint: "/server/upload", params: {}, paramsInBody: true, customHeaders: {}, forceMultipart: true, inputName: "qqfile", uuidName: "qquuid", totalFileSizeName: "qqtotalfilesize", filenameParam: "qqfilename" }, validation: { allowedExtensions: [], sizeLimit: 0, minSizeLimit: 0, itemLimit: 0, stopOnFirstInvalidFile: true, acceptFiles: null, image: { maxHeight: 0, maxWidth: 0, minHeight: 0, minWidth: 0 } }, callbacks: { onSubmit: function(id, name){}, onSubmitted: function(id, name){}, onComplete: function(id, name, responseJSON, maybeXhr){}, onAllComplete: function(successful, failed) {}, onCancel: function(id, name){}, onUpload: function(id, name){}, onUploadChunk: function(id, name, chunkData){}, onUploadChunkSuccess: function(id, chunkData, responseJSON, xhr){}, onResume: function(id, fileName, chunkData){}, onProgress: function(id, name, loaded, total){}, onError: function(id, name, reason, maybeXhrOrXdr) {}, onAutoRetry: function(id, name, attemptNumber) {}, onManualRetry: function(id, name) {}, onValidateBatch: function(fileOrBlobData) {}, onValidate: function(fileOrBlobData) {}, onSubmitDelete: function(id) {}, onDelete: function(id){}, onDeleteComplete: function(id, xhrOrXdr, isError){}, onPasteReceived: function(blob) {}, onStatusChange: function(id, oldStatus, newStatus) {}, onSessionRequestComplete: function(response, success, xhrOrXdr) {} }, messages: { typeError: "{file} has an invalid extension. Valid extension(s): {extensions}.", sizeError: "{file} is too large, maximum file size is {sizeLimit}.", minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.", emptyError: "{file} is empty, please select files again without it.", noFilesError: "No files to upload.", tooManyItemsError: "Too many items ({netItems}) would be uploaded. Item limit is {itemLimit}.", maxHeightImageError: "Image is too tall.", maxWidthImageError: "Image is too wide.", minHeightImageError: "Image is not tall enough.", minWidthImageError: "Image is not wide enough.", retryFailTooManyItems: "Retry failed - you have reached your file limit.", onLeave: "The files are being uploaded, if you leave now the upload will be canceled." }, retry: { enableAuto: false, maxAutoAttempts: 3, autoAttemptDelay: 5, preventRetryResponseProperty: "preventRetry" }, classes: { buttonHover: "qq-upload-button-hover", buttonFocus: "qq-upload-button-focus" }, chunking: { enabled: false, partSize: 2000000, paramNames: { partIndex: "qqpartindex", partByteOffset: "qqpartbyteoffset", chunkSize: "qqchunksize", totalFileSize: "qqtotalfilesize", totalParts: "qqtotalparts" } }, resume: { enabled: false, id: null, cookiesExpireIn: 7, //days paramNames: { resuming: "qqresume" } }, formatFileName: function(fileOrBlobName) { if (fileOrBlobName !== undefined && fileOrBlobName.length > 33) { fileOrBlobName = fileOrBlobName.slice(0, 19) + "..." + fileOrBlobName.slice(-14); } return fileOrBlobName; }, text: { defaultResponseError: "Upload failure reason unknown", sizeSymbols: ["kB", "MB", "GB", "TB", "PB", "EB"] }, deleteFile : { enabled: false, method: "DELETE", endpoint: "/server/upload", customHeaders: {}, params: {} }, cors: { expected: false, sendCredentials: false, allowXdr: false }, blobs: { defaultName: "misc_data" }, paste: { targetElement: null, defaultName: "pasted_image" }, camera: { ios: false, // if ios is true: button is null means target the default button, otherwise target the button specified button: null }, // This refers to additional upload buttons to be handled by Fine Uploader. // Each element is an object, containing `element` as the only required // property. The `element` must be a container that will ultimately // contain an invisible `<input type="file">` created by Fine Uploader. // Optional properties of each object include `multiple`, `validation`, // and `folders`. extraButtons: [], // Depends on the session module. Used to query the server for an initial file list // during initialization and optionally after a `reset`. session: { endpoint: null, params: {}, customHeaders: {}, refreshOnReset: true }, // Send parameters associated with an existing form along with the files form: { // Element ID, HTMLElement, or null element: "qq-form", // Overrides the base `autoUpload`, unless `element` is null. autoUpload: false, // true = upload files on form submission (and squelch submit event) interceptSubmit: true } }; // Replace any default options with user defined ones qq.extend(this._options, o, true); this._buttons = []; this._extraButtonSpecs = {}; this._buttonIdsForFileIds = []; this._wrapCallbacks(); this._disposeSupport = new qq.DisposeSupport(); this._storedIds = []; this._autoRetries = []; this._retryTimeouts = []; this._preventRetries = []; this._thumbnailUrls = []; this._netUploadedOrQueued = 0; this._netUploaded = 0; this._uploadData = this._createUploadDataTracker(); this._initFormSupportAndParams(); this._deleteFileParamsStore = this._createStore(this._options.deleteFile.params); this._endpointStore = this._createStore(this._options.request.endpoint); this._deleteFileEndpointStore = this._createStore(this._options.deleteFile.endpoint); this._handler = this._createUploadHandler(); this._deleteHandler = qq.DeleteFileAjaxRequester && this._createDeleteHandler(); if (this._options.button) { this._defaultButtonId = this._createUploadButton({element: this._options.button}).getButtonId(); } this._generateExtraButtonSpecs(); this._handleCameraAccess(); if (this._options.paste.targetElement) { if (qq.PasteSupport) { this._pasteHandler = this._createPasteHandler(); } else { qq.log("Paste support module not found", "info"); } } this._preventLeaveInProgress(); this._imageGenerator = qq.ImageGenerator && new qq.ImageGenerator(qq.bind(this.log, this)); this._refreshSessionData(); this._succeededSinceLastAllComplete = []; this._failedSinceLastAllComplete = []; }; // Define the private & public API methods. qq.FineUploaderBasic.prototype = qq.basePublicApi; qq.extend(qq.FineUploaderBasic.prototype, qq.basePrivateApi); }()); /*globals qq, XDomainRequest*/ /** Generic class for sending non-upload ajax requests and handling the associated responses **/ qq.AjaxRequester = function (o) { "use strict"; var log, shouldParamsBeInQueryString, queue = [], requestData = {}, options = { validMethods: ["POST"], method: "POST", contentType: "application/x-www-form-urlencoded", maxConnections: 3, customHeaders: {}, endpointStore: {}, paramsStore: {}, mandatedParams: {}, allowXRequestedWithAndCacheControl: true, successfulResponseCodes: { "DELETE": [200, 202, 204], "POST": [200, 204], "GET": [200] }, cors: { expected: false, sendCredentials: false }, log: function (str, level) {}, onSend: function (id) {}, onComplete: function (id, xhrOrXdr, isError) {}, onProgress: null }; qq.extend(options, o); log = options.log; if (qq.indexOf(options.validMethods, options.method) < 0) { throw new Error("'" + options.method + "' is not a supported method for this type of request!"); } // [Simple methods](http://www.w3.org/TR/cors/#simple-method) // are defined by the W3C in the CORS spec as a list of methods that, in part, // make a CORS request eligible to be exempt from preflighting. function isSimpleMethod() { return qq.indexOf(["GET", "POST", "HEAD"], options.method) >= 0; } // [Simple headers](http://www.w3.org/TR/cors/#simple-header) // are defined by the W3C in the CORS spec as a list of headers that, in part, // make a CORS request eligible to be exempt from preflighting. function containsNonSimpleHeaders(headers) { var containsNonSimple = false; qq.each(containsNonSimple, function(idx, header) { if (qq.indexOf(["Accept", "Accept-Language", "Content-Language", "Content-Type"], header) < 0) { containsNonSimple = true; return false; } }); return containsNonSimple; } function isXdr(xhr) { //The `withCredentials` test is a commonly accepted way to determine if XHR supports CORS. return options.cors.expected && xhr.withCredentials === undefined; } // Returns either a new `XMLHttpRequest` or `XDomainRequest` instance. function getCorsAjaxTransport() { var xhrOrXdr; if (window.XMLHttpRequest || window.ActiveXObject) { xhrOrXdr = qq.createXhrInstance(); if (xhrOrXdr.withCredentials === undefined) { xhrOrXdr = new XDomainRequest(); } } return xhrOrXdr; } // Returns either a new XHR/XDR instance, or an existing one for the associated `File` or `Blob`. function getXhrOrXdr(id, dontCreateIfNotExist) { var xhrOrXdr = requestData[id].xhr; if (!xhrOrXdr && !dontCreateIfNotExist) { if (options.cors.expected) { xhrOrXdr = getCorsAjaxTransport(); } else { xhrOrXdr = qq.createXhrInstance(); } requestData[id].xhr = xhrOrXdr; } return xhrOrXdr; } // Removes element from queue, sends next request function dequeue(id) { var i = qq.indexOf(queue, id), max = options.maxConnections, nextId; delete requestData[id]; queue.splice(i, 1); if (queue.length >= max && i < max) { nextId = queue[max - 1]; sendRequest(nextId); } } function onComplete(id, xdrError) { var xhr = getXhrOrXdr(id), method = options.method, isError = xdrError === true; dequeue(id); if (isError) { log(method + " request for " + id + " has failed", "error"); } else if (!isXdr(xhr) && !isResponseSuccessful(xhr.status)) { isError = true; log(method + " request for " + id + " has failed - response code " + xhr.status, "error"); } options.onComplete(id, xhr, isError); } function getParams(id) { var onDemandParams = requestData[id].additionalParams, mandatedParams = options.mandatedParams, params; if (options.paramsStore.get) { params = options.paramsStore.get(id); } if (onDemandParams) { qq.each(onDemandParams, function (name, val) { params = params || {}; params[name] = val; }); } if (mandatedParams) { qq.each(mandatedParams, function (name, val) { params = params || {}; params[name] = val; }); } return params; } function sendRequest(id) { var xhr = getXhrOrXdr(id), method = options.method, params = getParams(id), payload = requestData[id].payload, url; options.onSend(id); url = createUrl(id, params); // XDR and XHR status detection APIs differ a bit. if (isXdr(xhr)) { xhr.onload = getXdrLoadHandler(id); xhr.onerror = getXdrErrorHandler(id); } else { xhr.onreadystatechange = getXhrReadyStateChangeHandler(id); } registerForUploadProgress(id); // The last parameter is assumed to be ignored if we are actually using `XDomainRequest`. xhr.open(method, url, true); // Instruct the transport to send cookies along with the CORS request, // unless we are using `XDomainRequest`, which is not capable of this. if (options.cors.expected && options.cors.sendCredentials && !isXdr(xhr)) { xhr.withCredentials = true; } setHeaders(id); log("Sending " + method + " request for " + id); if (payload) { xhr.send(payload); } else if (shouldParamsBeInQueryString || !params) { xhr.send(); } else if (params && options.contentType && options.contentType.toLowerCase().indexOf("application/x-www-form-urlencoded") >= 0) { xhr.send(qq.obj2url(params, "")); } else if (params && options.contentType && options.contentType.toLowerCase().indexOf("application/json") >= 0) { xhr.send(JSON.stringify(params)); } else { xhr.send(params); } return xhr; } function createUrl(id, params) { var endpoint = options.endpointStore.get(id), addToPath = requestData[id].addToPath; /*jshint -W116,-W041 */ if (addToPath != undefined) { endpoint += "/" + addToPath; } if (shouldParamsBeInQueryString && params) { return qq.obj2url(params, endpoint); } else { return endpoint; } } // Invoked by the UA to indicate a number of possible states that describe // a live `XMLHttpRequest` transport. function getXhrReadyStateChangeHandler(id) { return function () { if (getXhrOrXdr(id).readyState === 4) { onComplete(id); } }; } function registerForUploadProgress(id) { var onProgress = options.onProgress; if (onProgress) { getXhrOrXdr(id).upload.onprogress = function(e) { if (e.lengthComputable) { onProgress(id, e.loaded, e.total); } }; } } // This will be called by IE to indicate **success** for an associated // `XDomainRequest` transported request. function getXdrLoadHandler(id) { return function () { onComplete(id); }; } // This will be called by IE to indicate **failure** for an associated // `XDomainRequest` transported request. function getXdrErrorHandler(id) { return function () { onComplete(id, true); }; } function setHeaders(id) { var xhr = getXhrOrXdr(id), customHeaders = options.customHeaders, onDemandHeaders = requestData[id].additionalHeaders || {}, method = options.method, allHeaders = {}; // If XDomainRequest is being used, we can't set headers, so just ignore this block. if (!isXdr(xhr)) { // Only attempt to add X-Requested-With & Cache-Control if permitted if (options.allowXRequestedWithAndCacheControl) { // Do not add X-Requested-With & Cache-Control if this is a cross-origin request // OR the cross-origin request contains a non-simple method or header. // This is done to ensure a preflight is not triggered exclusively based on the // addition of these 2 non-simple headers. if (!options.cors.expected || (!isSimpleMethod() || containsNonSimpleHeaders(customHeaders))) { xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); xhr.setRequestHeader("Cache-Control", "no-cache"); } } if (options.contentType && (method === "POST" || method === "PUT")) { xhr.setRequestHeader("Content-Type", options.contentType); } qq.extend(allHeaders, qq.isFunction(customHeaders) ? customHeaders(id) : customHeaders); qq.extend(allHeaders, onDemandHeaders); qq.each(allHeaders, function (name, val) { xhr.setRequestHeader(name, val); }); } } function isResponseSuccessful(responseCode) { return qq.indexOf(options.successfulResponseCodes[options.method], responseCode) >= 0; } function prepareToSend(id, addToPath, additionalParams, additionalHeaders, payload) { requestData[id] = { addToPath: addToPath, additionalParams: additionalParams, additionalHeaders: additionalHeaders, payload: payload }; var len = queue.push(id); // if too many active connections, wait... if (len <= options.maxConnections) { return sendRequest(id); } } shouldParamsBeInQueryString = options.method === "GET" || options.method === "DELETE"; qq.extend(this, { // Start the process of sending the request. The ID refers to the file associated with the request. initTransport: function(id) { var path, params, headers, payload, cacheBuster; return { // Optionally specify the end of the endpoint path for the request. withPath: function(appendToPath) { path = appendToPath; return this; }, // Optionally specify additional parameters to send along with the request. // These will be added to the query string for GET/DELETE requests or the payload // for POST/PUT requests. The Content-Type of the request will be used to determine // how these parameters should be formatted as well. withParams: function(additionalParams) { params = additionalParams; return this; }, // Optionally specify additional headers to send along with the request. withHeaders: function(additionalHeaders) { headers = additionalHeaders; return this; }, // Optionally specify a payload/body for the request. withPayload: function(thePayload) { payload = thePayload; return this; }, // Appends a cache buster (timestamp) to the request URL as a query parameter (only if GET or DELETE) withCacheBuster: function() { cacheBuster = true; return this; }, // Send the constructed request. send: function() { if (cacheBuster && qq.indexOf(["GET", "DELETE"], options.method) >= 0) { params.qqtimestamp = new Date().getTime(); } return prepareToSend(id, path, params, headers, payload); } }; }, canceled: function(id) { dequeue(id); } }); }; /*globals qq*/ /** * Base upload handler module. Delegates to more specific handlers. * * @param o Options. Passed along to the specific handler submodule as well. * @param namespace [optional] Namespace for the specific handler. */ qq.UploadHandler = function(o, namespace) { "use strict"; var queue = [], options, log, handlerImpl; // Default options, can be overridden by the user options = { debug: false, forceMultipart: true, paramsInBody: false, paramsStore: {}, endpointStore: {}, filenameParam: "qqfilename", cors: { expected: false, sendCredentials: false }, maxConnections: 3, // maximum number of concurrent uploads uuidName: "qquuid", totalFileSizeName: "qqtotalfilesize", chunking: { enabled: false, partSize: 2000000, //bytes paramNames: { partIndex: "qqpartindex", partByteOffset: "qqpartbyteoffset", chunkSize: "qqchunksize", totalParts: "qqtotalparts", filename: "qqfilename" } }, resume: { enabled: false, id: null, cookiesExpireIn: 7, //days paramNames: { resuming: "qqresume" } }, log: function(str, level) {}, onProgress: function(id, fileName, loaded, total){}, onComplete: function(id, fileName, response, xhr){}, onCancel: function(id, fileName){}, onUpload: function(id, fileName){}, onUploadChunk: function(id, fileName, chunkData){}, onUploadChunkSuccess: function(id, chunkData, response, xhr){}, onAutoRetry: function(id, fileName, response, xhr){}, onResume: function(id, fileName, chunkData){}, onUuidChanged: function(id, newUuid){}, getName: function(id) {} }; qq.extend(options, o); log = options.log; /** * Removes element from queue, starts upload of next */ function dequeue(id) { var i = qq.indexOf(queue, id), max = options.maxConnections, nextId; if (i >= 0) { queue.splice(i, 1); if (queue.length >= max && i < max){ nextId = queue[max-1]; handlerImpl.upload(nextId); } } } function cancelSuccess(id) { log("Cancelling " + id); options.paramsStore.remove(id); dequeue(id); } function determineHandlerImpl() { var handlerType = namespace ? qq[namespace] : qq, handlerModuleSubtype = qq.supportedFeatures.ajaxUploading ? "Xhr" : "Form"; handlerImpl = new handlerType["UploadHandler" + handlerModuleSubtype]( options, {onUploadComplete: dequeue, onUuidChanged: options.onUuidChanged, getName: options.getName, getUuid: options.getUuid, getSize: options.getSize, log: log} ); } qq.extend(this, { /** * Adds file or file input to the queue * @returns id **/ add: function(id, file) { return handlerImpl.add.apply(this, arguments); }, /** * Sends the file identified by id */ upload: function(id) { var len = queue.push(id); // if too many active uploads, wait... if (len <= options.maxConnections){ handlerImpl.upload(id); return true; } return false; }, retry: function(id) { var i = qq.indexOf(queue, id); if (i >= 0) { return handlerImpl.upload(id, true); } else { return this.upload(id); } }, /** * Cancels file upload by id */ cancel: function(id) { var cancelRetVal = handlerImpl.cancel(id); if (cancelRetVal instanceof qq.Promise) { cancelRetVal.then(function() { cancelSuccess(id); }); } else if (cancelRetVal !== false) { cancelSuccess(id); } }, /** * Cancels all queued or in-progress uploads */ cancelAll: function() { var self = this, queueCopy = []; qq.extend(queueCopy, queue); qq.each(queueCopy, function(idx, fileId) { self.cancel(fileId); }); queue = []; }, getFile: function(id) { if (handlerImpl.getFile) { return handlerImpl.getFile(id); } }, getInput: function(id) { if (handlerImpl.getInput) { return handlerImpl.getInput(id); } }, reset: function() { log("Resetting upload handler"); this.cancelAll(); queue = []; handlerImpl.reset(); }, expunge: function(id) { if (this.isValid(id)) { return handlerImpl.expunge(id); } }, /** * Determine if the file exists. */ isValid: function(id) { return handlerImpl.isValid(id); }, getResumableFilesData: function() { if (handlerImpl.getResumableFilesData) { return handlerImpl.getResumableFilesData(); } return []; }, /** * This may or may not be implemented, depending on the handler. For handlers where a third-party ID is * available (such as the "key" for Amazon S3), this will return that value. Otherwise, the return value * will be undefined. * * @param id Internal file ID * @returns {*} Some identifier used by a 3rd-party service involved in the upload process */ getThirdPartyFileId: function(id) { if (handlerImpl.getThirdPartyFileId && this.isValid(id)) { return handlerImpl.getThirdPartyFileId(id); } }, /** * Attempts to pause the associated upload if the specific handler supports this and the file is "valid". * @param id ID of the upload/file to pause * @returns {boolean} true if the upload was paused */ pause: function(id) { if (handlerImpl.pause && this.isValid(id) && handlerImpl.pause(id)) { dequeue(id); return true; } } }); determineHandlerImpl(); }; /* globals qq */ /** * Common APIs exposed to creators of upload via form/iframe handlers. This is reused and possibly overridden * in some cases by specific form upload handlers. * * @constructor */ qq.AbstractUploadHandlerForm = function(spec) { "use strict"; var options = spec.options, handler = this, proxy = spec.proxy, formHandlerInstanceId = qq.getUniqueId(), onloadCallbacks = {}, detachLoadEvents = {}, postMessageCallbackTimers = {}, isCors = options.isCors, fileState = {}, inputName = options.inputName, onCancel = proxy.onCancel, onUuidChanged = proxy.onUuidChanged, getName = proxy.getName, getUuid = proxy.getUuid, log = proxy.log, corsMessageReceiver = new qq.WindowReceiveMessage({log: log}); /** * Remove any trace of the file from the handler. * * @param id ID of the associated file */ function expungeFile(id) { delete detachLoadEvents[id]; delete fileState[id]; // If we are dealing with CORS, we might still be waiting for a response from a loaded iframe. // In that case, terminate the timer waiting for a message from the loaded iframe // and stop listening for any more messages coming from this iframe. if (isCors) { clearTimeout(postMessageCallbackTimers[id]); delete postMessageCallbackTimers[id]; corsMessageReceiver.stopReceivingMessages(id); } var iframe = document.getElementById(handler._getIframeName(id)); if (iframe) { // To cancel request set src to something else. We use src="javascript:false;" // because it doesn't trigger ie6 prompt on https iframe.setAttribute("src", "java" + String.fromCharCode(115) + "cript:false;"); //deal with "JSLint: javascript URL" warning, which apparently cannot be turned off qq(iframe).remove(); } } /** * If we are in CORS mode, we must listen for messages (containing the server response) from the associated * iframe, since we cannot directly parse the content of the iframe due to cross-origin restrictions. * * @param iframe Listen for messages on this iframe. * @param callback Invoke this callback with the message from the iframe. */ function registerPostMessageCallback(iframe, callback) { var iframeName = iframe.id, fileId = getFileIdForIframeName(iframeName), uuid = getUuid(fileId); onloadCallbacks[uuid] = callback; // When the iframe has loaded (after the server responds to an upload request) // declare the attempt a failure if we don't receive a valid message shortly after the response comes in. detachLoadEvents[fileId] = qq(iframe).attach("load", function() { if (fileState[fileId].input) { log("Received iframe load event for CORS upload request (iframe name " + iframeName + ")"); postMessageCallbackTimers[iframeName] = setTimeout(function() { var errorMessage = "No valid message received from loaded iframe for iframe name " + iframeName; log(errorMessage, "error"); callback({ error: errorMessage }); }, 1000); } }); // Listen for messages coming from this iframe. When a message has been received, cancel the timer // that declares the upload a failure if a message is not received within a reasonable amount of time. corsMessageReceiver.receiveMessage(iframeName, function(message) { log("Received the following window message: '" + message + "'"); var fileId = getFileIdForIframeName(iframeName), response = handler._parseJsonResponse(fileId, message), uuid = response.uuid, onloadCallback; if (uuid && onloadCallbacks[uuid]) { log("Handling response for iframe name " + iframeName); clearTimeout(postMessageCallbackTimers[iframeName]); delete postMessageCallbackTimers[iframeName]; handler._detachLoadEvent(iframeName); onloadCallback = onloadCallbacks[uuid]; delete onloadCallbacks[uuid]; corsMessageReceiver.stopReceivingMessages(iframeName); onloadCallback(response); } else if (!uuid) { log("'" + message + "' does not contain a UUID - ignoring."); } }); } /** * Generates an iframe to be used as a target for upload-related form submits. This also adds the iframe * to the current `document`. Note that the iframe is hidden from view. * * @param name Name of the iframe. * @returns {HTMLIFrameElement} The created iframe */ function initIframeForUpload(name) { var iframe = qq.toElement("<iframe src='javascript:false;' name='" + name + "' />"); iframe.setAttribute("id", name); iframe.style.display = "none"; document.body.appendChild(iframe); return iframe; } /** * @param iframeName `document`-unique Name of the associated iframe * @returns {*} ID of the associated file */ function getFileIdForIframeName(iframeName) { return iframeName.split("_")[0]; } qq.extend(this, { add: function(id, fileInput) { fileState[id] = {input: fileInput}; fileInput.setAttribute("name", inputName); // remove file input from DOM if (fileInput.parentNode){ qq(fileInput).remove(); } }, getInput: function(id) { return fileState[id].input; }, isValid: function(id) { return fileState[id] !== undefined && fileState[id].input !== undefined; }, reset: function() { fileState.length = 0; }, expunge: function(id) { return expungeFile(id); }, cancel: function(id) { var onCancelRetVal = onCancel(id, getName(id)); if (onCancelRetVal instanceof qq.Promise) { return onCancelRetVal.then(function() { this.expunge(id); }); } else if (onCancelRetVal !== false) { this.expunge(id); return true; } return false; }, upload: function(id) { // implementation-specific }, /** * @param fileId ID of the associated file * @returns {string} The `document`-unique name of the iframe */ _getIframeName: function(fileId) { return fileId + "_" + formHandlerInstanceId; }, /** * Creates an iframe with a specific document-unique name. * * @param id ID of the associated file * @returns {HTMLIFrameElement} */ _createIframe: function(id) { var iframeName = handler._getIframeName(id); return initIframeForUpload(iframeName); }, /** * @param id ID of the associated file * @param innerHtmlOrMessage JSON message * @returns {*} The parsed response, or an empty object if the response could not be parsed */ _parseJsonResponse: function(id, innerHtmlOrMessage) { var response; try { response = qq.parseJson(innerHtmlOrMessage); if (response.newUuid !== undefined) { onUuidChanged(id, response.newUuid); } } catch(error) { log("Error when attempting to parse iframe upload response (" + error.message + ")", "error"); response = {}; } return response; }, /** * Generates a form element and appends it to the `document`. When the form is submitted, a specific iframe is targeted. * The name of the iframe is passed in as a property of the spec parameter, and must be unique in the `document`. Note * that the form is hidden from view. * * @param spec An object containing various properties to be used when constructing the form. Required properties are * currently: `method`, `endpoint`, `params`, `paramsInBody`, and `targetName`. * @returns {HTMLFormElement} The created form */ _initFormForUpload: function(spec) { var method = spec.method, endpoint = spec.endpoint, params = spec.params, paramsInBody = spec.paramsInBody, targetName = spec.targetName, form = qq.toElement("<form method='" + method + "' enctype='multipart/form-data'></form>"), url = endpoint; if (paramsInBody) { qq.obj2Inputs(params, form); } else { url = qq.obj2url(params, endpoint); } form.setAttribute("action", url); form.setAttribute("target", targetName); form.style.display = "none"; document.body.appendChild(form); return form; }, /** * This function either delegates to a more specific message handler if CORS is involved, * or simply registers a callback when the iframe has been loaded that invokes the passed callback * after determining if the content of the iframe is accessible. * * @param iframe Associated iframe * @param callback Callback to invoke after we have determined if the iframe content is accessible. */ _attachLoadEvent: function(iframe, callback) { /*jslint eqeq: true*/ var responseDescriptor; if (isCors) { registerPostMessageCallback(iframe, callback); } else { detachLoadEvents[iframe.id] = qq(iframe).attach("load", function(){ log("Received response for " + iframe.id); // when we remove iframe from dom // the request stops, but in IE load // event fires if (!iframe.parentNode){ return; } try { // fixing Opera 10.53 if (iframe.contentDocument && iframe.contentDocument.body && iframe.contentDocument.body.innerHTML == "false"){ // In Opera event is fired second time // when body.innerHTML changed from false // to server response approx. after 1 sec // when we upload file with iframe return; } } catch (error) { //IE may throw an "access is denied" error when attempting to access contentDocument on the iframe in some cases log("Error when attempting to access iframe during handling of upload response (" + error.message + ")", "error"); responseDescriptor = {success: false}; } callback(responseDescriptor); }); } }, /** * Called when we are no longer interested in being notified when an iframe has loaded. * * @param id Associated file ID */ _detachLoadEvent: function(id) { if (detachLoadEvents[id] !== undefined) { detachLoadEvents[id](); delete detachLoadEvents[id]; } }, _getFileState: function(id) { return fileState[id]; } }); }; /* globals qq */ /** * Common API exposed to creators of XHR handlers. This is reused and possibly overriding in some cases by specific * XHR upload handlers. * * @constructor */ qq.AbstractUploadHandlerXhr = function(spec) { "use strict"; var publicApi = this, options = spec.options, proxy = spec.proxy, fileState = {}, chunking = options.chunking, onUpload = proxy.onUpload, onCancel = proxy.onCancel, getName = proxy.getName, getSize = proxy.getSize, log = proxy.log; function getChunk(fileOrBlob, startByte, endByte) { if (fileOrBlob.slice) { return fileOrBlob.slice(startByte, endByte); } else if (fileOrBlob.mozSlice) { return fileOrBlob.mozSlice(startByte, endByte); } else if (fileOrBlob.webkitSlice) { return fileOrBlob.webkitSlice(startByte, endByte); } } function abort(id) { var xhr = fileState[id].xhr, ajaxRequester = fileState[id].currentAjaxRequester; xhr.onreadystatechange = null; xhr.upload.onprogress = null; xhr.abort(); ajaxRequester && ajaxRequester.canceled && ajaxRequester.canceled(id); } qq.extend(this, { /** * Adds File or Blob to the queue **/ add: function(id, fileOrBlobData) { if (qq.isFile(fileOrBlobData)) { fileState[id] = {file: fileOrBlobData}; } else if (qq.isBlob(fileOrBlobData.blob)) { fileState[id] = {blobData: fileOrBlobData}; } else { throw new Error("Passed obj is not a File or BlobData (in qq.UploadHandlerXhr)"); } }, getFile: function(id) { if (fileState[id]) { return fileState[id].file || fileState[id].blobData.blob; } }, isValid: function(id) { return fileState[id] !== undefined; }, reset: function() { fileState.length = 0; }, expunge: function(id) { var xhr = fileState[id].xhr; xhr && abort(id); delete fileState[id]; }, /** * Sends the file identified by id to the server */ upload: function(id, retry) { fileState[id] && delete fileState[id].paused; return onUpload(id, retry); }, cancel: function(id) { var onCancelRetVal = onCancel(id, getName(id)); if (onCancelRetVal instanceof qq.Promise) { return onCancelRetVal.then(function() { fileState[id].canceled = true; this.expunge(id); }); } else if (onCancelRetVal !== false) { fileState[id].canceled = true; this.expunge(id); return true; } return false; }, pause: function(id) { var xhr = fileState[id].xhr; if(xhr) { log(qq.format("Aborting XHR upload for {} '{}' due to pause instruction.", id, getName(id))); fileState[id].paused = true; abort(id); return true; } }, /** * Creates an XHR instance for this file and stores it in the fileState. * * @param id File ID * @returns {XMLHttpRequest} */ _createXhr: function(id) { return this._registerXhr(id, qq.createXhrInstance()); }, /** * Registers an XHR transport instance created elsewhere. * * @param id ID of the associated file * @param xhr XMLHttpRequest object instance * @returns {XMLHttpRequest} */ _registerXhr: function(id, xhr, ajaxRequester) { fileState[id].xhr = xhr; fileState[id].currentAjaxRequester = ajaxRequester; return xhr; }, _getMimeType: function(id) { return publicApi.getFile(id).type; }, /** * @param id ID of the associated file * @returns {number} Number of parts this file can be divided into, or undefined if chunking is not supported in this UA */ _getTotalChunks: function(id) { if (chunking) { var fileSize = getSize(id), chunkSize = chunking.partSize; return Math.ceil(fileSize / chunkSize); } }, _getChunkData: function(id, chunkIndex) { var chunkSize = chunking.partSize, fileSize = getSize(id), fileOrBlob = publicApi.getFile(id), startBytes = chunkSize * chunkIndex, endBytes = startBytes+chunkSize >= fileSize ? fileSize : startBytes+chunkSize, totalChunks = this._getTotalChunks(id); return { part: chunkIndex, start: startBytes, end: endBytes, count: totalChunks, blob: getChunk(fileOrBlob, startBytes, endBytes), size: endBytes - startBytes }; }, _getChunkDataForCallback: function(chunkData) { return { partIndex: chunkData.part, startByte: chunkData.start + 1, endByte: chunkData.end, totalParts: chunkData.count }; }, _getFileState: function(id) { return fileState[id]; } }); }; /*globals qq */ /*jshint -W117 */ qq.WindowReceiveMessage = function(o) { "use strict"; var options = { log: function(message, level) {} }, callbackWrapperDetachers = {}; qq.extend(options, o); qq.extend(this, { receiveMessage : function(id, callback) { var onMessageCallbackWrapper = function(event) { callback(event.data); }; if (window.postMessage) { callbackWrapperDetachers[id] = qq(window).attach("message", onMessageCallbackWrapper); } else { log("iframe message passing not supported in this browser!", "error"); } }, stopReceivingMessages : function(id) { if (window.postMessage) { var detacher = callbackWrapperDetachers[id]; if (detacher) { detacher(); } } } }); }; /*globals qq */ /** * Defines the public API for FineUploader mode. */ (function(){ "use strict"; qq.uiPublicApi = { clearStoredFiles: function() { this._parent.prototype.clearStoredFiles.apply(this, arguments); this._templating.clearFiles(); }, addExtraDropzone: function(element){ this._dnd && this._dnd.setupExtraDropzone(element); }, removeExtraDropzone: function(element){ if (this._dnd) { return this._dnd.removeDropzone(element); } }, getItemByFileId: function(id) { return this._templating.getFileContainer(id); }, reset: function() { this._parent.prototype.reset.apply(this, arguments); this._templating.reset(); if (!this._options.button && this._templating.getButton()) { this._defaultButtonId = this._createUploadButton({element: this._templating.getButton()}).getButtonId(); } if (this._dnd) { this._dnd.dispose(); this._dnd = this._setupDragAndDrop(); } this._totalFilesInBatch = 0; this._filesInBatchAddedToUi = 0; this._setupClickAndEditEventHandlers(); }, pauseUpload: function(id) { var paused = this._parent.prototype.pauseUpload.apply(this, arguments); paused && this._templating.uploadPaused(id); return paused; }, continueUpload: function(id) { var continued = this._parent.prototype.continueUpload.apply(this, arguments); continued && this._templating.uploadContinued(id); return continued; }, getId: function(fileContainerOrChildEl) { return this._templating.getFileId(fileContainerOrChildEl); }, getDropTarget: function(fileId) { var file = this.getFile(fileId); return file.qqDropTarget; } }; /** * Defines the private (internal) API for FineUploader mode. */ qq.uiPrivateApi = { _getButton: function(buttonId) { var button = this._parent.prototype._getButton.apply(this, arguments); if (!button) { if (buttonId === this._defaultButtonId) { button = this._templating.getButton(); } } return button; }, _removeFileItem: function(fileId) { this._templating.removeFile(fileId); }, _setupClickAndEditEventHandlers: function() { this._fileButtonsClickHandler = qq.FileButtonsClickHandler && this._bindFileButtonsClickEvent(); // A better approach would be to check specifically for focusin event support by querying the DOM API, // but the DOMFocusIn event is not exposed as a property, so we have to resort to UA string sniffing. this._focusinEventSupported = !qq.firefox(); if (this._isEditFilenameEnabled()) { this._filenameClickHandler = this._bindFilenameClickEvent(); this._filenameInputFocusInHandler = this._bindFilenameInputFocusInEvent(); this._filenameInputFocusHandler = this._bindFilenameInputFocusEvent(); } }, _setupDragAndDrop: function() { var self = this, dropZoneElements = this._options.dragAndDrop.extraDropzones, templating = this._templating, defaultDropZone = templating.getDropZone(); defaultDropZone && dropZoneElements.push(defaultDropZone); return new qq.DragAndDrop({ dropZoneElements: dropZoneElements, allowMultipleItems: this._options.multiple, classes: { dropActive: this._options.classes.dropActive }, callbacks: { processingDroppedFiles: function() { templating.showDropProcessing(); }, processingDroppedFilesComplete: function(files, targetEl) { templating.hideDropProcessing(); qq.each(files, function(idx, file) { file.qqDropTarget = targetEl; }); if (files.length) { self.addFiles(files, null, null); } }, dropError: function(code, errorData) { self._itemError(code, errorData); }, dropLog: function(message, level) { self.log(message, level); } } }); }, _bindFileButtonsClickEvent: function() { var self = this; return new qq.FileButtonsClickHandler({ templating: this._templating, log: function(message, lvl) { self.log(message, lvl); }, onDeleteFile: function(fileId) { self.deleteFile(fileId); }, onCancel: function(fileId) { self.cancel(fileId); }, onRetry: function(fileId) { qq(self._templating.getFileContainer(fileId)).removeClass(self._classes.retryable); self.retry(fileId); }, onPause: function(fileId) { self.pauseUpload(fileId); }, onContinue: function(fileId) { self.continueUpload(fileId); }, onGetName: function(fileId) { return self.getName(fileId); } }); }, _isEditFilenameEnabled: function() { /*jshint -W014 */ return this._templating.isEditFilenamePossible() && !this._options.autoUpload && qq.FilenameClickHandler && qq.FilenameInputFocusHandler && qq.FilenameInputFocusHandler; }, _filenameEditHandler: function() { var self = this, templating = this._templating; return { templating: templating, log: function(message, lvl) { self.log(message, lvl); }, onGetUploadStatus: function(fileId) { return self.getUploads({id: fileId}).status; }, onGetName: function(fileId) { return self.getName(fileId); }, onSetName: function(id, newName) { var formattedFilename = self._options.formatFileName(newName); templating.updateFilename(id, formattedFilename); self.setName(id, newName); }, onEditingStatusChange: function(id, isEditing) { var qqInput = qq(templating.getEditInput(id)), qqFileContainer = qq(templating.getFileContainer(id)); if (isEditing) { qqInput.addClass("qq-editing"); templating.hideFilename(id); templating.hideEditIcon(id); } else { qqInput.removeClass("qq-editing"); templating.showFilename(id); templating.showEditIcon(id); } // Force IE8 and older to repaint qqFileContainer.addClass("qq-temp").removeClass("qq-temp"); } }; }, _onUploadStatusChange: function(id, oldStatus, newStatus) { this._parent.prototype._onUploadStatusChange.apply(this, arguments); if (this._isEditFilenameEnabled()) { // Status for a file exists before it has been added to the DOM, so we must be careful here. if (this._templating.getFileContainer(id) && newStatus !== qq.status.SUBMITTED) { this._templating.markFilenameEditable(id); this._templating.hideEditIcon(id); } } }, _bindFilenameInputFocusInEvent: function() { var spec = qq.extend({}, this._filenameEditHandler()); return new qq.FilenameInputFocusInHandler(spec); }, _bindFilenameInputFocusEvent: function() { var spec = qq.extend({}, this._filenameEditHandler()); return new qq.FilenameInputFocusHandler(spec); }, _bindFilenameClickEvent: function() { var spec = qq.extend({}, this._filenameEditHandler()); return new qq.FilenameClickHandler(spec); }, _storeForLater: function(id) { this._parent.prototype._storeForLater.apply(this, arguments); this._templating.hideSpinner(id); }, _onSubmit: function(id, name) { this._parent.prototype._onSubmit.apply(this, arguments); this._addToList(id, name); }, // The file item has been added to the DOM. _onSubmitted: function(id) { // If the edit filename feature is enabled, mark the filename element as "editable" and the associated edit icon if (this._isEditFilenameEnabled()) { this._templating.markFilenameEditable(id); this._templating.showEditIcon(id); // If the focusin event is not supported, we must add a focus handler to the newly create edit filename text input if (!this._focusinEventSupported) { this._filenameInputFocusHandler.addHandler(this._templating.getEditInput(id)); } } }, // Update the progress bar & percentage as the file is uploaded _onProgress: function(id, name, loaded, total){ this._parent.prototype._onProgress.apply(this, arguments); this._templating.updateProgress(id, loaded, total); if (loaded === total) { this._templating.hideCancel(id); this._templating.hidePause(id); this._templating.setStatusText(id, this._options.text.waitingForResponse); // If last byte was sent, display total file size this._displayFileSize(id); } else { // If still uploading, display percentage - total size is actually the total request(s) size this._displayFileSize(id, loaded, total); } }, _onComplete: function(id, name, result, xhr) { var parentRetVal = this._parent.prototype._onComplete.apply(this, arguments), templating = this._templating, self = this; function completeUpload(result) { templating.setStatusText(id); qq(templating.getFileContainer(id)).removeClass(self._classes.retrying); templating.hideProgress(id); if (!self._options.disableCancelForFormUploads || qq.supportedFeatures.ajaxUploading) { templating.hideCancel(id); } templating.hideSpinner(id); if (result.success) { self._markFileAsSuccessful(id); } else { qq(templating.getFileContainer(id)).addClass(self._classes.fail); if (self._templating.isRetryPossible() && !self._preventRetries[id]) { qq(templating.getFileContainer(id)).addClass(self._classes.retryable); } self._controlFailureTextDisplay(id, result); } } // The parent may need to perform some async operation before we can accurately determine the status of the upload. if (parentRetVal instanceof qq.Promise) { parentRetVal.done(function(newResult) { completeUpload(newResult); }); } else { completeUpload(result); } return parentRetVal; }, _markFileAsSuccessful: function(id) { var templating = this._templating; if (this._isDeletePossible()) { templating.showDeleteButton(id); } qq(templating.getFileContainer(id)).addClass(this._classes.success); this._maybeUpdateThumbnail(id); }, _onUpload: function(id, name){ var parentRetVal = this._parent.prototype._onUpload.apply(this, arguments); this._templating.showSpinner(id); return parentRetVal; }, _onUploadChunk: function(id, chunkData) { this._parent.prototype._onUploadChunk.apply(this, arguments); // Only display the pause button if we have finished uploading at least one chunk chunkData.partIndex > 0 && this._templating.allowPause(id); }, _onCancel: function(id, name) { this._parent.prototype._onCancel.apply(this, arguments); this._removeFileItem(id); }, _onBeforeAutoRetry: function(id) { var retryNumForDisplay, maxAuto, retryNote; this._parent.prototype._onBeforeAutoRetry.apply(this, arguments); this._showCancelLink(id); if (this._options.retry.showAutoRetryNote) { retryNumForDisplay = this._autoRetries[id] + 1; maxAuto = this._options.retry.maxAutoAttempts; retryNote = this._options.retry.autoRetryNote.replace(/\{retryNum\}/g, retryNumForDisplay); retryNote = retryNote.replace(/\{maxAuto\}/g, maxAuto); this._templating.setStatusText(id, retryNote); qq(this._templating.getFileContainer(id)).addClass(this._classes.retrying); } }, //return false if we should not attempt the requested retry _onBeforeManualRetry: function(id) { if (this._parent.prototype._onBeforeManualRetry.apply(this, arguments)) { this._templating.resetProgress(id); qq(this._templating.getFileContainer(id)).removeClass(this._classes.fail); this._templating.setStatusText(id); this._templating.showSpinner(id); this._showCancelLink(id); return true; } else { qq(this._templating.getFileContainer(id)).addClass(this._classes.retryable); return false; } }, _onSubmitDelete: function(id) { var onSuccessCallback = qq.bind(this._onSubmitDeleteSuccess, this); this._parent.prototype._onSubmitDelete.call(this, id, onSuccessCallback); }, _onSubmitDeleteSuccess: function(id, uuid, additionalMandatedParams) { if (this._options.deleteFile.forceConfirm) { this._showDeleteConfirm.apply(this, arguments); } else { this._sendDeleteRequest.apply(this, arguments); } }, _onDeleteComplete: function(id, xhr, isError) { this._parent.prototype._onDeleteComplete.apply(this, arguments); this._templating.hideSpinner(id); if (isError) { this._templating.setStatusText(id, this._options.deleteFile.deletingFailedText); this._templating.showDeleteButton(id); } else { this._removeFileItem(id); } }, _sendDeleteRequest: function(id, uuid, additionalMandatedParams) { this._templating.hideDeleteButton(id); this._templating.showSpinner(id); this._templating.setStatusText(id, this._options.deleteFile.deletingStatusText); this._deleteHandler.sendDelete.apply(this, arguments); }, _showDeleteConfirm: function(id, uuid, mandatedParams) { /*jshint -W004 */ var fileName = this.getName(id), confirmMessage = this._options.deleteFile.confirmMessage.replace(/\{filename\}/g, fileName), uuid = this.getUuid(id), deleteRequestArgs = arguments, self = this, retVal; retVal = this._options.showConfirm(confirmMessage); if (retVal instanceof qq.Promise) { retVal.then(function () { self._sendDeleteRequest.apply(self, deleteRequestArgs); }); } else if (retVal !== false) { self._sendDeleteRequest.apply(self, deleteRequestArgs); } }, _addToList: function(id, name, canned) { var prependData, prependIndex = 0; if (this._options.display.prependFiles) { if (this._totalFilesInBatch > 1 && this._filesInBatchAddedToUi > 0) { prependIndex = this._filesInBatchAddedToUi - 1; } prependData = { index: prependIndex }; } if (!canned) { if (this._options.disableCancelForFormUploads && !qq.supportedFeatures.ajaxUploading) { this._templating.disableCancel(); } if (!this._options.multiple) { this._handler.cancelAll(); this._clearList(); } } this._templating.addFile(id, this._options.formatFileName(name), prependData); if (canned) { this._thumbnailUrls[id] && this._templating.updateThumbnail(id, this._thumbnailUrls[id], true); } else { this._templating.generatePreview(id, this.getFile(id)); } this._filesInBatchAddedToUi += 1; if (canned || (this._options.display.fileSizeOnSubmit && qq.supportedFeatures.ajaxUploading)) { this._displayFileSize(id); } }, _clearList: function(){ this._templating.clearFiles(); this.clearStoredFiles(); }, _displayFileSize: function(id, loadedSize, totalSize) { var size = this.getSize(id), sizeForDisplay = this._formatSize(size); if (size >= 0) { if (loadedSize !== undefined && totalSize !== undefined) { sizeForDisplay = this._formatProgress(loadedSize, totalSize); } this._templating.updateSize(id, sizeForDisplay); } }, _formatProgress: function (uploadedSize, totalSize) { var message = this._options.text.formatProgress; function r(name, replacement) { message = message.replace(name, replacement); } r("{percent}", Math.round(uploadedSize / totalSize * 100)); r("{total_size}", this._formatSize(totalSize)); return message; }, _controlFailureTextDisplay: function(id, response) { var mode, maxChars, responseProperty, failureReason, shortFailureReason; mode = this._options.failedUploadTextDisplay.mode; maxChars = this._options.failedUploadTextDisplay.maxChars; responseProperty = this._options.failedUploadTextDisplay.responseProperty; if (mode === "custom") { failureReason = response[responseProperty]; if (failureReason) { if (failureReason.length > maxChars) { shortFailureReason = failureReason.substring(0, maxChars) + "..."; } } else { failureReason = this._options.text.failUpload; this.log("'" + responseProperty + "' is not a valid property on the server response.", "warn"); } this._templating.setStatusText(id, shortFailureReason || failureReason); if (this._options.failedUploadTextDisplay.enableTooltip) { this._showTooltip(id, failureReason); } } else if (mode === "default") { this._templating.setStatusText(id, this._options.text.failUpload); } else if (mode !== "none") { this.log("failedUploadTextDisplay.mode value of '" + mode + "' is not valid", "warn"); } }, _showTooltip: function(id, text) { this._templating.getFileContainer(id).title = text; }, _showCancelLink: function(id) { if (!this._options.disableCancelForFormUploads || qq.supportedFeatures.ajaxUploading) { this._templating.showCancel(id); } }, _itemError: function(code, name, item) { var message = this._parent.prototype._itemError.apply(this, arguments); this._options.showMessage(message); }, _batchError: function(message) { this._parent.prototype._batchError.apply(this, arguments); this._options.showMessage(message); }, _setupPastePrompt: function() { var self = this; this._options.callbacks.onPasteReceived = function() { var message = self._options.paste.namePromptMessage, defaultVal = self._options.paste.defaultName; return self._options.showPrompt(message, defaultVal); }; }, _fileOrBlobRejected: function(id, name) { this._totalFilesInBatch -= 1; this._parent.prototype._fileOrBlobRejected.apply(this, arguments); }, _prepareItemsForUpload: function(items, params, endpoint) { this._totalFilesInBatch = items.length; this._filesInBatchAddedToUi = 0; this._parent.prototype._prepareItemsForUpload.apply(this, arguments); }, _maybeUpdateThumbnail: function(fileId) { var thumbnailUrl = this._thumbnailUrls[fileId]; this._templating.updateThumbnail(fileId, thumbnailUrl); }, _addCannedFile: function(sessionData) { var id = this._parent.prototype._addCannedFile.apply(this, arguments); this._addToList(id, this.getName(id), true); this._templating.hideSpinner(id); this._templating.hideCancel(id); this._markFileAsSuccessful(id); return id; } }; }()); /*globals qq */ /** * This defines FineUploader mode, which is a default UI w/ drag & drop uploading. */ qq.FineUploader = function(o, namespace) { "use strict"; // By default this should inherit instance data from FineUploaderBasic, but this can be overridden // if the (internal) caller defines a different parent. The parent is also used by // the private and public API functions that need to delegate to a parent function. this._parent = namespace ? qq[namespace].FineUploaderBasic : qq.FineUploaderBasic; this._parent.apply(this, arguments); // Options provided by FineUploader mode qq.extend(this._options, { element: null, button: null, listElement: null, dragAndDrop: { extraDropzones: [] }, text: { formatProgress: "{percent}% of {total_size}", failUpload: "Upload failed", waitingForResponse: "Processing...", paused: "Paused" }, template: "qq-template", classes: { retrying: "qq-upload-retrying", retryable: "qq-upload-retryable", success: "qq-upload-success", fail: "qq-upload-fail", editable: "qq-editable", hide: "qq-hide", dropActive: "qq-upload-drop-area-active" }, failedUploadTextDisplay: { mode: "default", //default, custom, or none maxChars: 50, responseProperty: "error", enableTooltip: true }, messages: { tooManyFilesError: "You may only drop one file", unsupportedBrowser: "Unrecoverable error - this browser does not permit file uploading of any kind." }, retry: { showAutoRetryNote: true, autoRetryNote: "Retrying {retryNum}/{maxAuto}..." }, deleteFile: { forceConfirm: false, confirmMessage: "Are you sure you want to delete {filename}?", deletingStatusText: "Deleting...", deletingFailedText: "Delete failed" }, display: { fileSizeOnSubmit: false, prependFiles: false }, paste: { promptForName: false, namePromptMessage: "Please name this image" }, thumbnails: { placeholders: { waitUntilResponse: false, notAvailablePath: null, waitingPath: null } }, showMessage: function(message){ setTimeout(function() { window.alert(message); }, 0); }, showConfirm: function(message) { return window.confirm(message); }, showPrompt: function(message, defaultValue) { return window.prompt(message, defaultValue); } }, true); // Replace any default options with user defined ones qq.extend(this._options, o, true); this._templating = new qq.Templating({ log: qq.bind(this.log, this), templateIdOrEl: this._options.template, containerEl: this._options.element, fileContainerEl: this._options.listElement, button: this._options.button, imageGenerator: this._imageGenerator, classes: { hide: this._options.classes.hide, editable: this._options.classes.editable }, placeholders: { waitUntilUpdate: this._options.thumbnails.placeholders.waitUntilResponse, thumbnailNotAvailable: this._options.thumbnails.placeholders.notAvailablePath, waitingForThumbnail: this._options.thumbnails.placeholders.waitingPath }, text: this._options.text }); if (!qq.supportedFeatures.uploading || (this._options.cors.expected && !qq.supportedFeatures.uploadCors)) { this._templating.renderFailure(this._options.messages.unsupportedBrowser); } else { this._wrapCallbacks(); this._templating.render(); this._classes = this._options.classes; if (!this._options.button && this._templating.getButton()) { this._defaultButtonId = this._createUploadButton({element: this._templating.getButton()}).getButtonId(); } this._setupClickAndEditEventHandlers(); if (qq.DragAndDrop && qq.supportedFeatures.fileDrop) { this._dnd = this._setupDragAndDrop(); } if (this._options.paste.targetElement && this._options.paste.promptForName) { if (qq.PasteSupport) { this._setupPastePrompt(); } else { qq.log("Paste support module not found.", "info"); } } this._totalFilesInBatch = 0; this._filesInBatchAddedToUi = 0; } }; // Inherit the base public & private API methods qq.extend(qq.FineUploader.prototype, qq.basePublicApi); qq.extend(qq.FineUploader.prototype, qq.basePrivateApi); // Add the FineUploader/default UI public & private UI methods, which may override some base methods. qq.extend(qq.FineUploader.prototype, qq.uiPublicApi); qq.extend(qq.FineUploader.prototype, qq.uiPrivateApi); /* globals qq */ /* jshint -W065 */ /** * Module responsible for rendering all Fine Uploader UI templates. This module also asserts at least * a limited amount of control over the template elements after they are added to the DOM. * Wherever possible, this module asserts total control over template elements present in the DOM. * * @param spec Specification object used to control various templating behaviors * @constructor */ qq.Templating = function(spec) { "use strict"; var FILE_ID_ATTR = "qq-file-id", FILE_CLASS_PREFIX = "qq-file-id-", THUMBNAIL_MAX_SIZE_ATTR = "qq-max-size", THUMBNAIL_SERVER_SCALE_ATTR = "qq-server-scale", // This variable is duplicated in the DnD module since it can function as a standalone as well HIDE_DROPZONE_ATTR = "qq-hide-dropzone", isCancelDisabled = false, thumbnailMaxSize = -1, options = { log: null, templateIdOrEl: "qq-template", containerEl: null, fileContainerEl: null, button: null, imageGenerator: null, classes: { hide: "qq-hide", editable: "qq-editable" }, placeholders: { waitUntilUpdate: false, thumbnailNotAvailable: null, waitingForThumbnail: null }, text: { paused: "Paused" } }, selectorClasses = { button: "qq-upload-button-selector", drop: "qq-upload-drop-area-selector", list: "qq-upload-list-selector", progressBarContainer: "qq-progress-bar-container-selector", progressBar: "qq-progress-bar-selector", file: "qq-upload-file-selector", spinner: "qq-upload-spinner-selector", size: "qq-upload-size-selector", cancel: "qq-upload-cancel-selector", pause: "qq-upload-pause-selector", continueButton: "qq-upload-continue-selector", deleteButton: "qq-upload-delete-selector", retry: "qq-upload-retry-selector", statusText: "qq-upload-status-text-selector", editFilenameInput: "qq-edit-filename-selector", editNameIcon: "qq-edit-filename-icon-selector", dropProcessing: "qq-drop-processing-selector", dropProcessingSpinner: "qq-drop-processing-spinner-selector", thumbnail: "qq-thumbnail-selector" }, previewGeneration = {}, cachedThumbnailNotAvailableImg = new qq.Promise(), cachedWaitingForThumbnailImg = new qq.Promise(), log, isEditElementsExist, isRetryElementExist, templateHtml, container, fileList, showThumbnails, serverScale; /** * Grabs the HTML from the script tag holding the template markup. This function will also adjust * some internally-tracked state variables based on the contents of the template. * The template is filtered so that irrelevant elements (such as the drop zone if DnD is not supported) * are omitted from the DOM. Useful errors will be thrown if the template cannot be parsed. * * @returns {{template: *, fileTemplate: *}} HTML for the top-level file items templates */ function parseAndGetTemplate() { var scriptEl, scriptHtml, fileListNode, tempTemplateEl, fileListHtml, defaultButton, dropArea, thumbnail, dropProcessing; log("Parsing template"); /*jshint -W116*/ if (options.templateIdOrEl == null) { throw new Error("You MUST specify either a template element or ID!"); } // Grab the contents of the script tag holding the template. if (qq.isString(options.templateIdOrEl)) { scriptEl = document.getElementById(options.templateIdOrEl); if (scriptEl === null) { throw new Error(qq.format("Cannot find template script at ID '{}'!", options.templateIdOrEl)); } scriptHtml = scriptEl.innerHTML; } else { if (options.templateIdOrEl.innerHTML === undefined) { throw new Error("You have specified an invalid value for the template option! " + "It must be an ID or an Element."); } scriptHtml = options.templateIdOrEl.innerHTML; } scriptHtml = qq.trimStr(scriptHtml); tempTemplateEl = document.createElement("div"); tempTemplateEl.appendChild(qq.toElement(scriptHtml)); // Don't include the default template button in the DOM // if an alternate button container has been specified. if (options.button) { defaultButton = qq(tempTemplateEl).getByClass(selectorClasses.button)[0]; if (defaultButton) { qq(defaultButton).remove(); } } // Omit the drop processing element from the DOM if DnD is not supported by the UA, // or the drag and drop module is not found. // NOTE: We are consciously not removing the drop zone if the UA doesn't support DnD // to support layouts where the drop zone is also a container for visible elements, // such as the file list. if (!qq.DragAndDrop || !qq.supportedFeatures.fileDrop) { dropProcessing = qq(tempTemplateEl).getByClass(selectorClasses.dropProcessing)[0]; if (dropProcessing) { qq(dropProcessing).remove(); } } dropArea = qq(tempTemplateEl).getByClass(selectorClasses.drop)[0]; // If DnD is not available then remove // it from the DOM as well. if (dropArea && !qq.DragAndDrop) { qq.log("DnD module unavailable.", "info"); qq(dropArea).remove(); } // If there is a drop area defined in the template, and the current UA doesn't support DnD, // and the drop area is marked as "hide before enter", ensure it is hidden as the DnD module // will not do this (since we will not be loading the DnD module) if (dropArea && !qq.supportedFeatures.fileDrop && qq(dropArea).hasAttribute(HIDE_DROPZONE_ATTR)) { qq(dropArea).css({ display: "none" }); } // Ensure the `showThumbnails` flag is only set if the thumbnail element // is present in the template AND the current UA is capable of generating client-side previews. thumbnail = qq(tempTemplateEl).getByClass(selectorClasses.thumbnail)[0]; if (!showThumbnails) { thumbnail && qq(thumbnail).remove(); } else if (thumbnail) { thumbnailMaxSize = parseInt(thumbnail.getAttribute(THUMBNAIL_MAX_SIZE_ATTR)); // Only enforce max size if the attr value is non-zero thumbnailMaxSize = thumbnailMaxSize > 0 ? thumbnailMaxSize : null; serverScale = qq(thumbnail).hasAttribute(THUMBNAIL_SERVER_SCALE_ATTR); } showThumbnails = showThumbnails && thumbnail; isEditElementsExist = qq(tempTemplateEl).getByClass(selectorClasses.editFilenameInput).length > 0; isRetryElementExist = qq(tempTemplateEl).getByClass(selectorClasses.retry).length > 0; fileListNode = qq(tempTemplateEl).getByClass(selectorClasses.list)[0]; /*jshint -W116*/ if (fileListNode == null) { throw new Error("Could not find the file list container in the template!"); } fileListHtml = fileListNode.innerHTML; fileListNode.innerHTML = ""; log("Template parsing complete"); return { template: qq.trimStr(tempTemplateEl.innerHTML), fileTemplate: qq.trimStr(fileListHtml) }; } function getFile(id) { return qq(fileList).getByClass(FILE_CLASS_PREFIX + id)[0]; } function getTemplateEl(context, cssClass) { return qq(context).getByClass(cssClass)[0]; } function prependFile(el, index) { var parentEl = fileList, beforeEl = parentEl.firstChild; if (index > 0) { beforeEl = qq(parentEl).children()[index].nextSibling; } parentEl.insertBefore(el, beforeEl); } function getCancel(id) { return getTemplateEl(getFile(id), selectorClasses.cancel); } function getPause(id) { return getTemplateEl(getFile(id), selectorClasses.pause); } function getContinue(id) { return getTemplateEl(getFile(id), selectorClasses.continueButton); } function getProgress(id) { return getTemplateEl(getFile(id), selectorClasses.progressBarContainer) || getTemplateEl(getFile(id), selectorClasses.progressBar); } function getSpinner(id) { return getTemplateEl(getFile(id), selectorClasses.spinner); } function getEditIcon(id) { return getTemplateEl(getFile(id), selectorClasses.editNameIcon); } function getSize(id) { return getTemplateEl(getFile(id), selectorClasses.size); } function getDelete(id) { return getTemplateEl(getFile(id), selectorClasses.deleteButton); } function getRetry(id) { return getTemplateEl(getFile(id), selectorClasses.retry); } function getFilename(id) { return getTemplateEl(getFile(id), selectorClasses.file); } function getDropProcessing() { return getTemplateEl(container, selectorClasses.dropProcessing); } function getThumbnail(id) { return showThumbnails && getTemplateEl(getFile(id), selectorClasses.thumbnail); } function hide(el) { el && qq(el).addClass(options.classes.hide); } function show(el) { el && qq(el).removeClass(options.classes.hide); } function setProgressBarWidth(id, percent) { var bar = getProgress(id); if (bar && !qq(bar).hasClass(selectorClasses.progressBar)) { bar = qq(bar).getByClass(selectorClasses.progressBar)[0]; } bar && qq(bar).css({width: percent + "%"}); } // During initialization of the templating module we should cache any // placeholder images so we can quickly swap them into the file list on demand. // Any placeholder images that cannot be loaded/found are simply ignored. function cacheThumbnailPlaceholders() { var notAvailableUrl = options.placeholders.thumbnailNotAvailable, waitingUrl = options.placeholders.waitingForThumbnail, spec = { maxSize: thumbnailMaxSize, scale: serverScale }; if (showThumbnails) { if (notAvailableUrl) { options.imageGenerator.generate(notAvailableUrl, new Image(), spec).then( function(updatedImg) { cachedThumbnailNotAvailableImg.success(updatedImg); }, function() { cachedThumbnailNotAvailableImg.failure(); log("Problem loading 'not available' placeholder image at " + notAvailableUrl, "error"); } ); } else { cachedThumbnailNotAvailableImg.failure(); } if (waitingUrl) { options.imageGenerator.generate(waitingUrl, new Image(), spec).then( function(updatedImg) { cachedWaitingForThumbnailImg.success(updatedImg); }, function() { cachedWaitingForThumbnailImg.failure(); log("Problem loading 'waiting for thumbnail' placeholder image at " + waitingUrl, "error"); } ); } else { cachedWaitingForThumbnailImg.failure(); } } } // Displays a "waiting for thumbnail" type placeholder image // iff we were able to load it during initialization of the templating module. function displayWaitingImg(thumbnail) { cachedWaitingForThumbnailImg.then(function(img) { maybeScalePlaceholderViaCss(img, thumbnail); /* jshint eqnull:true */ if (thumbnail.getAttribute("src") == null) { thumbnail.src = img.src; show(thumbnail); } }, function() { // In some browsers (such as IE9 and older) an img w/out a src attribute // are displayed as "broken" images, so we sohuld just hide the img tag // if we aren't going to display the "waiting" placeholder. hide(thumbnail); }); } // Displays a "thumbnail not available" type placeholder image // iff we were able to load this placeholder during initialization // of the templating module or after preview generation has failed. function maybeSetDisplayNotAvailableImg(id, thumbnail) { var previewing = previewGeneration[id] || new qq.Promise().failure(); cachedThumbnailNotAvailableImg.then(function(img) { previewing.then( function() { delete previewGeneration[id]; }, function() { maybeScalePlaceholderViaCss(img, thumbnail); thumbnail.src = img.src; show(thumbnail); delete previewGeneration[id]; } ); }); } // Ensures a placeholder image does not exceed any max size specified // via `style` attribute properties iff <canvas> was not used to scale // the placeholder AND the target <img> doesn't already have these `style` attribute properties set. function maybeScalePlaceholderViaCss(placeholder, thumbnail) { var maxWidth = placeholder.style.maxWidth, maxHeight = placeholder.style.maxHeight; if (maxHeight && maxWidth && !thumbnail.style.maxWidth && !thumbnail.style.maxHeight) { qq(thumbnail).css({ maxWidth: maxWidth, maxHeight: maxHeight }); } } qq.extend(options, spec); log = options.log; container = options.containerEl; showThumbnails = options.imageGenerator !== undefined; templateHtml = parseAndGetTemplate(); cacheThumbnailPlaceholders(); qq.extend(this, { render: function() { log("Rendering template in DOM."); container.innerHTML = templateHtml.template; hide(getDropProcessing()); fileList = options.fileContainerEl || getTemplateEl(container, selectorClasses.list); log("Template rendering complete"); }, renderFailure: function(message) { var cantRenderEl = qq.toElement(message); container.innerHTML = ""; container.appendChild(cantRenderEl); }, reset: function() { this.render(); }, clearFiles: function() { fileList.innerHTML = ""; }, disableCancel: function() { isCancelDisabled = true; }, addFile: function(id, name, prependInfo) { var fileEl = qq.toElement(templateHtml.fileTemplate), fileNameEl = getTemplateEl(fileEl, selectorClasses.file); qq(fileEl).addClass(FILE_CLASS_PREFIX + id); fileNameEl && qq(fileNameEl).setText(name); fileEl.setAttribute(FILE_ID_ATTR, id); if (prependInfo) { prependFile(fileEl, prependInfo.index); } else { fileList.appendChild(fileEl); } hide(getProgress(id)); hide(getSize(id)); hide(getDelete(id)); hide(getRetry(id)); hide(getPause(id)); hide(getContinue(id)); if (isCancelDisabled) { this.hideCancel(id); } }, removeFile: function(id) { qq(getFile(id)).remove(); }, getFileId: function(el) { var currentNode = el; if (currentNode) { /*jshint -W116*/ while (currentNode.getAttribute(FILE_ID_ATTR) == null) { currentNode = currentNode.parentNode; } return parseInt(currentNode.getAttribute(FILE_ID_ATTR)); } }, getFileList: function() { return fileList; }, markFilenameEditable: function(id) { var filename = getFilename(id); filename && qq(filename).addClass(options.classes.editable); }, updateFilename: function(id, name) { var filename = getFilename(id); filename && qq(filename).setText(name); }, hideFilename: function(id) { hide(getFilename(id)); }, showFilename: function(id) { show(getFilename(id)); }, isFileName: function(el) { return qq(el).hasClass(selectorClasses.file); }, getButton: function() { return options.button || getTemplateEl(container, selectorClasses.button); }, hideDropProcessing: function() { hide(getDropProcessing()); }, showDropProcessing: function() { show(getDropProcessing()); }, getDropZone: function() { return getTemplateEl(container, selectorClasses.drop); }, isEditFilenamePossible: function() { return isEditElementsExist; }, isRetryPossible: function() { return isRetryElementExist; }, getFileContainer: function(id) { return getFile(id); }, showEditIcon: function(id) { var icon = getEditIcon(id); icon && qq(icon).addClass(options.classes.editable); }, hideEditIcon: function(id) { var icon = getEditIcon(id); icon && qq(icon).removeClass(options.classes.editable); }, isEditIcon: function(el) { return qq(el).hasClass(selectorClasses.editNameIcon); }, getEditInput: function(id) { return getTemplateEl(getFile(id), selectorClasses.editFilenameInput); }, isEditInput: function(el) { return qq(el).hasClass(selectorClasses.editFilenameInput); }, updateProgress: function(id, loaded, total) { var bar = getProgress(id), percent; if (bar) { percent = Math.round(loaded / total * 100); if (loaded === total) { hide(bar); } else { show(bar); } setProgressBarWidth(id, percent); } }, hideProgress: function(id) { var bar = getProgress(id); bar && hide(bar); }, resetProgress: function(id) { setProgressBarWidth(id, 0); }, showCancel: function(id) { if (!isCancelDisabled) { var cancel = getCancel(id); cancel && qq(cancel).removeClass(options.classes.hide); } }, hideCancel: function(id) { hide(getCancel(id)); }, isCancel: function(el) { return qq(el).hasClass(selectorClasses.cancel); }, allowPause: function(id) { show(getPause(id)); hide(getContinue(id)); }, uploadPaused: function(id) { this.setStatusText(id, options.text.paused); this.allowContinueButton(id); hide(getSpinner(id)); }, hidePause: function(id) { hide(getPause(id)); }, isPause: function(el) { return qq(el).hasClass(selectorClasses.pause); }, isContinueButton: function(el) { return qq(el).hasClass(selectorClasses.continueButton); }, allowContinueButton: function(id) { show(getContinue(id)); hide(getPause(id)); }, uploadContinued: function(id) { this.setStatusText(id, ""); this.allowPause(id); show(getSpinner(id)); }, showDeleteButton: function(id) { show(getDelete(id)); }, hideDeleteButton: function(id) { hide(getDelete(id)); }, isDeleteButton: function(el) { return qq(el).hasClass(selectorClasses.deleteButton); }, isRetry: function(el) { return qq(el).hasClass(selectorClasses.retry); }, updateSize: function(id, text) { var size = getSize(id); if (size) { show(size); qq(size).setText(text); } }, setStatusText: function(id, text) { var textEl = getTemplateEl(getFile(id), selectorClasses.statusText); if (textEl) { /*jshint -W116*/ if (text == null) { qq(textEl).clearText(); } else { qq(textEl).setText(text); } } }, hideSpinner: function(id) { hide(getSpinner(id)); }, showSpinner: function(id) { show(getSpinner(id)); }, generatePreview: function(id, fileOrBlob) { var thumbnail = getThumbnail(id), spec = { maxSize: thumbnailMaxSize, scale: true, orient: true }; if (qq.supportedFeatures.imagePreviews) { previewGeneration[id] = new qq.Promise(); if (thumbnail) { displayWaitingImg(thumbnail); return options.imageGenerator.generate(fileOrBlob, thumbnail, spec).then( function() { show(thumbnail); previewGeneration[id].success(); }, function() { previewGeneration[id].failure(); // Display the "not available" placeholder img only if we are // not expecting a thumbnail at a later point, such as in a server response. if (!options.placeholders.waitUntilUpdate) { maybeSetDisplayNotAvailableImg(id, thumbnail); } }); } } else if (thumbnail) { displayWaitingImg(thumbnail); } }, updateThumbnail: function(id, thumbnailUrl, showWaitingImg) { var thumbnail = getThumbnail(id), spec = { maxSize: thumbnailMaxSize, scale: serverScale }; if (thumbnail) { if (thumbnailUrl) { if (showWaitingImg) { displayWaitingImg(thumbnail); } return options.imageGenerator.generate(thumbnailUrl, thumbnail, spec).then( function() { show(thumbnail); }, function() { maybeSetDisplayNotAvailableImg(id, thumbnail); } ); } else { maybeSetDisplayNotAvailableImg(id, thumbnail); } } } }); }; /*globals qq*/ /** * Upload handler used that assumes the current user agent does not have any support for the * File API, and, therefore, makes use of iframes and forms to submit the files directly to * a generic server. * * @param options Options passed from the base handler * @param proxy Callbacks & methods used to query for or push out data/changes */ qq.UploadHandlerForm = function(options, proxy) { "use strict"; var handler = this, uploadCompleteCallback = proxy.onUploadComplete, onUuidChanged = proxy.onUuidChanged, getName = proxy.getName, getUuid = proxy.getUuid, uploadComplete = uploadCompleteCallback, log = proxy.log; /** * Returns json object received by iframe from server. */ function getIframeContentJson(id, iframe) { /*jshint evil: true*/ var response; //IE may throw an "access is denied" error when attempting to access contentDocument on the iframe in some cases try { // iframe.contentWindow.document - for IE<7 var doc = iframe.contentDocument || iframe.contentWindow.document, innerHtml = doc.body.innerHTML; log("converting iframe's innerHTML to JSON"); log("innerHTML = " + innerHtml); //plain text response may be wrapped in <pre> tag if (innerHtml && innerHtml.match(/^<pre/i)) { innerHtml = doc.body.firstChild.firstChild.nodeValue; } response = handler._parseJsonResponse(id, innerHtml); } catch(error) { log("Error when attempting to parse form upload response (" + error.message + ")", "error"); response = {success: false}; } return response; } /** * Creates form, that will be submitted to iframe */ function createForm(id, iframe){ var params = options.paramsStore.get(id), method = options.demoMode ? "GET" : "POST", endpoint = options.endpointStore.get(id), name = getName(id); params[options.uuidName] = getUuid(id); params[options.filenameParam] = name; return handler._initFormForUpload({ method: method, endpoint: endpoint, params: params, paramsInBody: options.paramsInBody, targetName: iframe.name }); } qq.extend(this, new qq.AbstractUploadHandlerForm({ options: { isCors: options.cors.expected, inputName: options.inputName }, proxy: { onCancel: options.onCancel, onUuidChanged: onUuidChanged, getName: getName, getUuid: getUuid, log: log } } )); qq.extend(this, { upload: function(id) { var input = handler._getFileState(id).input, fileName = getName(id), iframe = handler._createIframe(id), form; if (!input){ throw new Error("file with passed id was not added, or already uploaded or canceled"); } options.onUpload(id, getName(id)); form = createForm(id, iframe); form.appendChild(input); handler._attachLoadEvent(iframe, function(responseFromMessage){ log("iframe loaded"); var response = responseFromMessage ? responseFromMessage : getIframeContentJson(id, iframe); handler._detachLoadEvent(id); //we can't remove an iframe if the iframe doesn't belong to the same domain if (!options.cors.expected) { qq(iframe).remove(); } if (!response.success) { if (options.onAutoRetry(id, fileName, response)) { return; } } options.onComplete(id, fileName, response); uploadComplete(id); }); log("Sending upload request for " + id); form.submit(); qq(form).remove(); } }); }; /*globals qq*/ /** * Upload handler used to upload to traditional endpoints. It depends on File API support, and, therefore, * makes use of `XMLHttpRequest` level 2 to upload `File`s and `Blob`s to a generic server. * * @param spec Options passed from the base handler * @param proxy Callbacks & methods used to query for or push out data/changes */ qq.UploadHandlerXhr = function(spec, proxy) { "use strict"; var uploadComplete = proxy.onUploadComplete, onUuidChanged = proxy.onUuidChanged, getName = proxy.getName, getUuid = proxy.getUuid, getSize = proxy.getSize, log = proxy.log, cookieItemDelimiter = "|", chunkFiles = spec.chunking.enabled && qq.supportedFeatures.chunking, resumeEnabled = spec.resume.enabled && chunkFiles && qq.supportedFeatures.resume, multipart = spec.forceMultipart || spec.paramsInBody, handler = this, resumeId; function getResumeId() { if (spec.resume.id !== null && spec.resume.id !== undefined && !qq.isFunction(spec.resume.id) && !qq.isObject(spec.resume.id)) { return spec.resume.id; } } resumeId = getResumeId(); function addChunkingSpecificParams(id, params, chunkData) { var size = getSize(id), name = getName(id); params[spec.chunking.paramNames.partIndex] = chunkData.part; params[spec.chunking.paramNames.partByteOffset] = chunkData.start; params[spec.chunking.paramNames.chunkSize] = chunkData.size; params[spec.chunking.paramNames.totalParts] = chunkData.count; params[spec.totalFileSizeName] = size; /** * When a Blob is sent in a multipart request, the filename value in the content-disposition header is either "blob" * or an empty string. So, we will need to include the actual file name as a param in this case. */ if (multipart) { params[spec.filenameParam] = name; } } function addResumeSpecificParams(params) { params[spec.resume.paramNames.resuming] = true; } function getChunk(fileOrBlob, startByte, endByte) { if (fileOrBlob.slice) { return fileOrBlob.slice(startByte, endByte); } else if (fileOrBlob.mozSlice) { return fileOrBlob.mozSlice(startByte, endByte); } else if (fileOrBlob.webkitSlice) { return fileOrBlob.webkitSlice(startByte, endByte); } } function setParamsAndGetEntityToSend(params, xhr, fileOrBlob, id) { var formData = new FormData(), method = spec.demoMode ? "GET" : "POST", endpoint = spec.endpointStore.get(id), url = endpoint, name = getName(id), size = getSize(id); params[spec.uuidName] = getUuid(id); params[spec.filenameParam] = name; if (multipart) { params[spec.totalFileSizeName] = size; } //build query string if (!spec.paramsInBody) { if (!multipart) { params[spec.inputName] = name; } url = qq.obj2url(params, endpoint); } xhr.open(method, url, true); if (spec.cors.expected && spec.cors.sendCredentials) { xhr.withCredentials = true; } if (multipart) { if (spec.paramsInBody) { qq.obj2FormData(params, formData); } formData.append(spec.inputName, fileOrBlob); return formData; } return fileOrBlob; } function setHeaders(id, xhr) { var extraHeaders = spec.customHeaders, fileOrBlob = handler._getFileState(id).file || handler._getFileState(id).blobData.blob; xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); xhr.setRequestHeader("Cache-Control", "no-cache"); if (!multipart) { xhr.setRequestHeader("Content-Type", "application/octet-stream"); //NOTE: return mime type in xhr works on chrome 16.0.9 firefox 11.0a2 xhr.setRequestHeader("X-Mime-Type", fileOrBlob.type); } qq.each(extraHeaders, function(name, val) { xhr.setRequestHeader(name, val); }); } function handleCompletedItem(id, response, xhr) { var name = getName(id), size = getSize(id); handler._getFileState(id).attemptingResume = false; spec.onProgress(id, name, size, size); spec.onComplete(id, name, response, xhr); if (handler._getFileState(id)) { delete handler._getFileState(id).xhr; } uploadComplete(id); } function uploadNextChunk(id) { var chunkIdx = handler._getFileState(id).remainingChunkIdxs[0], chunkData = handler._getChunkData(id, chunkIdx), xhr = handler._createXhr(id), size = getSize(id), name = getName(id), toSend, params; if (handler._getFileState(id).loaded === undefined) { handler._getFileState(id).loaded = 0; } if (resumeEnabled && handler._getFileState(id).file) { persistChunkData(id, chunkData); } xhr.onreadystatechange = getReadyStateChangeHandler(id, xhr); xhr.upload.onprogress = function(e) { if (e.lengthComputable) { var totalLoaded = e.loaded + handler._getFileState(id).loaded, estTotalRequestsSize = calcAllRequestsSizeForChunkedUpload(id, chunkIdx, e.total); spec.onProgress(id, name, totalLoaded, estTotalRequestsSize); } }; spec.onUploadChunk(id, name, handler._getChunkDataForCallback(chunkData)); params = spec.paramsStore.get(id); addChunkingSpecificParams(id, params, chunkData); if (handler._getFileState(id).attemptingResume) { addResumeSpecificParams(params); } toSend = setParamsAndGetEntityToSend(params, xhr, chunkData.blob, id); setHeaders(id, xhr); log("Sending chunked upload request for item " + id + ": bytes " + (chunkData.start+1) + "-" + chunkData.end + " of " + size); xhr.send(toSend); } function calcAllRequestsSizeForChunkedUpload(id, chunkIdx, requestSize) { var chunkData = handler._getChunkData(id, chunkIdx), blobSize = chunkData.size, overhead = requestSize - blobSize, size = getSize(id), chunkCount = chunkData.count, initialRequestOverhead = handler._getFileState(id).initialRequestOverhead, overheadDiff = overhead - initialRequestOverhead; handler._getFileState(id).lastRequestOverhead = overhead; if (chunkIdx === 0) { handler._getFileState(id).lastChunkIdxProgress = 0; handler._getFileState(id).initialRequestOverhead = overhead; handler._getFileState(id).estTotalRequestsSize = size + (chunkCount * overhead); } else if (handler._getFileState(id).lastChunkIdxProgress !== chunkIdx) { handler._getFileState(id).lastChunkIdxProgress = chunkIdx; handler._getFileState(id).estTotalRequestsSize += overheadDiff; } return handler._getFileState(id).estTotalRequestsSize; } function getLastRequestOverhead(id) { if (multipart) { return handler._getFileState(id).lastRequestOverhead; } else { return 0; } } function handleSuccessfullyCompletedChunk(id, response, xhr) { var chunkIdx = handler._getFileState(id).remainingChunkIdxs.shift(), chunkData = handler._getChunkData(id, chunkIdx); handler._getFileState(id).attemptingResume = false; handler._getFileState(id).loaded += chunkData.size + getLastRequestOverhead(id); spec.onUploadChunkSuccess(id, handler._getChunkDataForCallback(chunkData), response, xhr); if (handler._getFileState(id).remainingChunkIdxs.length > 0) { uploadNextChunk(id); } else { if (resumeEnabled) { deletePersistedChunkData(id); } handleCompletedItem(id, response, xhr); } } function isErrorResponse(xhr, response) { return xhr.status !== 200 || !response.success || response.reset; } function parseResponse(id, xhr) { var response; try { log(qq.format("Received response status {} with body: {}", xhr.status, xhr.responseText)); response = qq.parseJson(xhr.responseText); if (response.newUuid !== undefined) { onUuidChanged(id, response.newUuid); } } catch(error) { log("Error when attempting to parse xhr response text (" + error.message + ")", "error"); response = {}; } return response; } function handleResetResponse(id) { log("Server has ordered chunking effort to be restarted on next attempt for item ID " + id, "error"); if (resumeEnabled) { deletePersistedChunkData(id); handler._getFileState(id).attemptingResume = false; } handler._getFileState(id).remainingChunkIdxs = []; delete handler._getFileState(id).loaded; delete handler._getFileState(id).estTotalRequestsSize; delete handler._getFileState(id).initialRequestOverhead; } function handleResetResponseOnResumeAttempt(id) { handler._getFileState(id).attemptingResume = false; log("Server has declared that it cannot handle resume for item ID " + id + " - starting from the first chunk", "error"); handleResetResponse(id); handler.upload(id, true); } function handleNonResetErrorResponse(id, response, xhr) { var name = getName(id); if (spec.onAutoRetry(id, name, response, xhr)) { return; } else { if (xhr.status !== 200) { response.success = false; } handleCompletedItem(id, response, xhr); } } function onComplete(id, xhr) { var state = handler._getFileState(id), attemptingResume = state && state.attemptingResume, paused = state && state.paused, response; // The logic in this function targets uploads that have not been paused or canceled, // so return at once if this is not the case. if (!state || paused) { return; } log("xhr - server response received for " + id); log("responseText = " + xhr.responseText); response = parseResponse(id, xhr); if (isErrorResponse(xhr, response)) { if (response.reset) { handleResetResponse(id); } if (attemptingResume && response.reset) { handleResetResponseOnResumeAttempt(id); } else { handleNonResetErrorResponse(id, response, xhr); } } else if (chunkFiles) { handleSuccessfullyCompletedChunk(id, response, xhr); } else { handleCompletedItem(id, response, xhr); } } function getReadyStateChangeHandler(id, xhr) { return function() { if (xhr.readyState === 4) { onComplete(id, xhr); } }; } function persistChunkData(id, chunkData) { var fileUuid = getUuid(id), lastByteSent = handler._getFileState(id).loaded, initialRequestOverhead = handler._getFileState(id).initialRequestOverhead, estTotalRequestsSize = handler._getFileState(id).estTotalRequestsSize, cookieName = getChunkDataCookieName(id), cookieValue = fileUuid + cookieItemDelimiter + chunkData.part + cookieItemDelimiter + lastByteSent + cookieItemDelimiter + initialRequestOverhead + cookieItemDelimiter + estTotalRequestsSize, cookieExpDays = spec.resume.cookiesExpireIn; qq.setCookie(cookieName, cookieValue, cookieExpDays); } function deletePersistedChunkData(id) { if (handler._getFileState(id).file) { var cookieName = getChunkDataCookieName(id); qq.deleteCookie(cookieName); } } function getPersistedChunkData(id) { var chunkCookieValue = qq.getCookie(getChunkDataCookieName(id)), filename = getName(id), sections, uuid, partIndex, lastByteSent, initialRequestOverhead, estTotalRequestsSize; if (chunkCookieValue) { sections = chunkCookieValue.split(cookieItemDelimiter); if (sections.length === 5) { uuid = sections[0]; partIndex = parseInt(sections[1], 10); lastByteSent = parseInt(sections[2], 10); initialRequestOverhead = parseInt(sections[3], 10); estTotalRequestsSize = parseInt(sections[4], 10); return { uuid: uuid, part: partIndex, lastByteSent: lastByteSent, initialRequestOverhead: initialRequestOverhead, estTotalRequestsSize: estTotalRequestsSize }; } else { log("Ignoring previously stored resume/chunk cookie for " + filename + " - old cookie format", "warn"); } } } function getChunkDataCookieName(id) { var filename = getName(id), fileSize = getSize(id), maxChunkSize = spec.chunking.partSize, cookieName; cookieName = "qqfilechunk" + cookieItemDelimiter + encodeURIComponent(filename) + cookieItemDelimiter + fileSize + cookieItemDelimiter + maxChunkSize; if (resumeId !== undefined) { cookieName += cookieItemDelimiter + resumeId; } return cookieName; } function calculateRemainingChunkIdxsAndUpload(id, firstChunkIndex) { var currentChunkIndex; for (currentChunkIndex = handler._getTotalChunks(id)-1; currentChunkIndex >= firstChunkIndex; currentChunkIndex-=1) { handler._getFileState(id).remainingChunkIdxs.unshift(currentChunkIndex); } uploadNextChunk(id); } function onResumeSuccess(id, name, firstChunkIndex, persistedChunkInfoForResume) { firstChunkIndex = persistedChunkInfoForResume.part; handler._getFileState(id).loaded = persistedChunkInfoForResume.lastByteSent; handler._getFileState(id).estTotalRequestsSize = persistedChunkInfoForResume.estTotalRequestsSize; handler._getFileState(id).initialRequestOverhead = persistedChunkInfoForResume.initialRequestOverhead; handler._getFileState(id).attemptingResume = true; log("Resuming " + name + " at partition index " + firstChunkIndex); calculateRemainingChunkIdxsAndUpload(id, firstChunkIndex); } function handlePossibleResumeAttempt(id, persistedChunkInfoForResume, firstChunkIndex) { var name = getName(id), firstChunkDataForResume = handler._getChunkData(id, persistedChunkInfoForResume.part), onResumeRetVal; onResumeRetVal = spec.onResume(id, name, handler._getChunkDataForCallback(firstChunkDataForResume)); if (onResumeRetVal instanceof qq.Promise) { log("Waiting for onResume promise to be fulfilled for " + id); onResumeRetVal.then( function() { onResumeSuccess(id, name, firstChunkIndex, persistedChunkInfoForResume); }, function() { log("onResume promise fulfilled - failure indicated. Will not resume."); calculateRemainingChunkIdxsAndUpload(id, firstChunkIndex); } ); } else if (onResumeRetVal !== false) { onResumeSuccess(id, name, firstChunkIndex, persistedChunkInfoForResume); } else { log("onResume callback returned false. Will not resume."); calculateRemainingChunkIdxsAndUpload(id, firstChunkIndex); } } function handleFileChunkingUpload(id, retry) { var firstChunkIndex = 0, persistedChunkInfoForResume; if (!handler._getFileState(id).remainingChunkIdxs || handler._getFileState(id).remainingChunkIdxs.length === 0) { handler._getFileState(id).remainingChunkIdxs = []; if (resumeEnabled && !retry && handler._getFileState(id).file) { persistedChunkInfoForResume = getPersistedChunkData(id); if (persistedChunkInfoForResume) { handlePossibleResumeAttempt(id, persistedChunkInfoForResume, firstChunkIndex); } else { calculateRemainingChunkIdxsAndUpload(id, firstChunkIndex); } } else { calculateRemainingChunkIdxsAndUpload(id, firstChunkIndex); } } else { uploadNextChunk(id); } } function handleStandardFileUpload(id) { var fileOrBlob = handler._getFileState(id).file || handler._getFileState(id).blobData.blob, name = getName(id), xhr, params, toSend; handler._getFileState(id).loaded = 0; xhr = handler._createXhr(id); xhr.upload.onprogress = function(e){ if (e.lengthComputable){ handler._getFileState(id).loaded = e.loaded; spec.onProgress(id, name, e.loaded, e.total); } }; xhr.onreadystatechange = getReadyStateChangeHandler(id, xhr); params = spec.paramsStore.get(id); toSend = setParamsAndGetEntityToSend(params, xhr, fileOrBlob, id); setHeaders(id, xhr); log("Sending upload request for " + id); xhr.send(toSend); } function handleUploadSignal(id, retry) { var name = getName(id); if (handler.isValid(id)) { spec.onUpload(id, name); if (chunkFiles) { handleFileChunkingUpload(id, retry); } else { handleStandardFileUpload(id); } } } qq.extend(this, new qq.AbstractUploadHandlerXhr({ options: { chunking: chunkFiles ? spec.chunking : null }, proxy: { onUpload: handleUploadSignal, onCancel: spec.onCancel, onUuidChanged: onUuidChanged, getName: getName, getSize: getSize, getUuid: getUuid, log: log } } )); qq.override(this, function(super_) { return { add: function(id, fileOrBlobData) { var persistedChunkData; super_.add.apply(this, arguments); if (resumeEnabled) { persistedChunkData = getPersistedChunkData(id); if (persistedChunkData) { onUuidChanged(id, persistedChunkData.uuid); } } return id; }, getResumableFilesData: function() { var matchingCookieNames = [], resumableFilesData = []; if (chunkFiles && resumeEnabled) { if (resumeId === undefined) { matchingCookieNames = qq.getCookieNames(new RegExp("^qqfilechunk\\" + cookieItemDelimiter + ".+\\" + cookieItemDelimiter + "\\d+\\" + cookieItemDelimiter + spec.chunking.partSize + "=")); } else { matchingCookieNames = qq.getCookieNames(new RegExp("^qqfilechunk\\" + cookieItemDelimiter + ".+\\" + cookieItemDelimiter + "\\d+\\" + cookieItemDelimiter + spec.chunking.partSize + "\\" + cookieItemDelimiter + resumeId + "=")); } qq.each(matchingCookieNames, function(idx, cookieName) { var cookiesNameParts = cookieName.split(cookieItemDelimiter); var cookieValueParts = qq.getCookie(cookieName).split(cookieItemDelimiter); resumableFilesData.push({ name: decodeURIComponent(cookiesNameParts[1]), size: cookiesNameParts[2], uuid: cookieValueParts[0], partIdx: cookieValueParts[1] }); }); return resumableFilesData; } return []; }, expunge: function(id) { if (resumeEnabled) { deletePersistedChunkData(id); } super_.expunge(id); } }; }); }; /*globals qq*/ qq.PasteSupport = function(o) { "use strict"; var options, detachPasteHandler; options = { targetElement: null, callbacks: { log: function(message, level) {}, pasteReceived: function(blob) {} } }; function isImage(item) { return item.type && item.type.indexOf("image/") === 0; } function registerPasteHandler() { qq(options.targetElement).attach("paste", function(event) { var clipboardData = event.clipboardData; if (clipboardData) { qq.each(clipboardData.items, function(idx, item) { if (isImage(item)) { var blob = item.getAsFile(); options.callbacks.pasteReceived(blob); } }); } }); } function unregisterPasteHandler() { if (detachPasteHandler) { detachPasteHandler(); } } qq.extend(options, o); registerPasteHandler(); qq.extend(this, { reset: function() { unregisterPasteHandler(); } }); }; /*globals qq, document, CustomEvent*/ qq.DragAndDrop = function(o) { "use strict"; var options, HIDE_ZONES_EVENT_NAME = "qq-hidezones", HIDE_BEFORE_ENTER_ATTR = "qq-hide-dropzone", uploadDropZones = [], droppedFiles = [], disposeSupport = new qq.DisposeSupport(); options = { dropZoneElements: [], allowMultipleItems: true, classes: { dropActive: null }, callbacks: new qq.DragAndDrop.callbacks() }; qq.extend(options, o, true); function uploadDroppedFiles(files, uploadDropZone) { // We need to convert the `FileList` to an actual `Array` to avoid iteration issues var filesAsArray = Array.prototype.slice.call(files); options.callbacks.dropLog("Grabbed " + files.length + " dropped files."); uploadDropZone.dropDisabled(false); options.callbacks.processingDroppedFilesComplete(filesAsArray, uploadDropZone.getElement()); } function traverseFileTree(entry) { var dirReader, parseEntryPromise = new qq.Promise(); if (entry.isFile) { entry.file(function(file) { droppedFiles.push(file); parseEntryPromise.success(); }, function(fileError) { options.callbacks.dropLog("Problem parsing '" + entry.fullPath + "'. FileError code " + fileError.code + ".", "error"); parseEntryPromise.failure(); }); } else if (entry.isDirectory) { dirReader = entry.createReader(); dirReader.readEntries(function(entries) { var entriesLeft = entries.length; qq.each(entries, function(idx, entry) { traverseFileTree(entry).done(function() { entriesLeft-=1; if (entriesLeft === 0) { parseEntryPromise.success(); } }); }); if (!entries.length) { parseEntryPromise.success(); } }, function(fileError) { options.callbacks.dropLog("Problem parsing '" + entry.fullPath + "'. FileError code " + fileError.code + ".", "error"); parseEntryPromise.failure(); }); } return parseEntryPromise; } function handleDataTransfer(dataTransfer, uploadDropZone) { var pendingFolderPromises = [], handleDataTransferPromise = new qq.Promise(); options.callbacks.processingDroppedFiles(); uploadDropZone.dropDisabled(true); if (dataTransfer.files.length > 1 && !options.allowMultipleItems) { options.callbacks.processingDroppedFilesComplete([]); options.callbacks.dropError("tooManyFilesError", ""); uploadDropZone.dropDisabled(false); handleDataTransferPromise.failure(); } else { droppedFiles = []; if (qq.isFolderDropSupported(dataTransfer)) { qq.each(dataTransfer.items, function(idx, item) { var entry = item.webkitGetAsEntry(); if (entry) { //due to a bug in Chrome's File System API impl - #149735 if (entry.isFile) { droppedFiles.push(item.getAsFile()); } else { pendingFolderPromises.push(traverseFileTree(entry).done(function() { pendingFolderPromises.pop(); if (pendingFolderPromises.length === 0) { handleDataTransferPromise.success(); } })); } } }); } else { droppedFiles = dataTransfer.files; } if (pendingFolderPromises.length === 0) { handleDataTransferPromise.success(); } } return handleDataTransferPromise; } function setupDropzone(dropArea) { var dropZone = new qq.UploadDropZone({ HIDE_ZONES_EVENT_NAME: HIDE_ZONES_EVENT_NAME, element: dropArea, onEnter: function(e){ qq(dropArea).addClass(options.classes.dropActive); e.stopPropagation(); }, onLeaveNotDescendants: function(e){ qq(dropArea).removeClass(options.classes.dropActive); }, onDrop: function(e){ handleDataTransfer(e.dataTransfer, dropZone).then( function() { uploadDroppedFiles(droppedFiles, dropZone); }, function() { options.callbacks.dropLog("Drop event DataTransfer parsing failed. No files will be uploaded.", "error"); } ); } }); disposeSupport.addDisposer(function() { dropZone.dispose(); }); qq(dropArea).hasAttribute(HIDE_BEFORE_ENTER_ATTR) && qq(dropArea).hide(); uploadDropZones.push(dropZone); return dropZone; } function isFileDrag(dragEvent) { var fileDrag; qq.each(dragEvent.dataTransfer.types, function(key, val) { if (val === "Files") { fileDrag = true; return false; } }); return fileDrag; } function leavingDocumentOut(e) { /* jshint -W041, eqeqeq:false */ // null coords for Chrome and Safari Windows return ((qq.chrome() || (qq.safari() && qq.windows())) && e.clientX == 0 && e.clientY == 0) || // null e.relatedTarget for Firefox (qq.firefox() && !e.relatedTarget); } function setupDragDrop() { var dropZones = options.dropZoneElements; qq.each(dropZones, function(idx, dropZone) { var uploadDropZone = setupDropzone(dropZone); // IE <= 9 does not support the File API used for drag+drop uploads if (dropZones.length && (!qq.ie() || qq.ie10())) { disposeSupport.attach(document, "dragenter", function(e) { if (!uploadDropZone.dropDisabled() && isFileDrag(e)) { qq.each(dropZones, function(idx, dropZone) { // We can't apply styles to non-HTMLElements, since they lack the `style` property if (dropZone instanceof HTMLElement) { qq(dropZone).css({display: "block"}); } }); } }); } }); disposeSupport.attach(document, "dragleave", function(e) { if (leavingDocumentOut(e)) { qq.each(dropZones, function(idx, dropZone) { qq(dropZone).hasAttribute(HIDE_BEFORE_ENTER_ATTR) && qq(dropZone).hide(); }); } }); disposeSupport.attach(document, "drop", function(e){ qq.each(dropZones, function(idx, dropZone) { qq(dropZone).hasAttribute(HIDE_BEFORE_ENTER_ATTR) && qq(dropZone).hide(); }); e.preventDefault(); }); disposeSupport.attach(document, HIDE_ZONES_EVENT_NAME, function(e) { qq.each(options.dropZoneElements, function(idx, zone) { qq(zone).hasAttribute(HIDE_BEFORE_ENTER_ATTR) && qq(zone).hide(); qq(zone).removeClass(options.classes.dropActive); }); }); } setupDragDrop(); qq.extend(this, { setupExtraDropzone: function(element) { options.dropZoneElements.push(element); setupDropzone(element); }, removeDropzone: function(element) { var i, dzs = options.dropZoneElements; for(i in dzs) { if (dzs[i] === element) { return dzs.splice(i, 1); } } }, dispose: function() { disposeSupport.dispose(); qq.each(uploadDropZones, function(idx, dropZone) { dropZone.dispose(); }); } }); }; qq.DragAndDrop.callbacks = function() { "use strict"; return { processingDroppedFiles: function() {}, processingDroppedFilesComplete: function(files, targetEl) {}, dropError: function(code, errorSpecifics) { qq.log("Drag & drop error code '" + code + " with these specifics: '" + errorSpecifics + "'", "error"); }, dropLog: function(message, level) { qq.log(message, level); } }; }; qq.UploadDropZone = function(o){ "use strict"; var disposeSupport = new qq.DisposeSupport(), options, element, preventDrop, dropOutsideDisabled; options = { element: null, onEnter: function(e){}, onLeave: function(e){}, // is not fired when leaving element by hovering descendants onLeaveNotDescendants: function(e){}, onDrop: function(e){} }; qq.extend(options, o); element = options.element; function dragover_should_be_canceled(){ return qq.safari() || (qq.firefox() && qq.windows()); } function disableDropOutside(e){ // run only once for all instances if (!dropOutsideDisabled ){ // for these cases we need to catch onDrop to reset dropArea if (dragover_should_be_canceled){ disposeSupport.attach(document, "dragover", function(e){ e.preventDefault(); }); } else { disposeSupport.attach(document, "dragover", function(e){ if (e.dataTransfer){ e.dataTransfer.dropEffect = "none"; e.preventDefault(); } }); } dropOutsideDisabled = true; } } function isValidFileDrag(e){ // e.dataTransfer currently causing IE errors // IE9 does NOT support file API, so drag-and-drop is not possible if (qq.ie() && !qq.ie10()) { return false; } var effectTest, dt = e.dataTransfer, // do not check dt.types.contains in webkit, because it crashes safari 4 isSafari = qq.safari(); // dt.effectAllowed is none in Safari 5 // dt.types.contains check is for firefox // dt.effectAllowed crashes IE11 when files have been dragged from // the filesystem effectTest = (qq.ie10() || qq.ie11()) ? true : dt.effectAllowed !== "none"; return dt && effectTest && (dt.files || (!isSafari && dt.types.contains && dt.types.contains("Files"))); } function isOrSetDropDisabled(isDisabled) { if (isDisabled !== undefined) { preventDrop = isDisabled; } return preventDrop; } function triggerHidezonesEvent() { var hideZonesEvent; function triggerUsingOldApi() { hideZonesEvent = document.createEvent("Event"); hideZonesEvent.initEvent(options.HIDE_ZONES_EVENT_NAME, true, true); } if (window.CustomEvent) { try { hideZonesEvent = new CustomEvent(options.HIDE_ZONES_EVENT_NAME); } catch (err) { triggerUsingOldApi(); } } else { triggerUsingOldApi(); } document.dispatchEvent(hideZonesEvent); } function attachEvents(){ disposeSupport.attach(element, "dragover", function(e){ if (!isValidFileDrag(e)) { return; } // dt.effectAllowed crashes IE11 when files have been dragged from // the filesystem var effect = (qq.ie() || qq.ie11()) ? null : e.dataTransfer.effectAllowed; if (effect === "move" || effect === "linkMove"){ e.dataTransfer.dropEffect = "move"; // for FF (only move allowed) } else { e.dataTransfer.dropEffect = "copy"; // for Chrome } e.stopPropagation(); e.preventDefault(); }); disposeSupport.attach(element, "dragenter", function(e){ if (!isOrSetDropDisabled()) { if (!isValidFileDrag(e)) { return; } options.onEnter(e); } }); disposeSupport.attach(element, "dragleave", function(e){ if (!isValidFileDrag(e)) { return; } options.onLeave(e); var relatedTarget = document.elementFromPoint(e.clientX, e.clientY); // do not fire when moving a mouse over a descendant if (qq(this).contains(relatedTarget)) { return; } options.onLeaveNotDescendants(e); }); disposeSupport.attach(element, "drop", function(e) { if (!isOrSetDropDisabled()) { if (!isValidFileDrag(e)) { return; } e.preventDefault(); e.stopPropagation(); options.onDrop(e); triggerHidezonesEvent(); } }); } disableDropOutside(); attachEvents(); qq.extend(this, { dropDisabled: function(isDisabled) { return isOrSetDropDisabled(isDisabled); }, dispose: function() { disposeSupport.dispose(); }, getElement: function() { return element; } }); }; /*globals qq, XMLHttpRequest*/ qq.DeleteFileAjaxRequester = function(o) { "use strict"; var requester, options = { method: "DELETE", uuidParamName: "qquuid", endpointStore: {}, maxConnections: 3, customHeaders: {}, paramsStore: {}, demoMode: false, cors: { expected: false, sendCredentials: false }, log: function(str, level) {}, onDelete: function(id) {}, onDeleteComplete: function(id, xhrOrXdr, isError) {} }; qq.extend(options, o); function getMandatedParams() { if (options.method.toUpperCase() === "POST") { return { "_method": "DELETE" }; } return {}; } requester = qq.extend(this, new qq.AjaxRequester({ validMethods: ["POST", "DELETE"], method: options.method, endpointStore: options.endpointStore, paramsStore: options.paramsStore, mandatedParams: getMandatedParams(), maxConnections: options.maxConnections, customHeaders: options.customHeaders, demoMode: options.demoMode, log: options.log, onSend: options.onDelete, onComplete: options.onDeleteComplete, cors: options.cors })); qq.extend(this, { sendDelete: function(id, uuid, additionalMandatedParams) { var additionalOptions = additionalMandatedParams || {}; options.log("Submitting delete file request for " + id); if (options.method === "DELETE") { requester.initTransport(id) .withPath(uuid) .withParams(additionalOptions) .send(); } else { additionalOptions[options.uuidParamName] = uuid; requester.initTransport(id) .withParams(additionalOptions) .send(); } } }); }; /*global qq, define */ /*jshint strict:false,bitwise:false,nonew:false,asi:true,-W064,-W116,-W089 */ /** * Mega pixel image rendering library for iOS6 Safari * * Fixes iOS6 Safari's image file rendering issue for large size image (over mega-pixel), * which causes unexpected subsampling when drawing it in canvas. * By using this library, you can safely render the image with proper stretching. * * Copyright (c) 2012 Shinichi Tomita <shinichi.tomita@gmail.com> * Released under the MIT license */ (function() { /** * Detect subsampling in loaded image. * In iOS, larger images than 2M pixels may be subsampled in rendering. */ function detectSubsampling(img) { var iw = img.naturalWidth, ih = img.naturalHeight; if (iw * ih > 1024 * 1024) { // subsampling may happen over megapixel image var canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; var ctx = canvas.getContext('2d'); ctx.drawImage(img, -iw + 1, 0); // subsampled image becomes half smaller in rendering size. // check alpha channel value to confirm image is covering edge pixel or not. // if alpha value is 0 image is not covering, hence subsampled. return ctx.getImageData(0, 0, 1, 1).data[3] === 0; } else { return false; } } /** * Detecting vertical squash in loaded image. * Fixes a bug which squash image vertically while drawing into canvas for some images. */ function detectVerticalSquash(img, iw, ih) { var canvas = document.createElement('canvas'); canvas.width = 1; canvas.height = ih; var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); var data = ctx.getImageData(0, 0, 1, ih).data; // search image edge pixel position in case it is squashed vertically. var sy = 0; var ey = ih; var py = ih; while (py > sy) { var alpha = data[(py - 1) * 4 + 3]; if (alpha === 0) { ey = py; } else { sy = py; } py = (ey + sy) >> 1; } var ratio = (py / ih); return (ratio===0)?1:ratio; } /** * Rendering image element (with resizing) and get its data URL */ function renderImageToDataURL(img, options, doSquash) { var canvas = document.createElement('canvas'), mime = options.mime || "image/jpeg"; renderImageToCanvas(img, canvas, options, doSquash); return canvas.toDataURL(mime, options.quality || 0.8); } /** * Rendering image element (with resizing) into the canvas element */ function renderImageToCanvas(img, canvas, options, doSquash) { var iw = img.naturalWidth, ih = img.naturalHeight; var width = options.width, height = options.height; var ctx = canvas.getContext('2d'); ctx.save(); transformCoordinate(canvas, width, height, options.orientation); // Fine Uploader specific: Save some CPU cycles if not using iOS // Assumption: This logic is only needed to overcome iOS image sampling issues if (qq.ios()) { var subsampled = detectSubsampling(img); if (subsampled) { iw /= 2; ih /= 2; } var d = 1024; // size of tiling canvas var tmpCanvas = document.createElement('canvas'); tmpCanvas.width = tmpCanvas.height = d; var tmpCtx = tmpCanvas.getContext('2d'); var vertSquashRatio = doSquash ? detectVerticalSquash(img, iw, ih) : 1; var dw = Math.ceil(d * width / iw); var dh = Math.ceil(d * height / ih / vertSquashRatio); var sy = 0; var dy = 0; while (sy < ih) { var sx = 0; var dx = 0; while (sx < iw) { tmpCtx.clearRect(0, 0, d, d); tmpCtx.drawImage(img, -sx, -sy); ctx.drawImage(tmpCanvas, 0, 0, d, d, dx, dy, dw, dh); sx += d; dx += dw; } sy += d; dy += dh; } ctx.restore(); tmpCanvas = tmpCtx = null; } else { ctx.drawImage(img, 0, 0, width, height); } } /** * Transform canvas coordination according to specified frame size and orientation * Orientation value is from EXIF tag */ function transformCoordinate(canvas, width, height, orientation) { switch (orientation) { case 5: case 6: case 7: case 8: canvas.width = height; canvas.height = width; break; default: canvas.width = width; canvas.height = height; } var ctx = canvas.getContext('2d'); switch (orientation) { case 2: // horizontal flip ctx.translate(width, 0); ctx.scale(-1, 1); break; case 3: // 180 rotate left ctx.translate(width, height); ctx.rotate(Math.PI); break; case 4: // vertical flip ctx.translate(0, height); ctx.scale(1, -1); break; case 5: // vertical flip + 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.scale(1, -1); break; case 6: // 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.translate(0, -height); break; case 7: // horizontal flip + 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.translate(width, -height); ctx.scale(-1, 1); break; case 8: // 90 rotate left ctx.rotate(-0.5 * Math.PI); ctx.translate(-width, 0); break; default: break; } } /** * MegaPixImage class */ function MegaPixImage(srcImage, errorCallback) { if (window.Blob && srcImage instanceof Blob) { var img = new Image(); var URL = window.URL && window.URL.createObjectURL ? window.URL : window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL : null; if (!URL) { throw Error("No createObjectURL function found to create blob url"); } img.src = URL.createObjectURL(srcImage); this.blob = srcImage; srcImage = img; } if (!srcImage.naturalWidth && !srcImage.naturalHeight) { var _this = this; srcImage.onload = function() { var listeners = _this.imageLoadListeners; if (listeners) { _this.imageLoadListeners = null; for (var i=0, len=listeners.length; i<len; i++) { listeners[i](); } } }; srcImage.onerror = errorCallback; this.imageLoadListeners = []; } this.srcImage = srcImage; } /** * Rendering megapix image into specified target element */ MegaPixImage.prototype.render = function(target, options) { if (this.imageLoadListeners) { var _this = this; this.imageLoadListeners.push(function() { _this.render(target, options) }); return; } options = options || {}; var imgWidth = this.srcImage.naturalWidth, imgHeight = this.srcImage.naturalHeight, width = options.width, height = options.height, maxWidth = options.maxWidth, maxHeight = options.maxHeight, doSquash = !this.blob || this.blob.type === 'image/jpeg'; if (width && !height) { height = (imgHeight * width / imgWidth) << 0; } else if (height && !width) { width = (imgWidth * height / imgHeight) << 0; } else { width = imgWidth; height = imgHeight; } if (maxWidth && width > maxWidth) { width = maxWidth; height = (imgHeight * width / imgWidth) << 0; } if (maxHeight && height > maxHeight) { height = maxHeight; width = (imgWidth * height / imgHeight) << 0; } var opt = { width : width, height : height }; for (var k in options) opt[k] = options[k]; var tagName = target.tagName.toLowerCase(); if (tagName === 'img') { target.src = renderImageToDataURL(this.srcImage, opt, doSquash); } else if (tagName === 'canvas') { renderImageToCanvas(this.srcImage, target, opt, doSquash); } if (typeof this.onrender === 'function') { this.onrender(target); } }; /** * Export class to global */ if (typeof define === 'function' && define.amd) { define([], function() { return MegaPixImage; }); // for AMD loader } else { this.MegaPixImage = MegaPixImage; } })(); /*globals qq, MegaPixImage */ /** * Draws a thumbnail of a Blob/File/URL onto an <img> or <canvas>. * * @constructor */ qq.ImageGenerator = function(log) { "use strict"; function isImg(el) { return el.tagName.toLowerCase() === "img"; } function isCanvas(el) { return el.tagName.toLowerCase() === "canvas"; } function isImgCorsSupported() { return new Image().crossOrigin !== undefined; } function isCanvasSupported() { var canvas = document.createElement("canvas"); return canvas.getContext && canvas.getContext("2d"); } // This is only meant to determine the MIME type of a renderable image file. // It is used to ensure images drawn from a URL that have transparent backgrounds // are rendered correctly, among other things. function determineMimeOfFileName(nameWithPath) { /*jshint -W015 */ var pathSegments = nameWithPath.split("/"), name = pathSegments[pathSegments.length - 1], extension = qq.getExtension(name); extension = extension && extension.toLowerCase(); switch(extension) { case "jpeg": case "jpg": return "image/jpeg"; case "png": return "image/png"; case "bmp": return "image/bmp"; case "gif": return "image/gif"; case "tiff": case "tif": return "image/tiff"; } } // This will likely not work correctly in IE8 and older. // It's only used as part of a formula to determine // if a canvas can be used to scale a server-hosted thumbnail. // If canvas isn't supported by the UA (IE8 and older) // this method should not even be called. function isCrossOrigin(url) { var targetAnchor = document.createElement("a"), targetProtocol, targetHostname, targetPort; targetAnchor.href = url; targetProtocol = targetAnchor.protocol; targetPort = targetAnchor.port; targetHostname = targetAnchor.hostname; if (targetProtocol.toLowerCase() !== window.location.protocol.toLowerCase()) { return true; } if (targetHostname.toLowerCase() !== window.location.hostname.toLowerCase()) { return true; } // IE doesn't take ports into consideration when determining if two endpoints are same origin. if (targetPort !== window.location.port && !qq.ie()) { return true; } return false; } function registerImgLoadListeners(img, promise) { img.onload = function() { img.onload = null; img.onerror = null; promise.success(img); }; img.onerror = function() { img.onload = null; img.onerror = null; log("Problem drawing thumbnail!", "error"); promise.failure(img, "Problem drawing thumbnail!"); }; } function registerCanvasDrawImageListener(canvas, promise) { var context = canvas.getContext("2d"), oldDrawImage = context.drawImage; // The image is drawn on the canvas by a third-party library, // and we want to know when this happens so we can fulfill the associated promise. context.drawImage = function() { oldDrawImage.apply(this, arguments); promise.success(canvas); context.drawImage = oldDrawImage; }; } // Fulfills a `qq.Promise` when an image has been drawn onto the target, // whether that is a <canvas> or an <img>. The attempt is considered a // failure if the target is not an <img> or a <canvas>, or if the drawing // attempt was not successful. function registerThumbnailRenderedListener(imgOrCanvas, promise) { var registered = isImg(imgOrCanvas) || isCanvas(imgOrCanvas); if (isImg(imgOrCanvas)) { registerImgLoadListeners(imgOrCanvas, promise); } else if (isCanvas(imgOrCanvas)) { registerCanvasDrawImageListener(imgOrCanvas, promise); } else { promise.failure(imgOrCanvas); log(qq.format("Element container of type {} is not supported!", imgOrCanvas.tagName), "error"); } return registered; } // Draw a preview iff the current UA can natively display it. // Also rotate the image if necessary. function draw(fileOrBlob, container, options) { var drawPreview = new qq.Promise(), identifier = new qq.Identify(fileOrBlob, log), maxSize = options.maxSize, megapixErrorHandler = function() { container.onerror = null; container.onload = null; log("Could not render preview, file may be too large!", "error"); drawPreview.failure(container, "Browser cannot render image!"); }; identifier.isPreviewable().then( function(mime) { var exif = new qq.Exif(fileOrBlob, log), mpImg = new MegaPixImage(fileOrBlob, megapixErrorHandler); if (registerThumbnailRenderedListener(container, drawPreview)) { exif.parse().then( function(exif) { var orientation = exif.Orientation; mpImg.render(container, { maxWidth: maxSize, maxHeight: maxSize, orientation: orientation, mime: mime }); }, function(failureMsg) { log(qq.format("EXIF data could not be parsed ({}). Assuming orientation = 1.", failureMsg)); mpImg.render(container, { maxWidth: maxSize, maxHeight: maxSize, mime: mime }); } ); } }, function() { log("Not previewable"); drawPreview.failure(container, "Not previewable"); } ); return drawPreview; } function drawOnCanvasOrImgFromUrl(url, canvasOrImg, draw, maxSize) { var tempImg = new Image(), tempImgRender = new qq.Promise(); registerThumbnailRenderedListener(tempImg, tempImgRender); if (isCrossOrigin(url)) { tempImg.crossOrigin = "anonymous"; } tempImg.src = url; tempImgRender.then(function() { registerThumbnailRenderedListener(canvasOrImg, draw); var mpImg = new MegaPixImage(tempImg); mpImg.render(canvasOrImg, { maxWidth: maxSize, maxHeight: maxSize, mime: determineMimeOfFileName(url) }); }); } function drawOnImgFromUrlWithCssScaling(url, img, draw, maxSize) { registerThumbnailRenderedListener(img, draw); qq(img).css({ maxWidth: maxSize + "px", maxHeight: maxSize + "px" }); img.src = url; } // Draw a (server-hosted) thumbnail given a URL. // This will optionally scale the thumbnail as well. // It attempts to use <canvas> to scale, but will fall back // to max-width and max-height style properties if the UA // doesn't support canvas or if the images is cross-domain and // the UA doesn't support the crossorigin attribute on img tags, // which is required to scale a cross-origin image using <canvas> & // then export it back to an <img>. function drawFromUrl(url, container, options) { var draw = new qq.Promise(), scale = options.scale, maxSize = scale ? options.maxSize : null; // container is an img, scaling needed if (scale && isImg(container)) { // Iff canvas is available in this UA, try to use it for scaling. // Otherwise, fall back to CSS scaling if (isCanvasSupported()) { // Attempt to use <canvas> for image scaling, // but we must fall back to scaling via CSS/styles // if this is a cross-origin image and the UA doesn't support <img> CORS. if (isCrossOrigin(url) && !isImgCorsSupported()) { drawOnImgFromUrlWithCssScaling(url, container, draw, maxSize); } else { drawOnCanvasOrImgFromUrl(url, container, draw, maxSize); } } else { drawOnImgFromUrlWithCssScaling(url, container, draw, maxSize); } } // container is a canvas, scaling optional else if (isCanvas(container)) { drawOnCanvasOrImgFromUrl(url, container, draw, maxSize); } // container is an img & no scaling: just set the src attr to the passed url else if (registerThumbnailRenderedListener(container, draw)) { container.src = url; } return draw; } qq.extend(this, { /** * Generate a thumbnail. Depending on the arguments, this may either result in * a client-side rendering of an image (if a `Blob` is supplied) or a server-generated * image that may optionally be scaled client-side using <canvas> or CSS/styles (as a fallback). * * @param fileBlobOrUrl a `File`, `Blob`, or a URL pointing to the image * @param container <img> or <canvas> to contain the preview * @param options possible properties include `maxSize` (int), `orient` (bool), and `resize` (bool) * @returns qq.Promise fulfilled when the preview has been drawn, or the attempt has failed */ generate: function(fileBlobOrUrl, container, options) { if (qq.isString(fileBlobOrUrl)) { log("Attempting to update thumbnail based on server response."); return drawFromUrl(fileBlobOrUrl, container, options || {}); } else { log("Attempting to draw client-side image preview."); return draw(fileBlobOrUrl, container, options || {}); } } }); /*<testing>*/ this._testing = {}; this._testing.isImg = isImg; this._testing.isCanvas = isCanvas; this._testing.isCrossOrigin = isCrossOrigin; this._testing.determineMimeOfFileName = determineMimeOfFileName; /*</testing>*/ }; /*globals qq */ /** * EXIF image data parser. Currently only parses the Orientation tag value, * but this may be expanded to other tags in the future. * * @param fileOrBlob Attempt to parse EXIF data in this `Blob` * @constructor */ qq.Exif = function(fileOrBlob, log) { "use strict"; // Orientation is the only tag parsed here at this time. var TAG_IDS = [274], TAG_INFO = { 274: { name: "Orientation", bytes: 2 } }; // Convert a little endian (hex string) to big endian (decimal). function parseLittleEndian(hex) { var result = 0, pow = 0; while (hex.length > 0) { result += parseInt(hex.substring(0, 2), 16) * Math.pow(2, pow); hex = hex.substring(2, hex.length); pow += 8; } return result; } // Find the byte offset, of Application Segment 1 (EXIF). // External callers need not supply any arguments. function seekToApp1(offset, promise) { var theOffset = offset, thePromise = promise; if (theOffset === undefined) { theOffset = 2; thePromise = new qq.Promise(); } qq.readBlobToHex(fileOrBlob, theOffset, 4).then(function(hex) { var match = /^ffe([0-9])/.exec(hex); if (match) { if (match[1] !== "1") { var segmentLength = parseInt(hex.slice(4, 8), 16); seekToApp1(theOffset + segmentLength + 2, thePromise); } else { thePromise.success(theOffset); } } else { thePromise.failure("No EXIF header to be found!"); } }); return thePromise; } // Find the byte offset of Application Segment 1 (EXIF) for valid JPEGs only. function getApp1Offset() { var promise = new qq.Promise(); qq.readBlobToHex(fileOrBlob, 0, 6).then(function(hex) { if (hex.indexOf("ffd8") !== 0) { promise.failure("Not a valid JPEG!"); } else { seekToApp1().then(function(offset) { promise.success(offset); }, function(error) { promise.failure(error); }); } }); return promise; } // Determine the byte ordering of the EXIF header. function isLittleEndian(app1Start) { var promise = new qq.Promise(); qq.readBlobToHex(fileOrBlob, app1Start + 10, 2).then(function(hex) { promise.success(hex === "4949"); }); return promise; } // Determine the number of directory entries in the EXIF header. function getDirEntryCount(app1Start, littleEndian) { var promise = new qq.Promise(); qq.readBlobToHex(fileOrBlob, app1Start + 18, 2).then(function(hex) { if (littleEndian) { return promise.success(parseLittleEndian(hex)); } else { promise.success(parseInt(hex, 16)); } }); return promise; } // Get the IFD portion of the EXIF header as a hex string. function getIfd(app1Start, dirEntries) { var offset = app1Start + 20, bytes = dirEntries * 12; return qq.readBlobToHex(fileOrBlob, offset, bytes); } // Obtain an array of all directory entries (as hex strings) in the EXIF header. function getDirEntries(ifdHex) { var entries = [], offset = 0; while (offset+24 <= ifdHex.length) { entries.push(ifdHex.slice(offset, offset + 24)); offset += 24; } return entries; } // Obtain values for all relevant tags and return them. function getTagValues(littleEndian, dirEntries) { var TAG_VAL_OFFSET = 16, tagsToFind = qq.extend([], TAG_IDS), vals = {}; qq.each(dirEntries, function(idx, entry) { var idHex = entry.slice(0, 4), id = littleEndian ? parseLittleEndian(idHex) : parseInt(idHex, 16), tagsToFindIdx = tagsToFind.indexOf(id), tagValHex, tagName, tagValLength; if (tagsToFindIdx >= 0) { tagName = TAG_INFO[id].name; tagValLength = TAG_INFO[id].bytes; tagValHex = entry.slice(TAG_VAL_OFFSET, TAG_VAL_OFFSET + (tagValLength*2)); vals[tagName] = littleEndian ? parseLittleEndian(tagValHex) : parseInt(tagValHex, 16); tagsToFind.splice(tagsToFindIdx, 1); } if (tagsToFind.length === 0) { return false; } }); return vals; } qq.extend(this, { /** * Attempt to parse the EXIF header for the `Blob` associated with this instance. * * @returns {qq.Promise} To be fulfilled when the parsing is complete. * If successful, the parsed EXIF header as an object will be included. */ parse: function() { var parser = new qq.Promise(), onParseFailure = function(message) { log(qq.format("EXIF header parse failed: '{}' ", message)); parser.failure(message); }; getApp1Offset().then(function(app1Offset) { log(qq.format("Moving forward with EXIF header parsing for '{}'", fileOrBlob.name === undefined ? "blob" : fileOrBlob.name)); isLittleEndian(app1Offset).then(function(littleEndian) { log(qq.format("EXIF Byte order is {} endian", littleEndian ? "little" : "big")); getDirEntryCount(app1Offset, littleEndian).then(function(dirEntryCount) { log(qq.format("Found {} APP1 directory entries", dirEntryCount)); getIfd(app1Offset, dirEntryCount).then(function(ifdHex) { var dirEntries = getDirEntries(ifdHex), tagValues = getTagValues(littleEndian, dirEntries); log("Successfully parsed some EXIF tags"); parser.success(tagValues); }, onParseFailure); }, onParseFailure); }, onParseFailure); }, onParseFailure); return parser; } }); /*<testing>*/ this._testing = {}; this._testing.parseLittleEndian = parseLittleEndian; /*</testing>*/ }; /*globals qq */ qq.Identify = function(fileOrBlob, log) { "use strict"; var PREVIEWABLE_MAGIC_BYTES = { "image/jpeg": "ffd8ff", "image/gif": "474946", "image/png": "89504e", "image/bmp": "424d", "image/tiff": ["49492a00", "4d4d002a"] }; function isIdentifiable(magicBytes, questionableBytes) { var identifiable = false, magicBytesEntries = [].concat(magicBytes); qq.each(magicBytesEntries, function(idx, magicBytesArrayEntry) { if (questionableBytes.indexOf(magicBytesArrayEntry) === 0) { identifiable = true; return false; } }); return identifiable; } qq.extend(this, { isPreviewable: function() { var idenitifer = new qq.Promise(), previewable = false, name = fileOrBlob.name === undefined ? "blob" : fileOrBlob.name; log(qq.format("Attempting to determine if {} can be rendered in this browser", name)); qq.readBlobToHex(fileOrBlob, 0, 4).then(function(hex) { qq.each(PREVIEWABLE_MAGIC_BYTES, function(mime, bytes) { if (isIdentifiable(bytes, hex)) { // Safari is the only supported browser that can deal with TIFFs natively, // so, if this is a TIFF and the UA isn't Safari, declare this file "non-previewable". if (mime !== "image/tiff" || qq.safari()) { previewable = true; idenitifer.success(mime); } return false; } }); log(qq.format("'{}' is {} able to be rendered in this browser", name, previewable ? "" : "NOT")); if (!previewable) { idenitifer.failure(); } }); return idenitifer; } }); }; /*globals qq*/ /** * Attempts to validate an image, wherever possible. * * @param blob File or Blob representing a user-selecting image. * @param log Uses this to post log messages to the console. * @constructor */ qq.ImageValidation = function(blob, log) { "use strict"; /** * @param limits Object with possible image-related limits to enforce. * @returns {boolean} true if at least one of the limits has a non-zero value */ function hasNonZeroLimits(limits) { var atLeastOne = false; qq.each(limits, function(limit, value) { if (value > 0) { atLeastOne = true; return false; } }); return atLeastOne; } /** * @returns {qq.Promise} The promise is a failure if we can't obtain the width & height. * Otherwise, `success` is called on the returned promise with an object containing * `width` and `height` properties. */ function getWidthHeight() { var sizeDetermination = new qq.Promise(); new qq.Identify(blob, log).isPreviewable().then(function() { var image = new Image(), url = window.URL && window.URL.createObjectURL ? window.URL : window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL : null; if (url) { image.onerror = function() { log("Cannot determine dimensions for image. May be too large.", "error"); sizeDetermination.failure(); }; image.onload = function() { sizeDetermination.success({ width: this.width, height: this.height }); }; image.src = url.createObjectURL(blob); } else { log("No createObjectURL function available to generate image URL!", "error"); sizeDetermination.failure(); } }, sizeDetermination.failure); return sizeDetermination; } /** * * @param limits Object with possible image-related limits to enforce. * @param dimensions Object containing `width` & `height` properties for the image to test. * @returns {String || undefined} The name of the failing limit. Undefined if no failing limits. */ function getFailingLimit(limits, dimensions) { var failingLimit; qq.each(limits, function(limitName, limitValue) { if (limitValue > 0) { var limitMatcher = /(max|min)(Width|Height)/.exec(limitName), dimensionPropName = limitMatcher[2].charAt(0).toLowerCase() + limitMatcher[2].slice(1), actualValue = dimensions[dimensionPropName]; /*jshint -W015*/ switch(limitMatcher[1]) { case "min": if (actualValue < limitValue) { failingLimit = limitName; return false; } break; case "max": if (actualValue > limitValue) { failingLimit = limitName; return false; } break; } } }); return failingLimit; } /** * Validate the associated blob. * * @param limits * @returns {qq.Promise} `success` is called on the promise is the image is valid or * if the blob is not an image, or if the image is not verifiable. * Otherwise, `failure` with the name of the failing limit. */ this.validate = function(limits) { var validationEffort = new qq.Promise(); log("Attempting to validate image."); if (hasNonZeroLimits(limits)) { getWidthHeight().then(function(dimensions) { var failingLimit = getFailingLimit(limits, dimensions); if (failingLimit) { validationEffort.failure(failingLimit); } else { validationEffort.success(); } }, validationEffort.success); } else { validationEffort.success(); } return validationEffort; }; }; /* globals qq */ /** * Module used to control populating the initial list of files. * * @constructor */ qq.Session = function(spec) { "use strict"; var options = { endpoint: null, params: {}, customHeaders: {}, cors: {}, addFileRecord: function(sessionData) {}, log: function(message, level) {} }; qq.extend(options, spec, true); function isJsonResponseValid(response) { if (qq.isArray(response)) { return true; } options.log("Session response is not an array.", "error"); } function handleFileItems(fileItems, success, xhrOrXdr, promise) { var someItemsIgnored = false; success = success && isJsonResponseValid(fileItems); if (success) { qq.each(fileItems, function(idx, fileItem) { /* jshint eqnull:true */ if (fileItem.uuid == null) { someItemsIgnored = true; options.log(qq.format("Session response item {} did not include a valid UUID - ignoring.", idx), "error"); } else if (fileItem.name == null) { someItemsIgnored = true; options.log(qq.format("Session response item {} did not include a valid name - ignoring.", idx), "error"); } else { try { options.addFileRecord(fileItem); return true; } catch(err) { someItemsIgnored = true; options.log(err.message, "error"); } } return false; }); } promise[success && !someItemsIgnored ? "success" : "failure"](fileItems, xhrOrXdr); } // Initiate a call to the server that will be used to populate the initial file list. // Returns a `qq.Promise`. this.refresh = function() { /*jshint indent:false */ var refreshEffort = new qq.Promise(), refreshCompleteCallback = function(response, success, xhrOrXdr) { handleFileItems(response, success, xhrOrXdr, refreshEffort); }, requsterOptions = qq.extend({}, options), requester = new qq.SessionAjaxRequester( qq.extend(requsterOptions, {onComplete: refreshCompleteCallback}) ); requester.queryServer(); return refreshEffort; }; }; /*globals qq, XMLHttpRequest*/ /** * Thin module used to send GET requests to the server, expecting information about session * data used to initialize an uploader instance. * * @param spec Various options used to influence the associated request. * @constructor */ qq.SessionAjaxRequester = function(spec) { "use strict"; var requester, options = { endpoint: null, customHeaders: {}, params: {}, cors: { expected: false, sendCredentials: false }, onComplete: function(response, success, xhrOrXdr) {}, log: function(str, level) {} }; qq.extend(options, spec); function onComplete(id, xhrOrXdr, isError) { var response = null; /* jshint eqnull:true */ if (xhrOrXdr.responseText != null) { try { response = qq.parseJson(xhrOrXdr.responseText); } catch(err) { options.log("Problem parsing session response: " + err.message, "error"); isError = true; } } options.onComplete(response, !isError, xhrOrXdr); } requester = qq.extend(this, new qq.AjaxRequester({ validMethods: ["GET"], method: "GET", endpointStore: { get: function() { return options.endpoint; } }, customHeaders: options.customHeaders, log: options.log, onComplete: onComplete, cors: options.cors })); qq.extend(this, { queryServer: function() { var params = qq.extend({}, options.params); options.log("Session query request."); requester.initTransport("sessionRefresh") .withParams(params) .withCacheBuster() .send(); } }); }; /* globals qq */ /** * Module that handles support for existing forms. * * @param options Options passed from the integrator-supplied options related to form support. * @param startUpload Callback to invoke when files "stored" should be uploaded. * @param log Proxy for the logger * @constructor */ qq.FormSupport = function(options, startUpload, log) { "use strict"; var self = this, interceptSubmit = options.interceptSubmit, formEl = options.element, autoUpload = options.autoUpload; // Available on the public API associated with this module. qq.extend(this, { // To be used by the caller to determine if the endpoint will be determined by some processing // that occurs in this module, such as if the form has an action attribute. // Ignore if `attachToForm === false`. newEndpoint: null, // To be used by the caller to determine if auto uploading should be allowed. // Ignore if `attachToForm === false`. newAutoUpload: autoUpload, // true if a form was detected and is being tracked by this module attachedToForm: false, // Returns an object with names and values for all valid form elements associated with the attached form. getFormInputsAsObject: function() { /* jshint eqnull:true */ if (formEl == null) { return null; } return self._form2Obj(formEl); } }); // If the form contains an action attribute, this should be the new upload endpoint. function determineNewEndpoint(formEl) { if (formEl.getAttribute("action")) { self.newEndpoint = formEl.getAttribute("action"); } } // Return true only if the form is valid, or if we cannot make this determination. // If the form is invalid, ensure invalid field(s) are highlighted in the UI. function validateForm(formEl, nativeSubmit) { if (formEl.checkValidity && !formEl.checkValidity()) { log("Form did not pass validation checks - will not upload.", "error"); nativeSubmit(); } else { return true; } } // Intercept form submit attempts, unless the integrator has told us not to do this. function maybeUploadOnSubmit(formEl) { var nativeSubmit = formEl.submit; // Intercept and squelch submit events. qq(formEl).attach("submit", function(event) { event = event || window.event; if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } validateForm(formEl, nativeSubmit) && startUpload(); }); // The form's `submit()` function may be called instead (i.e. via jQuery.submit()). // Intercept that too. formEl.submit = function() { validateForm(formEl, nativeSubmit) && startUpload(); }; } // If the element value passed from the uploader is a string, assume it is an element ID - select it. // The rest of the code in this module depends on this being an HTMLElement. function determineFormEl(formEl) { if (formEl) { if (qq.isString(formEl)) { formEl = document.getElementById(formEl); } if (formEl) { log("Attaching to form element."); determineNewEndpoint(formEl); interceptSubmit && maybeUploadOnSubmit(formEl); } } return formEl; } formEl = determineFormEl(formEl); this.attachedToForm = !!formEl; }; qq.extend(qq.FormSupport.prototype, { // Converts all relevant form fields to key/value pairs. This is meant to mimic the data a browser will // construct from a given form when the form is submitted. _form2Obj: function(form) { "use strict"; var obj = {}, notIrrelevantType = function(type) { var irrelevantTypes = [ "button", "image", "reset", "submit" ]; return qq.indexOf(irrelevantTypes, type.toLowerCase()) < 0; }, radioOrCheckbox = function(type) { return qq.indexOf(["checkbox", "radio"], type.toLowerCase()) >= 0; }, ignoreValue = function(el) { if (radioOrCheckbox(el.type) && !el.checked) { return true; } return el.disabled && el.type.toLowerCase() !== "hidden"; }, selectValue = function(select) { var value = null; qq.each(qq(select).children(), function(idx, child) { if (child.tagName.toLowerCase() === "option" && child.selected) { value = child.value; return false; } }); return value; }; qq.each(form.elements, function(idx, el) { if (qq.isInput(el, true) && notIrrelevantType(el.type) && !ignoreValue(el)) { obj[el.name] = el.value; } else if (el.tagName.toLowerCase() === "select" && !ignoreValue(el)) { var value = selectValue(el); if (value !== null) { obj[el.name] = value; } } }); return obj; } }); /*globals qq */ // Base handler for UI (FineUploader mode) events. // Some more specific handlers inherit from this one. qq.UiEventHandler = function(s, protectedApi) { "use strict"; var disposer = new qq.DisposeSupport(), spec = { eventType: "click", attachTo: null, onHandled: function(target, event) {} }; // This makes up the "public" API methods that will be accessible // to instances constructing a base or child handler qq.extend(this, { addHandler: function(element) { addHandler(element); }, dispose: function() { disposer.dispose(); } }); function addHandler(element) { disposer.attach(element, spec.eventType, function(event) { // Only in IE: the `event` is a property of the `window`. event = event || window.event; // On older browsers, we must check the `srcElement` instead of the `target`. var target = event.target || event.srcElement; spec.onHandled(target, event); }); } // These make up the "protected" API methods that children of this base handler will utilize. qq.extend(protectedApi, { getFileIdFromItem: function(item) { return item.qqFileId; }, getDisposeSupport: function() { return disposer; } }); qq.extend(spec, s); if (spec.attachTo) { addHandler(spec.attachTo); } }; /* global qq */ qq.FileButtonsClickHandler = function(s) { "use strict"; var inheritedInternalApi = {}, spec = { templating: null, log: function(message, lvl) {}, onDeleteFile: function(fileId) {}, onCancel: function(fileId) {}, onRetry: function(fileId) {}, onPause: function(fileId) {}, onContinue: function(fileId) {}, onGetName: function(fileId) {} }, buttonHandlers = { cancel: function(id) { spec.onCancel(id); }, retry: function(id) { spec.onRetry(id); }, deleteButton: function(id) { spec.onDeleteFile(id); }, pause: function(id) { spec.onPause(id); }, continueButton: function(id) { spec.onContinue(id); } }; function examineEvent(target, event) { qq.each(buttonHandlers, function(buttonType, handler) { var firstLetterCapButtonType = buttonType.charAt(0).toUpperCase() + buttonType.slice(1), fileId; if (spec.templating["is" + firstLetterCapButtonType](target)) { fileId = spec.templating.getFileId(target); qq.preventDefault(event); spec.log(qq.format("Detected valid file button click event on file '{}', ID: {}.", spec.onGetName(fileId), fileId)); handler(fileId); return false; } }); } qq.extend(spec, s); spec.eventType = "click"; spec.onHandled = examineEvent; spec.attachTo = spec.templating.getFileList(); qq.extend(this, new qq.UiEventHandler(spec, inheritedInternalApi)); }; /*globals qq */ // Child of FilenameEditHandler. Used to detect click events on filename display elements. qq.FilenameClickHandler = function(s) { "use strict"; var inheritedInternalApi = {}, spec = { templating: null, log: function(message, lvl) {}, classes: { file: "qq-upload-file", editNameIcon: "qq-edit-filename-icon" }, onGetUploadStatus: function(fileId) {}, onGetName: function(fileId) {} }; qq.extend(spec, s); // This will be called by the parent handler when a `click` event is received on the list element. function examineEvent(target, event) { if (spec.templating.isFileName(target) || spec.templating.isEditIcon(target)) { var fileId = spec.templating.getFileId(target), status = spec.onGetUploadStatus(fileId); // We only allow users to change filenames of files that have been submitted but not yet uploaded. if (status === qq.status.SUBMITTED) { spec.log(qq.format("Detected valid filename click event on file '{}', ID: {}.", spec.onGetName(fileId), fileId)); qq.preventDefault(event); inheritedInternalApi.handleFilenameEdit(fileId, target, true); } } } spec.eventType = "click"; spec.onHandled = examineEvent; qq.extend(this, new qq.FilenameEditHandler(spec, inheritedInternalApi)); }; /*globals qq */ // Child of FilenameEditHandler. Used to detect focusin events on file edit input elements. qq.FilenameInputFocusInHandler = function(s, inheritedInternalApi) { "use strict"; var spec = { templating: null, onGetUploadStatus: function(fileId) {}, log: function(message, lvl) {} }; if (!inheritedInternalApi) { inheritedInternalApi = {}; } // This will be called by the parent handler when a `focusin` event is received on the list element. function handleInputFocus(target, event) { if (spec.templating.isEditInput(target)) { var fileId = spec.templating.getFileId(target), status = spec.onGetUploadStatus(fileId); if (status === qq.status.SUBMITTED) { spec.log(qq.format("Detected valid filename input focus event on file '{}', ID: {}.", spec.onGetName(fileId), fileId)); inheritedInternalApi.handleFilenameEdit(fileId, target); } } } spec.eventType = "focusin"; spec.onHandled = handleInputFocus; qq.extend(spec, s); qq.extend(this, new qq.FilenameEditHandler(spec, inheritedInternalApi)); }; /*globals qq */ /** * Child of FilenameInputFocusInHandler. Used to detect focus events on file edit input elements. This child module is only * needed for UAs that do not support the focusin event. Currently, only Firefox lacks this event. * * @param spec Overrides for default specifications */ qq.FilenameInputFocusHandler = function(spec) { "use strict"; spec.eventType = "focus"; spec.attachTo = null; qq.extend(this, new qq.FilenameInputFocusInHandler(spec, {})); }; /*globals qq */ // Handles edit-related events on a file item (FineUploader mode). This is meant to be a parent handler. // Children will delegate to this handler when specific edit-related actions are detected. qq.FilenameEditHandler = function(s, inheritedInternalApi) { "use strict"; var spec = { templating: null, log: function(message, lvl) {}, onGetUploadStatus: function(fileId) {}, onGetName: function(fileId) {}, onSetName: function(fileId, newName) {}, onEditingStatusChange: function(fileId, isEditing) {} }; function getFilenameSansExtension(fileId) { var filenameSansExt = spec.onGetName(fileId), extIdx = filenameSansExt.lastIndexOf("."); if (extIdx > 0) { filenameSansExt = filenameSansExt.substr(0, extIdx); } return filenameSansExt; } function getOriginalExtension(fileId) { var origName = spec.onGetName(fileId); return qq.getExtension(origName); } // Callback iff the name has been changed function handleNameUpdate(newFilenameInputEl, fileId) { var newName = newFilenameInputEl.value, origExtension; if (newName !== undefined && qq.trimStr(newName).length > 0) { origExtension = getOriginalExtension(fileId); if (origExtension !== undefined) { newName = newName + "." + origExtension; } spec.onSetName(fileId, newName); } spec.onEditingStatusChange(fileId, false); } // The name has been updated if the filename edit input loses focus. function registerInputBlurHandler(inputEl, fileId) { inheritedInternalApi.getDisposeSupport().attach(inputEl, "blur", function() { handleNameUpdate(inputEl, fileId); }); } // The name has been updated if the user presses enter. function registerInputEnterKeyHandler(inputEl, fileId) { inheritedInternalApi.getDisposeSupport().attach(inputEl, "keyup", function(event) { var code = event.keyCode || event.which; if (code === 13) { handleNameUpdate(inputEl, fileId); } }); } qq.extend(spec, s); spec.attachTo = spec.templating.getFileList(); qq.extend(this, new qq.UiEventHandler(spec, inheritedInternalApi)); qq.extend(inheritedInternalApi, { handleFilenameEdit: function(id, target, focusInput) { var newFilenameInputEl = spec.templating.getEditInput(id); spec.onEditingStatusChange(id, true); newFilenameInputEl.value = getFilenameSansExtension(id); if (focusInput) { newFilenameInputEl.focus(); } registerInputBlurHandler(newFilenameInputEl, id); registerInputEnterKeyHandler(newFilenameInputEl, id); } }); }; /*globals jQuery, qq*/ (function($) { "use strict"; var $el, pluginOptions = ["uploaderType", "endpointType"]; function init(options) { var xformedOpts = transformVariables(options || {}), newUploaderInstance = getNewUploaderInstance(xformedOpts); uploader(newUploaderInstance); addCallbacks(xformedOpts, newUploaderInstance); return $el; } function getNewUploaderInstance(params) { var uploaderType = pluginOption("uploaderType"), namespace = pluginOption("endpointType"); // If the integrator has defined a specific type of uploader to load, use that, otherwise assume `qq.FineUploader` if (uploaderType) { // We can determine the correct constructor function to invoke by combining "FineUploader" // with the upper camel cased `uploaderType` value. uploaderType = uploaderType.charAt(0).toUpperCase() + uploaderType.slice(1).toLowerCase(); if (namespace) { return new qq[namespace]["FineUploader" + uploaderType](params); } return new qq["FineUploader" + uploaderType](params); } else { if (namespace) { return new qq[namespace].FineUploader(params); } return new qq.FineUploader(params); } } function dataStore(key, val) { var data = $el.data("fineuploader"); if (val) { if (data === undefined) { data = {}; } data[key] = val; $el.data("fineuploader", data); } else { if (data === undefined) { return null; } return data[key]; } } //the underlying Fine Uploader instance is stored in jQuery's data stored, associated with the element // tied to this instance of the plug-in function uploader(instanceToStore) { return dataStore("uploader", instanceToStore); } function pluginOption(option, optionVal) { return dataStore(option, optionVal); } // Implement all callbacks defined in Fine Uploader as functions that trigger appropriately names events and // return the result of executing the bound handler back to Fine Uploader function addCallbacks(transformedOpts, newUploaderInstance) { var callbacks = transformedOpts.callbacks = {}; $.each(newUploaderInstance._options.callbacks, function(prop, nonJqueryCallback) { var name, callbackEventTarget; name = /^on(\w+)/.exec(prop)[1]; name = name.substring(0, 1).toLowerCase() + name.substring(1); callbackEventTarget = $el; callbacks[prop] = function() { var originalArgs = Array.prototype.slice.call(arguments), transformedArgs = [], nonJqueryCallbackRetVal, jqueryEventCallbackRetVal; $.each(originalArgs, function(idx, arg) { transformedArgs.push(maybeWrapInJquery(arg)); }); nonJqueryCallbackRetVal = nonJqueryCallback.apply(this, originalArgs); try { jqueryEventCallbackRetVal = callbackEventTarget.triggerHandler(name, transformedArgs); } catch (error) { qq.log("Caught error in Fine Uploader jQuery event handler: " + error.message, "error"); } /*jshint -W116*/ if (nonJqueryCallbackRetVal != null) { return nonJqueryCallbackRetVal; } return jqueryEventCallbackRetVal; }; }); newUploaderInstance._options.callbacks = callbacks; } //transform jQuery objects into HTMLElements, and pass along all other option properties function transformVariables(source, dest) { var xformed, arrayVals; if (dest === undefined) { if (source.uploaderType !== "basic") { xformed = { element : $el[0] }; } else { xformed = {}; } } else { xformed = dest; } $.each(source, function(prop, val) { if ($.inArray(prop, pluginOptions) >= 0) { pluginOption(prop, val); } else if (val instanceof $) { xformed[prop] = val[0]; } else if ($.isPlainObject(val)) { xformed[prop] = {}; transformVariables(val, xformed[prop]); } else if ($.isArray(val)) { arrayVals = []; $.each(val, function(idx, arrayVal) { var arrayObjDest = {}; if (arrayVal instanceof $) { $.merge(arrayVals, arrayVal); } else if ($.isPlainObject(arrayVal)) { transformVariables(arrayVal, arrayObjDest); arrayVals.push(arrayObjDest); } else { arrayVals.push(arrayVal); } }); xformed[prop] = arrayVals; } else { xformed[prop] = val; } }); if (dest === undefined) { return xformed; } } function isValidCommand(command) { return $.type(command) === "string" && !command.match(/^_/) && //enforce private methods convention uploader()[command] !== undefined; } // Assuming we have already verified that this is a valid command, call the associated function in the underlying // Fine Uploader instance (passing along the arguments from the caller) and return the result of the call back to the caller function delegateCommand(command) { var xformedArgs = [], origArgs = Array.prototype.slice.call(arguments, 1), retVal; transformVariables(origArgs, xformedArgs); retVal = uploader()[command].apply(uploader(), xformedArgs); return maybeWrapInJquery(retVal); } // If the value is an `HTMLElement` or `HTMLDocument`, wrap it in a `jQuery` object function maybeWrapInJquery(val) { var transformedVal = val; // If the command is returning an `HTMLElement` or `HTMLDocument`, wrap it in a `jQuery` object /*jshint -W116*/ if (val != null && typeof val === "object" && (val.nodeType === 1 || val.nodeType === 9) && val.cloneNode) { transformedVal = $(val); } return transformedVal; } $.fn.fineUploader = function(optionsOrCommand) { var self = this, selfArgs = arguments, retVals = []; this.each(function(index, el) { $el = $(el); if (uploader() && isValidCommand(optionsOrCommand)) { retVals.push(delegateCommand.apply(self, selfArgs)); if (self.length === 1) { return false; } } else if (typeof optionsOrCommand === "object" || !optionsOrCommand) { init.apply(self, selfArgs); } else { $.error("Method " + optionsOrCommand + " does not exist on jQuery.fineUploader"); } }); if (retVals.length === 1) { return retVals[0]; } else if (retVals.length > 1) { return retVals; } return this; }; }(jQuery)); /*globals jQuery, qq*/ (function($) { "use strict"; var rootDataKey = "fineUploaderDnd", $el; function init (options) { if (!options) { options = {}; } options.dropZoneElements = [$el]; var xformedOpts = transformVariables(options); addCallbacks(xformedOpts); dnd(new qq.DragAndDrop(xformedOpts)); return $el; } function dataStore(key, val) { var data = $el.data(rootDataKey); if (val) { if (data === undefined) { data = {}; } data[key] = val; $el.data(rootDataKey, data); } else { if (data === undefined) { return null; } return data[key]; } } function dnd(instanceToStore) { return dataStore("dndInstance", instanceToStore); } function addCallbacks(transformedOpts) { var callbacks = transformedOpts.callbacks = {}, dndInst = new qq.FineUploaderBasic(); $.each(new qq.DragAndDrop.callbacks(), function(prop, func) { var name = prop, $callbackEl; $callbackEl = $el; callbacks[prop] = function() { var args = Array.prototype.slice.call(arguments), jqueryHandlerResult = $callbackEl.triggerHandler(name, args); return jqueryHandlerResult; }; }); } //transform jQuery objects into HTMLElements, and pass along all other option properties function transformVariables(source, dest) { var xformed, arrayVals; if (dest === undefined) { xformed = {}; } else { xformed = dest; } $.each(source, function(prop, val) { if (val instanceof $) { xformed[prop] = val[0]; } else if ($.isPlainObject(val)) { xformed[prop] = {}; transformVariables(val, xformed[prop]); } else if ($.isArray(val)) { arrayVals = []; $.each(val, function(idx, arrayVal) { if (arrayVal instanceof $) { $.merge(arrayVals, arrayVal); } else { arrayVals.push(arrayVal); } }); xformed[prop] = arrayVals; } else { xformed[prop] = val; } }); if (dest === undefined) { return xformed; } } function isValidCommand(command) { return $.type(command) === "string" && command === "dispose" && dnd()[command] !== undefined; } function delegateCommand(command) { var xformedArgs = [], origArgs = Array.prototype.slice.call(arguments, 1); transformVariables(origArgs, xformedArgs); return dnd()[command].apply(dnd(), xformedArgs); } $.fn.fineUploaderDnd = function(optionsOrCommand) { var self = this, selfArgs = arguments, retVals = []; this.each(function(index, el) { $el = $(el); if (dnd() && isValidCommand(optionsOrCommand)) { retVals.push(delegateCommand.apply(self, selfArgs)); if (self.length === 1) { return false; } } else if (typeof optionsOrCommand === "object" || !optionsOrCommand) { init.apply(self, selfArgs); } else { $.error("Method " + optionsOrCommand + " does not exist in Fine Uploader's DnD module."); } }); if (retVals.length === 1) { return retVals[0]; } else if (retVals.length > 1) { return retVals; } return this; }; }(jQuery)); /*! 2014-02-16 */
JavaScript
/* Flot plugin for automatically redrawing plots as the placeholder resizes. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. It works by listening for changes on the placeholder div (through the jQuery resize event plugin) - if the size changes, it will redraw the plot. There are no options. If you need to disable the plugin for some plots, you can just fix the size of their placeholders. */ /* Inline dependency: * jQuery resize event - v1.1 - 3/14/2010 * http://benalman.com/projects/jquery-resize-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ (function($,t,n){function p(){for(var n=r.length-1;n>=0;n--){var o=$(r[n]);if(o[0]==t||o.is(":visible")){var h=o.width(),d=o.height(),v=o.data(a);!v||h===v.w&&d===v.h?i[f]=i[l]:(i[f]=i[c],o.trigger(u,[v.w=h,v.h=d]))}else v=o.data(a),v.w=0,v.h=0}s!==null&&(s=t.requestAnimationFrame(p))}var r=[],i=$.resize=$.extend($.resize,{}),s,o="setTimeout",u="resize",a=u+"-special-event",f="delay",l="pendingDelay",c="activeDelay",h="throttleWindow";i[l]=250,i[c]=20,i[f]=i[l],i[h]=!0,$.event.special[u]={setup:function(){if(!i[h]&&this[o])return!1;var t=$(this);r.push(this),t.data(a,{w:t.width(),h:t.height()}),r.length===1&&(s=n,p())},teardown:function(){if(!i[h]&&this[o])return!1;var t=$(this);for(var n=r.length-1;n>=0;n--)if(r[n]==this){r.splice(n,1);break}t.removeData(a),r.length||(cancelAnimationFrame(s),s=null)},add:function(t){function s(t,i,s){var o=$(this),u=o.data(a);u.w=i!==n?i:o.width(),u.h=s!==n?s:o.height(),r.apply(this,arguments)}if(!i[h]&&this[o])return!1;var r;if($.isFunction(t))return r=t,s;r=t.handler,t.handler=s}},t.requestAnimationFrame||(t.requestAnimationFrame=function(){return t.webkitRequestAnimationFrame||t.mozRequestAnimationFrame||t.oRequestAnimationFrame||t.msRequestAnimationFrame||function(e,n){return t.setTimeout(e,i[f])}}()),t.cancelAnimationFrame||(t.cancelAnimationFrame=function(){return t.webkitCancelRequestAnimationFrame||t.mozCancelRequestAnimationFrame||t.oCancelRequestAnimationFrame||t.msCancelRequestAnimationFrame||clearTimeout}())})(jQuery,this); (function ($) { var options = { }; // no options function init(plot) { function onResize() { var placeholder = plot.getPlaceholder(); // somebody might have hidden us and we can't plot // when we don't have the dimensions if (placeholder.width() == 0 || placeholder.height() == 0) return; plot.resize(); plot.setupGrid(); plot.draw(); } function bindEvents(plot, eventHolder) { plot.getPlaceholder().resize(onResize); } function shutdown(plot, eventHolder) { plot.getPlaceholder().unbind("resize", onResize); } plot.hooks.bindEvents.push(bindEvents); plot.hooks.shutdown.push(shutdown); } $.plot.plugins.push({ init: init, options: options, name: 'resize', version: '1.0' }); })(jQuery);
JavaScript
/* Pretty handling of time axes. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. Set axis.mode to "time" to enable. See the section "Time series data" in API.txt for details. */ (function($) { var options = { xaxis: { timezone: null, // "browser" for local to the client or timezone for timezone-js timeformat: null, // format string to use twelveHourClock: false, // 12 or 24 time in time mode monthNames: null // list of names of months } }; // round to nearby lower multiple of base function floorInBase(n, base) { return base * Math.floor(n / base); } // Returns a string with the date d formatted according to fmt. // A subset of the Open Group's strftime format is supported. function formatDate(d, fmt, monthNames, dayNames) { if (typeof d.strftime == "function") { return d.strftime(fmt); } var leftPad = function(n, pad) { n = "" + n; pad = "" + (pad == null ? "0" : pad); return n.length == 1 ? pad + n : n; }; var r = []; var escape = false; var hours = d.getHours(); var isAM = hours < 12; if (monthNames == null) { monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; } if (dayNames == null) { dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; } var hours12; if (hours > 12) { hours12 = hours - 12; } else if (hours == 0) { hours12 = 12; } else { hours12 = hours; } for (var i = 0; i < fmt.length; ++i) { var c = fmt.charAt(i); if (escape) { switch (c) { case 'a': c = "" + dayNames[d.getDay()]; break; case 'b': c = "" + monthNames[d.getMonth()]; break; case 'd': c = leftPad(d.getDate()); break; case 'e': c = leftPad(d.getDate(), " "); break; case 'h': // For back-compat with 0.7; remove in 1.0 case 'H': c = leftPad(hours); break; case 'I': c = leftPad(hours12); break; case 'l': c = leftPad(hours12, " "); break; case 'm': c = leftPad(d.getMonth() + 1); break; case 'M': c = leftPad(d.getMinutes()); break; // quarters not in Open Group's strftime specification case 'q': c = "" + (Math.floor(d.getMonth() / 3) + 1); break; case 'S': c = leftPad(d.getSeconds()); break; case 'y': c = leftPad(d.getFullYear() % 100); break; case 'Y': c = "" + d.getFullYear(); break; case 'p': c = (isAM) ? ("" + "am") : ("" + "pm"); break; case 'P': c = (isAM) ? ("" + "AM") : ("" + "PM"); break; case 'w': c = "" + d.getDay(); break; } r.push(c); escape = false; } else { if (c == "%") { escape = true; } else { r.push(c); } } } return r.join(""); } // To have a consistent view of time-based data independent of which time // zone the client happens to be in we need a date-like object independent // of time zones. This is done through a wrapper that only calls the UTC // versions of the accessor methods. function makeUtcWrapper(d) { function addProxyMethod(sourceObj, sourceMethod, targetObj, targetMethod) { sourceObj[sourceMethod] = function() { return targetObj[targetMethod].apply(targetObj, arguments); }; }; var utc = { date: d }; // support strftime, if found if (d.strftime != undefined) { addProxyMethod(utc, "strftime", d, "strftime"); } addProxyMethod(utc, "getTime", d, "getTime"); addProxyMethod(utc, "setTime", d, "setTime"); var props = ["Date", "Day", "FullYear", "Hours", "Milliseconds", "Minutes", "Month", "Seconds"]; for (var p = 0; p < props.length; p++) { addProxyMethod(utc, "get" + props[p], d, "getUTC" + props[p]); addProxyMethod(utc, "set" + props[p], d, "setUTC" + props[p]); } return utc; }; // select time zone strategy. This returns a date-like object tied to the // desired timezone function dateGenerator(ts, opts) { if (opts.timezone == "browser") { return new Date(ts); } else if (!opts.timezone || opts.timezone == "utc") { return makeUtcWrapper(new Date(ts)); } else if (typeof timezoneJS != "undefined" && typeof timezoneJS.Date != "undefined") { var d = new timezoneJS.Date(); // timezone-js is fickle, so be sure to set the time zone before // setting the time. d.setTimezone(opts.timezone); d.setTime(ts); return d; } else { return makeUtcWrapper(new Date(ts)); } } // map of app. size of time units in milliseconds var timeUnitSize = { "second": 1000, "minute": 60 * 1000, "hour": 60 * 60 * 1000, "day": 24 * 60 * 60 * 1000, "month": 30 * 24 * 60 * 60 * 1000, "quarter": 3 * 30 * 24 * 60 * 60 * 1000, "year": 365.2425 * 24 * 60 * 60 * 1000 }; // the allowed tick sizes, after 1 year we use // an integer algorithm var baseSpec = [ [1, "second"], [2, "second"], [5, "second"], [10, "second"], [30, "second"], [1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"], [30, "minute"], [1, "hour"], [2, "hour"], [4, "hour"], [8, "hour"], [12, "hour"], [1, "day"], [2, "day"], [3, "day"], [0.25, "month"], [0.5, "month"], [1, "month"], [2, "month"] ]; // we don't know which variant(s) we'll need yet, but generating both is // cheap var specMonths = baseSpec.concat([[3, "month"], [6, "month"], [1, "year"]]); var specQuarters = baseSpec.concat([[1, "quarter"], [2, "quarter"], [1, "year"]]); function init(plot) { plot.hooks.processOptions.push(function (plot, options) { $.each(plot.getAxes(), function(axisName, axis) { var opts = axis.options; if (opts.mode == "time") { axis.tickGenerator = function(axis) { var ticks = []; var d = dateGenerator(axis.min, opts); var minSize = 0; // make quarter use a possibility if quarters are // mentioned in either of these options var spec = (opts.tickSize && opts.tickSize[1] === "quarter") || (opts.minTickSize && opts.minTickSize[1] === "quarter") ? specQuarters : specMonths; if (opts.minTickSize != null) { if (typeof opts.tickSize == "number") { minSize = opts.tickSize; } else { minSize = opts.minTickSize[0] * timeUnitSize[opts.minTickSize[1]]; } } for (var i = 0; i < spec.length - 1; ++i) { if (axis.delta < (spec[i][0] * timeUnitSize[spec[i][1]] + spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2 && spec[i][0] * timeUnitSize[spec[i][1]] >= minSize) { break; } } var size = spec[i][0]; var unit = spec[i][1]; // special-case the possibility of several years if (unit == "year") { // if given a minTickSize in years, just use it, // ensuring that it's an integer if (opts.minTickSize != null && opts.minTickSize[1] == "year") { size = Math.floor(opts.minTickSize[0]); } else { var magn = Math.pow(10, Math.floor(Math.log(axis.delta / timeUnitSize.year) / Math.LN10)); var norm = (axis.delta / timeUnitSize.year) / magn; if (norm < 1.5) { size = 1; } else if (norm < 3) { size = 2; } else if (norm < 7.5) { size = 5; } else { size = 10; } size *= magn; } // minimum size for years is 1 if (size < 1) { size = 1; } } axis.tickSize = opts.tickSize || [size, unit]; var tickSize = axis.tickSize[0]; unit = axis.tickSize[1]; var step = tickSize * timeUnitSize[unit]; if (unit == "second") { d.setSeconds(floorInBase(d.getSeconds(), tickSize)); } else if (unit == "minute") { d.setMinutes(floorInBase(d.getMinutes(), tickSize)); } else if (unit == "hour") { d.setHours(floorInBase(d.getHours(), tickSize)); } else if (unit == "month") { d.setMonth(floorInBase(d.getMonth(), tickSize)); } else if (unit == "quarter") { d.setMonth(3 * floorInBase(d.getMonth() / 3, tickSize)); } else if (unit == "year") { d.setFullYear(floorInBase(d.getFullYear(), tickSize)); } // reset smaller components d.setMilliseconds(0); if (step >= timeUnitSize.minute) { d.setSeconds(0); } if (step >= timeUnitSize.hour) { d.setMinutes(0); } if (step >= timeUnitSize.day) { d.setHours(0); } if (step >= timeUnitSize.day * 4) { d.setDate(1); } if (step >= timeUnitSize.month * 2) { d.setMonth(floorInBase(d.getMonth(), 3)); } if (step >= timeUnitSize.quarter * 2) { d.setMonth(floorInBase(d.getMonth(), 6)); } if (step >= timeUnitSize.year) { d.setMonth(0); } var carry = 0; var v = Number.NaN; var prev; do { prev = v; v = d.getTime(); ticks.push(v); if (unit == "month" || unit == "quarter") { if (tickSize < 1) { // a bit complicated - we'll divide the // month/quarter up but we need to take // care of fractions so we don't end up in // the middle of a day d.setDate(1); var start = d.getTime(); d.setMonth(d.getMonth() + (unit == "quarter" ? 3 : 1)); var end = d.getTime(); d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize); carry = d.getHours(); d.setHours(0); } else { d.setMonth(d.getMonth() + tickSize * (unit == "quarter" ? 3 : 1)); } } else if (unit == "year") { d.setFullYear(d.getFullYear() + tickSize); } else { d.setTime(v + step); } } while (v < axis.max && v != prev); return ticks; }; axis.tickFormatter = function (v, axis) { var d = dateGenerator(v, axis.options); // first check global format if (opts.timeformat != null) { return formatDate(d, opts.timeformat, opts.monthNames, opts.dayNames); } // possibly use quarters if quarters are mentioned in // any of these places var useQuarters = (axis.options.tickSize && axis.options.tickSize[1] == "quarter") || (axis.options.minTickSize && axis.options.minTickSize[1] == "quarter"); var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]]; var span = axis.max - axis.min; var suffix = (opts.twelveHourClock) ? " %p" : ""; var hourCode = (opts.twelveHourClock) ? "%I" : "%H"; var fmt; if (t < timeUnitSize.minute) { fmt = hourCode + ":%M:%S" + suffix; } else if (t < timeUnitSize.day) { if (span < 2 * timeUnitSize.day) { fmt = hourCode + ":%M" + suffix; } else { fmt = "%b %d " + hourCode + ":%M" + suffix; } } else if (t < timeUnitSize.month) { fmt = "%b %d"; } else if ((useQuarters && t < timeUnitSize.quarter) || (!useQuarters && t < timeUnitSize.year)) { if (span < timeUnitSize.year) { fmt = "%b"; } else { fmt = "%b %Y"; } } else if (useQuarters && t < timeUnitSize.year) { if (span < timeUnitSize.year) { fmt = "Q%q"; } else { fmt = "Q%q %Y"; } } else { fmt = "%Y"; } var rt = formatDate(d, fmt, opts.monthNames, opts.dayNames); return rt; }; } }); }); } $.plot.plugins.push({ init: init, options: options, name: 'time', version: '1.0' }); // Time-axis support used to be in Flot core, which exposed the // formatDate function on the plot object. Various plugins depend // on the function, so we need to re-expose it here. $.plot.formatDate = formatDate; })(jQuery);
JavaScript
/* Javascript plotting library for jQuery, version 0.8.2. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. */ // first an inline dependency, jquery.colorhelpers.js, we inline it here // for convenience /* Plugin for jQuery for working with colors. * * Version 1.1. * * Inspiration from jQuery color animation plugin by John Resig. * * Released under the MIT license by Ole Laursen, October 2009. * * Examples: * * $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString() * var c = $.color.extract($("#mydiv"), 'background-color'); * console.log(c.r, c.g, c.b, c.a); * $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)" * * Note that .scale() and .add() return the same modified object * instead of making a new one. * * V. 1.1: Fix error handling so e.g. parsing an empty string does * produce a color rather than just crashing. */ (function($){$.color={};$.color.make=function(r,g,b,a){var o={};o.r=r||0;o.g=g||0;o.b=b||0;o.a=a!=null?a:1;o.add=function(c,d){for(var i=0;i<c.length;++i)o[c.charAt(i)]+=d;return o.normalize()};o.scale=function(c,f){for(var i=0;i<c.length;++i)o[c.charAt(i)]*=f;return o.normalize()};o.toString=function(){if(o.a>=1){return"rgb("+[o.r,o.g,o.b].join(",")+")"}else{return"rgba("+[o.r,o.g,o.b,o.a].join(",")+")"}};o.normalize=function(){function clamp(min,value,max){return value<min?min:value>max?max:value}o.r=clamp(0,parseInt(o.r),255);o.g=clamp(0,parseInt(o.g),255);o.b=clamp(0,parseInt(o.b),255);o.a=clamp(0,o.a,1);return o};o.clone=function(){return $.color.make(o.r,o.b,o.g,o.a)};return o.normalize()};$.color.extract=function(elem,css){var c;do{c=elem.css(css).toLowerCase();if(c!=""&&c!="transparent")break;elem=elem.parent()}while(elem.length&&!$.nodeName(elem.get(0),"body"));if(c=="rgba(0, 0, 0, 0)")c="transparent";return $.color.parse(c)};$.color.parse=function(str){var res,m=$.color.make;if(res=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str))return m(parseInt(res[1],10),parseInt(res[2],10),parseInt(res[3],10));if(res=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))return m(parseInt(res[1],10),parseInt(res[2],10),parseInt(res[3],10),parseFloat(res[4]));if(res=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str))return m(parseFloat(res[1])*2.55,parseFloat(res[2])*2.55,parseFloat(res[3])*2.55);if(res=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))return m(parseFloat(res[1])*2.55,parseFloat(res[2])*2.55,parseFloat(res[3])*2.55,parseFloat(res[4]));if(res=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str))return m(parseInt(res[1],16),parseInt(res[2],16),parseInt(res[3],16));if(res=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str))return m(parseInt(res[1]+res[1],16),parseInt(res[2]+res[2],16),parseInt(res[3]+res[3],16));var name=$.trim(str).toLowerCase();if(name=="transparent")return m(255,255,255,0);else{res=lookupColors[name]||[0,0,0];return m(res[0],res[1],res[2])}};var lookupColors={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery); // the actual Flot code (function($) { // Cache the prototype hasOwnProperty for faster access var hasOwnProperty = Object.prototype.hasOwnProperty; /////////////////////////////////////////////////////////////////////////// // The Canvas object is a wrapper around an HTML5 <canvas> tag. // // @constructor // @param {string} cls List of classes to apply to the canvas. // @param {element} container Element onto which to append the canvas. // // Requiring a container is a little iffy, but unfortunately canvas // operations don't work unless the canvas is attached to the DOM. function Canvas(cls, container) { var element = container.children("." + cls)[0]; if (element == null) { element = document.createElement("canvas"); element.className = cls; $(element).css({ direction: "ltr", position: "absolute", left: 0, top: 0 }) .appendTo(container); // If HTML5 Canvas isn't available, fall back to [Ex|Flash]canvas if (!element.getContext) { if (window.G_vmlCanvasManager) { element = window.G_vmlCanvasManager.initElement(element); } else { throw new Error("Canvas is not available. If you're using IE with a fall-back such as Excanvas, then there's either a mistake in your conditional include, or the page has no DOCTYPE and is rendering in Quirks Mode."); } } } this.element = element; var context = this.context = element.getContext("2d"); // Determine the screen's ratio of physical to device-independent // pixels. This is the ratio between the canvas width that the browser // advertises and the number of pixels actually present in that space. // The iPhone 4, for example, has a device-independent width of 320px, // but its screen is actually 640px wide. It therefore has a pixel // ratio of 2, while most normal devices have a ratio of 1. var devicePixelRatio = window.devicePixelRatio || 1, backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; this.pixelRatio = devicePixelRatio / backingStoreRatio; // Size the canvas to match the internal dimensions of its container this.resize(container.width(), container.height()); // Collection of HTML div layers for text overlaid onto the canvas this.textContainer = null; this.text = {}; // Cache of text fragments and metrics, so we can avoid expensively // re-calculating them when the plot is re-rendered in a loop. this._textCache = {}; } // Resizes the canvas to the given dimensions. // // @param {number} width New width of the canvas, in pixels. // @param {number} width New height of the canvas, in pixels. Canvas.prototype.resize = function(width, height) { if (width <= 0 || height <= 0) { throw new Error("Invalid dimensions for plot, width = " + width + ", height = " + height); } var element = this.element, context = this.context, pixelRatio = this.pixelRatio; // Resize the canvas, increasing its density based on the display's // pixel ratio; basically giving it more pixels without increasing the // size of its element, to take advantage of the fact that retina // displays have that many more pixels in the same advertised space. // Resizing should reset the state (excanvas seems to be buggy though) if (this.width != width) { element.width = width * pixelRatio; element.style.width = width + "px"; this.width = width; } if (this.height != height) { element.height = height * pixelRatio; element.style.height = height + "px"; this.height = height; } // Save the context, so we can reset in case we get replotted. The // restore ensure that we're really back at the initial state, and // should be safe even if we haven't saved the initial state yet. context.restore(); context.save(); // Scale the coordinate space to match the display density; so even though we // may have twice as many pixels, we still want lines and other drawing to // appear at the same size; the extra pixels will just make them crisper. context.scale(pixelRatio, pixelRatio); }; // Clears the entire canvas area, not including any overlaid HTML text Canvas.prototype.clear = function() { this.context.clearRect(0, 0, this.width, this.height); }; // Finishes rendering the canvas, including managing the text overlay. Canvas.prototype.render = function() { var cache = this._textCache; // For each text layer, add elements marked as active that haven't // already been rendered, and remove those that are no longer active. for (var layerKey in cache) { if (hasOwnProperty.call(cache, layerKey)) { var layer = this.getTextLayer(layerKey), layerCache = cache[layerKey]; layer.hide(); for (var styleKey in layerCache) { if (hasOwnProperty.call(layerCache, styleKey)) { var styleCache = layerCache[styleKey]; for (var key in styleCache) { if (hasOwnProperty.call(styleCache, key)) { var positions = styleCache[key].positions; for (var i = 0, position; position = positions[i]; i++) { if (position.active) { if (!position.rendered) { layer.append(position.element); position.rendered = true; } } else { positions.splice(i--, 1); if (position.rendered) { position.element.detach(); } } } if (positions.length == 0) { delete styleCache[key]; } } } } } layer.show(); } } }; // Creates (if necessary) and returns the text overlay container. // // @param {string} classes String of space-separated CSS classes used to // uniquely identify the text layer. // @return {object} The jQuery-wrapped text-layer div. Canvas.prototype.getTextLayer = function(classes) { var layer = this.text[classes]; // Create the text layer if it doesn't exist if (layer == null) { // Create the text layer container, if it doesn't exist if (this.textContainer == null) { this.textContainer = $("<div class='flot-text'></div>") .css({ position: "absolute", top: 0, left: 0, bottom: 0, right: 0, 'font-size': "smaller", color: "#545454" }) .insertAfter(this.element); } layer = this.text[classes] = $("<div></div>") .addClass(classes) .css({ position: "absolute", top: 0, left: 0, bottom: 0, right: 0 }) .appendTo(this.textContainer); } return layer; }; // Creates (if necessary) and returns a text info object. // // The object looks like this: // // { // width: Width of the text's wrapper div. // height: Height of the text's wrapper div. // element: The jQuery-wrapped HTML div containing the text. // positions: Array of positions at which this text is drawn. // } // // The positions array contains objects that look like this: // // { // active: Flag indicating whether the text should be visible. // rendered: Flag indicating whether the text is currently visible. // element: The jQuery-wrapped HTML div containing the text. // x: X coordinate at which to draw the text. // y: Y coordinate at which to draw the text. // } // // Each position after the first receives a clone of the original element. // // The idea is that that the width, height, and general 'identity' of the // text is constant no matter where it is placed; the placements are a // secondary property. // // Canvas maintains a cache of recently-used text info objects; getTextInfo // either returns the cached element or creates a new entry. // // @param {string} layer A string of space-separated CSS classes uniquely // identifying the layer containing this text. // @param {string} text Text string to retrieve info for. // @param {(string|object)=} font Either a string of space-separated CSS // classes or a font-spec object, defining the text's font and style. // @param {number=} angle Angle at which to rotate the text, in degrees. // Angle is currently unused, it will be implemented in the future. // @param {number=} width Maximum width of the text before it wraps. // @return {object} a text info object. Canvas.prototype.getTextInfo = function(layer, text, font, angle, width) { var textStyle, layerCache, styleCache, info; // Cast the value to a string, in case we were given a number or such text = "" + text; // If the font is a font-spec object, generate a CSS font definition if (typeof font === "object") { textStyle = font.style + " " + font.variant + " " + font.weight + " " + font.size + "px/" + font.lineHeight + "px " + font.family; } else { textStyle = font; } // Retrieve (or create) the cache for the text's layer and styles layerCache = this._textCache[layer]; if (layerCache == null) { layerCache = this._textCache[layer] = {}; } styleCache = layerCache[textStyle]; if (styleCache == null) { styleCache = layerCache[textStyle] = {}; } info = styleCache[text]; // If we can't find a matching element in our cache, create a new one if (info == null) { var element = $("<div></div>").html(text) .css({ position: "absolute", 'max-width': width, top: -9999 }) .appendTo(this.getTextLayer(layer)); if (typeof font === "object") { element.css({ font: textStyle, color: font.color }); } else if (typeof font === "string") { element.addClass(font); } info = styleCache[text] = { width: element.outerWidth(true), height: element.outerHeight(true), element: element, positions: [] }; element.detach(); } return info; }; // Adds a text string to the canvas text overlay. // // The text isn't drawn immediately; it is marked as rendering, which will // result in its addition to the canvas on the next render pass. // // @param {string} layer A string of space-separated CSS classes uniquely // identifying the layer containing this text. // @param {number} x X coordinate at which to draw the text. // @param {number} y Y coordinate at which to draw the text. // @param {string} text Text string to draw. // @param {(string|object)=} font Either a string of space-separated CSS // classes or a font-spec object, defining the text's font and style. // @param {number=} angle Angle at which to rotate the text, in degrees. // Angle is currently unused, it will be implemented in the future. // @param {number=} width Maximum width of the text before it wraps. // @param {string=} halign Horizontal alignment of the text; either "left", // "center" or "right". // @param {string=} valign Vertical alignment of the text; either "top", // "middle" or "bottom". Canvas.prototype.addText = function(layer, x, y, text, font, angle, width, halign, valign) { var info = this.getTextInfo(layer, text, font, angle, width), positions = info.positions; // Tweak the div's position to match the text's alignment if (halign == "center") { x -= info.width / 2; } else if (halign == "right") { x -= info.width; } if (valign == "middle") { y -= info.height / 2; } else if (valign == "bottom") { y -= info.height; } // Determine whether this text already exists at this position. // If so, mark it for inclusion in the next render pass. for (var i = 0, position; position = positions[i]; i++) { if (position.x == x && position.y == y) { position.active = true; return; } } // If the text doesn't exist at this position, create a new entry // For the very first position we'll re-use the original element, // while for subsequent ones we'll clone it. position = { active: true, rendered: false, element: positions.length ? info.element.clone() : info.element, x: x, y: y }; positions.push(position); // Move the element to its final position within the container position.element.css({ top: Math.round(y), left: Math.round(x), 'text-align': halign // In case the text wraps }); }; // Removes one or more text strings from the canvas text overlay. // // If no parameters are given, all text within the layer is removed. // // Note that the text is not immediately removed; it is simply marked as // inactive, which will result in its removal on the next render pass. // This avoids the performance penalty for 'clear and redraw' behavior, // where we potentially get rid of all text on a layer, but will likely // add back most or all of it later, as when redrawing axes, for example. // // @param {string} layer A string of space-separated CSS classes uniquely // identifying the layer containing this text. // @param {number=} x X coordinate of the text. // @param {number=} y Y coordinate of the text. // @param {string=} text Text string to remove. // @param {(string|object)=} font Either a string of space-separated CSS // classes or a font-spec object, defining the text's font and style. // @param {number=} angle Angle at which the text is rotated, in degrees. // Angle is currently unused, it will be implemented in the future. Canvas.prototype.removeText = function(layer, x, y, text, font, angle) { if (text == null) { var layerCache = this._textCache[layer]; if (layerCache != null) { for (var styleKey in layerCache) { if (hasOwnProperty.call(layerCache, styleKey)) { var styleCache = layerCache[styleKey]; for (var key in styleCache) { if (hasOwnProperty.call(styleCache, key)) { var positions = styleCache[key].positions; for (var i = 0, position; position = positions[i]; i++) { position.active = false; } } } } } } } else { var positions = this.getTextInfo(layer, text, font, angle).positions; for (var i = 0, position; position = positions[i]; i++) { if (position.x == x && position.y == y) { position.active = false; } } } }; /////////////////////////////////////////////////////////////////////////// // The top-level container for the entire plot. function Plot(placeholder, data_, options_, plugins) { // data is on the form: // [ series1, series2 ... ] // where series is either just the data as [ [x1, y1], [x2, y2], ... ] // or { data: [ [x1, y1], [x2, y2], ... ], label: "some label", ... } var series = [], options = { // the color theme used for graphs colors: ["#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed"], legend: { show: true, noColumns: 1, // number of colums in legend table labelFormatter: null, // fn: string -> string labelBoxBorderColor: "#ccc", // border color for the little label boxes container: null, // container (as jQuery object) to put legend in, null means default on top of graph position: "ne", // position of default legend container within plot margin: 5, // distance from grid edge to default legend container within plot backgroundColor: null, // null means auto-detect backgroundOpacity: 0.85, // set to 0 to avoid background sorted: null // default to no legend sorting }, xaxis: { show: null, // null = auto-detect, true = always, false = never position: "bottom", // or "top" mode: null, // null or "time" font: null, // null (derived from CSS in placeholder) or object like { size: 11, lineHeight: 13, style: "italic", weight: "bold", family: "sans-serif", variant: "small-caps" } color: null, // base color, labels, ticks tickColor: null, // possibly different color of ticks, e.g. "rgba(0,0,0,0.15)" transform: null, // null or f: number -> number to transform axis inverseTransform: null, // if transform is set, this should be the inverse function min: null, // min. value to show, null means set automatically max: null, // max. value to show, null means set automatically autoscaleMargin: null, // margin in % to add if auto-setting min/max ticks: null, // either [1, 3] or [[1, "a"], 3] or (fn: axis info -> ticks) or app. number of ticks for auto-ticks tickFormatter: null, // fn: number -> string labelWidth: null, // size of tick labels in pixels labelHeight: null, reserveSpace: null, // whether to reserve space even if axis isn't shown tickLength: null, // size in pixels of ticks, or "full" for whole line alignTicksWithAxis: null, // axis number or null for no sync tickDecimals: null, // no. of decimals, null means auto tickSize: null, // number or [number, "unit"] minTickSize: null // number or [number, "unit"] }, yaxis: { autoscaleMargin: 0.02, position: "left" // or "right" }, xaxes: [], yaxes: [], series: { points: { show: false, radius: 3, lineWidth: 2, // in pixels fill: true, fillColor: "#ffffff", symbol: "circle" // or callback }, lines: { // we don't put in show: false so we can see // whether lines were actively disabled lineWidth: 2, // in pixels fill: false, fillColor: null, steps: false // Omit 'zero', so we can later default its value to // match that of the 'fill' option. }, bars: { show: false, lineWidth: 2, // in pixels barWidth: 1, // in units of the x axis fill: true, fillColor: null, align: "left", // "left", "right", or "center" horizontal: false, zero: true }, shadowSize: 3, highlightColor: null }, grid: { show: true, aboveData: false, color: "#545454", // primary color used for outline and labels backgroundColor: null, // null for transparent, else color borderColor: null, // set if different from the grid color tickColor: null, // color for the ticks, e.g. "rgba(0,0,0,0.15)" margin: 0, // distance from the canvas edge to the grid labelMargin: 5, // in pixels axisMargin: 8, // in pixels borderWidth: 2, // in pixels minBorderMargin: null, // in pixels, null means taken from points radius markings: null, // array of ranges or fn: axes -> array of ranges markingsColor: "#f4f4f4", markingsLineWidth: 2, // interactive stuff clickable: false, hoverable: false, autoHighlight: true, // highlight in case mouse is near mouseActiveRadius: 10 // how far the mouse can be away to activate an item }, interaction: { redrawOverlayInterval: 1000/60 // time between updates, -1 means in same flow }, hooks: {} }, surface = null, // the canvas for the plot itself overlay = null, // canvas for interactive stuff on top of plot eventHolder = null, // jQuery object that events should be bound to ctx = null, octx = null, xaxes = [], yaxes = [], plotOffset = { left: 0, right: 0, top: 0, bottom: 0}, plotWidth = 0, plotHeight = 0, hooks = { processOptions: [], processRawData: [], processDatapoints: [], processOffset: [], drawBackground: [], drawSeries: [], draw: [], bindEvents: [], drawOverlay: [], shutdown: [] }, plot = this; // public functions plot.setData = setData; plot.setupGrid = setupGrid; plot.draw = draw; plot.getPlaceholder = function() { return placeholder; }; plot.getCanvas = function() { return surface.element; }; plot.getPlotOffset = function() { return plotOffset; }; plot.width = function () { return plotWidth; }; plot.height = function () { return plotHeight; }; plot.offset = function () { var o = eventHolder.offset(); o.left += plotOffset.left; o.top += plotOffset.top; return o; }; plot.getData = function () { return series; }; plot.getAxes = function () { var res = {}, i; $.each(xaxes.concat(yaxes), function (_, axis) { if (axis) res[axis.direction + (axis.n != 1 ? axis.n : "") + "axis"] = axis; }); return res; }; plot.getXAxes = function () { return xaxes; }; plot.getYAxes = function () { return yaxes; }; plot.c2p = canvasToAxisCoords; plot.p2c = axisToCanvasCoords; plot.getOptions = function () { return options; }; plot.highlight = highlight; plot.unhighlight = unhighlight; plot.triggerRedrawOverlay = triggerRedrawOverlay; plot.pointOffset = function(point) { return { left: parseInt(xaxes[axisNumber(point, "x") - 1].p2c(+point.x) + plotOffset.left, 10), top: parseInt(yaxes[axisNumber(point, "y") - 1].p2c(+point.y) + plotOffset.top, 10) }; }; plot.shutdown = shutdown; plot.destroy = function () { shutdown(); placeholder.removeData("plot").empty(); series = []; options = null; surface = null; overlay = null; eventHolder = null; ctx = null; octx = null; xaxes = []; yaxes = []; hooks = null; highlights = []; plot = null; }; plot.resize = function () { var width = placeholder.width(), height = placeholder.height(); surface.resize(width, height); overlay.resize(width, height); }; // public attributes plot.hooks = hooks; // initialize initPlugins(plot); parseOptions(options_); setupCanvases(); setData(data_); setupGrid(); draw(); bindEvents(); function executeHooks(hook, args) { args = [plot].concat(args); for (var i = 0; i < hook.length; ++i) hook[i].apply(this, args); } function initPlugins() { // References to key classes, allowing plugins to modify them var classes = { Canvas: Canvas }; for (var i = 0; i < plugins.length; ++i) { var p = plugins[i]; p.init(plot, classes); if (p.options) $.extend(true, options, p.options); } } function parseOptions(opts) { $.extend(true, options, opts); // $.extend merges arrays, rather than replacing them. When less // colors are provided than the size of the default palette, we // end up with those colors plus the remaining defaults, which is // not expected behavior; avoid it by replacing them here. if (opts && opts.colors) { options.colors = opts.colors; } if (options.xaxis.color == null) options.xaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString(); if (options.yaxis.color == null) options.yaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString(); if (options.xaxis.tickColor == null) // grid.tickColor for back-compatibility options.xaxis.tickColor = options.grid.tickColor || options.xaxis.color; if (options.yaxis.tickColor == null) // grid.tickColor for back-compatibility options.yaxis.tickColor = options.grid.tickColor || options.yaxis.color; if (options.grid.borderColor == null) options.grid.borderColor = options.grid.color; if (options.grid.tickColor == null) options.grid.tickColor = $.color.parse(options.grid.color).scale('a', 0.22).toString(); // Fill in defaults for axis options, including any unspecified // font-spec fields, if a font-spec was provided. // If no x/y axis options were provided, create one of each anyway, // since the rest of the code assumes that they exist. var i, axisOptions, axisCount, fontSize = placeholder.css("font-size"), fontSizeDefault = fontSize ? +fontSize.replace("px", "") : 13, fontDefaults = { style: placeholder.css("font-style"), size: Math.round(0.8 * fontSizeDefault), variant: placeholder.css("font-variant"), weight: placeholder.css("font-weight"), family: placeholder.css("font-family") }; axisCount = options.xaxes.length || 1; for (i = 0; i < axisCount; ++i) { axisOptions = options.xaxes[i]; if (axisOptions && !axisOptions.tickColor) { axisOptions.tickColor = axisOptions.color; } axisOptions = $.extend(true, {}, options.xaxis, axisOptions); options.xaxes[i] = axisOptions; if (axisOptions.font) { axisOptions.font = $.extend({}, fontDefaults, axisOptions.font); if (!axisOptions.font.color) { axisOptions.font.color = axisOptions.color; } if (!axisOptions.font.lineHeight) { axisOptions.font.lineHeight = Math.round(axisOptions.font.size * 1.15); } } } axisCount = options.yaxes.length || 1; for (i = 0; i < axisCount; ++i) { axisOptions = options.yaxes[i]; if (axisOptions && !axisOptions.tickColor) { axisOptions.tickColor = axisOptions.color; } axisOptions = $.extend(true, {}, options.yaxis, axisOptions); options.yaxes[i] = axisOptions; if (axisOptions.font) { axisOptions.font = $.extend({}, fontDefaults, axisOptions.font); if (!axisOptions.font.color) { axisOptions.font.color = axisOptions.color; } if (!axisOptions.font.lineHeight) { axisOptions.font.lineHeight = Math.round(axisOptions.font.size * 1.15); } } } // backwards compatibility, to be removed in future if (options.xaxis.noTicks && options.xaxis.ticks == null) options.xaxis.ticks = options.xaxis.noTicks; if (options.yaxis.noTicks && options.yaxis.ticks == null) options.yaxis.ticks = options.yaxis.noTicks; if (options.x2axis) { options.xaxes[1] = $.extend(true, {}, options.xaxis, options.x2axis); options.xaxes[1].position = "top"; } if (options.y2axis) { options.yaxes[1] = $.extend(true, {}, options.yaxis, options.y2axis); options.yaxes[1].position = "right"; } if (options.grid.coloredAreas) options.grid.markings = options.grid.coloredAreas; if (options.grid.coloredAreasColor) options.grid.markingsColor = options.grid.coloredAreasColor; if (options.lines) $.extend(true, options.series.lines, options.lines); if (options.points) $.extend(true, options.series.points, options.points); if (options.bars) $.extend(true, options.series.bars, options.bars); if (options.shadowSize != null) options.series.shadowSize = options.shadowSize; if (options.highlightColor != null) options.series.highlightColor = options.highlightColor; // save options on axes for future reference for (i = 0; i < options.xaxes.length; ++i) getOrCreateAxis(xaxes, i + 1).options = options.xaxes[i]; for (i = 0; i < options.yaxes.length; ++i) getOrCreateAxis(yaxes, i + 1).options = options.yaxes[i]; // add hooks from options for (var n in hooks) if (options.hooks[n] && options.hooks[n].length) hooks[n] = hooks[n].concat(options.hooks[n]); executeHooks(hooks.processOptions, [options]); } function setData(d) { series = parseData(d); fillInSeriesOptions(); processData(); } function parseData(d) { var res = []; for (var i = 0; i < d.length; ++i) { var s = $.extend(true, {}, options.series); if (d[i].data != null) { s.data = d[i].data; // move the data instead of deep-copy delete d[i].data; $.extend(true, s, d[i]); d[i].data = s.data; } else s.data = d[i]; res.push(s); } return res; } function axisNumber(obj, coord) { var a = obj[coord + "axis"]; if (typeof a == "object") // if we got a real axis, extract number a = a.n; if (typeof a != "number") a = 1; // default to first axis return a; } function allAxes() { // return flat array without annoying null entries return $.grep(xaxes.concat(yaxes), function (a) { return a; }); } function canvasToAxisCoords(pos) { // return an object with x/y corresponding to all used axes var res = {}, i, axis; for (i = 0; i < xaxes.length; ++i) { axis = xaxes[i]; if (axis && axis.used) res["x" + axis.n] = axis.c2p(pos.left); } for (i = 0; i < yaxes.length; ++i) { axis = yaxes[i]; if (axis && axis.used) res["y" + axis.n] = axis.c2p(pos.top); } if (res.x1 !== undefined) res.x = res.x1; if (res.y1 !== undefined) res.y = res.y1; return res; } function axisToCanvasCoords(pos) { // get canvas coords from the first pair of x/y found in pos var res = {}, i, axis, key; for (i = 0; i < xaxes.length; ++i) { axis = xaxes[i]; if (axis && axis.used) { key = "x" + axis.n; if (pos[key] == null && axis.n == 1) key = "x"; if (pos[key] != null) { res.left = axis.p2c(pos[key]); break; } } } for (i = 0; i < yaxes.length; ++i) { axis = yaxes[i]; if (axis && axis.used) { key = "y" + axis.n; if (pos[key] == null && axis.n == 1) key = "y"; if (pos[key] != null) { res.top = axis.p2c(pos[key]); break; } } } return res; } function getOrCreateAxis(axes, number) { if (!axes[number - 1]) axes[number - 1] = { n: number, // save the number for future reference direction: axes == xaxes ? "x" : "y", options: $.extend(true, {}, axes == xaxes ? options.xaxis : options.yaxis) }; return axes[number - 1]; } function fillInSeriesOptions() { var neededColors = series.length, maxIndex = -1, i; // Subtract the number of series that already have fixed colors or // color indexes from the number that we still need to generate. for (i = 0; i < series.length; ++i) { var sc = series[i].color; if (sc != null) { neededColors--; if (typeof sc == "number" && sc > maxIndex) { maxIndex = sc; } } } // If any of the series have fixed color indexes, then we need to // generate at least as many colors as the highest index. if (neededColors <= maxIndex) { neededColors = maxIndex + 1; } // Generate all the colors, using first the option colors and then // variations on those colors once they're exhausted. var c, colors = [], colorPool = options.colors, colorPoolSize = colorPool.length, variation = 0; for (i = 0; i < neededColors; i++) { c = $.color.parse(colorPool[i % colorPoolSize] || "#666"); // Each time we exhaust the colors in the pool we adjust // a scaling factor used to produce more variations on // those colors. The factor alternates negative/positive // to produce lighter/darker colors. // Reset the variation after every few cycles, or else // it will end up producing only white or black colors. if (i % colorPoolSize == 0 && i) { if (variation >= 0) { if (variation < 0.5) { variation = -variation - 0.2; } else variation = 0; } else variation = -variation; } colors[i] = c.scale('rgb', 1 + variation); } // Finalize the series options, filling in their colors var colori = 0, s; for (i = 0; i < series.length; ++i) { s = series[i]; // assign colors if (s.color == null) { s.color = colors[colori].toString(); ++colori; } else if (typeof s.color == "number") s.color = colors[s.color].toString(); // turn on lines automatically in case nothing is set if (s.lines.show == null) { var v, show = true; for (v in s) if (s[v] && s[v].show) { show = false; break; } if (show) s.lines.show = true; } // If nothing was provided for lines.zero, default it to match // lines.fill, since areas by default should extend to zero. if (s.lines.zero == null) { s.lines.zero = !!s.lines.fill; } // setup axes s.xaxis = getOrCreateAxis(xaxes, axisNumber(s, "x")); s.yaxis = getOrCreateAxis(yaxes, axisNumber(s, "y")); } } function processData() { var topSentry = Number.POSITIVE_INFINITY, bottomSentry = Number.NEGATIVE_INFINITY, fakeInfinity = Number.MAX_VALUE, i, j, k, m, length, s, points, ps, x, y, axis, val, f, p, data, format; function updateAxis(axis, min, max) { if (min < axis.datamin && min != -fakeInfinity) axis.datamin = min; if (max > axis.datamax && max != fakeInfinity) axis.datamax = max; } $.each(allAxes(), function (_, axis) { // init axis axis.datamin = topSentry; axis.datamax = bottomSentry; axis.used = false; }); for (i = 0; i < series.length; ++i) { s = series[i]; s.datapoints = { points: [] }; executeHooks(hooks.processRawData, [ s, s.data, s.datapoints ]); } // first pass: clean and copy data for (i = 0; i < series.length; ++i) { s = series[i]; data = s.data; format = s.datapoints.format; if (!format) { format = []; // find out how to copy format.push({ x: true, number: true, required: true }); format.push({ y: true, number: true, required: true }); if (s.bars.show || (s.lines.show && s.lines.fill)) { var autoscale = !!((s.bars.show && s.bars.zero) || (s.lines.show && s.lines.zero)); format.push({ y: true, number: true, required: false, defaultValue: 0, autoscale: autoscale }); if (s.bars.horizontal) { delete format[format.length - 1].y; format[format.length - 1].x = true; } } s.datapoints.format = format; } if (s.datapoints.pointsize != null) continue; // already filled in s.datapoints.pointsize = format.length; ps = s.datapoints.pointsize; points = s.datapoints.points; var insertSteps = s.lines.show && s.lines.steps; s.xaxis.used = s.yaxis.used = true; for (j = k = 0; j < data.length; ++j, k += ps) { p = data[j]; var nullify = p == null; if (!nullify) { for (m = 0; m < ps; ++m) { val = p[m]; f = format[m]; if (f) { if (f.number && val != null) { val = +val; // convert to number if (isNaN(val)) val = null; else if (val == Infinity) val = fakeInfinity; else if (val == -Infinity) val = -fakeInfinity; } if (val == null) { if (f.required) nullify = true; if (f.defaultValue != null) val = f.defaultValue; } } points[k + m] = val; } } if (nullify) { for (m = 0; m < ps; ++m) { val = points[k + m]; if (val != null) { f = format[m]; // extract min/max info if (f.autoscale !== false) { if (f.x) { updateAxis(s.xaxis, val, val); } if (f.y) { updateAxis(s.yaxis, val, val); } } } points[k + m] = null; } } else { // a little bit of line specific stuff that // perhaps shouldn't be here, but lacking // better means... if (insertSteps && k > 0 && points[k - ps] != null && points[k - ps] != points[k] && points[k - ps + 1] != points[k + 1]) { // copy the point to make room for a middle point for (m = 0; m < ps; ++m) points[k + ps + m] = points[k + m]; // middle point has same y points[k + 1] = points[k - ps + 1]; // we've added a point, better reflect that k += ps; } } } } // give the hooks a chance to run for (i = 0; i < series.length; ++i) { s = series[i]; executeHooks(hooks.processDatapoints, [ s, s.datapoints]); } // second pass: find datamax/datamin for auto-scaling for (i = 0; i < series.length; ++i) { s = series[i]; points = s.datapoints.points; ps = s.datapoints.pointsize; format = s.datapoints.format; var xmin = topSentry, ymin = topSentry, xmax = bottomSentry, ymax = bottomSentry; for (j = 0; j < points.length; j += ps) { if (points[j] == null) continue; for (m = 0; m < ps; ++m) { val = points[j + m]; f = format[m]; if (!f || f.autoscale === false || val == fakeInfinity || val == -fakeInfinity) continue; if (f.x) { if (val < xmin) xmin = val; if (val > xmax) xmax = val; } if (f.y) { if (val < ymin) ymin = val; if (val > ymax) ymax = val; } } } if (s.bars.show) { // make sure we got room for the bar on the dancing floor var delta; switch (s.bars.align) { case "left": delta = 0; break; case "right": delta = -s.bars.barWidth; break; default: delta = -s.bars.barWidth / 2; } if (s.bars.horizontal) { ymin += delta; ymax += delta + s.bars.barWidth; } else { xmin += delta; xmax += delta + s.bars.barWidth; } } updateAxis(s.xaxis, xmin, xmax); updateAxis(s.yaxis, ymin, ymax); } $.each(allAxes(), function (_, axis) { if (axis.datamin == topSentry) axis.datamin = null; if (axis.datamax == bottomSentry) axis.datamax = null; }); } function setupCanvases() { // Make sure the placeholder is clear of everything except canvases // from a previous plot in this container that we'll try to re-use. placeholder.css("padding", 0) // padding messes up the positioning .children().filter(function(){ return !$(this).hasClass("flot-overlay") && !$(this).hasClass('flot-base'); }).remove(); if (placeholder.css("position") == 'static') placeholder.css("position", "relative"); // for positioning labels and overlay surface = new Canvas("flot-base", placeholder); overlay = new Canvas("flot-overlay", placeholder); // overlay canvas for interactive features ctx = surface.context; octx = overlay.context; // define which element we're listening for events on eventHolder = $(overlay.element).unbind(); // If we're re-using a plot object, shut down the old one var existing = placeholder.data("plot"); if (existing) { existing.shutdown(); overlay.clear(); } // save in case we get replotted placeholder.data("plot", plot); } function bindEvents() { // bind events if (options.grid.hoverable) { eventHolder.mousemove(onMouseMove); // Use bind, rather than .mouseleave, because we officially // still support jQuery 1.2.6, which doesn't define a shortcut // for mouseenter or mouseleave. This was a bug/oversight that // was fixed somewhere around 1.3.x. We can return to using // .mouseleave when we drop support for 1.2.6. eventHolder.bind("mouseleave", onMouseLeave); } if (options.grid.clickable) eventHolder.click(onClick); executeHooks(hooks.bindEvents, [eventHolder]); } function shutdown() { if (redrawTimeout) clearTimeout(redrawTimeout); eventHolder.unbind("mousemove", onMouseMove); eventHolder.unbind("mouseleave", onMouseLeave); eventHolder.unbind("click", onClick); executeHooks(hooks.shutdown, [eventHolder]); } function setTransformationHelpers(axis) { // set helper functions on the axis, assumes plot area // has been computed already function identity(x) { return x; } var s, m, t = axis.options.transform || identity, it = axis.options.inverseTransform; // precompute how much the axis is scaling a point // in canvas space if (axis.direction == "x") { s = axis.scale = plotWidth / Math.abs(t(axis.max) - t(axis.min)); m = Math.min(t(axis.max), t(axis.min)); } else { s = axis.scale = plotHeight / Math.abs(t(axis.max) - t(axis.min)); s = -s; m = Math.max(t(axis.max), t(axis.min)); } // data point to canvas coordinate if (t == identity) // slight optimization axis.p2c = function (p) { return (p - m) * s; }; else axis.p2c = function (p) { return (t(p) - m) * s; }; // canvas coordinate to data point if (!it) axis.c2p = function (c) { return m + c / s; }; else axis.c2p = function (c) { return it(m + c / s); }; } function measureTickLabels(axis) { var opts = axis.options, ticks = axis.ticks || [], labelWidth = opts.labelWidth || 0, labelHeight = opts.labelHeight || 0, maxWidth = labelWidth || (axis.direction == "x" ? Math.floor(surface.width / (ticks.length || 1)) : null), legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis", layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles, font = opts.font || "flot-tick-label tickLabel"; for (var i = 0; i < ticks.length; ++i) { var t = ticks[i]; if (!t.label) continue; var info = surface.getTextInfo(layer, t.label, font, null, maxWidth); labelWidth = Math.max(labelWidth, info.width); labelHeight = Math.max(labelHeight, info.height); } axis.labelWidth = opts.labelWidth || labelWidth; axis.labelHeight = opts.labelHeight || labelHeight; } function allocateAxisBoxFirstPhase(axis) { // find the bounding box of the axis by looking at label // widths/heights and ticks, make room by diminishing the // plotOffset; this first phase only looks at one // dimension per axis, the other dimension depends on the // other axes so will have to wait var lw = axis.labelWidth, lh = axis.labelHeight, pos = axis.options.position, isXAxis = axis.direction === "x", tickLength = axis.options.tickLength, axisMargin = options.grid.axisMargin, padding = options.grid.labelMargin, innermost = true, outermost = true, first = true, found = false; // Determine the axis's position in its direction and on its side $.each(isXAxis ? xaxes : yaxes, function(i, a) { if (a && a.reserveSpace) { if (a === axis) { found = true; } else if (a.options.position === pos) { if (found) { outermost = false; } else { innermost = false; } } if (!found) { first = false; } } }); // The outermost axis on each side has no margin if (outermost) { axisMargin = 0; } // The ticks for the first axis in each direction stretch across if (tickLength == null) { tickLength = first ? "full" : 5; } if (!isNaN(+tickLength)) padding += +tickLength; if (isXAxis) { lh += padding; if (pos == "bottom") { plotOffset.bottom += lh + axisMargin; axis.box = { top: surface.height - plotOffset.bottom, height: lh }; } else { axis.box = { top: plotOffset.top + axisMargin, height: lh }; plotOffset.top += lh + axisMargin; } } else { lw += padding; if (pos == "left") { axis.box = { left: plotOffset.left + axisMargin, width: lw }; plotOffset.left += lw + axisMargin; } else { plotOffset.right += lw + axisMargin; axis.box = { left: surface.width - plotOffset.right, width: lw }; } } // save for future reference axis.position = pos; axis.tickLength = tickLength; axis.box.padding = padding; axis.innermost = innermost; } function allocateAxisBoxSecondPhase(axis) { // now that all axis boxes have been placed in one // dimension, we can set the remaining dimension coordinates if (axis.direction == "x") { axis.box.left = plotOffset.left - axis.labelWidth / 2; axis.box.width = surface.width - plotOffset.left - plotOffset.right + axis.labelWidth; } else { axis.box.top = plotOffset.top - axis.labelHeight / 2; axis.box.height = surface.height - plotOffset.bottom - plotOffset.top + axis.labelHeight; } } function adjustLayoutForThingsStickingOut() { // possibly adjust plot offset to ensure everything stays // inside the canvas and isn't clipped off var minMargin = options.grid.minBorderMargin, axis, i; // check stuff from the plot (FIXME: this should just read // a value from the series, otherwise it's impossible to // customize) if (minMargin == null) { minMargin = 0; for (i = 0; i < series.length; ++i) minMargin = Math.max(minMargin, 2 * (series[i].points.radius + series[i].points.lineWidth/2)); } var margins = { left: minMargin, right: minMargin, top: minMargin, bottom: minMargin }; // check axis labels, note we don't check the actual // labels but instead use the overall width/height to not // jump as much around with replots $.each(allAxes(), function (_, axis) { if (axis.reserveSpace && axis.ticks && axis.ticks.length) { var lastTick = axis.ticks[axis.ticks.length - 1]; if (axis.direction === "x") { margins.left = Math.max(margins.left, axis.labelWidth / 2); if (lastTick.v <= axis.max) { margins.right = Math.max(margins.right, axis.labelWidth / 2); } } else { margins.bottom = Math.max(margins.bottom, axis.labelHeight / 2); if (lastTick.v <= axis.max) { margins.top = Math.max(margins.top, axis.labelHeight / 2); } } } }); plotOffset.left = Math.ceil(Math.max(margins.left, plotOffset.left)); plotOffset.right = Math.ceil(Math.max(margins.right, plotOffset.right)); plotOffset.top = Math.ceil(Math.max(margins.top, plotOffset.top)); plotOffset.bottom = Math.ceil(Math.max(margins.bottom, plotOffset.bottom)); } function setupGrid() { var i, axes = allAxes(), showGrid = options.grid.show; // Initialize the plot's offset from the edge of the canvas for (var a in plotOffset) { var margin = options.grid.margin || 0; plotOffset[a] = typeof margin == "number" ? margin : margin[a] || 0; } executeHooks(hooks.processOffset, [plotOffset]); // If the grid is visible, add its border width to the offset for (var a in plotOffset) { if(typeof(options.grid.borderWidth) == "object") { plotOffset[a] += showGrid ? options.grid.borderWidth[a] : 0; } else { plotOffset[a] += showGrid ? options.grid.borderWidth : 0; } } // init axes $.each(axes, function (_, axis) { axis.show = axis.options.show; if (axis.show == null) axis.show = axis.used; // by default an axis is visible if it's got data axis.reserveSpace = axis.show || axis.options.reserveSpace; setRange(axis); }); if (showGrid) { var allocatedAxes = $.grep(axes, function (axis) { return axis.reserveSpace; }); $.each(allocatedAxes, function (_, axis) { // make the ticks setupTickGeneration(axis); setTicks(axis); snapRangeToTicks(axis, axis.ticks); // find labelWidth/Height for axis measureTickLabels(axis); }); // with all dimensions calculated, we can compute the // axis bounding boxes, start from the outside // (reverse order) for (i = allocatedAxes.length - 1; i >= 0; --i) allocateAxisBoxFirstPhase(allocatedAxes[i]); // make sure we've got enough space for things that // might stick out adjustLayoutForThingsStickingOut(); $.each(allocatedAxes, function (_, axis) { allocateAxisBoxSecondPhase(axis); }); } plotWidth = surface.width - plotOffset.left - plotOffset.right; plotHeight = surface.height - plotOffset.bottom - plotOffset.top; // now we got the proper plot dimensions, we can compute the scaling $.each(axes, function (_, axis) { setTransformationHelpers(axis); }); if (showGrid) { drawAxisLabels(); } insertLegend(); } function setRange(axis) { var opts = axis.options, min = +(opts.min != null ? opts.min : axis.datamin), max = +(opts.max != null ? opts.max : axis.datamax), delta = max - min; if (delta == 0.0) { // degenerate case var widen = max == 0 ? 1 : 0.01; if (opts.min == null) min -= widen; // always widen max if we couldn't widen min to ensure we // don't fall into min == max which doesn't work if (opts.max == null || opts.min != null) max += widen; } else { // consider autoscaling var margin = opts.autoscaleMargin; if (margin != null) { if (opts.min == null) { min -= delta * margin; // make sure we don't go below zero if all values // are positive if (min < 0 && axis.datamin != null && axis.datamin >= 0) min = 0; } if (opts.max == null) { max += delta * margin; if (max > 0 && axis.datamax != null && axis.datamax <= 0) max = 0; } } } axis.min = min; axis.max = max; } function setupTickGeneration(axis) { var opts = axis.options; // estimate number of ticks var noTicks; if (typeof opts.ticks == "number" && opts.ticks > 0) noTicks = opts.ticks; else // heuristic based on the model a*sqrt(x) fitted to // some data points that seemed reasonable noTicks = 0.3 * Math.sqrt(axis.direction == "x" ? surface.width : surface.height); var delta = (axis.max - axis.min) / noTicks, dec = -Math.floor(Math.log(delta) / Math.LN10), maxDec = opts.tickDecimals; if (maxDec != null && dec > maxDec) { dec = maxDec; } var magn = Math.pow(10, -dec), norm = delta / magn, // norm is between 1.0 and 10.0 size; if (norm < 1.5) { size = 1; } else if (norm < 3) { size = 2; // special case for 2.5, requires an extra decimal if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) { size = 2.5; ++dec; } } else if (norm < 7.5) { size = 5; } else { size = 10; } size *= magn; if (opts.minTickSize != null && size < opts.minTickSize) { size = opts.minTickSize; } axis.delta = delta; axis.tickDecimals = Math.max(0, maxDec != null ? maxDec : dec); axis.tickSize = opts.tickSize || size; // Time mode was moved to a plug-in in 0.8, but since so many people use this // we'll add an especially friendly make sure they remembered to include it. if (opts.mode == "time" && !axis.tickGenerator) { throw new Error("Time mode requires the flot.time plugin."); } // Flot supports base-10 axes; any other mode else is handled by a plug-in, // like flot.time.js. if (!axis.tickGenerator) { axis.tickGenerator = function (axis) { var ticks = [], start = floorInBase(axis.min, axis.tickSize), i = 0, v = Number.NaN, prev; do { prev = v; v = start + i * axis.tickSize; ticks.push(v); ++i; } while (v < axis.max && v != prev); return ticks; }; axis.tickFormatter = function (value, axis) { var factor = axis.tickDecimals ? Math.pow(10, axis.tickDecimals) : 1; var formatted = "" + Math.round(value * factor) / factor; // If tickDecimals was specified, ensure that we have exactly that // much precision; otherwise default to the value's own precision. if (axis.tickDecimals != null) { var decimal = formatted.indexOf("."); var precision = decimal == -1 ? 0 : formatted.length - decimal - 1; if (precision < axis.tickDecimals) { return (precision ? formatted : formatted + ".") + ("" + factor).substr(1, axis.tickDecimals - precision); } } return formatted; }; } if ($.isFunction(opts.tickFormatter)) axis.tickFormatter = function (v, axis) { return "" + opts.tickFormatter(v, axis); }; if (opts.alignTicksWithAxis != null) { var otherAxis = (axis.direction == "x" ? xaxes : yaxes)[opts.alignTicksWithAxis - 1]; if (otherAxis && otherAxis.used && otherAxis != axis) { // consider snapping min/max to outermost nice ticks var niceTicks = axis.tickGenerator(axis); if (niceTicks.length > 0) { if (opts.min == null) axis.min = Math.min(axis.min, niceTicks[0]); if (opts.max == null && niceTicks.length > 1) axis.max = Math.max(axis.max, niceTicks[niceTicks.length - 1]); } axis.tickGenerator = function (axis) { // copy ticks, scaled to this axis var ticks = [], v, i; for (i = 0; i < otherAxis.ticks.length; ++i) { v = (otherAxis.ticks[i].v - otherAxis.min) / (otherAxis.max - otherAxis.min); v = axis.min + v * (axis.max - axis.min); ticks.push(v); } return ticks; }; // we might need an extra decimal since forced // ticks don't necessarily fit naturally if (!axis.mode && opts.tickDecimals == null) { var extraDec = Math.max(0, -Math.floor(Math.log(axis.delta) / Math.LN10) + 1), ts = axis.tickGenerator(axis); // only proceed if the tick interval rounded // with an extra decimal doesn't give us a // zero at end if (!(ts.length > 1 && /\..*0$/.test((ts[1] - ts[0]).toFixed(extraDec)))) axis.tickDecimals = extraDec; } } } } function setTicks(axis) { var oticks = axis.options.ticks, ticks = []; if (oticks == null || (typeof oticks == "number" && oticks > 0)) ticks = axis.tickGenerator(axis); else if (oticks) { if ($.isFunction(oticks)) // generate the ticks ticks = oticks(axis); else ticks = oticks; } // clean up/labelify the supplied ticks, copy them over var i, v; axis.ticks = []; for (i = 0; i < ticks.length; ++i) { var label = null; var t = ticks[i]; if (typeof t == "object") { v = +t[0]; if (t.length > 1) label = t[1]; } else v = +t; if (label == null) label = axis.tickFormatter(v, axis); if (!isNaN(v)) axis.ticks.push({ v: v, label: label }); } } function snapRangeToTicks(axis, ticks) { if (axis.options.autoscaleMargin && ticks.length > 0) { // snap to ticks if (axis.options.min == null) axis.min = Math.min(axis.min, ticks[0].v); if (axis.options.max == null && ticks.length > 1) axis.max = Math.max(axis.max, ticks[ticks.length - 1].v); } } function draw() { surface.clear(); executeHooks(hooks.drawBackground, [ctx]); var grid = options.grid; // draw background, if any if (grid.show && grid.backgroundColor) drawBackground(); if (grid.show && !grid.aboveData) { drawGrid(); } for (var i = 0; i < series.length; ++i) { executeHooks(hooks.drawSeries, [ctx, series[i]]); drawSeries(series[i]); } executeHooks(hooks.draw, [ctx]); if (grid.show && grid.aboveData) { drawGrid(); } surface.render(); // A draw implies that either the axes or data have changed, so we // should probably update the overlay highlights as well. triggerRedrawOverlay(); } function extractRange(ranges, coord) { var axis, from, to, key, axes = allAxes(); for (var i = 0; i < axes.length; ++i) { axis = axes[i]; if (axis.direction == coord) { key = coord + axis.n + "axis"; if (!ranges[key] && axis.n == 1) key = coord + "axis"; // support x1axis as xaxis if (ranges[key]) { from = ranges[key].from; to = ranges[key].to; break; } } } // backwards-compat stuff - to be removed in future if (!ranges[key]) { axis = coord == "x" ? xaxes[0] : yaxes[0]; from = ranges[coord + "1"]; to = ranges[coord + "2"]; } // auto-reverse as an added bonus if (from != null && to != null && from > to) { var tmp = from; from = to; to = tmp; } return { from: from, to: to, axis: axis }; } function drawBackground() { ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); ctx.fillStyle = getColorOrGradient(options.grid.backgroundColor, plotHeight, 0, "rgba(255, 255, 255, 0)"); ctx.fillRect(0, 0, plotWidth, plotHeight); ctx.restore(); } function drawGrid() { var i, axes, bw, bc; ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); // draw markings var markings = options.grid.markings; if (markings) { if ($.isFunction(markings)) { axes = plot.getAxes(); // xmin etc. is backwards compatibility, to be // removed in the future axes.xmin = axes.xaxis.min; axes.xmax = axes.xaxis.max; axes.ymin = axes.yaxis.min; axes.ymax = axes.yaxis.max; markings = markings(axes); } for (i = 0; i < markings.length; ++i) { var m = markings[i], xrange = extractRange(m, "x"), yrange = extractRange(m, "y"); // fill in missing if (xrange.from == null) xrange.from = xrange.axis.min; if (xrange.to == null) xrange.to = xrange.axis.max; if (yrange.from == null) yrange.from = yrange.axis.min; if (yrange.to == null) yrange.to = yrange.axis.max; // clip if (xrange.to < xrange.axis.min || xrange.from > xrange.axis.max || yrange.to < yrange.axis.min || yrange.from > yrange.axis.max) continue; xrange.from = Math.max(xrange.from, xrange.axis.min); xrange.to = Math.min(xrange.to, xrange.axis.max); yrange.from = Math.max(yrange.from, yrange.axis.min); yrange.to = Math.min(yrange.to, yrange.axis.max); if (xrange.from == xrange.to && yrange.from == yrange.to) continue; // then draw xrange.from = xrange.axis.p2c(xrange.from); xrange.to = xrange.axis.p2c(xrange.to); yrange.from = yrange.axis.p2c(yrange.from); yrange.to = yrange.axis.p2c(yrange.to); if (xrange.from == xrange.to || yrange.from == yrange.to) { // draw line ctx.beginPath(); ctx.strokeStyle = m.color || options.grid.markingsColor; ctx.lineWidth = m.lineWidth || options.grid.markingsLineWidth; ctx.moveTo(xrange.from, yrange.from); ctx.lineTo(xrange.to, yrange.to); ctx.stroke(); } else { // fill area ctx.fillStyle = m.color || options.grid.markingsColor; ctx.fillRect(xrange.from, yrange.to, xrange.to - xrange.from, yrange.from - yrange.to); } } } // draw the ticks axes = allAxes(); bw = options.grid.borderWidth; for (var j = 0; j < axes.length; ++j) { var axis = axes[j], box = axis.box, t = axis.tickLength, x, y, xoff, yoff; if (!axis.show || axis.ticks.length == 0) continue; ctx.lineWidth = 1; // find the edges if (axis.direction == "x") { x = 0; if (t == "full") y = (axis.position == "top" ? 0 : plotHeight); else y = box.top - plotOffset.top + (axis.position == "top" ? box.height : 0); } else { y = 0; if (t == "full") x = (axis.position == "left" ? 0 : plotWidth); else x = box.left - plotOffset.left + (axis.position == "left" ? box.width : 0); } // draw tick bar if (!axis.innermost) { ctx.strokeStyle = axis.options.color; ctx.beginPath(); xoff = yoff = 0; if (axis.direction == "x") xoff = plotWidth + 1; else yoff = plotHeight + 1; if (ctx.lineWidth == 1) { if (axis.direction == "x") { y = Math.floor(y) + 0.5; } else { x = Math.floor(x) + 0.5; } } ctx.moveTo(x, y); ctx.lineTo(x + xoff, y + yoff); ctx.stroke(); } // draw ticks ctx.strokeStyle = axis.options.tickColor; ctx.beginPath(); for (i = 0; i < axis.ticks.length; ++i) { var v = axis.ticks[i].v; xoff = yoff = 0; if (isNaN(v) || v < axis.min || v > axis.max // skip those lying on the axes if we got a border || (t == "full" && ((typeof bw == "object" && bw[axis.position] > 0) || bw > 0) && (v == axis.min || v == axis.max))) continue; if (axis.direction == "x") { x = axis.p2c(v); yoff = t == "full" ? -plotHeight : t; if (axis.position == "top") yoff = -yoff; } else { y = axis.p2c(v); xoff = t == "full" ? -plotWidth : t; if (axis.position == "left") xoff = -xoff; } if (ctx.lineWidth == 1) { if (axis.direction == "x") x = Math.floor(x) + 0.5; else y = Math.floor(y) + 0.5; } ctx.moveTo(x, y); ctx.lineTo(x + xoff, y + yoff); } ctx.stroke(); } // draw border if (bw) { // If either borderWidth or borderColor is an object, then draw the border // line by line instead of as one rectangle bc = options.grid.borderColor; if(typeof bw == "object" || typeof bc == "object") { if (typeof bw !== "object") { bw = {top: bw, right: bw, bottom: bw, left: bw}; } if (typeof bc !== "object") { bc = {top: bc, right: bc, bottom: bc, left: bc}; } if (bw.top > 0) { ctx.strokeStyle = bc.top; ctx.lineWidth = bw.top; ctx.beginPath(); ctx.moveTo(0 - bw.left, 0 - bw.top/2); ctx.lineTo(plotWidth, 0 - bw.top/2); ctx.stroke(); } if (bw.right > 0) { ctx.strokeStyle = bc.right; ctx.lineWidth = bw.right; ctx.beginPath(); ctx.moveTo(plotWidth + bw.right / 2, 0 - bw.top); ctx.lineTo(plotWidth + bw.right / 2, plotHeight); ctx.stroke(); } if (bw.bottom > 0) { ctx.strokeStyle = bc.bottom; ctx.lineWidth = bw.bottom; ctx.beginPath(); ctx.moveTo(plotWidth + bw.right, plotHeight + bw.bottom / 2); ctx.lineTo(0, plotHeight + bw.bottom / 2); ctx.stroke(); } if (bw.left > 0) { ctx.strokeStyle = bc.left; ctx.lineWidth = bw.left; ctx.beginPath(); ctx.moveTo(0 - bw.left/2, plotHeight + bw.bottom); ctx.lineTo(0- bw.left/2, 0); ctx.stroke(); } } else { ctx.lineWidth = bw; ctx.strokeStyle = options.grid.borderColor; ctx.strokeRect(-bw/2, -bw/2, plotWidth + bw, plotHeight + bw); } } ctx.restore(); } function drawAxisLabels() { $.each(allAxes(), function (_, axis) { var box = axis.box, legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis", layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles, font = axis.options.font || "flot-tick-label tickLabel", tick, x, y, halign, valign; // Remove text before checking for axis.show and ticks.length; // otherwise plugins, like flot-tickrotor, that draw their own // tick labels will end up with both theirs and the defaults. surface.removeText(layer); if (!axis.show || axis.ticks.length == 0) return; for (var i = 0; i < axis.ticks.length; ++i) { tick = axis.ticks[i]; if (!tick.label || tick.v < axis.min || tick.v > axis.max) continue; if (axis.direction == "x") { halign = "center"; x = plotOffset.left + axis.p2c(tick.v); if (axis.position == "bottom") { y = box.top + box.padding; } else { y = box.top + box.height - box.padding; valign = "bottom"; } } else { valign = "middle"; y = plotOffset.top + axis.p2c(tick.v); if (axis.position == "left") { x = box.left + box.width - box.padding; halign = "right"; } else { x = box.left + box.padding; } } surface.addText(layer, x, y, tick.label, font, null, null, halign, valign); } }); } function drawSeries(series) { if (series.lines.show) drawSeriesLines(series); if (series.bars.show) drawSeriesBars(series); if (series.points.show) drawSeriesPoints(series); } function drawSeriesLines(series) { function plotLine(datapoints, xoffset, yoffset, axisx, axisy) { var points = datapoints.points, ps = datapoints.pointsize, prevx = null, prevy = null; ctx.beginPath(); for (var i = ps; i < points.length; i += ps) { var x1 = points[i - ps], y1 = points[i - ps + 1], x2 = points[i], y2 = points[i + 1]; if (x1 == null || x2 == null) continue; // clip with ymin if (y1 <= y2 && y1 < axisy.min) { if (y2 < axisy.min) continue; // line segment is outside // compute new intersection point x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.min; } else if (y2 <= y1 && y2 < axisy.min) { if (y1 < axisy.min) continue; x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.min; } // clip with ymax if (y1 >= y2 && y1 > axisy.max) { if (y2 > axisy.max) continue; x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.max; } else if (y2 >= y1 && y2 > axisy.max) { if (y1 > axisy.max) continue; x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.max; } // clip with xmin if (x1 <= x2 && x1 < axisx.min) { if (x2 < axisx.min) continue; y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.min; } else if (x2 <= x1 && x2 < axisx.min) { if (x1 < axisx.min) continue; y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.min; } // clip with xmax if (x1 >= x2 && x1 > axisx.max) { if (x2 > axisx.max) continue; y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.max; } else if (x2 >= x1 && x2 > axisx.max) { if (x1 > axisx.max) continue; y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.max; } if (x1 != prevx || y1 != prevy) ctx.moveTo(axisx.p2c(x1) + xoffset, axisy.p2c(y1) + yoffset); prevx = x2; prevy = y2; ctx.lineTo(axisx.p2c(x2) + xoffset, axisy.p2c(y2) + yoffset); } ctx.stroke(); } function plotLineArea(datapoints, axisx, axisy) { var points = datapoints.points, ps = datapoints.pointsize, bottom = Math.min(Math.max(0, axisy.min), axisy.max), i = 0, top, areaOpen = false, ypos = 1, segmentStart = 0, segmentEnd = 0; // we process each segment in two turns, first forward // direction to sketch out top, then once we hit the // end we go backwards to sketch the bottom while (true) { if (ps > 0 && i > points.length + ps) break; i += ps; // ps is negative if going backwards var x1 = points[i - ps], y1 = points[i - ps + ypos], x2 = points[i], y2 = points[i + ypos]; if (areaOpen) { if (ps > 0 && x1 != null && x2 == null) { // at turning point segmentEnd = i; ps = -ps; ypos = 2; continue; } if (ps < 0 && i == segmentStart + ps) { // done with the reverse sweep ctx.fill(); areaOpen = false; ps = -ps; ypos = 1; i = segmentStart = segmentEnd + ps; continue; } } if (x1 == null || x2 == null) continue; // clip x values // clip with xmin if (x1 <= x2 && x1 < axisx.min) { if (x2 < axisx.min) continue; y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.min; } else if (x2 <= x1 && x2 < axisx.min) { if (x1 < axisx.min) continue; y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.min; } // clip with xmax if (x1 >= x2 && x1 > axisx.max) { if (x2 > axisx.max) continue; y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.max; } else if (x2 >= x1 && x2 > axisx.max) { if (x1 > axisx.max) continue; y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.max; } if (!areaOpen) { // open area ctx.beginPath(); ctx.moveTo(axisx.p2c(x1), axisy.p2c(bottom)); areaOpen = true; } // now first check the case where both is outside if (y1 >= axisy.max && y2 >= axisy.max) { ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.max)); ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.max)); continue; } else if (y1 <= axisy.min && y2 <= axisy.min) { ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.min)); ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.min)); continue; } // else it's a bit more complicated, there might // be a flat maxed out rectangle first, then a // triangular cutout or reverse; to find these // keep track of the current x values var x1old = x1, x2old = x2; // clip the y values, without shortcutting, we // go through all cases in turn // clip with ymin if (y1 <= y2 && y1 < axisy.min && y2 >= axisy.min) { x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.min; } else if (y2 <= y1 && y2 < axisy.min && y1 >= axisy.min) { x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.min; } // clip with ymax if (y1 >= y2 && y1 > axisy.max && y2 <= axisy.max) { x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.max; } else if (y2 >= y1 && y2 > axisy.max && y1 <= axisy.max) { x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.max; } // if the x value was changed we got a rectangle // to fill if (x1 != x1old) { ctx.lineTo(axisx.p2c(x1old), axisy.p2c(y1)); // it goes to (x1, y1), but we fill that below } // fill triangular section, this sometimes result // in redundant points if (x1, y1) hasn't changed // from previous line to, but we just ignore that ctx.lineTo(axisx.p2c(x1), axisy.p2c(y1)); ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2)); // fill the other rectangle if it's there if (x2 != x2old) { ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2)); ctx.lineTo(axisx.p2c(x2old), axisy.p2c(y2)); } } } ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); ctx.lineJoin = "round"; var lw = series.lines.lineWidth, sw = series.shadowSize; // FIXME: consider another form of shadow when filling is turned on if (lw > 0 && sw > 0) { // draw shadow as a thick and thin line with transparency ctx.lineWidth = sw; ctx.strokeStyle = "rgba(0,0,0,0.1)"; // position shadow at angle from the mid of line var angle = Math.PI/18; plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/2), Math.cos(angle) * (lw/2 + sw/2), series.xaxis, series.yaxis); ctx.lineWidth = sw/2; plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/4), Math.cos(angle) * (lw/2 + sw/4), series.xaxis, series.yaxis); } ctx.lineWidth = lw; ctx.strokeStyle = series.color; var fillStyle = getFillStyle(series.lines, series.color, 0, plotHeight); if (fillStyle) { ctx.fillStyle = fillStyle; plotLineArea(series.datapoints, series.xaxis, series.yaxis); } if (lw > 0) plotLine(series.datapoints, 0, 0, series.xaxis, series.yaxis); ctx.restore(); } function drawSeriesPoints(series) { function plotPoints(datapoints, radius, fillStyle, offset, shadow, axisx, axisy, symbol) { var points = datapoints.points, ps = datapoints.pointsize; for (var i = 0; i < points.length; i += ps) { var x = points[i], y = points[i + 1]; if (x == null || x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max) continue; ctx.beginPath(); x = axisx.p2c(x); y = axisy.p2c(y) + offset; if (symbol == "circle") ctx.arc(x, y, radius, 0, shadow ? Math.PI : Math.PI * 2, false); else symbol(ctx, x, y, radius, shadow); ctx.closePath(); if (fillStyle) { ctx.fillStyle = fillStyle; ctx.fill(); } ctx.stroke(); } } ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); var lw = series.points.lineWidth, sw = series.shadowSize, radius = series.points.radius, symbol = series.points.symbol; // If the user sets the line width to 0, we change it to a very // small value. A line width of 0 seems to force the default of 1. // Doing the conditional here allows the shadow setting to still be // optional even with a lineWidth of 0. if( lw == 0 ) lw = 0.0001; if (lw > 0 && sw > 0) { // draw shadow in two steps var w = sw / 2; ctx.lineWidth = w; ctx.strokeStyle = "rgba(0,0,0,0.1)"; plotPoints(series.datapoints, radius, null, w + w/2, true, series.xaxis, series.yaxis, symbol); ctx.strokeStyle = "rgba(0,0,0,0.2)"; plotPoints(series.datapoints, radius, null, w/2, true, series.xaxis, series.yaxis, symbol); } ctx.lineWidth = lw; ctx.strokeStyle = series.color; plotPoints(series.datapoints, radius, getFillStyle(series.points, series.color), 0, false, series.xaxis, series.yaxis, symbol); ctx.restore(); } function drawBar(x, y, b, barLeft, barRight, fillStyleCallback, axisx, axisy, c, horizontal, lineWidth) { var left, right, bottom, top, drawLeft, drawRight, drawTop, drawBottom, tmp; // in horizontal mode, we start the bar from the left // instead of from the bottom so it appears to be // horizontal rather than vertical if (horizontal) { drawBottom = drawRight = drawTop = true; drawLeft = false; left = b; right = x; top = y + barLeft; bottom = y + barRight; // account for negative bars if (right < left) { tmp = right; right = left; left = tmp; drawLeft = true; drawRight = false; } } else { drawLeft = drawRight = drawTop = true; drawBottom = false; left = x + barLeft; right = x + barRight; bottom = b; top = y; // account for negative bars if (top < bottom) { tmp = top; top = bottom; bottom = tmp; drawBottom = true; drawTop = false; } } // clip if (right < axisx.min || left > axisx.max || top < axisy.min || bottom > axisy.max) return; if (left < axisx.min) { left = axisx.min; drawLeft = false; } if (right > axisx.max) { right = axisx.max; drawRight = false; } if (bottom < axisy.min) { bottom = axisy.min; drawBottom = false; } if (top > axisy.max) { top = axisy.max; drawTop = false; } left = axisx.p2c(left); bottom = axisy.p2c(bottom); right = axisx.p2c(right); top = axisy.p2c(top); // fill the bar if (fillStyleCallback) { c.fillStyle = fillStyleCallback(bottom, top); c.fillRect(left, top, right - left, bottom - top) } // draw outline if (lineWidth > 0 && (drawLeft || drawRight || drawTop || drawBottom)) { c.beginPath(); // FIXME: inline moveTo is buggy with excanvas c.moveTo(left, bottom); if (drawLeft) c.lineTo(left, top); else c.moveTo(left, top); if (drawTop) c.lineTo(right, top); else c.moveTo(right, top); if (drawRight) c.lineTo(right, bottom); else c.moveTo(right, bottom); if (drawBottom) c.lineTo(left, bottom); else c.moveTo(left, bottom); c.stroke(); } } function drawSeriesBars(series) { function plotBars(datapoints, barLeft, barRight, fillStyleCallback, axisx, axisy) { var points = datapoints.points, ps = datapoints.pointsize; for (var i = 0; i < points.length; i += ps) { if (points[i] == null) continue; drawBar(points[i], points[i + 1], points[i + 2], barLeft, barRight, fillStyleCallback, axisx, axisy, ctx, series.bars.horizontal, series.bars.lineWidth); } } ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); // FIXME: figure out a way to add shadows (for instance along the right edge) ctx.lineWidth = series.bars.lineWidth; ctx.strokeStyle = series.color; var barLeft; switch (series.bars.align) { case "left": barLeft = 0; break; case "right": barLeft = -series.bars.barWidth; break; default: barLeft = -series.bars.barWidth / 2; } var fillStyleCallback = series.bars.fill ? function (bottom, top) { return getFillStyle(series.bars, series.color, bottom, top); } : null; plotBars(series.datapoints, barLeft, barLeft + series.bars.barWidth, fillStyleCallback, series.xaxis, series.yaxis); ctx.restore(); } function getFillStyle(filloptions, seriesColor, bottom, top) { var fill = filloptions.fill; if (!fill) return null; if (filloptions.fillColor) return getColorOrGradient(filloptions.fillColor, bottom, top, seriesColor); var c = $.color.parse(seriesColor); c.a = typeof fill == "number" ? fill : 0.4; c.normalize(); return c.toString(); } function insertLegend() { if (options.legend.container != null) { $(options.legend.container).html(""); } else { placeholder.find(".legend").remove(); } if (!options.legend.show) { return; } var fragments = [], entries = [], rowStarted = false, lf = options.legend.labelFormatter, s, label; // Build a list of legend entries, with each having a label and a color for (var i = 0; i < series.length; ++i) { s = series[i]; if (s.label) { label = lf ? lf(s.label, s) : s.label; if (label) { entries.push({ label: label, color: s.color }); } } } // Sort the legend using either the default or a custom comparator if (options.legend.sorted) { if ($.isFunction(options.legend.sorted)) { entries.sort(options.legend.sorted); } else if (options.legend.sorted == "reverse") { entries.reverse(); } else { var ascending = options.legend.sorted != "descending"; entries.sort(function(a, b) { return a.label == b.label ? 0 : ( (a.label < b.label) != ascending ? 1 : -1 // Logical XOR ); }); } } // Generate markup for the list of entries, in their final order for (var i = 0; i < entries.length; ++i) { var entry = entries[i]; if (i % options.legend.noColumns == 0) { if (rowStarted) fragments.push('</tr>'); fragments.push('<tr>'); rowStarted = true; } fragments.push( '<td class="legendColorBox"><div style="border:1px solid ' + options.legend.labelBoxBorderColor + ';padding:1px"><div style="width:4px;height:0;border:5px solid ' + entry.color + ';overflow:hidden"></div></div></td>' + '<td class="legendLabel">' + entry.label + '</td>' ); } if (rowStarted) fragments.push('</tr>'); if (fragments.length == 0) return; var table = '<table style="font-size:smaller;color:' + options.grid.color + '">' + fragments.join("") + '</table>'; if (options.legend.container != null) $(options.legend.container).html(table); else { var pos = "", p = options.legend.position, m = options.legend.margin; if (m[0] == null) m = [m, m]; if (p.charAt(0) == "n") pos += 'top:' + (m[1] + plotOffset.top) + 'px;'; else if (p.charAt(0) == "s") pos += 'bottom:' + (m[1] + plotOffset.bottom) + 'px;'; if (p.charAt(1) == "e") pos += 'right:' + (m[0] + plotOffset.right) + 'px;'; else if (p.charAt(1) == "w") pos += 'left:' + (m[0] + plotOffset.left) + 'px;'; var legend = $('<div class="legend">' + table.replace('style="', 'style="position:absolute;' + pos +';') + '</div>').appendTo(placeholder); if (options.legend.backgroundOpacity != 0.0) { // put in the transparent background // separately to avoid blended labels and // label boxes var c = options.legend.backgroundColor; if (c == null) { c = options.grid.backgroundColor; if (c && typeof c == "string") c = $.color.parse(c); else c = $.color.extract(legend, 'background-color'); c.a = 1; c = c.toString(); } var div = legend.children(); $('<div style="position:absolute;width:' + div.width() + 'px;height:' + div.height() + 'px;' + pos +'background-color:' + c + ';"> </div>').prependTo(legend).css('opacity', options.legend.backgroundOpacity); } } } // interactive features var highlights = [], redrawTimeout = null; // returns the data item the mouse is over, or null if none is found function findNearbyItem(mouseX, mouseY, seriesFilter) { var maxDistance = options.grid.mouseActiveRadius, smallestDistance = maxDistance * maxDistance + 1, item = null, foundPoint = false, i, j, ps; for (i = series.length - 1; i >= 0; --i) { if (!seriesFilter(series[i])) continue; var s = series[i], axisx = s.xaxis, axisy = s.yaxis, points = s.datapoints.points, mx = axisx.c2p(mouseX), // precompute some stuff to make the loop faster my = axisy.c2p(mouseY), maxx = maxDistance / axisx.scale, maxy = maxDistance / axisy.scale; ps = s.datapoints.pointsize; // with inverse transforms, we can't use the maxx/maxy // optimization, sadly if (axisx.options.inverseTransform) maxx = Number.MAX_VALUE; if (axisy.options.inverseTransform) maxy = Number.MAX_VALUE; if (s.lines.show || s.points.show) { for (j = 0; j < points.length; j += ps) { var x = points[j], y = points[j + 1]; if (x == null) continue; // For points and lines, the cursor must be within a // certain distance to the data point if (x - mx > maxx || x - mx < -maxx || y - my > maxy || y - my < -maxy) continue; // We have to calculate distances in pixels, not in // data units, because the scales of the axes may be different var dx = Math.abs(axisx.p2c(x) - mouseX), dy = Math.abs(axisy.p2c(y) - mouseY), dist = dx * dx + dy * dy; // we save the sqrt // use <= to ensure last point takes precedence // (last generally means on top of) if (dist < smallestDistance) { smallestDistance = dist; item = [i, j / ps]; } } } if (s.bars.show && !item) { // no other point can be nearby var barLeft, barRight; switch (s.bars.align) { case "left": barLeft = 0; break; case "right": barLeft = -s.bars.barWidth; break; default: barLeft = -s.bars.barWidth / 2; } barRight = barLeft + s.bars.barWidth; for (j = 0; j < points.length; j += ps) { var x = points[j], y = points[j + 1], b = points[j + 2]; if (x == null) continue; // for a bar graph, the cursor must be inside the bar if (series[i].bars.horizontal ? (mx <= Math.max(b, x) && mx >= Math.min(b, x) && my >= y + barLeft && my <= y + barRight) : (mx >= x + barLeft && mx <= x + barRight && my >= Math.min(b, y) && my <= Math.max(b, y))) item = [i, j / ps]; } } } if (item) { i = item[0]; j = item[1]; ps = series[i].datapoints.pointsize; return { datapoint: series[i].datapoints.points.slice(j * ps, (j + 1) * ps), dataIndex: j, series: series[i], seriesIndex: i }; } return null; } function onMouseMove(e) { if (options.grid.hoverable) triggerClickHoverEvent("plothover", e, function (s) { return s["hoverable"] != false; }); } function onMouseLeave(e) { if (options.grid.hoverable) triggerClickHoverEvent("plothover", e, function (s) { return false; }); } function onClick(e) { triggerClickHoverEvent("plotclick", e, function (s) { return s["clickable"] != false; }); } // trigger click or hover event (they send the same parameters // so we share their code) function triggerClickHoverEvent(eventname, event, seriesFilter) { var offset = eventHolder.offset(), canvasX = event.pageX - offset.left - plotOffset.left, canvasY = event.pageY - offset.top - plotOffset.top, pos = canvasToAxisCoords({ left: canvasX, top: canvasY }); pos.pageX = event.pageX; pos.pageY = event.pageY; var item = findNearbyItem(canvasX, canvasY, seriesFilter); if (item) { // fill in mouse pos for any listeners out there item.pageX = parseInt(item.series.xaxis.p2c(item.datapoint[0]) + offset.left + plotOffset.left, 10); item.pageY = parseInt(item.series.yaxis.p2c(item.datapoint[1]) + offset.top + plotOffset.top, 10); } if (options.grid.autoHighlight) { // clear auto-highlights for (var i = 0; i < highlights.length; ++i) { var h = highlights[i]; if (h.auto == eventname && !(item && h.series == item.series && h.point[0] == item.datapoint[0] && h.point[1] == item.datapoint[1])) unhighlight(h.series, h.point); } if (item) highlight(item.series, item.datapoint, eventname); } placeholder.trigger(eventname, [ pos, item ]); } function triggerRedrawOverlay() { var t = options.interaction.redrawOverlayInterval; if (t == -1) { // skip event queue drawOverlay(); return; } if (!redrawTimeout) redrawTimeout = setTimeout(drawOverlay, t); } function drawOverlay() { redrawTimeout = null; // draw highlights octx.save(); overlay.clear(); octx.translate(plotOffset.left, plotOffset.top); var i, hi; for (i = 0; i < highlights.length; ++i) { hi = highlights[i]; if (hi.series.bars.show) drawBarHighlight(hi.series, hi.point); else drawPointHighlight(hi.series, hi.point); } octx.restore(); executeHooks(hooks.drawOverlay, [octx]); } function highlight(s, point, auto) { if (typeof s == "number") s = series[s]; if (typeof point == "number") { var ps = s.datapoints.pointsize; point = s.datapoints.points.slice(ps * point, ps * (point + 1)); } var i = indexOfHighlight(s, point); if (i == -1) { highlights.push({ series: s, point: point, auto: auto }); triggerRedrawOverlay(); } else if (!auto) highlights[i].auto = false; } function unhighlight(s, point) { if (s == null && point == null) { highlights = []; triggerRedrawOverlay(); return; } if (typeof s == "number") s = series[s]; if (typeof point == "number") { var ps = s.datapoints.pointsize; point = s.datapoints.points.slice(ps * point, ps * (point + 1)); } var i = indexOfHighlight(s, point); if (i != -1) { highlights.splice(i, 1); triggerRedrawOverlay(); } } function indexOfHighlight(s, p) { for (var i = 0; i < highlights.length; ++i) { var h = highlights[i]; if (h.series == s && h.point[0] == p[0] && h.point[1] == p[1]) return i; } return -1; } function drawPointHighlight(series, point) { var x = point[0], y = point[1], axisx = series.xaxis, axisy = series.yaxis, highlightColor = (typeof series.highlightColor === "string") ? series.highlightColor : $.color.parse(series.color).scale('a', 0.5).toString(); if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max) return; var pointRadius = series.points.radius + series.points.lineWidth / 2; octx.lineWidth = pointRadius; octx.strokeStyle = highlightColor; var radius = 1.5 * pointRadius; x = axisx.p2c(x); y = axisy.p2c(y); octx.beginPath(); if (series.points.symbol == "circle") octx.arc(x, y, radius, 0, 2 * Math.PI, false); else series.points.symbol(octx, x, y, radius, false); octx.closePath(); octx.stroke(); } function drawBarHighlight(series, point) { var highlightColor = (typeof series.highlightColor === "string") ? series.highlightColor : $.color.parse(series.color).scale('a', 0.5).toString(), fillStyle = highlightColor, barLeft; switch (series.bars.align) { case "left": barLeft = 0; break; case "right": barLeft = -series.bars.barWidth; break; default: barLeft = -series.bars.barWidth / 2; } octx.lineWidth = series.bars.lineWidth; octx.strokeStyle = highlightColor; drawBar(point[0], point[1], point[2] || 0, barLeft, barLeft + series.bars.barWidth, function () { return fillStyle; }, series.xaxis, series.yaxis, octx, series.bars.horizontal, series.bars.lineWidth); } function getColorOrGradient(spec, bottom, top, defaultColor) { if (typeof spec == "string") return spec; else { // assume this is a gradient spec; IE currently only // supports a simple vertical gradient properly, so that's // what we support too var gradient = ctx.createLinearGradient(0, top, 0, bottom); for (var i = 0, l = spec.colors.length; i < l; ++i) { var c = spec.colors[i]; if (typeof c != "string") { var co = $.color.parse(defaultColor); if (c.brightness != null) co = co.scale('rgb', c.brightness); if (c.opacity != null) co.a *= c.opacity; c = co.toString(); } gradient.addColorStop(i / (l - 1), c); } return gradient; } } } // Add the plot function to the top level of the jQuery object $.plot = function(placeholder, data, options) { //var t0 = new Date(); var plot = new Plot($(placeholder), data, options, $.plot.plugins); //(window.console ? console.log : alert)("time used (msecs): " + ((new Date()).getTime() - t0.getTime())); return plot; }; $.plot.version = "0.8.2"; $.plot.plugins = []; // Also add the plot function as a chainable property $.fn.plot = function(data, options) { return this.each(function() { $.plot(this, data, options); }); }; // round to nearby lower multiple of base function floorInBase(n, base) { return base * Math.floor(n / base); } })(jQuery);
JavaScript
(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 = $("<div class='" + this.options["class"] + "'></div>"); 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 = "<div class='morris-hover-row-label'>" + row.label + "</div>"; _ref = row.y; for (j = _i = 0, _len = _ref.length; _i < _len; j = ++_i) { y = _ref[j]; content += "<div class='morris-hover-point' style='color: " + (this.colorFor(row, j, 'label')) + "'>\n " + this.options.labels[j] + ":\n " + (this.yLabelFormat(y)) + "\n</div>"; } 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 = "<div class='morris-hover-row-label'>" + row.label + "</div>"; _ref = row.y; for (j = _i = 0, _len = _ref.length; _i < _len; j = ++_i) { y = _ref[j]; content += "<div class='morris-hover-point' style='color: " + (this.colorFor(row, j, 'label')) + "'>\n " + this.options.labels[j] + ":\n " + (this.yLabelFormat(y)) + "\n</div>"; } 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);
JavaScript
// moment.js language configuration // language : Moroccan Arabic (ar-ma) // author : ElFadili Yassine : https://github.com/ElFadiliY // author : Abdel Said : https://github.com/abdelsaid (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('ar-ma', { months : "يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"), monthsShort : "يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"), weekdays : "الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"), weekdaysShort : "احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت".split("_"), weekdaysMin : "ح_ن_ث_ر_خ_ج_س".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[اليوم على الساعة] LT", nextDay: '[غدا على الساعة] LT', nextWeek: 'dddd [على الساعة] LT', lastDay: '[أمس على الساعة] LT', lastWeek: 'dddd [على الساعة] LT', sameElse: 'L' }, relativeTime : { future : "في %s", past : "منذ %s", s : "ثوان", m : "دقيقة", mm : "%d دقائق", h : "ساعة", hh : "%d ساعات", d : "يوم", dd : "%d أيام", M : "شهر", MM : "%d أشهر", y : "سنة", yy : "%d سنوات" }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Arabic (ar) // author : Abdel Said : https://github.com/abdelsaid // changes in months, weekdays : Ahmed Elkhatib (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('ar', { months : "يناير/ كانون الثاني_فبراير/ شباط_مارس/ آذار_أبريل/ نيسان_مايو/ أيار_يونيو/ حزيران_يوليو/ تموز_أغسطس/ آب_سبتمبر/ أيلول_أكتوبر/ تشرين الأول_نوفمبر/ تشرين الثاني_ديسمبر/ كانون الأول".split("_"), monthsShort : "يناير/ كانون الثاني_فبراير/ شباط_مارس/ آذار_أبريل/ نيسان_مايو/ أيار_يونيو/ حزيران_يوليو/ تموز_أغسطس/ آب_سبتمبر/ أيلول_أكتوبر/ تشرين الأول_نوفمبر/ تشرين الثاني_ديسمبر/ كانون الأول".split("_"), weekdays : "الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"), weekdaysShort : "الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"), weekdaysMin : "ح_ن_ث_ر_خ_ج_س".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[اليوم على الساعة] LT", nextDay: '[غدا على الساعة] LT', nextWeek: 'dddd [على الساعة] LT', lastDay: '[أمس على الساعة] LT', lastWeek: 'dddd [على الساعة] LT', sameElse: 'L' }, relativeTime : { future : "في %s", past : "منذ %s", s : "ثوان", m : "دقيقة", mm : "%d دقائق", h : "ساعة", hh : "%d ساعات", d : "يوم", dd : "%d أيام", M : "شهر", MM : "%d أشهر", y : "سنة", yy : "%d سنوات" }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : bulgarian (bg) // author : Krasen Borisov : https://github.com/kraz (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('bg', { months : "януари_февруари_март_април_май_юни_юли_август_септември_октомври_ноември_декември".split("_"), monthsShort : "янр_фев_мар_апр_май_юни_юли_авг_сеп_окт_ное_дек".split("_"), weekdays : "неделя_понеделник_вторник_сряда_четвъртък_петък_събота".split("_"), weekdaysShort : "нед_пон_вто_сря_чет_пет_съб".split("_"), weekdaysMin : "нд_пн_вт_ср_чт_пт_сб".split("_"), longDateFormat : { LT : "H:mm", L : "D.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[Днес в] LT', nextDay : '[Утре в] LT', nextWeek : 'dddd [в] LT', lastDay : '[Вчера в] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: case 6: return '[В изминалата] dddd [в] LT'; case 1: case 2: case 4: case 5: return '[В изминалия] dddd [в] LT'; } }, sameElse : 'L' }, relativeTime : { future : "след %s", past : "преди %s", s : "няколко секунди", m : "минута", mm : "%d минути", h : "час", hh : "%d часа", d : "ден", dd : "%d дни", M : "месец", MM : "%d месеца", y : "година", yy : "%d години" }, ordinal : function (number) { var lastDigit = number % 10, last2Digits = number % 100; if (number === 0) { return number + '-ев'; } else if (last2Digits === 0) { return number + '-ен'; } else if (last2Digits > 10 && last2Digits < 20) { return number + '-ти'; } else if (lastDigit === 1) { return number + '-ви'; } else if (lastDigit === 2) { return number + '-ри'; } else if (lastDigit === 7 || lastDigit === 8) { return number + '-ми'; } else { return number + '-ти'; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : breton (br) // author : Jean-Baptiste Le Duigou : https://github.com/jbleduigou (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function relativeTimeWithMutation(number, withoutSuffix, key) { var format = { 'mm': "munutenn", 'MM': "miz", 'dd': "devezh" }; return number + ' ' + mutation(format[key], number); } function specialMutationForYears(number) { switch (lastNumber(number)) { case 1: case 3: case 4: case 5: case 9: return number + ' bloaz'; default: return number + ' vloaz'; } } function lastNumber(number) { if (number > 9) { return lastNumber(number % 10); } return number; } function mutation(text, number) { if (number === 2) { return softMutation(text); } return text; } function softMutation(text) { var mutationTable = { 'm': 'v', 'b': 'v', 'd': 'z' }; if (mutationTable[text.charAt(0)] === undefined) { return text; } return mutationTable[text.charAt(0)] + text.substring(1); } return moment.lang('br', { months : "Genver_C'hwevrer_Meurzh_Ebrel_Mae_Mezheven_Gouere_Eost_Gwengolo_Here_Du_Kerzu".split("_"), monthsShort : "Gen_C'hwe_Meu_Ebr_Mae_Eve_Gou_Eos_Gwe_Her_Du_Ker".split("_"), weekdays : "Sul_Lun_Meurzh_Merc'her_Yaou_Gwener_Sadorn".split("_"), weekdaysShort : "Sul_Lun_Meu_Mer_Yao_Gwe_Sad".split("_"), weekdaysMin : "Su_Lu_Me_Mer_Ya_Gw_Sa".split("_"), longDateFormat : { LT : "h[e]mm A", L : "DD/MM/YYYY", LL : "D [a viz] MMMM YYYY", LLL : "D [a viz] MMMM YYYY LT", LLLL : "dddd, D [a viz] MMMM YYYY LT" }, calendar : { sameDay : '[Hiziv da] LT', nextDay : '[Warc\'hoazh da] LT', nextWeek : 'dddd [da] LT', lastDay : '[Dec\'h da] LT', lastWeek : 'dddd [paset da] LT', sameElse : 'L' }, relativeTime : { future : "a-benn %s", past : "%s 'zo", s : "un nebeud segondennoù", m : "ur vunutenn", mm : relativeTimeWithMutation, h : "un eur", hh : "%d eur", d : "un devezh", dd : relativeTimeWithMutation, M : "ur miz", MM : relativeTimeWithMutation, y : "ur bloaz", yy : specialMutationForYears }, ordinal : function (number) { var output = (number === 1) ? 'añ' : 'vet'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : bosnian (bs) // author : Nedim Cholich : https://github.com/frontyard // based on (hr) translation by Bojan Marković (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function translate(number, withoutSuffix, key) { var result = number + " "; switch (key) { case 'm': return withoutSuffix ? 'jedna minuta' : 'jedne minute'; case 'mm': if (number === 1) { result += 'minuta'; } else if (number === 2 || number === 3 || number === 4) { result += 'minute'; } else { result += 'minuta'; } return result; case 'h': return withoutSuffix ? 'jedan sat' : 'jednog sata'; case 'hh': if (number === 1) { result += 'sat'; } else if (number === 2 || number === 3 || number === 4) { result += 'sata'; } else { result += 'sati'; } return result; case 'dd': if (number === 1) { result += 'dan'; } else { result += 'dana'; } return result; case 'MM': if (number === 1) { result += 'mjesec'; } else if (number === 2 || number === 3 || number === 4) { result += 'mjeseca'; } else { result += 'mjeseci'; } return result; case 'yy': if (number === 1) { result += 'godina'; } else if (number === 2 || number === 3 || number === 4) { result += 'godine'; } else { result += 'godina'; } return result; } } return moment.lang('bs', { months : "januar_februar_mart_april_maj_juni_juli_avgust_septembar_oktobar_novembar_decembar".split("_"), monthsShort : "jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.".split("_"), weekdays : "nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota".split("_"), weekdaysShort : "ned._pon._uto._sri._čet._pet._sub.".split("_"), weekdaysMin : "ne_po_ut_sr_če_pe_su".split("_"), longDateFormat : { LT : "H:mm", L : "DD. MM. YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay : '[danas u] LT', nextDay : '[sutra u] LT', nextWeek : function () { switch (this.day()) { case 0: return '[u] [nedjelju] [u] LT'; case 3: return '[u] [srijedu] [u] LT'; case 6: return '[u] [subotu] [u] LT'; case 1: case 2: case 4: case 5: return '[u] dddd [u] LT'; } }, lastDay : '[jučer u] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: return '[prošlu] dddd [u] LT'; case 6: return '[prošle] [subote] [u] LT'; case 1: case 2: case 4: case 5: return '[prošli] dddd [u] LT'; } }, sameElse : 'L' }, relativeTime : { future : "za %s", past : "prije %s", s : "par sekundi", m : translate, mm : translate, h : translate, hh : translate, d : "dan", dd : translate, M : "mjesec", MM : translate, y : "godinu", yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : catalan (ca) // author : Juan G. Hurtado : https://github.com/juanghurtado (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('ca', { months : "gener_febrer_març_abril_maig_juny_juliol_agost_setembre_octubre_novembre_desembre".split("_"), monthsShort : "gen._febr._mar._abr._mai._jun._jul._ag._set._oct._nov._des.".split("_"), weekdays : "diumenge_dilluns_dimarts_dimecres_dijous_divendres_dissabte".split("_"), weekdaysShort : "dg._dl._dt._dc._dj._dv._ds.".split("_"), weekdaysMin : "Dg_Dl_Dt_Dc_Dj_Dv_Ds".split("_"), longDateFormat : { LT : "H:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay : function () { return '[avui a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, nextDay : function () { return '[demà a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, nextWeek : function () { return 'dddd [a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, lastDay : function () { return '[ahir a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, lastWeek : function () { return '[el] dddd [passat a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, sameElse : 'L' }, relativeTime : { future : "en %s", past : "fa %s", s : "uns segons", m : "un minut", mm : "%d minuts", h : "una hora", hh : "%d hores", d : "un dia", dd : "%d dies", M : "un mes", MM : "%d mesos", y : "un any", yy : "%d anys" }, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : czech (cs) // author : petrbela : https://github.com/petrbela (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var months = "leden_únor_březen_duben_květen_červen_červenec_srpen_září_říjen_listopad_prosinec".split("_"), monthsShort = "led_úno_bře_dub_kvě_čvn_čvc_srp_zář_říj_lis_pro".split("_"); function plural(n) { return (n > 1) && (n < 5) && (~~(n / 10) !== 1); } function translate(number, withoutSuffix, key, isFuture) { var result = number + " "; switch (key) { case 's': // a few seconds / in a few seconds / a few seconds ago return (withoutSuffix || isFuture) ? 'pár vteřin' : 'pár vteřinami'; case 'm': // a minute / in a minute / a minute ago return withoutSuffix ? 'minuta' : (isFuture ? 'minutu' : 'minutou'); case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'minuty' : 'minut'); } else { return result + 'minutami'; } break; case 'h': // an hour / in an hour / an hour ago return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou'); case 'hh': // 9 hours / in 9 hours / 9 hours ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'hodiny' : 'hodin'); } else { return result + 'hodinami'; } break; case 'd': // a day / in a day / a day ago return (withoutSuffix || isFuture) ? 'den' : 'dnem'; case 'dd': // 9 days / in 9 days / 9 days ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'dny' : 'dní'); } else { return result + 'dny'; } break; case 'M': // a month / in a month / a month ago return (withoutSuffix || isFuture) ? 'měsíc' : 'měsícem'; case 'MM': // 9 months / in 9 months / 9 months ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'měsíce' : 'měsíců'); } else { return result + 'měsíci'; } break; case 'y': // a year / in a year / a year ago return (withoutSuffix || isFuture) ? 'rok' : 'rokem'; case 'yy': // 9 years / in 9 years / 9 years ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'roky' : 'let'); } else { return result + 'lety'; } break; } } return moment.lang('cs', { months : months, monthsShort : monthsShort, monthsParse : (function (months, monthsShort) { var i, _monthsParse = []; for (i = 0; i < 12; i++) { // use custom parser to solve problem with July (červenec) _monthsParse[i] = new RegExp('^' + months[i] + '$|^' + monthsShort[i] + '$', 'i'); } return _monthsParse; }(months, monthsShort)), weekdays : "neděle_pondělí_úterý_středa_čtvrtek_pátek_sobota".split("_"), weekdaysShort : "ne_po_út_st_čt_pá_so".split("_"), weekdaysMin : "ne_po_út_st_čt_pá_so".split("_"), longDateFormat : { LT: "H:mm", L : "DD.MM.YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd D. MMMM YYYY LT" }, calendar : { sameDay: "[dnes v] LT", nextDay: '[zítra v] LT', nextWeek: function () { switch (this.day()) { case 0: return '[v neděli v] LT'; case 1: case 2: return '[v] dddd [v] LT'; case 3: return '[ve středu v] LT'; case 4: return '[ve čtvrtek v] LT'; case 5: return '[v pátek v] LT'; case 6: return '[v sobotu v] LT'; } }, lastDay: '[včera v] LT', lastWeek: function () { switch (this.day()) { case 0: return '[minulou neděli v] LT'; case 1: case 2: return '[minulé] dddd [v] LT'; case 3: return '[minulou středu v] LT'; case 4: case 5: return '[minulý] dddd [v] LT'; case 6: return '[minulou sobotu v] LT'; } }, sameElse: "L" }, relativeTime : { future : "za %s", past : "před %s", s : translate, m : translate, mm : translate, h : translate, hh : translate, d : translate, dd : translate, M : translate, MM : translate, y : translate, yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : chuvash (cv) // author : Anatoly Mironov : https://github.com/mirontoli (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('cv', { months : "кăрлач_нарăс_пуш_ака_май_çĕртме_утă_çурла_авăн_юпа_чӳк_раштав".split("_"), monthsShort : "кăр_нар_пуш_ака_май_çĕр_утă_çур_ав_юпа_чӳк_раш".split("_"), weekdays : "вырсарникун_тунтикун_ытларикун_юнкун_кĕçнерникун_эрнекун_шăматкун".split("_"), weekdaysShort : "выр_тун_ытл_юн_кĕç_эрн_шăм".split("_"), weekdaysMin : "вр_тн_ыт_юн_кç_эр_шм".split("_"), longDateFormat : { LT : "HH:mm", L : "DD-MM-YYYY", LL : "YYYY [çулхи] MMMM [уйăхĕн] D[-мĕшĕ]", LLL : "YYYY [çулхи] MMMM [уйăхĕн] D[-мĕшĕ], LT", LLLL : "dddd, YYYY [çулхи] MMMM [уйăхĕн] D[-мĕшĕ], LT" }, calendar : { sameDay: '[Паян] LT [сехетре]', nextDay: '[Ыран] LT [сехетре]', lastDay: '[Ĕнер] LT [сехетре]', nextWeek: '[Çитес] dddd LT [сехетре]', lastWeek: '[Иртнĕ] dddd LT [сехетре]', sameElse: 'L' }, relativeTime : { future : function (output) { var affix = /сехет$/i.exec(output) ? "рен" : /çул$/i.exec(output) ? "тан" : "ран"; return output + affix; }, past : "%s каялла", s : "пĕр-ик çеккунт", m : "пĕр минут", mm : "%d минут", h : "пĕр сехет", hh : "%d сехет", d : "пĕр кун", dd : "%d кун", M : "пĕр уйăх", MM : "%d уйăх", y : "пĕр çул", yy : "%d çул" }, ordinal : '%d-мĕш', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Welsh (cy) // author : Robert Allen (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang("cy", { months: "Ionawr_Chwefror_Mawrth_Ebrill_Mai_Mehefin_Gorffennaf_Awst_Medi_Hydref_Tachwedd_Rhagfyr".split("_"), monthsShort: "Ion_Chwe_Maw_Ebr_Mai_Meh_Gor_Aws_Med_Hyd_Tach_Rhag".split("_"), weekdays: "Dydd Sul_Dydd Llun_Dydd Mawrth_Dydd Mercher_Dydd Iau_Dydd Gwener_Dydd Sadwrn".split("_"), weekdaysShort: "Sul_Llun_Maw_Mer_Iau_Gwe_Sad".split("_"), weekdaysMin: "Su_Ll_Ma_Me_Ia_Gw_Sa".split("_"), // time formats are the same as en-gb longDateFormat: { LT: "HH:mm", L: "DD/MM/YYYY", LL: "D MMMM YYYY", LLL: "D MMMM YYYY LT", LLLL: "dddd, D MMMM YYYY LT" }, calendar: { sameDay: '[Heddiw am] LT', nextDay: '[Yfory am] LT', nextWeek: 'dddd [am] LT', lastDay: '[Ddoe am] LT', lastWeek: 'dddd [diwethaf am] LT', sameElse: 'L' }, relativeTime: { future: "mewn %s", past: "%s yn àl", s: "ychydig eiliadau", m: "munud", mm: "%d munud", h: "awr", hh: "%d awr", d: "diwrnod", dd: "%d diwrnod", M: "mis", MM: "%d mis", y: "blwyddyn", yy: "%d flynedd" }, // traditional ordinal numbers above 31 are not commonly used in colloquial Welsh ordinal: function (number) { var b = number, output = '', lookup = [ '', 'af', 'il', 'ydd', 'ydd', 'ed', 'ed', 'ed', 'fed', 'fed', 'fed', // 1af to 10fed 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'fed' // 11eg to 20fed ]; if (b > 20) { if (b === 40 || b === 50 || b === 60 || b === 80 || b === 100) { output = 'fed'; // not 30ain, 70ain or 90ain } else { output = 'ain'; } } else if (b > 0) { output = lookup[b]; } return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : danish (da) // author : Ulrik Nielsen : https://github.com/mrbase (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('da', { months : "januar_februar_marts_april_maj_juni_juli_august_september_oktober_november_december".split("_"), monthsShort : "jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec".split("_"), weekdays : "søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag".split("_"), weekdaysShort : "søn_man_tir_ons_tor_fre_lør".split("_"), weekdaysMin : "sø_ma_ti_on_to_fr_lø".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D. MMMM, YYYY LT" }, calendar : { sameDay : '[I dag kl.] LT', nextDay : '[I morgen kl.] LT', nextWeek : 'dddd [kl.] LT', lastDay : '[I går kl.] LT', lastWeek : '[sidste] dddd [kl] LT', sameElse : 'L' }, relativeTime : { future : "om %s", past : "%s siden", s : "få sekunder", m : "et minut", mm : "%d minutter", h : "en time", hh : "%d timer", d : "en dag", dd : "%d dage", M : "en måned", MM : "%d måneder", y : "et år", yy : "%d år" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : german (de) // author : lluchs : https://github.com/lluchs // author: Menelion Elensúle: https://github.com/Oire (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function processRelativeTime(number, withoutSuffix, key, isFuture) { var format = { 'm': ['eine Minute', 'einer Minute'], 'h': ['eine Stunde', 'einer Stunde'], 'd': ['ein Tag', 'einem Tag'], 'dd': [number + ' Tage', number + ' Tagen'], 'M': ['ein Monat', 'einem Monat'], 'MM': [number + ' Monate', number + ' Monaten'], 'y': ['ein Jahr', 'einem Jahr'], 'yy': [number + ' Jahre', number + ' Jahren'] }; return withoutSuffix ? format[key][0] : format[key][1]; } return moment.lang('de', { months : "Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember".split("_"), monthsShort : "Jan._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.".split("_"), weekdays : "Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag".split("_"), weekdaysShort : "So._Mo._Di._Mi._Do._Fr._Sa.".split("_"), weekdaysMin : "So_Mo_Di_Mi_Do_Fr_Sa".split("_"), longDateFormat : { LT: "H:mm [Uhr]", L : "DD.MM.YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay: "[Heute um] LT", sameElse: "L", nextDay: '[Morgen um] LT', nextWeek: 'dddd [um] LT', lastDay: '[Gestern um] LT', lastWeek: '[letzten] dddd [um] LT' }, relativeTime : { future : "in %s", past : "vor %s", s : "ein paar Sekunden", m : processRelativeTime, mm : "%d Minuten", h : processRelativeTime, hh : "%d Stunden", d : processRelativeTime, dd : processRelativeTime, M : processRelativeTime, MM : processRelativeTime, y : processRelativeTime, yy : processRelativeTime }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : modern greek (el) // author : Aggelos Karalias : https://github.com/mehiel (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('el', { monthsNominativeEl : "Ιανουάριος_Φεβρουάριος_Μάρτιος_Απρίλιος_Μάιος_Ιούνιος_Ιούλιος_Αύγουστος_Σεπτέμβριος_Οκτώβριος_Νοέμβριος_Δεκέμβριος".split("_"), monthsGenitiveEl : "Ιανουαρίου_Φεβρουαρίου_Μαρτίου_Απριλίου_Μαΐου_Ιουνίου_Ιουλίου_Αυγούστου_Σεπτεμβρίου_Οκτωβρίου_Νοεμβρίου_Δεκεμβρίου".split("_"), months : function (momentToFormat, format) { if (/D/.test(format.substring(0, format.indexOf("MMMM")))) { // if there is a day number before 'MMMM' return this._monthsGenitiveEl[momentToFormat.month()]; } else { return this._monthsNominativeEl[momentToFormat.month()]; } }, monthsShort : "Ιαν_Φεβ_Μαρ_Απρ_Μαϊ_Ιουν_Ιουλ_Αυγ_Σεπ_Οκτ_Νοε_Δεκ".split("_"), weekdays : "Κυριακή_Δευτέρα_Τρίτη_Τετάρτη_Πέμπτη_Παρασκευή_Σάββατο".split("_"), weekdaysShort : "Κυρ_Δευ_Τρι_Τετ_Πεμ_Παρ_Σαβ".split("_"), weekdaysMin : "Κυ_Δε_Τρ_Τε_Πε_Πα_Σα".split("_"), meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'μμ' : 'ΜΜ'; } else { return isLower ? 'πμ' : 'ΠΜ'; } }, longDateFormat : { LT : "h:mm A", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendarEl : { sameDay : '[Σήμερα {}] LT', nextDay : '[Αύριο {}] LT', nextWeek : 'dddd [{}] LT', lastDay : '[Χθες {}] LT', lastWeek : '[την προηγούμενη] dddd [{}] LT', sameElse : 'L' }, calendar : function (key, mom) { var output = this._calendarEl[key], hours = mom && mom.hours(); return output.replace("{}", (hours % 12 === 1 ? "στη" : "στις")); }, relativeTime : { future : "σε %s", past : "%s πριν", s : "δευτερόλεπτα", m : "ένα λεπτό", mm : "%d λεπτά", h : "μία ώρα", hh : "%d ώρες", d : "μία μέρα", dd : "%d μέρες", M : "ένας μήνας", MM : "%d μήνες", y : "ένας χρόνος", yy : "%d χρόνια" }, ordinal : function (number) { return number + 'η'; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4st is the first week of the year. } }); })); // moment.js language configuration // language : australian english (en-au) (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('en-au', { months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), longDateFormat : { LT : "h:mm A", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, relativeTime : { future : "in %s", past : "%s ago", s : "a few seconds", m : "a minute", mm : "%d minutes", h : "an hour", hh : "%d hours", d : "a day", dd : "%d days", M : "a month", MM : "%d months", y : "a year", yy : "%d years" }, ordinal : function (number) { var b = number % 10, output = (~~ (number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : canadian english (en-ca) // author : Jonathan Abourbih : https://github.com/jonbca (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('en-ca', { months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), longDateFormat : { LT : "h:mm A", L : "YYYY-MM-DD", LL : "D MMMM, YYYY", LLL : "D MMMM, YYYY LT", LLLL : "dddd, D MMMM, YYYY LT" }, calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, relativeTime : { future : "in %s", past : "%s ago", s : "a few seconds", m : "a minute", mm : "%d minutes", h : "an hour", hh : "%d hours", d : "a day", dd : "%d days", M : "a month", MM : "%d months", y : "a year", yy : "%d years" }, ordinal : function (number) { var b = number % 10, output = (~~ (number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); })); // moment.js language configuration // language : great britain english (en-gb) // author : Chris Gedrim : https://github.com/chrisgedrim (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('en-gb', { months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, relativeTime : { future : "in %s", past : "%s ago", s : "a few seconds", m : "a minute", mm : "%d minutes", h : "an hour", hh : "%d hours", d : "a day", dd : "%d days", M : "a month", MM : "%d months", y : "a year", yy : "%d years" }, ordinal : function (number) { var b = number % 10, output = (~~ (number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : esperanto (eo) // author : Colin Dean : https://github.com/colindean // komento: Mi estas malcerta se mi korekte traktis akuzativojn en tiu traduko. // Se ne, bonvolu korekti kaj avizi min por ke mi povas lerni! (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('eo', { months : "januaro_februaro_marto_aprilo_majo_junio_julio_aŭgusto_septembro_oktobro_novembro_decembro".split("_"), monthsShort : "jan_feb_mar_apr_maj_jun_jul_aŭg_sep_okt_nov_dec".split("_"), weekdays : "Dimanĉo_Lundo_Mardo_Merkredo_Ĵaŭdo_Vendredo_Sabato".split("_"), weekdaysShort : "Dim_Lun_Mard_Merk_Ĵaŭ_Ven_Sab".split("_"), weekdaysMin : "Di_Lu_Ma_Me_Ĵa_Ve_Sa".split("_"), longDateFormat : { LT : "HH:mm", L : "YYYY-MM-DD", LL : "D[-an de] MMMM, YYYY", LLL : "D[-an de] MMMM, YYYY LT", LLLL : "dddd, [la] D[-an de] MMMM, YYYY LT" }, meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'p.t.m.' : 'P.T.M.'; } else { return isLower ? 'a.t.m.' : 'A.T.M.'; } }, calendar : { sameDay : '[Hodiaŭ je] LT', nextDay : '[Morgaŭ je] LT', nextWeek : 'dddd [je] LT', lastDay : '[Hieraŭ je] LT', lastWeek : '[pasinta] dddd [je] LT', sameElse : 'L' }, relativeTime : { future : "je %s", past : "antaŭ %s", s : "sekundoj", m : "minuto", mm : "%d minutoj", h : "horo", hh : "%d horoj", d : "tago",//ne 'diurno', ĉar estas uzita por proksimumo dd : "%d tagoj", M : "monato", MM : "%d monatoj", y : "jaro", yy : "%d jaroj" }, ordinal : "%da", week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : spanish (es) // author : Julio Napurí : https://github.com/julionc (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('es', { months : "enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre".split("_"), monthsShort : "ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.".split("_"), weekdays : "domingo_lunes_martes_miércoles_jueves_viernes_sábado".split("_"), weekdaysShort : "dom._lun._mar._mié._jue._vie._sáb.".split("_"), weekdaysMin : "Do_Lu_Ma_Mi_Ju_Vi_Sá".split("_"), longDateFormat : { LT : "H:mm", L : "DD/MM/YYYY", LL : "D [de] MMMM [de] YYYY", LLL : "D [de] MMMM [de] YYYY LT", LLLL : "dddd, D [de] MMMM [de] YYYY LT" }, calendar : { sameDay : function () { return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextDay : function () { return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextWeek : function () { return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastDay : function () { return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastWeek : function () { return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, sameElse : 'L' }, relativeTime : { future : "en %s", past : "hace %s", s : "unos segundos", m : "un minuto", mm : "%d minutos", h : "una hora", hh : "%d horas", d : "un día", dd : "%d días", M : "un mes", MM : "%d meses", y : "un año", yy : "%d años" }, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : estonian (et) // author : Henry Kehlmann : https://github.com/madhenry // improvements : Illimar Tambek : https://github.com/ragulka (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function processRelativeTime(number, withoutSuffix, key, isFuture) { var format = { 's' : ['mõne sekundi', 'mõni sekund', 'paar sekundit'], 'm' : ['ühe minuti', 'üks minut'], 'mm': [number + ' minuti', number + ' minutit'], 'h' : ['ühe tunni', 'tund aega', 'üks tund'], 'hh': [number + ' tunni', number + ' tundi'], 'd' : ['ühe päeva', 'üks päev'], 'M' : ['kuu aja', 'kuu aega', 'üks kuu'], 'MM': [number + ' kuu', number + ' kuud'], 'y' : ['ühe aasta', 'aasta', 'üks aasta'], 'yy': [number + ' aasta', number + ' aastat'] }; if (withoutSuffix) { return format[key][2] ? format[key][2] : format[key][1]; } return isFuture ? format[key][0] : format[key][1]; } return moment.lang('et', { months : "jaanuar_veebruar_märts_aprill_mai_juuni_juuli_august_september_oktoober_november_detsember".split("_"), monthsShort : "jaan_veebr_märts_apr_mai_juuni_juuli_aug_sept_okt_nov_dets".split("_"), weekdays : "pühapäev_esmaspäev_teisipäev_kolmapäev_neljapäev_reede_laupäev".split("_"), weekdaysShort : "P_E_T_K_N_R_L".split("_"), weekdaysMin : "P_E_T_K_N_R_L".split("_"), longDateFormat : { LT : "H:mm", L : "DD.MM.YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay : '[Täna,] LT', nextDay : '[Homme,] LT', nextWeek : '[Järgmine] dddd LT', lastDay : '[Eile,] LT', lastWeek : '[Eelmine] dddd LT', sameElse : 'L' }, relativeTime : { future : "%s pärast", past : "%s tagasi", s : processRelativeTime, m : processRelativeTime, mm : processRelativeTime, h : processRelativeTime, hh : processRelativeTime, d : processRelativeTime, dd : '%d päeva', M : processRelativeTime, MM : processRelativeTime, y : processRelativeTime, yy : processRelativeTime }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : euskara (eu) // author : Eneko Illarramendi : https://github.com/eillarra (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('eu', { months : "urtarrila_otsaila_martxoa_apirila_maiatza_ekaina_uztaila_abuztua_iraila_urria_azaroa_abendua".split("_"), monthsShort : "urt._ots._mar._api._mai._eka._uzt._abu._ira._urr._aza._abe.".split("_"), weekdays : "igandea_astelehena_asteartea_asteazkena_osteguna_ostirala_larunbata".split("_"), weekdaysShort : "ig._al._ar._az._og._ol._lr.".split("_"), weekdaysMin : "ig_al_ar_az_og_ol_lr".split("_"), longDateFormat : { LT : "HH:mm", L : "YYYY-MM-DD", LL : "YYYY[ko] MMMM[ren] D[a]", LLL : "YYYY[ko] MMMM[ren] D[a] LT", LLLL : "dddd, YYYY[ko] MMMM[ren] D[a] LT", l : "YYYY-M-D", ll : "YYYY[ko] MMM D[a]", lll : "YYYY[ko] MMM D[a] LT", llll : "ddd, YYYY[ko] MMM D[a] LT" }, calendar : { sameDay : '[gaur] LT[etan]', nextDay : '[bihar] LT[etan]', nextWeek : 'dddd LT[etan]', lastDay : '[atzo] LT[etan]', lastWeek : '[aurreko] dddd LT[etan]', sameElse : 'L' }, relativeTime : { future : "%s barru", past : "duela %s", s : "segundo batzuk", m : "minutu bat", mm : "%d minutu", h : "ordu bat", hh : "%d ordu", d : "egun bat", dd : "%d egun", M : "hilabete bat", MM : "%d hilabete", y : "urte bat", yy : "%d urte" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Persian Language // author : Ebrahim Byagowi : https://github.com/ebraminio (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var symbolMap = { '1': '۱', '2': '۲', '3': '۳', '4': '۴', '5': '۵', '6': '۶', '7': '۷', '8': '۸', '9': '۹', '0': '۰' }, numberMap = { '۱': '1', '۲': '2', '۳': '3', '۴': '4', '۵': '5', '۶': '6', '۷': '7', '۸': '8', '۹': '9', '۰': '0' }; return moment.lang('fa', { months : 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'), monthsShort : 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'), weekdays : 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'), weekdaysShort : 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'), weekdaysMin : 'ی_د_س_چ_پ_ج_ش'.split('_'), longDateFormat : { LT : 'HH:mm', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY LT', LLLL : 'dddd, D MMMM YYYY LT' }, meridiem : function (hour, minute, isLower) { if (hour < 12) { return "قبل از ظهر"; } else { return "بعد از ظهر"; } }, calendar : { sameDay : '[امروز ساعت] LT', nextDay : '[فردا ساعت] LT', nextWeek : 'dddd [ساعت] LT', lastDay : '[دیروز ساعت] LT', lastWeek : 'dddd [پیش] [ساعت] LT', sameElse : 'L' }, relativeTime : { future : 'در %s', past : '%s پیش', s : 'چندین ثانیه', m : 'یک دقیقه', mm : '%d دقیقه', h : 'یک ساعت', hh : '%d ساعت', d : 'یک روز', dd : '%d روز', M : 'یک ماه', MM : '%d ماه', y : 'یک سال', yy : '%d سال' }, preparse: function (string) { return string.replace(/[۰-۹]/g, function (match) { return numberMap[match]; }).replace(/،/g, ','); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }).replace(/,/g, '،'); }, ordinal : '%dم', week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : finnish (fi) // author : Tarmo Aidantausta : https://github.com/bleadof (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var numbers_past = 'nolla yksi kaksi kolme neljä viisi kuusi seitsemän kahdeksan yhdeksän'.split(' '), numbers_future = ['nolla', 'yhden', 'kahden', 'kolmen', 'neljän', 'viiden', 'kuuden', numbers_past[7], numbers_past[8], numbers_past[9]]; function translate(number, withoutSuffix, key, isFuture) { var result = ""; switch (key) { case 's': return isFuture ? 'muutaman sekunnin' : 'muutama sekunti'; case 'm': return isFuture ? 'minuutin' : 'minuutti'; case 'mm': result = isFuture ? 'minuutin' : 'minuuttia'; break; case 'h': return isFuture ? 'tunnin' : 'tunti'; case 'hh': result = isFuture ? 'tunnin' : 'tuntia'; break; case 'd': return isFuture ? 'päivän' : 'päivä'; case 'dd': result = isFuture ? 'päivän' : 'päivää'; break; case 'M': return isFuture ? 'kuukauden' : 'kuukausi'; case 'MM': result = isFuture ? 'kuukauden' : 'kuukautta'; break; case 'y': return isFuture ? 'vuoden' : 'vuosi'; case 'yy': result = isFuture ? 'vuoden' : 'vuotta'; break; } result = verbal_number(number, isFuture) + " " + result; return result; } function verbal_number(number, isFuture) { return number < 10 ? (isFuture ? numbers_future[number] : numbers_past[number]) : number; } return moment.lang('fi', { months : "tammikuu_helmikuu_maaliskuu_huhtikuu_toukokuu_kesäkuu_heinäkuu_elokuu_syyskuu_lokakuu_marraskuu_joulukuu".split("_"), monthsShort : "tammi_helmi_maalis_huhti_touko_kesä_heinä_elo_syys_loka_marras_joulu".split("_"), weekdays : "sunnuntai_maanantai_tiistai_keskiviikko_torstai_perjantai_lauantai".split("_"), weekdaysShort : "su_ma_ti_ke_to_pe_la".split("_"), weekdaysMin : "su_ma_ti_ke_to_pe_la".split("_"), longDateFormat : { LT : "HH.mm", L : "DD.MM.YYYY", LL : "Do MMMM[ta] YYYY", LLL : "Do MMMM[ta] YYYY, [klo] LT", LLLL : "dddd, Do MMMM[ta] YYYY, [klo] LT", l : "D.M.YYYY", ll : "Do MMM YYYY", lll : "Do MMM YYYY, [klo] LT", llll : "ddd, Do MMM YYYY, [klo] LT" }, calendar : { sameDay : '[tänään] [klo] LT', nextDay : '[huomenna] [klo] LT', nextWeek : 'dddd [klo] LT', lastDay : '[eilen] [klo] LT', lastWeek : '[viime] dddd[na] [klo] LT', sameElse : 'L' }, relativeTime : { future : "%s päästä", past : "%s sitten", s : translate, m : translate, mm : translate, h : translate, hh : translate, d : translate, dd : translate, M : translate, MM : translate, y : translate, yy : translate }, ordinal : "%d.", week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : faroese (fo) // author : Ragnar Johannesen : https://github.com/ragnar123 (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('fo', { months : "januar_februar_mars_apríl_mai_juni_juli_august_september_oktober_november_desember".split("_"), monthsShort : "jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"), weekdays : "sunnudagur_mánadagur_týsdagur_mikudagur_hósdagur_fríggjadagur_leygardagur".split("_"), weekdaysShort : "sun_mán_týs_mik_hós_frí_ley".split("_"), weekdaysMin : "su_má_tý_mi_hó_fr_le".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D. MMMM, YYYY LT" }, calendar : { sameDay : '[Í dag kl.] LT', nextDay : '[Í morgin kl.] LT', nextWeek : 'dddd [kl.] LT', lastDay : '[Í gjár kl.] LT', lastWeek : '[síðstu] dddd [kl] LT', sameElse : 'L' }, relativeTime : { future : "um %s", past : "%s síðani", s : "fá sekund", m : "ein minutt", mm : "%d minuttir", h : "ein tími", hh : "%d tímar", d : "ein dagur", dd : "%d dagar", M : "ein mánaði", MM : "%d mánaðir", y : "eitt ár", yy : "%d ár" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : canadian french (fr-ca) // author : Jonathan Abourbih : https://github.com/jonbca (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('fr-ca', { months : "janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"), monthsShort : "janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"), weekdays : "dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"), weekdaysShort : "dim._lun._mar._mer._jeu._ven._sam.".split("_"), weekdaysMin : "Di_Lu_Ma_Me_Je_Ve_Sa".split("_"), longDateFormat : { LT : "HH:mm", L : "YYYY-MM-DD", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[Aujourd'hui à] LT", nextDay: '[Demain à] LT', nextWeek: 'dddd [à] LT', lastDay: '[Hier à] LT', lastWeek: 'dddd [dernier à] LT', sameElse: 'L' }, relativeTime : { future : "dans %s", past : "il y a %s", s : "quelques secondes", m : "une minute", mm : "%d minutes", h : "une heure", hh : "%d heures", d : "un jour", dd : "%d jours", M : "un mois", MM : "%d mois", y : "un an", yy : "%d ans" }, ordinal : function (number) { return number + (number === 1 ? 'er' : ''); } }); })); // moment.js language configuration // language : french (fr) // author : John Fischer : https://github.com/jfroffice (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('fr', { months : "janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"), monthsShort : "janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"), weekdays : "dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"), weekdaysShort : "dim._lun._mar._mer._jeu._ven._sam.".split("_"), weekdaysMin : "Di_Lu_Ma_Me_Je_Ve_Sa".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[Aujourd'hui à] LT", nextDay: '[Demain à] LT', nextWeek: 'dddd [à] LT', lastDay: '[Hier à] LT', lastWeek: 'dddd [dernier à] LT', sameElse: 'L' }, relativeTime : { future : "dans %s", past : "il y a %s", s : "quelques secondes", m : "une minute", mm : "%d minutes", h : "une heure", hh : "%d heures", d : "un jour", dd : "%d jours", M : "un mois", MM : "%d mois", y : "un an", yy : "%d ans" }, ordinal : function (number) { return number + (number === 1 ? 'er' : ''); }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : galician (gl) // author : Juan G. Hurtado : https://github.com/juanghurtado (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('gl', { months : "Xaneiro_Febreiro_Marzo_Abril_Maio_Xuño_Xullo_Agosto_Setembro_Outubro_Novembro_Decembro".split("_"), monthsShort : "Xan._Feb._Mar._Abr._Mai._Xuñ._Xul._Ago._Set._Out._Nov._Dec.".split("_"), weekdays : "Domingo_Luns_Martes_Mércores_Xoves_Venres_Sábado".split("_"), weekdaysShort : "Dom._Lun._Mar._Mér._Xov._Ven._Sáb.".split("_"), weekdaysMin : "Do_Lu_Ma_Mé_Xo_Ve_Sá".split("_"), longDateFormat : { LT : "H:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay : function () { return '[hoxe ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT'; }, nextDay : function () { return '[mañá ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT'; }, nextWeek : function () { return 'dddd [' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT'; }, lastDay : function () { return '[onte ' + ((this.hours() !== 1) ? 'á' : 'a') + '] LT'; }, lastWeek : function () { return '[o] dddd [pasado ' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT'; }, sameElse : 'L' }, relativeTime : { future : function (str) { if (str === "uns segundos") { return "nuns segundos"; } return "en " + str; }, past : "hai %s", s : "uns segundos", m : "un minuto", mm : "%d minutos", h : "unha hora", hh : "%d horas", d : "un día", dd : "%d días", M : "un mes", MM : "%d meses", y : "un ano", yy : "%d anos" }, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Hebrew (he) // author : Tomer Cohen : https://github.com/tomer // author : Moshe Simantov : https://github.com/DevelopmentIL // author : Tal Ater : https://github.com/TalAter (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('he', { months : "ינואר_פברואר_מרץ_אפריל_מאי_יוני_יולי_אוגוסט_ספטמבר_אוקטובר_נובמבר_דצמבר".split("_"), monthsShort : "ינו׳_פבר׳_מרץ_אפר׳_מאי_יוני_יולי_אוג׳_ספט׳_אוק׳_נוב׳_דצמ׳".split("_"), weekdays : "ראשון_שני_שלישי_רביעי_חמישי_שישי_שבת".split("_"), weekdaysShort : "א׳_ב׳_ג׳_ד׳_ה׳_ו׳_ש׳".split("_"), weekdaysMin : "א_ב_ג_ד_ה_ו_ש".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D [ב]MMMM YYYY", LLL : "D [ב]MMMM YYYY LT", LLLL : "dddd, D [ב]MMMM YYYY LT", l : "D/M/YYYY", ll : "D MMM YYYY", lll : "D MMM YYYY LT", llll : "ddd, D MMM YYYY LT" }, calendar : { sameDay : '[היום ב־]LT', nextDay : '[מחר ב־]LT', nextWeek : 'dddd [בשעה] LT', lastDay : '[אתמול ב־]LT', lastWeek : '[ביום] dddd [האחרון בשעה] LT', sameElse : 'L' }, relativeTime : { future : "בעוד %s", past : "לפני %s", s : "מספר שניות", m : "דקה", mm : "%d דקות", h : "שעה", hh : function (number) { if (number === 2) { return "שעתיים"; } return number + " שעות"; }, d : "יום", dd : function (number) { if (number === 2) { return "יומיים"; } return number + " ימים"; }, M : "חודש", MM : function (number) { if (number === 2) { return "חודשיים"; } return number + " חודשים"; }, y : "שנה", yy : function (number) { if (number === 2) { return "שנתיים"; } return number + " שנים"; } } }); })); // moment.js language configuration // language : hindi (hi) // author : Mayank Singhal : https://github.com/mayanksinghal (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var symbolMap = { '1': '१', '2': '२', '3': '३', '4': '४', '5': '५', '6': '६', '7': '७', '8': '८', '9': '९', '0': '०' }, numberMap = { '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9', '०': '0' }; return moment.lang('hi', { months : 'जनवरी_फ़रवरी_मार्च_अप्रैल_मई_जून_जुलाई_अगस्त_सितम्बर_अक्टूबर_नवम्बर_दिसम्बर'.split("_"), monthsShort : 'जन._फ़र._मार्च_अप्रै._मई_जून_जुल._अग._सित._अक्टू._नव._दिस.'.split("_"), weekdays : 'रविवार_सोमवार_मंगलवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split("_"), weekdaysShort : 'रवि_सोम_मंगल_बुध_गुरू_शुक्र_शनि'.split("_"), weekdaysMin : 'र_सो_मं_बु_गु_शु_श'.split("_"), longDateFormat : { LT : "A h:mm बजे", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY, LT", LLLL : "dddd, D MMMM YYYY, LT" }, calendar : { sameDay : '[आज] LT', nextDay : '[कल] LT', nextWeek : 'dddd, LT', lastDay : '[कल] LT', lastWeek : '[पिछले] dddd, LT', sameElse : 'L' }, relativeTime : { future : "%s में", past : "%s पहले", s : "कुछ ही क्षण", m : "एक मिनट", mm : "%d मिनट", h : "एक घंटा", hh : "%d घंटे", d : "एक दिन", dd : "%d दिन", M : "एक महीने", MM : "%d महीने", y : "एक वर्ष", yy : "%d वर्ष" }, preparse: function (string) { return string.replace(/[१२३४५६७८९०]/g, function (match) { return numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }); }, // Hindi notation for meridiems are quite fuzzy in practice. While there exists // a rigid notion of a 'Pahar' it is not used as rigidly in modern Hindi. meridiem : function (hour, minute, isLower) { if (hour < 4) { return "रात"; } else if (hour < 10) { return "सुबह"; } else if (hour < 17) { return "दोपहर"; } else if (hour < 20) { return "शाम"; } else { return "रात"; } }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : hrvatski (hr) // author : Bojan Marković : https://github.com/bmarkovic // based on (sl) translation by Robert Sedovšek (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function translate(number, withoutSuffix, key) { var result = number + " "; switch (key) { case 'm': return withoutSuffix ? 'jedna minuta' : 'jedne minute'; case 'mm': if (number === 1) { result += 'minuta'; } else if (number === 2 || number === 3 || number === 4) { result += 'minute'; } else { result += 'minuta'; } return result; case 'h': return withoutSuffix ? 'jedan sat' : 'jednog sata'; case 'hh': if (number === 1) { result += 'sat'; } else if (number === 2 || number === 3 || number === 4) { result += 'sata'; } else { result += 'sati'; } return result; case 'dd': if (number === 1) { result += 'dan'; } else { result += 'dana'; } return result; case 'MM': if (number === 1) { result += 'mjesec'; } else if (number === 2 || number === 3 || number === 4) { result += 'mjeseca'; } else { result += 'mjeseci'; } return result; case 'yy': if (number === 1) { result += 'godina'; } else if (number === 2 || number === 3 || number === 4) { result += 'godine'; } else { result += 'godina'; } return result; } } return moment.lang('hr', { months : "sječanj_veljača_ožujak_travanj_svibanj_lipanj_srpanj_kolovoz_rujan_listopad_studeni_prosinac".split("_"), monthsShort : "sje._vel._ožu._tra._svi._lip._srp._kol._ruj._lis._stu._pro.".split("_"), weekdays : "nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota".split("_"), weekdaysShort : "ned._pon._uto._sri._čet._pet._sub.".split("_"), weekdaysMin : "ne_po_ut_sr_če_pe_su".split("_"), longDateFormat : { LT : "H:mm", L : "DD. MM. YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay : '[danas u] LT', nextDay : '[sutra u] LT', nextWeek : function () { switch (this.day()) { case 0: return '[u] [nedjelju] [u] LT'; case 3: return '[u] [srijedu] [u] LT'; case 6: return '[u] [subotu] [u] LT'; case 1: case 2: case 4: case 5: return '[u] dddd [u] LT'; } }, lastDay : '[jučer u] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: return '[prošlu] dddd [u] LT'; case 6: return '[prošle] [subote] [u] LT'; case 1: case 2: case 4: case 5: return '[prošli] dddd [u] LT'; } }, sameElse : 'L' }, relativeTime : { future : "za %s", past : "prije %s", s : "par sekundi", m : translate, mm : translate, h : translate, hh : translate, d : "dan", dd : translate, M : "mjesec", MM : translate, y : "godinu", yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : hungarian (hu) // author : Adam Brunner : https://github.com/adambrunner (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var weekEndings = 'vasárnap hétfőn kedden szerdán csütörtökön pénteken szombaton'.split(' '); function translate(number, withoutSuffix, key, isFuture) { var num = number, suffix; switch (key) { case 's': return (isFuture || withoutSuffix) ? 'néhány másodperc' : 'néhány másodperce'; case 'm': return 'egy' + (isFuture || withoutSuffix ? ' perc' : ' perce'); case 'mm': return num + (isFuture || withoutSuffix ? ' perc' : ' perce'); case 'h': return 'egy' + (isFuture || withoutSuffix ? ' óra' : ' órája'); case 'hh': return num + (isFuture || withoutSuffix ? ' óra' : ' órája'); case 'd': return 'egy' + (isFuture || withoutSuffix ? ' nap' : ' napja'); case 'dd': return num + (isFuture || withoutSuffix ? ' nap' : ' napja'); case 'M': return 'egy' + (isFuture || withoutSuffix ? ' hónap' : ' hónapja'); case 'MM': return num + (isFuture || withoutSuffix ? ' hónap' : ' hónapja'); case 'y': return 'egy' + (isFuture || withoutSuffix ? ' év' : ' éve'); case 'yy': return num + (isFuture || withoutSuffix ? ' év' : ' éve'); } return ''; } function week(isFuture) { return (isFuture ? '' : '[múlt] ') + '[' + weekEndings[this.day()] + '] LT[-kor]'; } return moment.lang('hu', { months : "január_február_március_április_május_június_július_augusztus_szeptember_október_november_december".split("_"), monthsShort : "jan_feb_márc_ápr_máj_jún_júl_aug_szept_okt_nov_dec".split("_"), weekdays : "vasárnap_hétfő_kedd_szerda_csütörtök_péntek_szombat".split("_"), weekdaysShort : "vas_hét_kedd_sze_csüt_pén_szo".split("_"), weekdaysMin : "v_h_k_sze_cs_p_szo".split("_"), longDateFormat : { LT : "H:mm", L : "YYYY.MM.DD.", LL : "YYYY. MMMM D.", LLL : "YYYY. MMMM D., LT", LLLL : "YYYY. MMMM D., dddd LT" }, calendar : { sameDay : '[ma] LT[-kor]', nextDay : '[holnap] LT[-kor]', nextWeek : function () { return week.call(this, true); }, lastDay : '[tegnap] LT[-kor]', lastWeek : function () { return week.call(this, false); }, sameElse : 'L' }, relativeTime : { future : "%s múlva", past : "%s", s : translate, m : translate, mm : translate, h : translate, hh : translate, d : translate, dd : translate, M : translate, MM : translate, y : translate, yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Armenian (hy-am) // author : Armendarabyan : https://github.com/armendarabyan (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function monthsCaseReplace(m, format) { var months = { 'nominative': 'հունվար_փետրվար_մարտ_ապրիլ_մայիս_հունիս_հուլիս_օգոստոս_սեպտեմբեր_հոկտեմբեր_նոյեմբեր_դեկտեմբեր'.split('_'), 'accusative': 'հունվարի_փետրվարի_մարտի_ապրիլի_մայիսի_հունիսի_հուլիսի_օգոստոսի_սեպտեմբերի_հոկտեմբերի_նոյեմբերի_դեկտեմբերի'.split('_') }, nounCase = (/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/).test(format) ? 'accusative' : 'nominative'; return months[nounCase][m.month()]; } function monthsShortCaseReplace(m, format) { var monthsShort = 'հնվ_փտր_մրտ_ապր_մյս_հնս_հլս_օգս_սպտ_հկտ_նմբ_դկտ'.split('_'); return monthsShort[m.month()]; } function weekdaysCaseReplace(m, format) { var weekdays = 'կիրակի_երկուշաբթի_երեքշաբթի_չորեքշաբթի_հինգշաբթի_ուրբաթ_շաբաթ'.split('_'); return weekdays[m.day()]; } return moment.lang('hy-am', { months : monthsCaseReplace, monthsShort : monthsShortCaseReplace, weekdays : weekdaysCaseReplace, weekdaysShort : "կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ".split("_"), weekdaysMin : "կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY թ.", LLL : "D MMMM YYYY թ., LT", LLLL : "dddd, D MMMM YYYY թ., LT" }, calendar : { sameDay: '[այսօր] LT', nextDay: '[վաղը] LT', lastDay: '[երեկ] LT', nextWeek: function () { return 'dddd [օրը ժամը] LT'; }, lastWeek: function () { return '[անցած] dddd [օրը ժամը] LT'; }, sameElse: 'L' }, relativeTime : { future : "%s հետո", past : "%s առաջ", s : "մի քանի վայրկյան", m : "րոպե", mm : "%d րոպե", h : "ժամ", hh : "%d ժամ", d : "օր", dd : "%d օր", M : "ամիս", MM : "%d ամիս", y : "տարի", yy : "%d տարի" }, meridiem : function (hour) { if (hour < 4) { return "գիշերվա"; } else if (hour < 12) { return "առավոտվա"; } else if (hour < 17) { return "ցերեկվա"; } else { return "երեկոյան"; } }, ordinal: function (number, period) { switch (period) { case 'DDD': case 'w': case 'W': case 'DDDo': if (number === 1) { return number + '-ին'; } return number + '-րդ'; default: return number; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Bahasa Indonesia (id) // author : Mohammad Satrio Utomo : https://github.com/tyok // reference: http://id.wikisource.org/wiki/Pedoman_Umum_Ejaan_Bahasa_Indonesia_yang_Disempurnakan (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('id', { months : "Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_November_Desember".split("_"), monthsShort : "Jan_Feb_Mar_Apr_Mei_Jun_Jul_Ags_Sep_Okt_Nov_Des".split("_"), weekdays : "Minggu_Senin_Selasa_Rabu_Kamis_Jumat_Sabtu".split("_"), weekdaysShort : "Min_Sen_Sel_Rab_Kam_Jum_Sab".split("_"), weekdaysMin : "Mg_Sn_Sl_Rb_Km_Jm_Sb".split("_"), longDateFormat : { LT : "HH.mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY [pukul] LT", LLLL : "dddd, D MMMM YYYY [pukul] LT" }, meridiem : function (hours, minutes, isLower) { if (hours < 11) { return 'pagi'; } else if (hours < 15) { return 'siang'; } else if (hours < 19) { return 'sore'; } else { return 'malam'; } }, calendar : { sameDay : '[Hari ini pukul] LT', nextDay : '[Besok pukul] LT', nextWeek : 'dddd [pukul] LT', lastDay : '[Kemarin pukul] LT', lastWeek : 'dddd [lalu pukul] LT', sameElse : 'L' }, relativeTime : { future : "dalam %s", past : "%s yang lalu", s : "beberapa detik", m : "semenit", mm : "%d menit", h : "sejam", hh : "%d jam", d : "sehari", dd : "%d hari", M : "sebulan", MM : "%d bulan", y : "setahun", yy : "%d tahun" }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : icelandic (is) // author : Hinrik Örn Sigurðsson : https://github.com/hinrik (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function plural(n) { if (n % 100 === 11) { return true; } else if (n % 10 === 1) { return false; } return true; } function translate(number, withoutSuffix, key, isFuture) { var result = number + " "; switch (key) { case 's': return withoutSuffix || isFuture ? 'nokkrar sekúndur' : 'nokkrum sekúndum'; case 'm': return withoutSuffix ? 'mínúta' : 'mínútu'; case 'mm': if (plural(number)) { return result + (withoutSuffix || isFuture ? 'mínútur' : 'mínútum'); } else if (withoutSuffix) { return result + 'mínúta'; } return result + 'mínútu'; case 'hh': if (plural(number)) { return result + (withoutSuffix || isFuture ? 'klukkustundir' : 'klukkustundum'); } return result + 'klukkustund'; case 'd': if (withoutSuffix) { return 'dagur'; } return isFuture ? 'dag' : 'degi'; case 'dd': if (plural(number)) { if (withoutSuffix) { return result + 'dagar'; } return result + (isFuture ? 'daga' : 'dögum'); } else if (withoutSuffix) { return result + 'dagur'; } return result + (isFuture ? 'dag' : 'degi'); case 'M': if (withoutSuffix) { return 'mánuður'; } return isFuture ? 'mánuð' : 'mánuði'; case 'MM': if (plural(number)) { if (withoutSuffix) { return result + 'mánuðir'; } return result + (isFuture ? 'mánuði' : 'mánuðum'); } else if (withoutSuffix) { return result + 'mánuður'; } return result + (isFuture ? 'mánuð' : 'mánuði'); case 'y': return withoutSuffix || isFuture ? 'ár' : 'ári'; case 'yy': if (plural(number)) { return result + (withoutSuffix || isFuture ? 'ár' : 'árum'); } return result + (withoutSuffix || isFuture ? 'ár' : 'ári'); } } return moment.lang('is', { months : "janúar_febrúar_mars_apríl_maí_júní_júlí_ágúst_september_október_nóvember_desember".split("_"), monthsShort : "jan_feb_mar_apr_maí_jún_júl_ágú_sep_okt_nóv_des".split("_"), weekdays : "sunnudagur_mánudagur_þriðjudagur_miðvikudagur_fimmtudagur_föstudagur_laugardagur".split("_"), weekdaysShort : "sun_mán_þri_mið_fim_fös_lau".split("_"), weekdaysMin : "Su_Má_Þr_Mi_Fi_Fö_La".split("_"), longDateFormat : { LT : "H:mm", L : "DD/MM/YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY [kl.] LT", LLLL : "dddd, D. MMMM YYYY [kl.] LT" }, calendar : { sameDay : '[í dag kl.] LT', nextDay : '[á morgun kl.] LT', nextWeek : 'dddd [kl.] LT', lastDay : '[í gær kl.] LT', lastWeek : '[síðasta] dddd [kl.] LT', sameElse : 'L' }, relativeTime : { future : "eftir %s", past : "fyrir %s síðan", s : translate, m : translate, mm : translate, h : "klukkustund", hh : translate, d : translate, dd : translate, M : translate, MM : translate, y : translate, yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : italian (it) // author : Lorenzo : https://github.com/aliem // author: Mattia Larentis: https://github.com/nostalgiaz (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('it', { months : "Gennaio_Febbraio_Marzo_Aprile_Maggio_Giugno_Luglio_Agosto_Settembre_Ottobre_Novembre_Dicembre".split("_"), monthsShort : "Gen_Feb_Mar_Apr_Mag_Giu_Lug_Ago_Set_Ott_Nov_Dic".split("_"), weekdays : "Domenica_Lunedì_Martedì_Mercoledì_Giovedì_Venerdì_Sabato".split("_"), weekdaysShort : "Dom_Lun_Mar_Mer_Gio_Ven_Sab".split("_"), weekdaysMin : "D_L_Ma_Me_G_V_S".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay: '[Oggi alle] LT', nextDay: '[Domani alle] LT', nextWeek: 'dddd [alle] LT', lastDay: '[Ieri alle] LT', lastWeek: '[lo scorso] dddd [alle] LT', sameElse: 'L' }, relativeTime : { future : function (s) { return ((/^[0-9].+$/).test(s) ? "tra" : "in") + " " + s; }, past : "%s fa", s : "alcuni secondi", m : "un minuto", mm : "%d minuti", h : "un'ora", hh : "%d ore", d : "un giorno", dd : "%d giorni", M : "un mese", MM : "%d mesi", y : "un anno", yy : "%d anni" }, ordinal: '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : japanese (ja) // author : LI Long : https://github.com/baryon (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('ja', { months : "1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"), monthsShort : "1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"), weekdays : "日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日".split("_"), weekdaysShort : "日_月_火_水_木_金_土".split("_"), weekdaysMin : "日_月_火_水_木_金_土".split("_"), longDateFormat : { LT : "Ah時m分", L : "YYYY/MM/DD", LL : "YYYY年M月D日", LLL : "YYYY年M月D日LT", LLLL : "YYYY年M月D日LT dddd" }, meridiem : function (hour, minute, isLower) { if (hour < 12) { return "午前"; } else { return "午後"; } }, calendar : { sameDay : '[今日] LT', nextDay : '[明日] LT', nextWeek : '[来週]dddd LT', lastDay : '[昨日] LT', lastWeek : '[前週]dddd LT', sameElse : 'L' }, relativeTime : { future : "%s後", past : "%s前", s : "数秒", m : "1分", mm : "%d分", h : "1時間", hh : "%d時間", d : "1日", dd : "%d日", M : "1ヶ月", MM : "%dヶ月", y : "1年", yy : "%d年" } }); })); // moment.js language configuration // language : Georgian (ka) // author : Irakli Janiashvili : https://github.com/irakli-janiashvili (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function monthsCaseReplace(m, format) { var months = { 'nominative': 'იანვარი_თებერვალი_მარტი_აპრილი_მაისი_ივნისი_ივლისი_აგვისტო_სექტემბერი_ოქტომბერი_ნოემბერი_დეკემბერი'.split('_'), 'accusative': 'იანვარს_თებერვალს_მარტს_აპრილის_მაისს_ივნისს_ივლისს_აგვისტს_სექტემბერს_ოქტომბერს_ნოემბერს_დეკემბერს'.split('_') }, nounCase = (/D[oD] *MMMM?/).test(format) ? 'accusative' : 'nominative'; return months[nounCase][m.month()]; } function weekdaysCaseReplace(m, format) { var weekdays = { 'nominative': 'კვირა_ორშაბათი_სამშაბათი_ოთხშაბათი_ხუთშაბათი_პარასკევი_შაბათი'.split('_'), 'accusative': 'კვირას_ორშაბათს_სამშაბათს_ოთხშაბათს_ხუთშაბათს_პარასკევს_შაბათს'.split('_') }, nounCase = (/(წინა|შემდეგ)/).test(format) ? 'accusative' : 'nominative'; return weekdays[nounCase][m.day()]; } return moment.lang('ka', { months : monthsCaseReplace, monthsShort : "იან_თებ_მარ_აპრ_მაი_ივნ_ივლ_აგვ_სექ_ოქტ_ნოე_დეკ".split("_"), weekdays : weekdaysCaseReplace, weekdaysShort : "კვი_ორშ_სამ_ოთხ_ხუთ_პარ_შაბ".split("_"), weekdaysMin : "კვ_ორ_სა_ოთ_ხუ_პა_შა".split("_"), longDateFormat : { LT : "h:mm A", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[დღეს] LT[-ზე]', nextDay : '[ხვალ] LT[-ზე]', lastDay : '[გუშინ] LT[-ზე]', nextWeek : '[შემდეგ] dddd LT[-ზე]', lastWeek : '[წინა] dddd LT-ზე', sameElse : 'L' }, relativeTime : { future : function (s) { return (/(წამი|წუთი|საათი|წელი)/).test(s) ? s.replace(/ი$/, "ში") : s + "ში"; }, past : function (s) { if ((/(წამი|წუთი|საათი|დღე|თვე)/).test(s)) { return s.replace(/(ი|ე)$/, "ის წინ"); } if ((/წელი/).test(s)) { return s.replace(/წელი$/, "წლის წინ"); } }, s : "რამდენიმე წამი", m : "წუთი", mm : "%d წუთი", h : "საათი", hh : "%d საათი", d : "დღე", dd : "%d დღე", M : "თვე", MM : "%d თვე", y : "წელი", yy : "%d წელი" }, ordinal : function (number) { if (number === 0) { return number; } if (number === 1) { return number + "-ლი"; } if ((number < 20) || (number <= 100 && (number % 20 === 0)) || (number % 100 === 0)) { return "მე-" + number; } return number + "-ე"; }, week : { dow : 1, doy : 7 } }); })); // moment.js language configuration // language : korean (ko) // // authors // // - Kyungwook, Park : https://github.com/kyungw00k // - Jeeeyul Lee <jeeeyul@gmail.com> (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('ko', { months : "1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"), monthsShort : "1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"), weekdays : "일요일_월요일_화요일_수요일_목요일_금요일_토요일".split("_"), weekdaysShort : "일_월_화_수_목_금_토".split("_"), weekdaysMin : "일_월_화_수_목_금_토".split("_"), longDateFormat : { LT : "A h시 mm분", L : "YYYY.MM.DD", LL : "YYYY년 MMMM D일", LLL : "YYYY년 MMMM D일 LT", LLLL : "YYYY년 MMMM D일 dddd LT" }, meridiem : function (hour, minute, isUpper) { return hour < 12 ? '오전' : '오후'; }, calendar : { sameDay : '오늘 LT', nextDay : '내일 LT', nextWeek : 'dddd LT', lastDay : '어제 LT', lastWeek : '지난주 dddd LT', sameElse : 'L' }, relativeTime : { future : "%s 후", past : "%s 전", s : "몇초", ss : "%d초", m : "일분", mm : "%d분", h : "한시간", hh : "%d시간", d : "하루", dd : "%d일", M : "한달", MM : "%d달", y : "일년", yy : "%d년" }, ordinal : '%d일', meridiemParse : /(오전|오후)/, isPM : function (token) { return token === "오후"; } }); })); // moment.js language configuration // language : Luxembourgish (lb) // author : mweimerskirch : https://github.com/mweimerskirch // Note: Luxembourgish has a very particular phonological rule ("Eifeler Regel") that causes the // deletion of the final "n" in certain contexts. That's what the "eifelerRegelAppliesToWeekday" // and "eifelerRegelAppliesToNumber" methods are meant for (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function processRelativeTime(number, withoutSuffix, key, isFuture) { var format = { 'm': ['eng Minutt', 'enger Minutt'], 'h': ['eng Stonn', 'enger Stonn'], 'd': ['een Dag', 'engem Dag'], 'dd': [number + ' Deeg', number + ' Deeg'], 'M': ['ee Mount', 'engem Mount'], 'MM': [number + ' Méint', number + ' Méint'], 'y': ['ee Joer', 'engem Joer'], 'yy': [number + ' Joer', number + ' Joer'] }; return withoutSuffix ? format[key][0] : format[key][1]; } function processFutureTime(string) { var number = string.substr(0, string.indexOf(' ')); if (eifelerRegelAppliesToNumber(number)) { return "a " + string; } return "an " + string; } function processPastTime(string) { var number = string.substr(0, string.indexOf(' ')); if (eifelerRegelAppliesToNumber(number)) { return "viru " + string; } return "virun " + string; } function processLastWeek(string1) { var weekday = this.format('d'); if (eifelerRegelAppliesToWeekday(weekday)) { return '[Leschte] dddd [um] LT'; } return '[Leschten] dddd [um] LT'; } /** * Returns true if the word before the given week day loses the "-n" ending. * e.g. "Leschten Dënschdeg" but "Leschte Méindeg" * * @param weekday {integer} * @returns {boolean} */ function eifelerRegelAppliesToWeekday(weekday) { weekday = parseInt(weekday, 10); switch (weekday) { case 0: // Sonndeg case 1: // Méindeg case 3: // Mëttwoch case 5: // Freideg case 6: // Samschdeg return true; default: // 2 Dënschdeg, 4 Donneschdeg return false; } } /** * Returns true if the word before the given number loses the "-n" ending. * e.g. "an 10 Deeg" but "a 5 Deeg" * * @param number {integer} * @returns {boolean} */ function eifelerRegelAppliesToNumber(number) { number = parseInt(number, 10); if (isNaN(number)) { return false; } if (number < 0) { // Negative Number --> always true return true; } else if (number < 10) { // Only 1 digit if (4 <= number && number <= 7) { return true; } return false; } else if (number < 100) { // 2 digits var lastDigit = number % 10, firstDigit = number / 10; if (lastDigit === 0) { return eifelerRegelAppliesToNumber(firstDigit); } return eifelerRegelAppliesToNumber(lastDigit); } else if (number < 10000) { // 3 or 4 digits --> recursively check first digit while (number >= 10) { number = number / 10; } return eifelerRegelAppliesToNumber(number); } else { // Anything larger than 4 digits: recursively check first n-3 digits number = number / 1000; return eifelerRegelAppliesToNumber(number); } } return moment.lang('lb', { months: "Januar_Februar_Mäerz_Abrëll_Mee_Juni_Juli_August_September_Oktober_November_Dezember".split("_"), monthsShort: "Jan._Febr._Mrz._Abr._Mee_Jun._Jul._Aug._Sept._Okt._Nov._Dez.".split("_"), weekdays: "Sonndeg_Méindeg_Dënschdeg_Mëttwoch_Donneschdeg_Freideg_Samschdeg".split("_"), weekdaysShort: "So._Mé._Dë._Më._Do._Fr._Sa.".split("_"), weekdaysMin: "So_Mé_Dë_Më_Do_Fr_Sa".split("_"), longDateFormat: { LT: "H:mm [Auer]", L: "DD.MM.YYYY", LL: "D. MMMM YYYY", LLL: "D. MMMM YYYY LT", LLLL: "dddd, D. MMMM YYYY LT" }, calendar: { sameDay: "[Haut um] LT", sameElse: "L", nextDay: '[Muer um] LT', nextWeek: 'dddd [um] LT', lastDay: '[Gëschter um] LT', lastWeek: processLastWeek }, relativeTime: { future: processFutureTime, past: processPastTime, s: "e puer Sekonnen", m: processRelativeTime, mm: "%d Minutten", h: processRelativeTime, hh: "%d Stonnen", d: processRelativeTime, dd: processRelativeTime, M: processRelativeTime, MM: processRelativeTime, y: processRelativeTime, yy: processRelativeTime }, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : Lithuanian (lt) // author : Mindaugas Mozūras : https://github.com/mmozuras (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var units = { "m" : "minutė_minutės_minutę", "mm": "minutės_minučių_minutes", "h" : "valanda_valandos_valandą", "hh": "valandos_valandų_valandas", "d" : "diena_dienos_dieną", "dd": "dienos_dienų_dienas", "M" : "mėnuo_mėnesio_mėnesį", "MM": "mėnesiai_mėnesių_mėnesius", "y" : "metai_metų_metus", "yy": "metai_metų_metus" }, weekDays = "pirmadienis_antradienis_trečiadienis_ketvirtadienis_penktadienis_šeštadienis_sekmadienis".split("_"); function translateSeconds(number, withoutSuffix, key, isFuture) { if (withoutSuffix) { return "kelios sekundės"; } else { return isFuture ? "kelių sekundžių" : "kelias sekundes"; } } function translateSingular(number, withoutSuffix, key, isFuture) { return withoutSuffix ? forms(key)[0] : (isFuture ? forms(key)[1] : forms(key)[2]); } function special(number) { return number % 10 === 0 || (number > 10 && number < 20); } function forms(key) { return units[key].split("_"); } function translate(number, withoutSuffix, key, isFuture) { var result = number + " "; if (number === 1) { return result + translateSingular(number, withoutSuffix, key[0], isFuture); } else if (withoutSuffix) { return result + (special(number) ? forms(key)[1] : forms(key)[0]); } else { if (isFuture) { return result + forms(key)[1]; } else { return result + (special(number) ? forms(key)[1] : forms(key)[2]); } } } function relativeWeekDay(moment, format) { var nominative = format.indexOf('dddd LT') === -1, weekDay = weekDays[moment.weekday()]; return nominative ? weekDay : weekDay.substring(0, weekDay.length - 2) + "į"; } return moment.lang("lt", { months : "sausio_vasario_kovo_balandžio_gegužės_biržėlio_liepos_rugpjūčio_rugsėjo_spalio_lapkričio_gruodžio".split("_"), monthsShort : "sau_vas_kov_bal_geg_bir_lie_rgp_rgs_spa_lap_grd".split("_"), weekdays : relativeWeekDay, weekdaysShort : "Sek_Pir_Ant_Tre_Ket_Pen_Šeš".split("_"), weekdaysMin : "S_P_A_T_K_Pn_Š".split("_"), longDateFormat : { LT : "HH:mm", L : "YYYY-MM-DD", LL : "YYYY [m.] MMMM D [d.]", LLL : "YYYY [m.] MMMM D [d.], LT [val.]", LLLL : "YYYY [m.] MMMM D [d.], dddd, LT [val.]", l : "YYYY-MM-DD", ll : "YYYY [m.] MMMM D [d.]", lll : "YYYY [m.] MMMM D [d.], LT [val.]", llll : "YYYY [m.] MMMM D [d.], ddd, LT [val.]" }, calendar : { sameDay : "[Šiandien] LT", nextDay : "[Rytoj] LT", nextWeek : "dddd LT", lastDay : "[Vakar] LT", lastWeek : "[Praėjusį] dddd LT", sameElse : "L" }, relativeTime : { future : "po %s", past : "prieš %s", s : translateSeconds, m : translateSingular, mm : translate, h : translateSingular, hh : translate, d : translateSingular, dd : translate, M : translateSingular, MM : translate, y : translateSingular, yy : translate }, ordinal : function (number) { return number + '-oji'; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : latvian (lv) // author : Kristaps Karlsons : https://github.com/skakri (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var units = { 'mm': 'minūti_minūtes_minūte_minūtes', 'hh': 'stundu_stundas_stunda_stundas', 'dd': 'dienu_dienas_diena_dienas', 'MM': 'mēnesi_mēnešus_mēnesis_mēneši', 'yy': 'gadu_gadus_gads_gadi' }; function format(word, number, withoutSuffix) { var forms = word.split('_'); if (withoutSuffix) { return number % 10 === 1 && number !== 11 ? forms[2] : forms[3]; } else { return number % 10 === 1 && number !== 11 ? forms[0] : forms[1]; } } function relativeTimeWithPlural(number, withoutSuffix, key) { return number + ' ' + format(units[key], number, withoutSuffix); } return moment.lang('lv', { months : "janvāris_februāris_marts_aprīlis_maijs_jūnijs_jūlijs_augusts_septembris_oktobris_novembris_decembris".split("_"), monthsShort : "jan_feb_mar_apr_mai_jūn_jūl_aug_sep_okt_nov_dec".split("_"), weekdays : "svētdiena_pirmdiena_otrdiena_trešdiena_ceturtdiena_piektdiena_sestdiena".split("_"), weekdaysShort : "Sv_P_O_T_C_Pk_S".split("_"), weekdaysMin : "Sv_P_O_T_C_Pk_S".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "YYYY. [gada] D. MMMM", LLL : "YYYY. [gada] D. MMMM, LT", LLLL : "YYYY. [gada] D. MMMM, dddd, LT" }, calendar : { sameDay : '[Šodien pulksten] LT', nextDay : '[Rīt pulksten] LT', nextWeek : 'dddd [pulksten] LT', lastDay : '[Vakar pulksten] LT', lastWeek : '[Pagājušā] dddd [pulksten] LT', sameElse : 'L' }, relativeTime : { future : "%s vēlāk", past : "%s agrāk", s : "dažas sekundes", m : "minūti", mm : relativeTimeWithPlural, h : "stundu", hh : relativeTimeWithPlural, d : "dienu", dd : relativeTimeWithPlural, M : "mēnesi", MM : relativeTimeWithPlural, y : "gadu", yy : relativeTimeWithPlural }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : macedonian (mk) // author : Borislav Mickov : https://github.com/B0k0 (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('mk', { months : "јануари_февруари_март_април_мај_јуни_јули_август_септември_октомври_ноември_декември".split("_"), monthsShort : "јан_фев_мар_апр_мај_јун_јул_авг_сеп_окт_ное_дек".split("_"), weekdays : "недела_понеделник_вторник_среда_четврток_петок_сабота".split("_"), weekdaysShort : "нед_пон_вто_сре_чет_пет_саб".split("_"), weekdaysMin : "нe_пo_вт_ср_че_пе_сa".split("_"), longDateFormat : { LT : "H:mm", L : "D.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[Денес во] LT', nextDay : '[Утре во] LT', nextWeek : 'dddd [во] LT', lastDay : '[Вчера во] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: case 6: return '[Во изминатата] dddd [во] LT'; case 1: case 2: case 4: case 5: return '[Во изминатиот] dddd [во] LT'; } }, sameElse : 'L' }, relativeTime : { future : "после %s", past : "пред %s", s : "неколку секунди", m : "минута", mm : "%d минути", h : "час", hh : "%d часа", d : "ден", dd : "%d дена", M : "месец", MM : "%d месеци", y : "година", yy : "%d години" }, ordinal : function (number) { var lastDigit = number % 10, last2Digits = number % 100; if (number === 0) { return number + '-ев'; } else if (last2Digits === 0) { return number + '-ен'; } else if (last2Digits > 10 && last2Digits < 20) { return number + '-ти'; } else if (lastDigit === 1) { return number + '-ви'; } else if (lastDigit === 2) { return number + '-ри'; } else if (lastDigit === 7 || lastDigit === 8) { return number + '-ми'; } else { return number + '-ти'; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : malayalam (ml) // author : Floyd Pink : https://github.com/floydpink (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('ml', { months : 'ജനുവരി_ഫെബ്രുവരി_മാർച്ച്_ഏപ്രിൽ_മേയ്_ജൂൺ_ജൂലൈ_ഓഗസ്റ്റ്_സെപ്റ്റംബർ_ഒക്ടോബർ_നവംബർ_ഡിസംബർ'.split("_"), monthsShort : 'ജനു._ഫെബ്രു._മാർ._ഏപ്രി._മേയ്_ജൂൺ_ജൂലൈ._ഓഗ._സെപ്റ്റ._ഒക്ടോ._നവം._ഡിസം.'.split("_"), weekdays : 'ഞായറാഴ്ച_തിങ്കളാഴ്ച_ചൊവ്വാഴ്ച_ബുധനാഴ്ച_വ്യാഴാഴ്ച_വെള്ളിയാഴ്ച_ശനിയാഴ്ച'.split("_"), weekdaysShort : 'ഞായർ_തിങ്കൾ_ചൊവ്വ_ബുധൻ_വ്യാഴം_വെള്ളി_ശനി'.split("_"), weekdaysMin : 'ഞാ_തി_ചൊ_ബു_വ്യാ_വെ_ശ'.split("_"), longDateFormat : { LT : "A h:mm -നു", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY, LT", LLLL : "dddd, D MMMM YYYY, LT" }, calendar : { sameDay : '[ഇന്ന്] LT', nextDay : '[നാളെ] LT', nextWeek : 'dddd, LT', lastDay : '[ഇന്നലെ] LT', lastWeek : '[കഴിഞ്ഞ] dddd, LT', sameElse : 'L' }, relativeTime : { future : "%s കഴിഞ്ഞ്", past : "%s മുൻപ്", s : "അൽപ നിമിഷങ്ങൾ", m : "ഒരു മിനിറ്റ്", mm : "%d മിനിറ്റ്", h : "ഒരു മണിക്കൂർ", hh : "%d മണിക്കൂർ", d : "ഒരു ദിവസം", dd : "%d ദിവസം", M : "ഒരു മാസം", MM : "%d മാസം", y : "ഒരു വർഷം", yy : "%d വർഷം" }, meridiem : function (hour, minute, isLower) { if (hour < 4) { return "രാത്രി"; } else if (hour < 12) { return "രാവിലെ"; } else if (hour < 17) { return "ഉച്ച കഴിഞ്ഞ്"; } else if (hour < 20) { return "വൈകുന്നേരം"; } else { return "രാത്രി"; } } }); })); // moment.js language configuration // language : Marathi (mr) // author : Harshad Kale : https://github.com/kalehv (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var symbolMap = { '1': '१', '2': '२', '3': '३', '4': '४', '5': '५', '6': '६', '7': '७', '8': '८', '9': '९', '0': '०' }, numberMap = { '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9', '०': '0' }; return moment.lang('mr', { months : 'जानेवारी_फेब्रुवारी_मार्च_एप्रिल_मे_जून_जुलै_ऑगस्ट_सप्टेंबर_ऑक्टोबर_नोव्हेंबर_डिसेंबर'.split("_"), monthsShort: 'जाने._फेब्रु._मार्च._एप्रि._मे._जून._जुलै._ऑग._सप्टें._ऑक्टो._नोव्हें._डिसें.'.split("_"), weekdays : 'रविवार_सोमवार_मंगळवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split("_"), weekdaysShort : 'रवि_सोम_मंगळ_बुध_गुरू_शुक्र_शनि'.split("_"), weekdaysMin : 'र_सो_मं_बु_गु_शु_श'.split("_"), longDateFormat : { LT : "A h:mm वाजता", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY, LT", LLLL : "dddd, D MMMM YYYY, LT" }, calendar : { sameDay : '[आज] LT', nextDay : '[उद्या] LT', nextWeek : 'dddd, LT', lastDay : '[काल] LT', lastWeek: '[मागील] dddd, LT', sameElse : 'L' }, relativeTime : { future : "%s नंतर", past : "%s पूर्वी", s : "सेकंद", m: "एक मिनिट", mm: "%d मिनिटे", h : "एक तास", hh : "%d तास", d : "एक दिवस", dd : "%d दिवस", M : "एक महिना", MM : "%d महिने", y : "एक वर्ष", yy : "%d वर्षे" }, preparse: function (string) { return string.replace(/[१२३४५६७८९०]/g, function (match) { return numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }); }, meridiem: function (hour, minute, isLower) { if (hour < 4) { return "रात्री"; } else if (hour < 10) { return "सकाळी"; } else if (hour < 17) { return "दुपारी"; } else if (hour < 20) { return "सायंकाळी"; } else { return "रात्री"; } }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Bahasa Malaysia (ms-MY) // author : Weldan Jamili : https://github.com/weldan (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('ms-my', { months : "Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember".split("_"), monthsShort : "Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis".split("_"), weekdays : "Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu".split("_"), weekdaysShort : "Ahd_Isn_Sel_Rab_Kha_Jum_Sab".split("_"), weekdaysMin : "Ah_Is_Sl_Rb_Km_Jm_Sb".split("_"), longDateFormat : { LT : "HH.mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY [pukul] LT", LLLL : "dddd, D MMMM YYYY [pukul] LT" }, meridiem : function (hours, minutes, isLower) { if (hours < 11) { return 'pagi'; } else if (hours < 15) { return 'tengahari'; } else if (hours < 19) { return 'petang'; } else { return 'malam'; } }, calendar : { sameDay : '[Hari ini pukul] LT', nextDay : '[Esok pukul] LT', nextWeek : 'dddd [pukul] LT', lastDay : '[Kelmarin pukul] LT', lastWeek : 'dddd [lepas pukul] LT', sameElse : 'L' }, relativeTime : { future : "dalam %s", past : "%s yang lepas", s : "beberapa saat", m : "seminit", mm : "%d minit", h : "sejam", hh : "%d jam", d : "sehari", dd : "%d hari", M : "sebulan", MM : "%d bulan", y : "setahun", yy : "%d tahun" }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : norwegian bokmål (nb) // authors : Espen Hovlandsdal : https://github.com/rexxars // Sigurd Gartmann : https://github.com/sigurdga (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('nb', { months : "januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember".split("_"), monthsShort : "jan._feb._mars_april_mai_juni_juli_aug._sep._okt._nov._des.".split("_"), weekdays : "søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag".split("_"), weekdaysShort : "sø._ma._ti._on._to._fr._lø.".split("_"), weekdaysMin : "sø_ma_ti_on_to_fr_lø".split("_"), longDateFormat : { LT : "H.mm", L : "DD.MM.YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY [kl.] LT", LLLL : "dddd D. MMMM YYYY [kl.] LT" }, calendar : { sameDay: '[i dag kl.] LT', nextDay: '[i morgen kl.] LT', nextWeek: 'dddd [kl.] LT', lastDay: '[i går kl.] LT', lastWeek: '[forrige] dddd [kl.] LT', sameElse: 'L' }, relativeTime : { future : "om %s", past : "for %s siden", s : "noen sekunder", m : "ett minutt", mm : "%d minutter", h : "en time", hh : "%d timer", d : "en dag", dd : "%d dager", M : "en måned", MM : "%d måneder", y : "ett år", yy : "%d år" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : nepali/nepalese // author : suvash : https://github.com/suvash (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var symbolMap = { '1': '१', '2': '२', '3': '३', '4': '४', '5': '५', '6': '६', '7': '७', '8': '८', '9': '९', '0': '०' }, numberMap = { '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9', '०': '0' }; return moment.lang('ne', { months : 'जनवरी_फेब्रुवरी_मार्च_अप्रिल_मई_जुन_जुलाई_अगष्ट_सेप्टेम्बर_अक्टोबर_नोभेम्बर_डिसेम्बर'.split("_"), monthsShort : 'जन._फेब्रु._मार्च_अप्रि._मई_जुन_जुलाई._अग._सेप्ट._अक्टो._नोभे._डिसे.'.split("_"), weekdays : 'आइतबार_सोमबार_मङ्गलबार_बुधबार_बिहिबार_शुक्रबार_शनिबार'.split("_"), weekdaysShort : 'आइत._सोम._मङ्गल._बुध._बिहि._शुक्र._शनि.'.split("_"), weekdaysMin : 'आइ._सो._मङ्_बु._बि._शु._श.'.split("_"), longDateFormat : { LT : "Aको h:mm बजे", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY, LT", LLLL : "dddd, D MMMM YYYY, LT" }, preparse: function (string) { return string.replace(/[१२३४५६७८९०]/g, function (match) { return numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }); }, meridiem : function (hour, minute, isLower) { if (hour < 3) { return "राती"; } else if (hour < 10) { return "बिहान"; } else if (hour < 15) { return "दिउँसो"; } else if (hour < 18) { return "बेलुका"; } else if (hour < 20) { return "साँझ"; } else { return "राती"; } }, calendar : { sameDay : '[आज] LT', nextDay : '[भोली] LT', nextWeek : '[आउँदो] dddd[,] LT', lastDay : '[हिजो] LT', lastWeek : '[गएको] dddd[,] LT', sameElse : 'L' }, relativeTime : { future : "%sमा", past : "%s अगाडी", s : "केही समय", m : "एक मिनेट", mm : "%d मिनेट", h : "एक घण्टा", hh : "%d घण्टा", d : "एक दिन", dd : "%d दिन", M : "एक महिना", MM : "%d महिना", y : "एक बर्ष", yy : "%d बर्ष" }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : dutch (nl) // author : Joris Röling : https://github.com/jjupiter (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var monthsShortWithDots = "jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.".split("_"), monthsShortWithoutDots = "jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec".split("_"); return moment.lang('nl', { months : "januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december".split("_"), monthsShort : function (m, format) { if (/-MMM-/.test(format)) { return monthsShortWithoutDots[m.month()]; } else { return monthsShortWithDots[m.month()]; } }, weekdays : "zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag".split("_"), weekdaysShort : "zo._ma._di._wo._do._vr._za.".split("_"), weekdaysMin : "Zo_Ma_Di_Wo_Do_Vr_Za".split("_"), longDateFormat : { LT : "HH:mm", L : "DD-MM-YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: '[vandaag om] LT', nextDay: '[morgen om] LT', nextWeek: 'dddd [om] LT', lastDay: '[gisteren om] LT', lastWeek: '[afgelopen] dddd [om] LT', sameElse: 'L' }, relativeTime : { future : "over %s", past : "%s geleden", s : "een paar seconden", m : "één minuut", mm : "%d minuten", h : "één uur", hh : "%d uur", d : "één dag", dd : "%d dagen", M : "één maand", MM : "%d maanden", y : "één jaar", yy : "%d jaar" }, ordinal : function (number) { return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de'); }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : norwegian nynorsk (nn) // author : https://github.com/mechuwind (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('nn', { months : "januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember".split("_"), monthsShort : "jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"), weekdays : "sundag_måndag_tysdag_onsdag_torsdag_fredag_laurdag".split("_"), weekdaysShort : "sun_mån_tys_ons_tor_fre_lau".split("_"), weekdaysMin : "su_må_ty_on_to_fr_lø".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: '[I dag klokka] LT', nextDay: '[I morgon klokka] LT', nextWeek: 'dddd [klokka] LT', lastDay: '[I går klokka] LT', lastWeek: '[Føregående] dddd [klokka] LT', sameElse: 'L' }, relativeTime : { future : "om %s", past : "for %s siden", s : "noen sekund", m : "ett minutt", mm : "%d minutt", h : "en time", hh : "%d timar", d : "en dag", dd : "%d dagar", M : "en månad", MM : "%d månader", y : "ett år", yy : "%d år" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : polish (pl) // author : Rafal Hirsz : https://github.com/evoL (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var monthsNominative = "styczeń_luty_marzec_kwiecień_maj_czerwiec_lipiec_sierpień_wrzesień_październik_listopad_grudzień".split("_"), monthsSubjective = "stycznia_lutego_marca_kwietnia_maja_czerwca_lipca_sierpnia_września_października_listopada_grudnia".split("_"); function plural(n) { return (n % 10 < 5) && (n % 10 > 1) && ((~~(n / 10) % 10) !== 1); } function translate(number, withoutSuffix, key) { var result = number + " "; switch (key) { case 'm': return withoutSuffix ? 'minuta' : 'minutę'; case 'mm': return result + (plural(number) ? 'minuty' : 'minut'); case 'h': return withoutSuffix ? 'godzina' : 'godzinę'; case 'hh': return result + (plural(number) ? 'godziny' : 'godzin'); case 'MM': return result + (plural(number) ? 'miesiące' : 'miesięcy'); case 'yy': return result + (plural(number) ? 'lata' : 'lat'); } } return moment.lang('pl', { months : function (momentToFormat, format) { if (/D MMMM/.test(format)) { return monthsSubjective[momentToFormat.month()]; } else { return monthsNominative[momentToFormat.month()]; } }, monthsShort : "sty_lut_mar_kwi_maj_cze_lip_sie_wrz_paź_lis_gru".split("_"), weekdays : "niedziela_poniedziałek_wtorek_środa_czwartek_piątek_sobota".split("_"), weekdaysShort : "nie_pon_wt_śr_czw_pt_sb".split("_"), weekdaysMin : "N_Pn_Wt_Śr_Cz_Pt_So".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay: '[Dziś o] LT', nextDay: '[Jutro o] LT', nextWeek: '[W] dddd [o] LT', lastDay: '[Wczoraj o] LT', lastWeek: function () { switch (this.day()) { case 0: return '[W zeszłą niedzielę o] LT'; case 3: return '[W zeszłą środę o] LT'; case 6: return '[W zeszłą sobotę o] LT'; default: return '[W zeszły] dddd [o] LT'; } }, sameElse: 'L' }, relativeTime : { future : "za %s", past : "%s temu", s : "kilka sekund", m : translate, mm : translate, h : translate, hh : translate, d : "1 dzień", dd : '%d dni', M : "miesiąc", MM : translate, y : "rok", yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : brazilian portuguese (pt-br) // author : Caio Ribeiro Pereira : https://github.com/caio-ribeiro-pereira (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('pt-br', { months : "Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro".split("_"), monthsShort : "Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez".split("_"), weekdays : "Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado".split("_"), weekdaysShort : "Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"), weekdaysMin : "Dom_2ª_3ª_4ª_5ª_6ª_Sáb".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D [de] MMMM [de] YYYY", LLL : "D [de] MMMM [de] YYYY LT", LLLL : "dddd, D [de] MMMM [de] YYYY LT" }, calendar : { sameDay: '[Hoje às] LT', nextDay: '[Amanhã às] LT', nextWeek: 'dddd [às] LT', lastDay: '[Ontem às] LT', lastWeek: function () { return (this.day() === 0 || this.day() === 6) ? '[Último] dddd [às] LT' : // Saturday + Sunday '[Última] dddd [às] LT'; // Monday - Friday }, sameElse: 'L' }, relativeTime : { future : "em %s", past : "%s atrás", s : "segundos", m : "um minuto", mm : "%d minutos", h : "uma hora", hh : "%d horas", d : "um dia", dd : "%d dias", M : "um mês", MM : "%d meses", y : "um ano", yy : "%d anos" }, ordinal : '%dº' }); })); // moment.js language configuration // language : portuguese (pt) // author : Jefferson : https://github.com/jalex79 (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('pt', { months : "Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro".split("_"), monthsShort : "Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez".split("_"), weekdays : "Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado".split("_"), weekdaysShort : "Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"), weekdaysMin : "Dom_2ª_3ª_4ª_5ª_6ª_Sáb".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D [de] MMMM [de] YYYY", LLL : "D [de] MMMM [de] YYYY LT", LLLL : "dddd, D [de] MMMM [de] YYYY LT" }, calendar : { sameDay: '[Hoje às] LT', nextDay: '[Amanhã às] LT', nextWeek: 'dddd [às] LT', lastDay: '[Ontem às] LT', lastWeek: function () { return (this.day() === 0 || this.day() === 6) ? '[Último] dddd [às] LT' : // Saturday + Sunday '[Última] dddd [às] LT'; // Monday - Friday }, sameElse: 'L' }, relativeTime : { future : "em %s", past : "%s atrás", s : "segundos", m : "um minuto", mm : "%d minutos", h : "uma hora", hh : "%d horas", d : "um dia", dd : "%d dias", M : "um mês", MM : "%d meses", y : "um ano", yy : "%d anos" }, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : romanian (ro) // author : Vlad Gurdiga : https://github.com/gurdiga // author : Valentin Agachi : https://github.com/avaly (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function relativeTimeWithPlural(number, withoutSuffix, key) { var format = { 'mm': 'minute', 'hh': 'ore', 'dd': 'zile', 'MM': 'luni', 'yy': 'ani' }, separator = ' '; if (number % 100 >= 20 || (number >= 100 && number % 100 === 0)) { separator = ' de '; } return number + separator + format[key]; } return moment.lang('ro', { months : "ianuarie_februarie_martie_aprilie_mai_iunie_iulie_august_septembrie_octombrie_noiembrie_decembrie".split("_"), monthsShort : "ian_feb_mar_apr_mai_iun_iul_aug_sep_oct_noi_dec".split("_"), weekdays : "duminică_luni_marți_miercuri_joi_vineri_sâmbătă".split("_"), weekdaysShort : "Dum_Lun_Mar_Mie_Joi_Vin_Sâm".split("_"), weekdaysMin : "Du_Lu_Ma_Mi_Jo_Vi_Sâ".split("_"), longDateFormat : { LT : "H:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY H:mm", LLLL : "dddd, D MMMM YYYY H:mm" }, calendar : { sameDay: "[azi la] LT", nextDay: '[mâine la] LT', nextWeek: 'dddd [la] LT', lastDay: '[ieri la] LT', lastWeek: '[fosta] dddd [la] LT', sameElse: 'L' }, relativeTime : { future : "peste %s", past : "%s în urmă", s : "câteva secunde", m : "un minut", mm : relativeTimeWithPlural, h : "o oră", hh : relativeTimeWithPlural, d : "o zi", dd : relativeTimeWithPlural, M : "o lună", MM : relativeTimeWithPlural, y : "un an", yy : relativeTimeWithPlural }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : serbian (rs) // author : Limon Monte : https://github.com/limonte // based on (bs) translation by Nedim Cholich (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function translate(number, withoutSuffix, key) { var result = number + " "; switch (key) { case 'm': return withoutSuffix ? 'jedna minuta' : 'jedne minute'; case 'mm': if (number === 1) { result += 'minuta'; } else if (number === 2 || number === 3 || number === 4) { result += 'minute'; } else { result += 'minuta'; } return result; case 'h': return withoutSuffix ? 'jedan sat' : 'jednog sata'; case 'hh': if (number === 1) { result += 'sat'; } else if (number === 2 || number === 3 || number === 4) { result += 'sata'; } else { result += 'sati'; } return result; case 'dd': if (number === 1) { result += 'dan'; } else { result += 'dana'; } return result; case 'MM': if (number === 1) { result += 'mesec'; } else if (number === 2 || number === 3 || number === 4) { result += 'meseca'; } else { result += 'meseci'; } return result; case 'yy': if (number === 1) { result += 'godina'; } else if (number === 2 || number === 3 || number === 4) { result += 'godine'; } else { result += 'godina'; } return result; } } return moment.lang('rs', { months : "januar_februar_mart_april_maj_jun_jul_avgust_septembar_oktobar_novembar_decembar".split("_"), monthsShort : "jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.".split("_"), weekdays : "nedelja_ponedeljak_utorak_sreda_četvrtak_petak_subota".split("_"), weekdaysShort : "ned._pon._uto._sre._čet._pet._sub.".split("_"), weekdaysMin : "ne_po_ut_sr_če_pe_su".split("_"), longDateFormat : { LT : "H:mm", L : "DD. MM. YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay : '[danas u] LT', nextDay : '[sutra u] LT', nextWeek : function () { switch (this.day()) { case 0: return '[u] [nedelju] [u] LT'; case 3: return '[u] [sredu] [u] LT'; case 6: return '[u] [subotu] [u] LT'; case 1: case 2: case 4: case 5: return '[u] dddd [u] LT'; } }, lastDay : '[juče u] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: return '[prošlu] dddd [u] LT'; case 6: return '[prošle] [subote] [u] LT'; case 1: case 2: case 4: case 5: return '[prošli] dddd [u] LT'; } }, sameElse : 'L' }, relativeTime : { future : "za %s", past : "pre %s", s : "par sekundi", m : translate, mm : translate, h : translate, hh : translate, d : "dan", dd : translate, M : "mesec", MM : translate, y : "godinu", yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : russian (ru) // author : Viktorminator : https://github.com/Viktorminator // Author : Menelion Elensúle : https://github.com/Oire (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function plural(word, num) { var forms = word.split('_'); return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]); } function relativeTimeWithPlural(number, withoutSuffix, key) { var format = { 'mm': 'минута_минуты_минут', 'hh': 'час_часа_часов', 'dd': 'день_дня_дней', 'MM': 'месяц_месяца_месяцев', 'yy': 'год_года_лет' }; if (key === 'm') { return withoutSuffix ? 'минута' : 'минуту'; } else { return number + ' ' + plural(format[key], +number); } } function monthsCaseReplace(m, format) { var months = { 'nominative': 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_'), 'accusative': 'января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря'.split('_') }, nounCase = (/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/).test(format) ? 'accusative' : 'nominative'; return months[nounCase][m.month()]; } function monthsShortCaseReplace(m, format) { var monthsShort = { 'nominative': 'янв_фев_мар_апр_май_июнь_июль_авг_сен_окт_ноя_дек'.split('_'), 'accusative': 'янв_фев_мар_апр_мая_июня_июля_авг_сен_окт_ноя_дек'.split('_') }, nounCase = (/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/).test(format) ? 'accusative' : 'nominative'; return monthsShort[nounCase][m.month()]; } function weekdaysCaseReplace(m, format) { var weekdays = { 'nominative': 'воскресенье_понедельник_вторник_среда_четверг_пятница_суббота'.split('_'), 'accusative': 'воскресенье_понедельник_вторник_среду_четверг_пятницу_субботу'.split('_') }, nounCase = (/\[ ?[Вв] ?(?:прошлую|следующую)? ?\] ?dddd/).test(format) ? 'accusative' : 'nominative'; return weekdays[nounCase][m.day()]; } return moment.lang('ru', { months : monthsCaseReplace, monthsShort : monthsShortCaseReplace, weekdays : weekdaysCaseReplace, weekdaysShort : "вс_пн_вт_ср_чт_пт_сб".split("_"), weekdaysMin : "вс_пн_вт_ср_чт_пт_сб".split("_"), monthsParse : [/^янв/i, /^фев/i, /^мар/i, /^апр/i, /^ма[й|я]/i, /^июн/i, /^июл/i, /^авг/i, /^сен/i, /^окт/i, /^ноя/i, /^дек/i], longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY г.", LLL : "D MMMM YYYY г., LT", LLLL : "dddd, D MMMM YYYY г., LT" }, calendar : { sameDay: '[Сегодня в] LT', nextDay: '[Завтра в] LT', lastDay: '[Вчера в] LT', nextWeek: function () { return this.day() === 2 ? '[Во] dddd [в] LT' : '[В] dddd [в] LT'; }, lastWeek: function () { switch (this.day()) { case 0: return '[В прошлое] dddd [в] LT'; case 1: case 2: case 4: return '[В прошлый] dddd [в] LT'; case 3: case 5: case 6: return '[В прошлую] dddd [в] LT'; } }, sameElse: 'L' }, relativeTime : { future : "через %s", past : "%s назад", s : "несколько секунд", m : relativeTimeWithPlural, mm : relativeTimeWithPlural, h : "час", hh : relativeTimeWithPlural, d : "день", dd : relativeTimeWithPlural, M : "месяц", MM : relativeTimeWithPlural, y : "год", yy : relativeTimeWithPlural }, // M. E.: those two are virtually unused but a user might want to implement them for his/her website for some reason meridiem : function (hour, minute, isLower) { if (hour < 4) { return "ночи"; } else if (hour < 12) { return "утра"; } else if (hour < 17) { return "дня"; } else { return "вечера"; } }, ordinal: function (number, period) { switch (period) { case 'M': case 'd': case 'DDD': return number + '-й'; case 'D': return number + '-го'; case 'w': case 'W': return number + '-я'; default: return number; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : slovak (sk) // author : Martin Minka : https://github.com/k2s // based on work of petrbela : https://github.com/petrbela (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var months = "január_február_marec_apríl_máj_jún_júl_august_september_október_november_december".split("_"), monthsShort = "jan_feb_mar_apr_máj_jún_júl_aug_sep_okt_nov_dec".split("_"); function plural(n) { return (n > 1) && (n < 5); } function translate(number, withoutSuffix, key, isFuture) { var result = number + " "; switch (key) { case 's': // a few seconds / in a few seconds / a few seconds ago return (withoutSuffix || isFuture) ? 'pár sekúnd' : 'pár sekundami'; case 'm': // a minute / in a minute / a minute ago return withoutSuffix ? 'minúta' : (isFuture ? 'minútu' : 'minútou'); case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'minúty' : 'minút'); } else { return result + 'minútami'; } break; case 'h': // an hour / in an hour / an hour ago return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou'); case 'hh': // 9 hours / in 9 hours / 9 hours ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'hodiny' : 'hodín'); } else { return result + 'hodinami'; } break; case 'd': // a day / in a day / a day ago return (withoutSuffix || isFuture) ? 'deň' : 'dňom'; case 'dd': // 9 days / in 9 days / 9 days ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'dni' : 'dní'); } else { return result + 'dňami'; } break; case 'M': // a month / in a month / a month ago return (withoutSuffix || isFuture) ? 'mesiac' : 'mesiacom'; case 'MM': // 9 months / in 9 months / 9 months ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'mesiace' : 'mesiacov'); } else { return result + 'mesiacmi'; } break; case 'y': // a year / in a year / a year ago return (withoutSuffix || isFuture) ? 'rok' : 'rokom'; case 'yy': // 9 years / in 9 years / 9 years ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'roky' : 'rokov'); } else { return result + 'rokmi'; } break; } } return moment.lang('sk', { months : months, monthsShort : monthsShort, monthsParse : (function (months, monthsShort) { var i, _monthsParse = []; for (i = 0; i < 12; i++) { // use custom parser to solve problem with July (červenec) _monthsParse[i] = new RegExp('^' + months[i] + '$|^' + monthsShort[i] + '$', 'i'); } return _monthsParse; }(months, monthsShort)), weekdays : "nedeľa_pondelok_utorok_streda_štvrtok_piatok_sobota".split("_"), weekdaysShort : "ne_po_ut_st_št_pi_so".split("_"), weekdaysMin : "ne_po_ut_st_št_pi_so".split("_"), longDateFormat : { LT: "H:mm", L : "DD.MM.YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd D. MMMM YYYY LT" }, calendar : { sameDay: "[dnes o] LT", nextDay: '[zajtra o] LT', nextWeek: function () { switch (this.day()) { case 0: return '[v nedeľu o] LT'; case 1: case 2: return '[v] dddd [o] LT'; case 3: return '[v stredu o] LT'; case 4: return '[vo štvrtok o] LT'; case 5: return '[v piatok o] LT'; case 6: return '[v sobotu o] LT'; } }, lastDay: '[včera o] LT', lastWeek: function () { switch (this.day()) { case 0: return '[minulú nedeľu o] LT'; case 1: case 2: return '[minulý] dddd [o] LT'; case 3: return '[minulú stredu o] LT'; case 4: case 5: return '[minulý] dddd [o] LT'; case 6: return '[minulú sobotu o] LT'; } }, sameElse: "L" }, relativeTime : { future : "za %s", past : "pred %s", s : translate, m : translate, mm : translate, h : translate, hh : translate, d : translate, dd : translate, M : translate, MM : translate, y : translate, yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : slovenian (sl) // author : Robert Sedovšek : https://github.com/sedovsek (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function translate(number, withoutSuffix, key) { var result = number + " "; switch (key) { case 'm': return withoutSuffix ? 'ena minuta' : 'eno minuto'; case 'mm': if (number === 1) { result += 'minuta'; } else if (number === 2) { result += 'minuti'; } else if (number === 3 || number === 4) { result += 'minute'; } else { result += 'minut'; } return result; case 'h': return withoutSuffix ? 'ena ura' : 'eno uro'; case 'hh': if (number === 1) { result += 'ura'; } else if (number === 2) { result += 'uri'; } else if (number === 3 || number === 4) { result += 'ure'; } else { result += 'ur'; } return result; case 'dd': if (number === 1) { result += 'dan'; } else { result += 'dni'; } return result; case 'MM': if (number === 1) { result += 'mesec'; } else if (number === 2) { result += 'meseca'; } else if (number === 3 || number === 4) { result += 'mesece'; } else { result += 'mesecev'; } return result; case 'yy': if (number === 1) { result += 'leto'; } else if (number === 2) { result += 'leti'; } else if (number === 3 || number === 4) { result += 'leta'; } else { result += 'let'; } return result; } } return moment.lang('sl', { months : "januar_februar_marec_april_maj_junij_julij_avgust_september_oktober_november_december".split("_"), monthsShort : "jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.".split("_"), weekdays : "nedelja_ponedeljek_torek_sreda_četrtek_petek_sobota".split("_"), weekdaysShort : "ned._pon._tor._sre._čet._pet._sob.".split("_"), weekdaysMin : "ne_po_to_sr_če_pe_so".split("_"), longDateFormat : { LT : "H:mm", L : "DD. MM. YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay : '[danes ob] LT', nextDay : '[jutri ob] LT', nextWeek : function () { switch (this.day()) { case 0: return '[v] [nedeljo] [ob] LT'; case 3: return '[v] [sredo] [ob] LT'; case 6: return '[v] [soboto] [ob] LT'; case 1: case 2: case 4: case 5: return '[v] dddd [ob] LT'; } }, lastDay : '[včeraj ob] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: case 6: return '[prejšnja] dddd [ob] LT'; case 1: case 2: case 4: case 5: return '[prejšnji] dddd [ob] LT'; } }, sameElse : 'L' }, relativeTime : { future : "čez %s", past : "%s nazaj", s : "nekaj sekund", m : translate, mm : translate, h : translate, hh : translate, d : "en dan", dd : translate, M : "en mesec", MM : translate, y : "eno leto", yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Albanian (sq) // author : Flakërim Ismani : https://github.com/flakerimi // author: Menelion Elensúle: https://github.com/Oire (tests) (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('sq', { months : "Janar_Shkurt_Mars_Prill_Maj_Qershor_Korrik_Gusht_Shtator_Tetor_Nëntor_Dhjetor".split("_"), monthsShort : "Jan_Shk_Mar_Pri_Maj_Qer_Kor_Gus_Sht_Tet_Nën_Dhj".split("_"), weekdays : "E Diel_E Hënë_E Marte_E Mërkure_E Enjte_E Premte_E Shtunë".split("_"), weekdaysShort : "Die_Hën_Mar_Mër_Enj_Pre_Sht".split("_"), weekdaysMin : "D_H_Ma_Më_E_P_Sh".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[Sot në] LT', nextDay : '[Neser në] LT', nextWeek : 'dddd [në] LT', lastDay : '[Dje në] LT', lastWeek : 'dddd [e kaluar në] LT', sameElse : 'L' }, relativeTime : { future : "në %s", past : "%s me parë", s : "disa sekonda", m : "një minut", mm : "%d minuta", h : "një orë", hh : "%d orë", d : "një ditë", dd : "%d ditë", M : "një muaj", MM : "%d muaj", y : "një vit", yy : "%d vite" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : swedish (sv) // author : Jens Alm : https://github.com/ulmus (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('sv', { months : "januari_februari_mars_april_maj_juni_juli_augusti_september_oktober_november_december".split("_"), monthsShort : "jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec".split("_"), weekdays : "söndag_måndag_tisdag_onsdag_torsdag_fredag_lördag".split("_"), weekdaysShort : "sön_mån_tis_ons_tor_fre_lör".split("_"), weekdaysMin : "sö_må_ti_on_to_fr_lö".split("_"), longDateFormat : { LT : "HH:mm", L : "YYYY-MM-DD", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: '[Idag] LT', nextDay: '[Imorgon] LT', lastDay: '[Igår] LT', nextWeek: 'dddd LT', lastWeek: '[Förra] dddd[en] LT', sameElse: 'L' }, relativeTime : { future : "om %s", past : "för %s sedan", s : "några sekunder", m : "en minut", mm : "%d minuter", h : "en timme", hh : "%d timmar", d : "en dag", dd : "%d dagar", M : "en månad", MM : "%d månader", y : "ett år", yy : "%d år" }, ordinal : function (number) { var b = number % 10, output = (~~ (number % 100 / 10) === 1) ? 'e' : (b === 1) ? 'a' : (b === 2) ? 'a' : (b === 3) ? 'e' : 'e'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : tamil (ta) // author : Arjunkumar Krishnamoorthy : https://github.com/tk120404 (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { /*var symbolMap = { '1': '௧', '2': '௨', '3': '௩', '4': '௪', '5': '௫', '6': '௬', '7': '௭', '8': '௮', '9': '௯', '0': '௦' }, numberMap = { '௧': '1', '௨': '2', '௩': '3', '௪': '4', '௫': '5', '௬': '6', '௭': '7', '௮': '8', '௯': '9', '௦': '0' }; */ return moment.lang('ta', { months : 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split("_"), monthsShort : 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split("_"), weekdays : 'ஞாயிற்றுக்கிழமை_திங்கட்கிழமை_செவ்வாய்கிழமை_புதன்கிழமை_வியாழக்கிழமை_வெள்ளிக்கிழமை_சனிக்கிழமை'.split("_"), weekdaysShort : 'ஞாயிறு_திங்கள்_செவ்வாய்_புதன்_வியாழன்_வெள்ளி_சனி'.split("_"), weekdaysMin : 'ஞா_தி_செ_பு_வி_வெ_ச'.split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY, LT", LLLL : "dddd, D MMMM YYYY, LT" }, calendar : { sameDay : '[இன்று] LT', nextDay : '[நாளை] LT', nextWeek : 'dddd, LT', lastDay : '[நேற்று] LT', lastWeek : '[கடந்த வாரம்] dddd, LT', sameElse : 'L' }, relativeTime : { future : "%s இல்", past : "%s முன்", s : "ஒரு சில விநாடிகள்", m : "ஒரு நிமிடம்", mm : "%d நிமிடங்கள்", h : "ஒரு மணி நேரம்", hh : "%d மணி நேரம்", d : "ஒரு நாள்", dd : "%d நாட்கள்", M : "ஒரு மாதம்", MM : "%d மாதங்கள்", y : "ஒரு வருடம்", yy : "%d ஆண்டுகள்" }, /* preparse: function (string) { return string.replace(/[௧௨௩௪௫௬௭௮௯௦]/g, function (match) { return numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }); },*/ ordinal : function (number) { return number + 'வது'; }, // refer http://ta.wikipedia.org/s/1er1 meridiem : function (hour, minute, isLower) { if (hour >= 6 && hour <= 10) { return " காலை"; } else if (hour >= 10 && hour <= 14) { return " நண்பகல்"; } else if (hour >= 14 && hour <= 18) { return " எற்பாடு"; } else if (hour >= 18 && hour <= 20) { return " மாலை"; } else if (hour >= 20 && hour <= 24) { return " இரவு"; } else if (hour >= 0 && hour <= 6) { return " வைகறை"; } }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : thai (th) // author : Kridsada Thanabulpong : https://github.com/sirn (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('th', { months : "มกราคม_กุมภาพันธ์_มีนาคม_เมษายน_พฤษภาคม_มิถุนายน_กรกฎาคม_สิงหาคม_กันยายน_ตุลาคม_พฤศจิกายน_ธันวาคม".split("_"), monthsShort : "มกรา_กุมภา_มีนา_เมษา_พฤษภา_มิถุนา_กรกฎา_สิงหา_กันยา_ตุลา_พฤศจิกา_ธันวา".split("_"), weekdays : "อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัสบดี_ศุกร์_เสาร์".split("_"), weekdaysShort : "อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัส_ศุกร์_เสาร์".split("_"), // yes, three characters difference weekdaysMin : "อา._จ._อ._พ._พฤ._ศ._ส.".split("_"), longDateFormat : { LT : "H นาฬิกา m นาที", L : "YYYY/MM/DD", LL : "D MMMM YYYY", LLL : "D MMMM YYYY เวลา LT", LLLL : "วันddddที่ D MMMM YYYY เวลา LT" }, meridiem : function (hour, minute, isLower) { if (hour < 12) { return "ก่อนเที่ยง"; } else { return "หลังเที่ยง"; } }, calendar : { sameDay : '[วันนี้ เวลา] LT', nextDay : '[พรุ่งนี้ เวลา] LT', nextWeek : 'dddd[หน้า เวลา] LT', lastDay : '[เมื่อวานนี้ เวลา] LT', lastWeek : '[วัน]dddd[ที่แล้ว เวลา] LT', sameElse : 'L' }, relativeTime : { future : "อีก %s", past : "%sที่แล้ว", s : "ไม่กี่วินาที", m : "1 นาที", mm : "%d นาที", h : "1 ชั่วโมง", hh : "%d ชั่วโมง", d : "1 วัน", dd : "%d วัน", M : "1 เดือน", MM : "%d เดือน", y : "1 ปี", yy : "%d ปี" } }); })); // moment.js language configuration // language : Tagalog/Filipino (tl-ph) // author : Dan Hagman (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('tl-ph', { months : "Enero_Pebrero_Marso_Abril_Mayo_Hunyo_Hulyo_Agosto_Setyembre_Oktubre_Nobyembre_Disyembre".split("_"), monthsShort : "Ene_Peb_Mar_Abr_May_Hun_Hul_Ago_Set_Okt_Nob_Dis".split("_"), weekdays : "Linggo_Lunes_Martes_Miyerkules_Huwebes_Biyernes_Sabado".split("_"), weekdaysShort : "Lin_Lun_Mar_Miy_Huw_Biy_Sab".split("_"), weekdaysMin : "Li_Lu_Ma_Mi_Hu_Bi_Sab".split("_"), longDateFormat : { LT : "HH:mm", L : "MM/D/YYYY", LL : "MMMM D, YYYY", LLL : "MMMM D, YYYY LT", LLLL : "dddd, MMMM DD, YYYY LT" }, calendar : { sameDay: "[Ngayon sa] LT", nextDay: '[Bukas sa] LT', nextWeek: 'dddd [sa] LT', lastDay: '[Kahapon sa] LT', lastWeek: 'dddd [huling linggo] LT', sameElse: 'L' }, relativeTime : { future : "sa loob ng %s", past : "%s ang nakalipas", s : "ilang segundo", m : "isang minuto", mm : "%d minuto", h : "isang oras", hh : "%d oras", d : "isang araw", dd : "%d araw", M : "isang buwan", MM : "%d buwan", y : "isang taon", yy : "%d taon" }, ordinal : function (number) { return number; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : turkish (tr) // authors : Erhan Gundogan : https://github.com/erhangundogan, // Burak Yiğit Kaya: https://github.com/BYK (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var suffixes = { 1: "'inci", 5: "'inci", 8: "'inci", 70: "'inci", 80: "'inci", 2: "'nci", 7: "'nci", 20: "'nci", 50: "'nci", 3: "'üncü", 4: "'üncü", 100: "'üncü", 6: "'ncı", 9: "'uncu", 10: "'uncu", 30: "'uncu", 60: "'ıncı", 90: "'ıncı" }; return moment.lang('tr', { months : "Ocak_Şubat_Mart_Nisan_Mayıs_Haziran_Temmuz_Ağustos_Eylül_Ekim_Kasım_Aralık".split("_"), monthsShort : "Oca_Şub_Mar_Nis_May_Haz_Tem_Ağu_Eyl_Eki_Kas_Ara".split("_"), weekdays : "Pazar_Pazartesi_Salı_Çarşamba_Perşembe_Cuma_Cumartesi".split("_"), weekdaysShort : "Paz_Pts_Sal_Çar_Per_Cum_Cts".split("_"), weekdaysMin : "Pz_Pt_Sa_Ça_Pe_Cu_Ct".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[bugün saat] LT', nextDay : '[yarın saat] LT', nextWeek : '[haftaya] dddd [saat] LT', lastDay : '[dün] LT', lastWeek : '[geçen hafta] dddd [saat] LT', sameElse : 'L' }, relativeTime : { future : "%s sonra", past : "%s önce", s : "birkaç saniye", m : "bir dakika", mm : "%d dakika", h : "bir saat", hh : "%d saat", d : "bir gün", dd : "%d gün", M : "bir ay", MM : "%d ay", y : "bir yıl", yy : "%d yıl" }, ordinal : function (number) { if (number === 0) { // special case for zero return number + "'ıncı"; } var a = number % 10, b = number % 100 - a, c = number >= 100 ? 100 : null; return number + (suffixes[a] || suffixes[b] || suffixes[c]); }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Morocco Central Atlas Tamaziɣt in Latin (tzm-la) // author : Abdel Said : https://github.com/abdelsaid (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('tzm-la', { months : "innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir".split("_"), monthsShort : "innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir".split("_"), weekdays : "asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas".split("_"), weekdaysShort : "asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas".split("_"), weekdaysMin : "asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[asdkh g] LT", nextDay: '[aska g] LT', nextWeek: 'dddd [g] LT', lastDay: '[assant g] LT', lastWeek: 'dddd [g] LT', sameElse: 'L' }, relativeTime : { future : "dadkh s yan %s", past : "yan %s", s : "imik", m : "minuḍ", mm : "%d minuḍ", h : "saɛa", hh : "%d tassaɛin", d : "ass", dd : "%d ossan", M : "ayowr", MM : "%d iyyirn", y : "asgas", yy : "%d isgasn" }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Morocco Central Atlas Tamaziɣt (tzm) // author : Abdel Said : https://github.com/abdelsaid (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('tzm', { months : "ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ".split("_"), monthsShort : "ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ".split("_"), weekdays : "ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ".split("_"), weekdaysShort : "ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ".split("_"), weekdaysMin : "ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[ⴰⵙⴷⵅ ⴴ] LT", nextDay: '[ⴰⵙⴽⴰ ⴴ] LT', nextWeek: 'dddd [ⴴ] LT', lastDay: '[ⴰⵚⴰⵏⵜ ⴴ] LT', lastWeek: 'dddd [ⴴ] LT', sameElse: 'L' }, relativeTime : { future : "ⴷⴰⴷⵅ ⵙ ⵢⴰⵏ %s", past : "ⵢⴰⵏ %s", s : "ⵉⵎⵉⴽ", m : "ⵎⵉⵏⵓⴺ", mm : "%d ⵎⵉⵏⵓⴺ", h : "ⵙⴰⵄⴰ", hh : "%d ⵜⴰⵙⵙⴰⵄⵉⵏ", d : "ⴰⵙⵙ", dd : "%d oⵙⵙⴰⵏ", M : "ⴰⵢoⵓⵔ", MM : "%d ⵉⵢⵢⵉⵔⵏ", y : "ⴰⵙⴳⴰⵙ", yy : "%d ⵉⵙⴳⴰⵙⵏ" }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : ukrainian (uk) // author : zemlanin : https://github.com/zemlanin // Author : Menelion Elensúle : https://github.com/Oire (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function plural(word, num) { var forms = word.split('_'); return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]); } function relativeTimeWithPlural(number, withoutSuffix, key) { var format = { 'mm': 'хвилина_хвилини_хвилин', 'hh': 'година_години_годин', 'dd': 'день_дні_днів', 'MM': 'місяць_місяці_місяців', 'yy': 'рік_роки_років' }; if (key === 'm') { return withoutSuffix ? 'хвилина' : 'хвилину'; } else if (key === 'h') { return withoutSuffix ? 'година' : 'годину'; } else { return number + ' ' + plural(format[key], +number); } } function monthsCaseReplace(m, format) { var months = { 'nominative': 'січень_лютий_березень_квітень_травень_червень_липень_серпень_вересень_жовтень_листопад_грудень'.split('_'), 'accusative': 'січня_лютого_березня_квітня_травня_червня_липня_серпня_вересня_жовтня_листопада_грудня'.split('_') }, nounCase = (/D[oD]? *MMMM?/).test(format) ? 'accusative' : 'nominative'; return months[nounCase][m.month()]; } function weekdaysCaseReplace(m, format) { var weekdays = { 'nominative': 'неділя_понеділок_вівторок_середа_четвер_п’ятниця_субота'.split('_'), 'accusative': 'неділю_понеділок_вівторок_середу_четвер_п’ятницю_суботу'.split('_'), 'genitive': 'неділі_понеділка_вівторка_середи_четверга_п’ятниці_суботи'.split('_') }, nounCase = (/(\[[ВвУу]\]) ?dddd/).test(format) ? 'accusative' : ((/\[?(?:минулої|наступної)? ?\] ?dddd/).test(format) ? 'genitive' : 'nominative'); return weekdays[nounCase][m.day()]; } function processHoursFunction(str) { return function () { return str + 'о' + (this.hours() === 11 ? 'б' : '') + '] LT'; }; } return moment.lang('uk', { months : monthsCaseReplace, monthsShort : "січ_лют_бер_квіт_трав_черв_лип_серп_вер_жовт_лист_груд".split("_"), weekdays : weekdaysCaseReplace, weekdaysShort : "нд_пн_вт_ср_чт_пт_сб".split("_"), weekdaysMin : "нд_пн_вт_ср_чт_пт_сб".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY р.", LLL : "D MMMM YYYY р., LT", LLLL : "dddd, D MMMM YYYY р., LT" }, calendar : { sameDay: processHoursFunction('[Сьогодні '), nextDay: processHoursFunction('[Завтра '), lastDay: processHoursFunction('[Вчора '), nextWeek: processHoursFunction('[У] dddd ['), lastWeek: function () { switch (this.day()) { case 0: case 3: case 5: case 6: return processHoursFunction('[Минулої] dddd [').call(this); case 1: case 2: case 4: return processHoursFunction('[Минулого] dddd [').call(this); } }, sameElse: 'L' }, relativeTime : { future : "за %s", past : "%s тому", s : "декілька секунд", m : relativeTimeWithPlural, mm : relativeTimeWithPlural, h : "годину", hh : relativeTimeWithPlural, d : "день", dd : relativeTimeWithPlural, M : "місяць", MM : relativeTimeWithPlural, y : "рік", yy : relativeTimeWithPlural }, // M. E.: those two are virtually unused but a user might want to implement them for his/her website for some reason meridiem : function (hour, minute, isLower) { if (hour < 4) { return "ночі"; } else if (hour < 12) { return "ранку"; } else if (hour < 17) { return "дня"; } else { return "вечора"; } }, ordinal: function (number, period) { switch (period) { case 'M': case 'd': case 'DDD': case 'w': case 'W': return number + '-й'; case 'D': return number + '-го'; default: return number; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : uzbek // author : Sardor Muminov : https://github.com/muminoff (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('uz', { months : "январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь".split("_"), monthsShort : "янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек".split("_"), weekdays : "Якшанба_Душанба_Сешанба_Чоршанба_Пайшанба_Жума_Шанба".split("_"), weekdaysShort : "Якш_Душ_Сеш_Чор_Пай_Жум_Шан".split("_"), weekdaysMin : "Як_Ду_Се_Чо_Па_Жу_Ша".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "D MMMM YYYY, dddd LT" }, calendar : { sameDay : '[Бугун соат] LT [да]', nextDay : '[Эртага] LT [да]', nextWeek : 'dddd [куни соат] LT [да]', lastDay : '[Кеча соат] LT [да]', lastWeek : '[Утган] dddd [куни соат] LT [да]', sameElse : 'L' }, relativeTime : { future : "Якин %s ичида", past : "Бир неча %s олдин", s : "фурсат", m : "бир дакика", mm : "%d дакика", h : "бир соат", hh : "%d соат", d : "бир кун", dd : "%d кун", M : "бир ой", MM : "%d ой", y : "бир йил", yy : "%d йил" }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : vietnamese (vn) // author : Bang Nguyen : https://github.com/bangnk (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('vn', { months : "tháng 1_tháng 2_tháng 3_tháng 4_tháng 5_tháng 6_tháng 7_tháng 8_tháng 9_tháng 10_tháng 11_tháng 12".split("_"), monthsShort : "Th01_Th02_Th03_Th04_Th05_Th06_Th07_Th08_Th09_Th10_Th11_Th12".split("_"), weekdays : "chủ nhật_thứ hai_thứ ba_thứ tư_thứ năm_thứ sáu_thứ bảy".split("_"), weekdaysShort : "CN_T2_T3_T4_T5_T6_T7".split("_"), weekdaysMin : "CN_T2_T3_T4_T5_T6_T7".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM [năm] YYYY", LLL : "D MMMM [năm] YYYY LT", LLLL : "dddd, D MMMM [năm] YYYY LT", l : "DD/M/YYYY", ll : "D MMM YYYY", lll : "D MMM YYYY LT", llll : "ddd, D MMM YYYY LT" }, calendar : { sameDay: "[Hôm nay lúc] LT", nextDay: '[Ngày mai lúc] LT', nextWeek: 'dddd [tuần tới lúc] LT', lastDay: '[Hôm qua lúc] LT', lastWeek: 'dddd [tuần rồi lúc] LT', sameElse: 'L' }, relativeTime : { future : "%s tới", past : "%s trước", s : "vài giây", m : "một phút", mm : "%d phút", h : "một giờ", hh : "%d giờ", d : "một ngày", dd : "%d ngày", M : "một tháng", MM : "%d tháng", y : "một năm", yy : "%d năm" }, ordinal : function (number) { return number; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : chinese // author : suupic : https://github.com/suupic // author : Zeno Zeng : https://github.com/zenozeng (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('zh-cn', { months : "一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"), monthsShort : "1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"), weekdays : "星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"), weekdaysShort : "周日_周一_周二_周三_周四_周五_周六".split("_"), weekdaysMin : "日_一_二_三_四_五_六".split("_"), longDateFormat : { LT : "Ah点mm", L : "YYYY-MM-DD", LL : "YYYY年MMMD日", LLL : "YYYY年MMMD日LT", LLLL : "YYYY年MMMD日ddddLT", l : "YYYY-MM-DD", ll : "YYYY年MMMD日", lll : "YYYY年MMMD日LT", llll : "YYYY年MMMD日ddddLT" }, meridiem : function (hour, minute, isLower) { var hm = hour * 100 + minute; if (hm < 600) { return "凌晨"; } else if (hm < 900) { return "早上"; } else if (hm < 1130) { return "上午"; } else if (hm < 1230) { return "中午"; } else if (hm < 1800) { return "下午"; } else { return "晚上"; } }, calendar : { sameDay : function () { return this.minutes() === 0 ? "[今天]Ah[点整]" : "[今天]LT"; }, nextDay : function () { return this.minutes() === 0 ? "[明天]Ah[点整]" : "[明天]LT"; }, lastDay : function () { return this.minutes() === 0 ? "[昨天]Ah[点整]" : "[昨天]LT"; }, nextWeek : function () { var startOfWeek, prefix; startOfWeek = moment().startOf('week'); prefix = this.unix() - startOfWeek.unix() >= 7 * 24 * 3600 ? '[下]' : '[本]'; return this.minutes() === 0 ? prefix + "dddAh点整" : prefix + "dddAh点mm"; }, lastWeek : function () { var startOfWeek, prefix; startOfWeek = moment().startOf('week'); prefix = this.unix() < startOfWeek.unix() ? '[上]' : '[本]'; return this.minutes() === 0 ? prefix + "dddAh点整" : prefix + "dddAh点mm"; }, sameElse : 'LL' }, ordinal : function (number, period) { switch (period) { case "d": case "D": case "DDD": return number + "日"; case "M": return number + "月"; case "w": case "W": return number + "周"; default: return number; } }, relativeTime : { future : "%s内", past : "%s前", s : "几秒", m : "1分钟", mm : "%d分钟", h : "1小时", hh : "%d小时", d : "1天", dd : "%d天", M : "1个月", MM : "%d个月", y : "1年", yy : "%d年" }, week : { // GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效 dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : traditional chinese (zh-tw) // author : Ben : https://github.com/ben-lin (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('zh-tw', { months : "一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"), monthsShort : "1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"), weekdays : "星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"), weekdaysShort : "週日_週一_週二_週三_週四_週五_週六".split("_"), weekdaysMin : "日_一_二_三_四_五_六".split("_"), longDateFormat : { LT : "Ah點mm", L : "YYYY年MMMD日", LL : "YYYY年MMMD日", LLL : "YYYY年MMMD日LT", LLLL : "YYYY年MMMD日ddddLT", l : "YYYY年MMMD日", ll : "YYYY年MMMD日", lll : "YYYY年MMMD日LT", llll : "YYYY年MMMD日ddddLT" }, meridiem : function (hour, minute, isLower) { var hm = hour * 100 + minute; if (hm < 900) { return "早上"; } else if (hm < 1130) { return "上午"; } else if (hm < 1230) { return "中午"; } else if (hm < 1800) { return "下午"; } else { return "晚上"; } }, calendar : { sameDay : '[今天]LT', nextDay : '[明天]LT', nextWeek : '[下]ddddLT', lastDay : '[昨天]LT', lastWeek : '[上]ddddLT', sameElse : 'L' }, ordinal : function (number, period) { switch (period) { case "d" : case "D" : case "DDD" : return number + "日"; case "M" : return number + "月"; case "w" : case "W" : return number + "週"; default : return number; } }, relativeTime : { future : "%s內", past : "%s前", s : "幾秒", m : "一分鐘", mm : "%d分鐘", h : "一小時", hh : "%d小時", d : "一天", dd : "%d天", M : "一個月", MM : "%d個月", y : "一年", yy : "%d年" } }); }));
JavaScript
//! moment.js //! version : 2.5.1 //! authors : Tim Wood, Iskren Chernev, Moment.js contributors //! license : MIT //! momentjs.com (function (undefined) { /************************************ Constants ************************************/ var moment, VERSION = "2.5.1", global = this, round = Math.round, i, YEAR = 0, MONTH = 1, DATE = 2, HOUR = 3, MINUTE = 4, SECOND = 5, MILLISECOND = 6, // internal storage for language config files languages = {}, // moment internal properties momentProperties = { _isAMomentObject: null, _i : null, _f : null, _l : null, _strict : null, _isUTC : null, _offset : null, // optional. Combine with _isUTC _pf : null, _lang : null // optional }, // check for nodeJS hasModule = (typeof module !== 'undefined' && module.exports && typeof require !== 'undefined'), // ASP.NET json date format regex aspNetJsonRegex = /^\/?Date\((\-?\d+)/i, aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/, // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/, // format tokens formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|X|zz?|ZZ?|.)/g, localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g, // parsing token regexes parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99 parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999 parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999 parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999 parseTokenDigits = /\d+/, // nonzero number of digits parseTokenWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i, // any word (or two) characters or numbers including two/three word month in arabic. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z parseTokenT = /T/i, // T (ISO separator) parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123 //strict parsing regexes parseTokenOneDigit = /\d/, // 0 - 9 parseTokenTwoDigits = /\d\d/, // 00 - 99 parseTokenThreeDigits = /\d{3}/, // 000 - 999 parseTokenFourDigits = /\d{4}/, // 0000 - 9999 parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999 parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf // iso 8601 regex // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) isoRegex = /^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/, isoFormat = 'YYYY-MM-DDTHH:mm:ssZ', isoDates = [ ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/], ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/], ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/], ['GGGG-[W]WW', /\d{4}-W\d{2}/], ['YYYY-DDD', /\d{4}-\d{3}/] ], // iso time formats and regexes isoTimes = [ ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/], ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/], ['HH:mm', /(T| )\d\d:\d\d/], ['HH', /(T| )\d\d/] ], // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"] parseTimezoneChunker = /([\+\-]|\d\d)/gi, // getter and setter names proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'), unitMillisecondFactors = { 'Milliseconds' : 1, 'Seconds' : 1e3, 'Minutes' : 6e4, 'Hours' : 36e5, 'Days' : 864e5, 'Months' : 2592e6, 'Years' : 31536e6 }, unitAliases = { ms : 'millisecond', s : 'second', m : 'minute', h : 'hour', d : 'day', D : 'date', w : 'week', W : 'isoWeek', M : 'month', y : 'year', DDD : 'dayOfYear', e : 'weekday', E : 'isoWeekday', gg: 'weekYear', GG: 'isoWeekYear' }, camelFunctions = { dayofyear : 'dayOfYear', isoweekday : 'isoWeekday', isoweek : 'isoWeek', weekyear : 'weekYear', isoweekyear : 'isoWeekYear' }, // format function strings formatFunctions = {}, // tokens to ordinalize and pad ordinalizeTokens = 'DDD w W M D d'.split(' '), paddedTokens = 'M D H h m s w W'.split(' '), formatTokenFunctions = { M : function () { return this.month() + 1; }, MMM : function (format) { return this.lang().monthsShort(this, format); }, MMMM : function (format) { return this.lang().months(this, format); }, D : function () { return this.date(); }, DDD : function () { return this.dayOfYear(); }, d : function () { return this.day(); }, dd : function (format) { return this.lang().weekdaysMin(this, format); }, ddd : function (format) { return this.lang().weekdaysShort(this, format); }, dddd : function (format) { return this.lang().weekdays(this, format); }, w : function () { return this.week(); }, W : function () { return this.isoWeek(); }, YY : function () { return leftZeroFill(this.year() % 100, 2); }, YYYY : function () { return leftZeroFill(this.year(), 4); }, YYYYY : function () { return leftZeroFill(this.year(), 5); }, YYYYYY : function () { var y = this.year(), sign = y >= 0 ? '+' : '-'; return sign + leftZeroFill(Math.abs(y), 6); }, gg : function () { return leftZeroFill(this.weekYear() % 100, 2); }, gggg : function () { return leftZeroFill(this.weekYear(), 4); }, ggggg : function () { return leftZeroFill(this.weekYear(), 5); }, GG : function () { return leftZeroFill(this.isoWeekYear() % 100, 2); }, GGGG : function () { return leftZeroFill(this.isoWeekYear(), 4); }, GGGGG : function () { return leftZeroFill(this.isoWeekYear(), 5); }, e : function () { return this.weekday(); }, E : function () { return this.isoWeekday(); }, a : function () { return this.lang().meridiem(this.hours(), this.minutes(), true); }, A : function () { return this.lang().meridiem(this.hours(), this.minutes(), false); }, H : function () { return this.hours(); }, h : function () { return this.hours() % 12 || 12; }, m : function () { return this.minutes(); }, s : function () { return this.seconds(); }, S : function () { return toInt(this.milliseconds() / 100); }, SS : function () { return leftZeroFill(toInt(this.milliseconds() / 10), 2); }, SSS : function () { return leftZeroFill(this.milliseconds(), 3); }, SSSS : function () { return leftZeroFill(this.milliseconds(), 3); }, Z : function () { var a = -this.zone(), b = "+"; if (a < 0) { a = -a; b = "-"; } return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2); }, ZZ : function () { var a = -this.zone(), b = "+"; if (a < 0) { a = -a; b = "-"; } return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2); }, z : function () { return this.zoneAbbr(); }, zz : function () { return this.zoneName(); }, X : function () { return this.unix(); }, Q : function () { return this.quarter(); } }, lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin']; function defaultParsingFlags() { // We need to deep clone this object, and es5 standard is not very // helpful. return { empty : false, unusedTokens : [], unusedInput : [], overflow : -2, charsLeftOver : 0, nullInput : false, invalidMonth : null, invalidFormat : false, userInvalidated : false, iso: false }; } function padToken(func, count) { return function (a) { return leftZeroFill(func.call(this, a), count); }; } function ordinalizeToken(func, period) { return function (a) { return this.lang().ordinal(func.call(this, a), period); }; } while (ordinalizeTokens.length) { i = ordinalizeTokens.pop(); formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i); } while (paddedTokens.length) { i = paddedTokens.pop(); formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2); } formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3); /************************************ Constructors ************************************/ function Language() { } // Moment prototype object function Moment(config) { checkOverflow(config); extend(this, config); } // Duration Constructor function Duration(duration) { var normalizedInput = normalizeObjectUnits(duration), years = normalizedInput.year || 0, months = normalizedInput.month || 0, weeks = normalizedInput.week || 0, days = normalizedInput.day || 0, hours = normalizedInput.hour || 0, minutes = normalizedInput.minute || 0, seconds = normalizedInput.second || 0, milliseconds = normalizedInput.millisecond || 0; // representation for dateAddRemove this._milliseconds = +milliseconds + seconds * 1e3 + // 1000 minutes * 6e4 + // 1000 * 60 hours * 36e5; // 1000 * 60 * 60 // Because of dateAddRemove treats 24 hours as different from a // day when working around DST, we need to store them separately this._days = +days + weeks * 7; // It is impossible translate months into days without knowing // which months you are are talking about, so we have to store // it separately. this._months = +months + years * 12; this._data = {}; this._bubble(); } /************************************ Helpers ************************************/ function extend(a, b) { for (var i in b) { if (b.hasOwnProperty(i)) { a[i] = b[i]; } } if (b.hasOwnProperty("toString")) { a.toString = b.toString; } if (b.hasOwnProperty("valueOf")) { a.valueOf = b.valueOf; } return a; } function cloneMoment(m) { var result = {}, i; for (i in m) { if (m.hasOwnProperty(i) && momentProperties.hasOwnProperty(i)) { result[i] = m[i]; } } return result; } function absRound(number) { if (number < 0) { return Math.ceil(number); } else { return Math.floor(number); } } // left zero fill a number // see http://jsperf.com/left-zero-filling for performance comparison function leftZeroFill(number, targetLength, forceSign) { var output = '' + Math.abs(number), sign = number >= 0; while (output.length < targetLength) { output = '0' + output; } return (sign ? (forceSign ? '+' : '') : '-') + output; } // helper function for _.addTime and _.subtractTime function addOrSubtractDurationFromMoment(mom, duration, isAdding, ignoreUpdateOffset) { var milliseconds = duration._milliseconds, days = duration._days, months = duration._months, minutes, hours; if (milliseconds) { mom._d.setTime(+mom._d + milliseconds * isAdding); } // store the minutes and hours so we can restore them if (days || months) { minutes = mom.minute(); hours = mom.hour(); } if (days) { mom.date(mom.date() + days * isAdding); } if (months) { mom.month(mom.month() + months * isAdding); } if (milliseconds && !ignoreUpdateOffset) { moment.updateOffset(mom); } // restore the minutes and hours after possibly changing dst if (days || months) { mom.minute(minutes); mom.hour(hours); } } // check if is an array function isArray(input) { return Object.prototype.toString.call(input) === '[object Array]'; } function isDate(input) { return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date; } // compare two arrays, return the number of differences function compareArrays(array1, array2, dontConvert) { var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i; for (i = 0; i < len; i++) { if ((dontConvert && array1[i] !== array2[i]) || (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { diffs++; } } return diffs + lengthDiff; } function normalizeUnits(units) { if (units) { var lowered = units.toLowerCase().replace(/(.)s$/, '$1'); units = unitAliases[units] || camelFunctions[lowered] || lowered; } return units; } function normalizeObjectUnits(inputObject) { var normalizedInput = {}, normalizedProp, prop; for (prop in inputObject) { if (inputObject.hasOwnProperty(prop)) { normalizedProp = normalizeUnits(prop); if (normalizedProp) { normalizedInput[normalizedProp] = inputObject[prop]; } } } return normalizedInput; } function makeList(field) { var count, setter; if (field.indexOf('week') === 0) { count = 7; setter = 'day'; } else if (field.indexOf('month') === 0) { count = 12; setter = 'month'; } else { return; } moment[field] = function (format, index) { var i, getter, method = moment.fn._lang[field], results = []; if (typeof format === 'number') { index = format; format = undefined; } getter = function (i) { var m = moment().utc().set(setter, i); return method.call(moment.fn._lang, m, format || ''); }; if (index != null) { return getter(index); } else { for (i = 0; i < count; i++) { results.push(getter(i)); } return results; } }; } function toInt(argumentForCoercion) { var coercedNumber = +argumentForCoercion, value = 0; if (coercedNumber !== 0 && isFinite(coercedNumber)) { if (coercedNumber >= 0) { value = Math.floor(coercedNumber); } else { value = Math.ceil(coercedNumber); } } return value; } function daysInMonth(year, month) { return new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); } function daysInYear(year) { return isLeapYear(year) ? 366 : 365; } function isLeapYear(year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } function checkOverflow(m) { var overflow; if (m._a && m._pf.overflow === -2) { overflow = m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH : m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE : m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR : m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE : m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND : m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND : -1; if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { overflow = DATE; } m._pf.overflow = overflow; } } function isValid(m) { if (m._isValid == null) { m._isValid = !isNaN(m._d.getTime()) && m._pf.overflow < 0 && !m._pf.empty && !m._pf.invalidMonth && !m._pf.nullInput && !m._pf.invalidFormat && !m._pf.userInvalidated; if (m._strict) { m._isValid = m._isValid && m._pf.charsLeftOver === 0 && m._pf.unusedTokens.length === 0; } } return m._isValid; } function normalizeLanguage(key) { return key ? key.toLowerCase().replace('_', '-') : key; } // Return a moment from input, that is local/utc/zone equivalent to model. function makeAs(input, model) { return model._isUTC ? moment(input).zone(model._offset || 0) : moment(input).local(); } /************************************ Languages ************************************/ extend(Language.prototype, { set : function (config) { var prop, i; for (i in config) { prop = config[i]; if (typeof prop === 'function') { this[i] = prop; } else { this['_' + i] = prop; } } }, _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), months : function (m) { return this._months[m.month()]; }, _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), monthsShort : function (m) { return this._monthsShort[m.month()]; }, monthsParse : function (monthName) { var i, mom, regex; if (!this._monthsParse) { this._monthsParse = []; } for (i = 0; i < 12; i++) { // make the regex if we don't have it already if (!this._monthsParse[i]) { mom = moment.utc([2000, i]); regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._monthsParse[i].test(monthName)) { return i; } } }, _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), weekdays : function (m) { return this._weekdays[m.day()]; }, _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), weekdaysShort : function (m) { return this._weekdaysShort[m.day()]; }, _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), weekdaysMin : function (m) { return this._weekdaysMin[m.day()]; }, weekdaysParse : function (weekdayName) { var i, mom, regex; if (!this._weekdaysParse) { this._weekdaysParse = []; } for (i = 0; i < 7; i++) { // make the regex if we don't have it already if (!this._weekdaysParse[i]) { mom = moment([2000, 1]).day(i); regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._weekdaysParse[i].test(weekdayName)) { return i; } } }, _longDateFormat : { LT : "h:mm A", L : "MM/DD/YYYY", LL : "MMMM D YYYY", LLL : "MMMM D YYYY LT", LLLL : "dddd, MMMM D YYYY LT" }, longDateFormat : function (key) { var output = this._longDateFormat[key]; if (!output && this._longDateFormat[key.toUpperCase()]) { output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) { return val.slice(1); }); this._longDateFormat[key] = output; } return output; }, isPM : function (input) { // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays // Using charAt should be more compatible. return ((input + '').toLowerCase().charAt(0) === 'p'); }, _meridiemParse : /[ap]\.?m?\.?/i, meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'pm' : 'PM'; } else { return isLower ? 'am' : 'AM'; } }, _calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, calendar : function (key, mom) { var output = this._calendar[key]; return typeof output === 'function' ? output.apply(mom) : output; }, _relativeTime : { future : "in %s", past : "%s ago", s : "a few seconds", m : "a minute", mm : "%d minutes", h : "an hour", hh : "%d hours", d : "a day", dd : "%d days", M : "a month", MM : "%d months", y : "a year", yy : "%d years" }, relativeTime : function (number, withoutSuffix, string, isFuture) { var output = this._relativeTime[string]; return (typeof output === 'function') ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number); }, pastFuture : function (diff, output) { var format = this._relativeTime[diff > 0 ? 'future' : 'past']; return typeof format === 'function' ? format(output) : format.replace(/%s/i, output); }, ordinal : function (number) { return this._ordinal.replace("%d", number); }, _ordinal : "%d", preparse : function (string) { return string; }, postformat : function (string) { return string; }, week : function (mom) { return weekOfYear(mom, this._week.dow, this._week.doy).week; }, _week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. }, _invalidDate: 'Invalid date', invalidDate: function () { return this._invalidDate; } }); // Loads a language definition into the `languages` cache. The function // takes a key and optionally values. If not in the browser and no values // are provided, it will load the language file module. As a convenience, // this function also returns the language values. function loadLang(key, values) { values.abbr = key; if (!languages[key]) { languages[key] = new Language(); } languages[key].set(values); return languages[key]; } // Remove a language from the `languages` cache. Mostly useful in tests. function unloadLang(key) { delete languages[key]; } // Determines which language definition to use and returns it. // // With no parameters, it will return the global language. If you // pass in a language key, such as 'en', it will return the // definition for 'en', so long as 'en' has already been loaded using // moment.lang. function getLangDefinition(key) { var i = 0, j, lang, next, split, get = function (k) { if (!languages[k] && hasModule) { try { require('./lang/' + k); } catch (e) { } } return languages[k]; }; if (!key) { return moment.fn._lang; } if (!isArray(key)) { //short-circuit everything else lang = get(key); if (lang) { return lang; } key = [key]; } //pick the language from the array //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root while (i < key.length) { split = normalizeLanguage(key[i]).split('-'); j = split.length; next = normalizeLanguage(key[i + 1]); next = next ? next.split('-') : null; while (j > 0) { lang = get(split.slice(0, j).join('-')); if (lang) { return lang; } if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { //the next array item is better than a shallower substring of this one break; } j--; } i++; } return moment.fn._lang; } /************************************ Formatting ************************************/ function removeFormattingTokens(input) { if (input.match(/\[[\s\S]/)) { return input.replace(/^\[|\]$/g, ""); } return input.replace(/\\/g, ""); } function makeFormatFunction(format) { var array = format.match(formattingTokens), i, length; for (i = 0, length = array.length; i < length; i++) { if (formatTokenFunctions[array[i]]) { array[i] = formatTokenFunctions[array[i]]; } else { array[i] = removeFormattingTokens(array[i]); } } return function (mom) { var output = ""; for (i = 0; i < length; i++) { output += array[i] instanceof Function ? array[i].call(mom, format) : array[i]; } return output; }; } // format date using native date object function formatMoment(m, format) { if (!m.isValid()) { return m.lang().invalidDate(); } format = expandFormat(format, m.lang()); if (!formatFunctions[format]) { formatFunctions[format] = makeFormatFunction(format); } return formatFunctions[format](m); } function expandFormat(format, lang) { var i = 5; function replaceLongDateFormatTokens(input) { return lang.longDateFormat(input) || input; } localFormattingTokens.lastIndex = 0; while (i >= 0 && localFormattingTokens.test(format)) { format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); localFormattingTokens.lastIndex = 0; i -= 1; } return format; } /************************************ Parsing ************************************/ // get the regex to find the next token function getParseRegexForToken(token, config) { var a, strict = config._strict; switch (token) { case 'DDDD': return parseTokenThreeDigits; case 'YYYY': case 'GGGG': case 'gggg': return strict ? parseTokenFourDigits : parseTokenOneToFourDigits; case 'Y': case 'G': case 'g': return parseTokenSignedNumber; case 'YYYYYY': case 'YYYYY': case 'GGGGG': case 'ggggg': return strict ? parseTokenSixDigits : parseTokenOneToSixDigits; case 'S': if (strict) { return parseTokenOneDigit; } /* falls through */ case 'SS': if (strict) { return parseTokenTwoDigits; } /* falls through */ case 'SSS': if (strict) { return parseTokenThreeDigits; } /* falls through */ case 'DDD': return parseTokenOneToThreeDigits; case 'MMM': case 'MMMM': case 'dd': case 'ddd': case 'dddd': return parseTokenWord; case 'a': case 'A': return getLangDefinition(config._l)._meridiemParse; case 'X': return parseTokenTimestampMs; case 'Z': case 'ZZ': return parseTokenTimezone; case 'T': return parseTokenT; case 'SSSS': return parseTokenDigits; case 'MM': case 'DD': case 'YY': case 'GG': case 'gg': case 'HH': case 'hh': case 'mm': case 'ss': case 'ww': case 'WW': return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits; case 'M': case 'D': case 'd': case 'H': case 'h': case 'm': case 's': case 'w': case 'W': case 'e': case 'E': return parseTokenOneOrTwoDigits; default : a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i")); return a; } } function timezoneMinutesFromString(string) { string = string || ""; var possibleTzMatches = (string.match(parseTokenTimezone) || []), tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [], parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0], minutes = +(parts[1] * 60) + toInt(parts[2]); return parts[0] === '+' ? -minutes : minutes; } // function to convert string input to date function addTimeToArrayFromToken(token, input, config) { var a, datePartArray = config._a; switch (token) { // MONTH case 'M' : // fall through to MM case 'MM' : if (input != null) { datePartArray[MONTH] = toInt(input) - 1; } break; case 'MMM' : // fall through to MMMM case 'MMMM' : a = getLangDefinition(config._l).monthsParse(input); // if we didn't find a month name, mark the date as invalid. if (a != null) { datePartArray[MONTH] = a; } else { config._pf.invalidMonth = input; } break; // DAY OF MONTH case 'D' : // fall through to DD case 'DD' : if (input != null) { datePartArray[DATE] = toInt(input); } break; // DAY OF YEAR case 'DDD' : // fall through to DDDD case 'DDDD' : if (input != null) { config._dayOfYear = toInt(input); } break; // YEAR case 'YY' : datePartArray[YEAR] = toInt(input) + (toInt(input) > 68 ? 1900 : 2000); break; case 'YYYY' : case 'YYYYY' : case 'YYYYYY' : datePartArray[YEAR] = toInt(input); break; // AM / PM case 'a' : // fall through to A case 'A' : config._isPm = getLangDefinition(config._l).isPM(input); break; // 24 HOUR case 'H' : // fall through to hh case 'HH' : // fall through to hh case 'h' : // fall through to hh case 'hh' : datePartArray[HOUR] = toInt(input); break; // MINUTE case 'm' : // fall through to mm case 'mm' : datePartArray[MINUTE] = toInt(input); break; // SECOND case 's' : // fall through to ss case 'ss' : datePartArray[SECOND] = toInt(input); break; // MILLISECOND case 'S' : case 'SS' : case 'SSS' : case 'SSSS' : datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000); break; // UNIX TIMESTAMP WITH MS case 'X': config._d = new Date(parseFloat(input) * 1000); break; // TIMEZONE case 'Z' : // fall through to ZZ case 'ZZ' : config._useUTC = true; config._tzm = timezoneMinutesFromString(input); break; case 'w': case 'ww': case 'W': case 'WW': case 'd': case 'dd': case 'ddd': case 'dddd': case 'e': case 'E': token = token.substr(0, 1); /* falls through */ case 'gg': case 'gggg': case 'GG': case 'GGGG': case 'GGGGG': token = token.substr(0, 2); if (input) { config._w = config._w || {}; config._w[token] = input; } break; } } // convert an array to a date. // the array should mirror the parameters below // note: all values past the year are optional and will default to the lowest possible value. // [year, month, day , hour, minute, second, millisecond] function dateFromConfig(config) { var i, date, input = [], currentDate, yearToUse, fixYear, w, temp, lang, weekday, week; if (config._d) { return; } currentDate = currentDateArray(config); //compute day of the year from weeks and weekdays if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { fixYear = function (val) { var int_val = parseInt(val, 10); return val ? (val.length < 3 ? (int_val > 68 ? 1900 + int_val : 2000 + int_val) : int_val) : (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]); }; w = config._w; if (w.GG != null || w.W != null || w.E != null) { temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1); } else { lang = getLangDefinition(config._l); weekday = w.d != null ? parseWeekday(w.d, lang) : (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0); week = parseInt(w.w, 10) || 1; //if we're parsing 'd', then the low day numbers may be next week if (w.d != null && weekday < lang._week.dow) { week++; } temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow); } config._a[YEAR] = temp.year; config._dayOfYear = temp.dayOfYear; } //if the day of the year is set, figure out what it is if (config._dayOfYear) { yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR]; if (config._dayOfYear > daysInYear(yearToUse)) { config._pf._overflowDayOfYear = true; } date = makeUTCDate(yearToUse, 0, config._dayOfYear); config._a[MONTH] = date.getUTCMonth(); config._a[DATE] = date.getUTCDate(); } // Default to current date. // * if no year, month, day of month are given, default to today // * if day of month is given, default month and year // * if month is given, default only year // * if year is given, don't default anything for (i = 0; i < 3 && config._a[i] == null; ++i) { config._a[i] = input[i] = currentDate[i]; } // Zero out whatever was not defaulted, including time for (; i < 7; i++) { config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; } // add the offsets to the time to be parsed so that we can have a clean array for checking isValid input[HOUR] += toInt((config._tzm || 0) / 60); input[MINUTE] += toInt((config._tzm || 0) % 60); config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input); } function dateFromObject(config) { var normalizedInput; if (config._d) { return; } normalizedInput = normalizeObjectUnits(config._i); config._a = [ normalizedInput.year, normalizedInput.month, normalizedInput.day, normalizedInput.hour, normalizedInput.minute, normalizedInput.second, normalizedInput.millisecond ]; dateFromConfig(config); } function currentDateArray(config) { var now = new Date(); if (config._useUTC) { return [ now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() ]; } else { return [now.getFullYear(), now.getMonth(), now.getDate()]; } } // date from string and format string function makeDateFromStringAndFormat(config) { config._a = []; config._pf.empty = true; // This array is used to make a Date, either with `new Date` or `Date.UTC` var lang = getLangDefinition(config._l), string = '' + config._i, i, parsedInput, tokens, token, skipped, stringLength = string.length, totalParsedInputLength = 0; tokens = expandFormat(config._f, lang).match(formattingTokens) || []; for (i = 0; i < tokens.length; i++) { token = tokens[i]; parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; if (parsedInput) { skipped = string.substr(0, string.indexOf(parsedInput)); if (skipped.length > 0) { config._pf.unusedInput.push(skipped); } string = string.slice(string.indexOf(parsedInput) + parsedInput.length); totalParsedInputLength += parsedInput.length; } // don't parse if it's not a known token if (formatTokenFunctions[token]) { if (parsedInput) { config._pf.empty = false; } else { config._pf.unusedTokens.push(token); } addTimeToArrayFromToken(token, parsedInput, config); } else if (config._strict && !parsedInput) { config._pf.unusedTokens.push(token); } } // add remaining unparsed input length to the string config._pf.charsLeftOver = stringLength - totalParsedInputLength; if (string.length > 0) { config._pf.unusedInput.push(string); } // handle am pm if (config._isPm && config._a[HOUR] < 12) { config._a[HOUR] += 12; } // if is 12 am, change hours to 0 if (config._isPm === false && config._a[HOUR] === 12) { config._a[HOUR] = 0; } dateFromConfig(config); checkOverflow(config); } function unescapeFormat(s) { return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { return p1 || p2 || p3 || p4; }); } // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript function regexpEscape(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); } // date from string and array of format strings function makeDateFromStringAndArray(config) { var tempConfig, bestMoment, scoreToBeat, i, currentScore; if (config._f.length === 0) { config._pf.invalidFormat = true; config._d = new Date(NaN); return; } for (i = 0; i < config._f.length; i++) { currentScore = 0; tempConfig = extend({}, config); tempConfig._pf = defaultParsingFlags(); tempConfig._f = config._f[i]; makeDateFromStringAndFormat(tempConfig); if (!isValid(tempConfig)) { continue; } // if there is any input that was not parsed add a penalty for that format currentScore += tempConfig._pf.charsLeftOver; //or tokens currentScore += tempConfig._pf.unusedTokens.length * 10; tempConfig._pf.score = currentScore; if (scoreToBeat == null || currentScore < scoreToBeat) { scoreToBeat = currentScore; bestMoment = tempConfig; } } extend(config, bestMoment || tempConfig); } // date from iso format function makeDateFromString(config) { var i, l, string = config._i, match = isoRegex.exec(string); if (match) { config._pf.iso = true; for (i = 0, l = isoDates.length; i < l; i++) { if (isoDates[i][1].exec(string)) { // match[5] should be "T" or undefined config._f = isoDates[i][0] + (match[6] || " "); break; } } for (i = 0, l = isoTimes.length; i < l; i++) { if (isoTimes[i][1].exec(string)) { config._f += isoTimes[i][0]; break; } } if (string.match(parseTokenTimezone)) { config._f += "Z"; } makeDateFromStringAndFormat(config); } else { config._d = new Date(string); } } function makeDateFromInput(config) { var input = config._i, matched = aspNetJsonRegex.exec(input); if (input === undefined) { config._d = new Date(); } else if (matched) { config._d = new Date(+matched[1]); } else if (typeof input === 'string') { makeDateFromString(config); } else if (isArray(input)) { config._a = input.slice(0); dateFromConfig(config); } else if (isDate(input)) { config._d = new Date(+input); } else if (typeof(input) === 'object') { dateFromObject(config); } else { config._d = new Date(input); } } function makeDate(y, m, d, h, M, s, ms) { //can't just apply() to create a date: //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply var date = new Date(y, m, d, h, M, s, ms); //the date constructor doesn't accept years < 1970 if (y < 1970) { date.setFullYear(y); } return date; } function makeUTCDate(y) { var date = new Date(Date.UTC.apply(null, arguments)); if (y < 1970) { date.setUTCFullYear(y); } return date; } function parseWeekday(input, language) { if (typeof input === 'string') { if (!isNaN(input)) { input = parseInt(input, 10); } else { input = language.weekdaysParse(input); if (typeof input !== 'number') { return null; } } } return input; } /************************************ Relative Time ************************************/ // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) { return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture); } function relativeTime(milliseconds, withoutSuffix, lang) { var seconds = round(Math.abs(milliseconds) / 1000), minutes = round(seconds / 60), hours = round(minutes / 60), days = round(hours / 24), years = round(days / 365), args = seconds < 45 && ['s', seconds] || minutes === 1 && ['m'] || minutes < 45 && ['mm', minutes] || hours === 1 && ['h'] || hours < 22 && ['hh', hours] || days === 1 && ['d'] || days <= 25 && ['dd', days] || days <= 45 && ['M'] || days < 345 && ['MM', round(days / 30)] || years === 1 && ['y'] || ['yy', years]; args[2] = withoutSuffix; args[3] = milliseconds > 0; args[4] = lang; return substituteTimeAgo.apply({}, args); } /************************************ Week of Year ************************************/ // firstDayOfWeek 0 = sun, 6 = sat // the day of the week that starts the week // (usually sunday or monday) // firstDayOfWeekOfYear 0 = sun, 6 = sat // the first week is the week that contains the first // of this day of the week // (eg. ISO weeks use thursday (4)) function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) { var end = firstDayOfWeekOfYear - firstDayOfWeek, daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(), adjustedMoment; if (daysToDayOfWeek > end) { daysToDayOfWeek -= 7; } if (daysToDayOfWeek < end - 7) { daysToDayOfWeek += 7; } adjustedMoment = moment(mom).add('d', daysToDayOfWeek); return { week: Math.ceil(adjustedMoment.dayOfYear() / 7), year: adjustedMoment.year() }; } //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) { var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear; weekday = weekday != null ? weekday : firstDayOfWeek; daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0); dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1; return { year: dayOfYear > 0 ? year : year - 1, dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear }; } /************************************ Top Level Functions ************************************/ function makeMoment(config) { var input = config._i, format = config._f; if (input === null) { return moment.invalid({nullInput: true}); } if (typeof input === 'string') { config._i = input = getLangDefinition().preparse(input); } if (moment.isMoment(input)) { config = cloneMoment(input); config._d = new Date(+input._d); } else if (format) { if (isArray(format)) { makeDateFromStringAndArray(config); } else { makeDateFromStringAndFormat(config); } } else { makeDateFromInput(config); } return new Moment(config); } moment = function (input, format, lang, strict) { var c; if (typeof(lang) === "boolean") { strict = lang; lang = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c = {}; c._isAMomentObject = true; c._i = input; c._f = format; c._l = lang; c._strict = strict; c._isUTC = false; c._pf = defaultParsingFlags(); return makeMoment(c); }; // creating with utc moment.utc = function (input, format, lang, strict) { var c; if (typeof(lang) === "boolean") { strict = lang; lang = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c = {}; c._isAMomentObject = true; c._useUTC = true; c._isUTC = true; c._l = lang; c._i = input; c._f = format; c._strict = strict; c._pf = defaultParsingFlags(); return makeMoment(c).utc(); }; // creating with unix timestamp (in seconds) moment.unix = function (input) { return moment(input * 1000); }; // duration moment.duration = function (input, key) { var duration = input, // matching against regexp is expensive, do it on demand match = null, sign, ret, parseIso; if (moment.isDuration(input)) { duration = { ms: input._milliseconds, d: input._days, M: input._months }; } else if (typeof input === 'number') { duration = {}; if (key) { duration[key] = input; } else { duration.milliseconds = input; } } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) { sign = (match[1] === "-") ? -1 : 1; duration = { y: 0, d: toInt(match[DATE]) * sign, h: toInt(match[HOUR]) * sign, m: toInt(match[MINUTE]) * sign, s: toInt(match[SECOND]) * sign, ms: toInt(match[MILLISECOND]) * sign }; } else if (!!(match = isoDurationRegex.exec(input))) { sign = (match[1] === "-") ? -1 : 1; parseIso = function (inp) { // We'd normally use ~~inp for this, but unfortunately it also // converts floats to ints. // inp may be undefined, so careful calling replace on it. var res = inp && parseFloat(inp.replace(',', '.')); // apply sign while we're at it return (isNaN(res) ? 0 : res) * sign; }; duration = { y: parseIso(match[2]), M: parseIso(match[3]), d: parseIso(match[4]), h: parseIso(match[5]), m: parseIso(match[6]), s: parseIso(match[7]), w: parseIso(match[8]) }; } ret = new Duration(duration); if (moment.isDuration(input) && input.hasOwnProperty('_lang')) { ret._lang = input._lang; } return ret; }; // version number moment.version = VERSION; // default format moment.defaultFormat = isoFormat; // This function will be called whenever a moment is mutated. // It is intended to keep the offset in sync with the timezone. moment.updateOffset = function () {}; // This function will load languages and then set the global language. If // no arguments are passed in, it will simply return the current global // language key. moment.lang = function (key, values) { var r; if (!key) { return moment.fn._lang._abbr; } if (values) { loadLang(normalizeLanguage(key), values); } else if (values === null) { unloadLang(key); key = 'en'; } else if (!languages[key]) { getLangDefinition(key); } r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key); return r._abbr; }; // returns language data moment.langData = function (key) { if (key && key._lang && key._lang._abbr) { key = key._lang._abbr; } return getLangDefinition(key); }; // compare moment object moment.isMoment = function (obj) { return obj instanceof Moment || (obj != null && obj.hasOwnProperty('_isAMomentObject')); }; // for typechecking Duration objects moment.isDuration = function (obj) { return obj instanceof Duration; }; for (i = lists.length - 1; i >= 0; --i) { makeList(lists[i]); } moment.normalizeUnits = function (units) { return normalizeUnits(units); }; moment.invalid = function (flags) { var m = moment.utc(NaN); if (flags != null) { extend(m._pf, flags); } else { m._pf.userInvalidated = true; } return m; }; moment.parseZone = function (input) { return moment(input).parseZone(); }; /************************************ Moment Prototype ************************************/ extend(moment.fn = Moment.prototype, { clone : function () { return moment(this); }, valueOf : function () { return +this._d + ((this._offset || 0) * 60000); }, unix : function () { return Math.floor(+this / 1000); }, toString : function () { return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ"); }, toDate : function () { return this._offset ? new Date(+this) : this._d; }, toISOString : function () { var m = moment(this).utc(); if (0 < m.year() && m.year() <= 9999) { return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } else { return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } }, toArray : function () { var m = this; return [ m.year(), m.month(), m.date(), m.hours(), m.minutes(), m.seconds(), m.milliseconds() ]; }, isValid : function () { return isValid(this); }, isDSTShifted : function () { if (this._a) { return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0; } return false; }, parsingFlags : function () { return extend({}, this._pf); }, invalidAt: function () { return this._pf.overflow; }, utc : function () { return this.zone(0); }, local : function () { this.zone(0); this._isUTC = false; return this; }, format : function (inputString) { var output = formatMoment(this, inputString || moment.defaultFormat); return this.lang().postformat(output); }, add : function (input, val) { var dur; // switch args to support add('s', 1) and add(1, 's') if (typeof input === 'string') { dur = moment.duration(+val, input); } else { dur = moment.duration(input, val); } addOrSubtractDurationFromMoment(this, dur, 1); return this; }, subtract : function (input, val) { var dur; // switch args to support subtract('s', 1) and subtract(1, 's') if (typeof input === 'string') { dur = moment.duration(+val, input); } else { dur = moment.duration(input, val); } addOrSubtractDurationFromMoment(this, dur, -1); return this; }, diff : function (input, units, asFloat) { var that = makeAs(input, this), zoneDiff = (this.zone() - that.zone()) * 6e4, diff, output; units = normalizeUnits(units); if (units === 'year' || units === 'month') { // average number of days in the months in the given dates diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2 // difference in months output = ((this.year() - that.year()) * 12) + (this.month() - that.month()); // adjust by taking difference in days, average number of days // and dst in the given months. output += ((this - moment(this).startOf('month')) - (that - moment(that).startOf('month'))) / diff; // same as above but with zones, to negate all dst output -= ((this.zone() - moment(this).startOf('month').zone()) - (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff; if (units === 'year') { output = output / 12; } } else { diff = (this - that); output = units === 'second' ? diff / 1e3 : // 1000 units === 'minute' ? diff / 6e4 : // 1000 * 60 units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60 units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst diff; } return asFloat ? output : absRound(output); }, from : function (time, withoutSuffix) { return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix); }, fromNow : function (withoutSuffix) { return this.from(moment(), withoutSuffix); }, calendar : function () { // We want to compare the start of today, vs this. // Getting start-of-today depends on whether we're zone'd or not. var sod = makeAs(moment(), this).startOf('day'), diff = this.diff(sod, 'days', true), format = diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse'; return this.format(this.lang().calendar(format, this)); }, isLeapYear : function () { return isLeapYear(this.year()); }, isDST : function () { return (this.zone() < this.clone().month(0).zone() || this.zone() < this.clone().month(5).zone()); }, day : function (input) { var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); if (input != null) { input = parseWeekday(input, this.lang()); return this.add({ d : input - day }); } else { return day; } }, month : function (input) { var utc = this._isUTC ? 'UTC' : '', dayOfMonth; if (input != null) { if (typeof input === 'string') { input = this.lang().monthsParse(input); if (typeof input !== 'number') { return this; } } dayOfMonth = this.date(); this.date(1); this._d['set' + utc + 'Month'](input); this.date(Math.min(dayOfMonth, this.daysInMonth())); moment.updateOffset(this); return this; } else { return this._d['get' + utc + 'Month'](); } }, startOf: function (units) { units = normalizeUnits(units); // the following switch intentionally omits break keywords // to utilize falling through the cases. switch (units) { case 'year': this.month(0); /* falls through */ case 'month': this.date(1); /* falls through */ case 'week': case 'isoWeek': case 'day': this.hours(0); /* falls through */ case 'hour': this.minutes(0); /* falls through */ case 'minute': this.seconds(0); /* falls through */ case 'second': this.milliseconds(0); /* falls through */ } // weeks are a special case if (units === 'week') { this.weekday(0); } else if (units === 'isoWeek') { this.isoWeekday(1); } return this; }, endOf: function (units) { units = normalizeUnits(units); return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1); }, isAfter: function (input, units) { units = typeof units !== 'undefined' ? units : 'millisecond'; return +this.clone().startOf(units) > +moment(input).startOf(units); }, isBefore: function (input, units) { units = typeof units !== 'undefined' ? units : 'millisecond'; return +this.clone().startOf(units) < +moment(input).startOf(units); }, isSame: function (input, units) { units = units || 'ms'; return +this.clone().startOf(units) === +makeAs(input, this).startOf(units); }, min: function (other) { other = moment.apply(null, arguments); return other < this ? this : other; }, max: function (other) { other = moment.apply(null, arguments); return other > this ? this : other; }, zone : function (input) { var offset = this._offset || 0; if (input != null) { if (typeof input === "string") { input = timezoneMinutesFromString(input); } if (Math.abs(input) < 16) { input = input * 60; } this._offset = input; this._isUTC = true; if (offset !== input) { addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, true); } } else { return this._isUTC ? offset : this._d.getTimezoneOffset(); } return this; }, zoneAbbr : function () { return this._isUTC ? "UTC" : ""; }, zoneName : function () { return this._isUTC ? "Coordinated Universal Time" : ""; }, parseZone : function () { if (this._tzm) { this.zone(this._tzm); } else if (typeof this._i === 'string') { this.zone(this._i); } return this; }, hasAlignedHourOffset : function (input) { if (!input) { input = 0; } else { input = moment(input).zone(); } return (this.zone() - input) % 60 === 0; }, daysInMonth : function () { return daysInMonth(this.year(), this.month()); }, dayOfYear : function (input) { var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1; return input == null ? dayOfYear : this.add("d", (input - dayOfYear)); }, quarter : function () { return Math.ceil((this.month() + 1.0) / 3.0); }, weekYear : function (input) { var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year; return input == null ? year : this.add("y", (input - year)); }, isoWeekYear : function (input) { var year = weekOfYear(this, 1, 4).year; return input == null ? year : this.add("y", (input - year)); }, week : function (input) { var week = this.lang().week(this); return input == null ? week : this.add("d", (input - week) * 7); }, isoWeek : function (input) { var week = weekOfYear(this, 1, 4).week; return input == null ? week : this.add("d", (input - week) * 7); }, weekday : function (input) { var weekday = (this.day() + 7 - this.lang()._week.dow) % 7; return input == null ? weekday : this.add("d", input - weekday); }, isoWeekday : function (input) { // behaves the same as moment#day except // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) // as a setter, sunday should belong to the previous week. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7); }, get : function (units) { units = normalizeUnits(units); return this[units](); }, set : function (units, value) { units = normalizeUnits(units); if (typeof this[units] === 'function') { this[units](value); } return this; }, // If passed a language key, it will set the language for this // instance. Otherwise, it will return the language configuration // variables for this instance. lang : function (key) { if (key === undefined) { return this._lang; } else { this._lang = getLangDefinition(key); return this; } } }); // helper for adding shortcuts function makeGetterAndSetter(name, key) { moment.fn[name] = moment.fn[name + 's'] = function (input) { var utc = this._isUTC ? 'UTC' : ''; if (input != null) { this._d['set' + utc + key](input); moment.updateOffset(this); return this; } else { return this._d['get' + utc + key](); } }; } // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds) for (i = 0; i < proxyGettersAndSetters.length; i ++) { makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]); } // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear') makeGetterAndSetter('year', 'FullYear'); // add plural methods moment.fn.days = moment.fn.day; moment.fn.months = moment.fn.month; moment.fn.weeks = moment.fn.week; moment.fn.isoWeeks = moment.fn.isoWeek; // add aliased format methods moment.fn.toJSON = moment.fn.toISOString; /************************************ Duration Prototype ************************************/ extend(moment.duration.fn = Duration.prototype, { _bubble : function () { var milliseconds = this._milliseconds, days = this._days, months = this._months, data = this._data, seconds, minutes, hours, years; // The following code bubbles up values, see the tests for // examples of what that means. data.milliseconds = milliseconds % 1000; seconds = absRound(milliseconds / 1000); data.seconds = seconds % 60; minutes = absRound(seconds / 60); data.minutes = minutes % 60; hours = absRound(minutes / 60); data.hours = hours % 24; days += absRound(hours / 24); data.days = days % 30; months += absRound(days / 30); data.months = months % 12; years = absRound(months / 12); data.years = years; }, weeks : function () { return absRound(this.days() / 7); }, valueOf : function () { return this._milliseconds + this._days * 864e5 + (this._months % 12) * 2592e6 + toInt(this._months / 12) * 31536e6; }, humanize : function (withSuffix) { var difference = +this, output = relativeTime(difference, !withSuffix, this.lang()); if (withSuffix) { output = this.lang().pastFuture(difference, output); } return this.lang().postformat(output); }, add : function (input, val) { // supports only 2.0-style add(1, 's') or add(moment) var dur = moment.duration(input, val); this._milliseconds += dur._milliseconds; this._days += dur._days; this._months += dur._months; this._bubble(); return this; }, subtract : function (input, val) { var dur = moment.duration(input, val); this._milliseconds -= dur._milliseconds; this._days -= dur._days; this._months -= dur._months; this._bubble(); return this; }, get : function (units) { units = normalizeUnits(units); return this[units.toLowerCase() + 's'](); }, as : function (units) { units = normalizeUnits(units); return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's'](); }, lang : moment.fn.lang, toIsoString : function () { // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js var years = Math.abs(this.years()), months = Math.abs(this.months()), days = Math.abs(this.days()), hours = Math.abs(this.hours()), minutes = Math.abs(this.minutes()), seconds = Math.abs(this.seconds() + this.milliseconds() / 1000); if (!this.asSeconds()) { // this is the same as C#'s (Noda) and python (isodate)... // but not other JS (goog.date) return 'P0D'; } return (this.asSeconds() < 0 ? '-' : '') + 'P' + (years ? years + 'Y' : '') + (months ? months + 'M' : '') + (days ? days + 'D' : '') + ((hours || minutes || seconds) ? 'T' : '') + (hours ? hours + 'H' : '') + (minutes ? minutes + 'M' : '') + (seconds ? seconds + 'S' : ''); } }); function makeDurationGetter(name) { moment.duration.fn[name] = function () { return this._data[name]; }; } function makeDurationAsGetter(name, factor) { moment.duration.fn['as' + name] = function () { return +this / factor; }; } for (i in unitMillisecondFactors) { if (unitMillisecondFactors.hasOwnProperty(i)) { makeDurationAsGetter(i, unitMillisecondFactors[i]); makeDurationGetter(i.toLowerCase()); } } makeDurationAsGetter('Weeks', 6048e5); moment.duration.fn.asMonths = function () { return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12; }; /************************************ Default Lang ************************************/ // Set default language, other languages will inherit from English. moment.lang('en', { ordinal : function (number) { var b = number % 10, output = (toInt(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); // moment.js language configuration // language : Moroccan Arabic (ar-ma) // author : ElFadili Yassine : https://github.com/ElFadiliY // author : Abdel Said : https://github.com/abdelsaid (function (factory) { factory(moment); }(function (moment) { return moment.lang('ar-ma', { months : "يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"), monthsShort : "يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"), weekdays : "الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"), weekdaysShort : "احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت".split("_"), weekdaysMin : "ح_ن_ث_ر_خ_ج_س".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[اليوم على الساعة] LT", nextDay: '[غدا على الساعة] LT', nextWeek: 'dddd [على الساعة] LT', lastDay: '[أمس على الساعة] LT', lastWeek: 'dddd [على الساعة] LT', sameElse: 'L' }, relativeTime : { future : "في %s", past : "منذ %s", s : "ثوان", m : "دقيقة", mm : "%d دقائق", h : "ساعة", hh : "%d ساعات", d : "يوم", dd : "%d أيام", M : "شهر", MM : "%d أشهر", y : "سنة", yy : "%d سنوات" }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Arabic (ar) // author : Abdel Said : https://github.com/abdelsaid // changes in months, weekdays : Ahmed Elkhatib (function (factory) { factory(moment); }(function (moment) { return moment.lang('ar', { months : "يناير/ كانون الثاني_فبراير/ شباط_مارس/ آذار_أبريل/ نيسان_مايو/ أيار_يونيو/ حزيران_يوليو/ تموز_أغسطس/ آب_سبتمبر/ أيلول_أكتوبر/ تشرين الأول_نوفمبر/ تشرين الثاني_ديسمبر/ كانون الأول".split("_"), monthsShort : "يناير/ كانون الثاني_فبراير/ شباط_مارس/ آذار_أبريل/ نيسان_مايو/ أيار_يونيو/ حزيران_يوليو/ تموز_أغسطس/ آب_سبتمبر/ أيلول_أكتوبر/ تشرين الأول_نوفمبر/ تشرين الثاني_ديسمبر/ كانون الأول".split("_"), weekdays : "الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"), weekdaysShort : "الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"), weekdaysMin : "ح_ن_ث_ر_خ_ج_س".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[اليوم على الساعة] LT", nextDay: '[غدا على الساعة] LT', nextWeek: 'dddd [على الساعة] LT', lastDay: '[أمس على الساعة] LT', lastWeek: 'dddd [على الساعة] LT', sameElse: 'L' }, relativeTime : { future : "في %s", past : "منذ %s", s : "ثوان", m : "دقيقة", mm : "%d دقائق", h : "ساعة", hh : "%d ساعات", d : "يوم", dd : "%d أيام", M : "شهر", MM : "%d أشهر", y : "سنة", yy : "%d سنوات" }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : bulgarian (bg) // author : Krasen Borisov : https://github.com/kraz (function (factory) { factory(moment); }(function (moment) { return moment.lang('bg', { months : "януари_февруари_март_април_май_юни_юли_август_септември_октомври_ноември_декември".split("_"), monthsShort : "янр_фев_мар_апр_май_юни_юли_авг_сеп_окт_ное_дек".split("_"), weekdays : "неделя_понеделник_вторник_сряда_четвъртък_петък_събота".split("_"), weekdaysShort : "нед_пон_вто_сря_чет_пет_съб".split("_"), weekdaysMin : "нд_пн_вт_ср_чт_пт_сб".split("_"), longDateFormat : { LT : "H:mm", L : "D.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[Днес в] LT', nextDay : '[Утре в] LT', nextWeek : 'dddd [в] LT', lastDay : '[Вчера в] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: case 6: return '[В изминалата] dddd [в] LT'; case 1: case 2: case 4: case 5: return '[В изминалия] dddd [в] LT'; } }, sameElse : 'L' }, relativeTime : { future : "след %s", past : "преди %s", s : "няколко секунди", m : "минута", mm : "%d минути", h : "час", hh : "%d часа", d : "ден", dd : "%d дни", M : "месец", MM : "%d месеца", y : "година", yy : "%d години" }, ordinal : function (number) { var lastDigit = number % 10, last2Digits = number % 100; if (number === 0) { return number + '-ев'; } else if (last2Digits === 0) { return number + '-ен'; } else if (last2Digits > 10 && last2Digits < 20) { return number + '-ти'; } else if (lastDigit === 1) { return number + '-ви'; } else if (lastDigit === 2) { return number + '-ри'; } else if (lastDigit === 7 || lastDigit === 8) { return number + '-ми'; } else { return number + '-ти'; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : breton (br) // author : Jean-Baptiste Le Duigou : https://github.com/jbleduigou (function (factory) { factory(moment); }(function (moment) { function relativeTimeWithMutation(number, withoutSuffix, key) { var format = { 'mm': "munutenn", 'MM': "miz", 'dd': "devezh" }; return number + ' ' + mutation(format[key], number); } function specialMutationForYears(number) { switch (lastNumber(number)) { case 1: case 3: case 4: case 5: case 9: return number + ' bloaz'; default: return number + ' vloaz'; } } function lastNumber(number) { if (number > 9) { return lastNumber(number % 10); } return number; } function mutation(text, number) { if (number === 2) { return softMutation(text); } return text; } function softMutation(text) { var mutationTable = { 'm': 'v', 'b': 'v', 'd': 'z' }; if (mutationTable[text.charAt(0)] === undefined) { return text; } return mutationTable[text.charAt(0)] + text.substring(1); } return moment.lang('br', { months : "Genver_C'hwevrer_Meurzh_Ebrel_Mae_Mezheven_Gouere_Eost_Gwengolo_Here_Du_Kerzu".split("_"), monthsShort : "Gen_C'hwe_Meu_Ebr_Mae_Eve_Gou_Eos_Gwe_Her_Du_Ker".split("_"), weekdays : "Sul_Lun_Meurzh_Merc'her_Yaou_Gwener_Sadorn".split("_"), weekdaysShort : "Sul_Lun_Meu_Mer_Yao_Gwe_Sad".split("_"), weekdaysMin : "Su_Lu_Me_Mer_Ya_Gw_Sa".split("_"), longDateFormat : { LT : "h[e]mm A", L : "DD/MM/YYYY", LL : "D [a viz] MMMM YYYY", LLL : "D [a viz] MMMM YYYY LT", LLLL : "dddd, D [a viz] MMMM YYYY LT" }, calendar : { sameDay : '[Hiziv da] LT', nextDay : '[Warc\'hoazh da] LT', nextWeek : 'dddd [da] LT', lastDay : '[Dec\'h da] LT', lastWeek : 'dddd [paset da] LT', sameElse : 'L' }, relativeTime : { future : "a-benn %s", past : "%s 'zo", s : "un nebeud segondennoù", m : "ur vunutenn", mm : relativeTimeWithMutation, h : "un eur", hh : "%d eur", d : "un devezh", dd : relativeTimeWithMutation, M : "ur miz", MM : relativeTimeWithMutation, y : "ur bloaz", yy : specialMutationForYears }, ordinal : function (number) { var output = (number === 1) ? 'añ' : 'vet'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : bosnian (bs) // author : Nedim Cholich : https://github.com/frontyard // based on (hr) translation by Bojan Marković (function (factory) { factory(moment); }(function (moment) { function translate(number, withoutSuffix, key) { var result = number + " "; switch (key) { case 'm': return withoutSuffix ? 'jedna minuta' : 'jedne minute'; case 'mm': if (number === 1) { result += 'minuta'; } else if (number === 2 || number === 3 || number === 4) { result += 'minute'; } else { result += 'minuta'; } return result; case 'h': return withoutSuffix ? 'jedan sat' : 'jednog sata'; case 'hh': if (number === 1) { result += 'sat'; } else if (number === 2 || number === 3 || number === 4) { result += 'sata'; } else { result += 'sati'; } return result; case 'dd': if (number === 1) { result += 'dan'; } else { result += 'dana'; } return result; case 'MM': if (number === 1) { result += 'mjesec'; } else if (number === 2 || number === 3 || number === 4) { result += 'mjeseca'; } else { result += 'mjeseci'; } return result; case 'yy': if (number === 1) { result += 'godina'; } else if (number === 2 || number === 3 || number === 4) { result += 'godine'; } else { result += 'godina'; } return result; } } return moment.lang('bs', { months : "januar_februar_mart_april_maj_juni_juli_avgust_septembar_oktobar_novembar_decembar".split("_"), monthsShort : "jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.".split("_"), weekdays : "nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota".split("_"), weekdaysShort : "ned._pon._uto._sri._čet._pet._sub.".split("_"), weekdaysMin : "ne_po_ut_sr_če_pe_su".split("_"), longDateFormat : { LT : "H:mm", L : "DD. MM. YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay : '[danas u] LT', nextDay : '[sutra u] LT', nextWeek : function () { switch (this.day()) { case 0: return '[u] [nedjelju] [u] LT'; case 3: return '[u] [srijedu] [u] LT'; case 6: return '[u] [subotu] [u] LT'; case 1: case 2: case 4: case 5: return '[u] dddd [u] LT'; } }, lastDay : '[jučer u] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: return '[prošlu] dddd [u] LT'; case 6: return '[prošle] [subote] [u] LT'; case 1: case 2: case 4: case 5: return '[prošli] dddd [u] LT'; } }, sameElse : 'L' }, relativeTime : { future : "za %s", past : "prije %s", s : "par sekundi", m : translate, mm : translate, h : translate, hh : translate, d : "dan", dd : translate, M : "mjesec", MM : translate, y : "godinu", yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : catalan (ca) // author : Juan G. Hurtado : https://github.com/juanghurtado (function (factory) { factory(moment); }(function (moment) { return moment.lang('ca', { months : "gener_febrer_març_abril_maig_juny_juliol_agost_setembre_octubre_novembre_desembre".split("_"), monthsShort : "gen._febr._mar._abr._mai._jun._jul._ag._set._oct._nov._des.".split("_"), weekdays : "diumenge_dilluns_dimarts_dimecres_dijous_divendres_dissabte".split("_"), weekdaysShort : "dg._dl._dt._dc._dj._dv._ds.".split("_"), weekdaysMin : "Dg_Dl_Dt_Dc_Dj_Dv_Ds".split("_"), longDateFormat : { LT : "H:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay : function () { return '[avui a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, nextDay : function () { return '[demà a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, nextWeek : function () { return 'dddd [a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, lastDay : function () { return '[ahir a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, lastWeek : function () { return '[el] dddd [passat a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, sameElse : 'L' }, relativeTime : { future : "en %s", past : "fa %s", s : "uns segons", m : "un minut", mm : "%d minuts", h : "una hora", hh : "%d hores", d : "un dia", dd : "%d dies", M : "un mes", MM : "%d mesos", y : "un any", yy : "%d anys" }, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : czech (cs) // author : petrbela : https://github.com/petrbela (function (factory) { factory(moment); }(function (moment) { var months = "leden_únor_březen_duben_květen_červen_červenec_srpen_září_říjen_listopad_prosinec".split("_"), monthsShort = "led_úno_bře_dub_kvě_čvn_čvc_srp_zář_říj_lis_pro".split("_"); function plural(n) { return (n > 1) && (n < 5) && (~~(n / 10) !== 1); } function translate(number, withoutSuffix, key, isFuture) { var result = number + " "; switch (key) { case 's': // a few seconds / in a few seconds / a few seconds ago return (withoutSuffix || isFuture) ? 'pár vteřin' : 'pár vteřinami'; case 'm': // a minute / in a minute / a minute ago return withoutSuffix ? 'minuta' : (isFuture ? 'minutu' : 'minutou'); case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'minuty' : 'minut'); } else { return result + 'minutami'; } break; case 'h': // an hour / in an hour / an hour ago return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou'); case 'hh': // 9 hours / in 9 hours / 9 hours ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'hodiny' : 'hodin'); } else { return result + 'hodinami'; } break; case 'd': // a day / in a day / a day ago return (withoutSuffix || isFuture) ? 'den' : 'dnem'; case 'dd': // 9 days / in 9 days / 9 days ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'dny' : 'dní'); } else { return result + 'dny'; } break; case 'M': // a month / in a month / a month ago return (withoutSuffix || isFuture) ? 'měsíc' : 'měsícem'; case 'MM': // 9 months / in 9 months / 9 months ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'měsíce' : 'měsíců'); } else { return result + 'měsíci'; } break; case 'y': // a year / in a year / a year ago return (withoutSuffix || isFuture) ? 'rok' : 'rokem'; case 'yy': // 9 years / in 9 years / 9 years ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'roky' : 'let'); } else { return result + 'lety'; } break; } } return moment.lang('cs', { months : months, monthsShort : monthsShort, monthsParse : (function (months, monthsShort) { var i, _monthsParse = []; for (i = 0; i < 12; i++) { // use custom parser to solve problem with July (červenec) _monthsParse[i] = new RegExp('^' + months[i] + '$|^' + monthsShort[i] + '$', 'i'); } return _monthsParse; }(months, monthsShort)), weekdays : "neděle_pondělí_úterý_středa_čtvrtek_pátek_sobota".split("_"), weekdaysShort : "ne_po_út_st_čt_pá_so".split("_"), weekdaysMin : "ne_po_út_st_čt_pá_so".split("_"), longDateFormat : { LT: "H:mm", L : "DD.MM.YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd D. MMMM YYYY LT" }, calendar : { sameDay: "[dnes v] LT", nextDay: '[zítra v] LT', nextWeek: function () { switch (this.day()) { case 0: return '[v neděli v] LT'; case 1: case 2: return '[v] dddd [v] LT'; case 3: return '[ve středu v] LT'; case 4: return '[ve čtvrtek v] LT'; case 5: return '[v pátek v] LT'; case 6: return '[v sobotu v] LT'; } }, lastDay: '[včera v] LT', lastWeek: function () { switch (this.day()) { case 0: return '[minulou neděli v] LT'; case 1: case 2: return '[minulé] dddd [v] LT'; case 3: return '[minulou středu v] LT'; case 4: case 5: return '[minulý] dddd [v] LT'; case 6: return '[minulou sobotu v] LT'; } }, sameElse: "L" }, relativeTime : { future : "za %s", past : "před %s", s : translate, m : translate, mm : translate, h : translate, hh : translate, d : translate, dd : translate, M : translate, MM : translate, y : translate, yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : chuvash (cv) // author : Anatoly Mironov : https://github.com/mirontoli (function (factory) { factory(moment); }(function (moment) { return moment.lang('cv', { months : "кăрлач_нарăс_пуш_ака_май_çĕртме_утă_çурла_авăн_юпа_чӳк_раштав".split("_"), monthsShort : "кăр_нар_пуш_ака_май_çĕр_утă_çур_ав_юпа_чӳк_раш".split("_"), weekdays : "вырсарникун_тунтикун_ытларикун_юнкун_кĕçнерникун_эрнекун_шăматкун".split("_"), weekdaysShort : "выр_тун_ытл_юн_кĕç_эрн_шăм".split("_"), weekdaysMin : "вр_тн_ыт_юн_кç_эр_шм".split("_"), longDateFormat : { LT : "HH:mm", L : "DD-MM-YYYY", LL : "YYYY [çулхи] MMMM [уйăхĕн] D[-мĕшĕ]", LLL : "YYYY [çулхи] MMMM [уйăхĕн] D[-мĕшĕ], LT", LLLL : "dddd, YYYY [çулхи] MMMM [уйăхĕн] D[-мĕшĕ], LT" }, calendar : { sameDay: '[Паян] LT [сехетре]', nextDay: '[Ыран] LT [сехетре]', lastDay: '[Ĕнер] LT [сехетре]', nextWeek: '[Çитес] dddd LT [сехетре]', lastWeek: '[Иртнĕ] dddd LT [сехетре]', sameElse: 'L' }, relativeTime : { future : function (output) { var affix = /сехет$/i.exec(output) ? "рен" : /çул$/i.exec(output) ? "тан" : "ран"; return output + affix; }, past : "%s каялла", s : "пĕр-ик çеккунт", m : "пĕр минут", mm : "%d минут", h : "пĕр сехет", hh : "%d сехет", d : "пĕр кун", dd : "%d кун", M : "пĕр уйăх", MM : "%d уйăх", y : "пĕр çул", yy : "%d çул" }, ordinal : '%d-мĕш', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Welsh (cy) // author : Robert Allen (function (factory) { factory(moment); }(function (moment) { return moment.lang("cy", { months: "Ionawr_Chwefror_Mawrth_Ebrill_Mai_Mehefin_Gorffennaf_Awst_Medi_Hydref_Tachwedd_Rhagfyr".split("_"), monthsShort: "Ion_Chwe_Maw_Ebr_Mai_Meh_Gor_Aws_Med_Hyd_Tach_Rhag".split("_"), weekdays: "Dydd Sul_Dydd Llun_Dydd Mawrth_Dydd Mercher_Dydd Iau_Dydd Gwener_Dydd Sadwrn".split("_"), weekdaysShort: "Sul_Llun_Maw_Mer_Iau_Gwe_Sad".split("_"), weekdaysMin: "Su_Ll_Ma_Me_Ia_Gw_Sa".split("_"), // time formats are the same as en-gb longDateFormat: { LT: "HH:mm", L: "DD/MM/YYYY", LL: "D MMMM YYYY", LLL: "D MMMM YYYY LT", LLLL: "dddd, D MMMM YYYY LT" }, calendar: { sameDay: '[Heddiw am] LT', nextDay: '[Yfory am] LT', nextWeek: 'dddd [am] LT', lastDay: '[Ddoe am] LT', lastWeek: 'dddd [diwethaf am] LT', sameElse: 'L' }, relativeTime: { future: "mewn %s", past: "%s yn àl", s: "ychydig eiliadau", m: "munud", mm: "%d munud", h: "awr", hh: "%d awr", d: "diwrnod", dd: "%d diwrnod", M: "mis", MM: "%d mis", y: "blwyddyn", yy: "%d flynedd" }, // traditional ordinal numbers above 31 are not commonly used in colloquial Welsh ordinal: function (number) { var b = number, output = '', lookup = [ '', 'af', 'il', 'ydd', 'ydd', 'ed', 'ed', 'ed', 'fed', 'fed', 'fed', // 1af to 10fed 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'fed' // 11eg to 20fed ]; if (b > 20) { if (b === 40 || b === 50 || b === 60 || b === 80 || b === 100) { output = 'fed'; // not 30ain, 70ain or 90ain } else { output = 'ain'; } } else if (b > 0) { output = lookup[b]; } return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : danish (da) // author : Ulrik Nielsen : https://github.com/mrbase (function (factory) { factory(moment); }(function (moment) { return moment.lang('da', { months : "januar_februar_marts_april_maj_juni_juli_august_september_oktober_november_december".split("_"), monthsShort : "jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec".split("_"), weekdays : "søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag".split("_"), weekdaysShort : "søn_man_tir_ons_tor_fre_lør".split("_"), weekdaysMin : "sø_ma_ti_on_to_fr_lø".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D. MMMM, YYYY LT" }, calendar : { sameDay : '[I dag kl.] LT', nextDay : '[I morgen kl.] LT', nextWeek : 'dddd [kl.] LT', lastDay : '[I går kl.] LT', lastWeek : '[sidste] dddd [kl] LT', sameElse : 'L' }, relativeTime : { future : "om %s", past : "%s siden", s : "få sekunder", m : "et minut", mm : "%d minutter", h : "en time", hh : "%d timer", d : "en dag", dd : "%d dage", M : "en måned", MM : "%d måneder", y : "et år", yy : "%d år" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : german (de) // author : lluchs : https://github.com/lluchs // author: Menelion Elensúle: https://github.com/Oire (function (factory) { factory(moment); }(function (moment) { function processRelativeTime(number, withoutSuffix, key, isFuture) { var format = { 'm': ['eine Minute', 'einer Minute'], 'h': ['eine Stunde', 'einer Stunde'], 'd': ['ein Tag', 'einem Tag'], 'dd': [number + ' Tage', number + ' Tagen'], 'M': ['ein Monat', 'einem Monat'], 'MM': [number + ' Monate', number + ' Monaten'], 'y': ['ein Jahr', 'einem Jahr'], 'yy': [number + ' Jahre', number + ' Jahren'] }; return withoutSuffix ? format[key][0] : format[key][1]; } return moment.lang('de', { months : "Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember".split("_"), monthsShort : "Jan._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.".split("_"), weekdays : "Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag".split("_"), weekdaysShort : "So._Mo._Di._Mi._Do._Fr._Sa.".split("_"), weekdaysMin : "So_Mo_Di_Mi_Do_Fr_Sa".split("_"), longDateFormat : { LT: "H:mm [Uhr]", L : "DD.MM.YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay: "[Heute um] LT", sameElse: "L", nextDay: '[Morgen um] LT', nextWeek: 'dddd [um] LT', lastDay: '[Gestern um] LT', lastWeek: '[letzten] dddd [um] LT' }, relativeTime : { future : "in %s", past : "vor %s", s : "ein paar Sekunden", m : processRelativeTime, mm : "%d Minuten", h : processRelativeTime, hh : "%d Stunden", d : processRelativeTime, dd : processRelativeTime, M : processRelativeTime, MM : processRelativeTime, y : processRelativeTime, yy : processRelativeTime }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : modern greek (el) // author : Aggelos Karalias : https://github.com/mehiel (function (factory) { factory(moment); }(function (moment) { return moment.lang('el', { monthsNominativeEl : "Ιανουάριος_Φεβρουάριος_Μάρτιος_Απρίλιος_Μάιος_Ιούνιος_Ιούλιος_Αύγουστος_Σεπτέμβριος_Οκτώβριος_Νοέμβριος_Δεκέμβριος".split("_"), monthsGenitiveEl : "Ιανουαρίου_Φεβρουαρίου_Μαρτίου_Απριλίου_Μαΐου_Ιουνίου_Ιουλίου_Αυγούστου_Σεπτεμβρίου_Οκτωβρίου_Νοεμβρίου_Δεκεμβρίου".split("_"), months : function (momentToFormat, format) { if (/D/.test(format.substring(0, format.indexOf("MMMM")))) { // if there is a day number before 'MMMM' return this._monthsGenitiveEl[momentToFormat.month()]; } else { return this._monthsNominativeEl[momentToFormat.month()]; } }, monthsShort : "Ιαν_Φεβ_Μαρ_Απρ_Μαϊ_Ιουν_Ιουλ_Αυγ_Σεπ_Οκτ_Νοε_Δεκ".split("_"), weekdays : "Κυριακή_Δευτέρα_Τρίτη_Τετάρτη_Πέμπτη_Παρασκευή_Σάββατο".split("_"), weekdaysShort : "Κυρ_Δευ_Τρι_Τετ_Πεμ_Παρ_Σαβ".split("_"), weekdaysMin : "Κυ_Δε_Τρ_Τε_Πε_Πα_Σα".split("_"), meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'μμ' : 'ΜΜ'; } else { return isLower ? 'πμ' : 'ΠΜ'; } }, longDateFormat : { LT : "h:mm A", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendarEl : { sameDay : '[Σήμερα {}] LT', nextDay : '[Αύριο {}] LT', nextWeek : 'dddd [{}] LT', lastDay : '[Χθες {}] LT', lastWeek : '[την προηγούμενη] dddd [{}] LT', sameElse : 'L' }, calendar : function (key, mom) { var output = this._calendarEl[key], hours = mom && mom.hours(); return output.replace("{}", (hours % 12 === 1 ? "στη" : "στις")); }, relativeTime : { future : "σε %s", past : "%s πριν", s : "δευτερόλεπτα", m : "ένα λεπτό", mm : "%d λεπτά", h : "μία ώρα", hh : "%d ώρες", d : "μία μέρα", dd : "%d μέρες", M : "ένας μήνας", MM : "%d μήνες", y : "ένας χρόνος", yy : "%d χρόνια" }, ordinal : function (number) { return number + 'η'; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4st is the first week of the year. } }); })); // moment.js language configuration // language : australian english (en-au) (function (factory) { factory(moment); }(function (moment) { return moment.lang('en-au', { months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), longDateFormat : { LT : "h:mm A", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, relativeTime : { future : "in %s", past : "%s ago", s : "a few seconds", m : "a minute", mm : "%d minutes", h : "an hour", hh : "%d hours", d : "a day", dd : "%d days", M : "a month", MM : "%d months", y : "a year", yy : "%d years" }, ordinal : function (number) { var b = number % 10, output = (~~ (number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : canadian english (en-ca) // author : Jonathan Abourbih : https://github.com/jonbca (function (factory) { factory(moment); }(function (moment) { return moment.lang('en-ca', { months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), longDateFormat : { LT : "h:mm A", L : "YYYY-MM-DD", LL : "D MMMM, YYYY", LLL : "D MMMM, YYYY LT", LLLL : "dddd, D MMMM, YYYY LT" }, calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, relativeTime : { future : "in %s", past : "%s ago", s : "a few seconds", m : "a minute", mm : "%d minutes", h : "an hour", hh : "%d hours", d : "a day", dd : "%d days", M : "a month", MM : "%d months", y : "a year", yy : "%d years" }, ordinal : function (number) { var b = number % 10, output = (~~ (number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); })); // moment.js language configuration // language : great britain english (en-gb) // author : Chris Gedrim : https://github.com/chrisgedrim (function (factory) { factory(moment); }(function (moment) { return moment.lang('en-gb', { months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, relativeTime : { future : "in %s", past : "%s ago", s : "a few seconds", m : "a minute", mm : "%d minutes", h : "an hour", hh : "%d hours", d : "a day", dd : "%d days", M : "a month", MM : "%d months", y : "a year", yy : "%d years" }, ordinal : function (number) { var b = number % 10, output = (~~ (number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : esperanto (eo) // author : Colin Dean : https://github.com/colindean // komento: Mi estas malcerta se mi korekte traktis akuzativojn en tiu traduko. // Se ne, bonvolu korekti kaj avizi min por ke mi povas lerni! (function (factory) { factory(moment); }(function (moment) { return moment.lang('eo', { months : "januaro_februaro_marto_aprilo_majo_junio_julio_aŭgusto_septembro_oktobro_novembro_decembro".split("_"), monthsShort : "jan_feb_mar_apr_maj_jun_jul_aŭg_sep_okt_nov_dec".split("_"), weekdays : "Dimanĉo_Lundo_Mardo_Merkredo_Ĵaŭdo_Vendredo_Sabato".split("_"), weekdaysShort : "Dim_Lun_Mard_Merk_Ĵaŭ_Ven_Sab".split("_"), weekdaysMin : "Di_Lu_Ma_Me_Ĵa_Ve_Sa".split("_"), longDateFormat : { LT : "HH:mm", L : "YYYY-MM-DD", LL : "D[-an de] MMMM, YYYY", LLL : "D[-an de] MMMM, YYYY LT", LLLL : "dddd, [la] D[-an de] MMMM, YYYY LT" }, meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'p.t.m.' : 'P.T.M.'; } else { return isLower ? 'a.t.m.' : 'A.T.M.'; } }, calendar : { sameDay : '[Hodiaŭ je] LT', nextDay : '[Morgaŭ je] LT', nextWeek : 'dddd [je] LT', lastDay : '[Hieraŭ je] LT', lastWeek : '[pasinta] dddd [je] LT', sameElse : 'L' }, relativeTime : { future : "je %s", past : "antaŭ %s", s : "sekundoj", m : "minuto", mm : "%d minutoj", h : "horo", hh : "%d horoj", d : "tago",//ne 'diurno', ĉar estas uzita por proksimumo dd : "%d tagoj", M : "monato", MM : "%d monatoj", y : "jaro", yy : "%d jaroj" }, ordinal : "%da", week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : spanish (es) // author : Julio Napurí : https://github.com/julionc (function (factory) { factory(moment); }(function (moment) { return moment.lang('es', { months : "enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre".split("_"), monthsShort : "ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.".split("_"), weekdays : "domingo_lunes_martes_miércoles_jueves_viernes_sábado".split("_"), weekdaysShort : "dom._lun._mar._mié._jue._vie._sáb.".split("_"), weekdaysMin : "Do_Lu_Ma_Mi_Ju_Vi_Sá".split("_"), longDateFormat : { LT : "H:mm", L : "DD/MM/YYYY", LL : "D [de] MMMM [de] YYYY", LLL : "D [de] MMMM [de] YYYY LT", LLLL : "dddd, D [de] MMMM [de] YYYY LT" }, calendar : { sameDay : function () { return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextDay : function () { return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextWeek : function () { return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastDay : function () { return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastWeek : function () { return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, sameElse : 'L' }, relativeTime : { future : "en %s", past : "hace %s", s : "unos segundos", m : "un minuto", mm : "%d minutos", h : "una hora", hh : "%d horas", d : "un día", dd : "%d días", M : "un mes", MM : "%d meses", y : "un año", yy : "%d años" }, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : estonian (et) // author : Henry Kehlmann : https://github.com/madhenry // improvements : Illimar Tambek : https://github.com/ragulka (function (factory) { factory(moment); }(function (moment) { function processRelativeTime(number, withoutSuffix, key, isFuture) { var format = { 's' : ['mõne sekundi', 'mõni sekund', 'paar sekundit'], 'm' : ['ühe minuti', 'üks minut'], 'mm': [number + ' minuti', number + ' minutit'], 'h' : ['ühe tunni', 'tund aega', 'üks tund'], 'hh': [number + ' tunni', number + ' tundi'], 'd' : ['ühe päeva', 'üks päev'], 'M' : ['kuu aja', 'kuu aega', 'üks kuu'], 'MM': [number + ' kuu', number + ' kuud'], 'y' : ['ühe aasta', 'aasta', 'üks aasta'], 'yy': [number + ' aasta', number + ' aastat'] }; if (withoutSuffix) { return format[key][2] ? format[key][2] : format[key][1]; } return isFuture ? format[key][0] : format[key][1]; } return moment.lang('et', { months : "jaanuar_veebruar_märts_aprill_mai_juuni_juuli_august_september_oktoober_november_detsember".split("_"), monthsShort : "jaan_veebr_märts_apr_mai_juuni_juuli_aug_sept_okt_nov_dets".split("_"), weekdays : "pühapäev_esmaspäev_teisipäev_kolmapäev_neljapäev_reede_laupäev".split("_"), weekdaysShort : "P_E_T_K_N_R_L".split("_"), weekdaysMin : "P_E_T_K_N_R_L".split("_"), longDateFormat : { LT : "H:mm", L : "DD.MM.YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay : '[Täna,] LT', nextDay : '[Homme,] LT', nextWeek : '[Järgmine] dddd LT', lastDay : '[Eile,] LT', lastWeek : '[Eelmine] dddd LT', sameElse : 'L' }, relativeTime : { future : "%s pärast", past : "%s tagasi", s : processRelativeTime, m : processRelativeTime, mm : processRelativeTime, h : processRelativeTime, hh : processRelativeTime, d : processRelativeTime, dd : '%d päeva', M : processRelativeTime, MM : processRelativeTime, y : processRelativeTime, yy : processRelativeTime }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : euskara (eu) // author : Eneko Illarramendi : https://github.com/eillarra (function (factory) { factory(moment); }(function (moment) { return moment.lang('eu', { months : "urtarrila_otsaila_martxoa_apirila_maiatza_ekaina_uztaila_abuztua_iraila_urria_azaroa_abendua".split("_"), monthsShort : "urt._ots._mar._api._mai._eka._uzt._abu._ira._urr._aza._abe.".split("_"), weekdays : "igandea_astelehena_asteartea_asteazkena_osteguna_ostirala_larunbata".split("_"), weekdaysShort : "ig._al._ar._az._og._ol._lr.".split("_"), weekdaysMin : "ig_al_ar_az_og_ol_lr".split("_"), longDateFormat : { LT : "HH:mm", L : "YYYY-MM-DD", LL : "YYYY[ko] MMMM[ren] D[a]", LLL : "YYYY[ko] MMMM[ren] D[a] LT", LLLL : "dddd, YYYY[ko] MMMM[ren] D[a] LT", l : "YYYY-M-D", ll : "YYYY[ko] MMM D[a]", lll : "YYYY[ko] MMM D[a] LT", llll : "ddd, YYYY[ko] MMM D[a] LT" }, calendar : { sameDay : '[gaur] LT[etan]', nextDay : '[bihar] LT[etan]', nextWeek : 'dddd LT[etan]', lastDay : '[atzo] LT[etan]', lastWeek : '[aurreko] dddd LT[etan]', sameElse : 'L' }, relativeTime : { future : "%s barru", past : "duela %s", s : "segundo batzuk", m : "minutu bat", mm : "%d minutu", h : "ordu bat", hh : "%d ordu", d : "egun bat", dd : "%d egun", M : "hilabete bat", MM : "%d hilabete", y : "urte bat", yy : "%d urte" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Persian Language // author : Ebrahim Byagowi : https://github.com/ebraminio (function (factory) { factory(moment); }(function (moment) { var symbolMap = { '1': '۱', '2': '۲', '3': '۳', '4': '۴', '5': '۵', '6': '۶', '7': '۷', '8': '۸', '9': '۹', '0': '۰' }, numberMap = { '۱': '1', '۲': '2', '۳': '3', '۴': '4', '۵': '5', '۶': '6', '۷': '7', '۸': '8', '۹': '9', '۰': '0' }; return moment.lang('fa', { months : 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'), monthsShort : 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'), weekdays : 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'), weekdaysShort : 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'), weekdaysMin : 'ی_د_س_چ_پ_ج_ش'.split('_'), longDateFormat : { LT : 'HH:mm', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY LT', LLLL : 'dddd, D MMMM YYYY LT' }, meridiem : function (hour, minute, isLower) { if (hour < 12) { return "قبل از ظهر"; } else { return "بعد از ظهر"; } }, calendar : { sameDay : '[امروز ساعت] LT', nextDay : '[فردا ساعت] LT', nextWeek : 'dddd [ساعت] LT', lastDay : '[دیروز ساعت] LT', lastWeek : 'dddd [پیش] [ساعت] LT', sameElse : 'L' }, relativeTime : { future : 'در %s', past : '%s پیش', s : 'چندین ثانیه', m : 'یک دقیقه', mm : '%d دقیقه', h : 'یک ساعت', hh : '%d ساعت', d : 'یک روز', dd : '%d روز', M : 'یک ماه', MM : '%d ماه', y : 'یک سال', yy : '%d سال' }, preparse: function (string) { return string.replace(/[۰-۹]/g, function (match) { return numberMap[match]; }).replace(/،/g, ','); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }).replace(/,/g, '،'); }, ordinal : '%dم', week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : finnish (fi) // author : Tarmo Aidantausta : https://github.com/bleadof (function (factory) { factory(moment); }(function (moment) { var numbers_past = 'nolla yksi kaksi kolme neljä viisi kuusi seitsemän kahdeksan yhdeksän'.split(' '), numbers_future = ['nolla', 'yhden', 'kahden', 'kolmen', 'neljän', 'viiden', 'kuuden', numbers_past[7], numbers_past[8], numbers_past[9]]; function translate(number, withoutSuffix, key, isFuture) { var result = ""; switch (key) { case 's': return isFuture ? 'muutaman sekunnin' : 'muutama sekunti'; case 'm': return isFuture ? 'minuutin' : 'minuutti'; case 'mm': result = isFuture ? 'minuutin' : 'minuuttia'; break; case 'h': return isFuture ? 'tunnin' : 'tunti'; case 'hh': result = isFuture ? 'tunnin' : 'tuntia'; break; case 'd': return isFuture ? 'päivän' : 'päivä'; case 'dd': result = isFuture ? 'päivän' : 'päivää'; break; case 'M': return isFuture ? 'kuukauden' : 'kuukausi'; case 'MM': result = isFuture ? 'kuukauden' : 'kuukautta'; break; case 'y': return isFuture ? 'vuoden' : 'vuosi'; case 'yy': result = isFuture ? 'vuoden' : 'vuotta'; break; } result = verbal_number(number, isFuture) + " " + result; return result; } function verbal_number(number, isFuture) { return number < 10 ? (isFuture ? numbers_future[number] : numbers_past[number]) : number; } return moment.lang('fi', { months : "tammikuu_helmikuu_maaliskuu_huhtikuu_toukokuu_kesäkuu_heinäkuu_elokuu_syyskuu_lokakuu_marraskuu_joulukuu".split("_"), monthsShort : "tammi_helmi_maalis_huhti_touko_kesä_heinä_elo_syys_loka_marras_joulu".split("_"), weekdays : "sunnuntai_maanantai_tiistai_keskiviikko_torstai_perjantai_lauantai".split("_"), weekdaysShort : "su_ma_ti_ke_to_pe_la".split("_"), weekdaysMin : "su_ma_ti_ke_to_pe_la".split("_"), longDateFormat : { LT : "HH.mm", L : "DD.MM.YYYY", LL : "Do MMMM[ta] YYYY", LLL : "Do MMMM[ta] YYYY, [klo] LT", LLLL : "dddd, Do MMMM[ta] YYYY, [klo] LT", l : "D.M.YYYY", ll : "Do MMM YYYY", lll : "Do MMM YYYY, [klo] LT", llll : "ddd, Do MMM YYYY, [klo] LT" }, calendar : { sameDay : '[tänään] [klo] LT', nextDay : '[huomenna] [klo] LT', nextWeek : 'dddd [klo] LT', lastDay : '[eilen] [klo] LT', lastWeek : '[viime] dddd[na] [klo] LT', sameElse : 'L' }, relativeTime : { future : "%s päästä", past : "%s sitten", s : translate, m : translate, mm : translate, h : translate, hh : translate, d : translate, dd : translate, M : translate, MM : translate, y : translate, yy : translate }, ordinal : "%d.", week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : faroese (fo) // author : Ragnar Johannesen : https://github.com/ragnar123 (function (factory) { factory(moment); }(function (moment) { return moment.lang('fo', { months : "januar_februar_mars_apríl_mai_juni_juli_august_september_oktober_november_desember".split("_"), monthsShort : "jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"), weekdays : "sunnudagur_mánadagur_týsdagur_mikudagur_hósdagur_fríggjadagur_leygardagur".split("_"), weekdaysShort : "sun_mán_týs_mik_hós_frí_ley".split("_"), weekdaysMin : "su_má_tý_mi_hó_fr_le".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D. MMMM, YYYY LT" }, calendar : { sameDay : '[Í dag kl.] LT', nextDay : '[Í morgin kl.] LT', nextWeek : 'dddd [kl.] LT', lastDay : '[Í gjár kl.] LT', lastWeek : '[síðstu] dddd [kl] LT', sameElse : 'L' }, relativeTime : { future : "um %s", past : "%s síðani", s : "fá sekund", m : "ein minutt", mm : "%d minuttir", h : "ein tími", hh : "%d tímar", d : "ein dagur", dd : "%d dagar", M : "ein mánaði", MM : "%d mánaðir", y : "eitt ár", yy : "%d ár" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : canadian french (fr-ca) // author : Jonathan Abourbih : https://github.com/jonbca (function (factory) { factory(moment); }(function (moment) { return moment.lang('fr-ca', { months : "janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"), monthsShort : "janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"), weekdays : "dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"), weekdaysShort : "dim._lun._mar._mer._jeu._ven._sam.".split("_"), weekdaysMin : "Di_Lu_Ma_Me_Je_Ve_Sa".split("_"), longDateFormat : { LT : "HH:mm", L : "YYYY-MM-DD", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[Aujourd'hui à] LT", nextDay: '[Demain à] LT', nextWeek: 'dddd [à] LT', lastDay: '[Hier à] LT', lastWeek: 'dddd [dernier à] LT', sameElse: 'L' }, relativeTime : { future : "dans %s", past : "il y a %s", s : "quelques secondes", m : "une minute", mm : "%d minutes", h : "une heure", hh : "%d heures", d : "un jour", dd : "%d jours", M : "un mois", MM : "%d mois", y : "un an", yy : "%d ans" }, ordinal : function (number) { return number + (number === 1 ? 'er' : ''); } }); })); // moment.js language configuration // language : french (fr) // author : John Fischer : https://github.com/jfroffice (function (factory) { factory(moment); }(function (moment) { return moment.lang('fr', { months : "janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"), monthsShort : "janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"), weekdays : "dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"), weekdaysShort : "dim._lun._mar._mer._jeu._ven._sam.".split("_"), weekdaysMin : "Di_Lu_Ma_Me_Je_Ve_Sa".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[Aujourd'hui à] LT", nextDay: '[Demain à] LT', nextWeek: 'dddd [à] LT', lastDay: '[Hier à] LT', lastWeek: 'dddd [dernier à] LT', sameElse: 'L' }, relativeTime : { future : "dans %s", past : "il y a %s", s : "quelques secondes", m : "une minute", mm : "%d minutes", h : "une heure", hh : "%d heures", d : "un jour", dd : "%d jours", M : "un mois", MM : "%d mois", y : "un an", yy : "%d ans" }, ordinal : function (number) { return number + (number === 1 ? 'er' : ''); }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : galician (gl) // author : Juan G. Hurtado : https://github.com/juanghurtado (function (factory) { factory(moment); }(function (moment) { return moment.lang('gl', { months : "Xaneiro_Febreiro_Marzo_Abril_Maio_Xuño_Xullo_Agosto_Setembro_Outubro_Novembro_Decembro".split("_"), monthsShort : "Xan._Feb._Mar._Abr._Mai._Xuñ._Xul._Ago._Set._Out._Nov._Dec.".split("_"), weekdays : "Domingo_Luns_Martes_Mércores_Xoves_Venres_Sábado".split("_"), weekdaysShort : "Dom._Lun._Mar._Mér._Xov._Ven._Sáb.".split("_"), weekdaysMin : "Do_Lu_Ma_Mé_Xo_Ve_Sá".split("_"), longDateFormat : { LT : "H:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay : function () { return '[hoxe ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT'; }, nextDay : function () { return '[mañá ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT'; }, nextWeek : function () { return 'dddd [' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT'; }, lastDay : function () { return '[onte ' + ((this.hours() !== 1) ? 'á' : 'a') + '] LT'; }, lastWeek : function () { return '[o] dddd [pasado ' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT'; }, sameElse : 'L' }, relativeTime : { future : function (str) { if (str === "uns segundos") { return "nuns segundos"; } return "en " + str; }, past : "hai %s", s : "uns segundos", m : "un minuto", mm : "%d minutos", h : "unha hora", hh : "%d horas", d : "un día", dd : "%d días", M : "un mes", MM : "%d meses", y : "un ano", yy : "%d anos" }, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Hebrew (he) // author : Tomer Cohen : https://github.com/tomer // author : Moshe Simantov : https://github.com/DevelopmentIL // author : Tal Ater : https://github.com/TalAter (function (factory) { factory(moment); }(function (moment) { return moment.lang('he', { months : "ינואר_פברואר_מרץ_אפריל_מאי_יוני_יולי_אוגוסט_ספטמבר_אוקטובר_נובמבר_דצמבר".split("_"), monthsShort : "ינו׳_פבר׳_מרץ_אפר׳_מאי_יוני_יולי_אוג׳_ספט׳_אוק׳_נוב׳_דצמ׳".split("_"), weekdays : "ראשון_שני_שלישי_רביעי_חמישי_שישי_שבת".split("_"), weekdaysShort : "א׳_ב׳_ג׳_ד׳_ה׳_ו׳_ש׳".split("_"), weekdaysMin : "א_ב_ג_ד_ה_ו_ש".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D [ב]MMMM YYYY", LLL : "D [ב]MMMM YYYY LT", LLLL : "dddd, D [ב]MMMM YYYY LT", l : "D/M/YYYY", ll : "D MMM YYYY", lll : "D MMM YYYY LT", llll : "ddd, D MMM YYYY LT" }, calendar : { sameDay : '[היום ב־]LT', nextDay : '[מחר ב־]LT', nextWeek : 'dddd [בשעה] LT', lastDay : '[אתמול ב־]LT', lastWeek : '[ביום] dddd [האחרון בשעה] LT', sameElse : 'L' }, relativeTime : { future : "בעוד %s", past : "לפני %s", s : "מספר שניות", m : "דקה", mm : "%d דקות", h : "שעה", hh : function (number) { if (number === 2) { return "שעתיים"; } return number + " שעות"; }, d : "יום", dd : function (number) { if (number === 2) { return "יומיים"; } return number + " ימים"; }, M : "חודש", MM : function (number) { if (number === 2) { return "חודשיים"; } return number + " חודשים"; }, y : "שנה", yy : function (number) { if (number === 2) { return "שנתיים"; } return number + " שנים"; } } }); })); // moment.js language configuration // language : hindi (hi) // author : Mayank Singhal : https://github.com/mayanksinghal (function (factory) { factory(moment); }(function (moment) { var symbolMap = { '1': '१', '2': '२', '3': '३', '4': '४', '5': '५', '6': '६', '7': '७', '8': '८', '9': '९', '0': '०' }, numberMap = { '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9', '०': '0' }; return moment.lang('hi', { months : 'जनवरी_फ़रवरी_मार्च_अप्रैल_मई_जून_जुलाई_अगस्त_सितम्बर_अक्टूबर_नवम्बर_दिसम्बर'.split("_"), monthsShort : 'जन._फ़र._मार्च_अप्रै._मई_जून_जुल._अग._सित._अक्टू._नव._दिस.'.split("_"), weekdays : 'रविवार_सोमवार_मंगलवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split("_"), weekdaysShort : 'रवि_सोम_मंगल_बुध_गुरू_शुक्र_शनि'.split("_"), weekdaysMin : 'र_सो_मं_बु_गु_शु_श'.split("_"), longDateFormat : { LT : "A h:mm बजे", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY, LT", LLLL : "dddd, D MMMM YYYY, LT" }, calendar : { sameDay : '[आज] LT', nextDay : '[कल] LT', nextWeek : 'dddd, LT', lastDay : '[कल] LT', lastWeek : '[पिछले] dddd, LT', sameElse : 'L' }, relativeTime : { future : "%s में", past : "%s पहले", s : "कुछ ही क्षण", m : "एक मिनट", mm : "%d मिनट", h : "एक घंटा", hh : "%d घंटे", d : "एक दिन", dd : "%d दिन", M : "एक महीने", MM : "%d महीने", y : "एक वर्ष", yy : "%d वर्ष" }, preparse: function (string) { return string.replace(/[१२३४५६७८९०]/g, function (match) { return numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }); }, // Hindi notation for meridiems are quite fuzzy in practice. While there exists // a rigid notion of a 'Pahar' it is not used as rigidly in modern Hindi. meridiem : function (hour, minute, isLower) { if (hour < 4) { return "रात"; } else if (hour < 10) { return "सुबह"; } else if (hour < 17) { return "दोपहर"; } else if (hour < 20) { return "शाम"; } else { return "रात"; } }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : hrvatski (hr) // author : Bojan Marković : https://github.com/bmarkovic // based on (sl) translation by Robert Sedovšek (function (factory) { factory(moment); }(function (moment) { function translate(number, withoutSuffix, key) { var result = number + " "; switch (key) { case 'm': return withoutSuffix ? 'jedna minuta' : 'jedne minute'; case 'mm': if (number === 1) { result += 'minuta'; } else if (number === 2 || number === 3 || number === 4) { result += 'minute'; } else { result += 'minuta'; } return result; case 'h': return withoutSuffix ? 'jedan sat' : 'jednog sata'; case 'hh': if (number === 1) { result += 'sat'; } else if (number === 2 || number === 3 || number === 4) { result += 'sata'; } else { result += 'sati'; } return result; case 'dd': if (number === 1) { result += 'dan'; } else { result += 'dana'; } return result; case 'MM': if (number === 1) { result += 'mjesec'; } else if (number === 2 || number === 3 || number === 4) { result += 'mjeseca'; } else { result += 'mjeseci'; } return result; case 'yy': if (number === 1) { result += 'godina'; } else if (number === 2 || number === 3 || number === 4) { result += 'godine'; } else { result += 'godina'; } return result; } } return moment.lang('hr', { months : "sječanj_veljača_ožujak_travanj_svibanj_lipanj_srpanj_kolovoz_rujan_listopad_studeni_prosinac".split("_"), monthsShort : "sje._vel._ožu._tra._svi._lip._srp._kol._ruj._lis._stu._pro.".split("_"), weekdays : "nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota".split("_"), weekdaysShort : "ned._pon._uto._sri._čet._pet._sub.".split("_"), weekdaysMin : "ne_po_ut_sr_če_pe_su".split("_"), longDateFormat : { LT : "H:mm", L : "DD. MM. YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay : '[danas u] LT', nextDay : '[sutra u] LT', nextWeek : function () { switch (this.day()) { case 0: return '[u] [nedjelju] [u] LT'; case 3: return '[u] [srijedu] [u] LT'; case 6: return '[u] [subotu] [u] LT'; case 1: case 2: case 4: case 5: return '[u] dddd [u] LT'; } }, lastDay : '[jučer u] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: return '[prošlu] dddd [u] LT'; case 6: return '[prošle] [subote] [u] LT'; case 1: case 2: case 4: case 5: return '[prošli] dddd [u] LT'; } }, sameElse : 'L' }, relativeTime : { future : "za %s", past : "prije %s", s : "par sekundi", m : translate, mm : translate, h : translate, hh : translate, d : "dan", dd : translate, M : "mjesec", MM : translate, y : "godinu", yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : hungarian (hu) // author : Adam Brunner : https://github.com/adambrunner (function (factory) { factory(moment); }(function (moment) { var weekEndings = 'vasárnap hétfőn kedden szerdán csütörtökön pénteken szombaton'.split(' '); function translate(number, withoutSuffix, key, isFuture) { var num = number, suffix; switch (key) { case 's': return (isFuture || withoutSuffix) ? 'néhány másodperc' : 'néhány másodperce'; case 'm': return 'egy' + (isFuture || withoutSuffix ? ' perc' : ' perce'); case 'mm': return num + (isFuture || withoutSuffix ? ' perc' : ' perce'); case 'h': return 'egy' + (isFuture || withoutSuffix ? ' óra' : ' órája'); case 'hh': return num + (isFuture || withoutSuffix ? ' óra' : ' órája'); case 'd': return 'egy' + (isFuture || withoutSuffix ? ' nap' : ' napja'); case 'dd': return num + (isFuture || withoutSuffix ? ' nap' : ' napja'); case 'M': return 'egy' + (isFuture || withoutSuffix ? ' hónap' : ' hónapja'); case 'MM': return num + (isFuture || withoutSuffix ? ' hónap' : ' hónapja'); case 'y': return 'egy' + (isFuture || withoutSuffix ? ' év' : ' éve'); case 'yy': return num + (isFuture || withoutSuffix ? ' év' : ' éve'); } return ''; } function week(isFuture) { return (isFuture ? '' : '[múlt] ') + '[' + weekEndings[this.day()] + '] LT[-kor]'; } return moment.lang('hu', { months : "január_február_március_április_május_június_július_augusztus_szeptember_október_november_december".split("_"), monthsShort : "jan_feb_márc_ápr_máj_jún_júl_aug_szept_okt_nov_dec".split("_"), weekdays : "vasárnap_hétfő_kedd_szerda_csütörtök_péntek_szombat".split("_"), weekdaysShort : "vas_hét_kedd_sze_csüt_pén_szo".split("_"), weekdaysMin : "v_h_k_sze_cs_p_szo".split("_"), longDateFormat : { LT : "H:mm", L : "YYYY.MM.DD.", LL : "YYYY. MMMM D.", LLL : "YYYY. MMMM D., LT", LLLL : "YYYY. MMMM D., dddd LT" }, calendar : { sameDay : '[ma] LT[-kor]', nextDay : '[holnap] LT[-kor]', nextWeek : function () { return week.call(this, true); }, lastDay : '[tegnap] LT[-kor]', lastWeek : function () { return week.call(this, false); }, sameElse : 'L' }, relativeTime : { future : "%s múlva", past : "%s", s : translate, m : translate, mm : translate, h : translate, hh : translate, d : translate, dd : translate, M : translate, MM : translate, y : translate, yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Armenian (hy-am) // author : Armendarabyan : https://github.com/armendarabyan (function (factory) { factory(moment); }(function (moment) { function monthsCaseReplace(m, format) { var months = { 'nominative': 'հունվար_փետրվար_մարտ_ապրիլ_մայիս_հունիս_հուլիս_օգոստոս_սեպտեմբեր_հոկտեմբեր_նոյեմբեր_դեկտեմբեր'.split('_'), 'accusative': 'հունվարի_փետրվարի_մարտի_ապրիլի_մայիսի_հունիսի_հուլիսի_օգոստոսի_սեպտեմբերի_հոկտեմբերի_նոյեմբերի_դեկտեմբերի'.split('_') }, nounCase = (/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/).test(format) ? 'accusative' : 'nominative'; return months[nounCase][m.month()]; } function monthsShortCaseReplace(m, format) { var monthsShort = 'հնվ_փտր_մրտ_ապր_մյս_հնս_հլս_օգս_սպտ_հկտ_նմբ_դկտ'.split('_'); return monthsShort[m.month()]; } function weekdaysCaseReplace(m, format) { var weekdays = 'կիրակի_երկուշաբթի_երեքշաբթի_չորեքշաբթի_հինգշաբթի_ուրբաթ_շաբաթ'.split('_'); return weekdays[m.day()]; } return moment.lang('hy-am', { months : monthsCaseReplace, monthsShort : monthsShortCaseReplace, weekdays : weekdaysCaseReplace, weekdaysShort : "կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ".split("_"), weekdaysMin : "կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY թ.", LLL : "D MMMM YYYY թ., LT", LLLL : "dddd, D MMMM YYYY թ., LT" }, calendar : { sameDay: '[այսօր] LT', nextDay: '[վաղը] LT', lastDay: '[երեկ] LT', nextWeek: function () { return 'dddd [օրը ժամը] LT'; }, lastWeek: function () { return '[անցած] dddd [օրը ժամը] LT'; }, sameElse: 'L' }, relativeTime : { future : "%s հետո", past : "%s առաջ", s : "մի քանի վայրկյան", m : "րոպե", mm : "%d րոպե", h : "ժամ", hh : "%d ժամ", d : "օր", dd : "%d օր", M : "ամիս", MM : "%d ամիս", y : "տարի", yy : "%d տարի" }, meridiem : function (hour) { if (hour < 4) { return "գիշերվա"; } else if (hour < 12) { return "առավոտվա"; } else if (hour < 17) { return "ցերեկվա"; } else { return "երեկոյան"; } }, ordinal: function (number, period) { switch (period) { case 'DDD': case 'w': case 'W': case 'DDDo': if (number === 1) { return number + '-ին'; } return number + '-րդ'; default: return number; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Bahasa Indonesia (id) // author : Mohammad Satrio Utomo : https://github.com/tyok // reference: http://id.wikisource.org/wiki/Pedoman_Umum_Ejaan_Bahasa_Indonesia_yang_Disempurnakan (function (factory) { factory(moment); }(function (moment) { return moment.lang('id', { months : "Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_November_Desember".split("_"), monthsShort : "Jan_Feb_Mar_Apr_Mei_Jun_Jul_Ags_Sep_Okt_Nov_Des".split("_"), weekdays : "Minggu_Senin_Selasa_Rabu_Kamis_Jumat_Sabtu".split("_"), weekdaysShort : "Min_Sen_Sel_Rab_Kam_Jum_Sab".split("_"), weekdaysMin : "Mg_Sn_Sl_Rb_Km_Jm_Sb".split("_"), longDateFormat : { LT : "HH.mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY [pukul] LT", LLLL : "dddd, D MMMM YYYY [pukul] LT" }, meridiem : function (hours, minutes, isLower) { if (hours < 11) { return 'pagi'; } else if (hours < 15) { return 'siang'; } else if (hours < 19) { return 'sore'; } else { return 'malam'; } }, calendar : { sameDay : '[Hari ini pukul] LT', nextDay : '[Besok pukul] LT', nextWeek : 'dddd [pukul] LT', lastDay : '[Kemarin pukul] LT', lastWeek : 'dddd [lalu pukul] LT', sameElse : 'L' }, relativeTime : { future : "dalam %s", past : "%s yang lalu", s : "beberapa detik", m : "semenit", mm : "%d menit", h : "sejam", hh : "%d jam", d : "sehari", dd : "%d hari", M : "sebulan", MM : "%d bulan", y : "setahun", yy : "%d tahun" }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : icelandic (is) // author : Hinrik Örn Sigurðsson : https://github.com/hinrik (function (factory) { factory(moment); }(function (moment) { function plural(n) { if (n % 100 === 11) { return true; } else if (n % 10 === 1) { return false; } return true; } function translate(number, withoutSuffix, key, isFuture) { var result = number + " "; switch (key) { case 's': return withoutSuffix || isFuture ? 'nokkrar sekúndur' : 'nokkrum sekúndum'; case 'm': return withoutSuffix ? 'mínúta' : 'mínútu'; case 'mm': if (plural(number)) { return result + (withoutSuffix || isFuture ? 'mínútur' : 'mínútum'); } else if (withoutSuffix) { return result + 'mínúta'; } return result + 'mínútu'; case 'hh': if (plural(number)) { return result + (withoutSuffix || isFuture ? 'klukkustundir' : 'klukkustundum'); } return result + 'klukkustund'; case 'd': if (withoutSuffix) { return 'dagur'; } return isFuture ? 'dag' : 'degi'; case 'dd': if (plural(number)) { if (withoutSuffix) { return result + 'dagar'; } return result + (isFuture ? 'daga' : 'dögum'); } else if (withoutSuffix) { return result + 'dagur'; } return result + (isFuture ? 'dag' : 'degi'); case 'M': if (withoutSuffix) { return 'mánuður'; } return isFuture ? 'mánuð' : 'mánuði'; case 'MM': if (plural(number)) { if (withoutSuffix) { return result + 'mánuðir'; } return result + (isFuture ? 'mánuði' : 'mánuðum'); } else if (withoutSuffix) { return result + 'mánuður'; } return result + (isFuture ? 'mánuð' : 'mánuði'); case 'y': return withoutSuffix || isFuture ? 'ár' : 'ári'; case 'yy': if (plural(number)) { return result + (withoutSuffix || isFuture ? 'ár' : 'árum'); } return result + (withoutSuffix || isFuture ? 'ár' : 'ári'); } } return moment.lang('is', { months : "janúar_febrúar_mars_apríl_maí_júní_júlí_ágúst_september_október_nóvember_desember".split("_"), monthsShort : "jan_feb_mar_apr_maí_jún_júl_ágú_sep_okt_nóv_des".split("_"), weekdays : "sunnudagur_mánudagur_þriðjudagur_miðvikudagur_fimmtudagur_föstudagur_laugardagur".split("_"), weekdaysShort : "sun_mán_þri_mið_fim_fös_lau".split("_"), weekdaysMin : "Su_Má_Þr_Mi_Fi_Fö_La".split("_"), longDateFormat : { LT : "H:mm", L : "DD/MM/YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY [kl.] LT", LLLL : "dddd, D. MMMM YYYY [kl.] LT" }, calendar : { sameDay : '[í dag kl.] LT', nextDay : '[á morgun kl.] LT', nextWeek : 'dddd [kl.] LT', lastDay : '[í gær kl.] LT', lastWeek : '[síðasta] dddd [kl.] LT', sameElse : 'L' }, relativeTime : { future : "eftir %s", past : "fyrir %s síðan", s : translate, m : translate, mm : translate, h : "klukkustund", hh : translate, d : translate, dd : translate, M : translate, MM : translate, y : translate, yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : italian (it) // author : Lorenzo : https://github.com/aliem // author: Mattia Larentis: https://github.com/nostalgiaz (function (factory) { factory(moment); }(function (moment) { return moment.lang('it', { months : "Gennaio_Febbraio_Marzo_Aprile_Maggio_Giugno_Luglio_Agosto_Settembre_Ottobre_Novembre_Dicembre".split("_"), monthsShort : "Gen_Feb_Mar_Apr_Mag_Giu_Lug_Ago_Set_Ott_Nov_Dic".split("_"), weekdays : "Domenica_Lunedì_Martedì_Mercoledì_Giovedì_Venerdì_Sabato".split("_"), weekdaysShort : "Dom_Lun_Mar_Mer_Gio_Ven_Sab".split("_"), weekdaysMin : "D_L_Ma_Me_G_V_S".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay: '[Oggi alle] LT', nextDay: '[Domani alle] LT', nextWeek: 'dddd [alle] LT', lastDay: '[Ieri alle] LT', lastWeek: '[lo scorso] dddd [alle] LT', sameElse: 'L' }, relativeTime : { future : function (s) { return ((/^[0-9].+$/).test(s) ? "tra" : "in") + " " + s; }, past : "%s fa", s : "alcuni secondi", m : "un minuto", mm : "%d minuti", h : "un'ora", hh : "%d ore", d : "un giorno", dd : "%d giorni", M : "un mese", MM : "%d mesi", y : "un anno", yy : "%d anni" }, ordinal: '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : japanese (ja) // author : LI Long : https://github.com/baryon (function (factory) { factory(moment); }(function (moment) { return moment.lang('ja', { months : "1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"), monthsShort : "1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"), weekdays : "日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日".split("_"), weekdaysShort : "日_月_火_水_木_金_土".split("_"), weekdaysMin : "日_月_火_水_木_金_土".split("_"), longDateFormat : { LT : "Ah時m分", L : "YYYY/MM/DD", LL : "YYYY年M月D日", LLL : "YYYY年M月D日LT", LLLL : "YYYY年M月D日LT dddd" }, meridiem : function (hour, minute, isLower) { if (hour < 12) { return "午前"; } else { return "午後"; } }, calendar : { sameDay : '[今日] LT', nextDay : '[明日] LT', nextWeek : '[来週]dddd LT', lastDay : '[昨日] LT', lastWeek : '[前週]dddd LT', sameElse : 'L' }, relativeTime : { future : "%s後", past : "%s前", s : "数秒", m : "1分", mm : "%d分", h : "1時間", hh : "%d時間", d : "1日", dd : "%d日", M : "1ヶ月", MM : "%dヶ月", y : "1年", yy : "%d年" } }); })); // moment.js language configuration // language : Georgian (ka) // author : Irakli Janiashvili : https://github.com/irakli-janiashvili (function (factory) { factory(moment); }(function (moment) { function monthsCaseReplace(m, format) { var months = { 'nominative': 'იანვარი_თებერვალი_მარტი_აპრილი_მაისი_ივნისი_ივლისი_აგვისტო_სექტემბერი_ოქტომბერი_ნოემბერი_დეკემბერი'.split('_'), 'accusative': 'იანვარს_თებერვალს_მარტს_აპრილის_მაისს_ივნისს_ივლისს_აგვისტს_სექტემბერს_ოქტომბერს_ნოემბერს_დეკემბერს'.split('_') }, nounCase = (/D[oD] *MMMM?/).test(format) ? 'accusative' : 'nominative'; return months[nounCase][m.month()]; } function weekdaysCaseReplace(m, format) { var weekdays = { 'nominative': 'კვირა_ორშაბათი_სამშაბათი_ოთხშაბათი_ხუთშაბათი_პარასკევი_შაბათი'.split('_'), 'accusative': 'კვირას_ორშაბათს_სამშაბათს_ოთხშაბათს_ხუთშაბათს_პარასკევს_შაბათს'.split('_') }, nounCase = (/(წინა|შემდეგ)/).test(format) ? 'accusative' : 'nominative'; return weekdays[nounCase][m.day()]; } return moment.lang('ka', { months : monthsCaseReplace, monthsShort : "იან_თებ_მარ_აპრ_მაი_ივნ_ივლ_აგვ_სექ_ოქტ_ნოე_დეკ".split("_"), weekdays : weekdaysCaseReplace, weekdaysShort : "კვი_ორშ_სამ_ოთხ_ხუთ_პარ_შაბ".split("_"), weekdaysMin : "კვ_ორ_სა_ოთ_ხუ_პა_შა".split("_"), longDateFormat : { LT : "h:mm A", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[დღეს] LT[-ზე]', nextDay : '[ხვალ] LT[-ზე]', lastDay : '[გუშინ] LT[-ზე]', nextWeek : '[შემდეგ] dddd LT[-ზე]', lastWeek : '[წინა] dddd LT-ზე', sameElse : 'L' }, relativeTime : { future : function (s) { return (/(წამი|წუთი|საათი|წელი)/).test(s) ? s.replace(/ი$/, "ში") : s + "ში"; }, past : function (s) { if ((/(წამი|წუთი|საათი|დღე|თვე)/).test(s)) { return s.replace(/(ი|ე)$/, "ის წინ"); } if ((/წელი/).test(s)) { return s.replace(/წელი$/, "წლის წინ"); } }, s : "რამდენიმე წამი", m : "წუთი", mm : "%d წუთი", h : "საათი", hh : "%d საათი", d : "დღე", dd : "%d დღე", M : "თვე", MM : "%d თვე", y : "წელი", yy : "%d წელი" }, ordinal : function (number) { if (number === 0) { return number; } if (number === 1) { return number + "-ლი"; } if ((number < 20) || (number <= 100 && (number % 20 === 0)) || (number % 100 === 0)) { return "მე-" + number; } return number + "-ე"; }, week : { dow : 1, doy : 7 } }); })); // moment.js language configuration // language : korean (ko) // // authors // // - Kyungwook, Park : https://github.com/kyungw00k // - Jeeeyul Lee <jeeeyul@gmail.com> (function (factory) { factory(moment); }(function (moment) { return moment.lang('ko', { months : "1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"), monthsShort : "1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"), weekdays : "일요일_월요일_화요일_수요일_목요일_금요일_토요일".split("_"), weekdaysShort : "일_월_화_수_목_금_토".split("_"), weekdaysMin : "일_월_화_수_목_금_토".split("_"), longDateFormat : { LT : "A h시 mm분", L : "YYYY.MM.DD", LL : "YYYY년 MMMM D일", LLL : "YYYY년 MMMM D일 LT", LLLL : "YYYY년 MMMM D일 dddd LT" }, meridiem : function (hour, minute, isUpper) { return hour < 12 ? '오전' : '오후'; }, calendar : { sameDay : '오늘 LT', nextDay : '내일 LT', nextWeek : 'dddd LT', lastDay : '어제 LT', lastWeek : '지난주 dddd LT', sameElse : 'L' }, relativeTime : { future : "%s 후", past : "%s 전", s : "몇초", ss : "%d초", m : "일분", mm : "%d분", h : "한시간", hh : "%d시간", d : "하루", dd : "%d일", M : "한달", MM : "%d달", y : "일년", yy : "%d년" }, ordinal : '%d일', meridiemParse : /(오전|오후)/, isPM : function (token) { return token === "오후"; } }); })); // moment.js language configuration // language : Luxembourgish (lb) // author : mweimerskirch : https://github.com/mweimerskirch // Note: Luxembourgish has a very particular phonological rule ("Eifeler Regel") that causes the // deletion of the final "n" in certain contexts. That's what the "eifelerRegelAppliesToWeekday" // and "eifelerRegelAppliesToNumber" methods are meant for (function (factory) { factory(moment); }(function (moment) { function processRelativeTime(number, withoutSuffix, key, isFuture) { var format = { 'm': ['eng Minutt', 'enger Minutt'], 'h': ['eng Stonn', 'enger Stonn'], 'd': ['een Dag', 'engem Dag'], 'dd': [number + ' Deeg', number + ' Deeg'], 'M': ['ee Mount', 'engem Mount'], 'MM': [number + ' Méint', number + ' Méint'], 'y': ['ee Joer', 'engem Joer'], 'yy': [number + ' Joer', number + ' Joer'] }; return withoutSuffix ? format[key][0] : format[key][1]; } function processFutureTime(string) { var number = string.substr(0, string.indexOf(' ')); if (eifelerRegelAppliesToNumber(number)) { return "a " + string; } return "an " + string; } function processPastTime(string) { var number = string.substr(0, string.indexOf(' ')); if (eifelerRegelAppliesToNumber(number)) { return "viru " + string; } return "virun " + string; } function processLastWeek(string1) { var weekday = this.format('d'); if (eifelerRegelAppliesToWeekday(weekday)) { return '[Leschte] dddd [um] LT'; } return '[Leschten] dddd [um] LT'; } /** * Returns true if the word before the given week day loses the "-n" ending. * e.g. "Leschten Dënschdeg" but "Leschte Méindeg" * * @param weekday {integer} * @returns {boolean} */ function eifelerRegelAppliesToWeekday(weekday) { weekday = parseInt(weekday, 10); switch (weekday) { case 0: // Sonndeg case 1: // Méindeg case 3: // Mëttwoch case 5: // Freideg case 6: // Samschdeg return true; default: // 2 Dënschdeg, 4 Donneschdeg return false; } } /** * Returns true if the word before the given number loses the "-n" ending. * e.g. "an 10 Deeg" but "a 5 Deeg" * * @param number {integer} * @returns {boolean} */ function eifelerRegelAppliesToNumber(number) { number = parseInt(number, 10); if (isNaN(number)) { return false; } if (number < 0) { // Negative Number --> always true return true; } else if (number < 10) { // Only 1 digit if (4 <= number && number <= 7) { return true; } return false; } else if (number < 100) { // 2 digits var lastDigit = number % 10, firstDigit = number / 10; if (lastDigit === 0) { return eifelerRegelAppliesToNumber(firstDigit); } return eifelerRegelAppliesToNumber(lastDigit); } else if (number < 10000) { // 3 or 4 digits --> recursively check first digit while (number >= 10) { number = number / 10; } return eifelerRegelAppliesToNumber(number); } else { // Anything larger than 4 digits: recursively check first n-3 digits number = number / 1000; return eifelerRegelAppliesToNumber(number); } } return moment.lang('lb', { months: "Januar_Februar_Mäerz_Abrëll_Mee_Juni_Juli_August_September_Oktober_November_Dezember".split("_"), monthsShort: "Jan._Febr._Mrz._Abr._Mee_Jun._Jul._Aug._Sept._Okt._Nov._Dez.".split("_"), weekdays: "Sonndeg_Méindeg_Dënschdeg_Mëttwoch_Donneschdeg_Freideg_Samschdeg".split("_"), weekdaysShort: "So._Mé._Dë._Më._Do._Fr._Sa.".split("_"), weekdaysMin: "So_Mé_Dë_Më_Do_Fr_Sa".split("_"), longDateFormat: { LT: "H:mm [Auer]", L: "DD.MM.YYYY", LL: "D. MMMM YYYY", LLL: "D. MMMM YYYY LT", LLLL: "dddd, D. MMMM YYYY LT" }, calendar: { sameDay: "[Haut um] LT", sameElse: "L", nextDay: '[Muer um] LT', nextWeek: 'dddd [um] LT', lastDay: '[Gëschter um] LT', lastWeek: processLastWeek }, relativeTime: { future: processFutureTime, past: processPastTime, s: "e puer Sekonnen", m: processRelativeTime, mm: "%d Minutten", h: processRelativeTime, hh: "%d Stonnen", d: processRelativeTime, dd: processRelativeTime, M: processRelativeTime, MM: processRelativeTime, y: processRelativeTime, yy: processRelativeTime }, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : Lithuanian (lt) // author : Mindaugas Mozūras : https://github.com/mmozuras (function (factory) { factory(moment); }(function (moment) { var units = { "m" : "minutė_minutės_minutę", "mm": "minutės_minučių_minutes", "h" : "valanda_valandos_valandą", "hh": "valandos_valandų_valandas", "d" : "diena_dienos_dieną", "dd": "dienos_dienų_dienas", "M" : "mėnuo_mėnesio_mėnesį", "MM": "mėnesiai_mėnesių_mėnesius", "y" : "metai_metų_metus", "yy": "metai_metų_metus" }, weekDays = "pirmadienis_antradienis_trečiadienis_ketvirtadienis_penktadienis_šeštadienis_sekmadienis".split("_"); function translateSeconds(number, withoutSuffix, key, isFuture) { if (withoutSuffix) { return "kelios sekundės"; } else { return isFuture ? "kelių sekundžių" : "kelias sekundes"; } } function translateSingular(number, withoutSuffix, key, isFuture) { return withoutSuffix ? forms(key)[0] : (isFuture ? forms(key)[1] : forms(key)[2]); } function special(number) { return number % 10 === 0 || (number > 10 && number < 20); } function forms(key) { return units[key].split("_"); } function translate(number, withoutSuffix, key, isFuture) { var result = number + " "; if (number === 1) { return result + translateSingular(number, withoutSuffix, key[0], isFuture); } else if (withoutSuffix) { return result + (special(number) ? forms(key)[1] : forms(key)[0]); } else { if (isFuture) { return result + forms(key)[1]; } else { return result + (special(number) ? forms(key)[1] : forms(key)[2]); } } } function relativeWeekDay(moment, format) { var nominative = format.indexOf('dddd LT') === -1, weekDay = weekDays[moment.weekday()]; return nominative ? weekDay : weekDay.substring(0, weekDay.length - 2) + "į"; } return moment.lang("lt", { months : "sausio_vasario_kovo_balandžio_gegužės_biržėlio_liepos_rugpjūčio_rugsėjo_spalio_lapkričio_gruodžio".split("_"), monthsShort : "sau_vas_kov_bal_geg_bir_lie_rgp_rgs_spa_lap_grd".split("_"), weekdays : relativeWeekDay, weekdaysShort : "Sek_Pir_Ant_Tre_Ket_Pen_Šeš".split("_"), weekdaysMin : "S_P_A_T_K_Pn_Š".split("_"), longDateFormat : { LT : "HH:mm", L : "YYYY-MM-DD", LL : "YYYY [m.] MMMM D [d.]", LLL : "YYYY [m.] MMMM D [d.], LT [val.]", LLLL : "YYYY [m.] MMMM D [d.], dddd, LT [val.]", l : "YYYY-MM-DD", ll : "YYYY [m.] MMMM D [d.]", lll : "YYYY [m.] MMMM D [d.], LT [val.]", llll : "YYYY [m.] MMMM D [d.], ddd, LT [val.]" }, calendar : { sameDay : "[Šiandien] LT", nextDay : "[Rytoj] LT", nextWeek : "dddd LT", lastDay : "[Vakar] LT", lastWeek : "[Praėjusį] dddd LT", sameElse : "L" }, relativeTime : { future : "po %s", past : "prieš %s", s : translateSeconds, m : translateSingular, mm : translate, h : translateSingular, hh : translate, d : translateSingular, dd : translate, M : translateSingular, MM : translate, y : translateSingular, yy : translate }, ordinal : function (number) { return number + '-oji'; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : latvian (lv) // author : Kristaps Karlsons : https://github.com/skakri (function (factory) { factory(moment); }(function (moment) { var units = { 'mm': 'minūti_minūtes_minūte_minūtes', 'hh': 'stundu_stundas_stunda_stundas', 'dd': 'dienu_dienas_diena_dienas', 'MM': 'mēnesi_mēnešus_mēnesis_mēneši', 'yy': 'gadu_gadus_gads_gadi' }; function format(word, number, withoutSuffix) { var forms = word.split('_'); if (withoutSuffix) { return number % 10 === 1 && number !== 11 ? forms[2] : forms[3]; } else { return number % 10 === 1 && number !== 11 ? forms[0] : forms[1]; } } function relativeTimeWithPlural(number, withoutSuffix, key) { return number + ' ' + format(units[key], number, withoutSuffix); } return moment.lang('lv', { months : "janvāris_februāris_marts_aprīlis_maijs_jūnijs_jūlijs_augusts_septembris_oktobris_novembris_decembris".split("_"), monthsShort : "jan_feb_mar_apr_mai_jūn_jūl_aug_sep_okt_nov_dec".split("_"), weekdays : "svētdiena_pirmdiena_otrdiena_trešdiena_ceturtdiena_piektdiena_sestdiena".split("_"), weekdaysShort : "Sv_P_O_T_C_Pk_S".split("_"), weekdaysMin : "Sv_P_O_T_C_Pk_S".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "YYYY. [gada] D. MMMM", LLL : "YYYY. [gada] D. MMMM, LT", LLLL : "YYYY. [gada] D. MMMM, dddd, LT" }, calendar : { sameDay : '[Šodien pulksten] LT', nextDay : '[Rīt pulksten] LT', nextWeek : 'dddd [pulksten] LT', lastDay : '[Vakar pulksten] LT', lastWeek : '[Pagājušā] dddd [pulksten] LT', sameElse : 'L' }, relativeTime : { future : "%s vēlāk", past : "%s agrāk", s : "dažas sekundes", m : "minūti", mm : relativeTimeWithPlural, h : "stundu", hh : relativeTimeWithPlural, d : "dienu", dd : relativeTimeWithPlural, M : "mēnesi", MM : relativeTimeWithPlural, y : "gadu", yy : relativeTimeWithPlural }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : macedonian (mk) // author : Borislav Mickov : https://github.com/B0k0 (function (factory) { factory(moment); }(function (moment) { return moment.lang('mk', { months : "јануари_февруари_март_април_мај_јуни_јули_август_септември_октомври_ноември_декември".split("_"), monthsShort : "јан_фев_мар_апр_мај_јун_јул_авг_сеп_окт_ное_дек".split("_"), weekdays : "недела_понеделник_вторник_среда_четврток_петок_сабота".split("_"), weekdaysShort : "нед_пон_вто_сре_чет_пет_саб".split("_"), weekdaysMin : "нe_пo_вт_ср_че_пе_сa".split("_"), longDateFormat : { LT : "H:mm", L : "D.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[Денес во] LT', nextDay : '[Утре во] LT', nextWeek : 'dddd [во] LT', lastDay : '[Вчера во] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: case 6: return '[Во изминатата] dddd [во] LT'; case 1: case 2: case 4: case 5: return '[Во изминатиот] dddd [во] LT'; } }, sameElse : 'L' }, relativeTime : { future : "после %s", past : "пред %s", s : "неколку секунди", m : "минута", mm : "%d минути", h : "час", hh : "%d часа", d : "ден", dd : "%d дена", M : "месец", MM : "%d месеци", y : "година", yy : "%d години" }, ordinal : function (number) { var lastDigit = number % 10, last2Digits = number % 100; if (number === 0) { return number + '-ев'; } else if (last2Digits === 0) { return number + '-ен'; } else if (last2Digits > 10 && last2Digits < 20) { return number + '-ти'; } else if (lastDigit === 1) { return number + '-ви'; } else if (lastDigit === 2) { return number + '-ри'; } else if (lastDigit === 7 || lastDigit === 8) { return number + '-ми'; } else { return number + '-ти'; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : malayalam (ml) // author : Floyd Pink : https://github.com/floydpink (function (factory) { factory(moment); }(function (moment) { return moment.lang('ml', { months : 'ജനുവരി_ഫെബ്രുവരി_മാർച്ച്_ഏപ്രിൽ_മേയ്_ജൂൺ_ജൂലൈ_ഓഗസ്റ്റ്_സെപ്റ്റംബർ_ഒക്ടോബർ_നവംബർ_ഡിസംബർ'.split("_"), monthsShort : 'ജനു._ഫെബ്രു._മാർ._ഏപ്രി._മേയ്_ജൂൺ_ജൂലൈ._ഓഗ._സെപ്റ്റ._ഒക്ടോ._നവം._ഡിസം.'.split("_"), weekdays : 'ഞായറാഴ്ച_തിങ്കളാഴ്ച_ചൊവ്വാഴ്ച_ബുധനാഴ്ച_വ്യാഴാഴ്ച_വെള്ളിയാഴ്ച_ശനിയാഴ്ച'.split("_"), weekdaysShort : 'ഞായർ_തിങ്കൾ_ചൊവ്വ_ബുധൻ_വ്യാഴം_വെള്ളി_ശനി'.split("_"), weekdaysMin : 'ഞാ_തി_ചൊ_ബു_വ്യാ_വെ_ശ'.split("_"), longDateFormat : { LT : "A h:mm -നു", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY, LT", LLLL : "dddd, D MMMM YYYY, LT" }, calendar : { sameDay : '[ഇന്ന്] LT', nextDay : '[നാളെ] LT', nextWeek : 'dddd, LT', lastDay : '[ഇന്നലെ] LT', lastWeek : '[കഴിഞ്ഞ] dddd, LT', sameElse : 'L' }, relativeTime : { future : "%s കഴിഞ്ഞ്", past : "%s മുൻപ്", s : "അൽപ നിമിഷങ്ങൾ", m : "ഒരു മിനിറ്റ്", mm : "%d മിനിറ്റ്", h : "ഒരു മണിക്കൂർ", hh : "%d മണിക്കൂർ", d : "ഒരു ദിവസം", dd : "%d ദിവസം", M : "ഒരു മാസം", MM : "%d മാസം", y : "ഒരു വർഷം", yy : "%d വർഷം" }, meridiem : function (hour, minute, isLower) { if (hour < 4) { return "രാത്രി"; } else if (hour < 12) { return "രാവിലെ"; } else if (hour < 17) { return "ഉച്ച കഴിഞ്ഞ്"; } else if (hour < 20) { return "വൈകുന്നേരം"; } else { return "രാത്രി"; } } }); })); // moment.js language configuration // language : Marathi (mr) // author : Harshad Kale : https://github.com/kalehv (function (factory) { factory(moment); }(function (moment) { var symbolMap = { '1': '१', '2': '२', '3': '३', '4': '४', '5': '५', '6': '६', '7': '७', '8': '८', '9': '९', '0': '०' }, numberMap = { '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9', '०': '0' }; return moment.lang('mr', { months : 'जानेवारी_फेब्रुवारी_मार्च_एप्रिल_मे_जून_जुलै_ऑगस्ट_सप्टेंबर_ऑक्टोबर_नोव्हेंबर_डिसेंबर'.split("_"), monthsShort: 'जाने._फेब्रु._मार्च._एप्रि._मे._जून._जुलै._ऑग._सप्टें._ऑक्टो._नोव्हें._डिसें.'.split("_"), weekdays : 'रविवार_सोमवार_मंगळवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split("_"), weekdaysShort : 'रवि_सोम_मंगळ_बुध_गुरू_शुक्र_शनि'.split("_"), weekdaysMin : 'र_सो_मं_बु_गु_शु_श'.split("_"), longDateFormat : { LT : "A h:mm वाजता", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY, LT", LLLL : "dddd, D MMMM YYYY, LT" }, calendar : { sameDay : '[आज] LT', nextDay : '[उद्या] LT', nextWeek : 'dddd, LT', lastDay : '[काल] LT', lastWeek: '[मागील] dddd, LT', sameElse : 'L' }, relativeTime : { future : "%s नंतर", past : "%s पूर्वी", s : "सेकंद", m: "एक मिनिट", mm: "%d मिनिटे", h : "एक तास", hh : "%d तास", d : "एक दिवस", dd : "%d दिवस", M : "एक महिना", MM : "%d महिने", y : "एक वर्ष", yy : "%d वर्षे" }, preparse: function (string) { return string.replace(/[१२३४५६७८९०]/g, function (match) { return numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }); }, meridiem: function (hour, minute, isLower) { if (hour < 4) { return "रात्री"; } else if (hour < 10) { return "सकाळी"; } else if (hour < 17) { return "दुपारी"; } else if (hour < 20) { return "सायंकाळी"; } else { return "रात्री"; } }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Bahasa Malaysia (ms-MY) // author : Weldan Jamili : https://github.com/weldan (function (factory) { factory(moment); }(function (moment) { return moment.lang('ms-my', { months : "Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember".split("_"), monthsShort : "Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis".split("_"), weekdays : "Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu".split("_"), weekdaysShort : "Ahd_Isn_Sel_Rab_Kha_Jum_Sab".split("_"), weekdaysMin : "Ah_Is_Sl_Rb_Km_Jm_Sb".split("_"), longDateFormat : { LT : "HH.mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY [pukul] LT", LLLL : "dddd, D MMMM YYYY [pukul] LT" }, meridiem : function (hours, minutes, isLower) { if (hours < 11) { return 'pagi'; } else if (hours < 15) { return 'tengahari'; } else if (hours < 19) { return 'petang'; } else { return 'malam'; } }, calendar : { sameDay : '[Hari ini pukul] LT', nextDay : '[Esok pukul] LT', nextWeek : 'dddd [pukul] LT', lastDay : '[Kelmarin pukul] LT', lastWeek : 'dddd [lepas pukul] LT', sameElse : 'L' }, relativeTime : { future : "dalam %s", past : "%s yang lepas", s : "beberapa saat", m : "seminit", mm : "%d minit", h : "sejam", hh : "%d jam", d : "sehari", dd : "%d hari", M : "sebulan", MM : "%d bulan", y : "setahun", yy : "%d tahun" }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : norwegian bokmål (nb) // authors : Espen Hovlandsdal : https://github.com/rexxars // Sigurd Gartmann : https://github.com/sigurdga (function (factory) { factory(moment); }(function (moment) { return moment.lang('nb', { months : "januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember".split("_"), monthsShort : "jan._feb._mars_april_mai_juni_juli_aug._sep._okt._nov._des.".split("_"), weekdays : "søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag".split("_"), weekdaysShort : "sø._ma._ti._on._to._fr._lø.".split("_"), weekdaysMin : "sø_ma_ti_on_to_fr_lø".split("_"), longDateFormat : { LT : "H.mm", L : "DD.MM.YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY [kl.] LT", LLLL : "dddd D. MMMM YYYY [kl.] LT" }, calendar : { sameDay: '[i dag kl.] LT', nextDay: '[i morgen kl.] LT', nextWeek: 'dddd [kl.] LT', lastDay: '[i går kl.] LT', lastWeek: '[forrige] dddd [kl.] LT', sameElse: 'L' }, relativeTime : { future : "om %s", past : "for %s siden", s : "noen sekunder", m : "ett minutt", mm : "%d minutter", h : "en time", hh : "%d timer", d : "en dag", dd : "%d dager", M : "en måned", MM : "%d måneder", y : "ett år", yy : "%d år" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : nepali/nepalese // author : suvash : https://github.com/suvash (function (factory) { factory(moment); }(function (moment) { var symbolMap = { '1': '१', '2': '२', '3': '३', '4': '४', '5': '५', '6': '६', '7': '७', '8': '८', '9': '९', '0': '०' }, numberMap = { '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9', '०': '0' }; return moment.lang('ne', { months : 'जनवरी_फेब्रुवरी_मार्च_अप्रिल_मई_जुन_जुलाई_अगष्ट_सेप्टेम्बर_अक्टोबर_नोभेम्बर_डिसेम्बर'.split("_"), monthsShort : 'जन._फेब्रु._मार्च_अप्रि._मई_जुन_जुलाई._अग._सेप्ट._अक्टो._नोभे._डिसे.'.split("_"), weekdays : 'आइतबार_सोमबार_मङ्गलबार_बुधबार_बिहिबार_शुक्रबार_शनिबार'.split("_"), weekdaysShort : 'आइत._सोम._मङ्गल._बुध._बिहि._शुक्र._शनि.'.split("_"), weekdaysMin : 'आइ._सो._मङ्_बु._बि._शु._श.'.split("_"), longDateFormat : { LT : "Aको h:mm बजे", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY, LT", LLLL : "dddd, D MMMM YYYY, LT" }, preparse: function (string) { return string.replace(/[१२३४५६७८९०]/g, function (match) { return numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }); }, meridiem : function (hour, minute, isLower) { if (hour < 3) { return "राती"; } else if (hour < 10) { return "बिहान"; } else if (hour < 15) { return "दिउँसो"; } else if (hour < 18) { return "बेलुका"; } else if (hour < 20) { return "साँझ"; } else { return "राती"; } }, calendar : { sameDay : '[आज] LT', nextDay : '[भोली] LT', nextWeek : '[आउँदो] dddd[,] LT', lastDay : '[हिजो] LT', lastWeek : '[गएको] dddd[,] LT', sameElse : 'L' }, relativeTime : { future : "%sमा", past : "%s अगाडी", s : "केही समय", m : "एक मिनेट", mm : "%d मिनेट", h : "एक घण्टा", hh : "%d घण्टा", d : "एक दिन", dd : "%d दिन", M : "एक महिना", MM : "%d महिना", y : "एक बर्ष", yy : "%d बर्ष" }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : dutch (nl) // author : Joris Röling : https://github.com/jjupiter (function (factory) { factory(moment); }(function (moment) { var monthsShortWithDots = "jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.".split("_"), monthsShortWithoutDots = "jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec".split("_"); return moment.lang('nl', { months : "januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december".split("_"), monthsShort : function (m, format) { if (/-MMM-/.test(format)) { return monthsShortWithoutDots[m.month()]; } else { return monthsShortWithDots[m.month()]; } }, weekdays : "zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag".split("_"), weekdaysShort : "zo._ma._di._wo._do._vr._za.".split("_"), weekdaysMin : "Zo_Ma_Di_Wo_Do_Vr_Za".split("_"), longDateFormat : { LT : "HH:mm", L : "DD-MM-YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: '[vandaag om] LT', nextDay: '[morgen om] LT', nextWeek: 'dddd [om] LT', lastDay: '[gisteren om] LT', lastWeek: '[afgelopen] dddd [om] LT', sameElse: 'L' }, relativeTime : { future : "over %s", past : "%s geleden", s : "een paar seconden", m : "één minuut", mm : "%d minuten", h : "één uur", hh : "%d uur", d : "één dag", dd : "%d dagen", M : "één maand", MM : "%d maanden", y : "één jaar", yy : "%d jaar" }, ordinal : function (number) { return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de'); }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : norwegian nynorsk (nn) // author : https://github.com/mechuwind (function (factory) { factory(moment); }(function (moment) { return moment.lang('nn', { months : "januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember".split("_"), monthsShort : "jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"), weekdays : "sundag_måndag_tysdag_onsdag_torsdag_fredag_laurdag".split("_"), weekdaysShort : "sun_mån_tys_ons_tor_fre_lau".split("_"), weekdaysMin : "su_må_ty_on_to_fr_lø".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: '[I dag klokka] LT', nextDay: '[I morgon klokka] LT', nextWeek: 'dddd [klokka] LT', lastDay: '[I går klokka] LT', lastWeek: '[Føregående] dddd [klokka] LT', sameElse: 'L' }, relativeTime : { future : "om %s", past : "for %s siden", s : "noen sekund", m : "ett minutt", mm : "%d minutt", h : "en time", hh : "%d timar", d : "en dag", dd : "%d dagar", M : "en månad", MM : "%d månader", y : "ett år", yy : "%d år" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : polish (pl) // author : Rafal Hirsz : https://github.com/evoL (function (factory) { factory(moment); }(function (moment) { var monthsNominative = "styczeń_luty_marzec_kwiecień_maj_czerwiec_lipiec_sierpień_wrzesień_październik_listopad_grudzień".split("_"), monthsSubjective = "stycznia_lutego_marca_kwietnia_maja_czerwca_lipca_sierpnia_września_października_listopada_grudnia".split("_"); function plural(n) { return (n % 10 < 5) && (n % 10 > 1) && ((~~(n / 10) % 10) !== 1); } function translate(number, withoutSuffix, key) { var result = number + " "; switch (key) { case 'm': return withoutSuffix ? 'minuta' : 'minutę'; case 'mm': return result + (plural(number) ? 'minuty' : 'minut'); case 'h': return withoutSuffix ? 'godzina' : 'godzinę'; case 'hh': return result + (plural(number) ? 'godziny' : 'godzin'); case 'MM': return result + (plural(number) ? 'miesiące' : 'miesięcy'); case 'yy': return result + (plural(number) ? 'lata' : 'lat'); } } return moment.lang('pl', { months : function (momentToFormat, format) { if (/D MMMM/.test(format)) { return monthsSubjective[momentToFormat.month()]; } else { return monthsNominative[momentToFormat.month()]; } }, monthsShort : "sty_lut_mar_kwi_maj_cze_lip_sie_wrz_paź_lis_gru".split("_"), weekdays : "niedziela_poniedziałek_wtorek_środa_czwartek_piątek_sobota".split("_"), weekdaysShort : "nie_pon_wt_śr_czw_pt_sb".split("_"), weekdaysMin : "N_Pn_Wt_Śr_Cz_Pt_So".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay: '[Dziś o] LT', nextDay: '[Jutro o] LT', nextWeek: '[W] dddd [o] LT', lastDay: '[Wczoraj o] LT', lastWeek: function () { switch (this.day()) { case 0: return '[W zeszłą niedzielę o] LT'; case 3: return '[W zeszłą środę o] LT'; case 6: return '[W zeszłą sobotę o] LT'; default: return '[W zeszły] dddd [o] LT'; } }, sameElse: 'L' }, relativeTime : { future : "za %s", past : "%s temu", s : "kilka sekund", m : translate, mm : translate, h : translate, hh : translate, d : "1 dzień", dd : '%d dni', M : "miesiąc", MM : translate, y : "rok", yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : brazilian portuguese (pt-br) // author : Caio Ribeiro Pereira : https://github.com/caio-ribeiro-pereira (function (factory) { factory(moment); }(function (moment) { return moment.lang('pt-br', { months : "Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro".split("_"), monthsShort : "Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez".split("_"), weekdays : "Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado".split("_"), weekdaysShort : "Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"), weekdaysMin : "Dom_2ª_3ª_4ª_5ª_6ª_Sáb".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D [de] MMMM [de] YYYY", LLL : "D [de] MMMM [de] YYYY LT", LLLL : "dddd, D [de] MMMM [de] YYYY LT" }, calendar : { sameDay: '[Hoje às] LT', nextDay: '[Amanhã às] LT', nextWeek: 'dddd [às] LT', lastDay: '[Ontem às] LT', lastWeek: function () { return (this.day() === 0 || this.day() === 6) ? '[Último] dddd [às] LT' : // Saturday + Sunday '[Última] dddd [às] LT'; // Monday - Friday }, sameElse: 'L' }, relativeTime : { future : "em %s", past : "%s atrás", s : "segundos", m : "um minuto", mm : "%d minutos", h : "uma hora", hh : "%d horas", d : "um dia", dd : "%d dias", M : "um mês", MM : "%d meses", y : "um ano", yy : "%d anos" }, ordinal : '%dº' }); })); // moment.js language configuration // language : portuguese (pt) // author : Jefferson : https://github.com/jalex79 (function (factory) { factory(moment); }(function (moment) { return moment.lang('pt', { months : "Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro".split("_"), monthsShort : "Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez".split("_"), weekdays : "Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado".split("_"), weekdaysShort : "Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"), weekdaysMin : "Dom_2ª_3ª_4ª_5ª_6ª_Sáb".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D [de] MMMM [de] YYYY", LLL : "D [de] MMMM [de] YYYY LT", LLLL : "dddd, D [de] MMMM [de] YYYY LT" }, calendar : { sameDay: '[Hoje às] LT', nextDay: '[Amanhã às] LT', nextWeek: 'dddd [às] LT', lastDay: '[Ontem às] LT', lastWeek: function () { return (this.day() === 0 || this.day() === 6) ? '[Último] dddd [às] LT' : // Saturday + Sunday '[Última] dddd [às] LT'; // Monday - Friday }, sameElse: 'L' }, relativeTime : { future : "em %s", past : "%s atrás", s : "segundos", m : "um minuto", mm : "%d minutos", h : "uma hora", hh : "%d horas", d : "um dia", dd : "%d dias", M : "um mês", MM : "%d meses", y : "um ano", yy : "%d anos" }, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : romanian (ro) // author : Vlad Gurdiga : https://github.com/gurdiga // author : Valentin Agachi : https://github.com/avaly (function (factory) { factory(moment); }(function (moment) { function relativeTimeWithPlural(number, withoutSuffix, key) { var format = { 'mm': 'minute', 'hh': 'ore', 'dd': 'zile', 'MM': 'luni', 'yy': 'ani' }, separator = ' '; if (number % 100 >= 20 || (number >= 100 && number % 100 === 0)) { separator = ' de '; } return number + separator + format[key]; } return moment.lang('ro', { months : "ianuarie_februarie_martie_aprilie_mai_iunie_iulie_august_septembrie_octombrie_noiembrie_decembrie".split("_"), monthsShort : "ian_feb_mar_apr_mai_iun_iul_aug_sep_oct_noi_dec".split("_"), weekdays : "duminică_luni_marți_miercuri_joi_vineri_sâmbătă".split("_"), weekdaysShort : "Dum_Lun_Mar_Mie_Joi_Vin_Sâm".split("_"), weekdaysMin : "Du_Lu_Ma_Mi_Jo_Vi_Sâ".split("_"), longDateFormat : { LT : "H:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY H:mm", LLLL : "dddd, D MMMM YYYY H:mm" }, calendar : { sameDay: "[azi la] LT", nextDay: '[mâine la] LT', nextWeek: 'dddd [la] LT', lastDay: '[ieri la] LT', lastWeek: '[fosta] dddd [la] LT', sameElse: 'L' }, relativeTime : { future : "peste %s", past : "%s în urmă", s : "câteva secunde", m : "un minut", mm : relativeTimeWithPlural, h : "o oră", hh : relativeTimeWithPlural, d : "o zi", dd : relativeTimeWithPlural, M : "o lună", MM : relativeTimeWithPlural, y : "un an", yy : relativeTimeWithPlural }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : serbian (rs) // author : Limon Monte : https://github.com/limonte // based on (bs) translation by Nedim Cholich (function (factory) { factory(moment); }(function (moment) { function translate(number, withoutSuffix, key) { var result = number + " "; switch (key) { case 'm': return withoutSuffix ? 'jedna minuta' : 'jedne minute'; case 'mm': if (number === 1) { result += 'minuta'; } else if (number === 2 || number === 3 || number === 4) { result += 'minute'; } else { result += 'minuta'; } return result; case 'h': return withoutSuffix ? 'jedan sat' : 'jednog sata'; case 'hh': if (number === 1) { result += 'sat'; } else if (number === 2 || number === 3 || number === 4) { result += 'sata'; } else { result += 'sati'; } return result; case 'dd': if (number === 1) { result += 'dan'; } else { result += 'dana'; } return result; case 'MM': if (number === 1) { result += 'mesec'; } else if (number === 2 || number === 3 || number === 4) { result += 'meseca'; } else { result += 'meseci'; } return result; case 'yy': if (number === 1) { result += 'godina'; } else if (number === 2 || number === 3 || number === 4) { result += 'godine'; } else { result += 'godina'; } return result; } } return moment.lang('rs', { months : "januar_februar_mart_april_maj_jun_jul_avgust_septembar_oktobar_novembar_decembar".split("_"), monthsShort : "jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.".split("_"), weekdays : "nedelja_ponedeljak_utorak_sreda_četvrtak_petak_subota".split("_"), weekdaysShort : "ned._pon._uto._sre._čet._pet._sub.".split("_"), weekdaysMin : "ne_po_ut_sr_če_pe_su".split("_"), longDateFormat : { LT : "H:mm", L : "DD. MM. YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay : '[danas u] LT', nextDay : '[sutra u] LT', nextWeek : function () { switch (this.day()) { case 0: return '[u] [nedelju] [u] LT'; case 3: return '[u] [sredu] [u] LT'; case 6: return '[u] [subotu] [u] LT'; case 1: case 2: case 4: case 5: return '[u] dddd [u] LT'; } }, lastDay : '[juče u] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: return '[prošlu] dddd [u] LT'; case 6: return '[prošle] [subote] [u] LT'; case 1: case 2: case 4: case 5: return '[prošli] dddd [u] LT'; } }, sameElse : 'L' }, relativeTime : { future : "za %s", past : "pre %s", s : "par sekundi", m : translate, mm : translate, h : translate, hh : translate, d : "dan", dd : translate, M : "mesec", MM : translate, y : "godinu", yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : russian (ru) // author : Viktorminator : https://github.com/Viktorminator // Author : Menelion Elensúle : https://github.com/Oire (function (factory) { factory(moment); }(function (moment) { function plural(word, num) { var forms = word.split('_'); return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]); } function relativeTimeWithPlural(number, withoutSuffix, key) { var format = { 'mm': 'минута_минуты_минут', 'hh': 'час_часа_часов', 'dd': 'день_дня_дней', 'MM': 'месяц_месяца_месяцев', 'yy': 'год_года_лет' }; if (key === 'm') { return withoutSuffix ? 'минута' : 'минуту'; } else { return number + ' ' + plural(format[key], +number); } } function monthsCaseReplace(m, format) { var months = { 'nominative': 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_'), 'accusative': 'января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря'.split('_') }, nounCase = (/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/).test(format) ? 'accusative' : 'nominative'; return months[nounCase][m.month()]; } function monthsShortCaseReplace(m, format) { var monthsShort = { 'nominative': 'янв_фев_мар_апр_май_июнь_июль_авг_сен_окт_ноя_дек'.split('_'), 'accusative': 'янв_фев_мар_апр_мая_июня_июля_авг_сен_окт_ноя_дек'.split('_') }, nounCase = (/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/).test(format) ? 'accusative' : 'nominative'; return monthsShort[nounCase][m.month()]; } function weekdaysCaseReplace(m, format) { var weekdays = { 'nominative': 'воскресенье_понедельник_вторник_среда_четверг_пятница_суббота'.split('_'), 'accusative': 'воскресенье_понедельник_вторник_среду_четверг_пятницу_субботу'.split('_') }, nounCase = (/\[ ?[Вв] ?(?:прошлую|следующую)? ?\] ?dddd/).test(format) ? 'accusative' : 'nominative'; return weekdays[nounCase][m.day()]; } return moment.lang('ru', { months : monthsCaseReplace, monthsShort : monthsShortCaseReplace, weekdays : weekdaysCaseReplace, weekdaysShort : "вс_пн_вт_ср_чт_пт_сб".split("_"), weekdaysMin : "вс_пн_вт_ср_чт_пт_сб".split("_"), monthsParse : [/^янв/i, /^фев/i, /^мар/i, /^апр/i, /^ма[й|я]/i, /^июн/i, /^июл/i, /^авг/i, /^сен/i, /^окт/i, /^ноя/i, /^дек/i], longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY г.", LLL : "D MMMM YYYY г., LT", LLLL : "dddd, D MMMM YYYY г., LT" }, calendar : { sameDay: '[Сегодня в] LT', nextDay: '[Завтра в] LT', lastDay: '[Вчера в] LT', nextWeek: function () { return this.day() === 2 ? '[Во] dddd [в] LT' : '[В] dddd [в] LT'; }, lastWeek: function () { switch (this.day()) { case 0: return '[В прошлое] dddd [в] LT'; case 1: case 2: case 4: return '[В прошлый] dddd [в] LT'; case 3: case 5: case 6: return '[В прошлую] dddd [в] LT'; } }, sameElse: 'L' }, relativeTime : { future : "через %s", past : "%s назад", s : "несколько секунд", m : relativeTimeWithPlural, mm : relativeTimeWithPlural, h : "час", hh : relativeTimeWithPlural, d : "день", dd : relativeTimeWithPlural, M : "месяц", MM : relativeTimeWithPlural, y : "год", yy : relativeTimeWithPlural }, // M. E.: those two are virtually unused but a user might want to implement them for his/her website for some reason meridiem : function (hour, minute, isLower) { if (hour < 4) { return "ночи"; } else if (hour < 12) { return "утра"; } else if (hour < 17) { return "дня"; } else { return "вечера"; } }, ordinal: function (number, period) { switch (period) { case 'M': case 'd': case 'DDD': return number + '-й'; case 'D': return number + '-го'; case 'w': case 'W': return number + '-я'; default: return number; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : slovak (sk) // author : Martin Minka : https://github.com/k2s // based on work of petrbela : https://github.com/petrbela (function (factory) { factory(moment); }(function (moment) { var months = "január_február_marec_apríl_máj_jún_júl_august_september_október_november_december".split("_"), monthsShort = "jan_feb_mar_apr_máj_jún_júl_aug_sep_okt_nov_dec".split("_"); function plural(n) { return (n > 1) && (n < 5); } function translate(number, withoutSuffix, key, isFuture) { var result = number + " "; switch (key) { case 's': // a few seconds / in a few seconds / a few seconds ago return (withoutSuffix || isFuture) ? 'pár sekúnd' : 'pár sekundami'; case 'm': // a minute / in a minute / a minute ago return withoutSuffix ? 'minúta' : (isFuture ? 'minútu' : 'minútou'); case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'minúty' : 'minút'); } else { return result + 'minútami'; } break; case 'h': // an hour / in an hour / an hour ago return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou'); case 'hh': // 9 hours / in 9 hours / 9 hours ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'hodiny' : 'hodín'); } else { return result + 'hodinami'; } break; case 'd': // a day / in a day / a day ago return (withoutSuffix || isFuture) ? 'deň' : 'dňom'; case 'dd': // 9 days / in 9 days / 9 days ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'dni' : 'dní'); } else { return result + 'dňami'; } break; case 'M': // a month / in a month / a month ago return (withoutSuffix || isFuture) ? 'mesiac' : 'mesiacom'; case 'MM': // 9 months / in 9 months / 9 months ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'mesiace' : 'mesiacov'); } else { return result + 'mesiacmi'; } break; case 'y': // a year / in a year / a year ago return (withoutSuffix || isFuture) ? 'rok' : 'rokom'; case 'yy': // 9 years / in 9 years / 9 years ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'roky' : 'rokov'); } else { return result + 'rokmi'; } break; } } return moment.lang('sk', { months : months, monthsShort : monthsShort, monthsParse : (function (months, monthsShort) { var i, _monthsParse = []; for (i = 0; i < 12; i++) { // use custom parser to solve problem with July (červenec) _monthsParse[i] = new RegExp('^' + months[i] + '$|^' + monthsShort[i] + '$', 'i'); } return _monthsParse; }(months, monthsShort)), weekdays : "nedeľa_pondelok_utorok_streda_štvrtok_piatok_sobota".split("_"), weekdaysShort : "ne_po_ut_st_št_pi_so".split("_"), weekdaysMin : "ne_po_ut_st_št_pi_so".split("_"), longDateFormat : { LT: "H:mm", L : "DD.MM.YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd D. MMMM YYYY LT" }, calendar : { sameDay: "[dnes o] LT", nextDay: '[zajtra o] LT', nextWeek: function () { switch (this.day()) { case 0: return '[v nedeľu o] LT'; case 1: case 2: return '[v] dddd [o] LT'; case 3: return '[v stredu o] LT'; case 4: return '[vo štvrtok o] LT'; case 5: return '[v piatok o] LT'; case 6: return '[v sobotu o] LT'; } }, lastDay: '[včera o] LT', lastWeek: function () { switch (this.day()) { case 0: return '[minulú nedeľu o] LT'; case 1: case 2: return '[minulý] dddd [o] LT'; case 3: return '[minulú stredu o] LT'; case 4: case 5: return '[minulý] dddd [o] LT'; case 6: return '[minulú sobotu o] LT'; } }, sameElse: "L" }, relativeTime : { future : "za %s", past : "pred %s", s : translate, m : translate, mm : translate, h : translate, hh : translate, d : translate, dd : translate, M : translate, MM : translate, y : translate, yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : slovenian (sl) // author : Robert Sedovšek : https://github.com/sedovsek (function (factory) { factory(moment); }(function (moment) { function translate(number, withoutSuffix, key) { var result = number + " "; switch (key) { case 'm': return withoutSuffix ? 'ena minuta' : 'eno minuto'; case 'mm': if (number === 1) { result += 'minuta'; } else if (number === 2) { result += 'minuti'; } else if (number === 3 || number === 4) { result += 'minute'; } else { result += 'minut'; } return result; case 'h': return withoutSuffix ? 'ena ura' : 'eno uro'; case 'hh': if (number === 1) { result += 'ura'; } else if (number === 2) { result += 'uri'; } else if (number === 3 || number === 4) { result += 'ure'; } else { result += 'ur'; } return result; case 'dd': if (number === 1) { result += 'dan'; } else { result += 'dni'; } return result; case 'MM': if (number === 1) { result += 'mesec'; } else if (number === 2) { result += 'meseca'; } else if (number === 3 || number === 4) { result += 'mesece'; } else { result += 'mesecev'; } return result; case 'yy': if (number === 1) { result += 'leto'; } else if (number === 2) { result += 'leti'; } else if (number === 3 || number === 4) { result += 'leta'; } else { result += 'let'; } return result; } } return moment.lang('sl', { months : "januar_februar_marec_april_maj_junij_julij_avgust_september_oktober_november_december".split("_"), monthsShort : "jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.".split("_"), weekdays : "nedelja_ponedeljek_torek_sreda_četrtek_petek_sobota".split("_"), weekdaysShort : "ned._pon._tor._sre._čet._pet._sob.".split("_"), weekdaysMin : "ne_po_to_sr_če_pe_so".split("_"), longDateFormat : { LT : "H:mm", L : "DD. MM. YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay : '[danes ob] LT', nextDay : '[jutri ob] LT', nextWeek : function () { switch (this.day()) { case 0: return '[v] [nedeljo] [ob] LT'; case 3: return '[v] [sredo] [ob] LT'; case 6: return '[v] [soboto] [ob] LT'; case 1: case 2: case 4: case 5: return '[v] dddd [ob] LT'; } }, lastDay : '[včeraj ob] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: case 6: return '[prejšnja] dddd [ob] LT'; case 1: case 2: case 4: case 5: return '[prejšnji] dddd [ob] LT'; } }, sameElse : 'L' }, relativeTime : { future : "čez %s", past : "%s nazaj", s : "nekaj sekund", m : translate, mm : translate, h : translate, hh : translate, d : "en dan", dd : translate, M : "en mesec", MM : translate, y : "eno leto", yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Albanian (sq) // author : Flakërim Ismani : https://github.com/flakerimi // author: Menelion Elensúle: https://github.com/Oire (tests) (function (factory) { factory(moment); }(function (moment) { return moment.lang('sq', { months : "Janar_Shkurt_Mars_Prill_Maj_Qershor_Korrik_Gusht_Shtator_Tetor_Nëntor_Dhjetor".split("_"), monthsShort : "Jan_Shk_Mar_Pri_Maj_Qer_Kor_Gus_Sht_Tet_Nën_Dhj".split("_"), weekdays : "E Diel_E Hënë_E Marte_E Mërkure_E Enjte_E Premte_E Shtunë".split("_"), weekdaysShort : "Die_Hën_Mar_Mër_Enj_Pre_Sht".split("_"), weekdaysMin : "D_H_Ma_Më_E_P_Sh".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[Sot në] LT', nextDay : '[Neser në] LT', nextWeek : 'dddd [në] LT', lastDay : '[Dje në] LT', lastWeek : 'dddd [e kaluar në] LT', sameElse : 'L' }, relativeTime : { future : "në %s", past : "%s me parë", s : "disa sekonda", m : "një minut", mm : "%d minuta", h : "një orë", hh : "%d orë", d : "një ditë", dd : "%d ditë", M : "një muaj", MM : "%d muaj", y : "një vit", yy : "%d vite" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : swedish (sv) // author : Jens Alm : https://github.com/ulmus (function (factory) { factory(moment); }(function (moment) { return moment.lang('sv', { months : "januari_februari_mars_april_maj_juni_juli_augusti_september_oktober_november_december".split("_"), monthsShort : "jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec".split("_"), weekdays : "söndag_måndag_tisdag_onsdag_torsdag_fredag_lördag".split("_"), weekdaysShort : "sön_mån_tis_ons_tor_fre_lör".split("_"), weekdaysMin : "sö_må_ti_on_to_fr_lö".split("_"), longDateFormat : { LT : "HH:mm", L : "YYYY-MM-DD", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: '[Idag] LT', nextDay: '[Imorgon] LT', lastDay: '[Igår] LT', nextWeek: 'dddd LT', lastWeek: '[Förra] dddd[en] LT', sameElse: 'L' }, relativeTime : { future : "om %s", past : "för %s sedan", s : "några sekunder", m : "en minut", mm : "%d minuter", h : "en timme", hh : "%d timmar", d : "en dag", dd : "%d dagar", M : "en månad", MM : "%d månader", y : "ett år", yy : "%d år" }, ordinal : function (number) { var b = number % 10, output = (~~ (number % 100 / 10) === 1) ? 'e' : (b === 1) ? 'a' : (b === 2) ? 'a' : (b === 3) ? 'e' : 'e'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : tamil (ta) // author : Arjunkumar Krishnamoorthy : https://github.com/tk120404 (function (factory) { factory(moment); }(function (moment) { /*var symbolMap = { '1': '௧', '2': '௨', '3': '௩', '4': '௪', '5': '௫', '6': '௬', '7': '௭', '8': '௮', '9': '௯', '0': '௦' }, numberMap = { '௧': '1', '௨': '2', '௩': '3', '௪': '4', '௫': '5', '௬': '6', '௭': '7', '௮': '8', '௯': '9', '௦': '0' }; */ return moment.lang('ta', { months : 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split("_"), monthsShort : 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split("_"), weekdays : 'ஞாயிற்றுக்கிழமை_திங்கட்கிழமை_செவ்வாய்கிழமை_புதன்கிழமை_வியாழக்கிழமை_வெள்ளிக்கிழமை_சனிக்கிழமை'.split("_"), weekdaysShort : 'ஞாயிறு_திங்கள்_செவ்வாய்_புதன்_வியாழன்_வெள்ளி_சனி'.split("_"), weekdaysMin : 'ஞா_தி_செ_பு_வி_வெ_ச'.split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY, LT", LLLL : "dddd, D MMMM YYYY, LT" }, calendar : { sameDay : '[இன்று] LT', nextDay : '[நாளை] LT', nextWeek : 'dddd, LT', lastDay : '[நேற்று] LT', lastWeek : '[கடந்த வாரம்] dddd, LT', sameElse : 'L' }, relativeTime : { future : "%s இல்", past : "%s முன்", s : "ஒரு சில விநாடிகள்", m : "ஒரு நிமிடம்", mm : "%d நிமிடங்கள்", h : "ஒரு மணி நேரம்", hh : "%d மணி நேரம்", d : "ஒரு நாள்", dd : "%d நாட்கள்", M : "ஒரு மாதம்", MM : "%d மாதங்கள்", y : "ஒரு வருடம்", yy : "%d ஆண்டுகள்" }, /* preparse: function (string) { return string.replace(/[௧௨௩௪௫௬௭௮௯௦]/g, function (match) { return numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }); },*/ ordinal : function (number) { return number + 'வது'; }, // refer http://ta.wikipedia.org/s/1er1 meridiem : function (hour, minute, isLower) { if (hour >= 6 && hour <= 10) { return " காலை"; } else if (hour >= 10 && hour <= 14) { return " நண்பகல்"; } else if (hour >= 14 && hour <= 18) { return " எற்பாடு"; } else if (hour >= 18 && hour <= 20) { return " மாலை"; } else if (hour >= 20 && hour <= 24) { return " இரவு"; } else if (hour >= 0 && hour <= 6) { return " வைகறை"; } }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : thai (th) // author : Kridsada Thanabulpong : https://github.com/sirn (function (factory) { factory(moment); }(function (moment) { return moment.lang('th', { months : "มกราคม_กุมภาพันธ์_มีนาคม_เมษายน_พฤษภาคม_มิถุนายน_กรกฎาคม_สิงหาคม_กันยายน_ตุลาคม_พฤศจิกายน_ธันวาคม".split("_"), monthsShort : "มกรา_กุมภา_มีนา_เมษา_พฤษภา_มิถุนา_กรกฎา_สิงหา_กันยา_ตุลา_พฤศจิกา_ธันวา".split("_"), weekdays : "อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัสบดี_ศุกร์_เสาร์".split("_"), weekdaysShort : "อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัส_ศุกร์_เสาร์".split("_"), // yes, three characters difference weekdaysMin : "อา._จ._อ._พ._พฤ._ศ._ส.".split("_"), longDateFormat : { LT : "H นาฬิกา m นาที", L : "YYYY/MM/DD", LL : "D MMMM YYYY", LLL : "D MMMM YYYY เวลา LT", LLLL : "วันddddที่ D MMMM YYYY เวลา LT" }, meridiem : function (hour, minute, isLower) { if (hour < 12) { return "ก่อนเที่ยง"; } else { return "หลังเที่ยง"; } }, calendar : { sameDay : '[วันนี้ เวลา] LT', nextDay : '[พรุ่งนี้ เวลา] LT', nextWeek : 'dddd[หน้า เวลา] LT', lastDay : '[เมื่อวานนี้ เวลา] LT', lastWeek : '[วัน]dddd[ที่แล้ว เวลา] LT', sameElse : 'L' }, relativeTime : { future : "อีก %s", past : "%sที่แล้ว", s : "ไม่กี่วินาที", m : "1 นาที", mm : "%d นาที", h : "1 ชั่วโมง", hh : "%d ชั่วโมง", d : "1 วัน", dd : "%d วัน", M : "1 เดือน", MM : "%d เดือน", y : "1 ปี", yy : "%d ปี" } }); })); // moment.js language configuration // language : Tagalog/Filipino (tl-ph) // author : Dan Hagman (function (factory) { factory(moment); }(function (moment) { return moment.lang('tl-ph', { months : "Enero_Pebrero_Marso_Abril_Mayo_Hunyo_Hulyo_Agosto_Setyembre_Oktubre_Nobyembre_Disyembre".split("_"), monthsShort : "Ene_Peb_Mar_Abr_May_Hun_Hul_Ago_Set_Okt_Nob_Dis".split("_"), weekdays : "Linggo_Lunes_Martes_Miyerkules_Huwebes_Biyernes_Sabado".split("_"), weekdaysShort : "Lin_Lun_Mar_Miy_Huw_Biy_Sab".split("_"), weekdaysMin : "Li_Lu_Ma_Mi_Hu_Bi_Sab".split("_"), longDateFormat : { LT : "HH:mm", L : "MM/D/YYYY", LL : "MMMM D, YYYY", LLL : "MMMM D, YYYY LT", LLLL : "dddd, MMMM DD, YYYY LT" }, calendar : { sameDay: "[Ngayon sa] LT", nextDay: '[Bukas sa] LT', nextWeek: 'dddd [sa] LT', lastDay: '[Kahapon sa] LT', lastWeek: 'dddd [huling linggo] LT', sameElse: 'L' }, relativeTime : { future : "sa loob ng %s", past : "%s ang nakalipas", s : "ilang segundo", m : "isang minuto", mm : "%d minuto", h : "isang oras", hh : "%d oras", d : "isang araw", dd : "%d araw", M : "isang buwan", MM : "%d buwan", y : "isang taon", yy : "%d taon" }, ordinal : function (number) { return number; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : turkish (tr) // authors : Erhan Gundogan : https://github.com/erhangundogan, // Burak Yiğit Kaya: https://github.com/BYK (function (factory) { factory(moment); }(function (moment) { var suffixes = { 1: "'inci", 5: "'inci", 8: "'inci", 70: "'inci", 80: "'inci", 2: "'nci", 7: "'nci", 20: "'nci", 50: "'nci", 3: "'üncü", 4: "'üncü", 100: "'üncü", 6: "'ncı", 9: "'uncu", 10: "'uncu", 30: "'uncu", 60: "'ıncı", 90: "'ıncı" }; return moment.lang('tr', { months : "Ocak_Şubat_Mart_Nisan_Mayıs_Haziran_Temmuz_Ağustos_Eylül_Ekim_Kasım_Aralık".split("_"), monthsShort : "Oca_Şub_Mar_Nis_May_Haz_Tem_Ağu_Eyl_Eki_Kas_Ara".split("_"), weekdays : "Pazar_Pazartesi_Salı_Çarşamba_Perşembe_Cuma_Cumartesi".split("_"), weekdaysShort : "Paz_Pts_Sal_Çar_Per_Cum_Cts".split("_"), weekdaysMin : "Pz_Pt_Sa_Ça_Pe_Cu_Ct".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[bugün saat] LT', nextDay : '[yarın saat] LT', nextWeek : '[haftaya] dddd [saat] LT', lastDay : '[dün] LT', lastWeek : '[geçen hafta] dddd [saat] LT', sameElse : 'L' }, relativeTime : { future : "%s sonra", past : "%s önce", s : "birkaç saniye", m : "bir dakika", mm : "%d dakika", h : "bir saat", hh : "%d saat", d : "bir gün", dd : "%d gün", M : "bir ay", MM : "%d ay", y : "bir yıl", yy : "%d yıl" }, ordinal : function (number) { if (number === 0) { // special case for zero return number + "'ıncı"; } var a = number % 10, b = number % 100 - a, c = number >= 100 ? 100 : null; return number + (suffixes[a] || suffixes[b] || suffixes[c]); }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Morocco Central Atlas Tamaziɣt in Latin (tzm-la) // author : Abdel Said : https://github.com/abdelsaid (function (factory) { factory(moment); }(function (moment) { return moment.lang('tzm-la', { months : "innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir".split("_"), monthsShort : "innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir".split("_"), weekdays : "asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas".split("_"), weekdaysShort : "asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas".split("_"), weekdaysMin : "asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[asdkh g] LT", nextDay: '[aska g] LT', nextWeek: 'dddd [g] LT', lastDay: '[assant g] LT', lastWeek: 'dddd [g] LT', sameElse: 'L' }, relativeTime : { future : "dadkh s yan %s", past : "yan %s", s : "imik", m : "minuḍ", mm : "%d minuḍ", h : "saɛa", hh : "%d tassaɛin", d : "ass", dd : "%d ossan", M : "ayowr", MM : "%d iyyirn", y : "asgas", yy : "%d isgasn" }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Morocco Central Atlas Tamaziɣt (tzm) // author : Abdel Said : https://github.com/abdelsaid (function (factory) { factory(moment); }(function (moment) { return moment.lang('tzm', { months : "ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ".split("_"), monthsShort : "ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ".split("_"), weekdays : "ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ".split("_"), weekdaysShort : "ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ".split("_"), weekdaysMin : "ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[ⴰⵙⴷⵅ ⴴ] LT", nextDay: '[ⴰⵙⴽⴰ ⴴ] LT', nextWeek: 'dddd [ⴴ] LT', lastDay: '[ⴰⵚⴰⵏⵜ ⴴ] LT', lastWeek: 'dddd [ⴴ] LT', sameElse: 'L' }, relativeTime : { future : "ⴷⴰⴷⵅ ⵙ ⵢⴰⵏ %s", past : "ⵢⴰⵏ %s", s : "ⵉⵎⵉⴽ", m : "ⵎⵉⵏⵓⴺ", mm : "%d ⵎⵉⵏⵓⴺ", h : "ⵙⴰⵄⴰ", hh : "%d ⵜⴰⵙⵙⴰⵄⵉⵏ", d : "ⴰⵙⵙ", dd : "%d oⵙⵙⴰⵏ", M : "ⴰⵢoⵓⵔ", MM : "%d ⵉⵢⵢⵉⵔⵏ", y : "ⴰⵙⴳⴰⵙ", yy : "%d ⵉⵙⴳⴰⵙⵏ" }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : ukrainian (uk) // author : zemlanin : https://github.com/zemlanin // Author : Menelion Elensúle : https://github.com/Oire (function (factory) { factory(moment); }(function (moment) { function plural(word, num) { var forms = word.split('_'); return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]); } function relativeTimeWithPlural(number, withoutSuffix, key) { var format = { 'mm': 'хвилина_хвилини_хвилин', 'hh': 'година_години_годин', 'dd': 'день_дні_днів', 'MM': 'місяць_місяці_місяців', 'yy': 'рік_роки_років' }; if (key === 'm') { return withoutSuffix ? 'хвилина' : 'хвилину'; } else if (key === 'h') { return withoutSuffix ? 'година' : 'годину'; } else { return number + ' ' + plural(format[key], +number); } } function monthsCaseReplace(m, format) { var months = { 'nominative': 'січень_лютий_березень_квітень_травень_червень_липень_серпень_вересень_жовтень_листопад_грудень'.split('_'), 'accusative': 'січня_лютого_березня_квітня_травня_червня_липня_серпня_вересня_жовтня_листопада_грудня'.split('_') }, nounCase = (/D[oD]? *MMMM?/).test(format) ? 'accusative' : 'nominative'; return months[nounCase][m.month()]; } function weekdaysCaseReplace(m, format) { var weekdays = { 'nominative': 'неділя_понеділок_вівторок_середа_четвер_п’ятниця_субота'.split('_'), 'accusative': 'неділю_понеділок_вівторок_середу_четвер_п’ятницю_суботу'.split('_'), 'genitive': 'неділі_понеділка_вівторка_середи_четверга_п’ятниці_суботи'.split('_') }, nounCase = (/(\[[ВвУу]\]) ?dddd/).test(format) ? 'accusative' : ((/\[?(?:минулої|наступної)? ?\] ?dddd/).test(format) ? 'genitive' : 'nominative'); return weekdays[nounCase][m.day()]; } function processHoursFunction(str) { return function () { return str + 'о' + (this.hours() === 11 ? 'б' : '') + '] LT'; }; } return moment.lang('uk', { months : monthsCaseReplace, monthsShort : "січ_лют_бер_квіт_трав_черв_лип_серп_вер_жовт_лист_груд".split("_"), weekdays : weekdaysCaseReplace, weekdaysShort : "нд_пн_вт_ср_чт_пт_сб".split("_"), weekdaysMin : "нд_пн_вт_ср_чт_пт_сб".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY р.", LLL : "D MMMM YYYY р., LT", LLLL : "dddd, D MMMM YYYY р., LT" }, calendar : { sameDay: processHoursFunction('[Сьогодні '), nextDay: processHoursFunction('[Завтра '), lastDay: processHoursFunction('[Вчора '), nextWeek: processHoursFunction('[У] dddd ['), lastWeek: function () { switch (this.day()) { case 0: case 3: case 5: case 6: return processHoursFunction('[Минулої] dddd [').call(this); case 1: case 2: case 4: return processHoursFunction('[Минулого] dddd [').call(this); } }, sameElse: 'L' }, relativeTime : { future : "за %s", past : "%s тому", s : "декілька секунд", m : relativeTimeWithPlural, mm : relativeTimeWithPlural, h : "годину", hh : relativeTimeWithPlural, d : "день", dd : relativeTimeWithPlural, M : "місяць", MM : relativeTimeWithPlural, y : "рік", yy : relativeTimeWithPlural }, // M. E.: those two are virtually unused but a user might want to implement them for his/her website for some reason meridiem : function (hour, minute, isLower) { if (hour < 4) { return "ночі"; } else if (hour < 12) { return "ранку"; } else if (hour < 17) { return "дня"; } else { return "вечора"; } }, ordinal: function (number, period) { switch (period) { case 'M': case 'd': case 'DDD': case 'w': case 'W': return number + '-й'; case 'D': return number + '-го'; default: return number; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : uzbek // author : Sardor Muminov : https://github.com/muminoff (function (factory) { factory(moment); }(function (moment) { return moment.lang('uz', { months : "январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь".split("_"), monthsShort : "янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек".split("_"), weekdays : "Якшанба_Душанба_Сешанба_Чоршанба_Пайшанба_Жума_Шанба".split("_"), weekdaysShort : "Якш_Душ_Сеш_Чор_Пай_Жум_Шан".split("_"), weekdaysMin : "Як_Ду_Се_Чо_Па_Жу_Ша".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "D MMMM YYYY, dddd LT" }, calendar : { sameDay : '[Бугун соат] LT [да]', nextDay : '[Эртага] LT [да]', nextWeek : 'dddd [куни соат] LT [да]', lastDay : '[Кеча соат] LT [да]', lastWeek : '[Утган] dddd [куни соат] LT [да]', sameElse : 'L' }, relativeTime : { future : "Якин %s ичида", past : "Бир неча %s олдин", s : "фурсат", m : "бир дакика", mm : "%d дакика", h : "бир соат", hh : "%d соат", d : "бир кун", dd : "%d кун", M : "бир ой", MM : "%d ой", y : "бир йил", yy : "%d йил" }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : vietnamese (vn) // author : Bang Nguyen : https://github.com/bangnk (function (factory) { factory(moment); }(function (moment) { return moment.lang('vn', { months : "tháng 1_tháng 2_tháng 3_tháng 4_tháng 5_tháng 6_tháng 7_tháng 8_tháng 9_tháng 10_tháng 11_tháng 12".split("_"), monthsShort : "Th01_Th02_Th03_Th04_Th05_Th06_Th07_Th08_Th09_Th10_Th11_Th12".split("_"), weekdays : "chủ nhật_thứ hai_thứ ba_thứ tư_thứ năm_thứ sáu_thứ bảy".split("_"), weekdaysShort : "CN_T2_T3_T4_T5_T6_T7".split("_"), weekdaysMin : "CN_T2_T3_T4_T5_T6_T7".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM [năm] YYYY", LLL : "D MMMM [năm] YYYY LT", LLLL : "dddd, D MMMM [năm] YYYY LT", l : "DD/M/YYYY", ll : "D MMM YYYY", lll : "D MMM YYYY LT", llll : "ddd, D MMM YYYY LT" }, calendar : { sameDay: "[Hôm nay lúc] LT", nextDay: '[Ngày mai lúc] LT', nextWeek: 'dddd [tuần tới lúc] LT', lastDay: '[Hôm qua lúc] LT', lastWeek: 'dddd [tuần rồi lúc] LT', sameElse: 'L' }, relativeTime : { future : "%s tới", past : "%s trước", s : "vài giây", m : "một phút", mm : "%d phút", h : "một giờ", hh : "%d giờ", d : "một ngày", dd : "%d ngày", M : "một tháng", MM : "%d tháng", y : "một năm", yy : "%d năm" }, ordinal : function (number) { return number; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : chinese // author : suupic : https://github.com/suupic // author : Zeno Zeng : https://github.com/zenozeng (function (factory) { factory(moment); }(function (moment) { return moment.lang('zh-cn', { months : "一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"), monthsShort : "1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"), weekdays : "星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"), weekdaysShort : "周日_周一_周二_周三_周四_周五_周六".split("_"), weekdaysMin : "日_一_二_三_四_五_六".split("_"), longDateFormat : { LT : "Ah点mm", L : "YYYY-MM-DD", LL : "YYYY年MMMD日", LLL : "YYYY年MMMD日LT", LLLL : "YYYY年MMMD日ddddLT", l : "YYYY-MM-DD", ll : "YYYY年MMMD日", lll : "YYYY年MMMD日LT", llll : "YYYY年MMMD日ddddLT" }, meridiem : function (hour, minute, isLower) { var hm = hour * 100 + minute; if (hm < 600) { return "凌晨"; } else if (hm < 900) { return "早上"; } else if (hm < 1130) { return "上午"; } else if (hm < 1230) { return "中午"; } else if (hm < 1800) { return "下午"; } else { return "晚上"; } }, calendar : { sameDay : function () { return this.minutes() === 0 ? "[今天]Ah[点整]" : "[今天]LT"; }, nextDay : function () { return this.minutes() === 0 ? "[明天]Ah[点整]" : "[明天]LT"; }, lastDay : function () { return this.minutes() === 0 ? "[昨天]Ah[点整]" : "[昨天]LT"; }, nextWeek : function () { var startOfWeek, prefix; startOfWeek = moment().startOf('week'); prefix = this.unix() - startOfWeek.unix() >= 7 * 24 * 3600 ? '[下]' : '[本]'; return this.minutes() === 0 ? prefix + "dddAh点整" : prefix + "dddAh点mm"; }, lastWeek : function () { var startOfWeek, prefix; startOfWeek = moment().startOf('week'); prefix = this.unix() < startOfWeek.unix() ? '[上]' : '[本]'; return this.minutes() === 0 ? prefix + "dddAh点整" : prefix + "dddAh点mm"; }, sameElse : 'LL' }, ordinal : function (number, period) { switch (period) { case "d": case "D": case "DDD": return number + "日"; case "M": return number + "月"; case "w": case "W": return number + "周"; default: return number; } }, relativeTime : { future : "%s内", past : "%s前", s : "几秒", m : "1分钟", mm : "%d分钟", h : "1小时", hh : "%d小时", d : "1天", dd : "%d天", M : "1个月", MM : "%d个月", y : "1年", yy : "%d年" }, week : { // GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效 dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : traditional chinese (zh-tw) // author : Ben : https://github.com/ben-lin (function (factory) { factory(moment); }(function (moment) { return moment.lang('zh-tw', { months : "一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"), monthsShort : "1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"), weekdays : "星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"), weekdaysShort : "週日_週一_週二_週三_週四_週五_週六".split("_"), weekdaysMin : "日_一_二_三_四_五_六".split("_"), longDateFormat : { LT : "Ah點mm", L : "YYYY年MMMD日", LL : "YYYY年MMMD日", LLL : "YYYY年MMMD日LT", LLLL : "YYYY年MMMD日ddddLT", l : "YYYY年MMMD日", ll : "YYYY年MMMD日", lll : "YYYY年MMMD日LT", llll : "YYYY年MMMD日ddddLT" }, meridiem : function (hour, minute, isLower) { var hm = hour * 100 + minute; if (hm < 900) { return "早上"; } else if (hm < 1130) { return "上午"; } else if (hm < 1230) { return "中午"; } else if (hm < 1800) { return "下午"; } else { return "晚上"; } }, calendar : { sameDay : '[今天]LT', nextDay : '[明天]LT', nextWeek : '[下]ddddLT', lastDay : '[昨天]LT', lastWeek : '[上]ddddLT', sameElse : 'L' }, ordinal : function (number, period) { switch (period) { case "d" : case "D" : case "DDD" : return number + "日"; case "M" : return number + "月"; case "w" : case "W" : return number + "週"; default : return number; } }, relativeTime : { future : "%s內", past : "%s前", s : "幾秒", m : "一分鐘", mm : "%d分鐘", h : "一小時", hh : "%d小時", d : "一天", dd : "%d天", M : "一個月", MM : "%d個月", y : "一年", yy : "%d年" } }); })); moment.lang('en'); /************************************ Exposing Moment ************************************/ function makeGlobal(deprecate) { var warned = false, local_moment = moment; /*global ender:false */ if (typeof ender !== 'undefined') { return; } // here, `this` means `window` in the browser, or `global` on the server // add `moment` as a global object via a string identifier, // for Closure Compiler "advanced" mode if (deprecate) { global.moment = function () { if (!warned && console && console.warn) { warned = true; console.warn( "Accessing Moment through the global scope is " + "deprecated, and will be removed in an upcoming " + "release."); } return local_moment.apply(null, arguments); }; extend(global.moment, local_moment); } else { global['moment'] = moment; } } // CommonJS module is defined if (hasModule) { module.exports = moment; makeGlobal(true); } else if (typeof define === "function" && define.amd) { define("moment", function (require, exports, module) { if (module.config && module.config() && module.config().noGlobal !== true) { // If user provided noGlobal, he is aware of global makeGlobal(module.config().noGlobal === undefined); } return moment; }); } else { makeGlobal(); } }).call(this);
JavaScript
/* Justified Gallery Version: 2.1 Author: Miro Mannino Author URI: http://miromannino.it Copyright 2012 Miro Mannino (miro.mannino@gmail.com) This file is part of Justified Gallery. This work is licensed under the Creative Commons Attribution 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by/3.0/ or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA. */ (function($){ $.fn.justifiedGallery = function(options){ //TODO fare impostazione 'rel' che sostituisce tutti i link con il rel specificato var settings = $.extend( { 'sizeRangeSuffixes' : {'lt100':'_t', 'lt240':'_m', 'lt320':'_n', 'lt500':'', 'lt640':'_z', 'lt1024':'_b'}, 'rowHeight' : 120, 'margins' : 1, 'justifyLastRow' : true, 'fixedHeight' : false, 'captions' : true, 'rel' : null, //rewrite the rel of each analyzed links 'target' : null, //rewrite the target of all links 'extension' : /\.[^.]+$/, 'refreshTime' : 500, 'onComplete' : null }, options); function getErrorHtml(message, classOfError){ return "<div class=\"jg-error " + classOfError + "\"style=\"\">" + message + "</div>"; } return this.each(function(index, cont){ $(cont).addClass("justifiedGallery"); var loaded = 0; var images = new Array($(cont).find("img").length); if(images.length == 0) return; $(cont).append("<div class=\"jg-loading\"><div class=\"jg-loading-img\"></div></div>"); $(cont).find("a").each(function(index, entry){ var imgEntry = $(entry).find("img"); images[index] = new Array(5); images[index]["src"] = (typeof $(imgEntry).data("safe-src") != 'undefined') ? $(imgEntry).data("safe-src") : $(imgEntry).attr("src"); images[index]["alt"] = $(imgEntry).attr("alt"); images[index]["href"] = $(entry).attr("href"); images[index]["title"] = $(entry).attr("title"); images[index]["rel"] = (settings.rel != null) ? settings.rel : $(entry).attr("rel"); images[index]["target"] = (settings.target != null) ? settings.target : $(entry).attr("target"); images[index]["extension"] = images[index]["src"].match(settings.extension)[0]; $(entry).remove(); //remove the image, we have its data var img = new Image(); $(img).load(function() { if(images[index]["height"] != settings.rowHeight) images[index]["width"] = Math.ceil(this.width / (this.height / settings.rowHeight)); else images[index]["width"] = this.width; images[index]["height"] = settings.rowHeight; var usedSizeRangeRegExp = new RegExp("(" + settings.sizeRangeSuffixes.lt100 + "|" + settings.sizeRangeSuffixes.lt240 + "|" + settings.sizeRangeSuffixes.lt320 + "|" + settings.sizeRangeSuffixes.lt500 + "|" + settings.sizeRangeSuffixes.lt640 + "|" + settings.sizeRangeSuffixes.lt1024 + ")$"); images[index]["src"] = images[index]["src"].replace(settings.extension, "").replace(usedSizeRangeRegExp, ""); if(++loaded == images.length) startProcess(cont, images, settings); }); $(img).error(function() { $(cont).prepend(getErrorHtml("The image can't be loaded: \"" + images[index]["src"] +"\"", "jg-usedPrefixImageNotFound")); images[index] = null; if(++loaded == images.length) startProcess(cont, images, settings); }); $(img).attr('src', images[index]["src"]); }); }); function startProcess(cont, images, settings){ //FadeOut the loading image and FadeIn the images after their loading $(cont).find(".jg-loading").fadeOut(500, function(){ $(this).remove(); //remove the loading image processesImages($, cont, images, 0, settings); if($.isFunction(settings.onComplete)) settings.onComplete.call(this, cont); }); } function buildImage(image, suffix, nw, nh, l, minRowHeight, settings){ var ris; ris = "<div class=\"jg-image\" style=\"left:" + l + "px\">"; ris += " <a href=\"" + image["href"] + "\" "; if (typeof image["rel"] != 'undefined') ris += "rel=\"" + image["rel"] + "\""; if (typeof image["target"] != 'undefined') ris += "target=\"" + image["target"] + "\""; ris += "title=\"" + image["title"] + "\">"; ris += " <img alt=\"" + image["alt"] + "\" src=\"" + image["src"] + suffix + image.extension + "\""; ris += "style=\"width: " + nw + "px; height: " + nh + "px;\">"; if(settings.captions) ris += " <div style=\"bottom:" + (nh - minRowHeight) + "px;\" class=\"jg-image-label\">" + image["alt"] + "</div>"; ris += " </a></div>"; return ris; } function buildContRow(row, images, extraW, settings){ var j, l = 0; var minRowHeight; for(var j = 0; j < row.length; j++){ row[j]["nh"] = Math.ceil(images[row[j]["indx"]]["height"] * ((images[row[j]["indx"]]["width"] + extraW) / images[row[j]["indx"]]["width"])); row[j]["nw"] = images[row[j]["indx"]]["width"] + extraW; row[j]["suffix"] = getSuffix(row[j]["nw"], row[j]["nh"], settings); row[j]["l"] = l; if(!settings.fixedHeight){ if(j == 0) minRowHeight = row[j]["nh"]; else if(minRowHeight > row[j]["nh"]) minRowHeight = row[j]["nh"]; } l += row[j]["nw"] + settings.margins; } if(settings.fixedHeight) minRowHeight = settings.rowHeight; var rowCont = ""; for(var j = 0; j < row.length; j++){ rowCont += buildImage(images[row[j]["indx"]], row[j]["suffix"], row[j]["nw"], row[j]["nh"], row[j]["l"], minRowHeight, settings); } return "<div class=\"jg-row\" style=\"height: " + minRowHeight + "px; margin-bottom:" + settings.margins + "px;\">" + rowCont + "</div>"; } function getSuffix(nw, nh, settings){ var n; if(nw > nh) n = nw; else n = nh; if(n <= 100){ return settings.sizeRangeSuffixes.lt100; //thumbnail (longest side:100) }else if(n <= 240){ return settings.sizeRangeSuffixes.lt240; //small (longest side:240) }else if(n <= 320){ return settings.sizeRangeSuffixes.lt320; //small (longest side:320) }else if(n <= 500){ return settings.sizeRangeSuffixes.lt500; //small (longest side:320) }else if(n <= 640){ return settings.sizeRangeSuffixes.lt640; //medium (longest side:640) }else{ return settings.sizeRangeSuffixes.lt1024; //large (longest side:1024) } } function processesImages($, cont, images, lastRowWidth, settings){ var row = new Array(); var row_i, i; var partialRowWidth = 0; var extraW; var rowWidth = $(cont).width(); for(i = 0, row_i = 0; i < images.length; i++){ if(images[i] == null) continue; if(partialRowWidth + images[i]["width"] + settings.margins <= rowWidth){ //we can add the image partialRowWidth += images[i]["width"] + settings.margins; row[row_i] = new Array(5); row[row_i]["indx"] = i; row_i++; }else{ //the row is full extraW = Math.ceil((rowWidth - partialRowWidth + 1) / row.length); $(cont).append(buildContRow(row, images, extraW, settings)); row = new Array(); row[0] = new Array(5); row[0]["indx"] = i; row_i = 1; partialRowWidth = images[i]["width"] + settings.margins; } } //last row---------------------- //now we have all the images index loaded in the row arra if(settings.justifyLastRow){ extraW = Math.ceil((rowWidth - partialRowWidth + 1) / row.length); }else{ extraW = 0; } $(cont).append(buildContRow(row, images, extraW, settings)); //--------------------------- //Captions--------------------- if(settings.captions){ $(cont).find(".jg-image").mouseenter(function(sender){ $(sender.currentTarget).find(".jg-image-label").stop(); $(sender.currentTarget).find(".jg-image-label").fadeTo(500, 0.7); }); $(cont).find(".jg-image").mouseleave(function(sender){ $(sender.currentTarget).find(".jg-image-label").stop(); $(sender.currentTarget).find(".jg-image-label").fadeTo(500, 0); }); } $(cont).find(".jg-resizedImageNotFound").remove(); //fade in the images that we have changed and need to be reloaded $(cont).find(".jg-image img").load(function(){ $(this).fadeTo(500, 1); }).error(function(){ $(cont).prepend(getErrorHtml("The image can't be loaded: \"" + $(this).attr("src") +"\"", "jg-resizedImageNotFound")); }).each(function(){ if(this.complete) $(this).load(); }); checkWidth($, cont, images, rowWidth, settings); } function checkWidth($, cont, images, lastRowWidth, settings){ var id = setInterval(function(){ if(lastRowWidth != $(cont).width()){ $(cont).find(".jg-row").remove(); clearInterval(id); processesImages($, cont, images, lastRowWidth, settings); return; } }, settings.refreshTime); } } })(jQuery);
JavaScript
/** * * jquery.sparkline.js * * v2.1.2 * (c) Splunk, Inc * Contact: Gareth Watts (gareth@splunk.com) * http://omnipotent.net/jquery.sparkline/ * * Generates inline sparkline charts from data supplied either to the method * or inline in HTML * * Compatible with Internet Explorer 6.0+ and modern browsers equipped with the canvas tag * (Firefox 2.0+, Safari, Opera, etc) * * License: New BSD License * * Copyright (c) 2012, Splunk Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Splunk Inc nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * Usage: * $(selector).sparkline(values, options) * * If values is undefined or set to 'html' then the data values are read from the specified tag: * <p>Sparkline: <span class="sparkline">1,4,6,6,8,5,3,5</span></p> * $('.sparkline').sparkline(); * There must be no spaces in the enclosed data set * * Otherwise values must be an array of numbers or null values * <p>Sparkline: <span id="sparkline1">This text replaced if the browser is compatible</span></p> * $('#sparkline1').sparkline([1,4,6,6,8,5,3,5]) * $('#sparkline2').sparkline([1,4,6,null,null,5,3,5]) * * Values can also be specified in an HTML comment, or as a values attribute: * <p>Sparkline: <span class="sparkline"><!--1,4,6,6,8,5,3,5 --></span></p> * <p>Sparkline: <span class="sparkline" values="1,4,6,6,8,5,3,5"></span></p> * $('.sparkline').sparkline(); * * For line charts, x values can also be specified: * <p>Sparkline: <span class="sparkline">1:1,2.7:4,3.4:6,5:6,6:8,8.7:5,9:3,10:5</span></p> * $('#sparkline1').sparkline([ [1,1], [2.7,4], [3.4,6], [5,6], [6,8], [8.7,5], [9,3], [10,5] ]) * * By default, options should be passed in as teh second argument to the sparkline function: * $('.sparkline').sparkline([1,2,3,4], {type: 'bar'}) * * Options can also be set by passing them on the tag itself. This feature is disabled by default though * as there's a slight performance overhead: * $('.sparkline').sparkline([1,2,3,4], {enableTagOptions: true}) * <p>Sparkline: <span class="sparkline" sparkType="bar" sparkBarColor="red">loading</span></p> * Prefix all options supplied as tag attribute with "spark" (configurable by setting tagOptionPrefix) * * Supported options: * lineColor - Color of the line used for the chart * fillColor - Color used to fill in the chart - Set to '' or false for a transparent chart * width - Width of the chart - Defaults to 3 times the number of values in pixels * height - Height of the chart - Defaults to the height of the containing element * chartRangeMin - Specify the minimum value to use for the Y range of the chart - Defaults to the minimum value supplied * chartRangeMax - Specify the maximum value to use for the Y range of the chart - Defaults to the maximum value supplied * chartRangeClip - Clip out of range values to the max/min specified by chartRangeMin and chartRangeMax * chartRangeMinX - Specify the minimum value to use for the X range of the chart - Defaults to the minimum value supplied * chartRangeMaxX - Specify the maximum value to use for the X range of the chart - Defaults to the maximum value supplied * composite - If true then don't erase any existing chart attached to the tag, but draw * another chart over the top - Note that width and height are ignored if an * existing chart is detected. * tagValuesAttribute - Name of tag attribute to check for data values - Defaults to 'values' * enableTagOptions - Whether to check tags for sparkline options * tagOptionPrefix - Prefix used for options supplied as tag attributes - Defaults to 'spark' * disableHiddenCheck - If set to true, then the plugin will assume that charts will never be drawn into a * hidden dom element, avoding a browser reflow * disableInteraction - If set to true then all mouseover/click interaction behaviour will be disabled, * making the plugin perform much like it did in 1.x * disableTooltips - If set to true then tooltips will be disabled - Defaults to false (tooltips enabled) * disableHighlight - If set to true then highlighting of selected chart elements on mouseover will be disabled * defaults to false (highlights enabled) * highlightLighten - Factor to lighten/darken highlighted chart values by - Defaults to 1.4 for a 40% increase * tooltipContainer - Specify which DOM element the tooltip should be rendered into - defaults to document.body * tooltipClassname - Optional CSS classname to apply to tooltips - If not specified then a default style will be applied * tooltipOffsetX - How many pixels away from the mouse pointer to render the tooltip on the X axis * tooltipOffsetY - How many pixels away from the mouse pointer to render the tooltip on the r axis * tooltipFormatter - Optional callback that allows you to override the HTML displayed in the tooltip * callback is given arguments of (sparkline, options, fields) * tooltipChartTitle - If specified then the tooltip uses the string specified by this setting as a title * tooltipFormat - A format string or SPFormat object (or an array thereof for multiple entries) * to control the format of the tooltip * tooltipPrefix - A string to prepend to each field displayed in a tooltip * tooltipSuffix - A string to append to each field displayed in a tooltip * tooltipSkipNull - If true then null values will not have a tooltip displayed (defaults to true) * tooltipValueLookups - An object or range map to map field values to tooltip strings * (eg. to map -1 to "Lost", 0 to "Draw", and 1 to "Win") * numberFormatter - Optional callback for formatting numbers in tooltips * numberDigitGroupSep - Character to use for group separator in numbers "1,234" - Defaults to "," * numberDecimalMark - Character to use for the decimal point when formatting numbers - Defaults to "." * numberDigitGroupCount - Number of digits between group separator - Defaults to 3 * * There are 7 types of sparkline, selected by supplying a "type" option of 'line' (default), * 'bar', 'tristate', 'bullet', 'discrete', 'pie' or 'box' * line - Line chart. Options: * spotColor - Set to '' to not end each line in a circular spot * minSpotColor - If set, color of spot at minimum value * maxSpotColor - If set, color of spot at maximum value * spotRadius - Radius in pixels * lineWidth - Width of line in pixels * normalRangeMin * normalRangeMax - If set draws a filled horizontal bar between these two values marking the "normal" * or expected range of values * normalRangeColor - Color to use for the above bar * drawNormalOnTop - Draw the normal range above the chart fill color if true * defaultPixelsPerValue - Defaults to 3 pixels of width for each value in the chart * highlightSpotColor - The color to use for drawing a highlight spot on mouseover - Set to null to disable * highlightLineColor - The color to use for drawing a highlight line on mouseover - Set to null to disable * valueSpots - Specify which points to draw spots on, and in which color. Accepts a range map * * bar - Bar chart. Options: * barColor - Color of bars for postive values * negBarColor - Color of bars for negative values * zeroColor - Color of bars with zero values * nullColor - Color of bars with null values - Defaults to omitting the bar entirely * barWidth - Width of bars in pixels * colorMap - Optional mappnig of values to colors to override the *BarColor values above * can be an Array of values to control the color of individual bars or a range map * to specify colors for individual ranges of values * barSpacing - Gap between bars in pixels * zeroAxis - Centers the y-axis around zero if true * * tristate - Charts values of win (>0), lose (<0) or draw (=0) * posBarColor - Color of win values * negBarColor - Color of lose values * zeroBarColor - Color of draw values * barWidth - Width of bars in pixels * barSpacing - Gap between bars in pixels * colorMap - Optional mappnig of values to colors to override the *BarColor values above * can be an Array of values to control the color of individual bars or a range map * to specify colors for individual ranges of values * * discrete - Options: * lineHeight - Height of each line in pixels - Defaults to 30% of the graph height * thesholdValue - Values less than this value will be drawn using thresholdColor instead of lineColor * thresholdColor * * bullet - Values for bullet graphs msut be in the order: target, performance, range1, range2, range3, ... * options: * targetColor - The color of the vertical target marker * targetWidth - The width of the target marker in pixels * performanceColor - The color of the performance measure horizontal bar * rangeColors - Colors to use for each qualitative range background color * * pie - Pie chart. Options: * sliceColors - An array of colors to use for pie slices * offset - Angle in degrees to offset the first slice - Try -90 or +90 * borderWidth - Width of border to draw around the pie chart, in pixels - Defaults to 0 (no border) * borderColor - Color to use for the pie chart border - Defaults to #000 * * box - Box plot. Options: * raw - Set to true to supply pre-computed plot points as values * values should be: low_outlier, low_whisker, q1, median, q3, high_whisker, high_outlier * When set to false you can supply any number of values and the box plot will * be computed for you. Default is false. * showOutliers - Set to true (default) to display outliers as circles * outlierIQR - Interquartile range used to determine outliers. Default 1.5 * boxLineColor - Outline color of the box * boxFillColor - Fill color for the box * whiskerColor - Line color used for whiskers * outlierLineColor - Outline color of outlier circles * outlierFillColor - Fill color of the outlier circles * spotRadius - Radius of outlier circles * medianColor - Line color of the median line * target - Draw a target cross hair at the supplied value (default undefined) * * * * Examples: * $('#sparkline1').sparkline(myvalues, { lineColor: '#f00', fillColor: false }); * $('.barsparks').sparkline('html', { type:'bar', height:'40px', barWidth:5 }); * $('#tristate').sparkline([1,1,-1,1,0,0,-1], { type:'tristate' }): * $('#discrete').sparkline([1,3,4,5,5,3,4,5], { type:'discrete' }); * $('#bullet').sparkline([10,12,12,9,7], { type:'bullet' }); * $('#pie').sparkline([1,1,2], { type:'pie' }); */ /*jslint regexp: true, browser: true, jquery: true, white: true, nomen: false, plusplus: false, maxerr: 500, indent: 4 */ (function(document, Math, undefined) { // performance/minified-size optimization (function(factory) { if(typeof define === 'function' && define.amd) { define(['jquery'], factory); } else if (jQuery && !jQuery.fn.sparkline) { factory(jQuery); } } (function($) { 'use strict'; var UNSET_OPTION = {}, getDefaults, createClass, SPFormat, clipval, quartile, normalizeValue, normalizeValues, remove, isNumber, all, sum, addCSS, ensureArray, formatNumber, RangeMap, MouseHandler, Tooltip, barHighlightMixin, line, bar, tristate, discrete, bullet, pie, box, defaultStyles, initStyles, VShape, VCanvas_base, VCanvas_canvas, VCanvas_vml, pending, shapeCount = 0; /** * Default configuration settings */ getDefaults = function () { return { // Settings common to most/all chart types common: { type: 'line', lineColor: '#00f', fillColor: '#cdf', defaultPixelsPerValue: 3, width: 'auto', height: 'auto', composite: false, tagValuesAttribute: 'values', tagOptionsPrefix: 'spark', enableTagOptions: false, enableHighlight: true, highlightLighten: 1.4, tooltipSkipNull: true, tooltipPrefix: '', tooltipSuffix: '', disableHiddenCheck: false, numberFormatter: false, numberDigitGroupCount: 3, numberDigitGroupSep: ',', numberDecimalMark: '.', disableTooltips: false, disableInteraction: false }, // Defaults for line charts line: { spotColor: '#f80', highlightSpotColor: '#5f5', highlightLineColor: '#f22', spotRadius: 1.5, minSpotColor: '#f80', maxSpotColor: '#f80', lineWidth: 1, normalRangeMin: undefined, normalRangeMax: undefined, normalRangeColor: '#ccc', drawNormalOnTop: false, chartRangeMin: undefined, chartRangeMax: undefined, chartRangeMinX: undefined, chartRangeMaxX: undefined, tooltipFormat: new SPFormat('<span style="color: {{color}}">&#9679;</span> {{prefix}}{{y}}{{suffix}}') }, // Defaults for bar charts bar: { barColor: '#3366cc', negBarColor: '#f44', stackedBarColor: ['#3366cc', '#dc3912', '#ff9900', '#109618', '#66aa00', '#dd4477', '#0099c6', '#990099'], zeroColor: undefined, nullColor: undefined, zeroAxis: true, barWidth: 4, barSpacing: 1, chartRangeMax: undefined, chartRangeMin: undefined, chartRangeClip: false, colorMap: undefined, tooltipFormat: new SPFormat('<span style="color: {{color}}">&#9679;</span> {{prefix}}{{value}}{{suffix}}') }, // Defaults for tristate charts tristate: { barWidth: 4, barSpacing: 1, posBarColor: '#6f6', negBarColor: '#f44', zeroBarColor: '#999', colorMap: {}, tooltipFormat: new SPFormat('<span style="color: {{color}}">&#9679;</span> {{value:map}}'), tooltipValueLookups: { map: { '-1': 'Loss', '0': 'Draw', '1': 'Win' } } }, // Defaults for discrete charts discrete: { lineHeight: 'auto', thresholdColor: undefined, thresholdValue: 0, chartRangeMax: undefined, chartRangeMin: undefined, chartRangeClip: false, tooltipFormat: new SPFormat('{{prefix}}{{value}}{{suffix}}') }, // Defaults for bullet charts bullet: { targetColor: '#f33', targetWidth: 3, // width of the target bar in pixels performanceColor: '#33f', rangeColors: ['#d3dafe', '#a8b6ff', '#7f94ff'], base: undefined, // set this to a number to change the base start number tooltipFormat: new SPFormat('{{fieldkey:fields}} - {{value}}'), tooltipValueLookups: { fields: {r: 'Range', p: 'Performance', t: 'Target'} } }, // Defaults for pie charts pie: { offset: 0, sliceColors: ['#3366cc', '#dc3912', '#ff9900', '#109618', '#66aa00', '#dd4477', '#0099c6', '#990099'], borderWidth: 0, borderColor: '#000', tooltipFormat: new SPFormat('<span style="color: {{color}}">&#9679;</span> {{value}} ({{percent.1}}%)') }, // Defaults for box plots box: { raw: false, boxLineColor: '#000', boxFillColor: '#cdf', whiskerColor: '#000', outlierLineColor: '#333', outlierFillColor: '#fff', medianColor: '#f00', showOutliers: true, outlierIQR: 1.5, spotRadius: 1.5, target: undefined, targetColor: '#4a2', chartRangeMax: undefined, chartRangeMin: undefined, tooltipFormat: new SPFormat('{{field:fields}}: {{value}}'), tooltipFormatFieldlistKey: 'field', tooltipValueLookups: { fields: { lq: 'Lower Quartile', med: 'Median', uq: 'Upper Quartile', lo: 'Left Outlier', ro: 'Right Outlier', lw: 'Left Whisker', rw: 'Right Whisker'} } } }; }; // You can have tooltips use a css class other than jqstooltip by specifying tooltipClassname defaultStyles = '.jqstooltip { ' + 'position: absolute;' + 'left: 0px;' + 'top: 0px;' + 'visibility: hidden;' + 'background: rgb(0, 0, 0) transparent;' + 'background-color: rgba(0,0,0,0.6);' + 'filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);' + '-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";' + 'color: white;' + 'font: 10px arial, san serif;' + 'text-align: left;' + 'white-space: nowrap;' + 'padding: 5px;' + 'border: 1px solid white;' + 'z-index: 10000;' + '}' + '.jqsfield { ' + 'color: white;' + 'font: 10px arial, san serif;' + 'text-align: left;' + '}'; /** * Utilities */ createClass = function (/* [baseclass, [mixin, ...]], definition */) { var Class, args; Class = function () { this.init.apply(this, arguments); }; if (arguments.length > 1) { if (arguments[0]) { Class.prototype = $.extend(new arguments[0](), arguments[arguments.length - 1]); Class._super = arguments[0].prototype; } else { Class.prototype = arguments[arguments.length - 1]; } if (arguments.length > 2) { args = Array.prototype.slice.call(arguments, 1, -1); args.unshift(Class.prototype); $.extend.apply($, args); } } else { Class.prototype = arguments[0]; } Class.prototype.cls = Class; return Class; }; /** * Wraps a format string for tooltips * {{x}} * {{x.2} * {{x:months}} */ $.SPFormatClass = SPFormat = createClass({ fre: /\{\{([\w.]+?)(:(.+?))?\}\}/g, precre: /(\w+)\.(\d+)/, init: function (format, fclass) { this.format = format; this.fclass = fclass; }, render: function (fieldset, lookups, options) { var self = this, fields = fieldset, match, token, lookupkey, fieldvalue, prec; return this.format.replace(this.fre, function () { var lookup; token = arguments[1]; lookupkey = arguments[3]; match = self.precre.exec(token); if (match) { prec = match[2]; token = match[1]; } else { prec = false; } fieldvalue = fields[token]; if (fieldvalue === undefined) { return ''; } if (lookupkey && lookups && lookups[lookupkey]) { lookup = lookups[lookupkey]; if (lookup.get) { // RangeMap return lookups[lookupkey].get(fieldvalue) || fieldvalue; } else { return lookups[lookupkey][fieldvalue] || fieldvalue; } } if (isNumber(fieldvalue)) { if (options.get('numberFormatter')) { fieldvalue = options.get('numberFormatter')(fieldvalue); } else { fieldvalue = formatNumber(fieldvalue, prec, options.get('numberDigitGroupCount'), options.get('numberDigitGroupSep'), options.get('numberDecimalMark')); } } return fieldvalue; }); } }); // convience method to avoid needing the new operator $.spformat = function(format, fclass) { return new SPFormat(format, fclass); }; clipval = function (val, min, max) { if (val < min) { return min; } if (val > max) { return max; } return val; }; quartile = function (values, q) { var vl; if (q === 2) { vl = Math.floor(values.length / 2); return values.length % 2 ? values[vl] : (values[vl-1] + values[vl]) / 2; } else { if (values.length % 2 ) { // odd vl = (values.length * q + q) / 4; return vl % 1 ? (values[Math.floor(vl)] + values[Math.floor(vl) - 1]) / 2 : values[vl-1]; } else { //even vl = (values.length * q + 2) / 4; return vl % 1 ? (values[Math.floor(vl)] + values[Math.floor(vl) - 1]) / 2 : values[vl-1]; } } }; normalizeValue = function (val) { var nf; switch (val) { case 'undefined': val = undefined; break; case 'null': val = null; break; case 'true': val = true; break; case 'false': val = false; break; default: nf = parseFloat(val); if (val == nf) { val = nf; } } return val; }; normalizeValues = function (vals) { var i, result = []; for (i = vals.length; i--;) { result[i] = normalizeValue(vals[i]); } return result; }; remove = function (vals, filter) { var i, vl, result = []; for (i = 0, vl = vals.length; i < vl; i++) { if (vals[i] !== filter) { result.push(vals[i]); } } return result; }; isNumber = function (num) { return !isNaN(parseFloat(num)) && isFinite(num); }; formatNumber = function (num, prec, groupsize, groupsep, decsep) { var p, i; num = (prec === false ? parseFloat(num).toString() : num.toFixed(prec)).split(''); p = (p = $.inArray('.', num)) < 0 ? num.length : p; if (p < num.length) { num[p] = decsep; } for (i = p - groupsize; i > 0; i -= groupsize) { num.splice(i, 0, groupsep); } return num.join(''); }; // determine if all values of an array match a value // returns true if the array is empty all = function (val, arr, ignoreNull) { var i; for (i = arr.length; i--; ) { if (ignoreNull && arr[i] === null) continue; if (arr[i] !== val) { return false; } } return true; }; // sums the numeric values in an array, ignoring other values sum = function (vals) { var total = 0, i; for (i = vals.length; i--;) { total += typeof vals[i] === 'number' ? vals[i] : 0; } return total; }; ensureArray = function (val) { return $.isArray(val) ? val : [val]; }; // http://paulirish.com/2008/bookmarklet-inject-new-css-rules/ addCSS = function(css) { var tag; //if ('\v' == 'v') /* ie only */ { if (document.createStyleSheet) { document.createStyleSheet().cssText = css; } else { tag = document.createElement('style'); tag.type = 'text/css'; document.getElementsByTagName('head')[0].appendChild(tag); tag[(typeof document.body.style.WebkitAppearance == 'string') /* webkit only */ ? 'innerText' : 'innerHTML'] = css; } }; // Provide a cross-browser interface to a few simple drawing primitives $.fn.simpledraw = function (width, height, useExisting, interact) { var target, mhandler; if (useExisting && (target = this.data('_jqs_vcanvas'))) { return target; } if ($.fn.sparkline.canvas === false) { // We've already determined that neither Canvas nor VML are available return false; } else if ($.fn.sparkline.canvas === undefined) { // No function defined yet -- need to see if we support Canvas or VML var el = document.createElement('canvas'); if (!!(el.getContext && el.getContext('2d'))) { // Canvas is available $.fn.sparkline.canvas = function(width, height, target, interact) { return new VCanvas_canvas(width, height, target, interact); }; } else if (document.namespaces && !document.namespaces.v) { // VML is available document.namespaces.add('v', 'urn:schemas-microsoft-com:vml', '#default#VML'); $.fn.sparkline.canvas = function(width, height, target, interact) { return new VCanvas_vml(width, height, target); }; } else { // Neither Canvas nor VML are available $.fn.sparkline.canvas = false; return false; } } if (width === undefined) { width = $(this).innerWidth(); } if (height === undefined) { height = $(this).innerHeight(); } target = $.fn.sparkline.canvas(width, height, this, interact); mhandler = $(this).data('_jqs_mhandler'); if (mhandler) { mhandler.registerCanvas(target); } return target; }; $.fn.cleardraw = function () { var target = this.data('_jqs_vcanvas'); if (target) { target.reset(); } }; $.RangeMapClass = RangeMap = createClass({ init: function (map) { var key, range, rangelist = []; for (key in map) { if (map.hasOwnProperty(key) && typeof key === 'string' && key.indexOf(':') > -1) { range = key.split(':'); range[0] = range[0].length === 0 ? -Infinity : parseFloat(range[0]); range[1] = range[1].length === 0 ? Infinity : parseFloat(range[1]); range[2] = map[key]; rangelist.push(range); } } this.map = map; this.rangelist = rangelist || false; }, get: function (value) { var rangelist = this.rangelist, i, range, result; if ((result = this.map[value]) !== undefined) { return result; } if (rangelist) { for (i = rangelist.length; i--;) { range = rangelist[i]; if (range[0] <= value && range[1] >= value) { return range[2]; } } } return undefined; } }); // Convenience function $.range_map = function(map) { return new RangeMap(map); }; MouseHandler = createClass({ init: function (el, options) { var $el = $(el); this.$el = $el; this.options = options; this.currentPageX = 0; this.currentPageY = 0; this.el = el; this.splist = []; this.tooltip = null; this.over = false; this.displayTooltips = !options.get('disableTooltips'); this.highlightEnabled = !options.get('disableHighlight'); }, registerSparkline: function (sp) { this.splist.push(sp); if (this.over) { this.updateDisplay(); } }, registerCanvas: function (canvas) { var $canvas = $(canvas.canvas); this.canvas = canvas; this.$canvas = $canvas; $canvas.mouseenter($.proxy(this.mouseenter, this)); $canvas.mouseleave($.proxy(this.mouseleave, this)); $canvas.click($.proxy(this.mouseclick, this)); }, reset: function (removeTooltip) { this.splist = []; if (this.tooltip && removeTooltip) { this.tooltip.remove(); this.tooltip = undefined; } }, mouseclick: function (e) { var clickEvent = $.Event('sparklineClick'); clickEvent.originalEvent = e; clickEvent.sparklines = this.splist; this.$el.trigger(clickEvent); }, mouseenter: function (e) { $(document.body).unbind('mousemove.jqs'); $(document.body).bind('mousemove.jqs', $.proxy(this.mousemove, this)); this.over = true; this.currentPageX = e.pageX; this.currentPageY = e.pageY; this.currentEl = e.target; if (!this.tooltip && this.displayTooltips) { this.tooltip = new Tooltip(this.options); this.tooltip.updatePosition(e.pageX, e.pageY); } this.updateDisplay(); }, mouseleave: function () { $(document.body).unbind('mousemove.jqs'); var splist = this.splist, spcount = splist.length, needsRefresh = false, sp, i; this.over = false; this.currentEl = null; if (this.tooltip) { this.tooltip.remove(); this.tooltip = null; } for (i = 0; i < spcount; i++) { sp = splist[i]; if (sp.clearRegionHighlight()) { needsRefresh = true; } } if (needsRefresh) { this.canvas.render(); } }, mousemove: function (e) { this.currentPageX = e.pageX; this.currentPageY = e.pageY; this.currentEl = e.target; if (this.tooltip) { this.tooltip.updatePosition(e.pageX, e.pageY); } this.updateDisplay(); }, updateDisplay: function () { var splist = this.splist, spcount = splist.length, needsRefresh = false, offset = this.$canvas.offset(), localX = this.currentPageX - offset.left, localY = this.currentPageY - offset.top, tooltiphtml, sp, i, result, changeEvent; if (!this.over) { return; } for (i = 0; i < spcount; i++) { sp = splist[i]; result = sp.setRegionHighlight(this.currentEl, localX, localY); if (result) { needsRefresh = true; } } if (needsRefresh) { changeEvent = $.Event('sparklineRegionChange'); changeEvent.sparklines = this.splist; this.$el.trigger(changeEvent); if (this.tooltip) { tooltiphtml = ''; for (i = 0; i < spcount; i++) { sp = splist[i]; tooltiphtml += sp.getCurrentRegionTooltip(); } this.tooltip.setContent(tooltiphtml); } if (!this.disableHighlight) { this.canvas.render(); } } if (result === null) { this.mouseleave(); } } }); Tooltip = createClass({ sizeStyle: 'position: static !important;' + 'display: block !important;' + 'visibility: hidden !important;' + 'float: left !important;', init: function (options) { var tooltipClassname = options.get('tooltipClassname', 'jqstooltip'), sizetipStyle = this.sizeStyle, offset; this.container = options.get('tooltipContainer') || document.body; this.tooltipOffsetX = options.get('tooltipOffsetX', 10); this.tooltipOffsetY = options.get('tooltipOffsetY', 12); // remove any previous lingering tooltip $('#jqssizetip').remove(); $('#jqstooltip').remove(); this.sizetip = $('<div/>', { id: 'jqssizetip', style: sizetipStyle, 'class': tooltipClassname }); this.tooltip = $('<div/>', { id: 'jqstooltip', 'class': tooltipClassname }).appendTo(this.container); // account for the container's location offset = this.tooltip.offset(); this.offsetLeft = offset.left; this.offsetTop = offset.top; this.hidden = true; $(window).unbind('resize.jqs scroll.jqs'); $(window).bind('resize.jqs scroll.jqs', $.proxy(this.updateWindowDims, this)); this.updateWindowDims(); }, updateWindowDims: function () { this.scrollTop = $(window).scrollTop(); this.scrollLeft = $(window).scrollLeft(); this.scrollRight = this.scrollLeft + $(window).width(); this.updatePosition(); }, getSize: function (content) { this.sizetip.html(content).appendTo(this.container); this.width = this.sizetip.width() + 1; this.height = this.sizetip.height(); this.sizetip.remove(); }, setContent: function (content) { if (!content) { this.tooltip.css('visibility', 'hidden'); this.hidden = true; return; } this.getSize(content); this.tooltip.html(content) .css({ 'width': this.width, 'height': this.height, 'visibility': 'visible' }); if (this.hidden) { this.hidden = false; this.updatePosition(); } }, updatePosition: function (x, y) { if (x === undefined) { if (this.mousex === undefined) { return; } x = this.mousex - this.offsetLeft; y = this.mousey - this.offsetTop; } else { this.mousex = x = x - this.offsetLeft; this.mousey = y = y - this.offsetTop; } if (!this.height || !this.width || this.hidden) { return; } y -= this.height + this.tooltipOffsetY; x += this.tooltipOffsetX; if (y < this.scrollTop) { y = this.scrollTop; } if (x < this.scrollLeft) { x = this.scrollLeft; } else if (x + this.width > this.scrollRight) { x = this.scrollRight - this.width; } this.tooltip.css({ 'left': x, 'top': y }); }, remove: function () { this.tooltip.remove(); this.sizetip.remove(); this.sizetip = this.tooltip = undefined; $(window).unbind('resize.jqs scroll.jqs'); } }); initStyles = function() { addCSS(defaultStyles); }; $(initStyles); pending = []; $.fn.sparkline = function (userValues, userOptions) { return this.each(function () { var options = new $.fn.sparkline.options(this, userOptions), $this = $(this), render, i; render = function () { var values, width, height, tmp, mhandler, sp, vals; if (userValues === 'html' || userValues === undefined) { vals = this.getAttribute(options.get('tagValuesAttribute')); if (vals === undefined || vals === null) { vals = $this.html(); } values = vals.replace(/(^\s*<!--)|(-->\s*$)|\s+/g, '').split(','); } else { values = userValues; } width = options.get('width') === 'auto' ? values.length * options.get('defaultPixelsPerValue') : options.get('width'); if (options.get('height') === 'auto') { if (!options.get('composite') || !$.data(this, '_jqs_vcanvas')) { // must be a better way to get the line height tmp = document.createElement('span'); tmp.innerHTML = 'a'; $this.html(tmp); height = $(tmp).innerHeight() || $(tmp).height(); $(tmp).remove(); tmp = null; } } else { height = options.get('height'); } if (!options.get('disableInteraction')) { mhandler = $.data(this, '_jqs_mhandler'); if (!mhandler) { mhandler = new MouseHandler(this, options); $.data(this, '_jqs_mhandler', mhandler); } else if (!options.get('composite')) { mhandler.reset(); } } else { mhandler = false; } if (options.get('composite') && !$.data(this, '_jqs_vcanvas')) { if (!$.data(this, '_jqs_errnotify')) { alert('Attempted to attach a composite sparkline to an element with no existing sparkline'); $.data(this, '_jqs_errnotify', true); } return; } sp = new $.fn.sparkline[options.get('type')](this, values, options, width, height); sp.render(); if (mhandler) { mhandler.registerSparkline(sp); } }; if (($(this).html() && !options.get('disableHiddenCheck') && $(this).is(':hidden')) || !$(this).parents('body').length) { if (!options.get('composite') && $.data(this, '_jqs_pending')) { // remove any existing references to the element for (i = pending.length; i; i--) { if (pending[i - 1][0] == this) { pending.splice(i - 1, 1); } } } pending.push([this, render]); $.data(this, '_jqs_pending', true); } else { render.call(this); } }); }; $.fn.sparkline.defaults = getDefaults(); $.sparkline_display_visible = function () { var el, i, pl; var done = []; for (i = 0, pl = pending.length; i < pl; i++) { el = pending[i][0]; if ($(el).is(':visible') && !$(el).parents().is(':hidden')) { pending[i][1].call(el); $.data(pending[i][0], '_jqs_pending', false); done.push(i); } else if (!$(el).closest('html').length && !$.data(el, '_jqs_pending')) { // element has been inserted and removed from the DOM // If it was not yet inserted into the dom then the .data request // will return true. // removing from the dom causes the data to be removed. $.data(pending[i][0], '_jqs_pending', false); done.push(i); } } for (i = done.length; i; i--) { pending.splice(done[i - 1], 1); } }; /** * User option handler */ $.fn.sparkline.options = createClass({ init: function (tag, userOptions) { var extendedOptions, defaults, base, tagOptionType; this.userOptions = userOptions = userOptions || {}; this.tag = tag; this.tagValCache = {}; defaults = $.fn.sparkline.defaults; base = defaults.common; this.tagOptionsPrefix = userOptions.enableTagOptions && (userOptions.tagOptionsPrefix || base.tagOptionsPrefix); tagOptionType = this.getTagSetting('type'); if (tagOptionType === UNSET_OPTION) { extendedOptions = defaults[userOptions.type || base.type]; } else { extendedOptions = defaults[tagOptionType]; } this.mergedOptions = $.extend({}, base, extendedOptions, userOptions); }, getTagSetting: function (key) { var prefix = this.tagOptionsPrefix, val, i, pairs, keyval; if (prefix === false || prefix === undefined) { return UNSET_OPTION; } if (this.tagValCache.hasOwnProperty(key)) { val = this.tagValCache.key; } else { val = this.tag.getAttribute(prefix + key); if (val === undefined || val === null) { val = UNSET_OPTION; } else if (val.substr(0, 1) === '[') { val = val.substr(1, val.length - 2).split(','); for (i = val.length; i--;) { val[i] = normalizeValue(val[i].replace(/(^\s*)|(\s*$)/g, '')); } } else if (val.substr(0, 1) === '{') { pairs = val.substr(1, val.length - 2).split(','); val = {}; for (i = pairs.length; i--;) { keyval = pairs[i].split(':', 2); val[keyval[0].replace(/(^\s*)|(\s*$)/g, '')] = normalizeValue(keyval[1].replace(/(^\s*)|(\s*$)/g, '')); } } else { val = normalizeValue(val); } this.tagValCache.key = val; } return val; }, get: function (key, defaultval) { var tagOption = this.getTagSetting(key), result; if (tagOption !== UNSET_OPTION) { return tagOption; } return (result = this.mergedOptions[key]) === undefined ? defaultval : result; } }); $.fn.sparkline._base = createClass({ disabled: false, init: function (el, values, options, width, height) { this.el = el; this.$el = $(el); this.values = values; this.options = options; this.width = width; this.height = height; this.currentRegion = undefined; }, /** * Setup the canvas */ initTarget: function () { var interactive = !this.options.get('disableInteraction'); if (!(this.target = this.$el.simpledraw(this.width, this.height, this.options.get('composite'), interactive))) { this.disabled = true; } else { this.canvasWidth = this.target.pixelWidth; this.canvasHeight = this.target.pixelHeight; } }, /** * Actually render the chart to the canvas */ render: function () { if (this.disabled) { this.el.innerHTML = ''; return false; } return true; }, /** * Return a region id for a given x/y co-ordinate */ getRegion: function (x, y) { }, /** * Highlight an item based on the moused-over x,y co-ordinate */ setRegionHighlight: function (el, x, y) { var currentRegion = this.currentRegion, highlightEnabled = !this.options.get('disableHighlight'), newRegion; if (x > this.canvasWidth || y > this.canvasHeight || x < 0 || y < 0) { return null; } newRegion = this.getRegion(el, x, y); if (currentRegion !== newRegion) { if (currentRegion !== undefined && highlightEnabled) { this.removeHighlight(); } this.currentRegion = newRegion; if (newRegion !== undefined && highlightEnabled) { this.renderHighlight(); } return true; } return false; }, /** * Reset any currently highlighted item */ clearRegionHighlight: function () { if (this.currentRegion !== undefined) { this.removeHighlight(); this.currentRegion = undefined; return true; } return false; }, renderHighlight: function () { this.changeHighlight(true); }, removeHighlight: function () { this.changeHighlight(false); }, changeHighlight: function (highlight) {}, /** * Fetch the HTML to display as a tooltip */ getCurrentRegionTooltip: function () { var options = this.options, header = '', entries = [], fields, formats, formatlen, fclass, text, i, showFields, showFieldsKey, newFields, fv, formatter, format, fieldlen, j; if (this.currentRegion === undefined) { return ''; } fields = this.getCurrentRegionFields(); formatter = options.get('tooltipFormatter'); if (formatter) { return formatter(this, options, fields); } if (options.get('tooltipChartTitle')) { header += '<div class="jqs jqstitle">' + options.get('tooltipChartTitle') + '</div>\n'; } formats = this.options.get('tooltipFormat'); if (!formats) { return ''; } if (!$.isArray(formats)) { formats = [formats]; } if (!$.isArray(fields)) { fields = [fields]; } showFields = this.options.get('tooltipFormatFieldlist'); showFieldsKey = this.options.get('tooltipFormatFieldlistKey'); if (showFields && showFieldsKey) { // user-selected ordering of fields newFields = []; for (i = fields.length; i--;) { fv = fields[i][showFieldsKey]; if ((j = $.inArray(fv, showFields)) != -1) { newFields[j] = fields[i]; } } fields = newFields; } formatlen = formats.length; fieldlen = fields.length; for (i = 0; i < formatlen; i++) { format = formats[i]; if (typeof format === 'string') { format = new SPFormat(format); } fclass = format.fclass || 'jqsfield'; for (j = 0; j < fieldlen; j++) { if (!fields[j].isNull || !options.get('tooltipSkipNull')) { $.extend(fields[j], { prefix: options.get('tooltipPrefix'), suffix: options.get('tooltipSuffix') }); text = format.render(fields[j], options.get('tooltipValueLookups'), options); entries.push('<div class="' + fclass + '">' + text + '</div>'); } } } if (entries.length) { return header + entries.join('\n'); } return ''; }, getCurrentRegionFields: function () {}, calcHighlightColor: function (color, options) { var highlightColor = options.get('highlightColor'), lighten = options.get('highlightLighten'), parse, mult, rgbnew, i; if (highlightColor) { return highlightColor; } if (lighten) { // extract RGB values parse = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(color) || /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(color); if (parse) { rgbnew = []; mult = color.length === 4 ? 16 : 1; for (i = 0; i < 3; i++) { rgbnew[i] = clipval(Math.round(parseInt(parse[i + 1], 16) * mult * lighten), 0, 255); } return 'rgb(' + rgbnew.join(',') + ')'; } } return color; } }); barHighlightMixin = { changeHighlight: function (highlight) { var currentRegion = this.currentRegion, target = this.target, shapeids = this.regionShapes[currentRegion], newShapes; // will be null if the region value was null if (shapeids) { newShapes = this.renderRegion(currentRegion, highlight); if ($.isArray(newShapes) || $.isArray(shapeids)) { target.replaceWithShapes(shapeids, newShapes); this.regionShapes[currentRegion] = $.map(newShapes, function (newShape) { return newShape.id; }); } else { target.replaceWithShape(shapeids, newShapes); this.regionShapes[currentRegion] = newShapes.id; } } }, render: function () { var values = this.values, target = this.target, regionShapes = this.regionShapes, shapes, ids, i, j; if (!this.cls._super.render.call(this)) { return; } for (i = values.length; i--;) { shapes = this.renderRegion(i); if (shapes) { if ($.isArray(shapes)) { ids = []; for (j = shapes.length; j--;) { shapes[j].append(); ids.push(shapes[j].id); } regionShapes[i] = ids; } else { shapes.append(); regionShapes[i] = shapes.id; // store just the shapeid } } else { // null value regionShapes[i] = null; } } target.render(); } }; /** * Line charts */ $.fn.sparkline.line = line = createClass($.fn.sparkline._base, { type: 'line', init: function (el, values, options, width, height) { line._super.init.call(this, el, values, options, width, height); this.vertices = []; this.regionMap = []; this.xvalues = []; this.yvalues = []; this.yminmax = []; this.hightlightSpotId = null; this.lastShapeId = null; this.initTarget(); }, getRegion: function (el, x, y) { var i, regionMap = this.regionMap; // maps regions to value positions for (i = regionMap.length; i--;) { if (regionMap[i] !== null && x >= regionMap[i][0] && x <= regionMap[i][1]) { return regionMap[i][2]; } } return undefined; }, getCurrentRegionFields: function () { var currentRegion = this.currentRegion; return { isNull: this.yvalues[currentRegion] === null, x: this.xvalues[currentRegion], y: this.yvalues[currentRegion], color: this.options.get('lineColor'), fillColor: this.options.get('fillColor'), offset: currentRegion }; }, renderHighlight: function () { var currentRegion = this.currentRegion, target = this.target, vertex = this.vertices[currentRegion], options = this.options, spotRadius = options.get('spotRadius'), highlightSpotColor = options.get('highlightSpotColor'), highlightLineColor = options.get('highlightLineColor'), highlightSpot, highlightLine; if (!vertex) { return; } if (spotRadius && highlightSpotColor) { highlightSpot = target.drawCircle(vertex[0], vertex[1], spotRadius, undefined, highlightSpotColor); this.highlightSpotId = highlightSpot.id; target.insertAfterShape(this.lastShapeId, highlightSpot); } if (highlightLineColor) { highlightLine = target.drawLine(vertex[0], this.canvasTop, vertex[0], this.canvasTop + this.canvasHeight, highlightLineColor); this.highlightLineId = highlightLine.id; target.insertAfterShape(this.lastShapeId, highlightLine); } }, removeHighlight: function () { var target = this.target; if (this.highlightSpotId) { target.removeShapeId(this.highlightSpotId); this.highlightSpotId = null; } if (this.highlightLineId) { target.removeShapeId(this.highlightLineId); this.highlightLineId = null; } }, scanValues: function () { var values = this.values, valcount = values.length, xvalues = this.xvalues, yvalues = this.yvalues, yminmax = this.yminmax, i, val, isStr, isArray, sp; for (i = 0; i < valcount; i++) { val = values[i]; isStr = typeof(values[i]) === 'string'; isArray = typeof(values[i]) === 'object' && values[i] instanceof Array; sp = isStr && values[i].split(':'); if (isStr && sp.length === 2) { // x:y xvalues.push(Number(sp[0])); yvalues.push(Number(sp[1])); yminmax.push(Number(sp[1])); } else if (isArray) { xvalues.push(val[0]); yvalues.push(val[1]); yminmax.push(val[1]); } else { xvalues.push(i); if (values[i] === null || values[i] === 'null') { yvalues.push(null); } else { yvalues.push(Number(val)); yminmax.push(Number(val)); } } } if (this.options.get('xvalues')) { xvalues = this.options.get('xvalues'); } this.maxy = this.maxyorg = Math.max.apply(Math, yminmax); this.miny = this.minyorg = Math.min.apply(Math, yminmax); this.maxx = Math.max.apply(Math, xvalues); this.minx = Math.min.apply(Math, xvalues); this.xvalues = xvalues; this.yvalues = yvalues; this.yminmax = yminmax; }, processRangeOptions: function () { var options = this.options, normalRangeMin = options.get('normalRangeMin'), normalRangeMax = options.get('normalRangeMax'); if (normalRangeMin !== undefined) { if (normalRangeMin < this.miny) { this.miny = normalRangeMin; } if (normalRangeMax > this.maxy) { this.maxy = normalRangeMax; } } if (options.get('chartRangeMin') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMin') < this.miny)) { this.miny = options.get('chartRangeMin'); } if (options.get('chartRangeMax') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMax') > this.maxy)) { this.maxy = options.get('chartRangeMax'); } if (options.get('chartRangeMinX') !== undefined && (options.get('chartRangeClipX') || options.get('chartRangeMinX') < this.minx)) { this.minx = options.get('chartRangeMinX'); } if (options.get('chartRangeMaxX') !== undefined && (options.get('chartRangeClipX') || options.get('chartRangeMaxX') > this.maxx)) { this.maxx = options.get('chartRangeMaxX'); } }, drawNormalRange: function (canvasLeft, canvasTop, canvasHeight, canvasWidth, rangey) { var normalRangeMin = this.options.get('normalRangeMin'), normalRangeMax = this.options.get('normalRangeMax'), ytop = canvasTop + Math.round(canvasHeight - (canvasHeight * ((normalRangeMax - this.miny) / rangey))), height = Math.round((canvasHeight * (normalRangeMax - normalRangeMin)) / rangey); this.target.drawRect(canvasLeft, ytop, canvasWidth, height, undefined, this.options.get('normalRangeColor')).append(); }, render: function () { var options = this.options, target = this.target, canvasWidth = this.canvasWidth, canvasHeight = this.canvasHeight, vertices = this.vertices, spotRadius = options.get('spotRadius'), regionMap = this.regionMap, rangex, rangey, yvallast, canvasTop, canvasLeft, vertex, path, paths, x, y, xnext, xpos, xposnext, last, next, yvalcount, lineShapes, fillShapes, plen, valueSpots, hlSpotsEnabled, color, xvalues, yvalues, i; if (!line._super.render.call(this)) { return; } this.scanValues(); this.processRangeOptions(); xvalues = this.xvalues; yvalues = this.yvalues; if (!this.yminmax.length || this.yvalues.length < 2) { // empty or all null valuess return; } canvasTop = canvasLeft = 0; rangex = this.maxx - this.minx === 0 ? 1 : this.maxx - this.minx; rangey = this.maxy - this.miny === 0 ? 1 : this.maxy - this.miny; yvallast = this.yvalues.length - 1; if (spotRadius && (canvasWidth < (spotRadius * 4) || canvasHeight < (spotRadius * 4))) { spotRadius = 0; } if (spotRadius) { // adjust the canvas size as required so that spots will fit hlSpotsEnabled = options.get('highlightSpotColor') && !options.get('disableInteraction'); if (hlSpotsEnabled || options.get('minSpotColor') || (options.get('spotColor') && yvalues[yvallast] === this.miny)) { canvasHeight -= Math.ceil(spotRadius); } if (hlSpotsEnabled || options.get('maxSpotColor') || (options.get('spotColor') && yvalues[yvallast] === this.maxy)) { canvasHeight -= Math.ceil(spotRadius); canvasTop += Math.ceil(spotRadius); } if (hlSpotsEnabled || ((options.get('minSpotColor') || options.get('maxSpotColor')) && (yvalues[0] === this.miny || yvalues[0] === this.maxy))) { canvasLeft += Math.ceil(spotRadius); canvasWidth -= Math.ceil(spotRadius); } if (hlSpotsEnabled || options.get('spotColor') || (options.get('minSpotColor') || options.get('maxSpotColor') && (yvalues[yvallast] === this.miny || yvalues[yvallast] === this.maxy))) { canvasWidth -= Math.ceil(spotRadius); } } canvasHeight--; if (options.get('normalRangeMin') !== undefined && !options.get('drawNormalOnTop')) { this.drawNormalRange(canvasLeft, canvasTop, canvasHeight, canvasWidth, rangey); } path = []; paths = [path]; last = next = null; yvalcount = yvalues.length; for (i = 0; i < yvalcount; i++) { x = xvalues[i]; xnext = xvalues[i + 1]; y = yvalues[i]; xpos = canvasLeft + Math.round((x - this.minx) * (canvasWidth / rangex)); xposnext = i < yvalcount - 1 ? canvasLeft + Math.round((xnext - this.minx) * (canvasWidth / rangex)) : canvasWidth; next = xpos + ((xposnext - xpos) / 2); regionMap[i] = [last || 0, next, i]; last = next; if (y === null) { if (i) { if (yvalues[i - 1] !== null) { path = []; paths.push(path); } vertices.push(null); } } else { if (y < this.miny) { y = this.miny; } if (y > this.maxy) { y = this.maxy; } if (!path.length) { // previous value was null path.push([xpos, canvasTop + canvasHeight]); } vertex = [xpos, canvasTop + Math.round(canvasHeight - (canvasHeight * ((y - this.miny) / rangey)))]; path.push(vertex); vertices.push(vertex); } } lineShapes = []; fillShapes = []; plen = paths.length; for (i = 0; i < plen; i++) { path = paths[i]; if (path.length) { if (options.get('fillColor')) { path.push([path[path.length - 1][0], (canvasTop + canvasHeight)]); fillShapes.push(path.slice(0)); path.pop(); } // if there's only a single point in this path, then we want to display it // as a vertical line which means we keep path[0] as is if (path.length > 2) { // else we want the first value path[0] = [path[0][0], path[1][1]]; } lineShapes.push(path); } } // draw the fill first, then optionally the normal range, then the line on top of that plen = fillShapes.length; for (i = 0; i < plen; i++) { target.drawShape(fillShapes[i], options.get('fillColor'), options.get('fillColor')).append(); } if (options.get('normalRangeMin') !== undefined && options.get('drawNormalOnTop')) { this.drawNormalRange(canvasLeft, canvasTop, canvasHeight, canvasWidth, rangey); } plen = lineShapes.length; for (i = 0; i < plen; i++) { target.drawShape(lineShapes[i], options.get('lineColor'), undefined, options.get('lineWidth')).append(); } if (spotRadius && options.get('valueSpots')) { valueSpots = options.get('valueSpots'); if (valueSpots.get === undefined) { valueSpots = new RangeMap(valueSpots); } for (i = 0; i < yvalcount; i++) { color = valueSpots.get(yvalues[i]); if (color) { target.drawCircle(canvasLeft + Math.round((xvalues[i] - this.minx) * (canvasWidth / rangex)), canvasTop + Math.round(canvasHeight - (canvasHeight * ((yvalues[i] - this.miny) / rangey))), spotRadius, undefined, color).append(); } } } if (spotRadius && options.get('spotColor') && yvalues[yvallast] !== null) { target.drawCircle(canvasLeft + Math.round((xvalues[xvalues.length - 1] - this.minx) * (canvasWidth / rangex)), canvasTop + Math.round(canvasHeight - (canvasHeight * ((yvalues[yvallast] - this.miny) / rangey))), spotRadius, undefined, options.get('spotColor')).append(); } if (this.maxy !== this.minyorg) { if (spotRadius && options.get('minSpotColor')) { x = xvalues[$.inArray(this.minyorg, yvalues)]; target.drawCircle(canvasLeft + Math.round((x - this.minx) * (canvasWidth / rangex)), canvasTop + Math.round(canvasHeight - (canvasHeight * ((this.minyorg - this.miny) / rangey))), spotRadius, undefined, options.get('minSpotColor')).append(); } if (spotRadius && options.get('maxSpotColor')) { x = xvalues[$.inArray(this.maxyorg, yvalues)]; target.drawCircle(canvasLeft + Math.round((x - this.minx) * (canvasWidth / rangex)), canvasTop + Math.round(canvasHeight - (canvasHeight * ((this.maxyorg - this.miny) / rangey))), spotRadius, undefined, options.get('maxSpotColor')).append(); } } this.lastShapeId = target.getLastShapeId(); this.canvasTop = canvasTop; target.render(); } }); /** * Bar charts */ $.fn.sparkline.bar = bar = createClass($.fn.sparkline._base, barHighlightMixin, { type: 'bar', init: function (el, values, options, width, height) { var barWidth = parseInt(options.get('barWidth'), 10), barSpacing = parseInt(options.get('barSpacing'), 10), chartRangeMin = options.get('chartRangeMin'), chartRangeMax = options.get('chartRangeMax'), chartRangeClip = options.get('chartRangeClip'), stackMin = Infinity, stackMax = -Infinity, isStackString, groupMin, groupMax, stackRanges, numValues, i, vlen, range, zeroAxis, xaxisOffset, min, max, clipMin, clipMax, stacked, vlist, j, slen, svals, val, yoffset, yMaxCalc, canvasHeightEf; bar._super.init.call(this, el, values, options, width, height); // scan values to determine whether to stack bars for (i = 0, vlen = values.length; i < vlen; i++) { val = values[i]; isStackString = typeof(val) === 'string' && val.indexOf(':') > -1; if (isStackString || $.isArray(val)) { stacked = true; if (isStackString) { val = values[i] = normalizeValues(val.split(':')); } val = remove(val, null); // min/max will treat null as zero groupMin = Math.min.apply(Math, val); groupMax = Math.max.apply(Math, val); if (groupMin < stackMin) { stackMin = groupMin; } if (groupMax > stackMax) { stackMax = groupMax; } } } this.stacked = stacked; this.regionShapes = {}; this.barWidth = barWidth; this.barSpacing = barSpacing; this.totalBarWidth = barWidth + barSpacing; this.width = width = (values.length * barWidth) + ((values.length - 1) * barSpacing); this.initTarget(); if (chartRangeClip) { clipMin = chartRangeMin === undefined ? -Infinity : chartRangeMin; clipMax = chartRangeMax === undefined ? Infinity : chartRangeMax; } numValues = []; stackRanges = stacked ? [] : numValues; var stackTotals = []; var stackRangesNeg = []; for (i = 0, vlen = values.length; i < vlen; i++) { if (stacked) { vlist = values[i]; values[i] = svals = []; stackTotals[i] = 0; stackRanges[i] = stackRangesNeg[i] = 0; for (j = 0, slen = vlist.length; j < slen; j++) { val = svals[j] = chartRangeClip ? clipval(vlist[j], clipMin, clipMax) : vlist[j]; if (val !== null) { if (val > 0) { stackTotals[i] += val; } if (stackMin < 0 && stackMax > 0) { if (val < 0) { stackRangesNeg[i] += Math.abs(val); } else { stackRanges[i] += val; } } else { stackRanges[i] += Math.abs(val - (val < 0 ? stackMax : stackMin)); } numValues.push(val); } } } else { val = chartRangeClip ? clipval(values[i], clipMin, clipMax) : values[i]; val = values[i] = normalizeValue(val); if (val !== null) { numValues.push(val); } } } this.max = max = Math.max.apply(Math, numValues); this.min = min = Math.min.apply(Math, numValues); this.stackMax = stackMax = stacked ? Math.max.apply(Math, stackTotals) : max; this.stackMin = stackMin = stacked ? Math.min.apply(Math, numValues) : min; if (options.get('chartRangeMin') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMin') < min)) { min = options.get('chartRangeMin'); } if (options.get('chartRangeMax') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMax') > max)) { max = options.get('chartRangeMax'); } this.zeroAxis = zeroAxis = options.get('zeroAxis', true); if (min <= 0 && max >= 0 && zeroAxis) { xaxisOffset = 0; } else if (zeroAxis == false) { xaxisOffset = min; } else if (min > 0) { xaxisOffset = min; } else { xaxisOffset = max; } this.xaxisOffset = xaxisOffset; range = stacked ? (Math.max.apply(Math, stackRanges) + Math.max.apply(Math, stackRangesNeg)) : max - min; // as we plot zero/min values a single pixel line, we add a pixel to all other // values - Reduce the effective canvas size to suit this.canvasHeightEf = (zeroAxis && min < 0) ? this.canvasHeight - 2 : this.canvasHeight - 1; if (min < xaxisOffset) { yMaxCalc = (stacked && max >= 0) ? stackMax : max; yoffset = (yMaxCalc - xaxisOffset) / range * this.canvasHeight; if (yoffset !== Math.ceil(yoffset)) { this.canvasHeightEf -= 2; yoffset = Math.ceil(yoffset); } } else { yoffset = this.canvasHeight; } this.yoffset = yoffset; if ($.isArray(options.get('colorMap'))) { this.colorMapByIndex = options.get('colorMap'); this.colorMapByValue = null; } else { this.colorMapByIndex = null; this.colorMapByValue = options.get('colorMap'); if (this.colorMapByValue && this.colorMapByValue.get === undefined) { this.colorMapByValue = new RangeMap(this.colorMapByValue); } } this.range = range; }, getRegion: function (el, x, y) { var result = Math.floor(x / this.totalBarWidth); return (result < 0 || result >= this.values.length) ? undefined : result; }, getCurrentRegionFields: function () { var currentRegion = this.currentRegion, values = ensureArray(this.values[currentRegion]), result = [], value, i; for (i = values.length; i--;) { value = values[i]; result.push({ isNull: value === null, value: value, color: this.calcColor(i, value, currentRegion), offset: currentRegion }); } return result; }, calcColor: function (stacknum, value, valuenum) { var colorMapByIndex = this.colorMapByIndex, colorMapByValue = this.colorMapByValue, options = this.options, color, newColor; if (this.stacked) { color = options.get('stackedBarColor'); } else { color = (value < 0) ? options.get('negBarColor') : options.get('barColor'); } if (value === 0 && options.get('zeroColor') !== undefined) { color = options.get('zeroColor'); } if (colorMapByValue && (newColor = colorMapByValue.get(value))) { color = newColor; } else if (colorMapByIndex && colorMapByIndex.length > valuenum) { color = colorMapByIndex[valuenum]; } return $.isArray(color) ? color[stacknum % color.length] : color; }, /** * Render bar(s) for a region */ renderRegion: function (valuenum, highlight) { var vals = this.values[valuenum], options = this.options, xaxisOffset = this.xaxisOffset, result = [], range = this.range, stacked = this.stacked, target = this.target, x = valuenum * this.totalBarWidth, canvasHeightEf = this.canvasHeightEf, yoffset = this.yoffset, y, height, color, isNull, yoffsetNeg, i, valcount, val, minPlotted, allMin; vals = $.isArray(vals) ? vals : [vals]; valcount = vals.length; val = vals[0]; isNull = all(null, vals); allMin = all(xaxisOffset, vals, true); if (isNull) { if (options.get('nullColor')) { color = highlight ? options.get('nullColor') : this.calcHighlightColor(options.get('nullColor'), options); y = (yoffset > 0) ? yoffset - 1 : yoffset; return target.drawRect(x, y, this.barWidth - 1, 0, color, color); } else { return undefined; } } yoffsetNeg = yoffset; for (i = 0; i < valcount; i++) { val = vals[i]; if (stacked && val === xaxisOffset) { if (!allMin || minPlotted) { continue; } minPlotted = true; } if (range > 0) { height = Math.floor(canvasHeightEf * ((Math.abs(val - xaxisOffset) / range))) + 1; } else { height = 1; } if (val < xaxisOffset || (val === xaxisOffset && yoffset === 0)) { y = yoffsetNeg; yoffsetNeg += height; } else { y = yoffset - height; yoffset -= height; } color = this.calcColor(i, val, valuenum); if (highlight) { color = this.calcHighlightColor(color, options); } result.push(target.drawRect(x, y, this.barWidth - 1, height - 1, color, color)); } if (result.length === 1) { return result[0]; } return result; } }); /** * Tristate charts */ $.fn.sparkline.tristate = tristate = createClass($.fn.sparkline._base, barHighlightMixin, { type: 'tristate', init: function (el, values, options, width, height) { var barWidth = parseInt(options.get('barWidth'), 10), barSpacing = parseInt(options.get('barSpacing'), 10); tristate._super.init.call(this, el, values, options, width, height); this.regionShapes = {}; this.barWidth = barWidth; this.barSpacing = barSpacing; this.totalBarWidth = barWidth + barSpacing; this.values = $.map(values, Number); this.width = width = (values.length * barWidth) + ((values.length - 1) * barSpacing); if ($.isArray(options.get('colorMap'))) { this.colorMapByIndex = options.get('colorMap'); this.colorMapByValue = null; } else { this.colorMapByIndex = null; this.colorMapByValue = options.get('colorMap'); if (this.colorMapByValue && this.colorMapByValue.get === undefined) { this.colorMapByValue = new RangeMap(this.colorMapByValue); } } this.initTarget(); }, getRegion: function (el, x, y) { return Math.floor(x / this.totalBarWidth); }, getCurrentRegionFields: function () { var currentRegion = this.currentRegion; return { isNull: this.values[currentRegion] === undefined, value: this.values[currentRegion], color: this.calcColor(this.values[currentRegion], currentRegion), offset: currentRegion }; }, calcColor: function (value, valuenum) { var values = this.values, options = this.options, colorMapByIndex = this.colorMapByIndex, colorMapByValue = this.colorMapByValue, color, newColor; if (colorMapByValue && (newColor = colorMapByValue.get(value))) { color = newColor; } else if (colorMapByIndex && colorMapByIndex.length > valuenum) { color = colorMapByIndex[valuenum]; } else if (values[valuenum] < 0) { color = options.get('negBarColor'); } else if (values[valuenum] > 0) { color = options.get('posBarColor'); } else { color = options.get('zeroBarColor'); } return color; }, renderRegion: function (valuenum, highlight) { var values = this.values, options = this.options, target = this.target, canvasHeight, height, halfHeight, x, y, color; canvasHeight = target.pixelHeight; halfHeight = Math.round(canvasHeight / 2); x = valuenum * this.totalBarWidth; if (values[valuenum] < 0) { y = halfHeight; height = halfHeight - 1; } else if (values[valuenum] > 0) { y = 0; height = halfHeight - 1; } else { y = halfHeight - 1; height = 2; } color = this.calcColor(values[valuenum], valuenum); if (color === null) { return; } if (highlight) { color = this.calcHighlightColor(color, options); } return target.drawRect(x, y, this.barWidth - 1, height - 1, color, color); } }); /** * Discrete charts */ $.fn.sparkline.discrete = discrete = createClass($.fn.sparkline._base, barHighlightMixin, { type: 'discrete', init: function (el, values, options, width, height) { discrete._super.init.call(this, el, values, options, width, height); this.regionShapes = {}; this.values = values = $.map(values, Number); this.min = Math.min.apply(Math, values); this.max = Math.max.apply(Math, values); this.range = this.max - this.min; this.width = width = options.get('width') === 'auto' ? values.length * 2 : this.width; this.interval = Math.floor(width / values.length); this.itemWidth = width / values.length; if (options.get('chartRangeMin') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMin') < this.min)) { this.min = options.get('chartRangeMin'); } if (options.get('chartRangeMax') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMax') > this.max)) { this.max = options.get('chartRangeMax'); } this.initTarget(); if (this.target) { this.lineHeight = options.get('lineHeight') === 'auto' ? Math.round(this.canvasHeight * 0.3) : options.get('lineHeight'); } }, getRegion: function (el, x, y) { return Math.floor(x / this.itemWidth); }, getCurrentRegionFields: function () { var currentRegion = this.currentRegion; return { isNull: this.values[currentRegion] === undefined, value: this.values[currentRegion], offset: currentRegion }; }, renderRegion: function (valuenum, highlight) { var values = this.values, options = this.options, min = this.min, max = this.max, range = this.range, interval = this.interval, target = this.target, canvasHeight = this.canvasHeight, lineHeight = this.lineHeight, pheight = canvasHeight - lineHeight, ytop, val, color, x; val = clipval(values[valuenum], min, max); x = valuenum * interval; ytop = Math.round(pheight - pheight * ((val - min) / range)); color = (options.get('thresholdColor') && val < options.get('thresholdValue')) ? options.get('thresholdColor') : options.get('lineColor'); if (highlight) { color = this.calcHighlightColor(color, options); } return target.drawLine(x, ytop, x, ytop + lineHeight, color); } }); /** * Bullet charts */ $.fn.sparkline.bullet = bullet = createClass($.fn.sparkline._base, { type: 'bullet', init: function (el, values, options, width, height) { var min, max, vals; bullet._super.init.call(this, el, values, options, width, height); // values: target, performance, range1, range2, range3 this.values = values = normalizeValues(values); // target or performance could be null vals = values.slice(); vals[0] = vals[0] === null ? vals[2] : vals[0]; vals[1] = values[1] === null ? vals[2] : vals[1]; min = Math.min.apply(Math, values); max = Math.max.apply(Math, values); if (options.get('base') === undefined) { min = min < 0 ? min : 0; } else { min = options.get('base'); } this.min = min; this.max = max; this.range = max - min; this.shapes = {}; this.valueShapes = {}; this.regiondata = {}; this.width = width = options.get('width') === 'auto' ? '4.0em' : width; this.target = this.$el.simpledraw(width, height, options.get('composite')); if (!values.length) { this.disabled = true; } this.initTarget(); }, getRegion: function (el, x, y) { var shapeid = this.target.getShapeAt(el, x, y); return (shapeid !== undefined && this.shapes[shapeid] !== undefined) ? this.shapes[shapeid] : undefined; }, getCurrentRegionFields: function () { var currentRegion = this.currentRegion; return { fieldkey: currentRegion.substr(0, 1), value: this.values[currentRegion.substr(1)], region: currentRegion }; }, changeHighlight: function (highlight) { var currentRegion = this.currentRegion, shapeid = this.valueShapes[currentRegion], shape; delete this.shapes[shapeid]; switch (currentRegion.substr(0, 1)) { case 'r': shape = this.renderRange(currentRegion.substr(1), highlight); break; case 'p': shape = this.renderPerformance(highlight); break; case 't': shape = this.renderTarget(highlight); break; } this.valueShapes[currentRegion] = shape.id; this.shapes[shape.id] = currentRegion; this.target.replaceWithShape(shapeid, shape); }, renderRange: function (rn, highlight) { var rangeval = this.values[rn], rangewidth = Math.round(this.canvasWidth * ((rangeval - this.min) / this.range)), color = this.options.get('rangeColors')[rn - 2]; if (highlight) { color = this.calcHighlightColor(color, this.options); } return this.target.drawRect(0, 0, rangewidth - 1, this.canvasHeight - 1, color, color); }, renderPerformance: function (highlight) { var perfval = this.values[1], perfwidth = Math.round(this.canvasWidth * ((perfval - this.min) / this.range)), color = this.options.get('performanceColor'); if (highlight) { color = this.calcHighlightColor(color, this.options); } return this.target.drawRect(0, Math.round(this.canvasHeight * 0.3), perfwidth - 1, Math.round(this.canvasHeight * 0.4) - 1, color, color); }, renderTarget: function (highlight) { var targetval = this.values[0], x = Math.round(this.canvasWidth * ((targetval - this.min) / this.range) - (this.options.get('targetWidth') / 2)), targettop = Math.round(this.canvasHeight * 0.10), targetheight = this.canvasHeight - (targettop * 2), color = this.options.get('targetColor'); if (highlight) { color = this.calcHighlightColor(color, this.options); } return this.target.drawRect(x, targettop, this.options.get('targetWidth') - 1, targetheight - 1, color, color); }, render: function () { var vlen = this.values.length, target = this.target, i, shape; if (!bullet._super.render.call(this)) { return; } for (i = 2; i < vlen; i++) { shape = this.renderRange(i).append(); this.shapes[shape.id] = 'r' + i; this.valueShapes['r' + i] = shape.id; } if (this.values[1] !== null) { shape = this.renderPerformance().append(); this.shapes[shape.id] = 'p1'; this.valueShapes.p1 = shape.id; } if (this.values[0] !== null) { shape = this.renderTarget().append(); this.shapes[shape.id] = 't0'; this.valueShapes.t0 = shape.id; } target.render(); } }); /** * Pie charts */ $.fn.sparkline.pie = pie = createClass($.fn.sparkline._base, { type: 'pie', init: function (el, values, options, width, height) { var total = 0, i; pie._super.init.call(this, el, values, options, width, height); this.shapes = {}; // map shape ids to value offsets this.valueShapes = {}; // maps value offsets to shape ids this.values = values = $.map(values, Number); if (options.get('width') === 'auto') { this.width = this.height; } if (values.length > 0) { for (i = values.length; i--;) { total += values[i]; } } this.total = total; this.initTarget(); this.radius = Math.floor(Math.min(this.canvasWidth, this.canvasHeight) / 2); }, getRegion: function (el, x, y) { var shapeid = this.target.getShapeAt(el, x, y); return (shapeid !== undefined && this.shapes[shapeid] !== undefined) ? this.shapes[shapeid] : undefined; }, getCurrentRegionFields: function () { var currentRegion = this.currentRegion; return { isNull: this.values[currentRegion] === undefined, value: this.values[currentRegion], percent: this.values[currentRegion] / this.total * 100, color: this.options.get('sliceColors')[currentRegion % this.options.get('sliceColors').length], offset: currentRegion }; }, changeHighlight: function (highlight) { var currentRegion = this.currentRegion, newslice = this.renderSlice(currentRegion, highlight), shapeid = this.valueShapes[currentRegion]; delete this.shapes[shapeid]; this.target.replaceWithShape(shapeid, newslice); this.valueShapes[currentRegion] = newslice.id; this.shapes[newslice.id] = currentRegion; }, renderSlice: function (valuenum, highlight) { var target = this.target, options = this.options, radius = this.radius, borderWidth = options.get('borderWidth'), offset = options.get('offset'), circle = 2 * Math.PI, values = this.values, total = this.total, next = offset ? (2*Math.PI)*(offset/360) : 0, start, end, i, vlen, color; vlen = values.length; for (i = 0; i < vlen; i++) { start = next; end = next; if (total > 0) { // avoid divide by zero end = next + (circle * (values[i] / total)); } if (valuenum === i) { color = options.get('sliceColors')[i % options.get('sliceColors').length]; if (highlight) { color = this.calcHighlightColor(color, options); } return target.drawPieSlice(radius, radius, radius - borderWidth, start, end, undefined, color); } next = end; } }, render: function () { var target = this.target, values = this.values, options = this.options, radius = this.radius, borderWidth = options.get('borderWidth'), shape, i; if (!pie._super.render.call(this)) { return; } if (borderWidth) { target.drawCircle(radius, radius, Math.floor(radius - (borderWidth / 2)), options.get('borderColor'), undefined, borderWidth).append(); } for (i = values.length; i--;) { if (values[i]) { // don't render zero values shape = this.renderSlice(i).append(); this.valueShapes[i] = shape.id; // store just the shapeid this.shapes[shape.id] = i; } } target.render(); } }); /** * Box plots */ $.fn.sparkline.box = box = createClass($.fn.sparkline._base, { type: 'box', init: function (el, values, options, width, height) { box._super.init.call(this, el, values, options, width, height); this.values = $.map(values, Number); this.width = options.get('width') === 'auto' ? '4.0em' : width; this.initTarget(); if (!this.values.length) { this.disabled = 1; } }, /** * Simulate a single region */ getRegion: function () { return 1; }, getCurrentRegionFields: function () { var result = [ { field: 'lq', value: this.quartiles[0] }, { field: 'med', value: this.quartiles[1] }, { field: 'uq', value: this.quartiles[2] } ]; if (this.loutlier !== undefined) { result.push({ field: 'lo', value: this.loutlier}); } if (this.routlier !== undefined) { result.push({ field: 'ro', value: this.routlier}); } if (this.lwhisker !== undefined) { result.push({ field: 'lw', value: this.lwhisker}); } if (this.rwhisker !== undefined) { result.push({ field: 'rw', value: this.rwhisker}); } return result; }, render: function () { var target = this.target, values = this.values, vlen = values.length, options = this.options, canvasWidth = this.canvasWidth, canvasHeight = this.canvasHeight, minValue = options.get('chartRangeMin') === undefined ? Math.min.apply(Math, values) : options.get('chartRangeMin'), maxValue = options.get('chartRangeMax') === undefined ? Math.max.apply(Math, values) : options.get('chartRangeMax'), canvasLeft = 0, lwhisker, loutlier, iqr, q1, q2, q3, rwhisker, routlier, i, size, unitSize; if (!box._super.render.call(this)) { return; } if (options.get('raw')) { if (options.get('showOutliers') && values.length > 5) { loutlier = values[0]; lwhisker = values[1]; q1 = values[2]; q2 = values[3]; q3 = values[4]; rwhisker = values[5]; routlier = values[6]; } else { lwhisker = values[0]; q1 = values[1]; q2 = values[2]; q3 = values[3]; rwhisker = values[4]; } } else { values.sort(function (a, b) { return a - b; }); q1 = quartile(values, 1); q2 = quartile(values, 2); q3 = quartile(values, 3); iqr = q3 - q1; if (options.get('showOutliers')) { lwhisker = rwhisker = undefined; for (i = 0; i < vlen; i++) { if (lwhisker === undefined && values[i] > q1 - (iqr * options.get('outlierIQR'))) { lwhisker = values[i]; } if (values[i] < q3 + (iqr * options.get('outlierIQR'))) { rwhisker = values[i]; } } loutlier = values[0]; routlier = values[vlen - 1]; } else { lwhisker = values[0]; rwhisker = values[vlen - 1]; } } this.quartiles = [q1, q2, q3]; this.lwhisker = lwhisker; this.rwhisker = rwhisker; this.loutlier = loutlier; this.routlier = routlier; unitSize = canvasWidth / (maxValue - minValue + 1); if (options.get('showOutliers')) { canvasLeft = Math.ceil(options.get('spotRadius')); canvasWidth -= 2 * Math.ceil(options.get('spotRadius')); unitSize = canvasWidth / (maxValue - minValue + 1); if (loutlier < lwhisker) { target.drawCircle((loutlier - minValue) * unitSize + canvasLeft, canvasHeight / 2, options.get('spotRadius'), options.get('outlierLineColor'), options.get('outlierFillColor')).append(); } if (routlier > rwhisker) { target.drawCircle((routlier - minValue) * unitSize + canvasLeft, canvasHeight / 2, options.get('spotRadius'), options.get('outlierLineColor'), options.get('outlierFillColor')).append(); } } // box target.drawRect( Math.round((q1 - minValue) * unitSize + canvasLeft), Math.round(canvasHeight * 0.1), Math.round((q3 - q1) * unitSize), Math.round(canvasHeight * 0.8), options.get('boxLineColor'), options.get('boxFillColor')).append(); // left whisker target.drawLine( Math.round((lwhisker - minValue) * unitSize + canvasLeft), Math.round(canvasHeight / 2), Math.round((q1 - minValue) * unitSize + canvasLeft), Math.round(canvasHeight / 2), options.get('lineColor')).append(); target.drawLine( Math.round((lwhisker - minValue) * unitSize + canvasLeft), Math.round(canvasHeight / 4), Math.round((lwhisker - minValue) * unitSize + canvasLeft), Math.round(canvasHeight - canvasHeight / 4), options.get('whiskerColor')).append(); // right whisker target.drawLine(Math.round((rwhisker - minValue) * unitSize + canvasLeft), Math.round(canvasHeight / 2), Math.round((q3 - minValue) * unitSize + canvasLeft), Math.round(canvasHeight / 2), options.get('lineColor')).append(); target.drawLine( Math.round((rwhisker - minValue) * unitSize + canvasLeft), Math.round(canvasHeight / 4), Math.round((rwhisker - minValue) * unitSize + canvasLeft), Math.round(canvasHeight - canvasHeight / 4), options.get('whiskerColor')).append(); // median line target.drawLine( Math.round((q2 - minValue) * unitSize + canvasLeft), Math.round(canvasHeight * 0.1), Math.round((q2 - minValue) * unitSize + canvasLeft), Math.round(canvasHeight * 0.9), options.get('medianColor')).append(); if (options.get('target')) { size = Math.ceil(options.get('spotRadius')); target.drawLine( Math.round((options.get('target') - minValue) * unitSize + canvasLeft), Math.round((canvasHeight / 2) - size), Math.round((options.get('target') - minValue) * unitSize + canvasLeft), Math.round((canvasHeight / 2) + size), options.get('targetColor')).append(); target.drawLine( Math.round((options.get('target') - minValue) * unitSize + canvasLeft - size), Math.round(canvasHeight / 2), Math.round((options.get('target') - minValue) * unitSize + canvasLeft + size), Math.round(canvasHeight / 2), options.get('targetColor')).append(); } target.render(); } }); // Setup a very simple "virtual canvas" to make drawing the few shapes we need easier // This is accessible as $(foo).simpledraw() VShape = createClass({ init: function (target, id, type, args) { this.target = target; this.id = id; this.type = type; this.args = args; }, append: function () { this.target.appendShape(this); return this; } }); VCanvas_base = createClass({ _pxregex: /(\d+)(px)?\s*$/i, init: function (width, height, target) { if (!width) { return; } this.width = width; this.height = height; this.target = target; this.lastShapeId = null; if (target[0]) { target = target[0]; } $.data(target, '_jqs_vcanvas', this); }, drawLine: function (x1, y1, x2, y2, lineColor, lineWidth) { return this.drawShape([[x1, y1], [x2, y2]], lineColor, lineWidth); }, drawShape: function (path, lineColor, fillColor, lineWidth) { return this._genShape('Shape', [path, lineColor, fillColor, lineWidth]); }, drawCircle: function (x, y, radius, lineColor, fillColor, lineWidth) { return this._genShape('Circle', [x, y, radius, lineColor, fillColor, lineWidth]); }, drawPieSlice: function (x, y, radius, startAngle, endAngle, lineColor, fillColor) { return this._genShape('PieSlice', [x, y, radius, startAngle, endAngle, lineColor, fillColor]); }, drawRect: function (x, y, width, height, lineColor, fillColor) { return this._genShape('Rect', [x, y, width, height, lineColor, fillColor]); }, getElement: function () { return this.canvas; }, /** * Return the most recently inserted shape id */ getLastShapeId: function () { return this.lastShapeId; }, /** * Clear and reset the canvas */ reset: function () { alert('reset not implemented'); }, _insert: function (el, target) { $(target).html(el); }, /** * Calculate the pixel dimensions of the canvas */ _calculatePixelDims: function (width, height, canvas) { // XXX This should probably be a configurable option var match; match = this._pxregex.exec(height); if (match) { this.pixelHeight = match[1]; } else { this.pixelHeight = $(canvas).height(); } match = this._pxregex.exec(width); if (match) { this.pixelWidth = match[1]; } else { this.pixelWidth = $(canvas).width(); } }, /** * Generate a shape object and id for later rendering */ _genShape: function (shapetype, shapeargs) { var id = shapeCount++; shapeargs.unshift(id); return new VShape(this, id, shapetype, shapeargs); }, /** * Add a shape to the end of the render queue */ appendShape: function (shape) { alert('appendShape not implemented'); }, /** * Replace one shape with another */ replaceWithShape: function (shapeid, shape) { alert('replaceWithShape not implemented'); }, /** * Insert one shape after another in the render queue */ insertAfterShape: function (shapeid, shape) { alert('insertAfterShape not implemented'); }, /** * Remove a shape from the queue */ removeShapeId: function (shapeid) { alert('removeShapeId not implemented'); }, /** * Find a shape at the specified x/y co-ordinates */ getShapeAt: function (el, x, y) { alert('getShapeAt not implemented'); }, /** * Render all queued shapes onto the canvas */ render: function () { alert('render not implemented'); } }); VCanvas_canvas = createClass(VCanvas_base, { init: function (width, height, target, interact) { VCanvas_canvas._super.init.call(this, width, height, target); this.canvas = document.createElement('canvas'); if (target[0]) { target = target[0]; } $.data(target, '_jqs_vcanvas', this); $(this.canvas).css({ display: 'inline-block', width: width, height: height, verticalAlign: 'top' }); this._insert(this.canvas, target); this._calculatePixelDims(width, height, this.canvas); this.canvas.width = this.pixelWidth; this.canvas.height = this.pixelHeight; this.interact = interact; this.shapes = {}; this.shapeseq = []; this.currentTargetShapeId = undefined; $(this.canvas).css({width: this.pixelWidth, height: this.pixelHeight}); }, _getContext: function (lineColor, fillColor, lineWidth) { var context = this.canvas.getContext('2d'); if (lineColor !== undefined) { context.strokeStyle = lineColor; } context.lineWidth = lineWidth === undefined ? 1 : lineWidth; if (fillColor !== undefined) { context.fillStyle = fillColor; } return context; }, reset: function () { var context = this._getContext(); context.clearRect(0, 0, this.pixelWidth, this.pixelHeight); this.shapes = {}; this.shapeseq = []; this.currentTargetShapeId = undefined; }, _drawShape: function (shapeid, path, lineColor, fillColor, lineWidth) { var context = this._getContext(lineColor, fillColor, lineWidth), i, plen; context.beginPath(); context.moveTo(path[0][0] + 0.5, path[0][1] + 0.5); for (i = 1, plen = path.length; i < plen; i++) { context.lineTo(path[i][0] + 0.5, path[i][1] + 0.5); // the 0.5 offset gives us crisp pixel-width lines } if (lineColor !== undefined) { context.stroke(); } if (fillColor !== undefined) { context.fill(); } if (this.targetX !== undefined && this.targetY !== undefined && context.isPointInPath(this.targetX, this.targetY)) { this.currentTargetShapeId = shapeid; } }, _drawCircle: function (shapeid, x, y, radius, lineColor, fillColor, lineWidth) { var context = this._getContext(lineColor, fillColor, lineWidth); context.beginPath(); context.arc(x, y, radius, 0, 2 * Math.PI, false); if (this.targetX !== undefined && this.targetY !== undefined && context.isPointInPath(this.targetX, this.targetY)) { this.currentTargetShapeId = shapeid; } if (lineColor !== undefined) { context.stroke(); } if (fillColor !== undefined) { context.fill(); } }, _drawPieSlice: function (shapeid, x, y, radius, startAngle, endAngle, lineColor, fillColor) { var context = this._getContext(lineColor, fillColor); context.beginPath(); context.moveTo(x, y); context.arc(x, y, radius, startAngle, endAngle, false); context.lineTo(x, y); context.closePath(); if (lineColor !== undefined) { context.stroke(); } if (fillColor) { context.fill(); } if (this.targetX !== undefined && this.targetY !== undefined && context.isPointInPath(this.targetX, this.targetY)) { this.currentTargetShapeId = shapeid; } }, _drawRect: function (shapeid, x, y, width, height, lineColor, fillColor) { return this._drawShape(shapeid, [[x, y], [x + width, y], [x + width, y + height], [x, y + height], [x, y]], lineColor, fillColor); }, appendShape: function (shape) { this.shapes[shape.id] = shape; this.shapeseq.push(shape.id); this.lastShapeId = shape.id; return shape.id; }, replaceWithShape: function (shapeid, shape) { var shapeseq = this.shapeseq, i; this.shapes[shape.id] = shape; for (i = shapeseq.length; i--;) { if (shapeseq[i] == shapeid) { shapeseq[i] = shape.id; } } delete this.shapes[shapeid]; }, replaceWithShapes: function (shapeids, shapes) { var shapeseq = this.shapeseq, shapemap = {}, sid, i, first; for (i = shapeids.length; i--;) { shapemap[shapeids[i]] = true; } for (i = shapeseq.length; i--;) { sid = shapeseq[i]; if (shapemap[sid]) { shapeseq.splice(i, 1); delete this.shapes[sid]; first = i; } } for (i = shapes.length; i--;) { shapeseq.splice(first, 0, shapes[i].id); this.shapes[shapes[i].id] = shapes[i]; } }, insertAfterShape: function (shapeid, shape) { var shapeseq = this.shapeseq, i; for (i = shapeseq.length; i--;) { if (shapeseq[i] === shapeid) { shapeseq.splice(i + 1, 0, shape.id); this.shapes[shape.id] = shape; return; } } }, removeShapeId: function (shapeid) { var shapeseq = this.shapeseq, i; for (i = shapeseq.length; i--;) { if (shapeseq[i] === shapeid) { shapeseq.splice(i, 1); break; } } delete this.shapes[shapeid]; }, getShapeAt: function (el, x, y) { this.targetX = x; this.targetY = y; this.render(); return this.currentTargetShapeId; }, render: function () { var shapeseq = this.shapeseq, shapes = this.shapes, shapeCount = shapeseq.length, context = this._getContext(), shapeid, shape, i; context.clearRect(0, 0, this.pixelWidth, this.pixelHeight); for (i = 0; i < shapeCount; i++) { shapeid = shapeseq[i]; shape = shapes[shapeid]; this['_draw' + shape.type].apply(this, shape.args); } if (!this.interact) { // not interactive so no need to keep the shapes array this.shapes = {}; this.shapeseq = []; } } }); VCanvas_vml = createClass(VCanvas_base, { init: function (width, height, target) { var groupel; VCanvas_vml._super.init.call(this, width, height, target); if (target[0]) { target = target[0]; } $.data(target, '_jqs_vcanvas', this); this.canvas = document.createElement('span'); $(this.canvas).css({ display: 'inline-block', position: 'relative', overflow: 'hidden', width: width, height: height, margin: '0px', padding: '0px', verticalAlign: 'top'}); this._insert(this.canvas, target); this._calculatePixelDims(width, height, this.canvas); this.canvas.width = this.pixelWidth; this.canvas.height = this.pixelHeight; groupel = '<v:group coordorigin="0 0" coordsize="' + this.pixelWidth + ' ' + this.pixelHeight + '"' + ' style="position:absolute;top:0;left:0;width:' + this.pixelWidth + 'px;height=' + this.pixelHeight + 'px;"></v:group>'; this.canvas.insertAdjacentHTML('beforeEnd', groupel); this.group = $(this.canvas).children()[0]; this.rendered = false; this.prerender = ''; }, _drawShape: function (shapeid, path, lineColor, fillColor, lineWidth) { var vpath = [], initial, stroke, fill, closed, vel, plen, i; for (i = 0, plen = path.length; i < plen; i++) { vpath[i] = '' + (path[i][0]) + ',' + (path[i][1]); } initial = vpath.splice(0, 1); lineWidth = lineWidth === undefined ? 1 : lineWidth; stroke = lineColor === undefined ? ' stroked="false" ' : ' strokeWeight="' + lineWidth + 'px" strokeColor="' + lineColor + '" '; fill = fillColor === undefined ? ' filled="false"' : ' fillColor="' + fillColor + '" filled="true" '; closed = vpath[0] === vpath[vpath.length - 1] ? 'x ' : ''; vel = '<v:shape coordorigin="0 0" coordsize="' + this.pixelWidth + ' ' + this.pixelHeight + '" ' + ' id="jqsshape' + shapeid + '" ' + stroke + fill + ' style="position:absolute;left:0px;top:0px;height:' + this.pixelHeight + 'px;width:' + this.pixelWidth + 'px;padding:0px;margin:0px;" ' + ' path="m ' + initial + ' l ' + vpath.join(', ') + ' ' + closed + 'e">' + ' </v:shape>'; return vel; }, _drawCircle: function (shapeid, x, y, radius, lineColor, fillColor, lineWidth) { var stroke, fill, vel; x -= radius; y -= radius; stroke = lineColor === undefined ? ' stroked="false" ' : ' strokeWeight="' + lineWidth + 'px" strokeColor="' + lineColor + '" '; fill = fillColor === undefined ? ' filled="false"' : ' fillColor="' + fillColor + '" filled="true" '; vel = '<v:oval ' + ' id="jqsshape' + shapeid + '" ' + stroke + fill + ' style="position:absolute;top:' + y + 'px; left:' + x + 'px; width:' + (radius * 2) + 'px; height:' + (radius * 2) + 'px"></v:oval>'; return vel; }, _drawPieSlice: function (shapeid, x, y, radius, startAngle, endAngle, lineColor, fillColor) { var vpath, startx, starty, endx, endy, stroke, fill, vel; if (startAngle === endAngle) { return ''; // VML seems to have problem when start angle equals end angle. } if ((endAngle - startAngle) === (2 * Math.PI)) { startAngle = 0.0; // VML seems to have a problem when drawing a full circle that doesn't start 0 endAngle = (2 * Math.PI); } startx = x + Math.round(Math.cos(startAngle) * radius); starty = y + Math.round(Math.sin(startAngle) * radius); endx = x + Math.round(Math.cos(endAngle) * radius); endy = y + Math.round(Math.sin(endAngle) * radius); if (startx === endx && starty === endy) { if ((endAngle - startAngle) < Math.PI) { // Prevent very small slices from being mistaken as a whole pie return ''; } // essentially going to be the entire circle, so ignore startAngle startx = endx = x + radius; starty = endy = y; } if (startx === endx && starty === endy && (endAngle - startAngle) < Math.PI) { return ''; } vpath = [x - radius, y - radius, x + radius, y + radius, startx, starty, endx, endy]; stroke = lineColor === undefined ? ' stroked="false" ' : ' strokeWeight="1px" strokeColor="' + lineColor + '" '; fill = fillColor === undefined ? ' filled="false"' : ' fillColor="' + fillColor + '" filled="true" '; vel = '<v:shape coordorigin="0 0" coordsize="' + this.pixelWidth + ' ' + this.pixelHeight + '" ' + ' id="jqsshape' + shapeid + '" ' + stroke + fill + ' style="position:absolute;left:0px;top:0px;height:' + this.pixelHeight + 'px;width:' + this.pixelWidth + 'px;padding:0px;margin:0px;" ' + ' path="m ' + x + ',' + y + ' wa ' + vpath.join(', ') + ' x e">' + ' </v:shape>'; return vel; }, _drawRect: function (shapeid, x, y, width, height, lineColor, fillColor) { return this._drawShape(shapeid, [[x, y], [x, y + height], [x + width, y + height], [x + width, y], [x, y]], lineColor, fillColor); }, reset: function () { this.group.innerHTML = ''; }, appendShape: function (shape) { var vel = this['_draw' + shape.type].apply(this, shape.args); if (this.rendered) { this.group.insertAdjacentHTML('beforeEnd', vel); } else { this.prerender += vel; } this.lastShapeId = shape.id; return shape.id; }, replaceWithShape: function (shapeid, shape) { var existing = $('#jqsshape' + shapeid), vel = this['_draw' + shape.type].apply(this, shape.args); existing[0].outerHTML = vel; }, replaceWithShapes: function (shapeids, shapes) { // replace the first shapeid with all the new shapes then toast the remaining old shapes var existing = $('#jqsshape' + shapeids[0]), replace = '', slen = shapes.length, i; for (i = 0; i < slen; i++) { replace += this['_draw' + shapes[i].type].apply(this, shapes[i].args); } existing[0].outerHTML = replace; for (i = 1; i < shapeids.length; i++) { $('#jqsshape' + shapeids[i]).remove(); } }, insertAfterShape: function (shapeid, shape) { var existing = $('#jqsshape' + shapeid), vel = this['_draw' + shape.type].apply(this, shape.args); existing[0].insertAdjacentHTML('afterEnd', vel); }, removeShapeId: function (shapeid) { var existing = $('#jqsshape' + shapeid); this.group.removeChild(existing[0]); }, getShapeAt: function (el, x, y) { var shapeid = el.id.substr(8); return shapeid; }, render: function () { if (!this.rendered) { // batch the intial render into a single repaint this.group.innerHTML = this.prerender; this.rendered = true; } } }); }))}(document, Math));
JavaScript
// ┌────────────────────────────────────────────────────────────────────┐ \\ // │ Raphaël 2.1.2 - JavaScript Vector Library │ \\ // ├────────────────────────────────────────────────────────────────────┤ \\ // │ Copyright © 2008-2012 Dmitry Baranovskiy (http://raphaeljs.com) │ \\ // │ Copyright © 2008-2012 Sencha Labs (http://sencha.com) │ \\ // ├────────────────────────────────────────────────────────────────────┤ \\ // │ Licensed under the MIT (http://raphaeljs.com/license.html) license.│ \\ // └────────────────────────────────────────────────────────────────────┘ \\ // Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved. // // 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. // ┌────────────────────────────────────────────────────────────┐ \\ // │ Eve 0.4.2 - JavaScript Events Library │ \\ // ├────────────────────────────────────────────────────────────┤ \\ // │ Author Dmitry Baranovskiy (http://dmitry.baranovskiy.com/) │ \\ // └────────────────────────────────────────────────────────────┘ \\ (function (glob) { var version = "0.4.2", has = "hasOwnProperty", separator = /[\.\/]/, wildcard = "*", fun = function () {}, numsort = function (a, b) { return a - b; }, current_event, stop, events = {n: {}}, /*\ * eve [ method ] * Fires event with given `name`, given scope and other parameters. > Arguments - name (string) name of the *event*, dot (`.`) or slash (`/`) separated - scope (object) context for the event handlers - varargs (...) the rest of arguments will be sent to event handlers = (object) array of returned values from the listeners \*/ eve = function (name, scope) { name = String(name); var e = events, oldstop = stop, args = Array.prototype.slice.call(arguments, 2), listeners = eve.listeners(name), z = 0, f = false, l, indexed = [], queue = {}, out = [], ce = current_event, errors = []; current_event = name; stop = 0; for (var i = 0, ii = listeners.length; i < ii; i++) if ("zIndex" in listeners[i]) { indexed.push(listeners[i].zIndex); if (listeners[i].zIndex < 0) { queue[listeners[i].zIndex] = listeners[i]; } } indexed.sort(numsort); while (indexed[z] < 0) { l = queue[indexed[z++]]; out.push(l.apply(scope, args)); if (stop) { stop = oldstop; return out; } } for (i = 0; i < ii; i++) { l = listeners[i]; if ("zIndex" in l) { if (l.zIndex == indexed[z]) { out.push(l.apply(scope, args)); if (stop) { break; } do { z++; l = queue[indexed[z]]; l && out.push(l.apply(scope, args)); if (stop) { break; } } while (l) } else { queue[l.zIndex] = l; } } else { out.push(l.apply(scope, args)); if (stop) { break; } } } stop = oldstop; current_event = ce; return out.length ? out : null; }; // Undocumented. Debug only. eve._events = events; /*\ * eve.listeners [ method ] * Internal method which gives you array of all event handlers that will be triggered by the given `name`. > Arguments - name (string) name of the event, dot (`.`) or slash (`/`) separated = (array) array of event handlers \*/ eve.listeners = function (name) { var names = name.split(separator), e = events, item, items, k, i, ii, j, jj, nes, es = [e], out = []; for (i = 0, ii = names.length; i < ii; i++) { nes = []; for (j = 0, jj = es.length; j < jj; j++) { e = es[j].n; items = [e[names[i]], e[wildcard]]; k = 2; while (k--) { item = items[k]; if (item) { nes.push(item); out = out.concat(item.f || []); } } } es = nes; } return out; }; /*\ * eve.on [ method ] ** * Binds given event handler with a given name. You can use wildcards “`*`” for the names: | eve.on("*.under.*", f); | eve("mouse.under.floor"); // triggers f * Use @eve to trigger the listener. ** > Arguments ** - name (string) name of the event, dot (`.`) or slash (`/`) separated, with optional wildcards - f (function) event handler function ** = (function) returned function accepts a single numeric parameter that represents z-index of the handler. It is an optional feature and only used when you need to ensure that some subset of handlers will be invoked in a given order, despite of the order of assignment. > Example: | eve.on("mouse", eatIt)(2); | eve.on("mouse", scream); | eve.on("mouse", catchIt)(1); * This will ensure that `catchIt()` function will be called before `eatIt()`. * * If you want to put your handler before non-indexed handlers, specify a negative value. * Note: I assume most of the time you don’t need to worry about z-index, but it’s nice to have this feature “just in case”. \*/ eve.on = function (name, f) { name = String(name); if (typeof f != "function") { return function () {}; } var names = name.split(separator), e = events; for (var i = 0, ii = names.length; i < ii; i++) { e = e.n; e = e.hasOwnProperty(names[i]) && e[names[i]] || (e[names[i]] = {n: {}}); } e.f = e.f || []; for (i = 0, ii = e.f.length; i < ii; i++) if (e.f[i] == f) { return fun; } e.f.push(f); return function (zIndex) { if (+zIndex == +zIndex) { f.zIndex = +zIndex; } }; }; /*\ * eve.f [ method ] ** * Returns function that will fire given event with optional arguments. * Arguments that will be passed to the result function will be also * concated to the list of final arguments. | el.onclick = eve.f("click", 1, 2); | eve.on("click", function (a, b, c) { | console.log(a, b, c); // 1, 2, [event object] | }); > Arguments - event (string) event name - varargs (…) and any other arguments = (function) possible event handler function \*/ eve.f = function (event) { var attrs = [].slice.call(arguments, 1); return function () { eve.apply(null, [event, null].concat(attrs).concat([].slice.call(arguments, 0))); }; }; /*\ * eve.stop [ method ] ** * Is used inside an event handler to stop the event, preventing any subsequent listeners from firing. \*/ eve.stop = function () { stop = 1; }; /*\ * eve.nt [ method ] ** * Could be used inside event handler to figure out actual name of the event. ** > Arguments ** - subname (string) #optional subname of the event ** = (string) name of the event, if `subname` is not specified * or = (boolean) `true`, if current event’s name contains `subname` \*/ eve.nt = function (subname) { if (subname) { return new RegExp("(?:\\.|\\/|^)" + subname + "(?:\\.|\\/|$)").test(current_event); } return current_event; }; /*\ * eve.nts [ method ] ** * Could be used inside event handler to figure out actual name of the event. ** ** = (array) names of the event \*/ eve.nts = function () { return current_event.split(separator); }; /*\ * eve.off [ method ] ** * Removes given function from the list of event listeners assigned to given name. * If no arguments specified all the events will be cleared. ** > Arguments ** - name (string) name of the event, dot (`.`) or slash (`/`) separated, with optional wildcards - f (function) event handler function \*/ /*\ * eve.unbind [ method ] ** * See @eve.off \*/ eve.off = eve.unbind = function (name, f) { if (!name) { eve._events = events = {n: {}}; return; } var names = name.split(separator), e, key, splice, i, ii, j, jj, cur = [events]; for (i = 0, ii = names.length; i < ii; i++) { for (j = 0; j < cur.length; j += splice.length - 2) { splice = [j, 1]; e = cur[j].n; if (names[i] != wildcard) { if (e[names[i]]) { splice.push(e[names[i]]); } } else { for (key in e) if (e[has](key)) { splice.push(e[key]); } } cur.splice.apply(cur, splice); } } for (i = 0, ii = cur.length; i < ii; i++) { e = cur[i]; while (e.n) { if (f) { if (e.f) { for (j = 0, jj = e.f.length; j < jj; j++) if (e.f[j] == f) { e.f.splice(j, 1); break; } !e.f.length && delete e.f; } for (key in e.n) if (e.n[has](key) && e.n[key].f) { var funcs = e.n[key].f; for (j = 0, jj = funcs.length; j < jj; j++) if (funcs[j] == f) { funcs.splice(j, 1); break; } !funcs.length && delete e.n[key].f; } } else { delete e.f; for (key in e.n) if (e.n[has](key) && e.n[key].f) { delete e.n[key].f; } } e = e.n; } } }; /*\ * eve.once [ method ] ** * Binds given event handler with a given name to only run once then unbind itself. | eve.once("login", f); | eve("login"); // triggers f | eve("login"); // no listeners * Use @eve to trigger the listener. ** > Arguments ** - name (string) name of the event, dot (`.`) or slash (`/`) separated, with optional wildcards - f (function) event handler function ** = (function) same return function as @eve.on \*/ eve.once = function (name, f) { var f2 = function () { eve.unbind(name, f2); return f.apply(this, arguments); }; return eve.on(name, f2); }; /*\ * eve.version [ property (string) ] ** * Current version of the library. \*/ eve.version = version; eve.toString = function () { return "You are running Eve " + version; }; (typeof module != "undefined" && module.exports) ? (module.exports = eve) : (typeof define != "undefined" ? (define("eve", [], function() { return eve; })) : (glob.eve = eve)); })(window || this); // ┌─────────────────────────────────────────────────────────────────────┐ \\ // │ "Raphaël 2.1.2" - JavaScript Vector Library │ \\ // ├─────────────────────────────────────────────────────────────────────┤ \\ // │ Copyright (c) 2008-2011 Dmitry Baranovskiy (http://raphaeljs.com) │ \\ // │ Copyright (c) 2008-2011 Sencha Labs (http://sencha.com) │ \\ // │ Licensed under the MIT (http://raphaeljs.com/license.html) license. │ \\ // └─────────────────────────────────────────────────────────────────────┘ \\ (function (glob, factory) { // AMD support if (typeof define === "function" && define.amd) { // Define as an anonymous module define(["eve"], function( eve ) { return factory(glob, eve); }); } else { // Browser globals (glob is window) // Raphael adds itself to window factory(glob, glob.eve); } }(this, function (window, eve) { /*\ * Raphael [ method ] ** * Creates a canvas object on which to draw. * You must do this first, as all future calls to drawing methods * from this instance will be bound to this canvas. > Parameters ** - container (HTMLElement|string) DOM element or its ID which is going to be a parent for drawing surface - width (number) - height (number) - callback (function) #optional callback function which is going to be executed in the context of newly created paper * or - x (number) - y (number) - width (number) - height (number) - callback (function) #optional callback function which is going to be executed in the context of newly created paper * or - all (array) (first 3 or 4 elements in the array are equal to [containerID, width, height] or [x, y, width, height]. The rest are element descriptions in format {type: type, <attributes>}). See @Paper.add. - callback (function) #optional callback function which is going to be executed in the context of newly created paper * or - onReadyCallback (function) function that is going to be called on DOM ready event. You can also subscribe to this event via Eve’s “DOMLoad” event. In this case method returns `undefined`. = (object) @Paper > Usage | // Each of the following examples create a canvas | // that is 320px wide by 200px high. | // Canvas is created at the viewport’s 10,50 coordinate. | var paper = Raphael(10, 50, 320, 200); | // Canvas is created at the top left corner of the #notepad element | // (or its top right corner in dir="rtl" elements) | var paper = Raphael(document.getElementById("notepad"), 320, 200); | // Same as above | var paper = Raphael("notepad", 320, 200); | // Image dump | var set = Raphael(["notepad", 320, 200, { | type: "rect", | x: 10, | y: 10, | width: 25, | height: 25, | stroke: "#f00" | }, { | type: "text", | x: 30, | y: 40, | text: "Dump" | }]); \*/ function R(first) { if (R.is(first, "function")) { return loaded ? first() : eve.on("raphael.DOMload", first); } else if (R.is(first, array)) { return R._engine.create[apply](R, first.splice(0, 3 + R.is(first[0], nu))).add(first); } else { var args = Array.prototype.slice.call(arguments, 0); if (R.is(args[args.length - 1], "function")) { var f = args.pop(); return loaded ? f.call(R._engine.create[apply](R, args)) : eve.on("raphael.DOMload", function () { f.call(R._engine.create[apply](R, args)); }); } else { return R._engine.create[apply](R, arguments); } } } R.version = "2.1.2"; R.eve = eve; var loaded, separator = /[, ]+/, elements = {circle: 1, rect: 1, path: 1, ellipse: 1, text: 1, image: 1}, formatrg = /\{(\d+)\}/g, proto = "prototype", has = "hasOwnProperty", g = { doc: document, win: window }, oldRaphael = { was: Object.prototype[has].call(g.win, "Raphael"), is: g.win.Raphael }, Paper = function () { /*\ * Paper.ca [ property (object) ] ** * Shortcut for @Paper.customAttributes \*/ /*\ * Paper.customAttributes [ property (object) ] ** * If you have a set of attributes that you would like to represent * as a function of some number you can do it easily with custom attributes: > Usage | paper.customAttributes.hue = function (num) { | num = num % 1; | return {fill: "hsb(" + num + ", 0.75, 1)"}; | }; | // Custom attribute “hue” will change fill | // to be given hue with fixed saturation and brightness. | // Now you can use it like this: | var c = paper.circle(10, 10, 10).attr({hue: .45}); | // or even like this: | c.animate({hue: 1}, 1e3); | | // You could also create custom attribute | // with multiple parameters: | paper.customAttributes.hsb = function (h, s, b) { | return {fill: "hsb(" + [h, s, b].join(",") + ")"}; | }; | c.attr({hsb: "0.5 .8 1"}); | c.animate({hsb: [1, 0, 0.5]}, 1e3); \*/ this.ca = this.customAttributes = {}; }, paperproto, appendChild = "appendChild", apply = "apply", concat = "concat", supportsTouch = ('ontouchstart' in g.win) || g.win.DocumentTouch && g.doc instanceof DocumentTouch, //taken from Modernizr touch test E = "", S = " ", Str = String, split = "split", events = "click dblclick mousedown mousemove mouseout mouseover mouseup touchstart touchmove touchend touchcancel"[split](S), touchMap = { mousedown: "touchstart", mousemove: "touchmove", mouseup: "touchend" }, lowerCase = Str.prototype.toLowerCase, math = Math, mmax = math.max, mmin = math.min, abs = math.abs, pow = math.pow, PI = math.PI, nu = "number", string = "string", array = "array", toString = "toString", fillString = "fill", objectToString = Object.prototype.toString, paper = {}, push = "push", ISURL = R._ISURL = /^url\(['"]?([^\)]+?)['"]?\)$/i, colourRegExp = /^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+%?(?:\s*,\s*[\d\.]+%?)?)\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\))\s*$/i, isnan = {"NaN": 1, "Infinity": 1, "-Infinity": 1}, bezierrg = /^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/, round = math.round, setAttribute = "setAttribute", toFloat = parseFloat, toInt = parseInt, upperCase = Str.prototype.toUpperCase, availableAttrs = R._availableAttrs = { "arrow-end": "none", "arrow-start": "none", blur: 0, "clip-rect": "0 0 1e9 1e9", cursor: "default", cx: 0, cy: 0, fill: "#fff", "fill-opacity": 1, font: '10px "Arial"', "font-family": '"Arial"', "font-size": "10", "font-style": "normal", "font-weight": 400, gradient: 0, height: 0, href: "http://raphaeljs.com/", "letter-spacing": 0, opacity: 1, path: "M0,0", r: 0, rx: 0, ry: 0, src: "", stroke: "#000", "stroke-dasharray": "", "stroke-linecap": "butt", "stroke-linejoin": "butt", "stroke-miterlimit": 0, "stroke-opacity": 1, "stroke-width": 1, target: "_blank", "text-anchor": "middle", title: "Raphael", transform: "", width: 0, x: 0, y: 0 }, availableAnimAttrs = R._availableAnimAttrs = { blur: nu, "clip-rect": "csv", cx: nu, cy: nu, fill: "colour", "fill-opacity": nu, "font-size": nu, height: nu, opacity: nu, path: "path", r: nu, rx: nu, ry: nu, stroke: "colour", "stroke-opacity": nu, "stroke-width": nu, transform: "transform", width: nu, x: nu, y: nu }, whitespace = /[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]/g, commaSpaces = /[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*/, hsrg = {hs: 1, rg: 1}, p2s = /,?([achlmqrstvxz]),?/gi, pathCommand = /([achlmrqstvz])[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*)+)/ig, tCommand = /([rstm])[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*)+)/ig, pathValues = /(-?\d*\.?\d*(?:e[\-+]?\d+)?)[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*/ig, radial_gradient = R._radial_gradient = /^r(?:\(([^,]+?)[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*([^\)]+?)\))?/, eldata = {}, sortByKey = function (a, b) { return a.key - b.key; }, sortByNumber = function (a, b) { return toFloat(a) - toFloat(b); }, fun = function () {}, pipe = function (x) { return x; }, rectPath = R._rectPath = function (x, y, w, h, r) { if (r) { return [["M", x + r, y], ["l", w - r * 2, 0], ["a", r, r, 0, 0, 1, r, r], ["l", 0, h - r * 2], ["a", r, r, 0, 0, 1, -r, r], ["l", r * 2 - w, 0], ["a", r, r, 0, 0, 1, -r, -r], ["l", 0, r * 2 - h], ["a", r, r, 0, 0, 1, r, -r], ["z"]]; } return [["M", x, y], ["l", w, 0], ["l", 0, h], ["l", -w, 0], ["z"]]; }, ellipsePath = function (x, y, rx, ry) { if (ry == null) { ry = rx; } return [["M", x, y], ["m", 0, -ry], ["a", rx, ry, 0, 1, 1, 0, 2 * ry], ["a", rx, ry, 0, 1, 1, 0, -2 * ry], ["z"]]; }, getPath = R._getPath = { path: function (el) { return el.attr("path"); }, circle: function (el) { var a = el.attrs; return ellipsePath(a.cx, a.cy, a.r); }, ellipse: function (el) { var a = el.attrs; return ellipsePath(a.cx, a.cy, a.rx, a.ry); }, rect: function (el) { var a = el.attrs; return rectPath(a.x, a.y, a.width, a.height, a.r); }, image: function (el) { var a = el.attrs; return rectPath(a.x, a.y, a.width, a.height); }, text: function (el) { var bbox = el._getBBox(); return rectPath(bbox.x, bbox.y, bbox.width, bbox.height); }, set : function(el) { var bbox = el._getBBox(); return rectPath(bbox.x, bbox.y, bbox.width, bbox.height); } }, /*\ * Raphael.mapPath [ method ] ** * Transform the path string with given matrix. > Parameters - path (string) path string - matrix (object) see @Matrix = (string) transformed path string \*/ mapPath = R.mapPath = function (path, matrix) { if (!matrix) { return path; } var x, y, i, j, ii, jj, pathi; path = path2curve(path); for (i = 0, ii = path.length; i < ii; i++) { pathi = path[i]; for (j = 1, jj = pathi.length; j < jj; j += 2) { x = matrix.x(pathi[j], pathi[j + 1]); y = matrix.y(pathi[j], pathi[j + 1]); pathi[j] = x; pathi[j + 1] = y; } } return path; }; R._g = g; /*\ * Raphael.type [ property (string) ] ** * Can be “SVG”, “VML” or empty, depending on browser support. \*/ R.type = (g.win.SVGAngle || g.doc.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") ? "SVG" : "VML"); if (R.type == "VML") { var d = g.doc.createElement("div"), b; d.innerHTML = '<v:shape adj="1"/>'; b = d.firstChild; b.style.behavior = "url(#default#VML)"; if (!(b && typeof b.adj == "object")) { return (R.type = E); } d = null; } /*\ * Raphael.svg [ property (boolean) ] ** * `true` if browser supports SVG. \*/ /*\ * Raphael.vml [ property (boolean) ] ** * `true` if browser supports VML. \*/ R.svg = !(R.vml = R.type == "VML"); R._Paper = Paper; /*\ * Raphael.fn [ property (object) ] ** * You can add your own method to the canvas. For example if you want to draw a pie chart, * you can create your own pie chart function and ship it as a Raphaël plugin. To do this * you need to extend the `Raphael.fn` object. You should modify the `fn` object before a * Raphaël instance is created, otherwise it will take no effect. Please note that the * ability for namespaced plugins was removed in Raphael 2.0. It is up to the plugin to * ensure any namespacing ensures proper context. > Usage | Raphael.fn.arrow = function (x1, y1, x2, y2, size) { | return this.path( ... ); | }; | // or create namespace | Raphael.fn.mystuff = { | arrow: function () {…}, | star: function () {…}, | // etc… | }; | var paper = Raphael(10, 10, 630, 480); | // then use it | paper.arrow(10, 10, 30, 30, 5).attr({fill: "#f00"}); | paper.mystuff.arrow(); | paper.mystuff.star(); \*/ R.fn = paperproto = Paper.prototype = R.prototype; R._id = 0; R._oid = 0; /*\ * Raphael.is [ method ] ** * Handfull replacement for `typeof` operator. > Parameters - o (…) any object or primitive - type (string) name of the type, i.e. “string”, “function”, “number”, etc. = (boolean) is given value is of given type \*/ R.is = function (o, type) { type = lowerCase.call(type); if (type == "finite") { return !isnan[has](+o); } if (type == "array") { return o instanceof Array; } return (type == "null" && o === null) || (type == typeof o && o !== null) || (type == "object" && o === Object(o)) || (type == "array" && Array.isArray && Array.isArray(o)) || objectToString.call(o).slice(8, -1).toLowerCase() == type; }; function clone(obj) { if (typeof obj == "function" || Object(obj) !== obj) { return obj; } var res = new obj.constructor; for (var key in obj) if (obj[has](key)) { res[key] = clone(obj[key]); } return res; } /*\ * Raphael.angle [ method ] ** * Returns angle between two or three points > Parameters - x1 (number) x coord of first point - y1 (number) y coord of first point - x2 (number) x coord of second point - y2 (number) y coord of second point - x3 (number) #optional x coord of third point - y3 (number) #optional y coord of third point = (number) angle in degrees. \*/ R.angle = function (x1, y1, x2, y2, x3, y3) { if (x3 == null) { var x = x1 - x2, y = y1 - y2; if (!x && !y) { return 0; } return (180 + math.atan2(-y, -x) * 180 / PI + 360) % 360; } else { return R.angle(x1, y1, x3, y3) - R.angle(x2, y2, x3, y3); } }; /*\ * Raphael.rad [ method ] ** * Transform angle to radians > Parameters - deg (number) angle in degrees = (number) angle in radians. \*/ R.rad = function (deg) { return deg % 360 * PI / 180; }; /*\ * Raphael.deg [ method ] ** * Transform angle to degrees > Parameters - deg (number) angle in radians = (number) angle in degrees. \*/ R.deg = function (rad) { return rad * 180 / PI % 360; }; /*\ * Raphael.snapTo [ method ] ** * Snaps given value to given grid. > Parameters - values (array|number) given array of values or step of the grid - value (number) value to adjust - tolerance (number) #optional tolerance for snapping. Default is `10`. = (number) adjusted value. \*/ R.snapTo = function (values, value, tolerance) { tolerance = R.is(tolerance, "finite") ? tolerance : 10; if (R.is(values, array)) { var i = values.length; while (i--) if (abs(values[i] - value) <= tolerance) { return values[i]; } } else { values = +values; var rem = value % values; if (rem < tolerance) { return value - rem; } if (rem > values - tolerance) { return value - rem + values; } } return value; }; /*\ * Raphael.createUUID [ method ] ** * Returns RFC4122, version 4 ID \*/ var createUUID = R.createUUID = (function (uuidRegEx, uuidReplacer) { return function () { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(uuidRegEx, uuidReplacer).toUpperCase(); }; })(/[xy]/g, function (c) { var r = math.random() * 16 | 0, v = c == "x" ? r : (r & 3 | 8); return v.toString(16); }); /*\ * Raphael.setWindow [ method ] ** * Used when you need to draw in `&lt;iframe>`. Switched window to the iframe one. > Parameters - newwin (window) new window object \*/ R.setWindow = function (newwin) { eve("raphael.setWindow", R, g.win, newwin); g.win = newwin; g.doc = g.win.document; if (R._engine.initWin) { R._engine.initWin(g.win); } }; var toHex = function (color) { if (R.vml) { // http://dean.edwards.name/weblog/2009/10/convert-any-colour-value-to-hex-in-msie/ var trim = /^\s+|\s+$/g; var bod; try { var docum = new ActiveXObject("htmlfile"); docum.write("<body>"); docum.close(); bod = docum.body; } catch(e) { bod = createPopup().document.body; } var range = bod.createTextRange(); toHex = cacher(function (color) { try { bod.style.color = Str(color).replace(trim, E); var value = range.queryCommandValue("ForeColor"); value = ((value & 255) << 16) | (value & 65280) | ((value & 16711680) >>> 16); return "#" + ("000000" + value.toString(16)).slice(-6); } catch(e) { return "none"; } }); } else { var i = g.doc.createElement("i"); i.title = "Rapha\xebl Colour Picker"; i.style.display = "none"; g.doc.body.appendChild(i); toHex = cacher(function (color) { i.style.color = color; return g.doc.defaultView.getComputedStyle(i, E).getPropertyValue("color"); }); } return toHex(color); }, hsbtoString = function () { return "hsb(" + [this.h, this.s, this.b] + ")"; }, hsltoString = function () { return "hsl(" + [this.h, this.s, this.l] + ")"; }, rgbtoString = function () { return this.hex; }, prepareRGB = function (r, g, b) { if (g == null && R.is(r, "object") && "r" in r && "g" in r && "b" in r) { b = r.b; g = r.g; r = r.r; } if (g == null && R.is(r, string)) { var clr = R.getRGB(r); r = clr.r; g = clr.g; b = clr.b; } if (r > 1 || g > 1 || b > 1) { r /= 255; g /= 255; b /= 255; } return [r, g, b]; }, packageRGB = function (r, g, b, o) { r *= 255; g *= 255; b *= 255; var rgb = { r: r, g: g, b: b, hex: R.rgb(r, g, b), toString: rgbtoString }; R.is(o, "finite") && (rgb.opacity = o); return rgb; }; /*\ * Raphael.color [ method ] ** * Parses the color string and returns object with all values for the given color. > Parameters - clr (string) color string in one of the supported formats (see @Raphael.getRGB) = (object) Combined RGB & HSB object in format: o { o r (number) red, o g (number) green, o b (number) blue, o hex (string) color in HTML/CSS format: #••••••, o error (boolean) `true` if string can’t be parsed, o h (number) hue, o s (number) saturation, o v (number) value (brightness), o l (number) lightness o } \*/ R.color = function (clr) { var rgb; if (R.is(clr, "object") && "h" in clr && "s" in clr && "b" in clr) { rgb = R.hsb2rgb(clr); clr.r = rgb.r; clr.g = rgb.g; clr.b = rgb.b; clr.hex = rgb.hex; } else if (R.is(clr, "object") && "h" in clr && "s" in clr && "l" in clr) { rgb = R.hsl2rgb(clr); clr.r = rgb.r; clr.g = rgb.g; clr.b = rgb.b; clr.hex = rgb.hex; } else { if (R.is(clr, "string")) { clr = R.getRGB(clr); } if (R.is(clr, "object") && "r" in clr && "g" in clr && "b" in clr) { rgb = R.rgb2hsl(clr); clr.h = rgb.h; clr.s = rgb.s; clr.l = rgb.l; rgb = R.rgb2hsb(clr); clr.v = rgb.b; } else { clr = {hex: "none"}; clr.r = clr.g = clr.b = clr.h = clr.s = clr.v = clr.l = -1; } } clr.toString = rgbtoString; return clr; }; /*\ * Raphael.hsb2rgb [ method ] ** * Converts HSB values to RGB object. > Parameters - h (number) hue - s (number) saturation - v (number) value or brightness = (object) RGB object in format: o { o r (number) red, o g (number) green, o b (number) blue, o hex (string) color in HTML/CSS format: #•••••• o } \*/ R.hsb2rgb = function (h, s, v, o) { if (this.is(h, "object") && "h" in h && "s" in h && "b" in h) { v = h.b; s = h.s; h = h.h; o = h.o; } h *= 360; var R, G, B, X, C; h = (h % 360) / 60; C = v * s; X = C * (1 - abs(h % 2 - 1)); R = G = B = v - C; h = ~~h; R += [C, X, 0, 0, X, C][h]; G += [X, C, C, X, 0, 0][h]; B += [0, 0, X, C, C, X][h]; return packageRGB(R, G, B, o); }; /*\ * Raphael.hsl2rgb [ method ] ** * Converts HSL values to RGB object. > Parameters - h (number) hue - s (number) saturation - l (number) luminosity = (object) RGB object in format: o { o r (number) red, o g (number) green, o b (number) blue, o hex (string) color in HTML/CSS format: #•••••• o } \*/ R.hsl2rgb = function (h, s, l, o) { if (this.is(h, "object") && "h" in h && "s" in h && "l" in h) { l = h.l; s = h.s; h = h.h; } if (h > 1 || s > 1 || l > 1) { h /= 360; s /= 100; l /= 100; } h *= 360; var R, G, B, X, C; h = (h % 360) / 60; C = 2 * s * (l < .5 ? l : 1 - l); X = C * (1 - abs(h % 2 - 1)); R = G = B = l - C / 2; h = ~~h; R += [C, X, 0, 0, X, C][h]; G += [X, C, C, X, 0, 0][h]; B += [0, 0, X, C, C, X][h]; return packageRGB(R, G, B, o); }; /*\ * Raphael.rgb2hsb [ method ] ** * Converts RGB values to HSB object. > Parameters - r (number) red - g (number) green - b (number) blue = (object) HSB object in format: o { o h (number) hue o s (number) saturation o b (number) brightness o } \*/ R.rgb2hsb = function (r, g, b) { b = prepareRGB(r, g, b); r = b[0]; g = b[1]; b = b[2]; var H, S, V, C; V = mmax(r, g, b); C = V - mmin(r, g, b); H = (C == 0 ? null : V == r ? (g - b) / C : V == g ? (b - r) / C + 2 : (r - g) / C + 4 ); H = ((H + 360) % 6) * 60 / 360; S = C == 0 ? 0 : C / V; return {h: H, s: S, b: V, toString: hsbtoString}; }; /*\ * Raphael.rgb2hsl [ method ] ** * Converts RGB values to HSL object. > Parameters - r (number) red - g (number) green - b (number) blue = (object) HSL object in format: o { o h (number) hue o s (number) saturation o l (number) luminosity o } \*/ R.rgb2hsl = function (r, g, b) { b = prepareRGB(r, g, b); r = b[0]; g = b[1]; b = b[2]; var H, S, L, M, m, C; M = mmax(r, g, b); m = mmin(r, g, b); C = M - m; H = (C == 0 ? null : M == r ? (g - b) / C : M == g ? (b - r) / C + 2 : (r - g) / C + 4); H = ((H + 360) % 6) * 60 / 360; L = (M + m) / 2; S = (C == 0 ? 0 : L < .5 ? C / (2 * L) : C / (2 - 2 * L)); return {h: H, s: S, l: L, toString: hsltoString}; }; R._path2string = function () { return this.join(",").replace(p2s, "$1"); }; function repush(array, item) { for (var i = 0, ii = array.length; i < ii; i++) if (array[i] === item) { return array.push(array.splice(i, 1)[0]); } } function cacher(f, scope, postprocessor) { function newf() { var arg = Array.prototype.slice.call(arguments, 0), args = arg.join("\u2400"), cache = newf.cache = newf.cache || {}, count = newf.count = newf.count || []; if (cache[has](args)) { repush(count, args); return postprocessor ? postprocessor(cache[args]) : cache[args]; } count.length >= 1e3 && delete cache[count.shift()]; count.push(args); cache[args] = f[apply](scope, arg); return postprocessor ? postprocessor(cache[args]) : cache[args]; } return newf; } var preload = R._preload = function (src, f) { var img = g.doc.createElement("img"); img.style.cssText = "position:absolute;left:-9999em;top:-9999em"; img.onload = function () { f.call(this); this.onload = null; g.doc.body.removeChild(this); }; img.onerror = function () { g.doc.body.removeChild(this); }; g.doc.body.appendChild(img); img.src = src; }; function clrToString() { return this.hex; } /*\ * Raphael.getRGB [ method ] ** * Parses colour string as RGB object > Parameters - colour (string) colour string in one of formats: # <ul> # <li>Colour name (“<code>red</code>”, “<code>green</code>”, “<code>cornflowerblue</code>”, etc)</li> # <li>#••• — shortened HTML colour: (“<code>#000</code>”, “<code>#fc0</code>”, etc)</li> # <li>#•••••• — full length HTML colour: (“<code>#000000</code>”, “<code>#bd2300</code>”)</li> # <li>rgb(•••, •••, •••) — red, green and blue channels’ values: (“<code>rgb(200,&nbsp;100,&nbsp;0)</code>”)</li> # <li>rgb(•••%, •••%, •••%) — same as above, but in %: (“<code>rgb(100%,&nbsp;175%,&nbsp;0%)</code>”)</li> # <li>hsb(•••, •••, •••) — hue, saturation and brightness values: (“<code>hsb(0.5,&nbsp;0.25,&nbsp;1)</code>”)</li> # <li>hsb(•••%, •••%, •••%) — same as above, but in %</li> # <li>hsl(•••, •••, •••) — same as hsb</li> # <li>hsl(•••%, •••%, •••%) — same as hsb</li> # </ul> = (object) RGB object in format: o { o r (number) red, o g (number) green, o b (number) blue o hex (string) color in HTML/CSS format: #••••••, o error (boolean) true if string can’t be parsed o } \*/ R.getRGB = cacher(function (colour) { if (!colour || !!((colour = Str(colour)).indexOf("-") + 1)) { return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: clrToString}; } if (colour == "none") { return {r: -1, g: -1, b: -1, hex: "none", toString: clrToString}; } !(hsrg[has](colour.toLowerCase().substring(0, 2)) || colour.charAt() == "#") && (colour = toHex(colour)); var res, red, green, blue, opacity, t, values, rgb = colour.match(colourRegExp); if (rgb) { if (rgb[2]) { blue = toInt(rgb[2].substring(5), 16); green = toInt(rgb[2].substring(3, 5), 16); red = toInt(rgb[2].substring(1, 3), 16); } if (rgb[3]) { blue = toInt((t = rgb[3].charAt(3)) + t, 16); green = toInt((t = rgb[3].charAt(2)) + t, 16); red = toInt((t = rgb[3].charAt(1)) + t, 16); } if (rgb[4]) { values = rgb[4][split](commaSpaces); red = toFloat(values[0]); values[0].slice(-1) == "%" && (red *= 2.55); green = toFloat(values[1]); values[1].slice(-1) == "%" && (green *= 2.55); blue = toFloat(values[2]); values[2].slice(-1) == "%" && (blue *= 2.55); rgb[1].toLowerCase().slice(0, 4) == "rgba" && (opacity = toFloat(values[3])); values[3] && values[3].slice(-1) == "%" && (opacity /= 100); } if (rgb[5]) { values = rgb[5][split](commaSpaces); red = toFloat(values[0]); values[0].slice(-1) == "%" && (red *= 2.55); green = toFloat(values[1]); values[1].slice(-1) == "%" && (green *= 2.55); blue = toFloat(values[2]); values[2].slice(-1) == "%" && (blue *= 2.55); (values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360); rgb[1].toLowerCase().slice(0, 4) == "hsba" && (opacity = toFloat(values[3])); values[3] && values[3].slice(-1) == "%" && (opacity /= 100); return R.hsb2rgb(red, green, blue, opacity); } if (rgb[6]) { values = rgb[6][split](commaSpaces); red = toFloat(values[0]); values[0].slice(-1) == "%" && (red *= 2.55); green = toFloat(values[1]); values[1].slice(-1) == "%" && (green *= 2.55); blue = toFloat(values[2]); values[2].slice(-1) == "%" && (blue *= 2.55); (values[0].slice(-3) == "deg" || values[0].slice(-1) == "\xb0") && (red /= 360); rgb[1].toLowerCase().slice(0, 4) == "hsla" && (opacity = toFloat(values[3])); values[3] && values[3].slice(-1) == "%" && (opacity /= 100); return R.hsl2rgb(red, green, blue, opacity); } rgb = {r: red, g: green, b: blue, toString: clrToString}; rgb.hex = "#" + (16777216 | blue | (green << 8) | (red << 16)).toString(16).slice(1); R.is(opacity, "finite") && (rgb.opacity = opacity); return rgb; } return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: clrToString}; }, R); /*\ * Raphael.hsb [ method ] ** * Converts HSB values to hex representation of the colour. > Parameters - h (number) hue - s (number) saturation - b (number) value or brightness = (string) hex representation of the colour. \*/ R.hsb = cacher(function (h, s, b) { return R.hsb2rgb(h, s, b).hex; }); /*\ * Raphael.hsl [ method ] ** * Converts HSL values to hex representation of the colour. > Parameters - h (number) hue - s (number) saturation - l (number) luminosity = (string) hex representation of the colour. \*/ R.hsl = cacher(function (h, s, l) { return R.hsl2rgb(h, s, l).hex; }); /*\ * Raphael.rgb [ method ] ** * Converts RGB values to hex representation of the colour. > Parameters - r (number) red - g (number) green - b (number) blue = (string) hex representation of the colour. \*/ R.rgb = cacher(function (r, g, b) { return "#" + (16777216 | b | (g << 8) | (r << 16)).toString(16).slice(1); }); /*\ * Raphael.getColor [ method ] ** * On each call returns next colour in the spectrum. To reset it back to red call @Raphael.getColor.reset > Parameters - value (number) #optional brightness, default is `0.75` = (string) hex representation of the colour. \*/ R.getColor = function (value) { var start = this.getColor.start = this.getColor.start || {h: 0, s: 1, b: value || .75}, rgb = this.hsb2rgb(start.h, start.s, start.b); start.h += .075; if (start.h > 1) { start.h = 0; start.s -= .2; start.s <= 0 && (this.getColor.start = {h: 0, s: 1, b: start.b}); } return rgb.hex; }; /*\ * Raphael.getColor.reset [ method ] ** * Resets spectrum position for @Raphael.getColor back to red. \*/ R.getColor.reset = function () { delete this.start; }; // http://schepers.cc/getting-to-the-point function catmullRom2bezier(crp, z) { var d = []; for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) { var p = [ {x: +crp[i - 2], y: +crp[i - 1]}, {x: +crp[i], y: +crp[i + 1]}, {x: +crp[i + 2], y: +crp[i + 3]}, {x: +crp[i + 4], y: +crp[i + 5]} ]; if (z) { if (!i) { p[0] = {x: +crp[iLen - 2], y: +crp[iLen - 1]}; } else if (iLen - 4 == i) { p[3] = {x: +crp[0], y: +crp[1]}; } else if (iLen - 2 == i) { p[2] = {x: +crp[0], y: +crp[1]}; p[3] = {x: +crp[2], y: +crp[3]}; } } else { if (iLen - 4 == i) { p[3] = p[2]; } else if (!i) { p[0] = {x: +crp[i], y: +crp[i + 1]}; } } d.push(["C", (-p[0].x + 6 * p[1].x + p[2].x) / 6, (-p[0].y + 6 * p[1].y + p[2].y) / 6, (p[1].x + 6 * p[2].x - p[3].x) / 6, (p[1].y + 6*p[2].y - p[3].y) / 6, p[2].x, p[2].y ]); } return d; } /*\ * Raphael.parsePathString [ method ] ** * Utility method ** * Parses given path string into an array of arrays of path segments. > Parameters - pathString (string|array) path string or array of segments (in the last case it will be returned straight away) = (array) array of segments. \*/ R.parsePathString = function (pathString) { if (!pathString) { return null; } var pth = paths(pathString); if (pth.arr) { return pathClone(pth.arr); } var paramCounts = {a: 7, c: 6, h: 1, l: 2, m: 2, r: 4, q: 4, s: 4, t: 2, v: 1, z: 0}, data = []; if (R.is(pathString, array) && R.is(pathString[0], array)) { // rough assumption data = pathClone(pathString); } if (!data.length) { Str(pathString).replace(pathCommand, function (a, b, c) { var params = [], name = b.toLowerCase(); c.replace(pathValues, function (a, b) { b && params.push(+b); }); if (name == "m" && params.length > 2) { data.push([b][concat](params.splice(0, 2))); name = "l"; b = b == "m" ? "l" : "L"; } if (name == "r") { data.push([b][concat](params)); } else while (params.length >= paramCounts[name]) { data.push([b][concat](params.splice(0, paramCounts[name]))); if (!paramCounts[name]) { break; } } }); } data.toString = R._path2string; pth.arr = pathClone(data); return data; }; /*\ * Raphael.parseTransformString [ method ] ** * Utility method ** * Parses given path string into an array of transformations. > Parameters - TString (string|array) transform string or array of transformations (in the last case it will be returned straight away) = (array) array of transformations. \*/ R.parseTransformString = cacher(function (TString) { if (!TString) { return null; } var paramCounts = {r: 3, s: 4, t: 2, m: 6}, data = []; if (R.is(TString, array) && R.is(TString[0], array)) { // rough assumption data = pathClone(TString); } if (!data.length) { Str(TString).replace(tCommand, function (a, b, c) { var params = [], name = lowerCase.call(b); c.replace(pathValues, function (a, b) { b && params.push(+b); }); data.push([b][concat](params)); }); } data.toString = R._path2string; return data; }); // PATHS var paths = function (ps) { var p = paths.ps = paths.ps || {}; if (p[ps]) { p[ps].sleep = 100; } else { p[ps] = { sleep: 100 }; } setTimeout(function () { for (var key in p) if (p[has](key) && key != ps) { p[key].sleep--; !p[key].sleep && delete p[key]; } }); return p[ps]; }; /*\ * Raphael.findDotsAtSegment [ method ] ** * Utility method ** * Find dot coordinates on the given cubic bezier curve at the given t. > Parameters - p1x (number) x of the first point of the curve - p1y (number) y of the first point of the curve - c1x (number) x of the first anchor of the curve - c1y (number) y of the first anchor of the curve - c2x (number) x of the second anchor of the curve - c2y (number) y of the second anchor of the curve - p2x (number) x of the second point of the curve - p2y (number) y of the second point of the curve - t (number) position on the curve (0..1) = (object) point information in format: o { o x: (number) x coordinate of the point o y: (number) y coordinate of the point o m: { o x: (number) x coordinate of the left anchor o y: (number) y coordinate of the left anchor o } o n: { o x: (number) x coordinate of the right anchor o y: (number) y coordinate of the right anchor o } o start: { o x: (number) x coordinate of the start of the curve o y: (number) y coordinate of the start of the curve o } o end: { o x: (number) x coordinate of the end of the curve o y: (number) y coordinate of the end of the curve o } o alpha: (number) angle of the curve derivative at the point o } \*/ R.findDotsAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) { var t1 = 1 - t, t13 = pow(t1, 3), t12 = pow(t1, 2), t2 = t * t, t3 = t2 * t, x = t13 * p1x + t12 * 3 * t * c1x + t1 * 3 * t * t * c2x + t3 * p2x, y = t13 * p1y + t12 * 3 * t * c1y + t1 * 3 * t * t * c2y + t3 * p2y, mx = p1x + 2 * t * (c1x - p1x) + t2 * (c2x - 2 * c1x + p1x), my = p1y + 2 * t * (c1y - p1y) + t2 * (c2y - 2 * c1y + p1y), nx = c1x + 2 * t * (c2x - c1x) + t2 * (p2x - 2 * c2x + c1x), ny = c1y + 2 * t * (c2y - c1y) + t2 * (p2y - 2 * c2y + c1y), ax = t1 * p1x + t * c1x, ay = t1 * p1y + t * c1y, cx = t1 * c2x + t * p2x, cy = t1 * c2y + t * p2y, alpha = (90 - math.atan2(mx - nx, my - ny) * 180 / PI); (mx > nx || my < ny) && (alpha += 180); return { x: x, y: y, m: {x: mx, y: my}, n: {x: nx, y: ny}, start: {x: ax, y: ay}, end: {x: cx, y: cy}, alpha: alpha }; }; /*\ * Raphael.bezierBBox [ method ] ** * Utility method ** * Return bounding box of a given cubic bezier curve > Parameters - p1x (number) x of the first point of the curve - p1y (number) y of the first point of the curve - c1x (number) x of the first anchor of the curve - c1y (number) y of the first anchor of the curve - c2x (number) x of the second anchor of the curve - c2y (number) y of the second anchor of the curve - p2x (number) x of the second point of the curve - p2y (number) y of the second point of the curve * or - bez (array) array of six points for bezier curve = (object) point information in format: o { o min: { o x: (number) x coordinate of the left point o y: (number) y coordinate of the top point o } o max: { o x: (number) x coordinate of the right point o y: (number) y coordinate of the bottom point o } o } \*/ R.bezierBBox = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) { if (!R.is(p1x, "array")) { p1x = [p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y]; } var bbox = curveDim.apply(null, p1x); return { x: bbox.min.x, y: bbox.min.y, x2: bbox.max.x, y2: bbox.max.y, width: bbox.max.x - bbox.min.x, height: bbox.max.y - bbox.min.y }; }; /*\ * Raphael.isPointInsideBBox [ method ] ** * Utility method ** * Returns `true` if given point is inside bounding boxes. > Parameters - bbox (string) bounding box - x (string) x coordinate of the point - y (string) y coordinate of the point = (boolean) `true` if point inside \*/ R.isPointInsideBBox = function (bbox, x, y) { return x >= bbox.x && x <= bbox.x2 && y >= bbox.y && y <= bbox.y2; }; /*\ * Raphael.isBBoxIntersect [ method ] ** * Utility method ** * Returns `true` if two bounding boxes intersect > Parameters - bbox1 (string) first bounding box - bbox2 (string) second bounding box = (boolean) `true` if they intersect \*/ R.isBBoxIntersect = function (bbox1, bbox2) { var i = R.isPointInsideBBox; return i(bbox2, bbox1.x, bbox1.y) || i(bbox2, bbox1.x2, bbox1.y) || i(bbox2, bbox1.x, bbox1.y2) || i(bbox2, bbox1.x2, bbox1.y2) || i(bbox1, bbox2.x, bbox2.y) || i(bbox1, bbox2.x2, bbox2.y) || i(bbox1, bbox2.x, bbox2.y2) || i(bbox1, bbox2.x2, bbox2.y2) || (bbox1.x < bbox2.x2 && bbox1.x > bbox2.x || bbox2.x < bbox1.x2 && bbox2.x > bbox1.x) && (bbox1.y < bbox2.y2 && bbox1.y > bbox2.y || bbox2.y < bbox1.y2 && bbox2.y > bbox1.y); }; function base3(t, p1, p2, p3, p4) { var t1 = -3 * p1 + 9 * p2 - 9 * p3 + 3 * p4, t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3; return t * t2 - 3 * p1 + 3 * p2; } function bezlen(x1, y1, x2, y2, x3, y3, x4, y4, z) { if (z == null) { z = 1; } z = z > 1 ? 1 : z < 0 ? 0 : z; var z2 = z / 2, n = 12, Tvalues = [-0.1252,0.1252,-0.3678,0.3678,-0.5873,0.5873,-0.7699,0.7699,-0.9041,0.9041,-0.9816,0.9816], Cvalues = [0.2491,0.2491,0.2335,0.2335,0.2032,0.2032,0.1601,0.1601,0.1069,0.1069,0.0472,0.0472], sum = 0; for (var i = 0; i < n; i++) { var ct = z2 * Tvalues[i] + z2, xbase = base3(ct, x1, x2, x3, x4), ybase = base3(ct, y1, y2, y3, y4), comb = xbase * xbase + ybase * ybase; sum += Cvalues[i] * math.sqrt(comb); } return z2 * sum; } function getTatLen(x1, y1, x2, y2, x3, y3, x4, y4, ll) { if (ll < 0 || bezlen(x1, y1, x2, y2, x3, y3, x4, y4) < ll) { return; } var t = 1, step = t / 2, t2 = t - step, l, e = .01; l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2); while (abs(l - ll) > e) { step /= 2; t2 += (l < ll ? 1 : -1) * step; l = bezlen(x1, y1, x2, y2, x3, y3, x4, y4, t2); } return t2; } function intersect(x1, y1, x2, y2, x3, y3, x4, y4) { if ( mmax(x1, x2) < mmin(x3, x4) || mmin(x1, x2) > mmax(x3, x4) || mmax(y1, y2) < mmin(y3, y4) || mmin(y1, y2) > mmax(y3, y4) ) { return; } var nx = (x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4), ny = (x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4), denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); if (!denominator) { return; } var px = nx / denominator, py = ny / denominator, px2 = +px.toFixed(2), py2 = +py.toFixed(2); if ( px2 < +mmin(x1, x2).toFixed(2) || px2 > +mmax(x1, x2).toFixed(2) || px2 < +mmin(x3, x4).toFixed(2) || px2 > +mmax(x3, x4).toFixed(2) || py2 < +mmin(y1, y2).toFixed(2) || py2 > +mmax(y1, y2).toFixed(2) || py2 < +mmin(y3, y4).toFixed(2) || py2 > +mmax(y3, y4).toFixed(2) ) { return; } return {x: px, y: py}; } function inter(bez1, bez2) { return interHelper(bez1, bez2); } function interCount(bez1, bez2) { return interHelper(bez1, bez2, 1); } function interHelper(bez1, bez2, justCount) { var bbox1 = R.bezierBBox(bez1), bbox2 = R.bezierBBox(bez2); if (!R.isBBoxIntersect(bbox1, bbox2)) { return justCount ? 0 : []; } var l1 = bezlen.apply(0, bez1), l2 = bezlen.apply(0, bez2), n1 = mmax(~~(l1 / 5), 1), n2 = mmax(~~(l2 / 5), 1), dots1 = [], dots2 = [], xy = {}, res = justCount ? 0 : []; for (var i = 0; i < n1 + 1; i++) { var p = R.findDotsAtSegment.apply(R, bez1.concat(i / n1)); dots1.push({x: p.x, y: p.y, t: i / n1}); } for (i = 0; i < n2 + 1; i++) { p = R.findDotsAtSegment.apply(R, bez2.concat(i / n2)); dots2.push({x: p.x, y: p.y, t: i / n2}); } for (i = 0; i < n1; i++) { for (var j = 0; j < n2; j++) { var di = dots1[i], di1 = dots1[i + 1], dj = dots2[j], dj1 = dots2[j + 1], ci = abs(di1.x - di.x) < .001 ? "y" : "x", cj = abs(dj1.x - dj.x) < .001 ? "y" : "x", is = intersect(di.x, di.y, di1.x, di1.y, dj.x, dj.y, dj1.x, dj1.y); if (is) { if (xy[is.x.toFixed(4)] == is.y.toFixed(4)) { continue; } xy[is.x.toFixed(4)] = is.y.toFixed(4); var t1 = di.t + abs((is[ci] - di[ci]) / (di1[ci] - di[ci])) * (di1.t - di.t), t2 = dj.t + abs((is[cj] - dj[cj]) / (dj1[cj] - dj[cj])) * (dj1.t - dj.t); if (t1 >= 0 && t1 <= 1.001 && t2 >= 0 && t2 <= 1.001) { if (justCount) { res++; } else { res.push({ x: is.x, y: is.y, t1: mmin(t1, 1), t2: mmin(t2, 1) }); } } } } } return res; } /*\ * Raphael.pathIntersection [ method ] ** * Utility method ** * Finds intersections of two paths > Parameters - path1 (string) path string - path2 (string) path string = (array) dots of intersection o [ o { o x: (number) x coordinate of the point o y: (number) y coordinate of the point o t1: (number) t value for segment of path1 o t2: (number) t value for segment of path2 o segment1: (number) order number for segment of path1 o segment2: (number) order number for segment of path2 o bez1: (array) eight coordinates representing beziér curve for the segment of path1 o bez2: (array) eight coordinates representing beziér curve for the segment of path2 o } o ] \*/ R.pathIntersection = function (path1, path2) { return interPathHelper(path1, path2); }; R.pathIntersectionNumber = function (path1, path2) { return interPathHelper(path1, path2, 1); }; function interPathHelper(path1, path2, justCount) { path1 = R._path2curve(path1); path2 = R._path2curve(path2); var x1, y1, x2, y2, x1m, y1m, x2m, y2m, bez1, bez2, res = justCount ? 0 : []; for (var i = 0, ii = path1.length; i < ii; i++) { var pi = path1[i]; if (pi[0] == "M") { x1 = x1m = pi[1]; y1 = y1m = pi[2]; } else { if (pi[0] == "C") { bez1 = [x1, y1].concat(pi.slice(1)); x1 = bez1[6]; y1 = bez1[7]; } else { bez1 = [x1, y1, x1, y1, x1m, y1m, x1m, y1m]; x1 = x1m; y1 = y1m; } for (var j = 0, jj = path2.length; j < jj; j++) { var pj = path2[j]; if (pj[0] == "M") { x2 = x2m = pj[1]; y2 = y2m = pj[2]; } else { if (pj[0] == "C") { bez2 = [x2, y2].concat(pj.slice(1)); x2 = bez2[6]; y2 = bez2[7]; } else { bez2 = [x2, y2, x2, y2, x2m, y2m, x2m, y2m]; x2 = x2m; y2 = y2m; } var intr = interHelper(bez1, bez2, justCount); if (justCount) { res += intr; } else { for (var k = 0, kk = intr.length; k < kk; k++) { intr[k].segment1 = i; intr[k].segment2 = j; intr[k].bez1 = bez1; intr[k].bez2 = bez2; } res = res.concat(intr); } } } } } return res; } /*\ * Raphael.isPointInsidePath [ method ] ** * Utility method ** * Returns `true` if given point is inside a given closed path. > Parameters - path (string) path string - x (number) x of the point - y (number) y of the point = (boolean) true, if point is inside the path \*/ R.isPointInsidePath = function (path, x, y) { var bbox = R.pathBBox(path); return R.isPointInsideBBox(bbox, x, y) && interPathHelper(path, [["M", x, y], ["H", bbox.x2 + 10]], 1) % 2 == 1; }; R._removedFactory = function (methodname) { return function () { eve("raphael.log", null, "Rapha\xebl: you are calling to method \u201c" + methodname + "\u201d of removed object", methodname); }; }; /*\ * Raphael.pathBBox [ method ] ** * Utility method ** * Return bounding box of a given path > Parameters - path (string) path string = (object) bounding box o { o x: (number) x coordinate of the left top point of the box o y: (number) y coordinate of the left top point of the box o x2: (number) x coordinate of the right bottom point of the box o y2: (number) y coordinate of the right bottom point of the box o width: (number) width of the box o height: (number) height of the box o cx: (number) x coordinate of the center of the box o cy: (number) y coordinate of the center of the box o } \*/ var pathDimensions = R.pathBBox = function (path) { var pth = paths(path); if (pth.bbox) { return clone(pth.bbox); } if (!path) { return {x: 0, y: 0, width: 0, height: 0, x2: 0, y2: 0}; } path = path2curve(path); var x = 0, y = 0, X = [], Y = [], p; for (var i = 0, ii = path.length; i < ii; i++) { p = path[i]; if (p[0] == "M") { x = p[1]; y = p[2]; X.push(x); Y.push(y); } else { var dim = curveDim(x, y, p[1], p[2], p[3], p[4], p[5], p[6]); X = X[concat](dim.min.x, dim.max.x); Y = Y[concat](dim.min.y, dim.max.y); x = p[5]; y = p[6]; } } var xmin = mmin[apply](0, X), ymin = mmin[apply](0, Y), xmax = mmax[apply](0, X), ymax = mmax[apply](0, Y), width = xmax - xmin, height = ymax - ymin, bb = { x: xmin, y: ymin, x2: xmax, y2: ymax, width: width, height: height, cx: xmin + width / 2, cy: ymin + height / 2 }; pth.bbox = clone(bb); return bb; }, pathClone = function (pathArray) { var res = clone(pathArray); res.toString = R._path2string; return res; }, pathToRelative = R._pathToRelative = function (pathArray) { var pth = paths(pathArray); if (pth.rel) { return pathClone(pth.rel); } if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption pathArray = R.parsePathString(pathArray); } var res = [], x = 0, y = 0, mx = 0, my = 0, start = 0; if (pathArray[0][0] == "M") { x = pathArray[0][1]; y = pathArray[0][2]; mx = x; my = y; start++; res.push(["M", x, y]); } for (var i = start, ii = pathArray.length; i < ii; i++) { var r = res[i] = [], pa = pathArray[i]; if (pa[0] != lowerCase.call(pa[0])) { r[0] = lowerCase.call(pa[0]); switch (r[0]) { case "a": r[1] = pa[1]; r[2] = pa[2]; r[3] = pa[3]; r[4] = pa[4]; r[5] = pa[5]; r[6] = +(pa[6] - x).toFixed(3); r[7] = +(pa[7] - y).toFixed(3); break; case "v": r[1] = +(pa[1] - y).toFixed(3); break; case "m": mx = pa[1]; my = pa[2]; default: for (var j = 1, jj = pa.length; j < jj; j++) { r[j] = +(pa[j] - ((j % 2) ? x : y)).toFixed(3); } } } else { r = res[i] = []; if (pa[0] == "m") { mx = pa[1] + x; my = pa[2] + y; } for (var k = 0, kk = pa.length; k < kk; k++) { res[i][k] = pa[k]; } } var len = res[i].length; switch (res[i][0]) { case "z": x = mx; y = my; break; case "h": x += +res[i][len - 1]; break; case "v": y += +res[i][len - 1]; break; default: x += +res[i][len - 2]; y += +res[i][len - 1]; } } res.toString = R._path2string; pth.rel = pathClone(res); return res; }, pathToAbsolute = R._pathToAbsolute = function (pathArray) { var pth = paths(pathArray); if (pth.abs) { return pathClone(pth.abs); } if (!R.is(pathArray, array) || !R.is(pathArray && pathArray[0], array)) { // rough assumption pathArray = R.parsePathString(pathArray); } if (!pathArray || !pathArray.length) { return [["M", 0, 0]]; } var res = [], x = 0, y = 0, mx = 0, my = 0, start = 0; if (pathArray[0][0] == "M") { x = +pathArray[0][1]; y = +pathArray[0][2]; mx = x; my = y; start++; res[0] = ["M", x, y]; } var crz = pathArray.length == 3 && pathArray[0][0] == "M" && pathArray[1][0].toUpperCase() == "R" && pathArray[2][0].toUpperCase() == "Z"; for (var r, pa, i = start, ii = pathArray.length; i < ii; i++) { res.push(r = []); pa = pathArray[i]; if (pa[0] != upperCase.call(pa[0])) { r[0] = upperCase.call(pa[0]); switch (r[0]) { case "A": r[1] = pa[1]; r[2] = pa[2]; r[3] = pa[3]; r[4] = pa[4]; r[5] = pa[5]; r[6] = +(pa[6] + x); r[7] = +(pa[7] + y); break; case "V": r[1] = +pa[1] + y; break; case "H": r[1] = +pa[1] + x; break; case "R": var dots = [x, y][concat](pa.slice(1)); for (var j = 2, jj = dots.length; j < jj; j++) { dots[j] = +dots[j] + x; dots[++j] = +dots[j] + y; } res.pop(); res = res[concat](catmullRom2bezier(dots, crz)); break; case "M": mx = +pa[1] + x; my = +pa[2] + y; default: for (j = 1, jj = pa.length; j < jj; j++) { r[j] = +pa[j] + ((j % 2) ? x : y); } } } else if (pa[0] == "R") { dots = [x, y][concat](pa.slice(1)); res.pop(); res = res[concat](catmullRom2bezier(dots, crz)); r = ["R"][concat](pa.slice(-2)); } else { for (var k = 0, kk = pa.length; k < kk; k++) { r[k] = pa[k]; } } switch (r[0]) { case "Z": x = mx; y = my; break; case "H": x = r[1]; break; case "V": y = r[1]; break; case "M": mx = r[r.length - 2]; my = r[r.length - 1]; default: x = r[r.length - 2]; y = r[r.length - 1]; } } res.toString = R._path2string; pth.abs = pathClone(res); return res; }, l2c = function (x1, y1, x2, y2) { return [x1, y1, x2, y2, x2, y2]; }, q2c = function (x1, y1, ax, ay, x2, y2) { var _13 = 1 / 3, _23 = 2 / 3; return [ _13 * x1 + _23 * ax, _13 * y1 + _23 * ay, _13 * x2 + _23 * ax, _13 * y2 + _23 * ay, x2, y2 ]; }, a2c = function (x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) { // for more information of where this math came from visit: // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes var _120 = PI * 120 / 180, rad = PI / 180 * (+angle || 0), res = [], xy, rotate = cacher(function (x, y, rad) { var X = x * math.cos(rad) - y * math.sin(rad), Y = x * math.sin(rad) + y * math.cos(rad); return {x: X, y: Y}; }); if (!recursive) { xy = rotate(x1, y1, -rad); x1 = xy.x; y1 = xy.y; xy = rotate(x2, y2, -rad); x2 = xy.x; y2 = xy.y; var cos = math.cos(PI / 180 * angle), sin = math.sin(PI / 180 * angle), x = (x1 - x2) / 2, y = (y1 - y2) / 2; var h = (x * x) / (rx * rx) + (y * y) / (ry * ry); if (h > 1) { h = math.sqrt(h); rx = h * rx; ry = h * ry; } var rx2 = rx * rx, ry2 = ry * ry, k = (large_arc_flag == sweep_flag ? -1 : 1) * math.sqrt(abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))), cx = k * rx * y / ry + (x1 + x2) / 2, cy = k * -ry * x / rx + (y1 + y2) / 2, f1 = math.asin(((y1 - cy) / ry).toFixed(9)), f2 = math.asin(((y2 - cy) / ry).toFixed(9)); f1 = x1 < cx ? PI - f1 : f1; f2 = x2 < cx ? PI - f2 : f2; f1 < 0 && (f1 = PI * 2 + f1); f2 < 0 && (f2 = PI * 2 + f2); if (sweep_flag && f1 > f2) { f1 = f1 - PI * 2; } if (!sweep_flag && f2 > f1) { f2 = f2 - PI * 2; } } else { f1 = recursive[0]; f2 = recursive[1]; cx = recursive[2]; cy = recursive[3]; } var df = f2 - f1; if (abs(df) > _120) { var f2old = f2, x2old = x2, y2old = y2; f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1); x2 = cx + rx * math.cos(f2); y2 = cy + ry * math.sin(f2); res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]); } df = f2 - f1; var c1 = math.cos(f1), s1 = math.sin(f1), c2 = math.cos(f2), s2 = math.sin(f2), t = math.tan(df / 4), hx = 4 / 3 * rx * t, hy = 4 / 3 * ry * t, m1 = [x1, y1], m2 = [x1 + hx * s1, y1 - hy * c1], m3 = [x2 + hx * s2, y2 - hy * c2], m4 = [x2, y2]; m2[0] = 2 * m1[0] - m2[0]; m2[1] = 2 * m1[1] - m2[1]; if (recursive) { return [m2, m3, m4][concat](res); } else { res = [m2, m3, m4][concat](res).join()[split](","); var newres = []; for (var i = 0, ii = res.length; i < ii; i++) { newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x; } return newres; } }, findDotAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) { var t1 = 1 - t; return { x: pow(t1, 3) * p1x + pow(t1, 2) * 3 * t * c1x + t1 * 3 * t * t * c2x + pow(t, 3) * p2x, y: pow(t1, 3) * p1y + pow(t1, 2) * 3 * t * c1y + t1 * 3 * t * t * c2y + pow(t, 3) * p2y }; }, curveDim = cacher(function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) { var a = (c2x - 2 * c1x + p1x) - (p2x - 2 * c2x + c1x), b = 2 * (c1x - p1x) - 2 * (c2x - c1x), c = p1x - c1x, t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a, t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a, y = [p1y, p2y], x = [p1x, p2x], dot; abs(t1) > "1e12" && (t1 = .5); abs(t2) > "1e12" && (t2 = .5); if (t1 > 0 && t1 < 1) { dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1); x.push(dot.x); y.push(dot.y); } if (t2 > 0 && t2 < 1) { dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2); x.push(dot.x); y.push(dot.y); } a = (c2y - 2 * c1y + p1y) - (p2y - 2 * c2y + c1y); b = 2 * (c1y - p1y) - 2 * (c2y - c1y); c = p1y - c1y; t1 = (-b + math.sqrt(b * b - 4 * a * c)) / 2 / a; t2 = (-b - math.sqrt(b * b - 4 * a * c)) / 2 / a; abs(t1) > "1e12" && (t1 = .5); abs(t2) > "1e12" && (t2 = .5); if (t1 > 0 && t1 < 1) { dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t1); x.push(dot.x); y.push(dot.y); } if (t2 > 0 && t2 < 1) { dot = findDotAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t2); x.push(dot.x); y.push(dot.y); } return { min: {x: mmin[apply](0, x), y: mmin[apply](0, y)}, max: {x: mmax[apply](0, x), y: mmax[apply](0, y)} }; }), path2curve = R._path2curve = cacher(function (path, path2) { var pth = !path2 && paths(path); if (!path2 && pth.curve) { return pathClone(pth.curve); } var p = pathToAbsolute(path), p2 = path2 && pathToAbsolute(path2), attrs = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null}, attrs2 = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null}, processPath = function (path, d, pcom) { var nx, ny, tq = {T:1, Q:1}; if (!path) { return ["C", d.x, d.y, d.x, d.y, d.x, d.y]; } !(path[0] in tq) && (d.qx = d.qy = null); switch (path[0]) { case "M": d.X = path[1]; d.Y = path[2]; break; case "A": path = ["C"][concat](a2c[apply](0, [d.x, d.y][concat](path.slice(1)))); break; case "S": if (pcom == "C" || pcom == "S") { // In "S" case we have to take into account, if the previous command is C/S. nx = d.x * 2 - d.bx; // And reflect the previous ny = d.y * 2 - d.by; // command's control point relative to the current point. } else { // or some else or nothing nx = d.x; ny = d.y; } path = ["C", nx, ny][concat](path.slice(1)); break; case "T": if (pcom == "Q" || pcom == "T") { // In "T" case we have to take into account, if the previous command is Q/T. d.qx = d.x * 2 - d.qx; // And make a reflection similar d.qy = d.y * 2 - d.qy; // to case "S". } else { // or something else or nothing d.qx = d.x; d.qy = d.y; } path = ["C"][concat](q2c(d.x, d.y, d.qx, d.qy, path[1], path[2])); break; case "Q": d.qx = path[1]; d.qy = path[2]; path = ["C"][concat](q2c(d.x, d.y, path[1], path[2], path[3], path[4])); break; case "L": path = ["C"][concat](l2c(d.x, d.y, path[1], path[2])); break; case "H": path = ["C"][concat](l2c(d.x, d.y, path[1], d.y)); break; case "V": path = ["C"][concat](l2c(d.x, d.y, d.x, path[1])); break; case "Z": path = ["C"][concat](l2c(d.x, d.y, d.X, d.Y)); break; } return path; }, fixArc = function (pp, i) { if (pp[i].length > 7) { pp[i].shift(); var pi = pp[i]; while (pi.length) { pp.splice(i++, 0, ["C"][concat](pi.splice(0, 6))); } pp.splice(i, 1); ii = mmax(p.length, p2 && p2.length || 0); } }, fixM = function (path1, path2, a1, a2, i) { if (path1 && path2 && path1[i][0] == "M" && path2[i][0] != "M") { path2.splice(i, 0, ["M", a2.x, a2.y]); a1.bx = 0; a1.by = 0; a1.x = path1[i][1]; a1.y = path1[i][2]; ii = mmax(p.length, p2 && p2.length || 0); } }; for (var i = 0, ii = mmax(p.length, p2 && p2.length || 0); i < ii; i++) { p[i] = processPath(p[i], attrs); fixArc(p, i); p2 && (p2[i] = processPath(p2[i], attrs2)); p2 && fixArc(p2, i); fixM(p, p2, attrs, attrs2, i); fixM(p2, p, attrs2, attrs, i); var seg = p[i], seg2 = p2 && p2[i], seglen = seg.length, seg2len = p2 && seg2.length; attrs.x = seg[seglen - 2]; attrs.y = seg[seglen - 1]; attrs.bx = toFloat(seg[seglen - 4]) || attrs.x; attrs.by = toFloat(seg[seglen - 3]) || attrs.y; attrs2.bx = p2 && (toFloat(seg2[seg2len - 4]) || attrs2.x); attrs2.by = p2 && (toFloat(seg2[seg2len - 3]) || attrs2.y); attrs2.x = p2 && seg2[seg2len - 2]; attrs2.y = p2 && seg2[seg2len - 1]; } if (!p2) { pth.curve = pathClone(p); } return p2 ? [p, p2] : p; }, null, pathClone), parseDots = R._parseDots = cacher(function (gradient) { var dots = []; for (var i = 0, ii = gradient.length; i < ii; i++) { var dot = {}, par = gradient[i].match(/^([^:]*):?([\d\.]*)/); dot.color = R.getRGB(par[1]); if (dot.color.error) { return null; } dot.color = dot.color.hex; par[2] && (dot.offset = par[2] + "%"); dots.push(dot); } for (i = 1, ii = dots.length - 1; i < ii; i++) { if (!dots[i].offset) { var start = toFloat(dots[i - 1].offset || 0), end = 0; for (var j = i + 1; j < ii; j++) { if (dots[j].offset) { end = dots[j].offset; break; } } if (!end) { end = 100; j = ii; } end = toFloat(end); var d = (end - start) / (j - i + 1); for (; i < j; i++) { start += d; dots[i].offset = start + "%"; } } } return dots; }), tear = R._tear = function (el, paper) { el == paper.top && (paper.top = el.prev); el == paper.bottom && (paper.bottom = el.next); el.next && (el.next.prev = el.prev); el.prev && (el.prev.next = el.next); }, tofront = R._tofront = function (el, paper) { if (paper.top === el) { return; } tear(el, paper); el.next = null; el.prev = paper.top; paper.top.next = el; paper.top = el; }, toback = R._toback = function (el, paper) { if (paper.bottom === el) { return; } tear(el, paper); el.next = paper.bottom; el.prev = null; paper.bottom.prev = el; paper.bottom = el; }, insertafter = R._insertafter = function (el, el2, paper) { tear(el, paper); el2 == paper.top && (paper.top = el); el2.next && (el2.next.prev = el); el.next = el2.next; el.prev = el2; el2.next = el; }, insertbefore = R._insertbefore = function (el, el2, paper) { tear(el, paper); el2 == paper.bottom && (paper.bottom = el); el2.prev && (el2.prev.next = el); el.prev = el2.prev; el2.prev = el; el.next = el2; }, /*\ * Raphael.toMatrix [ method ] ** * Utility method ** * Returns matrix of transformations applied to a given path > Parameters - path (string) path string - transform (string|array) transformation string = (object) @Matrix \*/ toMatrix = R.toMatrix = function (path, transform) { var bb = pathDimensions(path), el = { _: { transform: E }, getBBox: function () { return bb; } }; extractTransform(el, transform); return el.matrix; }, /*\ * Raphael.transformPath [ method ] ** * Utility method ** * Returns path transformed by a given transformation > Parameters - path (string) path string - transform (string|array) transformation string = (string) path \*/ transformPath = R.transformPath = function (path, transform) { return mapPath(path, toMatrix(path, transform)); }, extractTransform = R._extractTransform = function (el, tstr) { if (tstr == null) { return el._.transform; } tstr = Str(tstr).replace(/\.{3}|\u2026/g, el._.transform || E); var tdata = R.parseTransformString(tstr), deg = 0, dx = 0, dy = 0, sx = 1, sy = 1, _ = el._, m = new Matrix; _.transform = tdata || []; if (tdata) { for (var i = 0, ii = tdata.length; i < ii; i++) { var t = tdata[i], tlen = t.length, command = Str(t[0]).toLowerCase(), absolute = t[0] != command, inver = absolute ? m.invert() : 0, x1, y1, x2, y2, bb; if (command == "t" && tlen == 3) { if (absolute) { x1 = inver.x(0, 0); y1 = inver.y(0, 0); x2 = inver.x(t[1], t[2]); y2 = inver.y(t[1], t[2]); m.translate(x2 - x1, y2 - y1); } else { m.translate(t[1], t[2]); } } else if (command == "r") { if (tlen == 2) { bb = bb || el.getBBox(1); m.rotate(t[1], bb.x + bb.width / 2, bb.y + bb.height / 2); deg += t[1]; } else if (tlen == 4) { if (absolute) { x2 = inver.x(t[2], t[3]); y2 = inver.y(t[2], t[3]); m.rotate(t[1], x2, y2); } else { m.rotate(t[1], t[2], t[3]); } deg += t[1]; } } else if (command == "s") { if (tlen == 2 || tlen == 3) { bb = bb || el.getBBox(1); m.scale(t[1], t[tlen - 1], bb.x + bb.width / 2, bb.y + bb.height / 2); sx *= t[1]; sy *= t[tlen - 1]; } else if (tlen == 5) { if (absolute) { x2 = inver.x(t[3], t[4]); y2 = inver.y(t[3], t[4]); m.scale(t[1], t[2], x2, y2); } else { m.scale(t[1], t[2], t[3], t[4]); } sx *= t[1]; sy *= t[2]; } } else if (command == "m" && tlen == 7) { m.add(t[1], t[2], t[3], t[4], t[5], t[6]); } _.dirtyT = 1; el.matrix = m; } } /*\ * Element.matrix [ property (object) ] ** * Keeps @Matrix object, which represents element transformation \*/ el.matrix = m; _.sx = sx; _.sy = sy; _.deg = deg; _.dx = dx = m.e; _.dy = dy = m.f; if (sx == 1 && sy == 1 && !deg && _.bbox) { _.bbox.x += +dx; _.bbox.y += +dy; } else { _.dirtyT = 1; } }, getEmpty = function (item) { var l = item[0]; switch (l.toLowerCase()) { case "t": return [l, 0, 0]; case "m": return [l, 1, 0, 0, 1, 0, 0]; case "r": if (item.length == 4) { return [l, 0, item[2], item[3]]; } else { return [l, 0]; } case "s": if (item.length == 5) { return [l, 1, 1, item[3], item[4]]; } else if (item.length == 3) { return [l, 1, 1]; } else { return [l, 1]; } } }, equaliseTransform = R._equaliseTransform = function (t1, t2) { t2 = Str(t2).replace(/\.{3}|\u2026/g, t1); t1 = R.parseTransformString(t1) || []; t2 = R.parseTransformString(t2) || []; var maxlength = mmax(t1.length, t2.length), from = [], to = [], i = 0, j, jj, tt1, tt2; for (; i < maxlength; i++) { tt1 = t1[i] || getEmpty(t2[i]); tt2 = t2[i] || getEmpty(tt1); if ((tt1[0] != tt2[0]) || (tt1[0].toLowerCase() == "r" && (tt1[2] != tt2[2] || tt1[3] != tt2[3])) || (tt1[0].toLowerCase() == "s" && (tt1[3] != tt2[3] || tt1[4] != tt2[4])) ) { return; } from[i] = []; to[i] = []; for (j = 0, jj = mmax(tt1.length, tt2.length); j < jj; j++) { j in tt1 && (from[i][j] = tt1[j]); j in tt2 && (to[i][j] = tt2[j]); } } return { from: from, to: to }; }; R._getContainer = function (x, y, w, h) { var container; container = h == null && !R.is(x, "object") ? g.doc.getElementById(x) : x; if (container == null) { return; } if (container.tagName) { if (y == null) { return { container: container, width: container.style.pixelWidth || container.offsetWidth, height: container.style.pixelHeight || container.offsetHeight }; } else { return { container: container, width: y, height: w }; } } return { container: 1, x: x, y: y, width: w, height: h }; }; /*\ * Raphael.pathToRelative [ method ] ** * Utility method ** * Converts path to relative form > Parameters - pathString (string|array) path string or array of segments = (array) array of segments. \*/ R.pathToRelative = pathToRelative; R._engine = {}; /*\ * Raphael.path2curve [ method ] ** * Utility method ** * Converts path to a new path where all segments are cubic bezier curves. > Parameters - pathString (string|array) path string or array of segments = (array) array of segments. \*/ R.path2curve = path2curve; /*\ * Raphael.matrix [ method ] ** * Utility method ** * Returns matrix based on given parameters. > Parameters - a (number) - b (number) - c (number) - d (number) - e (number) - f (number) = (object) @Matrix \*/ R.matrix = function (a, b, c, d, e, f) { return new Matrix(a, b, c, d, e, f); }; function Matrix(a, b, c, d, e, f) { if (a != null) { this.a = +a; this.b = +b; this.c = +c; this.d = +d; this.e = +e; this.f = +f; } else { this.a = 1; this.b = 0; this.c = 0; this.d = 1; this.e = 0; this.f = 0; } } (function (matrixproto) { /*\ * Matrix.add [ method ] ** * Adds given matrix to existing one. > Parameters - a (number) - b (number) - c (number) - d (number) - e (number) - f (number) or - matrix (object) @Matrix \*/ matrixproto.add = function (a, b, c, d, e, f) { var out = [[], [], []], m = [[this.a, this.c, this.e], [this.b, this.d, this.f], [0, 0, 1]], matrix = [[a, c, e], [b, d, f], [0, 0, 1]], x, y, z, res; if (a && a instanceof Matrix) { matrix = [[a.a, a.c, a.e], [a.b, a.d, a.f], [0, 0, 1]]; } for (x = 0; x < 3; x++) { for (y = 0; y < 3; y++) { res = 0; for (z = 0; z < 3; z++) { res += m[x][z] * matrix[z][y]; } out[x][y] = res; } } this.a = out[0][0]; this.b = out[1][0]; this.c = out[0][1]; this.d = out[1][1]; this.e = out[0][2]; this.f = out[1][2]; }; /*\ * Matrix.invert [ method ] ** * Returns inverted version of the matrix = (object) @Matrix \*/ matrixproto.invert = function () { var me = this, x = me.a * me.d - me.b * me.c; return new Matrix(me.d / x, -me.b / x, -me.c / x, me.a / x, (me.c * me.f - me.d * me.e) / x, (me.b * me.e - me.a * me.f) / x); }; /*\ * Matrix.clone [ method ] ** * Returns copy of the matrix = (object) @Matrix \*/ matrixproto.clone = function () { return new Matrix(this.a, this.b, this.c, this.d, this.e, this.f); }; /*\ * Matrix.translate [ method ] ** * Translate the matrix > Parameters - x (number) - y (number) \*/ matrixproto.translate = function (x, y) { this.add(1, 0, 0, 1, x, y); }; /*\ * Matrix.scale [ method ] ** * Scales the matrix > Parameters - x (number) - y (number) #optional - cx (number) #optional - cy (number) #optional \*/ matrixproto.scale = function (x, y, cx, cy) { y == null && (y = x); (cx || cy) && this.add(1, 0, 0, 1, cx, cy); this.add(x, 0, 0, y, 0, 0); (cx || cy) && this.add(1, 0, 0, 1, -cx, -cy); }; /*\ * Matrix.rotate [ method ] ** * Rotates the matrix > Parameters - a (number) - x (number) - y (number) \*/ matrixproto.rotate = function (a, x, y) { a = R.rad(a); x = x || 0; y = y || 0; var cos = +math.cos(a).toFixed(9), sin = +math.sin(a).toFixed(9); this.add(cos, sin, -sin, cos, x, y); this.add(1, 0, 0, 1, -x, -y); }; /*\ * Matrix.x [ method ] ** * Return x coordinate for given point after transformation described by the matrix. See also @Matrix.y > Parameters - x (number) - y (number) = (number) x \*/ matrixproto.x = function (x, y) { return x * this.a + y * this.c + this.e; }; /*\ * Matrix.y [ method ] ** * Return y coordinate for given point after transformation described by the matrix. See also @Matrix.x > Parameters - x (number) - y (number) = (number) y \*/ matrixproto.y = function (x, y) { return x * this.b + y * this.d + this.f; }; matrixproto.get = function (i) { return +this[Str.fromCharCode(97 + i)].toFixed(4); }; matrixproto.toString = function () { return R.svg ? "matrix(" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)].join() + ")" : [this.get(0), this.get(2), this.get(1), this.get(3), 0, 0].join(); }; matrixproto.toFilter = function () { return "progid:DXImageTransform.Microsoft.Matrix(M11=" + this.get(0) + ", M12=" + this.get(2) + ", M21=" + this.get(1) + ", M22=" + this.get(3) + ", Dx=" + this.get(4) + ", Dy=" + this.get(5) + ", sizingmethod='auto expand')"; }; matrixproto.offset = function () { return [this.e.toFixed(4), this.f.toFixed(4)]; }; function norm(a) { return a[0] * a[0] + a[1] * a[1]; } function normalize(a) { var mag = math.sqrt(norm(a)); a[0] && (a[0] /= mag); a[1] && (a[1] /= mag); } /*\ * Matrix.split [ method ] ** * Splits matrix into primitive transformations = (object) in format: o dx (number) translation by x o dy (number) translation by y o scalex (number) scale by x o scaley (number) scale by y o shear (number) shear o rotate (number) rotation in deg o isSimple (boolean) could it be represented via simple transformations \*/ matrixproto.split = function () { var out = {}; // translation out.dx = this.e; out.dy = this.f; // scale and shear var row = [[this.a, this.c], [this.b, this.d]]; out.scalex = math.sqrt(norm(row[0])); normalize(row[0]); out.shear = row[0][0] * row[1][0] + row[0][1] * row[1][1]; row[1] = [row[1][0] - row[0][0] * out.shear, row[1][1] - row[0][1] * out.shear]; out.scaley = math.sqrt(norm(row[1])); normalize(row[1]); out.shear /= out.scaley; // rotation var sin = -row[0][1], cos = row[1][1]; if (cos < 0) { out.rotate = R.deg(math.acos(cos)); if (sin < 0) { out.rotate = 360 - out.rotate; } } else { out.rotate = R.deg(math.asin(sin)); } out.isSimple = !+out.shear.toFixed(9) && (out.scalex.toFixed(9) == out.scaley.toFixed(9) || !out.rotate); out.isSuperSimple = !+out.shear.toFixed(9) && out.scalex.toFixed(9) == out.scaley.toFixed(9) && !out.rotate; out.noRotation = !+out.shear.toFixed(9) && !out.rotate; return out; }; /*\ * Matrix.toTransformString [ method ] ** * Return transform string that represents given matrix = (string) transform string \*/ matrixproto.toTransformString = function (shorter) { var s = shorter || this[split](); if (s.isSimple) { s.scalex = +s.scalex.toFixed(4); s.scaley = +s.scaley.toFixed(4); s.rotate = +s.rotate.toFixed(4); return (s.dx || s.dy ? "t" + [s.dx, s.dy] : E) + (s.scalex != 1 || s.scaley != 1 ? "s" + [s.scalex, s.scaley, 0, 0] : E) + (s.rotate ? "r" + [s.rotate, 0, 0] : E); } else { return "m" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)]; } }; })(Matrix.prototype); // WebKit rendering bug workaround method var version = navigator.userAgent.match(/Version\/(.*?)\s/) || navigator.userAgent.match(/Chrome\/(\d+)/); if ((navigator.vendor == "Apple Computer, Inc.") && (version && version[1] < 4 || navigator.platform.slice(0, 2) == "iP") || (navigator.vendor == "Google Inc." && version && version[1] < 8)) { /*\ * Paper.safari [ method ] ** * There is an inconvenient rendering bug in Safari (WebKit): * sometimes the rendering should be forced. * This method should help with dealing with this bug. \*/ paperproto.safari = function () { var rect = this.rect(-99, -99, this.width + 99, this.height + 99).attr({stroke: "none"}); setTimeout(function () {rect.remove();}); }; } else { paperproto.safari = fun; } var preventDefault = function () { this.returnValue = false; }, preventTouch = function () { return this.originalEvent.preventDefault(); }, stopPropagation = function () { this.cancelBubble = true; }, stopTouch = function () { return this.originalEvent.stopPropagation(); }, getEventPosition = function (e) { var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop, scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft; return { x: e.clientX + scrollX, y: e.clientY + scrollY }; }, addEvent = (function () { if (g.doc.addEventListener) { return function (obj, type, fn, element) { var f = function (e) { var pos = getEventPosition(e); return fn.call(element, e, pos.x, pos.y); }; obj.addEventListener(type, f, false); if (supportsTouch && touchMap[type]) { var _f = function (e) { var pos = getEventPosition(e), olde = e; for (var i = 0, ii = e.targetTouches && e.targetTouches.length; i < ii; i++) { if (e.targetTouches[i].target == obj) { e = e.targetTouches[i]; e.originalEvent = olde; e.preventDefault = preventTouch; e.stopPropagation = stopTouch; break; } } return fn.call(element, e, pos.x, pos.y); }; obj.addEventListener(touchMap[type], _f, false); } return function () { obj.removeEventListener(type, f, false); if (supportsTouch && touchMap[type]) obj.removeEventListener(touchMap[type], f, false); return true; }; }; } else if (g.doc.attachEvent) { return function (obj, type, fn, element) { var f = function (e) { e = e || g.win.event; var scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop, scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft, x = e.clientX + scrollX, y = e.clientY + scrollY; e.preventDefault = e.preventDefault || preventDefault; e.stopPropagation = e.stopPropagation || stopPropagation; return fn.call(element, e, x, y); }; obj.attachEvent("on" + type, f); var detacher = function () { obj.detachEvent("on" + type, f); return true; }; return detacher; }; } })(), drag = [], dragMove = function (e) { var x = e.clientX, y = e.clientY, scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop, scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft, dragi, j = drag.length; while (j--) { dragi = drag[j]; if (supportsTouch && e.touches) { var i = e.touches.length, touch; while (i--) { touch = e.touches[i]; if (touch.identifier == dragi.el._drag.id) { x = touch.clientX; y = touch.clientY; (e.originalEvent ? e.originalEvent : e).preventDefault(); break; } } } else { e.preventDefault(); } var node = dragi.el.node, o, next = node.nextSibling, parent = node.parentNode, display = node.style.display; g.win.opera && parent.removeChild(node); node.style.display = "none"; o = dragi.el.paper.getElementByPoint(x, y); node.style.display = display; g.win.opera && (next ? parent.insertBefore(node, next) : parent.appendChild(node)); o && eve("raphael.drag.over." + dragi.el.id, dragi.el, o); x += scrollX; y += scrollY; eve("raphael.drag.move." + dragi.el.id, dragi.move_scope || dragi.el, x - dragi.el._drag.x, y - dragi.el._drag.y, x, y, e); } }, dragUp = function (e) { R.unmousemove(dragMove).unmouseup(dragUp); var i = drag.length, dragi; while (i--) { dragi = drag[i]; dragi.el._drag = {}; eve("raphael.drag.end." + dragi.el.id, dragi.end_scope || dragi.start_scope || dragi.move_scope || dragi.el, e); } drag = []; }, /*\ * Raphael.el [ property (object) ] ** * You can add your own method to elements. This is usefull when you want to hack default functionality or * want to wrap some common transformation or attributes in one method. In difference to canvas methods, * you can redefine element method at any time. Expending element methods wouldn’t affect set. > Usage | Raphael.el.red = function () { | this.attr({fill: "#f00"}); | }; | // then use it | paper.circle(100, 100, 20).red(); \*/ elproto = R.el = {}; /*\ * Element.click [ method ] ** * Adds event handler for click for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.unclick [ method ] ** * Removes event handler for click for the element. > Parameters - handler (function) #optional handler for the event = (object) @Element \*/ /*\ * Element.dblclick [ method ] ** * Adds event handler for double click for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.undblclick [ method ] ** * Removes event handler for double click for the element. > Parameters - handler (function) #optional handler for the event = (object) @Element \*/ /*\ * Element.mousedown [ method ] ** * Adds event handler for mousedown for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.unmousedown [ method ] ** * Removes event handler for mousedown for the element. > Parameters - handler (function) #optional handler for the event = (object) @Element \*/ /*\ * Element.mousemove [ method ] ** * Adds event handler for mousemove for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.unmousemove [ method ] ** * Removes event handler for mousemove for the element. > Parameters - handler (function) #optional handler for the event = (object) @Element \*/ /*\ * Element.mouseout [ method ] ** * Adds event handler for mouseout for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.unmouseout [ method ] ** * Removes event handler for mouseout for the element. > Parameters - handler (function) #optional handler for the event = (object) @Element \*/ /*\ * Element.mouseover [ method ] ** * Adds event handler for mouseover for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.unmouseover [ method ] ** * Removes event handler for mouseover for the element. > Parameters - handler (function) #optional handler for the event = (object) @Element \*/ /*\ * Element.mouseup [ method ] ** * Adds event handler for mouseup for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.unmouseup [ method ] ** * Removes event handler for mouseup for the element. > Parameters - handler (function) #optional handler for the event = (object) @Element \*/ /*\ * Element.touchstart [ method ] ** * Adds event handler for touchstart for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.untouchstart [ method ] ** * Removes event handler for touchstart for the element. > Parameters - handler (function) #optional handler for the event = (object) @Element \*/ /*\ * Element.touchmove [ method ] ** * Adds event handler for touchmove for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.untouchmove [ method ] ** * Removes event handler for touchmove for the element. > Parameters - handler (function) #optional handler for the event = (object) @Element \*/ /*\ * Element.touchend [ method ] ** * Adds event handler for touchend for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.untouchend [ method ] ** * Removes event handler for touchend for the element. > Parameters - handler (function) #optional handler for the event = (object) @Element \*/ /*\ * Element.touchcancel [ method ] ** * Adds event handler for touchcancel for the element. > Parameters - handler (function) handler for the event = (object) @Element \*/ /*\ * Element.untouchcancel [ method ] ** * Removes event handler for touchcancel for the element. > Parameters - handler (function) #optional handler for the event = (object) @Element \*/ for (var i = events.length; i--;) { (function (eventName) { R[eventName] = elproto[eventName] = function (fn, scope) { if (R.is(fn, "function")) { this.events = this.events || []; this.events.push({name: eventName, f: fn, unbind: addEvent(this.shape || this.node || g.doc, eventName, fn, scope || this)}); } return this; }; R["un" + eventName] = elproto["un" + eventName] = function (fn) { var events = this.events || [], l = events.length; while (l--){ if (events[l].name == eventName && (R.is(fn, "undefined") || events[l].f == fn)) { events[l].unbind(); events.splice(l, 1); !events.length && delete this.events; } } return this; }; })(events[i]); } /*\ * Element.data [ method ] ** * Adds or retrieves given value asociated with given key. ** * See also @Element.removeData > Parameters - key (string) key to store data - value (any) #optional value to store = (object) @Element * or, if value is not specified: = (any) value * or, if key and value are not specified: = (object) Key/value pairs for all the data associated with the element. > Usage | for (var i = 0, i < 5, i++) { | paper.circle(10 + 15 * i, 10, 10) | .attr({fill: "#000"}) | .data("i", i) | .click(function () { | alert(this.data("i")); | }); | } \*/ elproto.data = function (key, value) { var data = eldata[this.id] = eldata[this.id] || {}; if (arguments.length == 0) { return data; } if (arguments.length == 1) { if (R.is(key, "object")) { for (var i in key) if (key[has](i)) { this.data(i, key[i]); } return this; } eve("raphael.data.get." + this.id, this, data[key], key); return data[key]; } data[key] = value; eve("raphael.data.set." + this.id, this, value, key); return this; }; /*\ * Element.removeData [ method ] ** * Removes value associated with an element by given key. * If key is not provided, removes all the data of the element. > Parameters - key (string) #optional key = (object) @Element \*/ elproto.removeData = function (key) { if (key == null) { eldata[this.id] = {}; } else { eldata[this.id] && delete eldata[this.id][key]; } return this; }; /*\ * Element.getData [ method ] ** * Retrieves the element data = (object) data \*/ elproto.getData = function () { return clone(eldata[this.id] || {}); }; /*\ * Element.hover [ method ] ** * Adds event handlers for hover for the element. > Parameters - f_in (function) handler for hover in - f_out (function) handler for hover out - icontext (object) #optional context for hover in handler - ocontext (object) #optional context for hover out handler = (object) @Element \*/ elproto.hover = function (f_in, f_out, scope_in, scope_out) { return this.mouseover(f_in, scope_in).mouseout(f_out, scope_out || scope_in); }; /*\ * Element.unhover [ method ] ** * Removes event handlers for hover for the element. > Parameters - f_in (function) handler for hover in - f_out (function) handler for hover out = (object) @Element \*/ elproto.unhover = function (f_in, f_out) { return this.unmouseover(f_in).unmouseout(f_out); }; var draggable = []; /*\ * Element.drag [ method ] ** * Adds event handlers for drag of the element. > Parameters - onmove (function) handler for moving - onstart (function) handler for drag start - onend (function) handler for drag end - mcontext (object) #optional context for moving handler - scontext (object) #optional context for drag start handler - econtext (object) #optional context for drag end handler * Additionaly following `drag` events will be triggered: `drag.start.<id>` on start, * `drag.end.<id>` on end and `drag.move.<id>` on every move. When element will be dragged over another element * `drag.over.<id>` will be fired as well. * * Start event and start handler will be called in specified context or in context of the element with following parameters: o x (number) x position of the mouse o y (number) y position of the mouse o event (object) DOM event object * Move event and move handler will be called in specified context or in context of the element with following parameters: o dx (number) shift by x from the start point o dy (number) shift by y from the start point o x (number) x position of the mouse o y (number) y position of the mouse o event (object) DOM event object * End event and end handler will be called in specified context or in context of the element with following parameters: o event (object) DOM event object = (object) @Element \*/ elproto.drag = function (onmove, onstart, onend, move_scope, start_scope, end_scope) { function start(e) { (e.originalEvent || e).preventDefault(); var x = e.clientX, y = e.clientY, scrollY = g.doc.documentElement.scrollTop || g.doc.body.scrollTop, scrollX = g.doc.documentElement.scrollLeft || g.doc.body.scrollLeft; this._drag.id = e.identifier; if (supportsTouch && e.touches) { var i = e.touches.length, touch; while (i--) { touch = e.touches[i]; this._drag.id = touch.identifier; if (touch.identifier == this._drag.id) { x = touch.clientX; y = touch.clientY; break; } } } this._drag.x = x + scrollX; this._drag.y = y + scrollY; !drag.length && R.mousemove(dragMove).mouseup(dragUp); drag.push({el: this, move_scope: move_scope, start_scope: start_scope, end_scope: end_scope}); onstart && eve.on("raphael.drag.start." + this.id, onstart); onmove && eve.on("raphael.drag.move." + this.id, onmove); onend && eve.on("raphael.drag.end." + this.id, onend); eve("raphael.drag.start." + this.id, start_scope || move_scope || this, e.clientX + scrollX, e.clientY + scrollY, e); } this._drag = {}; draggable.push({el: this, start: start}); this.mousedown(start); return this; }; /*\ * Element.onDragOver [ method ] ** * Shortcut for assigning event handler for `drag.over.<id>` event, where id is id of the element (see @Element.id). > Parameters - f (function) handler for event, first argument would be the element you are dragging over \*/ elproto.onDragOver = function (f) { f ? eve.on("raphael.drag.over." + this.id, f) : eve.unbind("raphael.drag.over." + this.id); }; /*\ * Element.undrag [ method ] ** * Removes all drag event handlers from given element. \*/ elproto.undrag = function () { var i = draggable.length; while (i--) if (draggable[i].el == this) { this.unmousedown(draggable[i].start); draggable.splice(i, 1); eve.unbind("raphael.drag.*." + this.id); } !draggable.length && R.unmousemove(dragMove).unmouseup(dragUp); drag = []; }; /*\ * Paper.circle [ method ] ** * Draws a circle. ** > Parameters ** - x (number) x coordinate of the centre - y (number) y coordinate of the centre - r (number) radius = (object) Raphaël element object with type “circle” ** > Usage | var c = paper.circle(50, 50, 40); \*/ paperproto.circle = function (x, y, r) { var out = R._engine.circle(this, x || 0, y || 0, r || 0); this.__set__ && this.__set__.push(out); return out; }; /*\ * Paper.rect [ method ] * * Draws a rectangle. ** > Parameters ** - x (number) x coordinate of the top left corner - y (number) y coordinate of the top left corner - width (number) width - height (number) height - r (number) #optional radius for rounded corners, default is 0 = (object) Raphaël element object with type “rect” ** > Usage | // regular rectangle | var c = paper.rect(10, 10, 50, 50); | // rectangle with rounded corners | var c = paper.rect(40, 40, 50, 50, 10); \*/ paperproto.rect = function (x, y, w, h, r) { var out = R._engine.rect(this, x || 0, y || 0, w || 0, h || 0, r || 0); this.__set__ && this.__set__.push(out); return out; }; /*\ * Paper.ellipse [ method ] ** * Draws an ellipse. ** > Parameters ** - x (number) x coordinate of the centre - y (number) y coordinate of the centre - rx (number) horizontal radius - ry (number) vertical radius = (object) Raphaël element object with type “ellipse” ** > Usage | var c = paper.ellipse(50, 50, 40, 20); \*/ paperproto.ellipse = function (x, y, rx, ry) { var out = R._engine.ellipse(this, x || 0, y || 0, rx || 0, ry || 0); this.__set__ && this.__set__.push(out); return out; }; /*\ * Paper.path [ method ] ** * Creates a path element by given path data string. > Parameters - pathString (string) #optional path string in SVG format. * Path string consists of one-letter commands, followed by comma seprarated arguments in numercal form. Example: | "M10,20L30,40" * Here we can see two commands: “M”, with arguments `(10, 20)` and “L” with arguments `(30, 40)`. Upper case letter mean command is absolute, lower case—relative. * # <p>Here is short list of commands available, for more details see <a href="http://www.w3.org/TR/SVG/paths.html#PathData" title="Details of a path's data attribute's format are described in the SVG specification.">SVG path string format</a>.</p> # <table><thead><tr><th>Command</th><th>Name</th><th>Parameters</th></tr></thead><tbody> # <tr><td>M</td><td>moveto</td><td>(x y)+</td></tr> # <tr><td>Z</td><td>closepath</td><td>(none)</td></tr> # <tr><td>L</td><td>lineto</td><td>(x y)+</td></tr> # <tr><td>H</td><td>horizontal lineto</td><td>x+</td></tr> # <tr><td>V</td><td>vertical lineto</td><td>y+</td></tr> # <tr><td>C</td><td>curveto</td><td>(x1 y1 x2 y2 x y)+</td></tr> # <tr><td>S</td><td>smooth curveto</td><td>(x2 y2 x y)+</td></tr> # <tr><td>Q</td><td>quadratic Bézier curveto</td><td>(x1 y1 x y)+</td></tr> # <tr><td>T</td><td>smooth quadratic Bézier curveto</td><td>(x y)+</td></tr> # <tr><td>A</td><td>elliptical arc</td><td>(rx ry x-axis-rotation large-arc-flag sweep-flag x y)+</td></tr> # <tr><td>R</td><td><a href="http://en.wikipedia.org/wiki/Catmull–Rom_spline#Catmull.E2.80.93Rom_spline">Catmull-Rom curveto</a>*</td><td>x1 y1 (x y)+</td></tr></tbody></table> * * “Catmull-Rom curveto” is a not standard SVG command and added in 2.0 to make life easier. * Note: there is a special case when path consist of just three commands: “M10,10R…z”. In this case path will smoothly connects to its beginning. > Usage | var c = paper.path("M10 10L90 90"); | // draw a diagonal line: | // move to 10,10, line to 90,90 * For example of path strings, check out these icons: http://raphaeljs.com/icons/ \*/ paperproto.path = function (pathString) { pathString && !R.is(pathString, string) && !R.is(pathString[0], array) && (pathString += E); var out = R._engine.path(R.format[apply](R, arguments), this); this.__set__ && this.__set__.push(out); return out; }; /*\ * Paper.image [ method ] ** * Embeds an image into the surface. ** > Parameters ** - src (string) URI of the source image - x (number) x coordinate position - y (number) y coordinate position - width (number) width of the image - height (number) height of the image = (object) Raphaël element object with type “image” ** > Usage | var c = paper.image("apple.png", 10, 10, 80, 80); \*/ paperproto.image = function (src, x, y, w, h) { var out = R._engine.image(this, src || "about:blank", x || 0, y || 0, w || 0, h || 0); this.__set__ && this.__set__.push(out); return out; }; /*\ * Paper.text [ method ] ** * Draws a text string. If you need line breaks, put “\n” in the string. ** > Parameters ** - x (number) x coordinate position - y (number) y coordinate position - text (string) The text string to draw = (object) Raphaël element object with type “text” ** > Usage | var t = paper.text(50, 50, "Raphaël\nkicks\nbutt!"); \*/ paperproto.text = function (x, y, text) { var out = R._engine.text(this, x || 0, y || 0, Str(text)); this.__set__ && this.__set__.push(out); return out; }; /*\ * Paper.set [ method ] ** * Creates array-like object to keep and operate several elements at once. * Warning: it doesn’t create any elements for itself in the page, it just groups existing elements. * Sets act as pseudo elements — all methods available to an element can be used on a set. = (object) array-like object that represents set of elements ** > Usage | var st = paper.set(); | st.push( | paper.circle(10, 10, 5), | paper.circle(30, 10, 5) | ); | st.attr({fill: "red"}); // changes the fill of both circles \*/ paperproto.set = function (itemsArray) { !R.is(itemsArray, "array") && (itemsArray = Array.prototype.splice.call(arguments, 0, arguments.length)); var out = new Set(itemsArray); this.__set__ && this.__set__.push(out); out["paper"] = this; out["type"] = "set"; return out; }; /*\ * Paper.setStart [ method ] ** * Creates @Paper.set. All elements that will be created after calling this method and before calling * @Paper.setFinish will be added to the set. ** > Usage | paper.setStart(); | paper.circle(10, 10, 5), | paper.circle(30, 10, 5) | var st = paper.setFinish(); | st.attr({fill: "red"}); // changes the fill of both circles \*/ paperproto.setStart = function (set) { this.__set__ = set || this.set(); }; /*\ * Paper.setFinish [ method ] ** * See @Paper.setStart. This method finishes catching and returns resulting set. ** = (object) set \*/ paperproto.setFinish = function (set) { var out = this.__set__; delete this.__set__; return out; }; /*\ * Paper.setSize [ method ] ** * If you need to change dimensions of the canvas call this method ** > Parameters ** - width (number) new width of the canvas - height (number) new height of the canvas \*/ paperproto.setSize = function (width, height) { return R._engine.setSize.call(this, width, height); }; /*\ * Paper.setViewBox [ method ] ** * Sets the view box of the paper. Practically it gives you ability to zoom and pan whole paper surface by * specifying new boundaries. ** > Parameters ** - x (number) new x position, default is `0` - y (number) new y position, default is `0` - w (number) new width of the canvas - h (number) new height of the canvas - fit (boolean) `true` if you want graphics to fit into new boundary box \*/ paperproto.setViewBox = function (x, y, w, h, fit) { return R._engine.setViewBox.call(this, x, y, w, h, fit); }; /*\ * Paper.top [ property ] ** * Points to the topmost element on the paper \*/ /*\ * Paper.bottom [ property ] ** * Points to the bottom element on the paper \*/ paperproto.top = paperproto.bottom = null; /*\ * Paper.raphael [ property ] ** * Points to the @Raphael object/function \*/ paperproto.raphael = R; var getOffset = function (elem) { var box = elem.getBoundingClientRect(), doc = elem.ownerDocument, body = doc.body, docElem = doc.documentElement, clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0, top = box.top + (g.win.pageYOffset || docElem.scrollTop || body.scrollTop ) - clientTop, left = box.left + (g.win.pageXOffset || docElem.scrollLeft || body.scrollLeft) - clientLeft; return { y: top, x: left }; }; /*\ * Paper.getElementByPoint [ method ] ** * Returns you topmost element under given point. ** = (object) Raphaël element object > Parameters ** - x (number) x coordinate from the top left corner of the window - y (number) y coordinate from the top left corner of the window > Usage | paper.getElementByPoint(mouseX, mouseY).attr({stroke: "#f00"}); \*/ paperproto.getElementByPoint = function (x, y) { var paper = this, svg = paper.canvas, target = g.doc.elementFromPoint(x, y); if (g.win.opera && target.tagName == "svg") { var so = getOffset(svg), sr = svg.createSVGRect(); sr.x = x - so.x; sr.y = y - so.y; sr.width = sr.height = 1; var hits = svg.getIntersectionList(sr, null); if (hits.length) { target = hits[hits.length - 1]; } } if (!target) { return null; } while (target.parentNode && target != svg.parentNode && !target.raphael) { target = target.parentNode; } target == paper.canvas.parentNode && (target = svg); target = target && target.raphael ? paper.getById(target.raphaelid) : null; return target; }; /*\ * Paper.getElementsByBBox [ method ] ** * Returns set of elements that have an intersecting bounding box ** > Parameters ** - bbox (object) bbox to check with = (object) @Set \*/ paperproto.getElementsByBBox = function (bbox) { var set = this.set(); this.forEach(function (el) { if (R.isBBoxIntersect(el.getBBox(), bbox)) { set.push(el); } }); return set; }; /*\ * Paper.getById [ method ] ** * Returns you element by its internal ID. ** > Parameters ** - id (number) id = (object) Raphaël element object \*/ paperproto.getById = function (id) { var bot = this.bottom; while (bot) { if (bot.id == id) { return bot; } bot = bot.next; } return null; }; /*\ * Paper.forEach [ method ] ** * Executes given function for each element on the paper * * If callback function returns `false` it will stop loop running. ** > Parameters ** - callback (function) function to run - thisArg (object) context object for the callback = (object) Paper object > Usage | paper.forEach(function (el) { | el.attr({ stroke: "blue" }); | }); \*/ paperproto.forEach = function (callback, thisArg) { var bot = this.bottom; while (bot) { if (callback.call(thisArg, bot) === false) { return this; } bot = bot.next; } return this; }; /*\ * Paper.getElementsByPoint [ method ] ** * Returns set of elements that have common point inside ** > Parameters ** - x (number) x coordinate of the point - y (number) y coordinate of the point = (object) @Set \*/ paperproto.getElementsByPoint = function (x, y) { var set = this.set(); this.forEach(function (el) { if (el.isPointInside(x, y)) { set.push(el); } }); return set; }; function x_y() { return this.x + S + this.y; } function x_y_w_h() { return this.x + S + this.y + S + this.width + " \xd7 " + this.height; } /*\ * Element.isPointInside [ method ] ** * Determine if given point is inside this element’s shape ** > Parameters ** - x (number) x coordinate of the point - y (number) y coordinate of the point = (boolean) `true` if point inside the shape \*/ elproto.isPointInside = function (x, y) { var rp = this.realPath = getPath[this.type](this); if (this.attr('transform') && this.attr('transform').length) { rp = R.transformPath(rp, this.attr('transform')); } return R.isPointInsidePath(rp, x, y); }; /*\ * Element.getBBox [ method ] ** * Return bounding box for a given element ** > Parameters ** - isWithoutTransform (boolean) flag, `true` if you want to have bounding box before transformations. Default is `false`. = (object) Bounding box object: o { o x: (number) top left corner x o y: (number) top left corner y o x2: (number) bottom right corner x o y2: (number) bottom right corner y o width: (number) width o height: (number) height o } \*/ elproto.getBBox = function (isWithoutTransform) { if (this.removed) { return {}; } var _ = this._; if (isWithoutTransform) { if (_.dirty || !_.bboxwt) { this.realPath = getPath[this.type](this); _.bboxwt = pathDimensions(this.realPath); _.bboxwt.toString = x_y_w_h; _.dirty = 0; } return _.bboxwt; } if (_.dirty || _.dirtyT || !_.bbox) { if (_.dirty || !this.realPath) { _.bboxwt = 0; this.realPath = getPath[this.type](this); } _.bbox = pathDimensions(mapPath(this.realPath, this.matrix)); _.bbox.toString = x_y_w_h; _.dirty = _.dirtyT = 0; } return _.bbox; }; /*\ * Element.clone [ method ] ** = (object) clone of a given element ** \*/ elproto.clone = function () { if (this.removed) { return null; } var out = this.paper[this.type]().attr(this.attr()); this.__set__ && this.__set__.push(out); return out; }; /*\ * Element.glow [ method ] ** * Return set of elements that create glow-like effect around given element. See @Paper.set. * * Note: Glow is not connected to the element. If you change element attributes it won’t adjust itself. ** > Parameters ** - glow (object) #optional parameters object with all properties optional: o { o width (number) size of the glow, default is `10` o fill (boolean) will it be filled, default is `false` o opacity (number) opacity, default is `0.5` o offsetx (number) horizontal offset, default is `0` o offsety (number) vertical offset, default is `0` o color (string) glow colour, default is `black` o } = (object) @Paper.set of elements that represents glow \*/ elproto.glow = function (glow) { if (this.type == "text") { return null; } glow = glow || {}; var s = { width: (glow.width || 10) + (+this.attr("stroke-width") || 1), fill: glow.fill || false, opacity: glow.opacity || .5, offsetx: glow.offsetx || 0, offsety: glow.offsety || 0, color: glow.color || "#000" }, c = s.width / 2, r = this.paper, out = r.set(), path = this.realPath || getPath[this.type](this); path = this.matrix ? mapPath(path, this.matrix) : path; for (var i = 1; i < c + 1; i++) { out.push(r.path(path).attr({ stroke: s.color, fill: s.fill ? s.color : "none", "stroke-linejoin": "round", "stroke-linecap": "round", "stroke-width": +(s.width / c * i).toFixed(3), opacity: +(s.opacity / c).toFixed(3) })); } return out.insertBefore(this).translate(s.offsetx, s.offsety); }; var curveslengths = {}, getPointAtSegmentLength = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length) { if (length == null) { return bezlen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y); } else { return R.findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, getTatLen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length)); } }, getLengthFactory = function (istotal, subpath) { return function (path, length, onlystart) { path = path2curve(path); var x, y, p, l, sp = "", subpaths = {}, point, len = 0; for (var i = 0, ii = path.length; i < ii; i++) { p = path[i]; if (p[0] == "M") { x = +p[1]; y = +p[2]; } else { l = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6]); if (len + l > length) { if (subpath && !subpaths.start) { point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len); sp += ["C" + point.start.x, point.start.y, point.m.x, point.m.y, point.x, point.y]; if (onlystart) {return sp;} subpaths.start = sp; sp = ["M" + point.x, point.y + "C" + point.n.x, point.n.y, point.end.x, point.end.y, p[5], p[6]].join(); len += l; x = +p[5]; y = +p[6]; continue; } if (!istotal && !subpath) { point = getPointAtSegmentLength(x, y, p[1], p[2], p[3], p[4], p[5], p[6], length - len); return {x: point.x, y: point.y, alpha: point.alpha}; } } len += l; x = +p[5]; y = +p[6]; } sp += p.shift() + p; } subpaths.end = sp; point = istotal ? len : subpath ? subpaths : R.findDotsAtSegment(x, y, p[0], p[1], p[2], p[3], p[4], p[5], 1); point.alpha && (point = {x: point.x, y: point.y, alpha: point.alpha}); return point; }; }; var getTotalLength = getLengthFactory(1), getPointAtLength = getLengthFactory(), getSubpathsAtLength = getLengthFactory(0, 1); /*\ * Raphael.getTotalLength [ method ] ** * Returns length of the given path in pixels. ** > Parameters ** - path (string) SVG path string. ** = (number) length. \*/ R.getTotalLength = getTotalLength; /*\ * Raphael.getPointAtLength [ method ] ** * Return coordinates of the point located at the given length on the given path. ** > Parameters ** - path (string) SVG path string - length (number) ** = (object) representation of the point: o { o x: (number) x coordinate o y: (number) y coordinate o alpha: (number) angle of derivative o } \*/ R.getPointAtLength = getPointAtLength; /*\ * Raphael.getSubpath [ method ] ** * Return subpath of a given path from given length to given length. ** > Parameters ** - path (string) SVG path string - from (number) position of the start of the segment - to (number) position of the end of the segment ** = (string) pathstring for the segment \*/ R.getSubpath = function (path, from, to) { if (this.getTotalLength(path) - to < 1e-6) { return getSubpathsAtLength(path, from).end; } var a = getSubpathsAtLength(path, to, 1); return from ? getSubpathsAtLength(a, from).end : a; }; /*\ * Element.getTotalLength [ method ] ** * Returns length of the path in pixels. Only works for element of “path” type. = (number) length. \*/ elproto.getTotalLength = function () { var path = this.getPath(); if (!path) { return; } if (this.node.getTotalLength) { return this.node.getTotalLength(); } return getTotalLength(path); }; /*\ * Element.getPointAtLength [ method ] ** * Return coordinates of the point located at the given length on the given path. Only works for element of “path” type. ** > Parameters ** - length (number) ** = (object) representation of the point: o { o x: (number) x coordinate o y: (number) y coordinate o alpha: (number) angle of derivative o } \*/ elproto.getPointAtLength = function (length) { var path = this.getPath(); if (!path) { return; } return getPointAtLength(path, length); }; /*\ * Element.getPath [ method ] ** * Returns path of the element. Only works for elements of “path” type and simple elements like circle. = (object) path ** \*/ elproto.getPath = function () { var path, getPath = R._getPath[this.type]; if (this.type == "text" || this.type == "set") { return; } if (getPath) { path = getPath(this); } return path; }; /*\ * Element.getSubpath [ method ] ** * Return subpath of a given element from given length to given length. Only works for element of “path” type. ** > Parameters ** - from (number) position of the start of the segment - to (number) position of the end of the segment ** = (string) pathstring for the segment \*/ elproto.getSubpath = function (from, to) { var path = this.getPath(); if (!path) { return; } return R.getSubpath(path, from, to); }; /*\ * Raphael.easing_formulas [ property ] ** * Object that contains easing formulas for animation. You could extend it with your own. By default it has following list of easing: # <ul> # <li>“linear”</li> # <li>“&lt;” or “easeIn” or “ease-in”</li> # <li>“>” or “easeOut” or “ease-out”</li> # <li>“&lt;>” or “easeInOut” or “ease-in-out”</li> # <li>“backIn” or “back-in”</li> # <li>“backOut” or “back-out”</li> # <li>“elastic”</li> # <li>“bounce”</li> # </ul> # <p>See also <a href="http://raphaeljs.com/easing.html">Easing demo</a>.</p> \*/ var ef = R.easing_formulas = { linear: function (n) { return n; }, "<": function (n) { return pow(n, 1.7); }, ">": function (n) { return pow(n, .48); }, "<>": function (n) { var q = .48 - n / 1.04, Q = math.sqrt(.1734 + q * q), x = Q - q, X = pow(abs(x), 1 / 3) * (x < 0 ? -1 : 1), y = -Q - q, Y = pow(abs(y), 1 / 3) * (y < 0 ? -1 : 1), t = X + Y + .5; return (1 - t) * 3 * t * t + t * t * t; }, backIn: function (n) { var s = 1.70158; return n * n * ((s + 1) * n - s); }, backOut: function (n) { n = n - 1; var s = 1.70158; return n * n * ((s + 1) * n + s) + 1; }, elastic: function (n) { if (n == !!n) { return n; } return pow(2, -10 * n) * math.sin((n - .075) * (2 * PI) / .3) + 1; }, bounce: function (n) { var s = 7.5625, p = 2.75, l; if (n < (1 / p)) { l = s * n * n; } else { if (n < (2 / p)) { n -= (1.5 / p); l = s * n * n + .75; } else { if (n < (2.5 / p)) { n -= (2.25 / p); l = s * n * n + .9375; } else { n -= (2.625 / p); l = s * n * n + .984375; } } } return l; } }; ef.easeIn = ef["ease-in"] = ef["<"]; ef.easeOut = ef["ease-out"] = ef[">"]; ef.easeInOut = ef["ease-in-out"] = ef["<>"]; ef["back-in"] = ef.backIn; ef["back-out"] = ef.backOut; var animationElements = [], requestAnimFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) { setTimeout(callback, 16); }, animation = function () { var Now = +new Date, l = 0; for (; l < animationElements.length; l++) { var e = animationElements[l]; if (e.el.removed || e.paused) { continue; } var time = Now - e.start, ms = e.ms, easing = e.easing, from = e.from, diff = e.diff, to = e.to, t = e.t, that = e.el, set = {}, now, init = {}, key; if (e.initstatus) { time = (e.initstatus * e.anim.top - e.prev) / (e.percent - e.prev) * ms; e.status = e.initstatus; delete e.initstatus; e.stop && animationElements.splice(l--, 1); } else { e.status = (e.prev + (e.percent - e.prev) * (time / ms)) / e.anim.top; } if (time < 0) { continue; } if (time < ms) { var pos = easing(time / ms); for (var attr in from) if (from[has](attr)) { switch (availableAnimAttrs[attr]) { case nu: now = +from[attr] + pos * ms * diff[attr]; break; case "colour": now = "rgb(" + [ upto255(round(from[attr].r + pos * ms * diff[attr].r)), upto255(round(from[attr].g + pos * ms * diff[attr].g)), upto255(round(from[attr].b + pos * ms * diff[attr].b)) ].join(",") + ")"; break; case "path": now = []; for (var i = 0, ii = from[attr].length; i < ii; i++) { now[i] = [from[attr][i][0]]; for (var j = 1, jj = from[attr][i].length; j < jj; j++) { now[i][j] = +from[attr][i][j] + pos * ms * diff[attr][i][j]; } now[i] = now[i].join(S); } now = now.join(S); break; case "transform": if (diff[attr].real) { now = []; for (i = 0, ii = from[attr].length; i < ii; i++) { now[i] = [from[attr][i][0]]; for (j = 1, jj = from[attr][i].length; j < jj; j++) { now[i][j] = from[attr][i][j] + pos * ms * diff[attr][i][j]; } } } else { var get = function (i) { return +from[attr][i] + pos * ms * diff[attr][i]; }; // now = [["r", get(2), 0, 0], ["t", get(3), get(4)], ["s", get(0), get(1), 0, 0]]; now = [["m", get(0), get(1), get(2), get(3), get(4), get(5)]]; } break; case "csv": if (attr == "clip-rect") { now = []; i = 4; while (i--) { now[i] = +from[attr][i] + pos * ms * diff[attr][i]; } } break; default: var from2 = [][concat](from[attr]); now = []; i = that.paper.customAttributes[attr].length; while (i--) { now[i] = +from2[i] + pos * ms * diff[attr][i]; } break; } set[attr] = now; } that.attr(set); (function (id, that, anim) { setTimeout(function () { eve("raphael.anim.frame." + id, that, anim); }); })(that.id, that, e.anim); } else { (function(f, el, a) { setTimeout(function() { eve("raphael.anim.frame." + el.id, el, a); eve("raphael.anim.finish." + el.id, el, a); R.is(f, "function") && f.call(el); }); })(e.callback, that, e.anim); that.attr(to); animationElements.splice(l--, 1); if (e.repeat > 1 && !e.next) { for (key in to) if (to[has](key)) { init[key] = e.totalOrigin[key]; } e.el.attr(init); runAnimation(e.anim, e.el, e.anim.percents[0], null, e.totalOrigin, e.repeat - 1); } if (e.next && !e.stop) { runAnimation(e.anim, e.el, e.next, null, e.totalOrigin, e.repeat); } } } R.svg && that && that.paper && that.paper.safari(); animationElements.length && requestAnimFrame(animation); }, upto255 = function (color) { return color > 255 ? 255 : color < 0 ? 0 : color; }; /*\ * Element.animateWith [ method ] ** * Acts similar to @Element.animate, but ensure that given animation runs in sync with another given element. ** > Parameters ** - el (object) element to sync with - anim (object) animation to sync with - params (object) #optional final attributes for the element, see also @Element.attr - ms (number) #optional number of milliseconds for animation to run - easing (string) #optional easing type. Accept on of @Raphael.easing_formulas or CSS format: `cubic&#x2010;bezier(XX,&#160;XX,&#160;XX,&#160;XX)` - callback (function) #optional callback function. Will be called at the end of animation. * or - element (object) element to sync with - anim (object) animation to sync with - animation (object) #optional animation object, see @Raphael.animation ** = (object) original element \*/ elproto.animateWith = function (el, anim, params, ms, easing, callback) { var element = this; if (element.removed) { callback && callback.call(element); return element; } var a = params instanceof Animation ? params : R.animation(params, ms, easing, callback), x, y; runAnimation(a, element, a.percents[0], null, element.attr()); for (var i = 0, ii = animationElements.length; i < ii; i++) { if (animationElements[i].anim == anim && animationElements[i].el == el) { animationElements[ii - 1].start = animationElements[i].start; break; } } return element; // // // var a = params ? R.animation(params, ms, easing, callback) : anim, // status = element.status(anim); // return this.animate(a).status(a, status * anim.ms / a.ms); }; function CubicBezierAtTime(t, p1x, p1y, p2x, p2y, duration) { var cx = 3 * p1x, bx = 3 * (p2x - p1x) - cx, ax = 1 - cx - bx, cy = 3 * p1y, by = 3 * (p2y - p1y) - cy, ay = 1 - cy - by; function sampleCurveX(t) { return ((ax * t + bx) * t + cx) * t; } function solve(x, epsilon) { var t = solveCurveX(x, epsilon); return ((ay * t + by) * t + cy) * t; } function solveCurveX(x, epsilon) { var t0, t1, t2, x2, d2, i; for(t2 = x, i = 0; i < 8; i++) { x2 = sampleCurveX(t2) - x; if (abs(x2) < epsilon) { return t2; } d2 = (3 * ax * t2 + 2 * bx) * t2 + cx; if (abs(d2) < 1e-6) { break; } t2 = t2 - x2 / d2; } t0 = 0; t1 = 1; t2 = x; if (t2 < t0) { return t0; } if (t2 > t1) { return t1; } while (t0 < t1) { x2 = sampleCurveX(t2); if (abs(x2 - x) < epsilon) { return t2; } if (x > x2) { t0 = t2; } else { t1 = t2; } t2 = (t1 - t0) / 2 + t0; } return t2; } return solve(t, 1 / (200 * duration)); } elproto.onAnimation = function (f) { f ? eve.on("raphael.anim.frame." + this.id, f) : eve.unbind("raphael.anim.frame." + this.id); return this; }; function Animation(anim, ms) { var percents = [], newAnim = {}; this.ms = ms; this.times = 1; if (anim) { for (var attr in anim) if (anim[has](attr)) { newAnim[toFloat(attr)] = anim[attr]; percents.push(toFloat(attr)); } percents.sort(sortByNumber); } this.anim = newAnim; this.top = percents[percents.length - 1]; this.percents = percents; } /*\ * Animation.delay [ method ] ** * Creates a copy of existing animation object with given delay. ** > Parameters ** - delay (number) number of ms to pass between animation start and actual animation ** = (object) new altered Animation object | var anim = Raphael.animation({cx: 10, cy: 20}, 2e3); | circle1.animate(anim); // run the given animation immediately | circle2.animate(anim.delay(500)); // run the given animation after 500 ms \*/ Animation.prototype.delay = function (delay) { var a = new Animation(this.anim, this.ms); a.times = this.times; a.del = +delay || 0; return a; }; /*\ * Animation.repeat [ method ] ** * Creates a copy of existing animation object with given repetition. ** > Parameters ** - repeat (number) number iterations of animation. For infinite animation pass `Infinity` ** = (object) new altered Animation object \*/ Animation.prototype.repeat = function (times) { var a = new Animation(this.anim, this.ms); a.del = this.del; a.times = math.floor(mmax(times, 0)) || 1; return a; }; function runAnimation(anim, element, percent, status, totalOrigin, times) { percent = toFloat(percent); var params, isInAnim, isInAnimSet, percents = [], next, prev, timestamp, ms = anim.ms, from = {}, to = {}, diff = {}; if (status) { for (i = 0, ii = animationElements.length; i < ii; i++) { var e = animationElements[i]; if (e.el.id == element.id && e.anim == anim) { if (e.percent != percent) { animationElements.splice(i, 1); isInAnimSet = 1; } else { isInAnim = e; } element.attr(e.totalOrigin); break; } } } else { status = +to; // NaN } for (var i = 0, ii = anim.percents.length; i < ii; i++) { if (anim.percents[i] == percent || anim.percents[i] > status * anim.top) { percent = anim.percents[i]; prev = anim.percents[i - 1] || 0; ms = ms / anim.top * (percent - prev); next = anim.percents[i + 1]; params = anim.anim[percent]; break; } else if (status) { element.attr(anim.anim[anim.percents[i]]); } } if (!params) { return; } if (!isInAnim) { for (var attr in params) if (params[has](attr)) { if (availableAnimAttrs[has](attr) || element.paper.customAttributes[has](attr)) { from[attr] = element.attr(attr); (from[attr] == null) && (from[attr] = availableAttrs[attr]); to[attr] = params[attr]; switch (availableAnimAttrs[attr]) { case nu: diff[attr] = (to[attr] - from[attr]) / ms; break; case "colour": from[attr] = R.getRGB(from[attr]); var toColour = R.getRGB(to[attr]); diff[attr] = { r: (toColour.r - from[attr].r) / ms, g: (toColour.g - from[attr].g) / ms, b: (toColour.b - from[attr].b) / ms }; break; case "path": var pathes = path2curve(from[attr], to[attr]), toPath = pathes[1]; from[attr] = pathes[0]; diff[attr] = []; for (i = 0, ii = from[attr].length; i < ii; i++) { diff[attr][i] = [0]; for (var j = 1, jj = from[attr][i].length; j < jj; j++) { diff[attr][i][j] = (toPath[i][j] - from[attr][i][j]) / ms; } } break; case "transform": var _ = element._, eq = equaliseTransform(_[attr], to[attr]); if (eq) { from[attr] = eq.from; to[attr] = eq.to; diff[attr] = []; diff[attr].real = true; for (i = 0, ii = from[attr].length; i < ii; i++) { diff[attr][i] = [from[attr][i][0]]; for (j = 1, jj = from[attr][i].length; j < jj; j++) { diff[attr][i][j] = (to[attr][i][j] - from[attr][i][j]) / ms; } } } else { var m = (element.matrix || new Matrix), to2 = { _: {transform: _.transform}, getBBox: function () { return element.getBBox(1); } }; from[attr] = [ m.a, m.b, m.c, m.d, m.e, m.f ]; extractTransform(to2, to[attr]); to[attr] = to2._.transform; diff[attr] = [ (to2.matrix.a - m.a) / ms, (to2.matrix.b - m.b) / ms, (to2.matrix.c - m.c) / ms, (to2.matrix.d - m.d) / ms, (to2.matrix.e - m.e) / ms, (to2.matrix.f - m.f) / ms ]; // from[attr] = [_.sx, _.sy, _.deg, _.dx, _.dy]; // var to2 = {_:{}, getBBox: function () { return element.getBBox(); }}; // extractTransform(to2, to[attr]); // diff[attr] = [ // (to2._.sx - _.sx) / ms, // (to2._.sy - _.sy) / ms, // (to2._.deg - _.deg) / ms, // (to2._.dx - _.dx) / ms, // (to2._.dy - _.dy) / ms // ]; } break; case "csv": var values = Str(params[attr])[split](separator), from2 = Str(from[attr])[split](separator); if (attr == "clip-rect") { from[attr] = from2; diff[attr] = []; i = from2.length; while (i--) { diff[attr][i] = (values[i] - from[attr][i]) / ms; } } to[attr] = values; break; default: values = [][concat](params[attr]); from2 = [][concat](from[attr]); diff[attr] = []; i = element.paper.customAttributes[attr].length; while (i--) { diff[attr][i] = ((values[i] || 0) - (from2[i] || 0)) / ms; } break; } } } var easing = params.easing, easyeasy = R.easing_formulas[easing]; if (!easyeasy) { easyeasy = Str(easing).match(bezierrg); if (easyeasy && easyeasy.length == 5) { var curve = easyeasy; easyeasy = function (t) { return CubicBezierAtTime(t, +curve[1], +curve[2], +curve[3], +curve[4], ms); }; } else { easyeasy = pipe; } } timestamp = params.start || anim.start || +new Date; e = { anim: anim, percent: percent, timestamp: timestamp, start: timestamp + (anim.del || 0), status: 0, initstatus: status || 0, stop: false, ms: ms, easing: easyeasy, from: from, diff: diff, to: to, el: element, callback: params.callback, prev: prev, next: next, repeat: times || anim.times, origin: element.attr(), totalOrigin: totalOrigin }; animationElements.push(e); if (status && !isInAnim && !isInAnimSet) { e.stop = true; e.start = new Date - ms * status; if (animationElements.length == 1) { return animation(); } } if (isInAnimSet) { e.start = new Date - e.ms * status; } animationElements.length == 1 && requestAnimFrame(animation); } else { isInAnim.initstatus = status; isInAnim.start = new Date - isInAnim.ms * status; } eve("raphael.anim.start." + element.id, element, anim); } /*\ * Raphael.animation [ method ] ** * Creates an animation object that can be passed to the @Element.animate or @Element.animateWith methods. * See also @Animation.delay and @Animation.repeat methods. ** > Parameters ** - params (object) final attributes for the element, see also @Element.attr - ms (number) number of milliseconds for animation to run - easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic&#x2010;bezier(XX,&#160;XX,&#160;XX,&#160;XX)` - callback (function) #optional callback function. Will be called at the end of animation. ** = (object) @Animation \*/ R.animation = function (params, ms, easing, callback) { if (params instanceof Animation) { return params; } if (R.is(easing, "function") || !easing) { callback = callback || easing || null; easing = null; } params = Object(params); ms = +ms || 0; var p = {}, json, attr; for (attr in params) if (params[has](attr) && toFloat(attr) != attr && toFloat(attr) + "%" != attr) { json = true; p[attr] = params[attr]; } if (!json) { return new Animation(params, ms); } else { easing && (p.easing = easing); callback && (p.callback = callback); return new Animation({100: p}, ms); } }; /*\ * Element.animate [ method ] ** * Creates and starts animation for given element. ** > Parameters ** - params (object) final attributes for the element, see also @Element.attr - ms (number) number of milliseconds for animation to run - easing (string) #optional easing type. Accept one of @Raphael.easing_formulas or CSS format: `cubic&#x2010;bezier(XX,&#160;XX,&#160;XX,&#160;XX)` - callback (function) #optional callback function. Will be called at the end of animation. * or - animation (object) animation object, see @Raphael.animation ** = (object) original element \*/ elproto.animate = function (params, ms, easing, callback) { var element = this; if (element.removed) { callback && callback.call(element); return element; } var anim = params instanceof Animation ? params : R.animation(params, ms, easing, callback); runAnimation(anim, element, anim.percents[0], null, element.attr()); return element; }; /*\ * Element.setTime [ method ] ** * Sets the status of animation of the element in milliseconds. Similar to @Element.status method. ** > Parameters ** - anim (object) animation object - value (number) number of milliseconds from the beginning of the animation ** = (object) original element if `value` is specified * Note, that during animation following events are triggered: * * On each animation frame event `anim.frame.<id>`, on start `anim.start.<id>` and on end `anim.finish.<id>`. \*/ elproto.setTime = function (anim, value) { if (anim && value != null) { this.status(anim, mmin(value, anim.ms) / anim.ms); } return this; }; /*\ * Element.status [ method ] ** * Gets or sets the status of animation of the element. ** > Parameters ** - anim (object) #optional animation object - value (number) #optional 0 – 1. If specified, method works like a setter and sets the status of a given animation to the value. This will cause animation to jump to the given position. ** = (number) status * or = (array) status if `anim` is not specified. Array of objects in format: o { o anim: (object) animation object o status: (number) status o } * or = (object) original element if `value` is specified \*/ elproto.status = function (anim, value) { var out = [], i = 0, len, e; if (value != null) { runAnimation(anim, this, -1, mmin(value, 1)); return this; } else { len = animationElements.length; for (; i < len; i++) { e = animationElements[i]; if (e.el.id == this.id && (!anim || e.anim == anim)) { if (anim) { return e.status; } out.push({ anim: e.anim, status: e.status }); } } if (anim) { return 0; } return out; } }; /*\ * Element.pause [ method ] ** * Stops animation of the element with ability to resume it later on. ** > Parameters ** - anim (object) #optional animation object ** = (object) original element \*/ elproto.pause = function (anim) { for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) { if (eve("raphael.anim.pause." + this.id, this, animationElements[i].anim) !== false) { animationElements[i].paused = true; } } return this; }; /*\ * Element.resume [ method ] ** * Resumes animation if it was paused with @Element.pause method. ** > Parameters ** - anim (object) #optional animation object ** = (object) original element \*/ elproto.resume = function (anim) { for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) { var e = animationElements[i]; if (eve("raphael.anim.resume." + this.id, this, e.anim) !== false) { delete e.paused; this.status(e.anim, e.status); } } return this; }; /*\ * Element.stop [ method ] ** * Stops animation of the element. ** > Parameters ** - anim (object) #optional animation object ** = (object) original element \*/ elproto.stop = function (anim) { for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) { if (eve("raphael.anim.stop." + this.id, this, animationElements[i].anim) !== false) { animationElements.splice(i--, 1); } } return this; }; function stopAnimation(paper) { for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.paper == paper) { animationElements.splice(i--, 1); } } eve.on("raphael.remove", stopAnimation); eve.on("raphael.clear", stopAnimation); elproto.toString = function () { return "Rapha\xebl\u2019s object"; }; // Set var Set = function (items) { this.items = []; this.length = 0; this.type = "set"; if (items) { for (var i = 0, ii = items.length; i < ii; i++) { if (items[i] && (items[i].constructor == elproto.constructor || items[i].constructor == Set)) { this[this.items.length] = this.items[this.items.length] = items[i]; this.length++; } } } }, setproto = Set.prototype; /*\ * Set.push [ method ] ** * Adds each argument to the current set. = (object) original element \*/ setproto.push = function () { var item, len; for (var i = 0, ii = arguments.length; i < ii; i++) { item = arguments[i]; if (item && (item.constructor == elproto.constructor || item.constructor == Set)) { len = this.items.length; this[len] = this.items[len] = item; this.length++; } } return this; }; /*\ * Set.pop [ method ] ** * Removes last element and returns it. = (object) element \*/ setproto.pop = function () { this.length && delete this[this.length--]; return this.items.pop(); }; /*\ * Set.forEach [ method ] ** * Executes given function for each element in the set. * * If function returns `false` it will stop loop running. ** > Parameters ** - callback (function) function to run - thisArg (object) context object for the callback = (object) Set object \*/ setproto.forEach = function (callback, thisArg) { for (var i = 0, ii = this.items.length; i < ii; i++) { if (callback.call(thisArg, this.items[i], i) === false) { return this; } } return this; }; for (var method in elproto) if (elproto[has](method)) { setproto[method] = (function (methodname) { return function () { var arg = arguments; return this.forEach(function (el) { el[methodname][apply](el, arg); }); }; })(method); } setproto.attr = function (name, value) { if (name && R.is(name, array) && R.is(name[0], "object")) { for (var j = 0, jj = name.length; j < jj; j++) { this.items[j].attr(name[j]); } } else { for (var i = 0, ii = this.items.length; i < ii; i++) { this.items[i].attr(name, value); } } return this; }; /*\ * Set.clear [ method ] ** * Removeds all elements from the set \*/ setproto.clear = function () { while (this.length) { this.pop(); } }; /*\ * Set.splice [ method ] ** * Removes given element from the set ** > Parameters ** - index (number) position of the deletion - count (number) number of element to remove - insertion… (object) #optional elements to insert = (object) set elements that were deleted \*/ setproto.splice = function (index, count, insertion) { index = index < 0 ? mmax(this.length + index, 0) : index; count = mmax(0, mmin(this.length - index, count)); var tail = [], todel = [], args = [], i; for (i = 2; i < arguments.length; i++) { args.push(arguments[i]); } for (i = 0; i < count; i++) { todel.push(this[index + i]); } for (; i < this.length - index; i++) { tail.push(this[index + i]); } var arglen = args.length; for (i = 0; i < arglen + tail.length; i++) { this.items[index + i] = this[index + i] = i < arglen ? args[i] : tail[i - arglen]; } i = this.items.length = this.length -= count - arglen; while (this[i]) { delete this[i++]; } return new Set(todel); }; /*\ * Set.exclude [ method ] ** * Removes given element from the set ** > Parameters ** - element (object) element to remove = (boolean) `true` if object was found & removed from the set \*/ setproto.exclude = function (el) { for (var i = 0, ii = this.length; i < ii; i++) if (this[i] == el) { this.splice(i, 1); return true; } }; setproto.animate = function (params, ms, easing, callback) { (R.is(easing, "function") || !easing) && (callback = easing || null); var len = this.items.length, i = len, item, set = this, collector; if (!len) { return this; } callback && (collector = function () { !--len && callback.call(set); }); easing = R.is(easing, string) ? easing : collector; var anim = R.animation(params, ms, easing, collector); item = this.items[--i].animate(anim); while (i--) { this.items[i] && !this.items[i].removed && this.items[i].animateWith(item, anim, anim); (this.items[i] && !this.items[i].removed) || len--; } return this; }; setproto.insertAfter = function (el) { var i = this.items.length; while (i--) { this.items[i].insertAfter(el); } return this; }; setproto.getBBox = function () { var x = [], y = [], x2 = [], y2 = []; for (var i = this.items.length; i--;) if (!this.items[i].removed) { var box = this.items[i].getBBox(); x.push(box.x); y.push(box.y); x2.push(box.x + box.width); y2.push(box.y + box.height); } x = mmin[apply](0, x); y = mmin[apply](0, y); x2 = mmax[apply](0, x2); y2 = mmax[apply](0, y2); return { x: x, y: y, x2: x2, y2: y2, width: x2 - x, height: y2 - y }; }; setproto.clone = function (s) { s = this.paper.set(); for (var i = 0, ii = this.items.length; i < ii; i++) { s.push(this.items[i].clone()); } return s; }; setproto.toString = function () { return "Rapha\xebl\u2018s set"; }; setproto.glow = function(glowConfig) { var ret = this.paper.set(); this.forEach(function(shape, index){ var g = shape.glow(glowConfig); if(g != null){ g.forEach(function(shape2, index2){ ret.push(shape2); }); } }); return ret; }; /*\ * Set.isPointInside [ method ] ** * Determine if given point is inside this set’s elements ** > Parameters ** - x (number) x coordinate of the point - y (number) y coordinate of the point = (boolean) `true` if point is inside any of the set's elements \*/ setproto.isPointInside = function (x, y) { var isPointInside = false; this.forEach(function (el) { if (el.isPointInside(x, y)) { console.log('runned'); isPointInside = true; return false; // stop loop } }); return isPointInside; }; /*\ * Raphael.registerFont [ method ] ** * Adds given font to the registered set of fonts for Raphaël. Should be used as an internal call from within Cufón’s font file. * Returns original parameter, so it could be used with chaining. # <a href="http://wiki.github.com/sorccu/cufon/about">More about Cufón and how to convert your font form TTF, OTF, etc to JavaScript file.</a> ** > Parameters ** - font (object) the font to register = (object) the font you passed in > Usage | Cufon.registerFont(Raphael.registerFont({…})); \*/ R.registerFont = function (font) { if (!font.face) { return font; } this.fonts = this.fonts || {}; var fontcopy = { w: font.w, face: {}, glyphs: {} }, family = font.face["font-family"]; for (var prop in font.face) if (font.face[has](prop)) { fontcopy.face[prop] = font.face[prop]; } if (this.fonts[family]) { this.fonts[family].push(fontcopy); } else { this.fonts[family] = [fontcopy]; } if (!font.svg) { fontcopy.face["units-per-em"] = toInt(font.face["units-per-em"], 10); for (var glyph in font.glyphs) if (font.glyphs[has](glyph)) { var path = font.glyphs[glyph]; fontcopy.glyphs[glyph] = { w: path.w, k: {}, d: path.d && "M" + path.d.replace(/[mlcxtrv]/g, function (command) { return {l: "L", c: "C", x: "z", t: "m", r: "l", v: "c"}[command] || "M"; }) + "z" }; if (path.k) { for (var k in path.k) if (path[has](k)) { fontcopy.glyphs[glyph].k[k] = path.k[k]; } } } } return font; }; /*\ * Paper.getFont [ method ] ** * Finds font object in the registered fonts by given parameters. You could specify only one word from the font name, like “Myriad” for “Myriad Pro”. ** > Parameters ** - family (string) font family name or any word from it - weight (string) #optional font weight - style (string) #optional font style - stretch (string) #optional font stretch = (object) the font object > Usage | paper.print(100, 100, "Test string", paper.getFont("Times", 800), 30); \*/ paperproto.getFont = function (family, weight, style, stretch) { stretch = stretch || "normal"; style = style || "normal"; weight = +weight || {normal: 400, bold: 700, lighter: 300, bolder: 800}[weight] || 400; if (!R.fonts) { return; } var font = R.fonts[family]; if (!font) { var name = new RegExp("(^|\\s)" + family.replace(/[^\w\d\s+!~.:_-]/g, E) + "(\\s|$)", "i"); for (var fontName in R.fonts) if (R.fonts[has](fontName)) { if (name.test(fontName)) { font = R.fonts[fontName]; break; } } } var thefont; if (font) { for (var i = 0, ii = font.length; i < ii; i++) { thefont = font[i]; if (thefont.face["font-weight"] == weight && (thefont.face["font-style"] == style || !thefont.face["font-style"]) && thefont.face["font-stretch"] == stretch) { break; } } } return thefont; }; /*\ * Paper.print [ method ] ** * Creates path that represent given text written using given font at given position with given size. * Result of the method is path element that contains whole text as a separate path. ** > Parameters ** - x (number) x position of the text - y (number) y position of the text - string (string) text to print - font (object) font object, see @Paper.getFont - size (number) #optional size of the font, default is `16` - origin (string) #optional could be `"baseline"` or `"middle"`, default is `"middle"` - letter_spacing (number) #optional number in range `-1..1`, default is `0` - line_spacing (number) #optional number in range `1..3`, default is `1` = (object) resulting path element, which consist of all letters > Usage | var txt = r.print(10, 50, "print", r.getFont("Museo"), 30).attr({fill: "#fff"}); \*/ paperproto.print = function (x, y, string, font, size, origin, letter_spacing, line_spacing) { origin = origin || "middle"; // baseline|middle letter_spacing = mmax(mmin(letter_spacing || 0, 1), -1); line_spacing = mmax(mmin(line_spacing || 1, 3), 1); var letters = Str(string)[split](E), shift = 0, notfirst = 0, path = E, scale; R.is(font, "string") && (font = this.getFont(font)); if (font) { scale = (size || 16) / font.face["units-per-em"]; var bb = font.face.bbox[split](separator), top = +bb[0], lineHeight = bb[3] - bb[1], shifty = 0, height = +bb[1] + (origin == "baseline" ? lineHeight + (+font.face.descent) : lineHeight / 2); for (var i = 0, ii = letters.length; i < ii; i++) { if (letters[i] == "\n") { shift = 0; curr = 0; notfirst = 0; shifty += lineHeight * line_spacing; } else { var prev = notfirst && font.glyphs[letters[i - 1]] || {}, curr = font.glyphs[letters[i]]; shift += notfirst ? (prev.w || font.w) + (prev.k && prev.k[letters[i]] || 0) + (font.w * letter_spacing) : 0; notfirst = 1; } if (curr && curr.d) { path += R.transformPath(curr.d, ["t", shift * scale, shifty * scale, "s", scale, scale, top, height, "t", (x - top) / scale, (y - height) / scale]); } } } return this.path(path).attr({ fill: "#000", stroke: "none" }); }; /*\ * Paper.add [ method ] ** * Imports elements in JSON array in format `{type: type, <attributes>}` ** > Parameters ** - json (array) = (object) resulting set of imported elements > Usage | paper.add([ | { | type: "circle", | cx: 10, | cy: 10, | r: 5 | }, | { | type: "rect", | x: 10, | y: 10, | width: 10, | height: 10, | fill: "#fc0" | } | ]); \*/ paperproto.add = function (json) { if (R.is(json, "array")) { var res = this.set(), i = 0, ii = json.length, j; for (; i < ii; i++) { j = json[i] || {}; elements[has](j.type) && res.push(this[j.type]().attr(j)); } } return res; }; /*\ * Raphael.format [ method ] ** * Simple format function. Replaces construction of type “`{<number>}`” to the corresponding argument. ** > Parameters ** - token (string) string to format - … (string) rest of arguments will be treated as parameters for replacement = (string) formated string > Usage | var x = 10, | y = 20, | width = 40, | height = 50; | // this will draw a rectangular shape equivalent to "M10,20h40v50h-40z" | paper.path(Raphael.format("M{0},{1}h{2}v{3}h{4}z", x, y, width, height, -width)); \*/ R.format = function (token, params) { var args = R.is(params, array) ? [0][concat](params) : arguments; token && R.is(token, string) && args.length - 1 && (token = token.replace(formatrg, function (str, i) { return args[++i] == null ? E : args[i]; })); return token || E; }; /*\ * Raphael.fullfill [ method ] ** * A little bit more advanced format function than @Raphael.format. Replaces construction of type “`{<name>}`” to the corresponding argument. ** > Parameters ** - token (string) string to format - json (object) object which properties will be used as a replacement = (string) formated string > Usage | // this will draw a rectangular shape equivalent to "M10,20h40v50h-40z" | paper.path(Raphael.fullfill("M{x},{y}h{dim.width}v{dim.height}h{dim['negative width']}z", { | x: 10, | y: 20, | dim: { | width: 40, | height: 50, | "negative width": -40 | } | })); \*/ R.fullfill = (function () { var tokenRegex = /\{([^\}]+)\}/g, objNotationRegex = /(?:(?:^|\.)(.+?)(?=\[|\.|$|\()|\[('|")(.+?)\2\])(\(\))?/g, // matches .xxxxx or ["xxxxx"] to run over object properties replacer = function (all, key, obj) { var res = obj; key.replace(objNotationRegex, function (all, name, quote, quotedName, isFunc) { name = name || quotedName; if (res) { if (name in res) { res = res[name]; } typeof res == "function" && isFunc && (res = res()); } }); res = (res == null || res == obj ? all : res) + ""; return res; }; return function (str, obj) { return String(str).replace(tokenRegex, function (all, key) { return replacer(all, key, obj); }); }; })(); /*\ * Raphael.ninja [ method ] ** * If you want to leave no trace of Raphaël (Well, Raphaël creates only one global variable `Raphael`, but anyway.) You can use `ninja` method. * Beware, that in this case plugins could stop working, because they are depending on global variable existance. ** = (object) Raphael object > Usage | (function (local_raphael) { | var paper = local_raphael(10, 10, 320, 200); | … | })(Raphael.ninja()); \*/ R.ninja = function () { oldRaphael.was ? (g.win.Raphael = oldRaphael.is) : delete Raphael; return R; }; /*\ * Raphael.st [ property (object) ] ** * You can add your own method to elements and sets. It is wise to add a set method for each element method * you added, so you will be able to call the same method on sets too. ** * See also @Raphael.el. > Usage | Raphael.el.red = function () { | this.attr({fill: "#f00"}); | }; | Raphael.st.red = function () { | this.forEach(function (el) { | el.red(); | }); | }; | // then use it | paper.set(paper.circle(100, 100, 20), paper.circle(110, 100, 20)).red(); \*/ R.st = setproto; // Firefox <3.6 fix: http://webreflection.blogspot.com/2009/11/195-chars-to-help-lazy-loading.html (function (doc, loaded, f) { if (doc.readyState == null && doc.addEventListener){ doc.addEventListener(loaded, f = function () { doc.removeEventListener(loaded, f, false); doc.readyState = "complete"; }, false); doc.readyState = "loading"; } function isLoaded() { (/in/).test(doc.readyState) ? setTimeout(isLoaded, 9) : R.eve("raphael.DOMload"); } isLoaded(); })(document, "DOMContentLoaded"); eve.on("raphael.DOMload", function () { loaded = true; }); // ┌─────────────────────────────────────────────────────────────────────┐ \\ // │ Raphaël - JavaScript Vector Library │ \\ // ├─────────────────────────────────────────────────────────────────────┤ \\ // │ SVG Module │ \\ // ├─────────────────────────────────────────────────────────────────────┤ \\ // │ Copyright (c) 2008-2011 Dmitry Baranovskiy (http://raphaeljs.com) │ \\ // │ Copyright (c) 2008-2011 Sencha Labs (http://sencha.com) │ \\ // │ Licensed under the MIT (http://raphaeljs.com/license.html) license. │ \\ // └─────────────────────────────────────────────────────────────────────┘ \\ (function(){ if (!R.svg) { return; } var has = "hasOwnProperty", Str = String, toFloat = parseFloat, toInt = parseInt, math = Math, mmax = math.max, abs = math.abs, pow = math.pow, separator = /[, ]+/, eve = R.eve, E = "", S = " "; var xlink = "http://www.w3.org/1999/xlink", markers = { block: "M5,0 0,2.5 5,5z", classic: "M5,0 0,2.5 5,5 3.5,3 3.5,2z", diamond: "M2.5,0 5,2.5 2.5,5 0,2.5z", open: "M6,1 1,3.5 6,6", oval: "M2.5,0A2.5,2.5,0,0,1,2.5,5 2.5,2.5,0,0,1,2.5,0z" }, markerCounter = {}; R.toString = function () { return "Your browser supports SVG.\nYou are running Rapha\xebl " + this.version; }; var $ = function (el, attr) { if (attr) { if (typeof el == "string") { el = $(el); } for (var key in attr) if (attr[has](key)) { if (key.substring(0, 6) == "xlink:") { el.setAttributeNS(xlink, key.substring(6), Str(attr[key])); } else { el.setAttribute(key, Str(attr[key])); } } } else { el = R._g.doc.createElementNS("http://www.w3.org/2000/svg", el); el.style && (el.style.webkitTapHighlightColor = "rgba(0,0,0,0)"); } return el; }, addGradientFill = function (element, gradient) { var type = "linear", id = element.id + gradient, fx = .5, fy = .5, o = element.node, SVG = element.paper, s = o.style, el = R._g.doc.getElementById(id); if (!el) { gradient = Str(gradient).replace(R._radial_gradient, function (all, _fx, _fy) { type = "radial"; if (_fx && _fy) { fx = toFloat(_fx); fy = toFloat(_fy); var dir = ((fy > .5) * 2 - 1); pow(fx - .5, 2) + pow(fy - .5, 2) > .25 && (fy = math.sqrt(.25 - pow(fx - .5, 2)) * dir + .5) && fy != .5 && (fy = fy.toFixed(5) - 1e-5 * dir); } return E; }); gradient = gradient.split(/\s*\-\s*/); if (type == "linear") { var angle = gradient.shift(); angle = -toFloat(angle); if (isNaN(angle)) { return null; } var vector = [0, 0, math.cos(R.rad(angle)), math.sin(R.rad(angle))], max = 1 / (mmax(abs(vector[2]), abs(vector[3])) || 1); vector[2] *= max; vector[3] *= max; if (vector[2] < 0) { vector[0] = -vector[2]; vector[2] = 0; } if (vector[3] < 0) { vector[1] = -vector[3]; vector[3] = 0; } } var dots = R._parseDots(gradient); if (!dots) { return null; } id = id.replace(/[\(\)\s,\xb0#]/g, "_"); if (element.gradient && id != element.gradient.id) { SVG.defs.removeChild(element.gradient); delete element.gradient; } if (!element.gradient) { el = $(type + "Gradient", {id: id}); element.gradient = el; $(el, type == "radial" ? { fx: fx, fy: fy } : { x1: vector[0], y1: vector[1], x2: vector[2], y2: vector[3], gradientTransform: element.matrix.invert() }); SVG.defs.appendChild(el); for (var i = 0, ii = dots.length; i < ii; i++) { el.appendChild($("stop", { offset: dots[i].offset ? dots[i].offset : i ? "100%" : "0%", "stop-color": dots[i].color || "#fff" })); } } } $(o, { fill: "url(#" + id + ")", opacity: 1, "fill-opacity": 1 }); s.fill = E; s.opacity = 1; s.fillOpacity = 1; return 1; }, updatePosition = function (o) { var bbox = o.getBBox(1); $(o.pattern, {patternTransform: o.matrix.invert() + " translate(" + bbox.x + "," + bbox.y + ")"}); }, addArrow = function (o, value, isEnd) { if (o.type == "path") { var values = Str(value).toLowerCase().split("-"), p = o.paper, se = isEnd ? "end" : "start", node = o.node, attrs = o.attrs, stroke = attrs["stroke-width"], i = values.length, type = "classic", from, to, dx, refX, attr, w = 3, h = 3, t = 5; while (i--) { switch (values[i]) { case "block": case "classic": case "oval": case "diamond": case "open": case "none": type = values[i]; break; case "wide": h = 5; break; case "narrow": h = 2; break; case "long": w = 5; break; case "short": w = 2; break; } } if (type == "open") { w += 2; h += 2; t += 2; dx = 1; refX = isEnd ? 4 : 1; attr = { fill: "none", stroke: attrs.stroke }; } else { refX = dx = w / 2; attr = { fill: attrs.stroke, stroke: "none" }; } if (o._.arrows) { if (isEnd) { o._.arrows.endPath && markerCounter[o._.arrows.endPath]--; o._.arrows.endMarker && markerCounter[o._.arrows.endMarker]--; } else { o._.arrows.startPath && markerCounter[o._.arrows.startPath]--; o._.arrows.startMarker && markerCounter[o._.arrows.startMarker]--; } } else { o._.arrows = {}; } if (type != "none") { var pathId = "raphael-marker-" + type, markerId = "raphael-marker-" + se + type + w + h; if (!R._g.doc.getElementById(pathId)) { p.defs.appendChild($($("path"), { "stroke-linecap": "round", d: markers[type], id: pathId })); markerCounter[pathId] = 1; } else { markerCounter[pathId]++; } var marker = R._g.doc.getElementById(markerId), use; if (!marker) { marker = $($("marker"), { id: markerId, markerHeight: h, markerWidth: w, orient: "auto", refX: refX, refY: h / 2 }); use = $($("use"), { "xlink:href": "#" + pathId, transform: (isEnd ? "rotate(180 " + w / 2 + " " + h / 2 + ") " : E) + "scale(" + w / t + "," + h / t + ")", "stroke-width": (1 / ((w / t + h / t) / 2)).toFixed(4) }); marker.appendChild(use); p.defs.appendChild(marker); markerCounter[markerId] = 1; } else { markerCounter[markerId]++; use = marker.getElementsByTagName("use")[0]; } $(use, attr); var delta = dx * (type != "diamond" && type != "oval"); if (isEnd) { from = o._.arrows.startdx * stroke || 0; to = R.getTotalLength(attrs.path) - delta * stroke; } else { from = delta * stroke; to = R.getTotalLength(attrs.path) - (o._.arrows.enddx * stroke || 0); } attr = {}; attr["marker-" + se] = "url(#" + markerId + ")"; if (to || from) { attr.d = R.getSubpath(attrs.path, from, to); } $(node, attr); o._.arrows[se + "Path"] = pathId; o._.arrows[se + "Marker"] = markerId; o._.arrows[se + "dx"] = delta; o._.arrows[se + "Type"] = type; o._.arrows[se + "String"] = value; } else { if (isEnd) { from = o._.arrows.startdx * stroke || 0; to = R.getTotalLength(attrs.path) - from; } else { from = 0; to = R.getTotalLength(attrs.path) - (o._.arrows.enddx * stroke || 0); } o._.arrows[se + "Path"] && $(node, {d: R.getSubpath(attrs.path, from, to)}); delete o._.arrows[se + "Path"]; delete o._.arrows[se + "Marker"]; delete o._.arrows[se + "dx"]; delete o._.arrows[se + "Type"]; delete o._.arrows[se + "String"]; } for (attr in markerCounter) if (markerCounter[has](attr) && !markerCounter[attr]) { var item = R._g.doc.getElementById(attr); item && item.parentNode.removeChild(item); } } }, dasharray = { "": [0], "none": [0], "-": [3, 1], ".": [1, 1], "-.": [3, 1, 1, 1], "-..": [3, 1, 1, 1, 1, 1], ". ": [1, 3], "- ": [4, 3], "--": [8, 3], "- .": [4, 3, 1, 3], "--.": [8, 3, 1, 3], "--..": [8, 3, 1, 3, 1, 3] }, addDashes = function (o, value, params) { value = dasharray[Str(value).toLowerCase()]; if (value) { var width = o.attrs["stroke-width"] || "1", butt = {round: width, square: width, butt: 0}[o.attrs["stroke-linecap"] || params["stroke-linecap"]] || 0, dashes = [], i = value.length; while (i--) { dashes[i] = value[i] * width + ((i % 2) ? 1 : -1) * butt; } $(o.node, {"stroke-dasharray": dashes.join(",")}); } }, setFillAndStroke = function (o, params) { var node = o.node, attrs = o.attrs, vis = node.style.visibility; node.style.visibility = "hidden"; for (var att in params) { if (params[has](att)) { if (!R._availableAttrs[has](att)) { continue; } var value = params[att]; attrs[att] = value; switch (att) { case "blur": o.blur(value); break; case "href": case "title": var hl = $("title"); var val = R._g.doc.createTextNode(value); hl.appendChild(val); node.appendChild(hl); break; case "target": var pn = node.parentNode; if (pn.tagName.toLowerCase() != "a") { var hl = $("a"); pn.insertBefore(hl, node); hl.appendChild(node); pn = hl; } if (att == "target") { pn.setAttributeNS(xlink, "show", value == "blank" ? "new" : value); } else { pn.setAttributeNS(xlink, att, value); } break; case "cursor": node.style.cursor = value; break; case "transform": o.transform(value); break; case "arrow-start": addArrow(o, value); break; case "arrow-end": addArrow(o, value, 1); break; case "clip-rect": var rect = Str(value).split(separator); if (rect.length == 4) { o.clip && o.clip.parentNode.parentNode.removeChild(o.clip.parentNode); var el = $("clipPath"), rc = $("rect"); el.id = R.createUUID(); $(rc, { x: rect[0], y: rect[1], width: rect[2], height: rect[3] }); el.appendChild(rc); o.paper.defs.appendChild(el); $(node, {"clip-path": "url(#" + el.id + ")"}); o.clip = rc; } if (!value) { var path = node.getAttribute("clip-path"); if (path) { var clip = R._g.doc.getElementById(path.replace(/(^url\(#|\)$)/g, E)); clip && clip.parentNode.removeChild(clip); $(node, {"clip-path": E}); delete o.clip; } } break; case "path": if (o.type == "path") { $(node, {d: value ? attrs.path = R._pathToAbsolute(value) : "M0,0"}); o._.dirty = 1; if (o._.arrows) { "startString" in o._.arrows && addArrow(o, o._.arrows.startString); "endString" in o._.arrows && addArrow(o, o._.arrows.endString, 1); } } break; case "width": node.setAttribute(att, value); o._.dirty = 1; if (attrs.fx) { att = "x"; value = attrs.x; } else { break; } case "x": if (attrs.fx) { value = -attrs.x - (attrs.width || 0); } case "rx": if (att == "rx" && o.type == "rect") { break; } case "cx": node.setAttribute(att, value); o.pattern && updatePosition(o); o._.dirty = 1; break; case "height": node.setAttribute(att, value); o._.dirty = 1; if (attrs.fy) { att = "y"; value = attrs.y; } else { break; } case "y": if (attrs.fy) { value = -attrs.y - (attrs.height || 0); } case "ry": if (att == "ry" && o.type == "rect") { break; } case "cy": node.setAttribute(att, value); o.pattern && updatePosition(o); o._.dirty = 1; break; case "r": if (o.type == "rect") { $(node, {rx: value, ry: value}); } else { node.setAttribute(att, value); } o._.dirty = 1; break; case "src": if (o.type == "image") { node.setAttributeNS(xlink, "href", value); } break; case "stroke-width": if (o._.sx != 1 || o._.sy != 1) { value /= mmax(abs(o._.sx), abs(o._.sy)) || 1; } if (o.paper._vbSize) { value *= o.paper._vbSize; } node.setAttribute(att, value); if (attrs["stroke-dasharray"]) { addDashes(o, attrs["stroke-dasharray"], params); } if (o._.arrows) { "startString" in o._.arrows && addArrow(o, o._.arrows.startString); "endString" in o._.arrows && addArrow(o, o._.arrows.endString, 1); } break; case "stroke-dasharray": addDashes(o, value, params); break; case "fill": var isURL = Str(value).match(R._ISURL); if (isURL) { el = $("pattern"); var ig = $("image"); el.id = R.createUUID(); $(el, {x: 0, y: 0, patternUnits: "userSpaceOnUse", height: 1, width: 1}); $(ig, {x: 0, y: 0, "xlink:href": isURL[1]}); el.appendChild(ig); (function (el) { R._preload(isURL[1], function () { var w = this.offsetWidth, h = this.offsetHeight; $(el, {width: w, height: h}); $(ig, {width: w, height: h}); o.paper.safari(); }); })(el); o.paper.defs.appendChild(el); $(node, {fill: "url(#" + el.id + ")"}); o.pattern = el; o.pattern && updatePosition(o); break; } var clr = R.getRGB(value); if (!clr.error) { delete params.gradient; delete attrs.gradient; !R.is(attrs.opacity, "undefined") && R.is(params.opacity, "undefined") && $(node, {opacity: attrs.opacity}); !R.is(attrs["fill-opacity"], "undefined") && R.is(params["fill-opacity"], "undefined") && $(node, {"fill-opacity": attrs["fill-opacity"]}); } else if ((o.type == "circle" || o.type == "ellipse" || Str(value).charAt() != "r") && addGradientFill(o, value)) { if ("opacity" in attrs || "fill-opacity" in attrs) { var gradient = R._g.doc.getElementById(node.getAttribute("fill").replace(/^url\(#|\)$/g, E)); if (gradient) { var stops = gradient.getElementsByTagName("stop"); $(stops[stops.length - 1], {"stop-opacity": ("opacity" in attrs ? attrs.opacity : 1) * ("fill-opacity" in attrs ? attrs["fill-opacity"] : 1)}); } } attrs.gradient = value; attrs.fill = "none"; break; } clr[has]("opacity") && $(node, {"fill-opacity": clr.opacity > 1 ? clr.opacity / 100 : clr.opacity}); case "stroke": clr = R.getRGB(value); node.setAttribute(att, clr.hex); att == "stroke" && clr[has]("opacity") && $(node, {"stroke-opacity": clr.opacity > 1 ? clr.opacity / 100 : clr.opacity}); if (att == "stroke" && o._.arrows) { "startString" in o._.arrows && addArrow(o, o._.arrows.startString); "endString" in o._.arrows && addArrow(o, o._.arrows.endString, 1); } break; case "gradient": (o.type == "circle" || o.type == "ellipse" || Str(value).charAt() != "r") && addGradientFill(o, value); break; case "opacity": if (attrs.gradient && !attrs[has]("stroke-opacity")) { $(node, {"stroke-opacity": value > 1 ? value / 100 : value}); } // fall case "fill-opacity": if (attrs.gradient) { gradient = R._g.doc.getElementById(node.getAttribute("fill").replace(/^url\(#|\)$/g, E)); if (gradient) { stops = gradient.getElementsByTagName("stop"); $(stops[stops.length - 1], {"stop-opacity": value}); } break; } default: att == "font-size" && (value = toInt(value, 10) + "px"); var cssrule = att.replace(/(\-.)/g, function (w) { return w.substring(1).toUpperCase(); }); node.style[cssrule] = value; o._.dirty = 1; node.setAttribute(att, value); break; } } } tuneText(o, params); node.style.visibility = vis; }, leading = 1.2, tuneText = function (el, params) { if (el.type != "text" || !(params[has]("text") || params[has]("font") || params[has]("font-size") || params[has]("x") || params[has]("y"))) { return; } var a = el.attrs, node = el.node, fontSize = node.firstChild ? toInt(R._g.doc.defaultView.getComputedStyle(node.firstChild, E).getPropertyValue("font-size"), 10) : 10; if (params[has]("text")) { a.text = params.text; while (node.firstChild) { node.removeChild(node.firstChild); } var texts = Str(params.text).split("\n"), tspans = [], tspan; for (var i = 0, ii = texts.length; i < ii; i++) { tspan = $("tspan"); i && $(tspan, {dy: fontSize * leading, x: a.x}); tspan.appendChild(R._g.doc.createTextNode(texts[i])); node.appendChild(tspan); tspans[i] = tspan; } } else { tspans = node.getElementsByTagName("tspan"); for (i = 0, ii = tspans.length; i < ii; i++) if (i) { $(tspans[i], {dy: fontSize * leading, x: a.x}); } else { $(tspans[0], {dy: 0}); } } $(node, {x: a.x, y: a.y}); el._.dirty = 1; var bb = el._getBBox(), dif = a.y - (bb.y + bb.height / 2); dif && R.is(dif, "finite") && $(tspans[0], {dy: dif}); }, Element = function (node, svg) { var X = 0, Y = 0; /*\ * Element.node [ property (object) ] ** * Gives you a reference to the DOM object, so you can assign event handlers or just mess around. ** * Note: Don’t mess with it. > Usage | // draw a circle at coordinate 10,10 with radius of 10 | var c = paper.circle(10, 10, 10); | c.node.onclick = function () { | c.attr("fill", "red"); | }; \*/ this[0] = this.node = node; /*\ * Element.raphael [ property (object) ] ** * Internal reference to @Raphael object. In case it is not available. > Usage | Raphael.el.red = function () { | var hsb = this.paper.raphael.rgb2hsb(this.attr("fill")); | hsb.h = 1; | this.attr({fill: this.paper.raphael.hsb2rgb(hsb).hex}); | } \*/ node.raphael = true; /*\ * Element.id [ property (number) ] ** * Unique id of the element. Especially usesful when you want to listen to events of the element, * because all events are fired in format `<module>.<action>.<id>`. Also useful for @Paper.getById method. \*/ this.id = R._oid++; node.raphaelid = this.id; this.matrix = R.matrix(); this.realPath = null; /*\ * Element.paper [ property (object) ] ** * Internal reference to “paper” where object drawn. Mainly for use in plugins and element extensions. > Usage | Raphael.el.cross = function () { | this.attr({fill: "red"}); | this.paper.path("M10,10L50,50M50,10L10,50") | .attr({stroke: "red"}); | } \*/ this.paper = svg; this.attrs = this.attrs || {}; this._ = { transform: [], sx: 1, sy: 1, deg: 0, dx: 0, dy: 0, dirty: 1 }; !svg.bottom && (svg.bottom = this); /*\ * Element.prev [ property (object) ] ** * Reference to the previous element in the hierarchy. \*/ this.prev = svg.top; svg.top && (svg.top.next = this); svg.top = this; /*\ * Element.next [ property (object) ] ** * Reference to the next element in the hierarchy. \*/ this.next = null; }, elproto = R.el; Element.prototype = elproto; elproto.constructor = Element; R._engine.path = function (pathString, SVG) { var el = $("path"); SVG.canvas && SVG.canvas.appendChild(el); var p = new Element(el, SVG); p.type = "path"; setFillAndStroke(p, { fill: "none", stroke: "#000", path: pathString }); return p; }; /*\ * Element.rotate [ method ] ** * Deprecated! Use @Element.transform instead. * Adds rotation by given angle around given point to the list of * transformations of the element. > Parameters - deg (number) angle in degrees - cx (number) #optional x coordinate of the centre of rotation - cy (number) #optional y coordinate of the centre of rotation * If cx & cy aren’t specified centre of the shape is used as a point of rotation. = (object) @Element \*/ elproto.rotate = function (deg, cx, cy) { if (this.removed) { return this; } deg = Str(deg).split(separator); if (deg.length - 1) { cx = toFloat(deg[1]); cy = toFloat(deg[2]); } deg = toFloat(deg[0]); (cy == null) && (cx = cy); if (cx == null || cy == null) { var bbox = this.getBBox(1); cx = bbox.x + bbox.width / 2; cy = bbox.y + bbox.height / 2; } this.transform(this._.transform.concat([["r", deg, cx, cy]])); return this; }; /*\ * Element.scale [ method ] ** * Deprecated! Use @Element.transform instead. * Adds scale by given amount relative to given point to the list of * transformations of the element. > Parameters - sx (number) horisontal scale amount - sy (number) vertical scale amount - cx (number) #optional x coordinate of the centre of scale - cy (number) #optional y coordinate of the centre of scale * If cx & cy aren’t specified centre of the shape is used instead. = (object) @Element \*/ elproto.scale = function (sx, sy, cx, cy) { if (this.removed) { return this; } sx = Str(sx).split(separator); if (sx.length - 1) { sy = toFloat(sx[1]); cx = toFloat(sx[2]); cy = toFloat(sx[3]); } sx = toFloat(sx[0]); (sy == null) && (sy = sx); (cy == null) && (cx = cy); if (cx == null || cy == null) { var bbox = this.getBBox(1); } cx = cx == null ? bbox.x + bbox.width / 2 : cx; cy = cy == null ? bbox.y + bbox.height / 2 : cy; this.transform(this._.transform.concat([["s", sx, sy, cx, cy]])); return this; }; /*\ * Element.translate [ method ] ** * Deprecated! Use @Element.transform instead. * Adds translation by given amount to the list of transformations of the element. > Parameters - dx (number) horisontal shift - dy (number) vertical shift = (object) @Element \*/ elproto.translate = function (dx, dy) { if (this.removed) { return this; } dx = Str(dx).split(separator); if (dx.length - 1) { dy = toFloat(dx[1]); } dx = toFloat(dx[0]) || 0; dy = +dy || 0; this.transform(this._.transform.concat([["t", dx, dy]])); return this; }; /*\ * Element.transform [ method ] ** * Adds transformation to the element which is separate to other attributes, * i.e. translation doesn’t change `x` or `y` of the rectange. The format * of transformation string is similar to the path string syntax: | "t100,100r30,100,100s2,2,100,100r45s1.5" * Each letter is a command. There are four commands: `t` is for translate, `r` is for rotate, `s` is for * scale and `m` is for matrix. * * There are also alternative “absolute” translation, rotation and scale: `T`, `R` and `S`. They will not take previous transformation into account. For example, `...T100,0` will always move element 100 px horisontally, while `...t100,0` could move it vertically if there is `r90` before. Just compare results of `r90t100,0` and `r90T100,0`. * * So, the example line above could be read like “translate by 100, 100; rotate 30° around 100, 100; scale twice around 100, 100; * rotate 45° around centre; scale 1.5 times relative to centre”. As you can see rotate and scale commands have origin * coordinates as optional parameters, the default is the centre point of the element. * Matrix accepts six parameters. > Usage | var el = paper.rect(10, 20, 300, 200); | // translate 100, 100, rotate 45°, translate -100, 0 | el.transform("t100,100r45t-100,0"); | // if you want you can append or prepend transformations | el.transform("...t50,50"); | el.transform("s2..."); | // or even wrap | el.transform("t50,50...t-50-50"); | // to reset transformation call method with empty string | el.transform(""); | // to get current value call it without parameters | console.log(el.transform()); > Parameters - tstr (string) #optional transformation string * If tstr isn’t specified = (string) current transformation string * else = (object) @Element \*/ elproto.transform = function (tstr) { var _ = this._; if (tstr == null) { return _.transform; } R._extractTransform(this, tstr); this.clip && $(this.clip, {transform: this.matrix.invert()}); this.pattern && updatePosition(this); this.node && $(this.node, {transform: this.matrix}); if (_.sx != 1 || _.sy != 1) { var sw = this.attrs[has]("stroke-width") ? this.attrs["stroke-width"] : 1; this.attr({"stroke-width": sw}); } return this; }; /*\ * Element.hide [ method ] ** * Makes element invisible. See @Element.show. = (object) @Element \*/ elproto.hide = function () { !this.removed && this.paper.safari(this.node.style.display = "none"); return this; }; /*\ * Element.show [ method ] ** * Makes element visible. See @Element.hide. = (object) @Element \*/ elproto.show = function () { !this.removed && this.paper.safari(this.node.style.display = ""); return this; }; /*\ * Element.remove [ method ] ** * Removes element from the paper. \*/ elproto.remove = function () { if (this.removed || !this.node.parentNode) { return; } var paper = this.paper; paper.__set__ && paper.__set__.exclude(this); eve.unbind("raphael.*.*." + this.id); if (this.gradient) { paper.defs.removeChild(this.gradient); } R._tear(this, paper); if (this.node.parentNode.tagName.toLowerCase() == "a") { this.node.parentNode.parentNode.removeChild(this.node.parentNode); } else { this.node.parentNode.removeChild(this.node); } for (var i in this) { this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null; } this.removed = true; }; elproto._getBBox = function () { if (this.node.style.display == "none") { this.show(); var hide = true; } var bbox = {}; try { bbox = this.node.getBBox(); } catch(e) { // Firefox 3.0.x plays badly here } finally { bbox = bbox || {}; } hide && this.hide(); return bbox; }; /*\ * Element.attr [ method ] ** * Sets the attributes of the element. > Parameters - attrName (string) attribute’s name - value (string) value * or - params (object) object of name/value pairs * or - attrName (string) attribute’s name * or - attrNames (array) in this case method returns array of current values for given attribute names = (object) @Element if attrsName & value or params are passed in. = (...) value of the attribute if only attrsName is passed in. = (array) array of values of the attribute if attrsNames is passed in. = (object) object of attributes if nothing is passed in. > Possible parameters # <p>Please refer to the <a href="http://www.w3.org/TR/SVG/" title="The W3C Recommendation for the SVG language describes these properties in detail.">SVG specification</a> for an explanation of these parameters.</p> o arrow-end (string) arrowhead on the end of the path. The format for string is `<type>[-<width>[-<length>]]`. Possible types: `classic`, `block`, `open`, `oval`, `diamond`, `none`, width: `wide`, `narrow`, `medium`, length: `long`, `short`, `midium`. o clip-rect (string) comma or space separated values: x, y, width and height o cursor (string) CSS type of the cursor o cx (number) the x-axis coordinate of the center of the circle, or ellipse o cy (number) the y-axis coordinate of the center of the circle, or ellipse o fill (string) colour, gradient or image o fill-opacity (number) o font (string) o font-family (string) o font-size (number) font size in pixels o font-weight (string) o height (number) o href (string) URL, if specified element behaves as hyperlink o opacity (number) o path (string) SVG path string format o r (number) radius of the circle, ellipse or rounded corner on the rect o rx (number) horisontal radius of the ellipse o ry (number) vertical radius of the ellipse o src (string) image URL, only works for @Element.image element o stroke (string) stroke colour o stroke-dasharray (string) [“”, “`-`”, “`.`”, “`-.`”, “`-..`”, “`. `”, “`- `”, “`--`”, “`- .`”, “`--.`”, “`--..`”] o stroke-linecap (string) [“`butt`”, “`square`”, “`round`”] o stroke-linejoin (string) [“`bevel`”, “`round`”, “`miter`”] o stroke-miterlimit (number) o stroke-opacity (number) o stroke-width (number) stroke width in pixels, default is '1' o target (string) used with href o text (string) contents of the text element. Use `\n` for multiline text o text-anchor (string) [“`start`”, “`middle`”, “`end`”], default is “`middle`” o title (string) will create tooltip with a given text o transform (string) see @Element.transform o width (number) o x (number) o y (number) > Gradients * Linear gradient format: “`‹angle›-‹colour›[-‹colour›[:‹offset›]]*-‹colour›`”, example: “`90-#fff-#000`” – 90° * gradient from white to black or “`0-#fff-#f00:20-#000`” – 0° gradient from white via red (at 20%) to black. * * radial gradient: “`r[(‹fx›, ‹fy›)]‹colour›[-‹colour›[:‹offset›]]*-‹colour›`”, example: “`r#fff-#000`” – * gradient from white to black or “`r(0.25, 0.75)#fff-#000`” – gradient from white to black with focus point * at 0.25, 0.75. Focus point coordinates are in 0..1 range. Radial gradients can only be applied to circles and ellipses. > Path String # <p>Please refer to <a href="http://www.w3.org/TR/SVG/paths.html#PathData" title="Details of a path’s data attribute’s format are described in the SVG specification.">SVG documentation regarding path string</a>. Raphaël fully supports it.</p> > Colour Parsing # <ul> # <li>Colour name (“<code>red</code>”, “<code>green</code>”, “<code>cornflowerblue</code>”, etc)</li> # <li>#••• — shortened HTML colour: (“<code>#000</code>”, “<code>#fc0</code>”, etc)</li> # <li>#•••••• — full length HTML colour: (“<code>#000000</code>”, “<code>#bd2300</code>”)</li> # <li>rgb(•••, •••, •••) — red, green and blue channels’ values: (“<code>rgb(200,&nbsp;100,&nbsp;0)</code>”)</li> # <li>rgb(•••%, •••%, •••%) — same as above, but in %: (“<code>rgb(100%,&nbsp;175%,&nbsp;0%)</code>”)</li> # <li>rgba(•••, •••, •••, •••) — red, green and blue channels’ values: (“<code>rgba(200,&nbsp;100,&nbsp;0, .5)</code>”)</li> # <li>rgba(•••%, •••%, •••%, •••%) — same as above, but in %: (“<code>rgba(100%,&nbsp;175%,&nbsp;0%, 50%)</code>”)</li> # <li>hsb(•••, •••, •••) — hue, saturation and brightness values: (“<code>hsb(0.5,&nbsp;0.25,&nbsp;1)</code>”)</li> # <li>hsb(•••%, •••%, •••%) — same as above, but in %</li> # <li>hsba(•••, •••, •••, •••) — same as above, but with opacity</li> # <li>hsl(•••, •••, •••) — almost the same as hsb, see <a href="http://en.wikipedia.org/wiki/HSL_and_HSV" title="HSL and HSV - Wikipedia, the free encyclopedia">Wikipedia page</a></li> # <li>hsl(•••%, •••%, •••%) — same as above, but in %</li> # <li>hsla(•••, •••, •••, •••) — same as above, but with opacity</li> # <li>Optionally for hsb and hsl you could specify hue as a degree: “<code>hsl(240deg,&nbsp;1,&nbsp;.5)</code>” or, if you want to go fancy, “<code>hsl(240°,&nbsp;1,&nbsp;.5)</code>”</li> # </ul> \*/ elproto.attr = function (name, value) { if (this.removed) { return this; } if (name == null) { var res = {}; for (var a in this.attrs) if (this.attrs[has](a)) { res[a] = this.attrs[a]; } res.gradient && res.fill == "none" && (res.fill = res.gradient) && delete res.gradient; res.transform = this._.transform; return res; } if (value == null && R.is(name, "string")) { if (name == "fill" && this.attrs.fill == "none" && this.attrs.gradient) { return this.attrs.gradient; } if (name == "transform") { return this._.transform; } var names = name.split(separator), out = {}; for (var i = 0, ii = names.length; i < ii; i++) { name = names[i]; if (name in this.attrs) { out[name] = this.attrs[name]; } else if (R.is(this.paper.customAttributes[name], "function")) { out[name] = this.paper.customAttributes[name].def; } else { out[name] = R._availableAttrs[name]; } } return ii - 1 ? out : out[names[0]]; } if (value == null && R.is(name, "array")) { out = {}; for (i = 0, ii = name.length; i < ii; i++) { out[name[i]] = this.attr(name[i]); } return out; } if (value != null) { var params = {}; params[name] = value; } else if (name != null && R.is(name, "object")) { params = name; } for (var key in params) { eve("raphael.attr." + key + "." + this.id, this, params[key]); } for (key in this.paper.customAttributes) if (this.paper.customAttributes[has](key) && params[has](key) && R.is(this.paper.customAttributes[key], "function")) { var par = this.paper.customAttributes[key].apply(this, [].concat(params[key])); this.attrs[key] = params[key]; for (var subkey in par) if (par[has](subkey)) { params[subkey] = par[subkey]; } } setFillAndStroke(this, params); return this; }; /*\ * Element.toFront [ method ] ** * Moves the element so it is the closest to the viewer’s eyes, on top of other elements. = (object) @Element \*/ elproto.toFront = function () { if (this.removed) { return this; } if (this.node.parentNode.tagName.toLowerCase() == "a") { this.node.parentNode.parentNode.appendChild(this.node.parentNode); } else { this.node.parentNode.appendChild(this.node); } var svg = this.paper; svg.top != this && R._tofront(this, svg); return this; }; /*\ * Element.toBack [ method ] ** * Moves the element so it is the furthest from the viewer’s eyes, behind other elements. = (object) @Element \*/ elproto.toBack = function () { if (this.removed) { return this; } var parent = this.node.parentNode; if (parent.tagName.toLowerCase() == "a") { parent.parentNode.insertBefore(this.node.parentNode, this.node.parentNode.parentNode.firstChild); } else if (parent.firstChild != this.node) { parent.insertBefore(this.node, this.node.parentNode.firstChild); } R._toback(this, this.paper); var svg = this.paper; return this; }; /*\ * Element.insertAfter [ method ] ** * Inserts current object after the given one. = (object) @Element \*/ elproto.insertAfter = function (element) { if (this.removed) { return this; } var node = element.node || element[element.length - 1].node; if (node.nextSibling) { node.parentNode.insertBefore(this.node, node.nextSibling); } else { node.parentNode.appendChild(this.node); } R._insertafter(this, element, this.paper); return this; }; /*\ * Element.insertBefore [ method ] ** * Inserts current object before the given one. = (object) @Element \*/ elproto.insertBefore = function (element) { if (this.removed) { return this; } var node = element.node || element[0].node; node.parentNode.insertBefore(this.node, node); R._insertbefore(this, element, this.paper); return this; }; elproto.blur = function (size) { // Experimental. No Safari support. Use it on your own risk. var t = this; if (+size !== 0) { var fltr = $("filter"), blur = $("feGaussianBlur"); t.attrs.blur = size; fltr.id = R.createUUID(); $(blur, {stdDeviation: +size || 1.5}); fltr.appendChild(blur); t.paper.defs.appendChild(fltr); t._blur = fltr; $(t.node, {filter: "url(#" + fltr.id + ")"}); } else { if (t._blur) { t._blur.parentNode.removeChild(t._blur); delete t._blur; delete t.attrs.blur; } t.node.removeAttribute("filter"); } return t; }; R._engine.circle = function (svg, x, y, r) { var el = $("circle"); svg.canvas && svg.canvas.appendChild(el); var res = new Element(el, svg); res.attrs = {cx: x, cy: y, r: r, fill: "none", stroke: "#000"}; res.type = "circle"; $(el, res.attrs); return res; }; R._engine.rect = function (svg, x, y, w, h, r) { var el = $("rect"); svg.canvas && svg.canvas.appendChild(el); var res = new Element(el, svg); res.attrs = {x: x, y: y, width: w, height: h, r: r || 0, rx: r || 0, ry: r || 0, fill: "none", stroke: "#000"}; res.type = "rect"; $(el, res.attrs); return res; }; R._engine.ellipse = function (svg, x, y, rx, ry) { var el = $("ellipse"); svg.canvas && svg.canvas.appendChild(el); var res = new Element(el, svg); res.attrs = {cx: x, cy: y, rx: rx, ry: ry, fill: "none", stroke: "#000"}; res.type = "ellipse"; $(el, res.attrs); return res; }; R._engine.image = function (svg, src, x, y, w, h) { var el = $("image"); $(el, {x: x, y: y, width: w, height: h, preserveAspectRatio: "none"}); el.setAttributeNS(xlink, "href", src); svg.canvas && svg.canvas.appendChild(el); var res = new Element(el, svg); res.attrs = {x: x, y: y, width: w, height: h, src: src}; res.type = "image"; return res; }; R._engine.text = function (svg, x, y, text) { var el = $("text"); svg.canvas && svg.canvas.appendChild(el); var res = new Element(el, svg); res.attrs = { x: x, y: y, "text-anchor": "middle", text: text, font: R._availableAttrs.font, stroke: "none", fill: "#000" }; res.type = "text"; setFillAndStroke(res, res.attrs); return res; }; R._engine.setSize = function (width, height) { this.width = width || this.width; this.height = height || this.height; this.canvas.setAttribute("width", this.width); this.canvas.setAttribute("height", this.height); if (this._viewBox) { this.setViewBox.apply(this, this._viewBox); } return this; }; R._engine.create = function () { var con = R._getContainer.apply(0, arguments), container = con && con.container, x = con.x, y = con.y, width = con.width, height = con.height; if (!container) { throw new Error("SVG container not found."); } var cnvs = $("svg"), css = "overflow:hidden;", isFloating; x = x || 0; y = y || 0; width = width || 512; height = height || 342; $(cnvs, { height: height, version: 1.1, width: width, xmlns: "http://www.w3.org/2000/svg" }); if (container == 1) { cnvs.style.cssText = css + "position:absolute;left:" + x + "px;top:" + y + "px"; R._g.doc.body.appendChild(cnvs); isFloating = 1; } else { cnvs.style.cssText = css + "position:relative"; if (container.firstChild) { container.insertBefore(cnvs, container.firstChild); } else { container.appendChild(cnvs); } } container = new R._Paper; container.width = width; container.height = height; container.canvas = cnvs; container.clear(); container._left = container._top = 0; isFloating && (container.renderfix = function () {}); container.renderfix(); return container; }; R._engine.setViewBox = function (x, y, w, h, fit) { eve("raphael.setViewBox", this, this._viewBox, [x, y, w, h, fit]); var size = mmax(w / this.width, h / this.height), top = this.top, aspectRatio = fit ? "meet" : "xMinYMin", vb, sw; if (x == null) { if (this._vbSize) { size = 1; } delete this._vbSize; vb = "0 0 " + this.width + S + this.height; } else { this._vbSize = size; vb = x + S + y + S + w + S + h; } $(this.canvas, { viewBox: vb, preserveAspectRatio: aspectRatio }); while (size && top) { sw = "stroke-width" in top.attrs ? top.attrs["stroke-width"] : 1; top.attr({"stroke-width": sw}); top._.dirty = 1; top._.dirtyT = 1; top = top.prev; } this._viewBox = [x, y, w, h, !!fit]; return this; }; /*\ * Paper.renderfix [ method ] ** * Fixes the issue of Firefox and IE9 regarding subpixel rendering. If paper is dependant * on other elements after reflow it could shift half pixel which cause for lines to lost their crispness. * This method fixes the issue. ** Special thanks to Mariusz Nowak (http://www.medikoo.com/) for this method. \*/ R.prototype.renderfix = function () { var cnvs = this.canvas, s = cnvs.style, pos; try { pos = cnvs.getScreenCTM() || cnvs.createSVGMatrix(); } catch (e) { pos = cnvs.createSVGMatrix(); } var left = -pos.e % 1, top = -pos.f % 1; if (left || top) { if (left) { this._left = (this._left + left) % 1; s.left = this._left + "px"; } if (top) { this._top = (this._top + top) % 1; s.top = this._top + "px"; } } }; /*\ * Paper.clear [ method ] ** * Clears the paper, i.e. removes all the elements. \*/ R.prototype.clear = function () { R.eve("raphael.clear", this); var c = this.canvas; while (c.firstChild) { c.removeChild(c.firstChild); } this.bottom = this.top = null; (this.desc = $("desc")).appendChild(R._g.doc.createTextNode("Created with Rapha\xebl " + R.version)); c.appendChild(this.desc); c.appendChild(this.defs = $("defs")); }; /*\ * Paper.remove [ method ] ** * Removes the paper from the DOM. \*/ R.prototype.remove = function () { eve("raphael.remove", this); this.canvas.parentNode && this.canvas.parentNode.removeChild(this.canvas); for (var i in this) { this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null; } }; var setproto = R.st; for (var method in elproto) if (elproto[has](method) && !setproto[has](method)) { setproto[method] = (function (methodname) { return function () { var arg = arguments; return this.forEach(function (el) { el[methodname].apply(el, arg); }); }; })(method); } })(); // ┌─────────────────────────────────────────────────────────────────────┐ \\ // │ Raphaël - JavaScript Vector Library │ \\ // ├─────────────────────────────────────────────────────────────────────┤ \\ // │ VML Module │ \\ // ├─────────────────────────────────────────────────────────────────────┤ \\ // │ Copyright (c) 2008-2011 Dmitry Baranovskiy (http://raphaeljs.com) │ \\ // │ Copyright (c) 2008-2011 Sencha Labs (http://sencha.com) │ \\ // │ Licensed under the MIT (http://raphaeljs.com/license.html) license. │ \\ // └─────────────────────────────────────────────────────────────────────┘ \\ (function(){ if (!R.vml) { return; } var has = "hasOwnProperty", Str = String, toFloat = parseFloat, math = Math, round = math.round, mmax = math.max, mmin = math.min, abs = math.abs, fillString = "fill", separator = /[, ]+/, eve = R.eve, ms = " progid:DXImageTransform.Microsoft", S = " ", E = "", map = {M: "m", L: "l", C: "c", Z: "x", m: "t", l: "r", c: "v", z: "x"}, bites = /([clmz]),?([^clmz]*)/gi, blurregexp = / progid:\S+Blur\([^\)]+\)/g, val = /-?[^,\s-]+/g, cssDot = "position:absolute;left:0;top:0;width:1px;height:1px", zoom = 21600, pathTypes = {path: 1, rect: 1, image: 1}, ovalTypes = {circle: 1, ellipse: 1}, path2vml = function (path) { var total = /[ahqstv]/ig, command = R._pathToAbsolute; Str(path).match(total) && (command = R._path2curve); total = /[clmz]/g; if (command == R._pathToAbsolute && !Str(path).match(total)) { var res = Str(path).replace(bites, function (all, command, args) { var vals = [], isMove = command.toLowerCase() == "m", res = map[command]; args.replace(val, function (value) { if (isMove && vals.length == 2) { res += vals + map[command == "m" ? "l" : "L"]; vals = []; } vals.push(round(value * zoom)); }); return res + vals; }); return res; } var pa = command(path), p, r; res = []; for (var i = 0, ii = pa.length; i < ii; i++) { p = pa[i]; r = pa[i][0].toLowerCase(); r == "z" && (r = "x"); for (var j = 1, jj = p.length; j < jj; j++) { r += round(p[j] * zoom) + (j != jj - 1 ? "," : E); } res.push(r); } return res.join(S); }, compensation = function (deg, dx, dy) { var m = R.matrix(); m.rotate(-deg, .5, .5); return { dx: m.x(dx, dy), dy: m.y(dx, dy) }; }, setCoords = function (p, sx, sy, dx, dy, deg) { var _ = p._, m = p.matrix, fillpos = _.fillpos, o = p.node, s = o.style, y = 1, flip = "", dxdy, kx = zoom / sx, ky = zoom / sy; s.visibility = "hidden"; if (!sx || !sy) { return; } o.coordsize = abs(kx) + S + abs(ky); s.rotation = deg * (sx * sy < 0 ? -1 : 1); if (deg) { var c = compensation(deg, dx, dy); dx = c.dx; dy = c.dy; } sx < 0 && (flip += "x"); sy < 0 && (flip += " y") && (y = -1); s.flip = flip; o.coordorigin = (dx * -kx) + S + (dy * -ky); if (fillpos || _.fillsize) { var fill = o.getElementsByTagName(fillString); fill = fill && fill[0]; o.removeChild(fill); if (fillpos) { c = compensation(deg, m.x(fillpos[0], fillpos[1]), m.y(fillpos[0], fillpos[1])); fill.position = c.dx * y + S + c.dy * y; } if (_.fillsize) { fill.size = _.fillsize[0] * abs(sx) + S + _.fillsize[1] * abs(sy); } o.appendChild(fill); } s.visibility = "visible"; }; R.toString = function () { return "Your browser doesn\u2019t support SVG. Falling down to VML.\nYou are running Rapha\xebl " + this.version; }; var addArrow = function (o, value, isEnd) { var values = Str(value).toLowerCase().split("-"), se = isEnd ? "end" : "start", i = values.length, type = "classic", w = "medium", h = "medium"; while (i--) { switch (values[i]) { case "block": case "classic": case "oval": case "diamond": case "open": case "none": type = values[i]; break; case "wide": case "narrow": h = values[i]; break; case "long": case "short": w = values[i]; break; } } var stroke = o.node.getElementsByTagName("stroke")[0]; stroke[se + "arrow"] = type; stroke[se + "arrowlength"] = w; stroke[se + "arrowwidth"] = h; }, setFillAndStroke = function (o, params) { // o.paper.canvas.style.display = "none"; o.attrs = o.attrs || {}; var node = o.node, a = o.attrs, s = node.style, xy, newpath = pathTypes[o.type] && (params.x != a.x || params.y != a.y || params.width != a.width || params.height != a.height || params.cx != a.cx || params.cy != a.cy || params.rx != a.rx || params.ry != a.ry || params.r != a.r), isOval = ovalTypes[o.type] && (a.cx != params.cx || a.cy != params.cy || a.r != params.r || a.rx != params.rx || a.ry != params.ry), res = o; for (var par in params) if (params[has](par)) { a[par] = params[par]; } if (newpath) { a.path = R._getPath[o.type](o); o._.dirty = 1; } params.href && (node.href = params.href); params.title && (node.title = params.title); params.target && (node.target = params.target); params.cursor && (s.cursor = params.cursor); "blur" in params && o.blur(params.blur); if (params.path && o.type == "path" || newpath) { node.path = path2vml(~Str(a.path).toLowerCase().indexOf("r") ? R._pathToAbsolute(a.path) : a.path); if (o.type == "image") { o._.fillpos = [a.x, a.y]; o._.fillsize = [a.width, a.height]; setCoords(o, 1, 1, 0, 0, 0); } } "transform" in params && o.transform(params.transform); if (isOval) { var cx = +a.cx, cy = +a.cy, rx = +a.rx || +a.r || 0, ry = +a.ry || +a.r || 0; node.path = R.format("ar{0},{1},{2},{3},{4},{1},{4},{1}x", round((cx - rx) * zoom), round((cy - ry) * zoom), round((cx + rx) * zoom), round((cy + ry) * zoom), round(cx * zoom)); o._.dirty = 1; } if ("clip-rect" in params) { var rect = Str(params["clip-rect"]).split(separator); if (rect.length == 4) { rect[2] = +rect[2] + (+rect[0]); rect[3] = +rect[3] + (+rect[1]); var div = node.clipRect || R._g.doc.createElement("div"), dstyle = div.style; dstyle.clip = R.format("rect({1}px {2}px {3}px {0}px)", rect); if (!node.clipRect) { dstyle.position = "absolute"; dstyle.top = 0; dstyle.left = 0; dstyle.width = o.paper.width + "px"; dstyle.height = o.paper.height + "px"; node.parentNode.insertBefore(div, node); div.appendChild(node); node.clipRect = div; } } if (!params["clip-rect"]) { node.clipRect && (node.clipRect.style.clip = "auto"); } } if (o.textpath) { var textpathStyle = o.textpath.style; params.font && (textpathStyle.font = params.font); params["font-family"] && (textpathStyle.fontFamily = '"' + params["font-family"].split(",")[0].replace(/^['"]+|['"]+$/g, E) + '"'); params["font-size"] && (textpathStyle.fontSize = params["font-size"]); params["font-weight"] && (textpathStyle.fontWeight = params["font-weight"]); params["font-style"] && (textpathStyle.fontStyle = params["font-style"]); } if ("arrow-start" in params) { addArrow(res, params["arrow-start"]); } if ("arrow-end" in params) { addArrow(res, params["arrow-end"], 1); } if (params.opacity != null || params["stroke-width"] != null || params.fill != null || params.src != null || params.stroke != null || params["stroke-width"] != null || params["stroke-opacity"] != null || params["fill-opacity"] != null || params["stroke-dasharray"] != null || params["stroke-miterlimit"] != null || params["stroke-linejoin"] != null || params["stroke-linecap"] != null) { var fill = node.getElementsByTagName(fillString), newfill = false; fill = fill && fill[0]; !fill && (newfill = fill = createNode(fillString)); if (o.type == "image" && params.src) { fill.src = params.src; } params.fill && (fill.on = true); if (fill.on == null || params.fill == "none" || params.fill === null) { fill.on = false; } if (fill.on && params.fill) { var isURL = Str(params.fill).match(R._ISURL); if (isURL) { fill.parentNode == node && node.removeChild(fill); fill.rotate = true; fill.src = isURL[1]; fill.type = "tile"; var bbox = o.getBBox(1); fill.position = bbox.x + S + bbox.y; o._.fillpos = [bbox.x, bbox.y]; R._preload(isURL[1], function () { o._.fillsize = [this.offsetWidth, this.offsetHeight]; }); } else { fill.color = R.getRGB(params.fill).hex; fill.src = E; fill.type = "solid"; if (R.getRGB(params.fill).error && (res.type in {circle: 1, ellipse: 1} || Str(params.fill).charAt() != "r") && addGradientFill(res, params.fill, fill)) { a.fill = "none"; a.gradient = params.fill; fill.rotate = false; } } } if ("fill-opacity" in params || "opacity" in params) { var opacity = ((+a["fill-opacity"] + 1 || 2) - 1) * ((+a.opacity + 1 || 2) - 1) * ((+R.getRGB(params.fill).o + 1 || 2) - 1); opacity = mmin(mmax(opacity, 0), 1); fill.opacity = opacity; if (fill.src) { fill.color = "none"; } } node.appendChild(fill); var stroke = (node.getElementsByTagName("stroke") && node.getElementsByTagName("stroke")[0]), newstroke = false; !stroke && (newstroke = stroke = createNode("stroke")); if ((params.stroke && params.stroke != "none") || params["stroke-width"] || params["stroke-opacity"] != null || params["stroke-dasharray"] || params["stroke-miterlimit"] || params["stroke-linejoin"] || params["stroke-linecap"]) { stroke.on = true; } (params.stroke == "none" || params.stroke === null || stroke.on == null || params.stroke == 0 || params["stroke-width"] == 0) && (stroke.on = false); var strokeColor = R.getRGB(params.stroke); stroke.on && params.stroke && (stroke.color = strokeColor.hex); opacity = ((+a["stroke-opacity"] + 1 || 2) - 1) * ((+a.opacity + 1 || 2) - 1) * ((+strokeColor.o + 1 || 2) - 1); var width = (toFloat(params["stroke-width"]) || 1) * .75; opacity = mmin(mmax(opacity, 0), 1); params["stroke-width"] == null && (width = a["stroke-width"]); params["stroke-width"] && (stroke.weight = width); width && width < 1 && (opacity *= width) && (stroke.weight = 1); stroke.opacity = opacity; params["stroke-linejoin"] && (stroke.joinstyle = params["stroke-linejoin"] || "miter"); stroke.miterlimit = params["stroke-miterlimit"] || 8; params["stroke-linecap"] && (stroke.endcap = params["stroke-linecap"] == "butt" ? "flat" : params["stroke-linecap"] == "square" ? "square" : "round"); if (params["stroke-dasharray"]) { var dasharray = { "-": "shortdash", ".": "shortdot", "-.": "shortdashdot", "-..": "shortdashdotdot", ". ": "dot", "- ": "dash", "--": "longdash", "- .": "dashdot", "--.": "longdashdot", "--..": "longdashdotdot" }; stroke.dashstyle = dasharray[has](params["stroke-dasharray"]) ? dasharray[params["stroke-dasharray"]] : E; } newstroke && node.appendChild(stroke); } if (res.type == "text") { res.paper.canvas.style.display = E; var span = res.paper.span, m = 100, fontSize = a.font && a.font.match(/\d+(?:\.\d*)?(?=px)/); s = span.style; a.font && (s.font = a.font); a["font-family"] && (s.fontFamily = a["font-family"]); a["font-weight"] && (s.fontWeight = a["font-weight"]); a["font-style"] && (s.fontStyle = a["font-style"]); fontSize = toFloat(a["font-size"] || fontSize && fontSize[0]) || 10; s.fontSize = fontSize * m + "px"; res.textpath.string && (span.innerHTML = Str(res.textpath.string).replace(/</g, "&#60;").replace(/&/g, "&#38;").replace(/\n/g, "<br>")); var brect = span.getBoundingClientRect(); res.W = a.w = (brect.right - brect.left) / m; res.H = a.h = (brect.bottom - brect.top) / m; // res.paper.canvas.style.display = "none"; res.X = a.x; res.Y = a.y + res.H / 2; ("x" in params || "y" in params) && (res.path.v = R.format("m{0},{1}l{2},{1}", round(a.x * zoom), round(a.y * zoom), round(a.x * zoom) + 1)); var dirtyattrs = ["x", "y", "text", "font", "font-family", "font-weight", "font-style", "font-size"]; for (var d = 0, dd = dirtyattrs.length; d < dd; d++) if (dirtyattrs[d] in params) { res._.dirty = 1; break; } // text-anchor emulation switch (a["text-anchor"]) { case "start": res.textpath.style["v-text-align"] = "left"; res.bbx = res.W / 2; break; case "end": res.textpath.style["v-text-align"] = "right"; res.bbx = -res.W / 2; break; default: res.textpath.style["v-text-align"] = "center"; res.bbx = 0; break; } res.textpath.style["v-text-kern"] = true; } // res.paper.canvas.style.display = E; }, addGradientFill = function (o, gradient, fill) { o.attrs = o.attrs || {}; var attrs = o.attrs, pow = Math.pow, opacity, oindex, type = "linear", fxfy = ".5 .5"; o.attrs.gradient = gradient; gradient = Str(gradient).replace(R._radial_gradient, function (all, fx, fy) { type = "radial"; if (fx && fy) { fx = toFloat(fx); fy = toFloat(fy); pow(fx - .5, 2) + pow(fy - .5, 2) > .25 && (fy = math.sqrt(.25 - pow(fx - .5, 2)) * ((fy > .5) * 2 - 1) + .5); fxfy = fx + S + fy; } return E; }); gradient = gradient.split(/\s*\-\s*/); if (type == "linear") { var angle = gradient.shift(); angle = -toFloat(angle); if (isNaN(angle)) { return null; } } var dots = R._parseDots(gradient); if (!dots) { return null; } o = o.shape || o.node; if (dots.length) { o.removeChild(fill); fill.on = true; fill.method = "none"; fill.color = dots[0].color; fill.color2 = dots[dots.length - 1].color; var clrs = []; for (var i = 0, ii = dots.length; i < ii; i++) { dots[i].offset && clrs.push(dots[i].offset + S + dots[i].color); } fill.colors = clrs.length ? clrs.join() : "0% " + fill.color; if (type == "radial") { fill.type = "gradientTitle"; fill.focus = "100%"; fill.focussize = "0 0"; fill.focusposition = fxfy; fill.angle = 0; } else { // fill.rotate= true; fill.type = "gradient"; fill.angle = (270 - angle) % 360; } o.appendChild(fill); } return 1; }, Element = function (node, vml) { this[0] = this.node = node; node.raphael = true; this.id = R._oid++; node.raphaelid = this.id; this.X = 0; this.Y = 0; this.attrs = {}; this.paper = vml; this.matrix = R.matrix(); this._ = { transform: [], sx: 1, sy: 1, dx: 0, dy: 0, deg: 0, dirty: 1, dirtyT: 1 }; !vml.bottom && (vml.bottom = this); this.prev = vml.top; vml.top && (vml.top.next = this); vml.top = this; this.next = null; }; var elproto = R.el; Element.prototype = elproto; elproto.constructor = Element; elproto.transform = function (tstr) { if (tstr == null) { return this._.transform; } var vbs = this.paper._viewBoxShift, vbt = vbs ? "s" + [vbs.scale, vbs.scale] + "-1-1t" + [vbs.dx, vbs.dy] : E, oldt; if (vbs) { oldt = tstr = Str(tstr).replace(/\.{3}|\u2026/g, this._.transform || E); } R._extractTransform(this, vbt + tstr); var matrix = this.matrix.clone(), skew = this.skew, o = this.node, split, isGrad = ~Str(this.attrs.fill).indexOf("-"), isPatt = !Str(this.attrs.fill).indexOf("url("); matrix.translate(1, 1); if (isPatt || isGrad || this.type == "image") { skew.matrix = "1 0 0 1"; skew.offset = "0 0"; split = matrix.split(); if ((isGrad && split.noRotation) || !split.isSimple) { o.style.filter = matrix.toFilter(); var bb = this.getBBox(), bbt = this.getBBox(1), dx = bb.x - bbt.x, dy = bb.y - bbt.y; o.coordorigin = (dx * -zoom) + S + (dy * -zoom); setCoords(this, 1, 1, dx, dy, 0); } else { o.style.filter = E; setCoords(this, split.scalex, split.scaley, split.dx, split.dy, split.rotate); } } else { o.style.filter = E; skew.matrix = Str(matrix); skew.offset = matrix.offset(); } oldt && (this._.transform = oldt); return this; }; elproto.rotate = function (deg, cx, cy) { if (this.removed) { return this; } if (deg == null) { return; } deg = Str(deg).split(separator); if (deg.length - 1) { cx = toFloat(deg[1]); cy = toFloat(deg[2]); } deg = toFloat(deg[0]); (cy == null) && (cx = cy); if (cx == null || cy == null) { var bbox = this.getBBox(1); cx = bbox.x + bbox.width / 2; cy = bbox.y + bbox.height / 2; } this._.dirtyT = 1; this.transform(this._.transform.concat([["r", deg, cx, cy]])); return this; }; elproto.translate = function (dx, dy) { if (this.removed) { return this; } dx = Str(dx).split(separator); if (dx.length - 1) { dy = toFloat(dx[1]); } dx = toFloat(dx[0]) || 0; dy = +dy || 0; if (this._.bbox) { this._.bbox.x += dx; this._.bbox.y += dy; } this.transform(this._.transform.concat([["t", dx, dy]])); return this; }; elproto.scale = function (sx, sy, cx, cy) { if (this.removed) { return this; } sx = Str(sx).split(separator); if (sx.length - 1) { sy = toFloat(sx[1]); cx = toFloat(sx[2]); cy = toFloat(sx[3]); isNaN(cx) && (cx = null); isNaN(cy) && (cy = null); } sx = toFloat(sx[0]); (sy == null) && (sy = sx); (cy == null) && (cx = cy); if (cx == null || cy == null) { var bbox = this.getBBox(1); } cx = cx == null ? bbox.x + bbox.width / 2 : cx; cy = cy == null ? bbox.y + bbox.height / 2 : cy; this.transform(this._.transform.concat([["s", sx, sy, cx, cy]])); this._.dirtyT = 1; return this; }; elproto.hide = function () { !this.removed && (this.node.style.display = "none"); return this; }; elproto.show = function () { !this.removed && (this.node.style.display = E); return this; }; elproto._getBBox = function () { if (this.removed) { return {}; } return { x: this.X + (this.bbx || 0) - this.W / 2, y: this.Y - this.H, width: this.W, height: this.H }; }; elproto.remove = function () { if (this.removed || !this.node.parentNode) { return; } this.paper.__set__ && this.paper.__set__.exclude(this); R.eve.unbind("raphael.*.*." + this.id); R._tear(this, this.paper); this.node.parentNode.removeChild(this.node); this.shape && this.shape.parentNode.removeChild(this.shape); for (var i in this) { this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null; } this.removed = true; }; elproto.attr = function (name, value) { if (this.removed) { return this; } if (name == null) { var res = {}; for (var a in this.attrs) if (this.attrs[has](a)) { res[a] = this.attrs[a]; } res.gradient && res.fill == "none" && (res.fill = res.gradient) && delete res.gradient; res.transform = this._.transform; return res; } if (value == null && R.is(name, "string")) { if (name == fillString && this.attrs.fill == "none" && this.attrs.gradient) { return this.attrs.gradient; } var names = name.split(separator), out = {}; for (var i = 0, ii = names.length; i < ii; i++) { name = names[i]; if (name in this.attrs) { out[name] = this.attrs[name]; } else if (R.is(this.paper.customAttributes[name], "function")) { out[name] = this.paper.customAttributes[name].def; } else { out[name] = R._availableAttrs[name]; } } return ii - 1 ? out : out[names[0]]; } if (this.attrs && value == null && R.is(name, "array")) { out = {}; for (i = 0, ii = name.length; i < ii; i++) { out[name[i]] = this.attr(name[i]); } return out; } var params; if (value != null) { params = {}; params[name] = value; } value == null && R.is(name, "object") && (params = name); for (var key in params) { eve("raphael.attr." + key + "." + this.id, this, params[key]); } if (params) { for (key in this.paper.customAttributes) if (this.paper.customAttributes[has](key) && params[has](key) && R.is(this.paper.customAttributes[key], "function")) { var par = this.paper.customAttributes[key].apply(this, [].concat(params[key])); this.attrs[key] = params[key]; for (var subkey in par) if (par[has](subkey)) { params[subkey] = par[subkey]; } } // this.paper.canvas.style.display = "none"; if (params.text && this.type == "text") { this.textpath.string = params.text; } setFillAndStroke(this, params); // this.paper.canvas.style.display = E; } return this; }; elproto.toFront = function () { !this.removed && this.node.parentNode.appendChild(this.node); this.paper && this.paper.top != this && R._tofront(this, this.paper); return this; }; elproto.toBack = function () { if (this.removed) { return this; } if (this.node.parentNode.firstChild != this.node) { this.node.parentNode.insertBefore(this.node, this.node.parentNode.firstChild); R._toback(this, this.paper); } return this; }; elproto.insertAfter = function (element) { if (this.removed) { return this; } if (element.constructor == R.st.constructor) { element = element[element.length - 1]; } if (element.node.nextSibling) { element.node.parentNode.insertBefore(this.node, element.node.nextSibling); } else { element.node.parentNode.appendChild(this.node); } R._insertafter(this, element, this.paper); return this; }; elproto.insertBefore = function (element) { if (this.removed) { return this; } if (element.constructor == R.st.constructor) { element = element[0]; } element.node.parentNode.insertBefore(this.node, element.node); R._insertbefore(this, element, this.paper); return this; }; elproto.blur = function (size) { var s = this.node.runtimeStyle, f = s.filter; f = f.replace(blurregexp, E); if (+size !== 0) { this.attrs.blur = size; s.filter = f + S + ms + ".Blur(pixelradius=" + (+size || 1.5) + ")"; s.margin = R.format("-{0}px 0 0 -{0}px", round(+size || 1.5)); } else { s.filter = f; s.margin = 0; delete this.attrs.blur; } return this; }; R._engine.path = function (pathString, vml) { var el = createNode("shape"); el.style.cssText = cssDot; el.coordsize = zoom + S + zoom; el.coordorigin = vml.coordorigin; var p = new Element(el, vml), attr = {fill: "none", stroke: "#000"}; pathString && (attr.path = pathString); p.type = "path"; p.path = []; p.Path = E; setFillAndStroke(p, attr); vml.canvas.appendChild(el); var skew = createNode("skew"); skew.on = true; el.appendChild(skew); p.skew = skew; p.transform(E); return p; }; R._engine.rect = function (vml, x, y, w, h, r) { var path = R._rectPath(x, y, w, h, r), res = vml.path(path), a = res.attrs; res.X = a.x = x; res.Y = a.y = y; res.W = a.width = w; res.H = a.height = h; a.r = r; a.path = path; res.type = "rect"; return res; }; R._engine.ellipse = function (vml, x, y, rx, ry) { var res = vml.path(), a = res.attrs; res.X = x - rx; res.Y = y - ry; res.W = rx * 2; res.H = ry * 2; res.type = "ellipse"; setFillAndStroke(res, { cx: x, cy: y, rx: rx, ry: ry }); return res; }; R._engine.circle = function (vml, x, y, r) { var res = vml.path(), a = res.attrs; res.X = x - r; res.Y = y - r; res.W = res.H = r * 2; res.type = "circle"; setFillAndStroke(res, { cx: x, cy: y, r: r }); return res; }; R._engine.image = function (vml, src, x, y, w, h) { var path = R._rectPath(x, y, w, h), res = vml.path(path).attr({stroke: "none"}), a = res.attrs, node = res.node, fill = node.getElementsByTagName(fillString)[0]; a.src = src; res.X = a.x = x; res.Y = a.y = y; res.W = a.width = w; res.H = a.height = h; a.path = path; res.type = "image"; fill.parentNode == node && node.removeChild(fill); fill.rotate = true; fill.src = src; fill.type = "tile"; res._.fillpos = [x, y]; res._.fillsize = [w, h]; node.appendChild(fill); setCoords(res, 1, 1, 0, 0, 0); return res; }; R._engine.text = function (vml, x, y, text) { var el = createNode("shape"), path = createNode("path"), o = createNode("textpath"); x = x || 0; y = y || 0; text = text || ""; path.v = R.format("m{0},{1}l{2},{1}", round(x * zoom), round(y * zoom), round(x * zoom) + 1); path.textpathok = true; o.string = Str(text); o.on = true; el.style.cssText = cssDot; el.coordsize = zoom + S + zoom; el.coordorigin = "0 0"; var p = new Element(el, vml), attr = { fill: "#000", stroke: "none", font: R._availableAttrs.font, text: text }; p.shape = el; p.path = path; p.textpath = o; p.type = "text"; p.attrs.text = Str(text); p.attrs.x = x; p.attrs.y = y; p.attrs.w = 1; p.attrs.h = 1; setFillAndStroke(p, attr); el.appendChild(o); el.appendChild(path); vml.canvas.appendChild(el); var skew = createNode("skew"); skew.on = true; el.appendChild(skew); p.skew = skew; p.transform(E); return p; }; R._engine.setSize = function (width, height) { var cs = this.canvas.style; this.width = width; this.height = height; width == +width && (width += "px"); height == +height && (height += "px"); cs.width = width; cs.height = height; cs.clip = "rect(0 " + width + " " + height + " 0)"; if (this._viewBox) { R._engine.setViewBox.apply(this, this._viewBox); } return this; }; R._engine.setViewBox = function (x, y, w, h, fit) { R.eve("raphael.setViewBox", this, this._viewBox, [x, y, w, h, fit]); var width = this.width, height = this.height, size = 1 / mmax(w / width, h / height), H, W; if (fit) { H = height / h; W = width / w; if (w * H < width) { x -= (width - w * H) / 2 / H; } if (h * W < height) { y -= (height - h * W) / 2 / W; } } this._viewBox = [x, y, w, h, !!fit]; this._viewBoxShift = { dx: -x, dy: -y, scale: size }; this.forEach(function (el) { el.transform("..."); }); return this; }; var createNode; R._engine.initWin = function (win) { var doc = win.document; doc.createStyleSheet().addRule(".rvml", "behavior:url(#default#VML)"); try { !doc.namespaces.rvml && doc.namespaces.add("rvml", "urn:schemas-microsoft-com:vml"); createNode = function (tagName) { return doc.createElement('<rvml:' + tagName + ' class="rvml">'); }; } catch (e) { createNode = function (tagName) { return doc.createElement('<' + tagName + ' xmlns="urn:schemas-microsoft.com:vml" class="rvml">'); }; } }; R._engine.initWin(R._g.win); R._engine.create = function () { var con = R._getContainer.apply(0, arguments), container = con.container, height = con.height, s, width = con.width, x = con.x, y = con.y; if (!container) { throw new Error("VML container not found."); } var res = new R._Paper, c = res.canvas = R._g.doc.createElement("div"), cs = c.style; x = x || 0; y = y || 0; width = width || 512; height = height || 342; res.width = width; res.height = height; width == +width && (width += "px"); height == +height && (height += "px"); res.coordsize = zoom * 1e3 + S + zoom * 1e3; res.coordorigin = "0 0"; res.span = R._g.doc.createElement("span"); res.span.style.cssText = "position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;"; c.appendChild(res.span); cs.cssText = R.format("top:0;left:0;width:{0};height:{1};display:inline-block;position:relative;clip:rect(0 {0} {1} 0);overflow:hidden", width, height); if (container == 1) { R._g.doc.body.appendChild(c); cs.left = x + "px"; cs.top = y + "px"; cs.position = "absolute"; } else { if (container.firstChild) { container.insertBefore(c, container.firstChild); } else { container.appendChild(c); } } res.renderfix = function () {}; return res; }; R.prototype.clear = function () { R.eve("raphael.clear", this); this.canvas.innerHTML = E; this.span = R._g.doc.createElement("span"); this.span.style.cssText = "position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;display:inline;"; this.canvas.appendChild(this.span); this.bottom = this.top = null; }; R.prototype.remove = function () { R.eve("raphael.remove", this); this.canvas.parentNode.removeChild(this.canvas); for (var i in this) { this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null; } return true; }; var setproto = R.st; for (var method in elproto) if (elproto[has](method) && !setproto[has](method)) { setproto[method] = (function (methodname) { return function () { var arg = arguments; return this.forEach(function (el) { el[methodname].apply(el, arg); }); }; })(method); } })(); // EXPOSE // SVG and VML are appended just before the EXPOSE line // Even with AMD, Raphael should be defined globally oldRaphael.was ? (g.win.Raphael = R) : (Raphael = R); return R; }));
JavaScript
/*!jQuery Knob*/ /** * Downward compatible, touchable dial * * Version: 1.2.5 (23/01/2014) * Requires: jQuery v1.7+ * * Copyright (c) 2012 Anthony Terrien * Under MIT License (http://www.opensource.org/licenses/mit-license.php) * * Thanks to vor, eskimoblood, spiffistan, FabrizioC */ (function($) { /** * Kontrol library */ "use strict"; /** * Definition of globals and core */ var k = {}, // kontrol max = Math.max, min = Math.min; k.c = {}; k.c.d = $(document); k.c.t = function (e) { return e.originalEvent.touches.length - 1; }; /** * Kontrol Object * * Definition of an abstract UI control * * Each concrete component must call this one. * <code> * k.o.call(this); * </code> */ k.o = function () { var s = this; this.o = null; // array of options this.$ = null; // jQuery wrapped element this.i = null; // mixed HTMLInputElement or array of HTMLInputElement this.g = null; // deprecated 2D graphics context for 'pre-rendering' this.v = null; // value ; mixed array or integer this.cv = null; // change value ; not commited value this.x = 0; // canvas x position this.y = 0; // canvas y position this.w = 0; // canvas width this.h = 0; // canvas height this.$c = null; // jQuery canvas element this.c = null; // rendered canvas context this.t = 0; // touches index this.isInit = false; this.fgColor = null; // main color this.pColor = null; // previous color this.dH = null; // draw hook this.cH = null; // change hook this.eH = null; // cancel hook this.rH = null; // release hook this.scale = 1; // scale factor this.relative = false; this.relativeWidth = false; this.relativeHeight = false; this.$div = null; // component div this.run = function () { var cf = function (e, conf) { var k; for (k in conf) { s.o[k] = conf[k]; } s._carve().init(); s._configure() ._draw(); }; if(this.$.data('kontroled')) return; this.$.data('kontroled', true); this.extend(); this.o = $.extend( { // Config min : this.$.data('min') !== undefined ? this.$.data('min') : 0, max : this.$.data('max') !== undefined ? this.$.data('max') : 100, stopper : true, readOnly : this.$.data('readonly') || (this.$.attr('readonly') === 'readonly'), // UI cursor : (this.$.data('cursor') === true && 30) || this.$.data('cursor') || 0, thickness : ( this.$.data('thickness') && Math.max(Math.min(this.$.data('thickness'), 1), 0.01) ) || 0.35, lineCap : this.$.data('linecap') || 'butt', width : this.$.data('width') || 200, height : this.$.data('height') || 200, displayInput : this.$.data('displayinput') == null || this.$.data('displayinput'), displayPrevious : this.$.data('displayprevious'), fgColor : this.$.data('fgcolor') || '#87CEEB', inputColor: this.$.data('inputcolor'), font: this.$.data('font') || 'Arial', fontWeight: this.$.data('font-weight') || 'bold', inline : false, step : this.$.data('step') || 1, // Hooks draw : null, // function () {} change : null, // function (value) {} cancel : null, // function () {} release : null // function (value) {} }, this.o ); // finalize options if(!this.o.inputColor) { this.o.inputColor = this.o.fgColor; } // routing value if(this.$.is('fieldset')) { // fieldset = array of integer this.v = {}; this.i = this.$.find('input'); this.i.each(function(k) { var $this = $(this); s.i[k] = $this; s.v[k] = $this.val(); $this.bind( 'change blur' , function () { var val = {}; val[k] = $this.val(); s.val(val); } ); }); this.$.find('legend').remove(); } else { // input = integer this.i = this.$; this.v = this.$.val(); (this.v === '') && (this.v = this.o.min); this.$.bind( 'change blur' , function () { s.val(s._validate(s.$.val())); } ); } (!this.o.displayInput) && this.$.hide(); // adds needed DOM elements (canvas, div) this.$c = $(document.createElement('canvas')).attr({ width: this.o.width, height: this.o.height }); // wraps all elements in a div // add to DOM before Canvas init is triggered this.$div = $('<div style="' + (this.o.inline ? 'display:inline;' : '') + 'width:' + this.o.width + 'px;height:' + this.o.height + 'px;' + '"></div>'); this.$.wrap(this.$div).before(this.$c); this.$div = this.$.parent(); if (typeof G_vmlCanvasManager !== 'undefined') { G_vmlCanvasManager.initElement(this.$c[0]); } this.c = this.$c[0].getContext ? this.$c[0].getContext('2d') : null; if (!this.c) { throw { name: "CanvasNotSupportedException", message: "Canvas not supported. Please use excanvas on IE8.0.", toString: function(){return this.name + ": " + this.message} } } // hdpi support this.scale = (window.devicePixelRatio || 1) / ( this.c.webkitBackingStorePixelRatio || this.c.mozBackingStorePixelRatio || this.c.msBackingStorePixelRatio || this.c.oBackingStorePixelRatio || this.c.backingStorePixelRatio || 1 ); // detects relative width / height this.relativeWidth = ((this.o.width % 1 !== 0) && this.o.width.indexOf('%')); this.relativeHeight = ((this.o.height % 1 !== 0) && this.o.height.indexOf('%')); this.relative = (this.relativeWidth || this.relativeHeight); // computes size and carves the component this._carve(); // prepares props for transaction if (this.v instanceof Object) { this.cv = {}; this.copy(this.v, this.cv); } else { this.cv = this.v; } // binds configure event this.$ .bind("configure", cf) .parent() .bind("configure", cf); // finalize init this._listen() ._configure() ._xy() .init(); this.isInit = true; // the most important ! this._draw(); return this; }; this._carve = function() { if(this.relative) { var w = this.relativeWidth ? this.$div.parent().width() * parseInt(this.o.width) / 100 : this.$div.parent().width(), h = this.relativeHeight ? this.$div.parent().height() * parseInt(this.o.height) / 100 : this.$div.parent().height(); // apply relative this.w = this.h = Math.min(w, h); } else { this.w = this.o.width; this.h = this.o.height; } // finalize div this.$div.css({ 'width': this.w + 'px', 'height': this.h + 'px' }); // finalize canvas with computed width this.$c.attr({ width: this.w, height: this.h }); // scaling if (this.scale !== 1) { this.$c[0].width = this.$c[0].width * this.scale; this.$c[0].height = this.$c[0].height * this.scale; this.$c.width(this.w); this.$c.height(this.h); } return this; } this._draw = function () { // canvas pre-rendering var d = true; s.g = s.c; s.clear(); s.dH && (d = s.dH()); (d !== false) && s.draw(); }; this._touch = function (e) { var touchMove = function (e) { var v = s.xy2val( e.originalEvent.touches[s.t].pageX, e.originalEvent.touches[s.t].pageY ); if (v == s.cv) return; if (s.cH && (s.cH(v) === false)) return; s.change(s._validate(v)); s._draw(); }; // get touches index this.t = k.c.t(e); // First touch touchMove(e); // Touch events listeners k.c.d .bind("touchmove.k", touchMove) .bind( "touchend.k" , function () { k.c.d.unbind('touchmove.k touchend.k'); s.val(s.cv); } ); return this; }; this._mouse = function (e) { var mouseMove = function (e) { var v = s.xy2val(e.pageX, e.pageY); if (v == s.cv) return; if (s.cH && (s.cH(v) === false)) return; s.change(s._validate(v)); s._draw(); }; // First click mouseMove(e); // Mouse events listeners k.c.d .bind("mousemove.k", mouseMove) .bind( // Escape key cancel current change "keyup.k" , function (e) { if (e.keyCode === 27) { k.c.d.unbind("mouseup.k mousemove.k keyup.k"); if ( s.eH && (s.eH() === false) ) return; s.cancel(); } } ) .bind( "mouseup.k" , function (e) { k.c.d.unbind('mousemove.k mouseup.k keyup.k'); s.val(s.cv); } ); return this; }; this._xy = function () { var o = this.$c.offset(); this.x = o.left; this.y = o.top; return this; }; this._listen = function () { if (!this.o.readOnly) { this.$c .bind( "mousedown" , function (e) { e.preventDefault(); s._xy()._mouse(e); } ) .bind( "touchstart" , function (e) { e.preventDefault(); s._xy()._touch(e); } ); this.listen(); } else { this.$.attr('readonly', 'readonly'); } if(this.relative) { $(window).resize(function() { s._carve() .init(); s._draw(); }); } return this; }; this._configure = function () { // Hooks if (this.o.draw) this.dH = this.o.draw; if (this.o.change) this.cH = this.o.change; if (this.o.cancel) this.eH = this.o.cancel; if (this.o.release) this.rH = this.o.release; if (this.o.displayPrevious) { this.pColor = this.h2rgba(this.o.fgColor, "0.4"); this.fgColor = this.h2rgba(this.o.fgColor, "0.6"); } else { this.fgColor = this.o.fgColor; } return this; }; this._clear = function () { this.$c[0].width = this.$c[0].width; }; this._validate = function(v) { return (~~ (((v < 0) ? -0.5 : 0.5) + (v/this.o.step))) * this.o.step; }; // Abstract methods this.listen = function () {}; // on start, one time this.extend = function () {}; // each time configure triggered this.init = function () {}; // each time configure triggered this.change = function (v) {}; // on change this.val = function (v) {}; // on release this.xy2val = function (x, y) {}; // this.draw = function () {}; // on change / on release this.clear = function () { this._clear(); }; // Utils this.h2rgba = function (h, a) { var rgb; h = h.substring(1,7) rgb = [parseInt(h.substring(0,2),16) ,parseInt(h.substring(2,4),16) ,parseInt(h.substring(4,6),16)]; return "rgba(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + "," + a + ")"; }; this.copy = function (f, t) { for (var i in f) { t[i] = f[i]; } }; }; /** * k.Dial */ k.Dial = function () { k.o.call(this); this.startAngle = null; this.xy = null; this.radius = null; this.lineWidth = null; this.cursorExt = null; this.w2 = null; this.PI2 = 2*Math.PI; this.extend = function () { this.o = $.extend( { bgColor : this.$.data('bgcolor') || '#EEEEEE', angleOffset : this.$.data('angleoffset') || 0, angleArc : this.$.data('anglearc') || 360, inline : true }, this.o ); }; this.val = function (v, triggerRelease) { if (null != v) { if ( triggerRelease !== false && (v != this.v) && this.rH && (this.rH(v) === false) ) return; this.cv = this.o.stopper ? max(min(v, this.o.max), this.o.min) : v; this.v = this.cv; this.$.val(this.v); this._draw(); } else { return this.v; } }; this.xy2val = function (x, y) { var a, ret; a = Math.atan2( x - (this.x + this.w2) , - (y - this.y - this.w2) ) - this.angleOffset; if(this.angleArc != this.PI2 && (a < 0) && (a > -0.5)) { // if isset angleArc option, set to min if .5 under min a = 0; } else if (a < 0) { a += this.PI2; } ret = ~~ (0.5 + (a * (this.o.max - this.o.min) / this.angleArc)) + this.o.min; this.o.stopper && (ret = max(min(ret, this.o.max), this.o.min)); return ret; }; this.listen = function () { // bind MouseWheel var s = this, mwTimerStop, mwTimerRelease, mw = function (e) { e.preventDefault(); var ori = e.originalEvent ,deltaX = ori.detail || ori.wheelDeltaX ,deltaY = ori.detail || ori.wheelDeltaY ,v = s._validate(s.$.val()) + (deltaX>0 || deltaY>0 ? s.o.step : deltaX<0 || deltaY<0 ? -s.o.step : 0); v = max(min(v, s.o.max), s.o.min); s.val(v, false); if(s.rH) { // Handle mousewheel stop clearTimeout(mwTimerStop); mwTimerStop = setTimeout(function() { s.rH(v); mwTimerStop = null; }, 100); // Handle mousewheel releases if(!mwTimerRelease) { mwTimerRelease = setTimeout(function() { if(mwTimerStop) s.rH(v); mwTimerRelease = null; }, 200); } } } , kval, to, m = 1, kv = {37:-s.o.step, 38:s.o.step, 39:s.o.step, 40:-s.o.step}; this.$ .bind( "keydown" ,function (e) { var kc = e.keyCode; // numpad support if(kc >= 96 && kc <= 105) { kc = e.keyCode = kc - 48; } kval = parseInt(String.fromCharCode(kc)); if (isNaN(kval)) { (kc !== 13) // enter && (kc !== 8) // bs && (kc !== 9) // tab && (kc !== 189) // - && (kc !== 190 || s.$.val().match(/\./)) // . only allowed once && e.preventDefault(); // arrows if ($.inArray(kc,[37,38,39,40]) > -1) { e.preventDefault(); var v = parseFloat(s.$.val()) + kv[kc] * m; s.o.stopper && (v = max(min(v, s.o.max), s.o.min)); s.change(v); s._draw(); // long time keydown speed-up to = window.setTimeout( function () { m *= 2; }, 30 ); } } } ) .bind( "keyup" ,function (e) { if (isNaN(kval)) { if (to) { window.clearTimeout(to); to = null; m = 1; s.val(s.$.val()); } } else { // kval postcond (s.$.val() > s.o.max && s.$.val(s.o.max)) || (s.$.val() < s.o.min && s.$.val(s.o.min)); } } ); this.$c.bind("mousewheel DOMMouseScroll", mw); this.$.bind("mousewheel DOMMouseScroll", mw) }; this.init = function () { if ( this.v < this.o.min || this.v > this.o.max ) this.v = this.o.min; this.$.val(this.v); this.w2 = this.w / 2; this.cursorExt = this.o.cursor / 100; this.xy = this.w2 * this.scale; this.lineWidth = this.xy * this.o.thickness; this.lineCap = this.o.lineCap; this.radius = this.xy - this.lineWidth / 2; this.o.angleOffset && (this.o.angleOffset = isNaN(this.o.angleOffset) ? 0 : this.o.angleOffset); this.o.angleArc && (this.o.angleArc = isNaN(this.o.angleArc) ? this.PI2 : this.o.angleArc); // deg to rad this.angleOffset = this.o.angleOffset * Math.PI / 180; this.angleArc = this.o.angleArc * Math.PI / 180; // compute start and end angles this.startAngle = 1.5 * Math.PI + this.angleOffset; this.endAngle = 1.5 * Math.PI + this.angleOffset + this.angleArc; var s = max( String(Math.abs(this.o.max)).length , String(Math.abs(this.o.min)).length , 2 ) + 2; this.o.displayInput && this.i.css({ 'width' : ((this.w / 2 + 4) >> 0) + 'px' ,'height' : ((this.w / 3) >> 0) + 'px' ,'position' : 'absolute' ,'vertical-align' : 'middle' ,'margin-top' : ((this.w / 3) >> 0) + 'px' ,'margin-left' : '-' + ((this.w * 3 / 4 + 2) >> 0) + 'px' ,'border' : 0 ,'background' : 'none' ,'font' : this.o.fontWeight + ' ' + ((this.w / s) >> 0) + 'px ' + this.o.font ,'text-align' : 'center' ,'color' : this.o.inputColor || this.o.fgColor ,'padding' : '0px' ,'-webkit-appearance': 'none' }) || this.i.css({ 'width' : '0px' ,'visibility' : 'hidden' }); }; this.change = function (v) { this.cv = v; this.$.val(v); }; this.angle = function (v) { return (v - this.o.min) * this.angleArc / (this.o.max - this.o.min); }; this.draw = function () { var c = this.g, // context a = this.angle(this.cv) // Angle , sat = this.startAngle // Start angle , eat = sat + a // End angle , sa, ea // Previous angles , r = 1; c.lineWidth = this.lineWidth; c.lineCap = this.lineCap; this.o.cursor && (sat = eat - this.cursorExt) && (eat = eat + this.cursorExt); c.beginPath(); c.strokeStyle = this.o.bgColor; c.arc(this.xy, this.xy, this.radius, this.endAngle - 0.00001, this.startAngle + 0.00001, true); c.stroke(); if (this.o.displayPrevious) { ea = this.startAngle + this.angle(this.v); sa = this.startAngle; this.o.cursor && (sa = ea - this.cursorExt) && (ea = ea + this.cursorExt); c.beginPath(); c.strokeStyle = this.pColor; c.arc(this.xy, this.xy, this.radius, sa - 0.00001, ea + 0.00001, false); c.stroke(); r = (this.cv == this.v); } c.beginPath(); c.strokeStyle = r ? this.o.fgColor : this.fgColor ; c.arc(this.xy, this.xy, this.radius, sat - 0.00001, eat + 0.00001, false); c.stroke(); }; this.cancel = function () { this.val(this.v); }; }; $.fn.dial = $.fn.knob = function (o) { return this.each( function () { var d = new k.Dial(); d.o = o; d.$ = $(this); d.run(); } ).parent(); }; })(jQuery);
JavaScript
/*! xCharts v0.3.0 Copyright (c) 2012, tenXer, Inc. All Rights Reserved. @license MIT license. http://github.com/tenXer/xcharts for details */ (function () { var xChart, _vis = {}, _scales = {}, _visutils = {}; (function(){var n=this,t=n._,r={},e=Array.prototype,u=Object.prototype,i=Function.prototype,a=e.push,o=e.slice,c=e.concat,l=u.toString,f=u.hasOwnProperty,s=e.forEach,p=e.map,v=e.reduce,h=e.reduceRight,g=e.filter,d=e.every,m=e.some,y=e.indexOf,b=e.lastIndexOf,x=Array.isArray,_=Object.keys,j=i.bind,w=function(n){return n instanceof w?n:this instanceof w?(this._wrapped=n,void 0):new w(n)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=w),exports._=w):n._=w,w.VERSION="1.4.3";var A=w.each=w.forEach=function(n,t,e){if(null!=n)if(s&&n.forEach===s)n.forEach(t,e);else if(n.length===+n.length){for(var u=0,i=n.length;i>u;u++)if(t.call(e,n[u],u,n)===r)return}else for(var a in n)if(w.has(n,a)&&t.call(e,n[a],a,n)===r)return};w.map=w.collect=function(n,t,r){var e=[];return null==n?e:p&&n.map===p?n.map(t,r):(A(n,function(n,u,i){e[e.length]=t.call(r,n,u,i)}),e)};var O="Reduce of empty array with no initial value";w.reduce=w.foldl=w.inject=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),v&&n.reduce===v)return e&&(t=w.bind(t,e)),u?n.reduce(t,r):n.reduce(t);if(A(n,function(n,i,a){u?r=t.call(e,r,n,i,a):(r=n,u=!0)}),!u)throw new TypeError(O);return r},w.reduceRight=w.foldr=function(n,t,r,e){var u=arguments.length>2;if(null==n&&(n=[]),h&&n.reduceRight===h)return e&&(t=w.bind(t,e)),u?n.reduceRight(t,r):n.reduceRight(t);var i=n.length;if(i!==+i){var a=w.keys(n);i=a.length}if(A(n,function(o,c,l){c=a?a[--i]:--i,u?r=t.call(e,r,n[c],c,l):(r=n[c],u=!0)}),!u)throw new TypeError(O);return r},w.find=w.detect=function(n,t,r){var e;return E(n,function(n,u,i){return t.call(r,n,u,i)?(e=n,!0):void 0}),e},w.filter=w.select=function(n,t,r){var e=[];return null==n?e:g&&n.filter===g?n.filter(t,r):(A(n,function(n,u,i){t.call(r,n,u,i)&&(e[e.length]=n)}),e)},w.reject=function(n,t,r){return w.filter(n,function(n,e,u){return!t.call(r,n,e,u)},r)},w.every=w.all=function(n,t,e){t||(t=w.identity);var u=!0;return null==n?u:d&&n.every===d?n.every(t,e):(A(n,function(n,i,a){return(u=u&&t.call(e,n,i,a))?void 0:r}),!!u)};var E=w.some=w.any=function(n,t,e){t||(t=w.identity);var u=!1;return null==n?u:m&&n.some===m?n.some(t,e):(A(n,function(n,i,a){return u||(u=t.call(e,n,i,a))?r:void 0}),!!u)};w.contains=w.include=function(n,t){return null==n?!1:y&&n.indexOf===y?-1!=n.indexOf(t):E(n,function(n){return n===t})},w.invoke=function(n,t){var r=o.call(arguments,2);return w.map(n,function(n){return(w.isFunction(t)?t:n[t]).apply(n,r)})},w.pluck=function(n,t){return w.map(n,function(n){return n[t]})},w.where=function(n,t){return w.isEmpty(t)?[]:w.filter(n,function(n){for(var r in t)if(t[r]!==n[r])return!1;return!0})},w.max=function(n,t,r){if(!t&&w.isArray(n)&&n[0]===+n[0]&&65535>n.length)return Math.max.apply(Math,n);if(!t&&w.isEmpty(n))return-1/0;var e={computed:-1/0,value:-1/0};return A(n,function(n,u,i){var a=t?t.call(r,n,u,i):n;a>=e.computed&&(e={value:n,computed:a})}),e.value},w.min=function(n,t,r){if(!t&&w.isArray(n)&&n[0]===+n[0]&&65535>n.length)return Math.min.apply(Math,n);if(!t&&w.isEmpty(n))return 1/0;var e={computed:1/0,value:1/0};return A(n,function(n,u,i){var a=t?t.call(r,n,u,i):n;e.computed>a&&(e={value:n,computed:a})}),e.value},w.shuffle=function(n){var t,r=0,e=[];return A(n,function(n){t=w.random(r++),e[r-1]=e[t],e[t]=n}),e};var F=function(n){return w.isFunction(n)?n:function(t){return t[n]}};w.sortBy=function(n,t,r){var e=F(t);return w.pluck(w.map(n,function(n,t,u){return{value:n,index:t,criteria:e.call(r,n,t,u)}}).sort(function(n,t){var r=n.criteria,e=t.criteria;if(r!==e){if(r>e||void 0===r)return 1;if(e>r||void 0===e)return-1}return n.index<t.index?-1:1}),"value")};var k=function(n,t,r,e){var u={},i=F(t||w.identity);return A(n,function(t,a){var o=i.call(r,t,a,n);e(u,o,t)}),u};w.groupBy=function(n,t,r){return k(n,t,r,function(n,t,r){(w.has(n,t)?n[t]:n[t]=[]).push(r)})},w.countBy=function(n,t,r){return k(n,t,r,function(n,t){w.has(n,t)||(n[t]=0),n[t]++})},w.sortedIndex=function(n,t,r,e){r=null==r?w.identity:F(r);for(var u=r.call(e,t),i=0,a=n.length;a>i;){var o=i+a>>>1;u>r.call(e,n[o])?i=o+1:a=o}return i},w.toArray=function(n){return n?w.isArray(n)?o.call(n):n.length===+n.length?w.map(n,w.identity):w.values(n):[]},w.size=function(n){return null==n?0:n.length===+n.length?n.length:w.keys(n).length},w.first=w.head=w.take=function(n,t,r){return null==n?void 0:null==t||r?n[0]:o.call(n,0,t)},w.initial=function(n,t,r){return o.call(n,0,n.length-(null==t||r?1:t))},w.last=function(n,t,r){return null==n?void 0:null==t||r?n[n.length-1]:o.call(n,Math.max(n.length-t,0))},w.rest=w.tail=w.drop=function(n,t,r){return o.call(n,null==t||r?1:t)},w.compact=function(n){return w.filter(n,w.identity)};var R=function(n,t,r){return A(n,function(n){w.isArray(n)?t?a.apply(r,n):R(n,t,r):r.push(n)}),r};w.flatten=function(n,t){return R(n,t,[])},w.without=function(n){return w.difference(n,o.call(arguments,1))},w.uniq=w.unique=function(n,t,r,e){w.isFunction(t)&&(e=r,r=t,t=!1);var u=r?w.map(n,r,e):n,i=[],a=[];return A(u,function(r,e){(t?e&&a[a.length-1]===r:w.contains(a,r))||(a.push(r),i.push(n[e]))}),i},w.union=function(){return w.uniq(c.apply(e,arguments))},w.intersection=function(n){var t=o.call(arguments,1);return w.filter(w.uniq(n),function(n){return w.every(t,function(t){return w.indexOf(t,n)>=0})})},w.difference=function(n){var t=c.apply(e,o.call(arguments,1));return w.filter(n,function(n){return!w.contains(t,n)})},w.zip=function(){for(var n=o.call(arguments),t=w.max(w.pluck(n,"length")),r=Array(t),e=0;t>e;e++)r[e]=w.pluck(n,""+e);return r},w.object=function(n,t){if(null==n)return{};for(var r={},e=0,u=n.length;u>e;e++)t?r[n[e]]=t[e]:r[n[e][0]]=n[e][1];return r},w.indexOf=function(n,t,r){if(null==n)return-1;var e=0,u=n.length;if(r){if("number"!=typeof r)return e=w.sortedIndex(n,t),n[e]===t?e:-1;e=0>r?Math.max(0,u+r):r}if(y&&n.indexOf===y)return n.indexOf(t,r);for(;u>e;e++)if(n[e]===t)return e;return-1},w.lastIndexOf=function(n,t,r){if(null==n)return-1;var e=null!=r;if(b&&n.lastIndexOf===b)return e?n.lastIndexOf(t,r):n.lastIndexOf(t);for(var u=e?r:n.length;u--;)if(n[u]===t)return u;return-1},w.range=function(n,t,r){1>=arguments.length&&(t=n||0,n=0),r=arguments[2]||1;for(var e=Math.max(Math.ceil((t-n)/r),0),u=0,i=Array(e);e>u;)i[u++]=n,n+=r;return i};var I=function(){};w.bind=function(n,t){var r,e;if(n.bind===j&&j)return j.apply(n,o.call(arguments,1));if(!w.isFunction(n))throw new TypeError;return r=o.call(arguments,2),e=function(){if(!(this instanceof e))return n.apply(t,r.concat(o.call(arguments)));I.prototype=n.prototype;var u=new I;I.prototype=null;var i=n.apply(u,r.concat(o.call(arguments)));return Object(i)===i?i:u}},w.bindAll=function(n){var t=o.call(arguments,1);return 0==t.length&&(t=w.functions(n)),A(t,function(t){n[t]=w.bind(n[t],n)}),n},w.memoize=function(n,t){var r={};return t||(t=w.identity),function(){var e=t.apply(this,arguments);return w.has(r,e)?r[e]:r[e]=n.apply(this,arguments)}},w.delay=function(n,t){var r=o.call(arguments,2);return setTimeout(function(){return n.apply(null,r)},t)},w.defer=function(n){return w.delay.apply(w,[n,1].concat(o.call(arguments,1)))},w.throttle=function(n,t){var r,e,u,i,a=0,o=function(){a=new Date,u=null,i=n.apply(r,e)};return function(){var c=new Date,l=t-(c-a);return r=this,e=arguments,0>=l?(clearTimeout(u),u=null,a=c,i=n.apply(r,e)):u||(u=setTimeout(o,l)),i}},w.debounce=function(n,t,r){var e,u;return function(){var i=this,a=arguments,o=function(){e=null,r||(u=n.apply(i,a))},c=r&&!e;return clearTimeout(e),e=setTimeout(o,t),c&&(u=n.apply(i,a)),u}},w.once=function(n){var t,r=!1;return function(){return r?t:(r=!0,t=n.apply(this,arguments),n=null,t)}},w.wrap=function(n,t){return function(){var r=[n];return a.apply(r,arguments),t.apply(this,r)}},w.compose=function(){var n=arguments;return function(){for(var t=arguments,r=n.length-1;r>=0;r--)t=[n[r].apply(this,t)];return t[0]}},w.after=function(n,t){return 0>=n?t():function(){return 1>--n?t.apply(this,arguments):void 0}},w.keys=_||function(n){if(n!==Object(n))throw new TypeError("Invalid object");var t=[];for(var r in n)w.has(n,r)&&(t[t.length]=r);return t},w.values=function(n){var t=[];for(var r in n)w.has(n,r)&&t.push(n[r]);return t},w.pairs=function(n){var t=[];for(var r in n)w.has(n,r)&&t.push([r,n[r]]);return t},w.invert=function(n){var t={};for(var r in n)w.has(n,r)&&(t[n[r]]=r);return t},w.functions=w.methods=function(n){var t=[];for(var r in n)w.isFunction(n[r])&&t.push(r);return t.sort()},w.extend=function(n){return A(o.call(arguments,1),function(t){if(t)for(var r in t)n[r]=t[r]}),n},w.pick=function(n){var t={},r=c.apply(e,o.call(arguments,1));return A(r,function(r){r in n&&(t[r]=n[r])}),t},w.omit=function(n){var t={},r=c.apply(e,o.call(arguments,1));for(var u in n)w.contains(r,u)||(t[u]=n[u]);return t},w.defaults=function(n){return A(o.call(arguments,1),function(t){if(t)for(var r in t)null==n[r]&&(n[r]=t[r])}),n},w.clone=function(n){return w.isObject(n)?w.isArray(n)?n.slice():w.extend({},n):n},w.tap=function(n,t){return t(n),n};var S=function(n,t,r,e){if(n===t)return 0!==n||1/n==1/t;if(null==n||null==t)return n===t;n instanceof w&&(n=n._wrapped),t instanceof w&&(t=t._wrapped);var u=l.call(n);if(u!=l.call(t))return!1;switch(u){case"[object String]":return n==t+"";case"[object Number]":return n!=+n?t!=+t:0==n?1/n==1/t:n==+t;case"[object Date]":case"[object Boolean]":return+n==+t;case"[object RegExp]":return n.source==t.source&&n.global==t.global&&n.multiline==t.multiline&&n.ignoreCase==t.ignoreCase}if("object"!=typeof n||"object"!=typeof t)return!1;for(var i=r.length;i--;)if(r[i]==n)return e[i]==t;r.push(n),e.push(t);var a=0,o=!0;if("[object Array]"==u){if(a=n.length,o=a==t.length)for(;a--&&(o=S(n[a],t[a],r,e)););}else{var c=n.constructor,f=t.constructor;if(c!==f&&!(w.isFunction(c)&&c instanceof c&&w.isFunction(f)&&f instanceof f))return!1;for(var s in n)if(w.has(n,s)&&(a++,!(o=w.has(t,s)&&S(n[s],t[s],r,e))))break;if(o){for(s in t)if(w.has(t,s)&&!a--)break;o=!a}}return r.pop(),e.pop(),o};w.isEqual=function(n,t){return S(n,t,[],[])},w.isEmpty=function(n){if(null==n)return!0;if(w.isArray(n)||w.isString(n))return 0===n.length;for(var t in n)if(w.has(n,t))return!1;return!0},w.isElement=function(n){return!(!n||1!==n.nodeType)},w.isArray=x||function(n){return"[object Array]"==l.call(n)},w.isObject=function(n){return n===Object(n)},A(["Arguments","Function","String","Number","Date","RegExp"],function(n){w["is"+n]=function(t){return l.call(t)=="[object "+n+"]"}}),w.isArguments(arguments)||(w.isArguments=function(n){return!(!n||!w.has(n,"callee"))}),w.isFunction=function(n){return"function"==typeof n},w.isFinite=function(n){return isFinite(n)&&!isNaN(parseFloat(n))},w.isNaN=function(n){return w.isNumber(n)&&n!=+n},w.isBoolean=function(n){return n===!0||n===!1||"[object Boolean]"==l.call(n)},w.isNull=function(n){return null===n},w.isUndefined=function(n){return void 0===n},w.has=function(n,t){return f.call(n,t)},w.noConflict=function(){return n._=t,this},w.identity=function(n){return n},w.times=function(n,t,r){for(var e=Array(n),u=0;n>u;u++)e[u]=t.call(r,u);return e},w.random=function(n,t){return null==t&&(t=n,n=0),n+(0|Math.random()*(t-n+1))};var T={escape:{"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","/":"&#x2F;"}};T.unescape=w.invert(T.escape);var M={escape:RegExp("["+w.keys(T.escape).join("")+"]","g"),unescape:RegExp("("+w.keys(T.unescape).join("|")+")","g")};w.each(["escape","unescape"],function(n){w[n]=function(t){return null==t?"":(""+t).replace(M[n],function(t){return T[n][t]})}}),w.result=function(n,t){if(null==n)return null;var r=n[t];return w.isFunction(r)?r.call(n):r},w.mixin=function(n){A(w.functions(n),function(t){var r=w[t]=n[t];w.prototype[t]=function(){var n=[this._wrapped];return a.apply(n,arguments),z.call(this,r.apply(w,n))}})};var N=0;w.uniqueId=function(n){var t=""+ ++N;return n?n+t:t},w.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var q=/(.)^/,B={"'":"'","\\":"\\","\r":"r","\n":"n"," ":"t","\u2028":"u2028","\u2029":"u2029"},D=/\\|'|\r|\n|\t|\u2028|\u2029/g;w.template=function(n,t,r){r=w.defaults({},r,w.templateSettings);var e=RegExp([(r.escape||q).source,(r.interpolate||q).source,(r.evaluate||q).source].join("|")+"|$","g"),u=0,i="__p+='";n.replace(e,function(t,r,e,a,o){return i+=n.slice(u,o).replace(D,function(n){return"\\"+B[n]}),r&&(i+="'+\n((__t=("+r+"))==null?'':_.escape(__t))+\n'"),e&&(i+="'+\n((__t=("+e+"))==null?'':__t)+\n'"),a&&(i+="';\n"+a+"\n__p+='"),u=o+t.length,t}),i+="';\n",r.variable||(i="with(obj||{}){\n"+i+"}\n"),i="var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n"+i+"return __p;\n";try{var a=Function(r.variable||"obj","_",i)}catch(o){throw o.source=i,o}if(t)return a(t,w);var c=function(n){return a.call(this,n,w)};return c.source="function("+(r.variable||"obj")+"){\n"+i+"}",c},w.chain=function(n){return w(n).chain()};var z=function(n){return this._chain?w(n).chain():n};w.mixin(w),A(["pop","push","reverse","shift","sort","splice","unshift"],function(n){var t=e[n];w.prototype[n]=function(){var r=this._wrapped;return t.apply(r,arguments),"shift"!=n&&"splice"!=n||0!==r.length||delete r[0],z.call(this,r)}}),A(["concat","join","slice"],function(n){var t=e[n];w.prototype[n]=function(){return z.call(this,t.apply(this._wrapped,arguments))}}),w.extend(w.prototype,{chain:function(){return this._chain=!0,this},value:function(){return this._wrapped}})}).call(this);function getInsertionPoint(zIndex) { return _.chain(_.range(zIndex, 10)).reverse().map(function (z) { return 'g[data-index="' + z + '"]'; }).value().join(', '); } function colorClass(el, i) { var c = el.getAttribute('class'); return ((c !== null) ? c.replace(/color\d+/g, '') : '') + ' color' + i; } _visutils = { getInsertionPoint: getInsertionPoint, colorClass: colorClass }; var local = this, defaultSpacing = 0.25; function _getDomain(data, axis) { return _.chain(data) .pluck('data') .flatten() .pluck(axis) .uniq() .filter(function (d) { return d !== undefined && d !== null; }) .value() .sort(d3.ascending); } _scales.ordinal = function (data, axis, bounds, extents) { var domain = _getDomain(data, axis); return d3.scale.ordinal() .domain(domain) .rangeRoundBands(bounds, defaultSpacing); }; _scales.linear = function (data, axis, bounds, extents) { return d3.scale.linear() .domain(extents) .nice() .rangeRound(bounds); }; _scales.exponential = function (data, axis, bounds, extents) { return d3.scale.pow() .exponent(0.65) .domain(extents) .nice() .rangeRound(bounds); }; _scales.time = function (data, axis, bounds, extents) { return d3.time.scale() .domain(_.map(extents, function (d) { return new Date(d); })) .range(bounds); }; function _extendDomain(domain, axis) { var min = domain[0], max = domain[1], diff, e; if (min === max) { e = Math.max(Math.round(min / 10), 4); min -= e; max += e; } diff = max - min; min = (min) ? min - (diff / 10) : min; min = (domain[0] > 0) ? Math.max(min, 0) : min; max = (max) ? max + (diff / 10) : max; max = (domain[1] < 0) ? Math.min(max, 0) : max; return [min, max]; } function _getExtents(options, data, xType, yType) { var extents, nData = _.chain(data) .pluck('data') .flatten() .value(); extents = { x: d3.extent(nData, function (d) { return d.x; }), y: d3.extent(nData, function (d) { return d.y; }) }; _.each([xType, yType], function (type, i) { var axis = (i) ? 'y' : 'x', extended; extents[axis] = d3.extent(nData, function (d) { return d[axis]; }); if (type === 'ordinal') { return; } _.each([axis + 'Min', axis + 'Max'], function (minMax, i) { if (type !== 'time') { extended = _extendDomain(extents[axis]); } if (options.hasOwnProperty(minMax) && options[minMax] !== null) { extents[axis][i] = options[minMax]; } else if (type !== 'time') { extents[axis][i] = extended[i]; } }); }); return extents; } _scales.xy = function (self, data, xType, yType) { var o = self._options, extents = _getExtents(o, data, xType, yType), scales = {}, horiz = [o.axisPaddingLeft, self._width], vert = [self._height, o.axisPaddingTop], xScale, yScale; _.each([xType, yType], function (type, i) { var axis = (i === 0) ? 'x' : 'y', bounds = (i === 0) ? horiz : vert, fn = xChart.getScale(type); scales[axis] = fn(data, axis, bounds, extents[axis]); }); return scales; }; (function () { var zIndex = 2, selector = 'g.bar', insertBefore = _visutils.getInsertionPoint(zIndex); function postUpdateScale(self, scaleData, mainData, compData) { self.xScale2 = d3.scale.ordinal() .domain(d3.range(0, mainData.length)) .rangeRoundBands([0, self.xScale.rangeBand()], 0.08); } function enter(self, storage, className, data, callbacks) { var barGroups, bars, yZero = self.yZero; barGroups = self._g.selectAll(selector + className) .data(data, function (d) { return d.className; }); barGroups.enter().insert('g', insertBefore) .attr('data-index', zIndex) .style('opacity', 0) .attr('class', function (d, i) { var cl = _.uniq((className + d.className).split('.')).join(' '); return cl + ' bar ' + _visutils.colorClass(this, i); }) .attr('transform', function (d, i) { return 'translate(' + self.xScale2(i) + ',0)'; }); bars = barGroups.selectAll('rect') .data(function (d) { return d.data; }, function (d) { return d.x; }); bars.enter().append('rect') .attr('width', 0) .attr('rx', 3) .attr('ry', 3) .attr('x', function (d) { return self.xScale(d.x) + (self.xScale2.rangeBand() / 2); }) .attr('height', function (d) { return Math.abs(yZero - self.yScale(d.y)); }) .attr('y', function (d) { return (d.y < 0) ? yZero : self.yScale(d.y); }) .on('mouseover', callbacks.mouseover) .on('mouseout', callbacks.mouseout) .on('click', callbacks.click); storage.barGroups = barGroups; storage.bars = bars; } function update(self, storage, timing) { var yZero = self.yZero; storage.barGroups .attr('class', function (d, i) { return _visutils.colorClass(this, i); }) .transition().duration(timing) .style('opacity', 1) .attr('transform', function (d, i) { return 'translate(' + self.xScale2(i) + ',0)'; }); storage.bars.transition().duration(timing) .attr('width', self.xScale2.rangeBand()) .attr('x', function (d) { return self.xScale(d.x); }) .attr('height', function (d) { return Math.abs(yZero - self.yScale(d.y)); }) .attr('y', function (d) { return (d.y < 0) ? yZero : self.yScale(d.y); }); } function exit(self, storage, timing) { storage.bars.exit() .transition().duration(timing) .attr('width', 0) .remove(); storage.barGroups.exit() .transition().duration(timing) .style('opacity', 0) .remove(); } function destroy(self, storage, timing) { var band = (self.xScale2) ? self.xScale2.rangeBand() / 2 : 0; delete self.xScale2; storage.bars .transition().duration(timing) .attr('width', 0) .attr('x', function (d) { return self.xScale(d.x) + band; }); } _vis.bar = { postUpdateScale: postUpdateScale, enter: enter, update: update, exit: exit, destroy: destroy }; }()); (function () { var zIndex = 3, selector = 'g.line', insertBefore = _visutils.getInsertionPoint(zIndex); function enter(self, storage, className, data, callbacks) { var inter = self._options.interpolation, x = function (d, i) { if (!self.xScale2 && !self.xScale.rangeBand) { return self.xScale(d.x); } return self.xScale(d.x) + (self.xScale.rangeBand() / 2); }, y = function (d) { return self.yScale(d.y); }, line = d3.svg.line() .x(x) .interpolate(inter), area = d3.svg.area() .x(x) .y1(self.yZero) .interpolate(inter), container, fills, paths; function datum(d) { return [d.data]; } container = self._g.selectAll(selector + className) .data(data, function (d) { return d.className; }); container.enter().insert('g', insertBefore) .attr('data-index', zIndex) .attr('class', function (d, i) { var cl = _.uniq((className + d.className).split('.')).join(' '); return cl + ' line ' + _visutils.colorClass(this, i); }); fills = container.selectAll('path.fill') .data(datum); fills.enter().append('path') .attr('class', 'fill') .style('opacity', 0) .attr('d', area.y0(y)); paths = container.selectAll('path.line') .data(datum); paths.enter().append('path') .attr('class', 'line') .style('opacity', 0) .attr('d', line.y(y)); storage.lineContainers = container; storage.lineFills = fills; storage.linePaths = paths; storage.lineX = x; storage.lineY = y; storage.lineA = area; storage.line = line; } function update(self, storage, timing) { storage.lineContainers .attr('class', function (d, i) { return _visutils.colorClass(this, i); }); storage.lineFills.transition().duration(timing) .style('opacity', 1) .attr('d', storage.lineA.y0(storage.lineY)); storage.linePaths.transition().duration(timing) .style('opacity', 1) .attr('d', storage.line.y(storage.lineY)); } function exit(self, storage) { storage.linePaths.exit() .style('opacity', 0) .remove(); storage.lineFills.exit() .style('opacity', 0) .remove(); storage.lineContainers.exit() .remove(); } function destroy(self, storage, timing) { storage.linePaths.transition().duration(timing) .style('opacity', 0); storage.lineFills.transition().duration(timing) .style('opacity', 0); } _vis.line = { enter: enter, update: update, exit: exit, destroy: destroy }; }()); (function () { var line = _vis.line; function enter(self, storage, className, data, callbacks) { var circles; line.enter(self, storage, className, data, callbacks); circles = storage.lineContainers.selectAll('circle') .data(function (d) { return d.data; }, function (d) { return d.x; }); circles.enter().append('circle') .style('opacity', 0) .attr('cx', storage.lineX) .attr('cy', storage.lineY) .attr('r', 5) .on('mouseover', callbacks.mouseover) .on('mouseout', callbacks.mouseout) .on('click', callbacks.click); storage.lineCircles = circles; } function update(self, storage, timing) { line.update.apply(null, _.toArray(arguments)); storage.lineCircles.transition().duration(timing) .style('opacity', 1) .attr('cx', storage.lineX) .attr('cy', storage.lineY); } function exit(self, storage) { storage.lineCircles.exit() .remove(); line.exit.apply(null, _.toArray(arguments)); } function destroy(self, storage, timing) { line.destroy.apply(null, _.toArray(arguments)); if (!storage.lineCircles) { return; } storage.lineCircles.transition().duration(timing) .style('opacity', 0); } _vis['line-dotted'] = { enter: enter, update: update, exit: exit, destroy: destroy }; }()); (function () { var line = _vis['line-dotted']; function enter(self, storage, className, data, callbacks) { line.enter(self, storage, className, data, callbacks); } function _accumulate_data(data) { function reduce(memo, num) { return memo + num.y; } var nData = _.map(data, function (set) { var i = set.data.length, d = _.clone(set.data); set = _.clone(set); while (i) { i -= 1; // Need to clone here, otherwise we are actually setting the same // data onto the original data set. d[i] = _.clone(set.data[i]); d[i].y0 = set.data[i].y; d[i].y = _.reduce(_.first(set.data, i), reduce, set.data[i].y); } return _.extend(set, { data: d }); }); return nData; } function _resetData(self) { if (!self.hasOwnProperty('cumulativeOMainData')) { return; } self._mainData = self.cumulativeOMainData; delete self.cumulativeOMainData; self._compData = self.cumulativeOCompData; delete self.cumulativeOCompData; } function preUpdateScale(self, data) { _resetData(self); self.cumulativeOMainData = self._mainData; self._mainData = _accumulate_data(self._mainData); self.cumulativeOCompData = self._compData; self._compData = _accumulate_data(self._compData); } function destroy(self, storage, timing) { _resetData(self); line.destroy.apply(null, _.toArray(arguments)); } _vis.cumulative = { preUpdateScale: preUpdateScale, enter: enter, update: line.update, exit: line.exit, destroy: destroy }; }()); var emptyData = [[]], defaults = { // User interaction callbacks mouseover: function (data, i) {}, mouseout: function (data, i) {}, click: function (data, i) {}, // Padding between the axes and the contents of the chart axisPaddingTop: 0, axisPaddingRight: 0, axisPaddingBottom: 5, axisPaddingLeft: 20, // Padding around the edge of the chart (space for axis labels, etc) paddingTop: 0, paddingRight: 0, paddingBottom: 20, paddingLeft: 60, // Axis tick formatting tickHintX: 10, tickFormatX: function (x) { return x; }, tickHintY: 10, tickFormatY: function (y) { return y; }, // Min/Max Axis Values xMin: null, xMax: null, yMin: null, yMax: null, // Pre-format input data dataFormatX: function (x) { return x; }, dataFormatY: function (y) { return y; }, unsupported: function (selector) { d3.select(selector).text('SVG is not supported on your browser'); }, // Callback functions if no data empty: function (self, selector, d) {}, notempty: function (self, selector) {}, timing: 750, // Line interpolation interpolation: 'monotone', // Data sorting sortX: function (a, b) { return (!a.x && !b.x) ? 0 : (a.x < b.x) ? -1 : 1; } }; // What/how should the warning/error be presented? function svgEnabled() { var d = document; return (!!d.createElementNS && !!d.createElementNS('http://www.w3.org/2000/svg', 'svg').createSVGRect); } /** * Creates a new chart * * @param string type The drawing type for the main data * @param array data Data to render in the chart * @param string selector CSS Selector for the parent element for the chart * @param object options Optional. See `defaults` for options * * Examples: * var data = { * "main": [ * { * "data": [ * { * "x": "2012-08-09T07:00:00.522Z", * "y": 68 * }, * { * "x": "2012-08-10T07:00:00.522Z", * "y": 295 * }, * { * "x": "2012-08-11T07:00:00.522Z", * "y": 339 * }, * ], * "className": ".foo" * } * ], * "xScale": "ordinal", * "yScale": "linear", * "comp": [ * { * "data": [ * { * "x": "2012-08-09T07:00:00.522Z", * "y": 288 * }, * { * "x": "2012-08-10T07:00:00.522Z", * "y": 407 * }, * { * "x": "2012-08-11T07:00:00.522Z", * "y": 459 * } * ], * "className": ".comp.comp_foo", * "type": "line-arrowed" * } * ] * }, * myChart = new Chart('bar', data, '#chart'); * */ function xChart(type, data, selector, options) { var self = this, resizeLock; self._options = options = _.defaults(options || {}, defaults); if (svgEnabled() === false) { return options.unsupported(selector); } self._selector = selector; self._container = d3.select(selector); self._drawSvg(); self._mainStorage = {}; self._compStorage = {}; data = _.clone(data); if (type && !data.type) { data.type = type; } self.setData(data); d3.select(window).on('resize.for.' + selector, function () { if (resizeLock) { clearTimeout(resizeLock); } resizeLock = setTimeout(function () { resizeLock = null; self._resize(); }, 500); }); } /** * Add a visualization type * * @param string type Unique key/name used with setType * @param object vis object map of vis methods */ xChart.setVis = function (type, vis) { if (_vis.hasOwnProperty(type)) { throw 'Cannot override vis type "' + type + '".'; } _vis[type] = vis; }; /** * Get a clone of a visualization * Useful for extending vis functionality * * @param string type Unique key/name of the vis */ xChart.getVis = function (type) { if (!_vis.hasOwnProperty(type)) { throw 'Vis type "' + type + '" does not exist.'; } return _.clone(_vis[type]); }; xChart.setScale = function (name, fn) { if (_scales.hasOwnProperty(name)) { throw 'Scale type "' + name + '" already exists.'; } _scales[name] = fn; }; xChart.getScale = function (name) { if (!_scales.hasOwnProperty(name)) { throw 'Scale type "' + name + '" does not exist.'; } return _scales[name]; }; xChart.visutils = _visutils; _.defaults(xChart.prototype, { /** * Set or change the drawing type for the main data. * * @param string type Must be an available drawing type * */ setType: function (type, skipDraw) { var self = this; if (self._type && type === self._type) { return; } if (!_vis.hasOwnProperty(type)) { throw 'Vis type "' + type + '" is not defined.'; } if (self._type) { self._destroy(self._vis, self._mainStorage); } self._type = type; self._vis = _vis[type]; if (!skipDraw) { self._draw(); } }, /** * Set and update the data for the chart. Optionally skip drawing. * * @param object data New data. See new xChart example for format * */ setData: function (data) { var self = this, o = self._options, nData = _.clone(data); if (!data.hasOwnProperty('main')) { throw 'No "main" key found in given chart data.'; } switch (data.type) { case 'bar': // force the xScale to be ordinal data.xScale = 'ordinal'; break; case undefined: data.type = self._type; break; } o.xMin = (isNaN(parseInt(data.xMin, 10))) ? o.xMin : data.xMin; o.xMax = (isNaN(parseInt(data.xMax, 10))) ? o.xMax : data.xMax; o.yMin = (isNaN(parseInt(data.yMin, 10))) ? o.yMin : data.yMin; o.yMax = (isNaN(parseInt(data.yMax, 10))) ? o.yMax : data.yMax; if (self._vis) { self._destroy(self._vis, self._mainStorage); } self.setType(data.type, true); function _mapData(set) { var d = _.map(_.clone(set.data), function (p) { var np = _.clone(p); if (p.hasOwnProperty('x')) { np.x = o.dataFormatX(p.x); } if (p.hasOwnProperty('y')) { np.y = o.dataFormatY(p.y); } return np; }).sort(o.sortX); return _.extend(_.clone(set), { data: d }); } nData.main = _.map(nData.main, _mapData); self._mainData = nData.main; self._xScaleType = nData.xScale; self._yScaleType = nData.yScale; if (nData.hasOwnProperty('comp')) { nData.comp = _.map(nData.comp, _mapData); self._compData = nData.comp; } else { self._compData = []; } self._draw(); }, /** * Change the scale of an axis * * @param string axis Name of an axis. One of 'x' or 'y' * @param string type Name of the scale type * */ setScale: function (axis, type) { var self = this; switch (axis) { case 'x': self._xScaleType = type; break; case 'y': self._yScaleType = type; break; default: throw 'Cannot change scale of unknown axis "' + axis + '".'; } self._draw(); }, /** * Create the SVG element and g container. Resize if necessary. */ _drawSvg: function () { var self = this, c = self._container, options = self._options, width = parseInt(c.style('width').replace('px', ''), 10), height = parseInt(c.style('height').replace('px', ''), 10), svg, g, gScale; svg = c.selectAll('svg') .data(emptyData); svg.enter().append('svg') // Inherit the height and width from the parent element .attr('height', height) .attr('width', width) .attr('class', 'xchart'); svg.transition() .attr('width', width) .attr('height', height); g = svg.selectAll('g') .data(emptyData); g.enter().append('g') .attr( 'transform', 'translate(' + options.paddingLeft + ',' + options.paddingTop + ')' ); gScale = g.selectAll('g.scale') .data(emptyData); gScale.enter().append('g') .attr('class', 'scale'); self._svg = svg; self._g = g; self._gScale = gScale; self._height = height - options.paddingTop - options.paddingBottom - options.axisPaddingTop - options.axisPaddingBottom; self._width = width - options.paddingLeft - options.paddingRight - options.axisPaddingLeft - options.axisPaddingRight; }, /** * Resize the visualization */ _resize: function (event) { var self = this; self._drawSvg(); self._draw(); }, /** * Draw the x and y axes */ _drawAxes: function () { if (this._noData) { return; } var self = this, o = self._options, t = self._gScale.transition().duration(o.timing), xTicks = o.tickHintX, yTicks = o.tickHintY, bottom = self._height + o.axisPaddingTop + o.axisPaddingBottom, zeroLine = d3.svg.line().x(function (d) { return d; }), zLine, zLinePath, xAxis, xRules, yAxis, yRules, labels; xRules = d3.svg.axis() .scale(self.xScale) .ticks(xTicks) .tickSize(-self._height) .tickFormat(o.tickFormatX) .orient('bottom'); xAxis = self._gScale.selectAll('g.axisX') .data(emptyData); xAxis.enter().append('g') .attr('class', 'axis axisX') .attr('transform', 'translate(0,' + bottom + ')'); xAxis.call(xRules); labels = self._gScale.selectAll('.axisX g')[0]; if (labels.length > (self._width / 80)) { labels.sort(function (a, b) { var r = /translate\(([^,)]+)/; a = a.getAttribute('transform').match(r); b = b.getAttribute('transform').match(r); return parseFloat(a[1], 10) - parseFloat(b[1], 10); }); d3.selectAll(labels) .filter(function (d, i) { return i % (Math.ceil(labels.length / xTicks) + 1); }) .remove(); } yRules = d3.svg.axis() .scale(self.yScale) .ticks(yTicks) .tickSize(-self._width - o.axisPaddingRight - o.axisPaddingLeft) .tickFormat(o.tickFormatY) .orient('left'); yAxis = self._gScale.selectAll('g.axisY') .data(emptyData); yAxis.enter().append('g') .attr('class', 'axis axisY') .attr('transform', 'translate(0,0)'); t.selectAll('g.axisY') .call(yRules); // zero line zLine = self._gScale.selectAll('g.axisZero') .data([[]]); zLine.enter().append('g') .attr('class', 'axisZero'); zLinePath = zLine.selectAll('line') .data([[]]); zLinePath.enter().append('line') .attr('x1', 0) .attr('x2', self._width + o.axisPaddingLeft + o.axisPaddingRight) .attr('y1', self.yZero) .attr('y2', self.yZero); zLinePath.transition().duration(o.timing) .attr('y1', self.yZero) .attr('y2', self.yZero); }, /** * Update the x and y scales (used when drawing) * * Optional methods in drawing types: * preUpdateScale * postUpdateScale * * Example implementation in vis type: * * function postUpdateScale(self, scaleData, mainData, compData) { * self.xScale2 = d3.scale.ordinal() * .domain(d3.range(0, mainData.length)) * .rangeRoundBands([0, self.xScale.rangeBand()], 0.08); * } * */ _updateScale: function () { var self = this, _unionData = function () { return _.union(self._mainData, self._compData); }, scaleData = _unionData(), vis = self._vis, scale, min; delete self.xScale; delete self.yScale; delete self.yZero; if (vis.hasOwnProperty('preUpdateScale')) { vis.preUpdateScale(self, scaleData, self._mainData, self._compData); } // Just in case preUpdateScale modified scaleData = _unionData(); scale = _scales.xy(self, scaleData, self._xScaleType, self._yScaleType); self.xScale = scale.x; self.yScale = scale.y; min = self.yScale.domain()[0]; self.yZero = (min > 0) ? self.yScale(min) : self.yScale(0); if (vis.hasOwnProperty('postUpdateScale')) { vis.postUpdateScale(self, scaleData, self._mainData, self._compData); } }, /** * Create (Enter) the elements for the vis * * Required method * * Example implementation in vis type: * * function enter(self, data, callbacks) { * var foo = self._g.selectAll('g.foobar') * .data(data); * foo.enter().append('g') * .attr('class', 'foobar'); * self.foo = foo; * } */ _enter: function (vis, storage, data, className) { var self = this, callbacks = { click: self._options.click, mouseover: self._options.mouseover, mouseout: self._options.mouseout }; self._checkVisMethod(vis, 'enter'); vis.enter(self, storage, className, data, callbacks); }, /** * Update the elements opened by the select method * * Required method * * Example implementation in vis type: * * function update(self, timing) { * self.bars.transition().duration(timing) * .attr('width', self.xScale2.rangeBand()) * .attr('height', function (d) { * return self.yScale(d.y); * }); * } */ _update: function (vis, storage) { var self = this; self._checkVisMethod(vis, 'update'); vis.update(self, storage, self._options.timing); }, /** * Remove or transition out the elements that no longer have data * * Required method * * Example implementation in vis type: * * function exit(self) { * self.bars.exit().remove(); * } */ _exit: function (vis, storage) { var self = this; self._checkVisMethod(vis, 'exit'); vis.exit(self, storage, self._options.timing); }, /** * Destroy the current vis type (transition to new type) * * Required method * * Example implementation in vis type: * * function destroy(self, timing) { * self.bars.transition().duration(timing) * attr('height', 0); * delete self.bars; * } */ _destroy: function (vis, storage) { var self = this; self._checkVisMethod(vis, 'destroy'); try { vis.destroy(self, storage, self._options.timing); } catch (e) {} }, /** * Draw the visualization */ _draw: function () { var self = this, o = self._options, comp, compKeys; self._noData = _.flatten(_.pluck(self._mainData, 'data') .concat(_.pluck(self._compData, 'data'))).length === 0; self._updateScale(); self._drawAxes(); self._enter(self._vis, self._mainStorage, self._mainData, '.main'); self._exit(self._vis, self._mainStorage); self._update(self._vis, self._mainStorage); comp = _.chain(self._compData).groupBy(function (d) { return d.type; }); compKeys = comp.keys(); // Find old comp vis items and remove any that no longer exist _.each(self._compStorage, function (d, key) { if (-1 === compKeys.indexOf(key).value()) { var vis = _vis[key]; self._enter(vis, d, [], '.comp.' + key.replace(/\W+/g, '')); self._exit(vis, d); } }); comp.each(function (d, key) { var vis = _vis[key], storage; if (!self._compStorage.hasOwnProperty(key)) { self._compStorage[key] = {}; } storage = self._compStorage[key]; self._enter(vis, storage, d, '.comp.' + key.replace(/\W+/g, '')); self._exit(vis, storage); self._update(vis, storage); }); if (self._noData) { o.empty(self, self._selector, self._mainData); } else { o.notempty(self, self._selector); } }, /** * Ensure drawing method exists */ _checkVisMethod: function (vis, method) { var self = this; if (!vis[method]) { throw 'Required method "' + method + '" not found on vis type "' + self._type + '".'; } } }); if (typeof define === 'function' && define.amd && typeof define.amd === 'object') { define(function () { return xChart; }); return; } window.xChart = xChart; }());
JavaScript
/*! * Thumbnail helper for fancyBox * version: 1.0.7 (Mon, 01 Oct 2012) * @requires fancyBox v2.0 or later * * Usage: * $(".fancybox").fancybox({ * helpers : { * thumbs: { * width : 50, * height : 50 * } * } * }); * */ (function ($) { //Shortcut for fancyBox object var F = $.fancybox; //Add helper object F.helpers.thumbs = { defaults : { width : 50, // thumbnail width height : 50, // thumbnail height position : 'bottom', // 'top' or 'bottom' source : function ( item ) { // function to obtain the URL of the thumbnail image var href; if (item.element) { href = $(item.element).find('img').attr('src'); } if (!href && item.type === 'image' && item.href) { href = item.href; } return href; } }, wrap : null, list : null, width : 0, init: function (opts, obj) { var that = this, list, thumbWidth = opts.width, thumbHeight = opts.height, thumbSource = opts.source; //Build list structure list = ''; for (var n = 0; n < obj.group.length; n++) { list += '<li><a style="width:' + thumbWidth + 'px;height:' + thumbHeight + 'px;" href="javascript:jQuery.fancybox.jumpto(' + n + ');"></a></li>'; } this.wrap = $('<div id="fancybox-thumbs"></div>').addClass(opts.position).appendTo('body'); this.list = $('<ul>' + list + '</ul>').appendTo(this.wrap); //Load each thumbnail $.each(obj.group, function (i) { var href = thumbSource( obj.group[ i ] ); if (!href) { return; } $("<img />").load(function () { var width = this.width, height = this.height, widthRatio, heightRatio, parent; if (!that.list || !width || !height) { return; } //Calculate thumbnail width/height and center it widthRatio = width / thumbWidth; heightRatio = height / thumbHeight; parent = that.list.children().eq(i).find('a'); if (widthRatio >= 1 && heightRatio >= 1) { if (widthRatio > heightRatio) { width = Math.floor(width / heightRatio); height = thumbHeight; } else { width = thumbWidth; height = Math.floor(height / widthRatio); } } $(this).css({ width : width, height : height, top : Math.floor(thumbHeight / 2 - height / 2), left : Math.floor(thumbWidth / 2 - width / 2) }); parent.width(thumbWidth).height(thumbHeight); $(this).hide().appendTo(parent).fadeIn(300); }).attr('src', href); }); //Set initial width this.width = this.list.children().eq(0).outerWidth(true); this.list.width(this.width * (obj.group.length + 1)).css('left', Math.floor($(window).width() * 0.5 - (obj.index * this.width + this.width * 0.5))); }, beforeLoad: function (opts, obj) { //Remove self if gallery do not have at least two items if (obj.group.length < 2) { obj.helpers.thumbs = false; return; } //Increase bottom margin to give space for thumbs obj.margin[ opts.position === 'top' ? 0 : 2 ] += ((opts.height) + 15); }, afterShow: function (opts, obj) { //Check if exists and create or update list if (this.list) { this.onUpdate(opts, obj); } else { this.init(opts, obj); } //Set active element this.list.children().removeClass('active').eq(obj.index).addClass('active'); }, //Center list onUpdate: function (opts, obj) { if (this.list) { this.list.stop(true).animate({ 'left': Math.floor($(window).width() * 0.5 - (obj.index * this.width + this.width * 0.5)) }, 150); } }, beforeClose: function () { if (this.wrap) { this.wrap.remove(); } this.wrap = null; this.list = null; this.width = 0; } } }(jQuery));
JavaScript
/*! * Media helper for fancyBox * version: 1.0.6 (Fri, 14 Jun 2013) * @requires fancyBox v2.0 or later * * Usage: * $(".fancybox").fancybox({ * helpers : { * media: true * } * }); * * Set custom URL parameters: * $(".fancybox").fancybox({ * helpers : { * media: { * youtube : { * params : { * autoplay : 0 * } * } * } * } * }); * * Or: * $(".fancybox").fancybox({, * helpers : { * media: true * }, * youtube : { * autoplay: 0 * } * }); * * Supports: * * Youtube * http://www.youtube.com/watch?v=opj24KnzrWo * http://www.youtube.com/embed/opj24KnzrWo * http://youtu.be/opj24KnzrWo * http://www.youtube-nocookie.com/embed/opj24KnzrWo * Vimeo * http://vimeo.com/40648169 * http://vimeo.com/channels/staffpicks/38843628 * http://vimeo.com/groups/surrealism/videos/36516384 * http://player.vimeo.com/video/45074303 * Metacafe * http://www.metacafe.com/watch/7635964/dr_seuss_the_lorax_movie_trailer/ * http://www.metacafe.com/watch/7635964/ * Dailymotion * http://www.dailymotion.com/video/xoytqh_dr-seuss-the-lorax-premiere_people * Twitvid * http://twitvid.com/QY7MD * Twitpic * http://twitpic.com/7p93st * Instagram * http://instagr.am/p/IejkuUGxQn/ * http://instagram.com/p/IejkuUGxQn/ * Google maps * http://maps.google.com/maps?q=Eiffel+Tower,+Avenue+Gustave+Eiffel,+Paris,+France&t=h&z=17 * http://maps.google.com/?ll=48.857995,2.294297&spn=0.007666,0.021136&t=m&z=16 * http://maps.google.com/?ll=48.859463,2.292626&spn=0.000965,0.002642&t=m&z=19&layer=c&cbll=48.859524,2.292532&panoid=YJ0lq28OOy3VT2IqIuVY0g&cbp=12,151.58,,0,-15.56 */ (function ($) { "use strict"; //Shortcut for fancyBox object var F = $.fancybox, format = function( url, rez, params ) { params = params || ''; if ( $.type( params ) === "object" ) { params = $.param(params, true); } $.each(rez, function(key, value) { url = url.replace( '$' + key, value || '' ); }); if (params.length) { url += ( url.indexOf('?') > 0 ? '&' : '?' ) + params; } return url; }; //Add helper object F.helpers.media = { defaults : { youtube : { matcher : /(youtube\.com|youtu\.be|youtube-nocookie\.com)\/(watch\?v=|v\/|u\/|embed\/?)?(videoseries\?list=(.*)|[\w-]{11}|\?listType=(.*)&list=(.*)).*/i, params : { autoplay : 1, autohide : 1, fs : 1, rel : 0, hd : 1, wmode : 'opaque', enablejsapi : 1 }, type : 'iframe', url : '//www.youtube.com/embed/$3' }, vimeo : { matcher : /(?:vimeo(?:pro)?.com)\/(?:[^\d]+)?(\d+)(?:.*)/, params : { autoplay : 1, hd : 1, show_title : 1, show_byline : 1, show_portrait : 0, fullscreen : 1 }, type : 'iframe', url : '//player.vimeo.com/video/$1' }, metacafe : { matcher : /metacafe.com\/(?:watch|fplayer)\/([\w\-]{1,10})/, params : { autoPlay : 'yes' }, type : 'swf', url : function( rez, params, obj ) { obj.swf.flashVars = 'playerVars=' + $.param( params, true ); return '//www.metacafe.com/fplayer/' + rez[1] + '/.swf'; } }, dailymotion : { matcher : /dailymotion.com\/video\/(.*)\/?(.*)/, params : { additionalInfos : 0, autoStart : 1 }, type : 'swf', url : '//www.dailymotion.com/swf/video/$1' }, twitvid : { matcher : /twitvid\.com\/([a-zA-Z0-9_\-\?\=]+)/i, params : { autoplay : 0 }, type : 'iframe', url : '//www.twitvid.com/embed.php?guid=$1' }, twitpic : { matcher : /twitpic\.com\/(?!(?:place|photos|events)\/)([a-zA-Z0-9\?\=\-]+)/i, type : 'image', url : '//twitpic.com/show/full/$1/' }, instagram : { matcher : /(instagr\.am|instagram\.com)\/p\/([a-zA-Z0-9_\-]+)\/?/i, type : 'image', url : '//$1/p/$2/media/?size=l' }, google_maps : { matcher : /maps\.google\.([a-z]{2,3}(\.[a-z]{2})?)\/(\?ll=|maps\?)(.*)/i, type : 'iframe', url : function( rez ) { return '//maps.google.' + rez[1] + '/' + rez[3] + '' + rez[4] + '&output=' + (rez[4].indexOf('layer=c') > 0 ? 'svembed' : 'embed'); } } }, beforeLoad : function(opts, obj) { var url = obj.href || '', type = false, what, item, rez, params; for (what in opts) { if (opts.hasOwnProperty(what)) { item = opts[ what ]; rez = url.match( item.matcher ); if (rez) { type = item.type; params = $.extend(true, {}, item.params, obj[ what ] || ($.isPlainObject(opts[ what ]) ? opts[ what ].params : null)); url = $.type( item.url ) === "function" ? item.url.call( this, rez, params, obj ) : format( item.url, rez, params ); break; } } } if (type) { obj.href = url; obj.type = type; obj.autoHeight = false; } } }; }(jQuery));
JavaScript
/*! * Buttons helper for fancyBox * version: 1.0.5 (Mon, 15 Oct 2012) * @requires fancyBox v2.0 or later * * Usage: * $(".fancybox").fancybox({ * helpers : { * buttons: { * position : 'top' * } * } * }); * */ (function ($) { //Shortcut for fancyBox object var F = $.fancybox; //Add helper object F.helpers.buttons = { defaults : { skipSingle : false, // disables if gallery contains single image position : 'top', // 'top' or 'bottom' tpl : '<div id="fancybox-buttons"><ul><li><a class="btnPrev" title="Previous" href="javascript:;"></a></li><li><a class="btnPlay" title="Start slideshow" href="javascript:;"></a></li><li><a class="btnNext" title="Next" href="javascript:;"></a></li><li><a class="btnToggle" title="Toggle size" href="javascript:;"></a></li><li><a class="btnClose" title="Close" href="javascript:;"></a></li></ul></div>' }, list : null, buttons: null, beforeLoad: function (opts, obj) { //Remove self if gallery do not have at least two items if (opts.skipSingle && obj.group.length < 2) { obj.helpers.buttons = false; obj.closeBtn = true; return; } //Increase top margin to give space for buttons obj.margin[ opts.position === 'bottom' ? 2 : 0 ] += 30; }, onPlayStart: function () { if (this.buttons) { this.buttons.play.attr('title', 'Pause slideshow').addClass('btnPlayOn'); } }, onPlayEnd: function () { if (this.buttons) { this.buttons.play.attr('title', 'Start slideshow').removeClass('btnPlayOn'); } }, afterShow: function (opts, obj) { var buttons = this.buttons; if (!buttons) { this.list = $(opts.tpl).addClass(opts.position).appendTo('body'); buttons = { prev : this.list.find('.btnPrev').click( F.prev ), next : this.list.find('.btnNext').click( F.next ), play : this.list.find('.btnPlay').click( F.play ), toggle : this.list.find('.btnToggle').click( F.toggle ), close : this.list.find('.btnClose').click( F.close ) } } //Prev if (obj.index > 0 || obj.loop) { buttons.prev.removeClass('btnDisabled'); } else { buttons.prev.addClass('btnDisabled'); } //Next / Play if (obj.loop || obj.index < obj.group.length - 1) { buttons.next.removeClass('btnDisabled'); buttons.play.removeClass('btnDisabled'); } else { buttons.next.addClass('btnDisabled'); buttons.play.addClass('btnDisabled'); } this.buttons = buttons; this.onUpdate(opts, obj); }, onUpdate: function (opts, obj) { var toggle; if (!this.buttons) { return; } toggle = this.buttons.toggle.removeClass('btnDisabled btnToggleOn'); //Size toggle button if (obj.canShrink) { toggle.addClass('btnToggleOn'); } else if (!obj.canExpand) { toggle.addClass('btnDisabled'); } }, beforeClose: function () { if (this.list) { this.list.remove(); } this.list = null; this.buttons = null; } }; }(jQuery));
JavaScript
/*! * FullCalendar v2.0.0-beta2 Google Calendar Plugin * Docs & License: http://arshaw.com/fullcalendar/ * (c) 2013 Adam Shaw */ (function(factory) { if (typeof define === 'function' && define.amd) { define([ 'jquery' ], factory); } else { factory(jQuery); } })(function($) { var fc = $.fullCalendar; var applyAll = fc.applyAll; fc.sourceNormalizers.push(function(sourceOptions) { if (sourceOptions.dataType == 'gcal' || sourceOptions.dataType === undefined && (sourceOptions.url || '').match(/^(http|https):\/\/www.google.com\/calendar\/feeds\//)) { sourceOptions.dataType = 'gcal'; if (sourceOptions.editable === undefined) { sourceOptions.editable = false; } } }); fc.sourceFetchers.push(function(sourceOptions, start, end, timezone) { if (sourceOptions.dataType == 'gcal') { return transformOptions(sourceOptions, start, end, timezone); } }); function transformOptions(sourceOptions, start, end, timezone) { var success = sourceOptions.success; var data = $.extend({}, sourceOptions.data || {}, { singleevents: true, 'max-results': 9999 }); return $.extend({}, sourceOptions, { url: sourceOptions.url.replace(/\/basic$/, '/full') + '?alt=json-in-script&callback=?', dataType: 'jsonp', data: data, timezoneParam: 'ctz', startParam: 'start-min', endParam: 'start-max', success: function(data) { var events = []; if (data.feed.entry) { $.each(data.feed.entry, function(i, entry) { var url; $.each(entry.link, function(i, link) { if (link.type == 'text/html') { url = link.href; if (timezone && timezone != 'local') { url += (url.indexOf('?') == -1 ? '?' : '&') + 'ctz=' + encodeURIComponent(timezone); } } }); events.push({ id: entry.gCal$uid.value, title: entry.title.$t, start: entry.gd$when[0].startTime, end: entry.gd$when[0].endTime, url: url, location: entry.gd$where[0].valueString, description: entry.content.$t }); }); } var args = [events].concat(Array.prototype.slice.call(arguments, 1)); var res = applyAll(success, this, args); if ($.isArray(res)) { return res; } return events; } }); } // legacy fc.gcalFeed = function(url, sourceOptions) { return $.extend({}, sourceOptions, { url: url, dataType: 'gcal' }); }; });
JavaScript
/*! * FullCalendar v2.0.0-beta2 * Docs & License: http://arshaw.com/fullcalendar/ * (c) 2013 Adam Shaw */ (function(factory) { if (typeof define === 'function' && define.amd) { define([ 'jquery', 'moment' ], factory); } else { factory(jQuery, moment); } })(function($, moment) { ;; var defaults = { lang: 'en', defaultTimedEventDuration: '02:00:00', defaultAllDayEventDuration: { days: 1 }, forceEventDuration: false, nextDayThreshold: '09:00:00', // 9am // display defaultView: 'month', aspectRatio: 1.35, header: { left: 'title', center: '', right: 'today prev,next' }, weekends: true, weekNumbers: false, weekNumberTitle: 'W', weekNumberCalculation: 'local', //editable: false, // event ajax lazyFetching: true, startParam: 'start', endParam: 'end', timezoneParam: 'timezone', //allDayDefault: undefined, // time formats titleFormat: { month: 'MMMM YYYY', // like "September 1986". each language will override this week: 'll', // like "Sep 4 1986" day: 'LL' // like "September 4 1986" }, columnFormat: { month: 'ddd', // like "Sat" week: generateWeekColumnFormat, day: 'dddd' // like "Saturday" }, timeFormat: { // for event elements 'default': generateShortTimeFormat }, // locale isRTL: false, buttonText: { prev: "prev", next: "next", prevYear: "prev year", nextYear: "next year", today: 'today', month: 'month', week: 'week', day: 'day' }, buttonIcons: { prev: 'left-single-arrow', next: 'right-single-arrow', prevYear: 'left-double-arrow', nextYear: 'right-double-arrow' }, // jquery-ui theming theme: false, themeButtonIcons: { prev: 'circle-triangle-w', next: 'circle-triangle-e', prevYear: 'seek-prev', nextYear: 'seek-next' }, //selectable: false, unselectAuto: true, dropAccept: '*', handleWindowResize: true }; function generateShortTimeFormat(options, langData) { return langData.longDateFormat('LT') .replace(':mm', '(:mm)') .replace(/(\Wmm)$/, '($1)') // like above, but for foreign langs .replace(/\s*a$/i, 't'); // convert to AM/PM/am/pm to lowercase one-letter. remove any spaces beforehand } function generateWeekColumnFormat(options, langData) { var format = langData.longDateFormat('L'); // for the format like "MM/DD/YYYY" format = format.replace(/^Y+[^\w\s]*|[^\w\s]*Y+$/g, ''); // strip the year off the edge, as well as other misc non-whitespace chars if (options.isRTL) { format += ' ddd'; // for RTL, add day-of-week to end } else { format = 'ddd ' + format; // for LTR, add day-of-week to beginning } return format; } var langOptionHash = { en: { columnFormat: { week: 'ddd M/D' // override for english. different from the generated default, which is MM/DD } } }; // right-to-left defaults var rtlDefaults = { header: { left: 'next,prev today', center: '', right: 'title' }, buttonIcons: { prev: 'right-single-arrow', next: 'left-single-arrow', prevYear: 'right-double-arrow', nextYear: 'left-double-arrow' }, themeButtonIcons: { prev: 'circle-triangle-e', next: 'circle-triangle-w', nextYear: 'seek-prev', prevYear: 'seek-next' } }; ;; var fc = $.fullCalendar = { version: "2.0.0-beta2" }; var fcViews = fc.views = {}; $.fn.fullCalendar = function(options) { var args = Array.prototype.slice.call(arguments, 1); // for a possible method call var res = this; // what this function will return (this jQuery object by default) this.each(function(i, _element) { // loop each DOM element involved var element = $(_element); var calendar = element.data('fullCalendar'); // get the existing calendar object (if any) var singleRes; // the returned value of this single method call // a method call if (typeof options === 'string') { if (calendar && $.isFunction(calendar[options])) { singleRes = calendar[options].apply(calendar, args); if (!i) { res = singleRes; // record the first method call result } if (options === 'destroy') { // for the destroy method, must remove Calendar object data element.removeData('fullCalendar'); } } } // a new calendar initialization else if (!calendar) { // don't initialize twice calendar = new Calendar(element, options); element.data('fullCalendar', calendar); calendar.render(); } }); return res; }; // function for adding/overriding defaults function setDefaults(d) { mergeOptions(defaults, d); } // Recursively combines option hash-objects. // Better than `$.extend(true, ...)` because arrays are not traversed/copied. // // called like: // mergeOptions(target, obj1, obj2, ...) // function mergeOptions(target) { function mergeIntoTarget(name, value) { if ($.isPlainObject(value) && $.isPlainObject(target[name]) && !isForcedAtomicOption(name)) { // merge into a new object to avoid destruction target[name] = mergeOptions({}, target[name], value); // combine. `value` object takes precedence } else if (value !== undefined) { // only use values that are set and not undefined target[name] = value; } } for (var i=1; i<arguments.length; i++) { $.each(arguments[i], mergeIntoTarget); } return target; } // overcome sucky view-option-hash and option-merging behavior messing with options it shouldn't function isForcedAtomicOption(name) { // Any option that ends in "Time" or "Duration" is probably a Duration, // and these will commonly be specified as plain objects, which we don't want to mess up. return /(Time|Duration)$/.test(name); } // FIX: find a different solution for view-option-hashes and have a whitelist // for options that can be recursively merged. ;; //var langOptionHash = {}; // initialized in defaults.js fc.langs = langOptionHash; // expose // Initialize jQuery UI Datepicker translations while using some of the translations // for our own purposes. Will set this as the default language for datepicker. // Called from a translation file. fc.datepickerLang = function(langCode, datepickerLangCode, options) { var langOptions = langOptionHash[langCode]; // initialize FullCalendar's lang hash for this language if (!langOptions) { langOptions = langOptionHash[langCode] = {}; } // merge certain Datepicker options into FullCalendar's options mergeOptions(langOptions, { isRTL: options.isRTL, weekNumberTitle: options.weekHeader, titleFormat: { month: options.showMonthAfterYear ? 'YYYY[' + options.yearSuffix + '] MMMM' : 'MMMM YYYY[' + options.yearSuffix + ']' }, buttonText: { // the translations sometimes wrongly contain HTML entities prev: stripHTMLEntities(options.prevText), next: stripHTMLEntities(options.nextText), today: stripHTMLEntities(options.currentText) } }); // is jQuery UI Datepicker is on the page? if ($.datepicker) { // Register the language data. // FullCalendar and MomentJS use language codes like "pt-br" but Datepicker // does it like "pt-BR" or if it doesn't have the language, maybe just "pt". // Make an alias so the language can be referenced either way. $.datepicker.regional[datepickerLangCode] = $.datepicker.regional[langCode] = // alias options; // Alias 'en' to the default language data. Do this every time. $.datepicker.regional.en = $.datepicker.regional['']; // Set as Datepicker's global defaults. $.datepicker.setDefaults(options); } }; // Sets FullCalendar-specific translations. Also sets the language as the global default. // Called from a translation file. fc.lang = function(langCode, options) { var langOptions; if (options) { langOptions = langOptionHash[langCode]; // initialize the hash for this language if (!langOptions) { langOptions = langOptionHash[langCode] = {}; } mergeOptions(langOptions, options || {}); } // set it as the default language for FullCalendar defaults.lang = langCode; }; ;; function Calendar(element, instanceOptions) { var t = this; // Build options object // ----------------------------------------------------------------------------------- // Precedence (lowest to highest): defaults, rtlDefaults, langOptions, instanceOptions instanceOptions = instanceOptions || {}; var options = mergeOptions({}, defaults, instanceOptions); var langOptions; // determine language options if (options.lang in langOptionHash) { langOptions = langOptionHash[options.lang]; } else { langOptions = langOptionHash[defaults.lang]; } if (langOptions) { // if language options exist, rebuild... options = mergeOptions({}, defaults, langOptions, instanceOptions); } if (options.isRTL) { // is isRTL, rebuild... options = mergeOptions({}, defaults, rtlDefaults, langOptions || {}, instanceOptions); } // Exports // ----------------------------------------------------------------------------------- t.options = options; t.render = render; t.destroy = destroy; t.refetchEvents = refetchEvents; t.reportEvents = reportEvents; t.reportEventChange = reportEventChange; t.rerenderEvents = rerenderEvents; t.changeView = changeView; t.select = select; t.unselect = unselect; t.prev = prev; t.next = next; t.prevYear = prevYear; t.nextYear = nextYear; t.today = today; t.gotoDate = gotoDate; t.incrementDate = incrementDate; t.getDate = getDate; t.getCalendar = getCalendar; t.getView = getView; t.option = option; t.trigger = trigger; // Language-data Internals // ----------------------------------------------------------------------------------- // Apply overrides to the current language's data var langData = createObject( // make a cheap clone moment.langData(options.lang) ); if (options.monthNames) { langData._months = options.monthNames; } if (options.monthNamesShort) { langData._monthsShort = options.monthNamesShort; } if (options.dayNames) { langData._weekdays = options.dayNames; } if (options.dayNamesShort) { langData._weekdaysShort = options.dayNamesShort; } if (options.firstDay) { var _week = createObject(langData._week); // _week: { dow: # } _week.dow = options.firstDay; langData._week = _week; } // Calendar-specific Date Utilities // ----------------------------------------------------------------------------------- t.defaultAllDayEventDuration = moment.duration(options.defaultAllDayEventDuration); t.defaultTimedEventDuration = moment.duration(options.defaultTimedEventDuration); // Builds a moment using the settings of the current calendar: timezone and language. // Accepts anything the vanilla moment() constructor accepts. t.moment = function() { var mom; if (options.timezone === 'local') { mom = fc.moment.apply(null, arguments); } else if (options.timezone === 'UTC') { mom = fc.moment.utc.apply(null, arguments); } else { mom = fc.moment.parseZone.apply(null, arguments); } mom._lang = langData; return mom; }; // Returns a boolean about whether or not the calendar knows how to calculate // the timezone offset of arbitrary dates in the current timezone. t.getIsAmbigTimezone = function() { return options.timezone !== 'local' && options.timezone !== 'UTC'; }; // Returns a copy of the given date in the current timezone of it is ambiguously zoned. // This will also give the date an unambiguous time. t.rezoneDate = function(date) { return t.moment(date.toArray()); }; // Returns a moment for the current date, as defined by the client's computer, // or overridden by the `now` option. t.getNow = function() { var now = options.now; if (typeof now === 'function') { now = now(); } return t.moment(now); }; // Calculates the week number for a moment according to the calendar's // `weekNumberCalculation` setting. t.calculateWeekNumber = function(mom) { var calc = options.weekNumberCalculation; if (typeof calc === 'function') { return calc(mom); } else if (calc === 'local') { return mom.week(); } else if (calc.toUpperCase() === 'ISO') { return mom.isoWeek(); } }; // Get an event's normalized end date. If not present, calculate it from the defaults. t.getEventEnd = function(event) { if (event.end) { return event.end.clone(); } else { return t.getDefaultEventEnd(event.allDay, event.start); } }; // Given an event's allDay status and start date, return swhat its fallback end date should be. t.getDefaultEventEnd = function(allDay, start) { // TODO: rename to computeDefaultEventEnd var end = start.clone(); if (allDay) { end.stripTime().add(t.defaultAllDayEventDuration); } else { end.add(t.defaultTimedEventDuration); } if (t.getIsAmbigTimezone()) { end.stripZone(); // we don't know what the tzo should be } return end; }; // Date-formatting Utilities // ----------------------------------------------------------------------------------- // Like the vanilla formatRange, but with calendar-specific settings applied. t.formatRange = function(m1, m2, formatStr) { // a function that returns a formatStr // TODO: in future, precompute this if (typeof formatStr === 'function') { formatStr = formatStr.call(t, options, langData); } return formatRange(m1, m2, formatStr, null, options.isRTL); }; // Like the vanilla formatDate, but with calendar-specific settings applied. t.formatDate = function(mom, formatStr) { // a function that returns a formatStr // TODO: in future, precompute this if (typeof formatStr === 'function') { formatStr = formatStr.call(t, options, langData); } return formatDate(mom, formatStr); }; // Imports // ----------------------------------------------------------------------------------- EventManager.call(t, options); var isFetchNeeded = t.isFetchNeeded; var fetchEvents = t.fetchEvents; // Locals // ----------------------------------------------------------------------------------- var _element = element[0]; var header; var headerElement; var content; var tm; // for making theme classes var currentView; var elementOuterWidth; var suggestedViewHeight; var resizeUID = 0; var ignoreWindowResize = 0; var date; var events = []; var _dragElement; // Main Rendering // ----------------------------------------------------------------------------------- if (options.defaultDate != null) { date = t.moment(options.defaultDate); } else { date = t.getNow(); } function render(inc) { if (!content) { initialRender(); } else if (elementVisible()) { // mainly for the public API calcSize(); _renderView(inc); } } function initialRender() { tm = options.theme ? 'ui' : 'fc'; element.addClass('fc'); if (options.isRTL) { element.addClass('fc-rtl'); } else { element.addClass('fc-ltr'); } if (options.theme) { element.addClass('ui-widget'); } content = $("<div class='fc-content' />") .prependTo(element); header = new Header(t, options); headerElement = header.render(); if (headerElement) { element.prepend(headerElement); } changeView(options.defaultView); if (options.handleWindowResize) { $(window).resize(windowResize); } // needed for IE in a 0x0 iframe, b/c when it is resized, never triggers a windowResize if (!bodyVisible()) { lateRender(); } } // called when we know the calendar couldn't be rendered when it was initialized, // but we think it's ready now function lateRender() { setTimeout(function() { // IE7 needs this so dimensions are calculated correctly if (!currentView.start && bodyVisible()) { // !currentView.start makes sure this never happens more than once renderView(); } },0); } function destroy() { if (currentView) { trigger('viewDestroy', currentView, currentView, currentView.element); currentView.triggerEventDestroy(); } $(window).unbind('resize', windowResize); header.destroy(); content.remove(); element.removeClass('fc fc-rtl ui-widget'); } function elementVisible() { return element.is(':visible'); } function bodyVisible() { return $('body').is(':visible'); } // View Rendering // ----------------------------------------------------------------------------------- function changeView(newViewName) { if (!currentView || newViewName != currentView.name) { _changeView(newViewName); } } function _changeView(newViewName) { ignoreWindowResize++; if (currentView) { trigger('viewDestroy', currentView, currentView, currentView.element); unselect(); currentView.triggerEventDestroy(); // trigger 'eventDestroy' for each event freezeContentHeight(); currentView.element.remove(); header.deactivateButton(currentView.name); } header.activateButton(newViewName); currentView = new fcViews[newViewName]( $("<div class='fc-view fc-view-" + newViewName + "' />") .appendTo(content), t // the calendar object ); renderView(); unfreezeContentHeight(); ignoreWindowResize--; } function renderView(inc) { if ( !currentView.start || // never rendered before inc || // explicit date window change !date.isWithin(currentView.intervalStart, currentView.intervalEnd) // implicit date window change ) { if (elementVisible()) { _renderView(inc); } } } function _renderView(inc) { // assumes elementVisible ignoreWindowResize++; if (currentView.start) { // already been rendered? trigger('viewDestroy', currentView, currentView, currentView.element); unselect(); clearEvents(); } freezeContentHeight(); if (inc) { date = currentView.incrementDate(date, inc); } currentView.render(date.clone()); // the view's render method ONLY renders the skeleton, nothing else setSize(); unfreezeContentHeight(); (currentView.afterRender || noop)(); updateTitle(); updateTodayButton(); trigger('viewRender', currentView, currentView, currentView.element); ignoreWindowResize--; getAndRenderEvents(); } // Resizing // ----------------------------------------------------------------------------------- function updateSize() { if (elementVisible()) { unselect(); clearEvents(); calcSize(); setSize(); renderEvents(); } } function calcSize() { // assumes elementVisible if (options.contentHeight) { suggestedViewHeight = options.contentHeight; } else if (options.height) { suggestedViewHeight = options.height - (headerElement ? headerElement.height() : 0) - vsides(content); } else { suggestedViewHeight = Math.round(content.width() / Math.max(options.aspectRatio, .5)); } } function setSize() { // assumes elementVisible if (suggestedViewHeight === undefined) { calcSize(); // for first time // NOTE: we don't want to recalculate on every renderView because // it could result in oscillating heights due to scrollbars. } ignoreWindowResize++; currentView.setHeight(suggestedViewHeight); currentView.setWidth(content.width()); ignoreWindowResize--; elementOuterWidth = element.outerWidth(); } function windowResize() { if (!ignoreWindowResize) { if (currentView.start) { // view has already been rendered var uid = ++resizeUID; setTimeout(function() { // add a delay if (uid == resizeUID && !ignoreWindowResize && elementVisible()) { if (elementOuterWidth != (elementOuterWidth = element.outerWidth())) { ignoreWindowResize++; // in case the windowResize callback changes the height updateSize(); currentView.trigger('windowResize', _element); ignoreWindowResize--; } } }, 200); }else{ // calendar must have been initialized in a 0x0 iframe that has just been resized lateRender(); } } } /* Event Fetching/Rendering -----------------------------------------------------------------------------*/ // TODO: going forward, most of this stuff should be directly handled by the view function refetchEvents() { // can be called as an API method clearEvents(); fetchAndRenderEvents(); } function rerenderEvents(modifiedEventID) { // can be called as an API method clearEvents(); renderEvents(modifiedEventID); } function renderEvents(modifiedEventID) { // TODO: remove modifiedEventID hack if (elementVisible()) { currentView.renderEvents(events, modifiedEventID); // actually render the DOM elements currentView.trigger('eventAfterAllRender'); } } function clearEvents() { currentView.triggerEventDestroy(); // trigger 'eventDestroy' for each event currentView.clearEvents(); // actually remove the DOM elements currentView.clearEventData(); // for View.js, TODO: unify with clearEvents } function getAndRenderEvents() { if (!options.lazyFetching || isFetchNeeded(currentView.start, currentView.end)) { fetchAndRenderEvents(); } else { renderEvents(); } } function fetchAndRenderEvents() { fetchEvents(currentView.start, currentView.end); // ... will call reportEvents // ... which will call renderEvents } // called when event data arrives function reportEvents(_events) { events = _events; renderEvents(); } // called when a single event's data has been changed function reportEventChange(eventID) { rerenderEvents(eventID); } /* Header Updating -----------------------------------------------------------------------------*/ function updateTitle() { header.updateTitle(currentView.title); } function updateTodayButton() { var now = t.getNow(); if (now.isWithin(currentView.intervalStart, currentView.intervalEnd)) { header.disableButton('today'); } else { header.enableButton('today'); } } /* Selection -----------------------------------------------------------------------------*/ function select(start, end) { currentView.select(start, end); } function unselect() { // safe to be called before renderView if (currentView) { currentView.unselect(); } } /* Date -----------------------------------------------------------------------------*/ function prev() { renderView(-1); } function next() { renderView(1); } function prevYear() { date.add('years', -1); renderView(); } function nextYear() { date.add('years', 1); renderView(); } function today() { date = t.getNow(); renderView(); } function gotoDate(dateInput) { date = t.moment(dateInput); renderView(); } function incrementDate() { date.add.apply(date, arguments); renderView(); } function getDate() { return date.clone(); } /* Height "Freezing" -----------------------------------------------------------------------------*/ function freezeContentHeight() { content.css({ width: '100%', height: content.height(), overflow: 'hidden' }); } function unfreezeContentHeight() { content.css({ width: '', height: '', overflow: '' }); } /* Misc -----------------------------------------------------------------------------*/ function getCalendar() { return t; } function getView() { return currentView; } function option(name, value) { if (value === undefined) { return options[name]; } if (name == 'height' || name == 'contentHeight' || name == 'aspectRatio') { options[name] = value; updateSize(); } } function trigger(name, thisObj) { if (options[name]) { return options[name].apply( thisObj || _element, Array.prototype.slice.call(arguments, 2) ); } } /* External Dragging ------------------------------------------------------------------------*/ if (options.droppable) { // TODO: unbind on destroy $(document) .bind('dragstart', function(ev, ui) { var _e = ev.target; var e = $(_e); if (!e.parents('.fc').length) { // not already inside a calendar var accept = options.dropAccept; if ($.isFunction(accept) ? accept.call(_e, e) : e.is(accept)) { _dragElement = _e; currentView.dragStart(_dragElement, ev, ui); } } }) .bind('dragstop', function(ev, ui) { if (_dragElement) { currentView.dragStop(_dragElement, ev, ui); _dragElement = null; } }); } } ;; function Header(calendar, options) { var t = this; // exports t.render = render; t.destroy = destroy; t.updateTitle = updateTitle; t.activateButton = activateButton; t.deactivateButton = deactivateButton; t.disableButton = disableButton; t.enableButton = enableButton; // locals var element = $([]); var tm; function render() { tm = options.theme ? 'ui' : 'fc'; var sections = options.header; if (sections) { element = $("<table class='fc-header' style='width:100%'/>") .append( $("<tr/>") .append(renderSection('left')) .append(renderSection('center')) .append(renderSection('right')) ); return element; } } function destroy() { element.remove(); } function renderSection(position) { var e = $("<td class='fc-header-" + position + "'/>"); var buttonStr = options.header[position]; if (buttonStr) { $.each(buttonStr.split(' '), function(i) { if (i > 0) { e.append("<span class='fc-header-space'/>"); } var prevButton; $.each(this.split(','), function(j, buttonName) { if (buttonName == 'title') { e.append("<span class='fc-header-title'><h2>&nbsp;</h2></span>"); if (prevButton) { prevButton.addClass(tm + '-corner-right'); } prevButton = null; }else{ var buttonClick; if (calendar[buttonName]) { buttonClick = calendar[buttonName]; // calendar method } else if (fcViews[buttonName]) { buttonClick = function() { button.removeClass(tm + '-state-hover'); // forget why calendar.changeView(buttonName); }; } if (buttonClick) { // smartProperty allows different text per view button (ex: "Agenda Week" vs "Basic Week") var themeIcon = smartProperty(options.themeButtonIcons, buttonName); var normalIcon = smartProperty(options.buttonIcons, buttonName); var text = smartProperty(options.buttonText, buttonName); var html; if (themeIcon && options.theme) { html = "<span class='ui-icon ui-icon-" + themeIcon + "'></span>"; } else if (normalIcon && !options.theme) { html = "<span class='fc-icon fc-icon-" + normalIcon + "'></span>"; } else { html = htmlEscape(text || buttonName); } var button = $( "<span class='fc-button fc-button-" + buttonName + " " + tm + "-state-default'>" + html + "</span>" ) .click(function() { if (!button.hasClass(tm + '-state-disabled')) { buttonClick(); } }) .mousedown(function() { button .not('.' + tm + '-state-active') .not('.' + tm + '-state-disabled') .addClass(tm + '-state-down'); }) .mouseup(function() { button.removeClass(tm + '-state-down'); }) .hover( function() { button .not('.' + tm + '-state-active') .not('.' + tm + '-state-disabled') .addClass(tm + '-state-hover'); }, function() { button .removeClass(tm + '-state-hover') .removeClass(tm + '-state-down'); } ) .appendTo(e); disableTextSelection(button); if (!prevButton) { button.addClass(tm + '-corner-left'); } prevButton = button; } } }); if (prevButton) { prevButton.addClass(tm + '-corner-right'); } }); } return e; } function updateTitle(html) { element.find('h2') .html(html); } function activateButton(buttonName) { element.find('span.fc-button-' + buttonName) .addClass(tm + '-state-active'); } function deactivateButton(buttonName) { element.find('span.fc-button-' + buttonName) .removeClass(tm + '-state-active'); } function disableButton(buttonName) { element.find('span.fc-button-' + buttonName) .addClass(tm + '-state-disabled'); } function enableButton(buttonName) { element.find('span.fc-button-' + buttonName) .removeClass(tm + '-state-disabled'); } } ;; fc.sourceNormalizers = []; fc.sourceFetchers = []; var ajaxDefaults = { dataType: 'json', cache: false }; var eventGUID = 1; function EventManager(options) { // assumed to be a calendar var t = this; // exports t.isFetchNeeded = isFetchNeeded; t.fetchEvents = fetchEvents; t.addEventSource = addEventSource; t.removeEventSource = removeEventSource; t.updateEvent = updateEvent; t.renderEvent = renderEvent; t.removeEvents = removeEvents; t.clientEvents = clientEvents; t.mutateEvent = mutateEvent; // imports var trigger = t.trigger; var getView = t.getView; var reportEvents = t.reportEvents; var getEventEnd = t.getEventEnd; // locals var stickySource = { events: [] }; var sources = [ stickySource ]; var rangeStart, rangeEnd; var currentFetchID = 0; var pendingSourceCnt = 0; var loadingLevel = 0; var cache = []; var _sources = options.eventSources || []; if (options.events) { _sources.push(options.events); } for (var i=0; i<_sources.length; i++) { _addEventSource(_sources[i]); } /* Fetching -----------------------------------------------------------------------------*/ function isFetchNeeded(start, end) { return !rangeStart || // nothing has been fetched yet? // or, a part of the new range is outside of the old range? (after normalizing) start.clone().stripZone() < rangeStart.clone().stripZone() || end.clone().stripZone() > rangeEnd.clone().stripZone(); } function fetchEvents(start, end) { rangeStart = start; rangeEnd = end; cache = []; var fetchID = ++currentFetchID; var len = sources.length; pendingSourceCnt = len; for (var i=0; i<len; i++) { fetchEventSource(sources[i], fetchID); } } function fetchEventSource(source, fetchID) { _fetchEventSource(source, function(events) { if (fetchID == currentFetchID) { if (events) { for (var i=0; i<events.length; i++) { var event = buildEvent(events[i], source); if (event) { cache.push(event); } } } pendingSourceCnt--; if (!pendingSourceCnt) { reportEvents(cache); } } }); } function _fetchEventSource(source, callback) { var i; var fetchers = fc.sourceFetchers; var res; for (i=0; i<fetchers.length; i++) { res = fetchers[i].call( t, // this, the Calendar object source, rangeStart.clone(), rangeEnd.clone(), options.timezone, callback ); if (res === true) { // the fetcher is in charge. made its own async request return; } else if (typeof res == 'object') { // the fetcher returned a new source. process it _fetchEventSource(res, callback); return; } } var events = source.events; if (events) { if ($.isFunction(events)) { pushLoading(); events.call( t, // this, the Calendar object rangeStart.clone(), rangeEnd.clone(), options.timezone, function(events) { callback(events); popLoading(); } ); } else if ($.isArray(events)) { callback(events); } else { callback(); } }else{ var url = source.url; if (url) { var success = source.success; var error = source.error; var complete = source.complete; // retrieve any outbound GET/POST $.ajax data from the options var customData; if ($.isFunction(source.data)) { // supplied as a function that returns a key/value object customData = source.data(); } else { // supplied as a straight key/value object customData = source.data; } // use a copy of the custom data so we can modify the parameters // and not affect the passed-in object. var data = $.extend({}, customData || {}); var startParam = firstDefined(source.startParam, options.startParam); var endParam = firstDefined(source.endParam, options.endParam); var timezoneParam = firstDefined(source.timezoneParam, options.timezoneParam); if (startParam) { data[startParam] = rangeStart.format(); } if (endParam) { data[endParam] = rangeEnd.format(); } if (options.timezone && options.timezone != 'local') { data[timezoneParam] = options.timezone; } pushLoading(); $.ajax($.extend({}, ajaxDefaults, source, { data: data, success: function(events) { events = events || []; var res = applyAll(success, this, arguments); if ($.isArray(res)) { events = res; } callback(events); }, error: function() { applyAll(error, this, arguments); callback(); }, complete: function() { applyAll(complete, this, arguments); popLoading(); } })); }else{ callback(); } } } /* Sources -----------------------------------------------------------------------------*/ function addEventSource(source) { source = _addEventSource(source); if (source) { pendingSourceCnt++; fetchEventSource(source, currentFetchID); // will eventually call reportEvents } } function _addEventSource(source) { if ($.isFunction(source) || $.isArray(source)) { source = { events: source }; } else if (typeof source == 'string') { source = { url: source }; } if (typeof source == 'object') { normalizeSource(source); sources.push(source); return source; } } function removeEventSource(source) { sources = $.grep(sources, function(src) { return !isSourcesEqual(src, source); }); // remove all client events from that source cache = $.grep(cache, function(e) { return !isSourcesEqual(e.source, source); }); reportEvents(cache); } /* Manipulation -----------------------------------------------------------------------------*/ function updateEvent(event) { mutateEvent(event); propagateMiscProperties(event); reportEvents(cache); // reports event modifications (so we can redraw) } var miscCopyableProps = [ 'title', 'url', 'allDay', 'className', 'editable', 'color', 'backgroundColor', 'borderColor', 'textColor' ]; function propagateMiscProperties(event) { var i; var cachedEvent; var j; var prop; for (i=0; i<cache.length; i++) { cachedEvent = cache[i]; if (cachedEvent._id == event._id && cachedEvent !== event) { for (j=0; j<miscCopyableProps.length; j++) { prop = miscCopyableProps[j]; if (event[prop] !== undefined) { cachedEvent[prop] = event[prop]; } } } } } function renderEvent(eventData, stick) { var event = buildEvent(eventData); if (event) { if (!event.source) { if (stick) { stickySource.events.push(event); event.source = stickySource; } cache.push(event); } reportEvents(cache); } } function removeEvents(filter) { var i; if (!filter) { // remove all cache = []; // clear all array sources for (i=0; i<sources.length; i++) { if ($.isArray(sources[i].events)) { sources[i].events = []; } } }else{ if (!$.isFunction(filter)) { // an event ID var id = filter + ''; filter = function(e) { return e._id == id; }; } cache = $.grep(cache, filter, true); // remove events from array sources for (i=0; i<sources.length; i++) { if ($.isArray(sources[i].events)) { sources[i].events = $.grep(sources[i].events, filter, true); } } } reportEvents(cache); } function clientEvents(filter) { if ($.isFunction(filter)) { return $.grep(cache, filter); } else if (filter) { // an event ID filter += ''; return $.grep(cache, function(e) { return e._id == filter; }); } return cache; // else, return all } /* Loading State -----------------------------------------------------------------------------*/ function pushLoading() { if (!(loadingLevel++)) { trigger('loading', null, true, getView()); } } function popLoading() { if (!(--loadingLevel)) { trigger('loading', null, false, getView()); } } /* Event Normalization -----------------------------------------------------------------------------*/ function buildEvent(data, source) { // source may be undefined! var out = {}; var start; var end; var allDay; var allDayDefault; if (options.eventDataTransform) { data = options.eventDataTransform(data); } if (source && source.eventDataTransform) { data = source.eventDataTransform(data); } start = t.moment(data.start || data.date); // "date" is an alias for "start" if (!start.isValid()) { return; } end = null; if (data.end) { end = t.moment(data.end); if (!end.isValid()) { return; } } allDay = data.allDay; if (allDay === undefined) { allDayDefault = firstDefined( source ? source.allDayDefault : undefined, options.allDayDefault ); if (allDayDefault !== undefined) { // use the default allDay = allDayDefault; } else { // all dates need to have ambig time for the event to be considered allDay allDay = !start.hasTime() && (!end || !end.hasTime()); } } // normalize the date based on allDay if (allDay) { // neither date should have a time if (start.hasTime()) { start.stripTime(); } if (end && end.hasTime()) { end.stripTime(); } } else { // force a time/zone up the dates if (!start.hasTime()) { start = t.rezoneDate(start); } if (end && !end.hasTime()) { end = t.rezoneDate(end); } } // Copy all properties over to the resulting object. // The special-case properties will be copied over afterwards. $.extend(out, data); if (source) { out.source = source; } out._id = data._id || (data.id === undefined ? '_fc' + eventGUID++ : data.id + ''); if (data.className) { if (typeof data.className == 'string') { out.className = data.className.split(/\s+/); } else { // assumed to be an array out.className = data.className; } } else { out.className = []; } out.allDay = allDay; out.start = start; out.end = end; if (options.forceEventDuration && !out.end) { out.end = getEventEnd(out); } backupEventDates(out); return out; } /* Event Modification Math -----------------------------------------------------------------------------------------*/ // Modify the date(s) of an event and make this change propagate to all other events with // the same ID (related repeating events). // // If `newStart`/`newEnd` are not specified, the "new" dates are assumed to be `event.start` and `event.end`. // The "old" dates to be compare against are always `event._start` and `event._end` (set by EventManager). // // Returns a function that can be called to undo all the operations. // function mutateEvent(event, newStart, newEnd) { var oldAllDay = event._allDay; var oldStart = event._start; var oldEnd = event._end; var clearEnd = false; var newAllDay; var dateDelta; var durationDelta; // if no new dates were passed in, compare against the event's existing dates if (!newStart && !newEnd) { newStart = event.start; newEnd = event.end; } // NOTE: throughout this function, the initial values of `newStart` and `newEnd` are // preserved. These values may be undefined. // detect new allDay if (event.allDay != oldAllDay) { // if value has changed, use it newAllDay = event.allDay; } else { // otherwise, see if any of the new dates are allDay newAllDay = !(newStart || newEnd).hasTime(); } // normalize the new dates based on allDay if (newAllDay) { if (newStart) { newStart = newStart.clone().stripTime(); } if (newEnd) { newEnd = newEnd.clone().stripTime(); } } // compute dateDelta if (newStart) { if (newAllDay) { dateDelta = dayishDiff(newStart, oldStart.clone().stripTime()); // treat oldStart as allDay } else { dateDelta = dayishDiff(newStart, oldStart); } } if (newAllDay != oldAllDay) { // if allDay has changed, always throw away the end clearEnd = true; } else if (newEnd) { durationDelta = dayishDiff( // new duration newEnd || t.getDefaultEventEnd(newAllDay, newStart || oldStart), newStart || oldStart ).subtract(dayishDiff( // subtract old duration oldEnd || t.getDefaultEventEnd(oldAllDay, oldStart), oldStart )); } return mutateEvents( clientEvents(event._id), // get events with this ID clearEnd, newAllDay, dateDelta, durationDelta ); } // Modifies an array of events in the following ways (operations are in order): // - clear the event's `end` // - convert the event to allDay // - add `dateDelta` to the start and end // - add `durationDelta` to the event's duration // // Returns a function that can be called to undo all the operations. // function mutateEvents(events, clearEnd, forceAllDay, dateDelta, durationDelta) { var isAmbigTimezone = t.getIsAmbigTimezone(); var undoFunctions = []; $.each(events, function(i, event) { var oldAllDay = event._allDay; var oldStart = event._start; var oldEnd = event._end; var newAllDay = forceAllDay != null ? forceAllDay : oldAllDay; var newStart = oldStart.clone(); var newEnd = (!clearEnd && oldEnd) ? oldEnd.clone() : null; // NOTE: this function is responsible for transforming `newStart` and `newEnd`, // which were initialized to the OLD values first. `newEnd` may be null. // normlize newStart/newEnd to be consistent with newAllDay if (newAllDay) { newStart.stripTime(); if (newEnd) { newEnd.stripTime(); } } else { if (!newStart.hasTime()) { newStart = t.rezoneDate(newStart); } if (newEnd && !newEnd.hasTime()) { newEnd = t.rezoneDate(newEnd); } } // ensure we have an end date if necessary if (!newEnd && (options.forceEventDuration || +durationDelta)) { newEnd = t.getDefaultEventEnd(newAllDay, newStart); } // translate the dates newStart.add(dateDelta); if (newEnd) { newEnd.add(dateDelta).add(durationDelta); } // if the dates have changed, and we know it is impossible to recompute the // timezone offsets, strip the zone. if (isAmbigTimezone) { if (+dateDelta) { newStart.stripZone(); } if (newEnd && (+dateDelta || +durationDelta)) { newEnd.stripZone(); } } event.allDay = newAllDay; event.start = newStart; event.end = newEnd; backupEventDates(event); undoFunctions.push(function() { event.allDay = oldAllDay; event.start = oldStart; event.end = oldEnd; backupEventDates(event); }); }); return function() { for (var i=0; i<undoFunctions.length; i++) { undoFunctions[i](); } }; } /* Utils ------------------------------------------------------------------------------*/ function normalizeSource(source) { if (source.className) { // TODO: repeat code, same code for event classNames if (typeof source.className == 'string') { source.className = source.className.split(/\s+/); } }else{ source.className = []; } var normalizers = fc.sourceNormalizers; for (var i=0; i<normalizers.length; i++) { normalizers[i].call(t, source); } } function isSourcesEqual(source1, source2) { return source1 && source2 && getSourcePrimitive(source1) == getSourcePrimitive(source2); } function getSourcePrimitive(source) { return ((typeof source == 'object') ? (source.events || source.url) : '') || source; } } // updates the "backup" properties, which are preserved in order to compute diffs later on. function backupEventDates(event) { event._allDay = event.allDay; event._start = event.start.clone(); event._end = event.end ? event.end.clone() : null; } ;; fc.applyAll = applyAll; // Create an object that has the given prototype. // Just like Object.create function createObject(proto) { var f = function() {}; f.prototype = proto; return new f(); } // copy specifically-owned (non-protoype) properties of `b` onto `a` function extend(a, b) { for (var i in b) { if (b.hasOwnProperty(i)) { a[i] = b[i]; } } } /* Date -----------------------------------------------------------------------------*/ var dayIDs = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']; // diffs the two moments into a Duration where full-days are recorded first, // then the remaining time. function dayishDiff(d1, d0) { return moment.duration({ days: d1.clone().stripTime().diff(d0.clone().stripTime(), 'days'), ms: d1.time() - d0.time() }); } function isNativeDate(input) { return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date; } /* Event Element Binding -----------------------------------------------------------------------------*/ function lazySegBind(container, segs, bindHandlers) { container.unbind('mouseover').mouseover(function(ev) { var parent=ev.target, e, i, seg; while (parent != this) { e = parent; parent = parent.parentNode; } if ((i = e._fci) !== undefined) { e._fci = undefined; seg = segs[i]; bindHandlers(seg.event, seg.element, seg); $(ev.target).trigger(ev); } ev.stopPropagation(); }); } /* Element Dimensions -----------------------------------------------------------------------------*/ function setOuterWidth(element, width, includeMargins) { for (var i=0, e; i<element.length; i++) { e = $(element[i]); e.width(Math.max(0, width - hsides(e, includeMargins))); } } function setOuterHeight(element, height, includeMargins) { for (var i=0, e; i<element.length; i++) { e = $(element[i]); e.height(Math.max(0, height - vsides(e, includeMargins))); } } function hsides(element, includeMargins) { return hpadding(element) + hborders(element) + (includeMargins ? hmargins(element) : 0); } function hpadding(element) { return (parseFloat($.css(element[0], 'paddingLeft', true)) || 0) + (parseFloat($.css(element[0], 'paddingRight', true)) || 0); } function hmargins(element) { return (parseFloat($.css(element[0], 'marginLeft', true)) || 0) + (parseFloat($.css(element[0], 'marginRight', true)) || 0); } function hborders(element) { return (parseFloat($.css(element[0], 'borderLeftWidth', true)) || 0) + (parseFloat($.css(element[0], 'borderRightWidth', true)) || 0); } function vsides(element, includeMargins) { return vpadding(element) + vborders(element) + (includeMargins ? vmargins(element) : 0); } function vpadding(element) { return (parseFloat($.css(element[0], 'paddingTop', true)) || 0) + (parseFloat($.css(element[0], 'paddingBottom', true)) || 0); } function vmargins(element) { return (parseFloat($.css(element[0], 'marginTop', true)) || 0) + (parseFloat($.css(element[0], 'marginBottom', true)) || 0); } function vborders(element) { return (parseFloat($.css(element[0], 'borderTopWidth', true)) || 0) + (parseFloat($.css(element[0], 'borderBottomWidth', true)) || 0); } /* Misc Utils -----------------------------------------------------------------------------*/ //TODO: arraySlice //TODO: isFunction, grep ? function noop() { } function dateCompare(a, b) { // works with moments too return a - b; } function arrayMax(a) { return Math.max.apply(Math, a); } function smartProperty(obj, name) { // get a camel-cased/namespaced property of an object if (obj[name] !== undefined) { return obj[name]; } var parts = name.split(/(?=[A-Z])/), i=parts.length-1, res; for (; i>=0; i--) { res = obj[parts[i].toLowerCase()]; if (res !== undefined) { return res; } } return obj['default']; } function htmlEscape(s) { return (s + '').replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/'/g, '&#039;') .replace(/"/g, '&quot;') .replace(/\n/g, '<br />'); } function stripHTMLEntities(text) { return text.replace(/&.*?;/g, ''); } function disableTextSelection(element) { element .attr('unselectable', 'on') .css('MozUserSelect', 'none') .bind('selectstart.ui', function() { return false; }); } /* function enableTextSelection(element) { element .attr('unselectable', 'off') .css('MozUserSelect', '') .unbind('selectstart.ui'); } */ function markFirstLast(e) { // TODO: use CSS selectors instead e.children() .removeClass('fc-first fc-last') .filter(':first-child') .addClass('fc-first') .end() .filter(':last-child') .addClass('fc-last'); } function getSkinCss(event, opt) { var source = event.source || {}; var eventColor = event.color; var sourceColor = source.color; var optionColor = opt('eventColor'); var backgroundColor = event.backgroundColor || eventColor || source.backgroundColor || sourceColor || opt('eventBackgroundColor') || optionColor; var borderColor = event.borderColor || eventColor || source.borderColor || sourceColor || opt('eventBorderColor') || optionColor; var textColor = event.textColor || source.textColor || opt('eventTextColor'); var statements = []; if (backgroundColor) { statements.push('background-color:' + backgroundColor); } if (borderColor) { statements.push('border-color:' + borderColor); } if (textColor) { statements.push('color:' + textColor); } return statements.join(';'); } function applyAll(functions, thisObj, args) { if ($.isFunction(functions)) { functions = [ functions ]; } if (functions) { var i; var ret; for (i=0; i<functions.length; i++) { ret = functions[i].apply(thisObj, args) || ret; } return ret; } } function firstDefined() { for (var i=0; i<arguments.length; i++) { if (arguments[i] !== undefined) { return arguments[i]; } } } ;; var ambigDateOfMonthRegex = /^\s*\d{4}-\d\d$/; var ambigTimeOrZoneRegex = /^\s*\d{4}-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?)?$/; // Creating // ------------------------------------------------------------------------------------------------- // Creates a moment in the local timezone, similar to the vanilla moment(...) constructor, // but with extra features: // - ambiguous times // - enhanced formatting (TODO) fc.moment = function() { return makeMoment(arguments); }; // Sames as fc.moment, but creates a moment in the UTC timezone. fc.moment.utc = function() { return makeMoment(arguments, true); }; // Creates a moment and preserves the timezone offset of the ISO8601 string, // allowing for ambigous timezones. If the string is not an ISO8601 string, // the moment is processed in UTC-mode (a departure from moment's method). fc.moment.parseZone = function() { return makeMoment(arguments, true, true); }; // when parseZone==true, if can't figure it out, fall back to parseUTC function makeMoment(args, parseUTC, parseZone) { var input = args[0]; var isSingleString = args.length == 1 && typeof input === 'string'; var isAmbigTime = false; var isAmbigZone = false; var ambigMatch; var mom; if (isSingleString) { if (ambigDateOfMonthRegex.test(input)) { // accept strings like '2014-05', but convert to the first of the month input += '-01'; isAmbigTime = true; isAmbigZone = true; } else if ((ambigMatch = ambigTimeOrZoneRegex.exec(input))) { isAmbigTime = !ambigMatch[5]; // no time part? isAmbigZone = true; } } else if ($.isArray(input)) { // arrays have no timezone information, so assume ambiguous zone isAmbigZone = true; } // instantiate a vanilla moment if (parseUTC || parseZone || isAmbigTime) { mom = moment.utc.apply(moment, args); } else { mom = moment.apply(null, args); } if (moment.isMoment(input)) { transferAmbigs(input, mom); } if (isAmbigTime) { mom._ambigTime = true; mom._ambigZone = true; // if ambiguous time, also ambiguous timezone offset } if (parseZone) { if (isAmbigZone) { mom._ambigZone = true; } else if (isSingleString) { mom.zone(input); // if fails, will set it to 0, which it already was } else if (isNativeDate(input) || input === undefined) { // native Date object? // specified with no arguments? // then consider the moment to be local mom.local(); } } return new FCMoment(mom); } // our subclass of Moment. // accepts an object with the internal Moment properties that should be copied over to // this object (most likely another Moment object). function FCMoment(config) { extend(this, config); } // chain the prototype to Moment's FCMoment.prototype = createObject(moment.fn); // we need this because Moment's implementation will not copy of the ambig flags FCMoment.prototype.clone = function() { return makeMoment([ this ]); }; // Time-of-day // ------------------------------------------------------------------------------------------------- // GETTER // Returns a Duration with the hours/minutes/seconds/ms values of the moment. // If the moment has an ambiguous time, a duration of 00:00 will be returned. // // SETTER // You can supply a Duration, a Moment, or a Duration-like argument. // When setting the time, and the moment has an ambiguous time, it then becomes unambiguous. FCMoment.prototype.time = function(time) { if (time == null) { // getter return moment.duration({ hours: this.hours(), minutes: this.minutes(), seconds: this.seconds(), milliseconds: this.milliseconds() }); } else { // setter delete this._ambigTime; // mark that the moment now has a time if (!moment.isDuration(time) && !moment.isMoment(time)) { time = moment.duration(time); } return this.hours(time.hours() + time.days() * 24) // day value will cause overflow (so 24 hours becomes 00:00:00 of next day) .minutes(time.minutes()) .seconds(time.seconds()) .milliseconds(time.milliseconds()); } }; // Converts the moment to UTC, stripping out its time-of-day and timezone offset, // but preserving its YMD. A moment with a stripped time will display no time // nor timezone offset when .format() is called. FCMoment.prototype.stripTime = function() { var a = this.toArray(); // year,month,date,hours,minutes,seconds as an array // set the internal UTC flag moment.fn.utc.call(this); // call the original method, because we don't want to affect _ambigZone this._ambigTime = true; this._ambigZone = true; // if ambiguous time, also ambiguous timezone offset this.year(a[0]) .month(a[1]) .date(a[2]) .hours(0) .minutes(0) .seconds(0) .milliseconds(0); return this; // for chaining }; // Returns if the moment has a non-ambiguous time (boolean) FCMoment.prototype.hasTime = function() { return !this._ambigTime; }; // Timezone // ------------------------------------------------------------------------------------------------- // Converts the moment to UTC, stripping out its timezone offset, but preserving its // YMD and time-of-day. A moment with a stripped timezone offset will display no // timezone offset when .format() is called. FCMoment.prototype.stripZone = function() { var a = this.toArray(); // year,month,date,hours,minutes,seconds as an array // set the internal UTC flag moment.fn.utc.call(this); // call the original method, because we don't want to affect _ambigZone this._ambigZone = true; this.year(a[0]) .month(a[1]) .date(a[2]) .hours(a[3]) .minutes(a[4]) .seconds(a[5]) .milliseconds(a[6]); return this; // for chaining }; // Returns of the moment has a non-ambiguous timezone offset (boolean) FCMoment.prototype.hasZone = function() { return !this._ambigZone; }; // this method implicitly marks a zone FCMoment.prototype.zone = function(tzo) { if (tzo != null) { delete this._ambigZone; } return moment.fn.zone.apply(this, arguments); }; // this method implicitly marks a zone. // we don't need this, because .local internally calls .zone, but we don't want to depend on that. FCMoment.prototype.local = function() { delete this._ambigZone; return moment.fn.local.apply(this, arguments); }; // this method implicitly marks a zone. // we don't need this, because .utc internally calls .zone, but we don't want to depend on that. FCMoment.prototype.utc = function() { delete this._ambigZone; return moment.fn.utc.apply(this, arguments); }; // Formatting // ------------------------------------------------------------------------------------------------- FCMoment.prototype.format = function() { if (arguments[0]) { return formatDate(this, arguments[0]); // our extended formatting } if (this._ambigTime) { return momentFormat(this, 'YYYY-MM-DD'); } if (this._ambigZone) { return momentFormat(this, 'YYYY-MM-DD[T]HH:mm:ss'); } return momentFormat(this); // default moment original formatting }; FCMoment.prototype.toISOString = function() { if (this._ambigTime) { return momentFormat(this, 'YYYY-MM-DD'); } if (this._ambigZone) { return momentFormat(this, 'YYYY-MM-DD[T]HH:mm:ss'); } return moment.fn.toISOString.apply(this, arguments); }; // Querying // ------------------------------------------------------------------------------------------------- // Is the moment within the specified range? `end` is exclusive. FCMoment.prototype.isWithin = function(start, end) { var a = commonlyAmbiguate([ this, start, end ]); return a[0] >= a[1] && a[0] < a[2]; }; // Make these query methods work with ambiguous moments $.each([ 'isBefore', 'isAfter', 'isSame' ], function(i, methodName) { FCMoment.prototype[methodName] = function(input, units) { var a = commonlyAmbiguate([ this, input ]); return moment.fn[methodName].call(a[0], a[1], units); }; }); // Misc Internals // ------------------------------------------------------------------------------------------------- // transfers our internal _ambig properties from one moment to another function transferAmbigs(src, dest) { if (src._ambigTime) { dest._ambigTime = true; } else if (dest._ambigTime) { delete dest._ambigTime; } if (src._ambigZone) { dest._ambigZone = true; } else if (dest._ambigZone) { delete dest._ambigZone; } } // given an array of moment-like inputs, return a parallel array w/ moments similarly ambiguated. // for example, of one moment has ambig time, but not others, all moments will have their time stripped. function commonlyAmbiguate(inputs) { var outputs = []; var anyAmbigTime = false; var anyAmbigZone = false; var i; for (i=0; i<inputs.length; i++) { outputs.push(fc.moment(inputs[i])); anyAmbigTime = anyAmbigTime || outputs[i]._ambigTime; anyAmbigZone = anyAmbigZone || outputs[i]._ambigZone; } for (i=0; i<outputs.length; i++) { if (anyAmbigTime) { outputs[i].stripTime(); } else if (anyAmbigZone) { outputs[i].stripZone(); } } return outputs; } ;; // Single Date Formatting // ------------------------------------------------------------------------------------------------- // call this if you want Moment's original format method to be used function momentFormat(mom, formatStr) { return moment.fn.format.call(mom, formatStr); } // Formats `date` with a Moment formatting string, but allow our non-zero areas and // additional token. function formatDate(date, formatStr) { return formatDateWithChunks(date, getFormatStringChunks(formatStr)); } function formatDateWithChunks(date, chunks) { var s = ''; var i; for (i=0; i<chunks.length; i++) { s += formatDateWithChunk(date, chunks[i]); } return s; } // addition formatting tokens we want recognized var tokenOverrides = { t: function(date) { // "a" or "p" return momentFormat(date, 'a').charAt(0); }, T: function(date) { // "A" or "P" return momentFormat(date, 'A').charAt(0); } }; function formatDateWithChunk(date, chunk) { var token; var maybeStr; if (typeof chunk === 'string') { // a literal string return chunk; } else if ((token = chunk.token)) { // a token, like "YYYY" if (tokenOverrides[token]) { return tokenOverrides[token](date); // use our custom token } return momentFormat(date, token); } else if (chunk.maybe) { // a grouping of other chunks that must be non-zero maybeStr = formatDateWithChunks(date, chunk.maybe); if (maybeStr.match(/[1-9]/)) { return maybeStr; } } return ''; } // Date Range Formatting // ------------------------------------------------------------------------------------------------- // TODO: make it work with timezone offset // Using a formatting string meant for a single date, generate a range string, like // "Sep 2 - 9 2013", that intelligently inserts a separator where the dates differ. // If the dates are the same as far as the format string is concerned, just return a single // rendering of one date, without any separator. function formatRange(date1, date2, formatStr, separator, isRTL) { // Expand localized format strings, like "LL" -> "MMMM D YYYY" formatStr = date1.lang().longDateFormat(formatStr) || formatStr; // BTW, this is not important for `formatDate` because it is impossible to put custom tokens // or non-zero areas in Moment's localized format strings. separator = separator || ' - '; return formatRangeWithChunks( date1, date2, getFormatStringChunks(formatStr), separator, isRTL ); } fc.formatRange = formatRange; // expose function formatRangeWithChunks(date1, date2, chunks, separator, isRTL) { var chunkStr; // the rendering of the chunk var leftI; var leftStr = ''; var rightI; var rightStr = ''; var middleI; var middleStr1 = ''; var middleStr2 = ''; var middleStr = ''; // Start at the leftmost side of the formatting string and continue until you hit a token // that is not the same between dates. for (leftI=0; leftI<chunks.length; leftI++) { chunkStr = formatSimilarChunk(date1, date2, chunks[leftI]); if (chunkStr === false) { break; } leftStr += chunkStr; } // Similarly, start at the rightmost side of the formatting string and move left for (rightI=chunks.length-1; rightI>leftI; rightI--) { chunkStr = formatSimilarChunk(date1, date2, chunks[rightI]); if (chunkStr === false) { break; } rightStr = chunkStr + rightStr; } // The area in the middle is different for both of the dates. // Collect them distinctly so we can jam them together later. for (middleI=leftI; middleI<=rightI; middleI++) { middleStr1 += formatDateWithChunk(date1, chunks[middleI]); middleStr2 += formatDateWithChunk(date2, chunks[middleI]); } if (middleStr1 || middleStr2) { if (isRTL) { middleStr = middleStr2 + separator + middleStr1; } else { middleStr = middleStr1 + separator + middleStr2; } } return leftStr + middleStr + rightStr; } var similarUnitMap = { Y: 'year', M: 'month', D: 'day', // day of month d: 'day' // day of week }; // don't go any further than day, because we don't want to break apart times like "12:30:00" // TODO: week maybe? // Given a formatting chunk, and given that both dates are similar in the regard the // formatting chunk is concerned, format date1 against `chunk`. Otherwise, return `false`. function formatSimilarChunk(date1, date2, chunk) { var token; var unit; if (typeof chunk === 'string') { // a literal string return chunk; } else if ((token = chunk.token)) { unit = similarUnitMap[token.charAt(0)]; // are the dates the same for this unit of measurement? if (unit && date1.isSame(date2, unit)) { return momentFormat(date1, token); // would be the same if we used `date2` // BTW, don't support custom tokens } } return false; // the chunk is NOT the same for the two dates // BTW, don't support splitting on non-zero areas } // Chunking Utils // ------------------------------------------------------------------------------------------------- var formatStringChunkCache = {}; function getFormatStringChunks(formatStr) { if (formatStr in formatStringChunkCache) { return formatStringChunkCache[formatStr]; } return (formatStringChunkCache[formatStr] = chunkFormatString(formatStr)); } // Break the formatting string into an array of chunks function chunkFormatString(formatStr) { var chunks = []; var chunker = /\[([^\]]*)\]|\(([^\)]*)\)|((\w)\4*o?T?)|([^\w\[\(]+)/g; // TODO: more descrimination var match; while ((match = chunker.exec(formatStr))) { if (match[1]) { // a literal string instead [ ... ] chunks.push(match[1]); } else if (match[2]) { // non-zero formatting inside ( ... ) chunks.push({ maybe: chunkFormatString(match[2]) }); } else if (match[3]) { // a formatting token chunks.push({ token: match[3] }); } else if (match[5]) { // an unenclosed literal string chunks.push(match[5]); } } return chunks; } ;; fcViews.month = MonthView; function MonthView(element, calendar) { var t = this; // exports t.incrementDate = incrementDate; t.render = render; // imports BasicView.call(t, element, calendar, 'month'); function incrementDate(date, delta) { return date.clone().stripTime().add('months', delta).startOf('month'); } function render(date) { t.intervalStart = date.clone().stripTime().startOf('month'); t.intervalEnd = t.intervalStart.clone().add('months', 1); t.start = t.intervalStart.clone().startOf('week'); t.start = t.skipHiddenDays(t.start); t.end = t.intervalEnd.clone().add('days', (7 - t.intervalEnd.weekday()) % 7); t.end = t.skipHiddenDays(t.end, -1, true); var rowCnt = Math.ceil( // need to ceil in case there are hidden days t.end.diff(t.start, 'weeks', true) // returnfloat=true ); if (t.opt('weekMode') == 'fixed') { t.end.add('weeks', 6 - rowCnt); rowCnt = 6; } t.title = calendar.formatDate(t.intervalStart, t.opt('titleFormat')); t.renderBasic(rowCnt, t.getCellsPerWeek(), true); } } ;; fcViews.basicWeek = BasicWeekView; function BasicWeekView(element, calendar) { // TODO: do a WeekView mixin var t = this; // exports t.incrementDate = incrementDate; t.render = render; // imports BasicView.call(t, element, calendar, 'basicWeek'); function incrementDate(date, delta) { return date.clone().stripTime().add('weeks', delta).startOf('week'); } function render(date) { t.intervalStart = date.clone().stripTime().startOf('week'); t.intervalEnd = t.intervalStart.clone().add('weeks', 1); t.start = t.skipHiddenDays(t.intervalStart); t.end = t.skipHiddenDays(t.intervalEnd, -1, true); t.title = calendar.formatRange( t.start, t.end.clone().subtract(1), // make inclusive by subtracting 1 ms t.opt('titleFormat'), ' \u2014 ' // emphasized dash ); t.renderBasic(1, t.getCellsPerWeek(), false); } } ;; fcViews.basicDay = BasicDayView; function BasicDayView(element, calendar) { // TODO: make a DayView mixin var t = this; // exports t.incrementDate = incrementDate; t.render = render; // imports BasicView.call(t, element, calendar, 'basicDay'); function incrementDate(date, delta) { var out = date.clone().stripTime().add('days', delta); out = t.skipHiddenDays(out, delta < 0 ? -1 : 1); return out; } function render(date) { t.start = t.intervalStart = date.clone().stripTime(); t.end = t.intervalEnd = t.start.clone().add('days', 1); t.title = calendar.formatDate(t.start, t.opt('titleFormat')); t.renderBasic(1, 1, false); } } ;; setDefaults({ weekMode: 'fixed' }); function BasicView(element, calendar, viewName) { var t = this; // exports t.renderBasic = renderBasic; t.setHeight = setHeight; t.setWidth = setWidth; t.renderDayOverlay = renderDayOverlay; t.defaultSelectionEnd = defaultSelectionEnd; t.renderSelection = renderSelection; t.clearSelection = clearSelection; t.reportDayClick = reportDayClick; // for selection (kinda hacky) t.dragStart = dragStart; t.dragStop = dragStop; t.getHoverListener = function() { return hoverListener; }; t.colLeft = colLeft; t.colRight = colRight; t.colContentLeft = colContentLeft; t.colContentRight = colContentRight; t.getIsCellAllDay = function() { return true; }; t.allDayRow = allDayRow; t.getRowCnt = function() { return rowCnt; }; t.getColCnt = function() { return colCnt; }; t.getColWidth = function() { return colWidth; }; t.getDaySegmentContainer = function() { return daySegmentContainer; }; // imports View.call(t, element, calendar, viewName); OverlayManager.call(t); SelectionManager.call(t); BasicEventRenderer.call(t); var opt = t.opt; var trigger = t.trigger; var renderOverlay = t.renderOverlay; var clearOverlays = t.clearOverlays; var daySelectionMousedown = t.daySelectionMousedown; var cellToDate = t.cellToDate; var dateToCell = t.dateToCell; var rangeToSegments = t.rangeToSegments; var formatDate = calendar.formatDate; var calculateWeekNumber = calendar.calculateWeekNumber; // locals var table; var head; var headCells; var body; var bodyRows; var bodyCells; var bodyFirstCells; var firstRowCellInners; var firstRowCellContentInners; var daySegmentContainer; var viewWidth; var viewHeight; var colWidth; var weekNumberWidth; var rowCnt, colCnt; var showNumbers; var coordinateGrid; var hoverListener; var colPositions; var colContentPositions; var tm; var colFormat; var showWeekNumbers; /* Rendering ------------------------------------------------------------*/ disableTextSelection(element.addClass('fc-grid')); function renderBasic(_rowCnt, _colCnt, _showNumbers) { rowCnt = _rowCnt; colCnt = _colCnt; showNumbers = _showNumbers; updateOptions(); if (!body) { buildEventContainer(); } buildTable(); } function updateOptions() { tm = opt('theme') ? 'ui' : 'fc'; colFormat = opt('columnFormat'); showWeekNumbers = opt('weekNumbers'); } function buildEventContainer() { daySegmentContainer = $("<div class='fc-event-container' style='position:absolute;z-index:8;top:0;left:0'/>") .appendTo(element); } function buildTable() { var html = buildTableHTML(); if (table) { table.remove(); } table = $(html).appendTo(element); head = table.find('thead'); headCells = head.find('.fc-day-header'); body = table.find('tbody'); bodyRows = body.find('tr'); bodyCells = body.find('.fc-day'); bodyFirstCells = bodyRows.find('td:first-child'); firstRowCellInners = bodyRows.eq(0).find('.fc-day > div'); firstRowCellContentInners = bodyRows.eq(0).find('.fc-day-content > div'); markFirstLast(head.add(head.find('tr'))); // marks first+last tr/th's markFirstLast(bodyRows); // marks first+last td's bodyRows.eq(0).addClass('fc-first'); bodyRows.filter(':last').addClass('fc-last'); bodyCells.each(function(i, _cell) { var date = cellToDate( Math.floor(i / colCnt), i % colCnt ); trigger('dayRender', t, date, $(_cell)); }); dayBind(bodyCells); } /* HTML Building -----------------------------------------------------------*/ function buildTableHTML() { var html = "<table class='fc-border-separate' style='width:100%' cellspacing='0'>" + buildHeadHTML() + buildBodyHTML() + "</table>"; return html; } function buildHeadHTML() { var headerClass = tm + "-widget-header"; var html = ''; var col; var date; html += "<thead><tr>"; if (showWeekNumbers) { html += "<th class='fc-week-number " + headerClass + "'>" + htmlEscape(opt('weekNumberTitle')) + "</th>"; } for (col=0; col<colCnt; col++) { date = cellToDate(0, col); html += "<th class='fc-day-header fc-" + dayIDs[date.day()] + " " + headerClass + "'>" + htmlEscape(formatDate(date, colFormat)) + "</th>"; } html += "</tr></thead>"; return html; } function buildBodyHTML() { var contentClass = tm + "-widget-content"; var html = ''; var row; var col; var date; html += "<tbody>"; for (row=0; row<rowCnt; row++) { html += "<tr class='fc-week'>"; if (showWeekNumbers) { date = cellToDate(row, 0); html += "<td class='fc-week-number " + contentClass + "'>" + "<div>" + htmlEscape(calculateWeekNumber(date)) + "</div>" + "</td>"; } for (col=0; col<colCnt; col++) { date = cellToDate(row, col); html += buildCellHTML(date); } html += "</tr>"; } html += "</tbody>"; return html; } function buildCellHTML(date) { // date assumed to have stripped time var month = t.intervalStart.month(); var today = calendar.getNow().stripTime(); var html = ''; var contentClass = tm + "-widget-content"; var classNames = [ 'fc-day', 'fc-' + dayIDs[date.day()], contentClass ]; if (date.month() != month) { classNames.push('fc-other-month'); } if (date.isSame(today, 'day')) { classNames.push( 'fc-today', tm + '-state-highlight' ); } else if (date < today) { classNames.push('fc-past'); } else { classNames.push('fc-future'); } html += "<td" + " class='" + classNames.join(' ') + "'" + " data-date='" + date.format() + "'" + ">" + "<div>"; if (showNumbers) { html += "<div class='fc-day-number'>" + date.date() + "</div>"; } html += "<div class='fc-day-content'>" + "<div style='position:relative'>&nbsp;</div>" + "</div>" + "</div>" + "</td>"; return html; } /* Dimensions -----------------------------------------------------------*/ function setHeight(height) { viewHeight = height; var bodyHeight = Math.max(viewHeight - head.height(), 0); var rowHeight; var rowHeightLast; var cell; if (opt('weekMode') == 'variable') { rowHeight = rowHeightLast = Math.floor(bodyHeight / (rowCnt==1 ? 2 : 6)); }else{ rowHeight = Math.floor(bodyHeight / rowCnt); rowHeightLast = bodyHeight - rowHeight * (rowCnt-1); } bodyFirstCells.each(function(i, _cell) { if (i < rowCnt) { cell = $(_cell); cell.find('> div').css( 'min-height', (i==rowCnt-1 ? rowHeightLast : rowHeight) - vsides(cell) ); } }); } function setWidth(width) { viewWidth = width; colPositions.clear(); colContentPositions.clear(); weekNumberWidth = 0; if (showWeekNumbers) { weekNumberWidth = head.find('th.fc-week-number').outerWidth(); } colWidth = Math.floor((viewWidth - weekNumberWidth) / colCnt); setOuterWidth(headCells.slice(0, -1), colWidth); } /* Day clicking and binding -----------------------------------------------------------*/ function dayBind(days) { days.click(dayClick) .mousedown(daySelectionMousedown); } function dayClick(ev) { if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick var date = calendar.moment($(this).data('date')); trigger('dayClick', this, date, ev); } } /* Semi-transparent Overlay Helpers ------------------------------------------------------*/ // TODO: should be consolidated with AgendaView's methods function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive if (refreshCoordinateGrid) { coordinateGrid.build(); } var segments = rangeToSegments(overlayStart, overlayEnd); for (var i=0; i<segments.length; i++) { var segment = segments[i]; dayBind( renderCellOverlay( segment.row, segment.leftCol, segment.row, segment.rightCol ) ); } } function renderCellOverlay(row0, col0, row1, col1) { // row1,col1 is inclusive var rect = coordinateGrid.rect(row0, col0, row1, col1, element); return renderOverlay(rect, element); } /* Selection -----------------------------------------------------------------------*/ function defaultSelectionEnd(start) { return start.clone().stripTime().add('days', 1); } function renderSelection(start, end) { // end is exclusive renderDayOverlay(start, end, true); // true = rebuild every time } function clearSelection() { clearOverlays(); } function reportDayClick(date, ev) { var cell = dateToCell(date); var _element = bodyCells[cell.row*colCnt + cell.col]; trigger('dayClick', _element, date, ev); } /* External Dragging -----------------------------------------------------------------------*/ function dragStart(_dragElement, ev, ui) { hoverListener.start(function(cell) { clearOverlays(); if (cell) { var d1 = cellToDate(cell); var d2 = d1.clone().add(calendar.defaultAllDayEventDuration); renderDayOverlay(d1, d2); } }, ev); } function dragStop(_dragElement, ev, ui) { var cell = hoverListener.stop(); clearOverlays(); if (cell) { trigger( 'drop', _dragElement, cellToDate(cell), ev, ui ); } } /* Utilities --------------------------------------------------------*/ coordinateGrid = new CoordinateGrid(function(rows, cols) { var e, n, p; headCells.each(function(i, _e) { e = $(_e); n = e.offset().left; if (i) { p[1] = n; } p = [n]; cols[i] = p; }); p[1] = n + e.outerWidth(); bodyRows.each(function(i, _e) { if (i < rowCnt) { e = $(_e); n = e.offset().top; if (i) { p[1] = n; } p = [n]; rows[i] = p; } }); p[1] = n + e.outerHeight(); }); hoverListener = new HoverListener(coordinateGrid); colPositions = new HorizontalPositionCache(function(col) { return firstRowCellInners.eq(col); }); colContentPositions = new HorizontalPositionCache(function(col) { return firstRowCellContentInners.eq(col); }); function colLeft(col) { return colPositions.left(col); } function colRight(col) { return colPositions.right(col); } function colContentLeft(col) { return colContentPositions.left(col); } function colContentRight(col) { return colContentPositions.right(col); } function allDayRow(i) { return bodyRows.eq(i); } } ;; function BasicEventRenderer() { var t = this; // exports t.renderEvents = renderEvents; t.clearEvents = clearEvents; // imports DayEventRenderer.call(t); function renderEvents(events, modifiedEventId) { t.renderDayEvents(events, modifiedEventId); } function clearEvents() { t.getDaySegmentContainer().empty(); } // TODO: have this class (and AgendaEventRenderer) be responsible for creating the event container div } ;; fcViews.agendaWeek = AgendaWeekView; function AgendaWeekView(element, calendar) { // TODO: do a WeekView mixin var t = this; // exports t.incrementDate = incrementDate; t.render = render; // imports AgendaView.call(t, element, calendar, 'agendaWeek'); function incrementDate(date, delta) { return date.clone().stripTime().add('weeks', delta).startOf('week'); } function render(date) { t.intervalStart = date.clone().stripTime().startOf('week'); t.intervalEnd = t.intervalStart.clone().add('weeks', 1); t.start = t.skipHiddenDays(t.intervalStart); t.end = t.skipHiddenDays(t.intervalEnd, -1, true); t.title = calendar.formatRange( t.start, t.end.clone().subtract(1), // make inclusive by subtracting 1 ms t.opt('titleFormat'), ' \u2014 ' // emphasized dash ); t.renderAgenda(t.getCellsPerWeek()); } } ;; fcViews.agendaDay = AgendaDayView; function AgendaDayView(element, calendar) { // TODO: make a DayView mixin var t = this; // exports t.incrementDate = incrementDate; t.render = render; // imports AgendaView.call(t, element, calendar, 'agendaDay'); function incrementDate(date, delta) { var out = date.clone().stripTime().add('days', delta); out = t.skipHiddenDays(out, delta < 0 ? -1 : 1); return out; } function render(date) { t.start = t.intervalStart = date.clone().stripTime(); t.end = t.intervalEnd = t.start.clone().add('days', 1); t.title = calendar.formatDate(t.start, t.opt('titleFormat')); t.renderAgenda(1); } } ;; setDefaults({ allDaySlot: true, allDayText: 'all-day', scrollTime: '06:00:00', slotDuration: '00:30:00', axisFormat: generateAgendaAxisFormat, timeFormat: { agenda: generateAgendaTimeFormat }, dragOpacity: { agenda: .5 }, minTime: '00:00:00', maxTime: '24:00:00', slotEventOverlap: true }); function generateAgendaAxisFormat(options, langData) { return langData.longDateFormat('LT') .replace(':mm', '(:mm)') .replace(/(\Wmm)$/, '($1)') // like above, but for foreign langs .replace(/\s*a$/i, 'a'); // convert AM/PM/am/pm to lowercase. remove any spaces beforehand } function generateAgendaTimeFormat(options, langData) { return langData.longDateFormat('LT') .replace(/\s*a$/i, ''); // remove trailing AM/PM } // TODO: make it work in quirks mode (event corners, all-day height) // TODO: test liquid width, especially in IE6 function AgendaView(element, calendar, viewName) { var t = this; // exports t.renderAgenda = renderAgenda; t.setWidth = setWidth; t.setHeight = setHeight; t.afterRender = afterRender; t.computeDateTop = computeDateTop; t.getIsCellAllDay = getIsCellAllDay; t.allDayRow = function() { return allDayRow; }; // badly named t.getCoordinateGrid = function() { return coordinateGrid; }; // specifically for AgendaEventRenderer t.getHoverListener = function() { return hoverListener; }; t.colLeft = colLeft; t.colRight = colRight; t.colContentLeft = colContentLeft; t.colContentRight = colContentRight; t.getDaySegmentContainer = function() { return daySegmentContainer; }; t.getSlotSegmentContainer = function() { return slotSegmentContainer; }; t.getSlotContainer = function() { return slotContainer; }; t.getRowCnt = function() { return 1; }; t.getColCnt = function() { return colCnt; }; t.getColWidth = function() { return colWidth; }; t.getSnapHeight = function() { return snapHeight; }; t.getSnapDuration = function() { return snapDuration; }; t.getSlotHeight = function() { return slotHeight; }; t.getSlotDuration = function() { return slotDuration; }; t.getMinTime = function() { return minTime; }; t.getMaxTime = function() { return maxTime; }; t.defaultSelectionEnd = defaultSelectionEnd; t.renderDayOverlay = renderDayOverlay; t.renderSelection = renderSelection; t.clearSelection = clearSelection; t.reportDayClick = reportDayClick; // selection mousedown hack t.dragStart = dragStart; t.dragStop = dragStop; // imports View.call(t, element, calendar, viewName); OverlayManager.call(t); SelectionManager.call(t); AgendaEventRenderer.call(t); var opt = t.opt; var trigger = t.trigger; var renderOverlay = t.renderOverlay; var clearOverlays = t.clearOverlays; var reportSelection = t.reportSelection; var unselect = t.unselect; var daySelectionMousedown = t.daySelectionMousedown; var slotSegHtml = t.slotSegHtml; var cellToDate = t.cellToDate; var dateToCell = t.dateToCell; var rangeToSegments = t.rangeToSegments; var formatDate = calendar.formatDate; var calculateWeekNumber = calendar.calculateWeekNumber; // locals var dayTable; var dayHead; var dayHeadCells; var dayBody; var dayBodyCells; var dayBodyCellInners; var dayBodyCellContentInners; var dayBodyFirstCell; var dayBodyFirstCellStretcher; var slotLayer; var daySegmentContainer; var allDayTable; var allDayRow; var slotScroller; var slotContainer; var slotSegmentContainer; var slotTable; var selectionHelper; var viewWidth; var viewHeight; var axisWidth; var colWidth; var gutterWidth; var slotDuration; var slotHeight; // TODO: what if slotHeight changes? (see issue 650) var snapDuration; var snapRatio; // ratio of number of "selection" slots to normal slots. (ex: 1, 2, 4) var snapHeight; // holds the pixel hight of a "selection" slot var colCnt; var slotCnt; var coordinateGrid; var hoverListener; var colPositions; var colContentPositions; var slotTopCache = {}; var tm; var rtl; var minTime; var maxTime; var colFormat; /* Rendering -----------------------------------------------------------------------------*/ disableTextSelection(element.addClass('fc-agenda')); function renderAgenda(c) { colCnt = c; updateOptions(); if (!dayTable) { // first time rendering? buildSkeleton(); // builds day table, slot area, events containers } else { buildDayTable(); // rebuilds day table } } function updateOptions() { tm = opt('theme') ? 'ui' : 'fc'; rtl = opt('isRTL'); colFormat = opt('columnFormat'); minTime = moment.duration(opt('minTime')); maxTime = moment.duration(opt('maxTime')); slotDuration = moment.duration(opt('slotDuration')); snapDuration = opt('snapDuration'); snapDuration = snapDuration ? moment.duration(snapDuration) : slotDuration; } /* Build DOM -----------------------------------------------------------------------*/ function buildSkeleton() { var s; var headerClass = tm + "-widget-header"; var contentClass = tm + "-widget-content"; var slotTime; var slotDate; var minutes; var slotNormal = slotDuration.asMinutes() % 15 === 0; buildDayTable(); slotLayer = $("<div style='position:absolute;z-index:2;left:0;width:100%'/>") .appendTo(element); if (opt('allDaySlot')) { daySegmentContainer = $("<div class='fc-event-container' style='position:absolute;z-index:8;top:0;left:0'/>") .appendTo(slotLayer); s = "<table style='width:100%' class='fc-agenda-allday' cellspacing='0'>" + "<tr>" + "<th class='" + headerClass + " fc-agenda-axis'>" + ( opt('allDayHTML') || htmlEscape(opt('allDayText')) ) + "</th>" + "<td>" + "<div class='fc-day-content'><div style='position:relative'/></div>" + "</td>" + "<th class='" + headerClass + " fc-agenda-gutter'>&nbsp;</th>" + "</tr>" + "</table>"; allDayTable = $(s).appendTo(slotLayer); allDayRow = allDayTable.find('tr'); dayBind(allDayRow.find('td')); slotLayer.append( "<div class='fc-agenda-divider " + headerClass + "'>" + "<div class='fc-agenda-divider-inner'/>" + "</div>" ); }else{ daySegmentContainer = $([]); // in jQuery 1.4, we can just do $() } slotScroller = $("<div style='position:absolute;width:100%;overflow-x:hidden;overflow-y:auto'/>") .appendTo(slotLayer); slotContainer = $("<div style='position:relative;width:100%;overflow:hidden'/>") .appendTo(slotScroller); slotSegmentContainer = $("<div class='fc-event-container' style='position:absolute;z-index:8;top:0;left:0'/>") .appendTo(slotContainer); s = "<table class='fc-agenda-slots' style='width:100%' cellspacing='0'>" + "<tbody>"; slotTime = moment.duration(+minTime); // i wish there was .clone() for durations slotCnt = 0; while (slotTime < maxTime) { slotDate = t.start.clone().time(slotTime); // will be in UTC but that's good. to avoid DST issues minutes = slotDate.minutes(); s += "<tr class='fc-slot" + slotCnt + ' ' + (!minutes ? '' : 'fc-minor') + "'>" + "<th class='fc-agenda-axis " + headerClass + "'>" + ((!slotNormal || !minutes) ? htmlEscape(formatDate(slotDate, opt('axisFormat'))) : '&nbsp;' ) + "</th>" + "<td class='" + contentClass + "'>" + "<div style='position:relative'>&nbsp;</div>" + "</td>" + "</tr>"; slotTime.add(slotDuration); slotCnt++; } s += "</tbody>" + "</table>"; slotTable = $(s).appendTo(slotContainer); slotBind(slotTable.find('td')); } /* Build Day Table -----------------------------------------------------------------------*/ function buildDayTable() { var html = buildDayTableHTML(); if (dayTable) { dayTable.remove(); } dayTable = $(html).appendTo(element); dayHead = dayTable.find('thead'); dayHeadCells = dayHead.find('th').slice(1, -1); // exclude gutter dayBody = dayTable.find('tbody'); dayBodyCells = dayBody.find('td').slice(0, -1); // exclude gutter dayBodyCellInners = dayBodyCells.find('> div'); dayBodyCellContentInners = dayBodyCells.find('.fc-day-content > div'); dayBodyFirstCell = dayBodyCells.eq(0); dayBodyFirstCellStretcher = dayBodyCellInners.eq(0); markFirstLast(dayHead.add(dayHead.find('tr'))); markFirstLast(dayBody.add(dayBody.find('tr'))); // TODO: now that we rebuild the cells every time, we should call dayRender } function buildDayTableHTML() { var html = "<table style='width:100%' class='fc-agenda-days fc-border-separate' cellspacing='0'>" + buildDayTableHeadHTML() + buildDayTableBodyHTML() + "</table>"; return html; } function buildDayTableHeadHTML() { var headerClass = tm + "-widget-header"; var date; var html = ''; var weekText; var col; html += "<thead>" + "<tr>"; if (opt('weekNumbers')) { date = cellToDate(0, 0); weekText = calculateWeekNumber(date); if (rtl) { weekText += opt('weekNumberTitle'); } else { weekText = opt('weekNumberTitle') + weekText; } html += "<th class='fc-agenda-axis fc-week-number " + headerClass + "'>" + htmlEscape(weekText) + "</th>"; } else { html += "<th class='fc-agenda-axis " + headerClass + "'>&nbsp;</th>"; } for (col=0; col<colCnt; col++) { date = cellToDate(0, col); html += "<th class='fc-" + dayIDs[date.day()] + " fc-col" + col + ' ' + headerClass + "'>" + htmlEscape(formatDate(date, colFormat)) + "</th>"; } html += "<th class='fc-agenda-gutter " + headerClass + "'>&nbsp;</th>" + "</tr>" + "</thead>"; return html; } function buildDayTableBodyHTML() { var headerClass = tm + "-widget-header"; // TODO: make these when updateOptions() called var contentClass = tm + "-widget-content"; var date; var today = calendar.getNow().stripTime(); var col; var cellsHTML; var cellHTML; var classNames; var html = ''; html += "<tbody>" + "<tr>" + "<th class='fc-agenda-axis " + headerClass + "'>&nbsp;</th>"; cellsHTML = ''; for (col=0; col<colCnt; col++) { date = cellToDate(0, col); classNames = [ 'fc-col' + col, 'fc-' + dayIDs[date.day()], contentClass ]; if (date.isSame(today, 'day')) { classNames.push( tm + '-state-highlight', 'fc-today' ); } else if (date < today) { classNames.push('fc-past'); } else { classNames.push('fc-future'); } cellHTML = "<td class='" + classNames.join(' ') + "'>" + "<div>" + "<div class='fc-day-content'>" + "<div style='position:relative'>&nbsp;</div>" + "</div>" + "</div>" + "</td>"; cellsHTML += cellHTML; } html += cellsHTML; html += "<td class='fc-agenda-gutter " + contentClass + "'>&nbsp;</td>" + "</tr>" + "</tbody>"; return html; } // TODO: data-date on the cells /* Dimensions -----------------------------------------------------------------------*/ function setHeight(height) { if (height === undefined) { height = viewHeight; } viewHeight = height; slotTopCache = {}; var headHeight = dayBody.position().top; var allDayHeight = slotScroller.position().top; // including divider var bodyHeight = Math.min( // total body height, including borders height - headHeight, // when scrollbars slotTable.height() + allDayHeight + 1 // when no scrollbars. +1 for bottom border ); dayBodyFirstCellStretcher .height(bodyHeight - vsides(dayBodyFirstCell)); slotLayer.css('top', headHeight); slotScroller.height(bodyHeight - allDayHeight - 1); // the stylesheet guarantees that the first row has no border. // this allows .height() to work well cross-browser. var slotHeight0 = slotTable.find('tr:first').height() + 1; // +1 for bottom border var slotHeight1 = slotTable.find('tr:eq(1)').height(); // HACK: i forget why we do this, but i think a cross-browser issue slotHeight = (slotHeight0 + slotHeight1) / 2; snapRatio = slotDuration / snapDuration; snapHeight = slotHeight / snapRatio; } function setWidth(width) { viewWidth = width; colPositions.clear(); colContentPositions.clear(); var axisFirstCells = dayHead.find('th:first'); if (allDayTable) { axisFirstCells = axisFirstCells.add(allDayTable.find('th:first')); } axisFirstCells = axisFirstCells.add(slotTable.find('th:first')); axisWidth = 0; setOuterWidth( axisFirstCells .width('') .each(function(i, _cell) { axisWidth = Math.max(axisWidth, $(_cell).outerWidth()); }), axisWidth ); var gutterCells = dayTable.find('.fc-agenda-gutter'); if (allDayTable) { gutterCells = gutterCells.add(allDayTable.find('th.fc-agenda-gutter')); } var slotTableWidth = slotScroller[0].clientWidth; // needs to be done after axisWidth (for IE7) gutterWidth = slotScroller.width() - slotTableWidth; if (gutterWidth) { setOuterWidth(gutterCells, gutterWidth); gutterCells .show() .prev() .removeClass('fc-last'); }else{ gutterCells .hide() .prev() .addClass('fc-last'); } colWidth = Math.floor((slotTableWidth - axisWidth) / colCnt); setOuterWidth(dayHeadCells.slice(0, -1), colWidth); } /* Scrolling -----------------------------------------------------------------------*/ function resetScroll() { var top = computeTimeTop( moment.duration(opt('scrollTime')) ) + 1; // +1 for the border function scroll() { slotScroller.scrollTop(top); } scroll(); setTimeout(scroll, 0); // overrides any previous scroll state made by the browser } function afterRender() { // after the view has been freshly rendered and sized resetScroll(); } /* Slot/Day clicking and binding -----------------------------------------------------------------------*/ function dayBind(cells) { cells.click(slotClick) .mousedown(daySelectionMousedown); } function slotBind(cells) { cells.click(slotClick) .mousedown(slotSelectionMousedown); } function slotClick(ev) { if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick var col = Math.min(colCnt-1, Math.floor((ev.pageX - dayTable.offset().left - axisWidth) / colWidth)); var date = cellToDate(0, col); var match = this.parentNode.className.match(/fc-slot(\d+)/); // TODO: maybe use data if (match) { var slotIndex = parseInt(match[1]); date.add(minTime + slotIndex * slotDuration); date = calendar.rezoneDate(date); trigger( 'dayClick', dayBodyCells[col], date, ev ); }else{ trigger( 'dayClick', dayBodyCells[col], date, ev ); } } } /* Semi-transparent Overlay Helpers -----------------------------------------------------*/ // TODO: should be consolidated with BasicView's methods function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive if (refreshCoordinateGrid) { coordinateGrid.build(); } var segments = rangeToSegments(overlayStart, overlayEnd); for (var i=0; i<segments.length; i++) { var segment = segments[i]; dayBind( renderCellOverlay( segment.row, segment.leftCol, segment.row, segment.rightCol ) ); } } function renderCellOverlay(row0, col0, row1, col1) { // only for all-day? var rect = coordinateGrid.rect(row0, col0, row1, col1, slotLayer); return renderOverlay(rect, slotLayer); } function renderSlotOverlay(overlayStart, overlayEnd) { // normalize, because dayStart/dayEnd have stripped time+zone overlayStart = overlayStart.clone().stripZone(); overlayEnd = overlayEnd.clone().stripZone(); for (var i=0; i<colCnt; i++) { // loop through the day columns var dayStart = cellToDate(0, i); var dayEnd = dayStart.clone().add('days', 1); var stretchStart = dayStart < overlayStart ? overlayStart : dayStart; // the max of the two var stretchEnd = dayEnd < overlayEnd ? dayEnd : overlayEnd; // the min of the two if (stretchStart < stretchEnd) { var rect = coordinateGrid.rect(0, i, 0, i, slotContainer); // only use it for horizontal coords var top = computeDateTop(stretchStart, dayStart); var bottom = computeDateTop(stretchEnd, dayStart); rect.top = top; rect.height = bottom - top; slotBind( renderOverlay(rect, slotContainer) ); } } } /* Coordinate Utilities -----------------------------------------------------------------------------*/ coordinateGrid = new CoordinateGrid(function(rows, cols) { var e, n, p; dayHeadCells.each(function(i, _e) { e = $(_e); n = e.offset().left; if (i) { p[1] = n; } p = [n]; cols[i] = p; }); p[1] = n + e.outerWidth(); if (opt('allDaySlot')) { e = allDayRow; n = e.offset().top; rows[0] = [n, n+e.outerHeight()]; } var slotTableTop = slotContainer.offset().top; var slotScrollerTop = slotScroller.offset().top; var slotScrollerBottom = slotScrollerTop + slotScroller.outerHeight(); function constrain(n) { return Math.max(slotScrollerTop, Math.min(slotScrollerBottom, n)); } for (var i=0; i<slotCnt*snapRatio; i++) { // adapt slot count to increased/decreased selection slot count rows.push([ constrain(slotTableTop + snapHeight*i), constrain(slotTableTop + snapHeight*(i+1)) ]); } }); hoverListener = new HoverListener(coordinateGrid); colPositions = new HorizontalPositionCache(function(col) { return dayBodyCellInners.eq(col); }); colContentPositions = new HorizontalPositionCache(function(col) { return dayBodyCellContentInners.eq(col); }); function colLeft(col) { return colPositions.left(col); } function colContentLeft(col) { return colContentPositions.left(col); } function colRight(col) { return colPositions.right(col); } function colContentRight(col) { return colContentPositions.right(col); } function getIsCellAllDay(cell) { // TODO: remove because mom.hasTime() from realCellToDate() is better return opt('allDaySlot') && !cell.row; } function realCellToDate(cell) { // ugh "real" ... but blame it on our abuse of the "cell" system var date = cellToDate(0, cell.col); var slotIndex = cell.row; if (opt('allDaySlot')) { slotIndex--; } if (slotIndex >= 0) { date.time(moment.duration(minTime + slotIndex * slotDuration)); date = calendar.rezoneDate(date); } return date; } function computeDateTop(date, startOfDayDate) { return computeTimeTop( moment.duration( date.clone().stripZone() - startOfDayDate.clone().stripTime() ) ); } function computeTimeTop(time) { // time is a duration if (time < minTime) { return 0; } if (time >= maxTime) { return slotTable.height(); } var slots = (time - minTime) / slotDuration; var slotIndex = Math.floor(slots); var slotPartial = slots - slotIndex; var slotTop = slotTopCache[slotIndex]; // find the position of the corresponding <tr> // need to use this tecnhique because not all rows are rendered at same height sometimes. if (slotTop === undefined) { slotTop = slotTopCache[slotIndex] = slotTable.find('tr').eq(slotIndex).find('td div')[0].offsetTop; // .eq() is faster than ":eq()" selector // [0].offsetTop is faster than .position().top (do we really need this optimization?) // a better optimization would be to cache all these divs } var top = slotTop - 1 + // because first row doesn't have a top border slotPartial * slotHeight; // part-way through the row top = Math.max(top, 0); return top; } /* Selection ---------------------------------------------------------------------------------*/ function defaultSelectionEnd(start) { if (start.hasTime()) { return start.clone().add(slotDuration); } else { return start.clone().add('days', 1); } } function renderSelection(start, end) { if (start.hasTime() || end.hasTime()) { renderSlotSelection(start, end); } else if (opt('allDaySlot')) { renderDayOverlay(start, end, true); // true for refreshing coordinate grid } } function renderSlotSelection(startDate, endDate) { var helperOption = opt('selectHelper'); coordinateGrid.build(); if (helperOption) { var col = dateToCell(startDate).col; if (col >= 0 && col < colCnt) { // only works when times are on same day var rect = coordinateGrid.rect(0, col, 0, col, slotContainer); // only for horizontal coords var top = computeDateTop(startDate, startDate); var bottom = computeDateTop(endDate, startDate); if (bottom > top) { // protect against selections that are entirely before or after visible range rect.top = top; rect.height = bottom - top; rect.left += 2; rect.width -= 5; if ($.isFunction(helperOption)) { var helperRes = helperOption(startDate, endDate); if (helperRes) { rect.position = 'absolute'; selectionHelper = $(helperRes) .css(rect) .appendTo(slotContainer); } }else{ rect.isStart = true; // conside rect a "seg" now rect.isEnd = true; // selectionHelper = $(slotSegHtml( { title: '', start: startDate, end: endDate, className: ['fc-select-helper'], editable: false }, rect )); selectionHelper.css('opacity', opt('dragOpacity')); } if (selectionHelper) { slotBind(selectionHelper); slotContainer.append(selectionHelper); setOuterWidth(selectionHelper, rect.width, true); // needs to be after appended setOuterHeight(selectionHelper, rect.height, true); } } } }else{ renderSlotOverlay(startDate, endDate); } } function clearSelection() { clearOverlays(); if (selectionHelper) { selectionHelper.remove(); selectionHelper = null; } } function slotSelectionMousedown(ev) { if (ev.which == 1 && opt('selectable')) { // ev.which==1 means left mouse button unselect(ev); var dates; hoverListener.start(function(cell, origCell) { clearSelection(); if (cell && cell.col == origCell.col && !getIsCellAllDay(cell)) { var d1 = realCellToDate(origCell); var d2 = realCellToDate(cell); dates = [ d1, d1.clone().add(snapDuration), // calculate minutes depending on selection slot minutes d2, d2.clone().add(snapDuration) ].sort(dateCompare); renderSlotSelection(dates[0], dates[3]); }else{ dates = null; } }, ev); $(document).one('mouseup', function(ev) { hoverListener.stop(); if (dates) { if (+dates[0] == +dates[1]) { reportDayClick(dates[0], ev); } reportSelection(dates[0], dates[3], ev); } }); } } function reportDayClick(date, ev) { trigger('dayClick', dayBodyCells[dateToCell(date).col], date, ev); } /* External Dragging --------------------------------------------------------------------------------*/ function dragStart(_dragElement, ev, ui) { hoverListener.start(function(cell) { clearOverlays(); if (cell) { var d1 = realCellToDate(cell); var d2 = d1.clone(); if (d1.hasTime()) { d2.add(calendar.defaultTimedEventDuration); renderSlotOverlay(d1, d2); } else { d2.add(calendar.defaultAllDayEventDuration); renderDayOverlay(d1, d2); } } }, ev); } function dragStop(_dragElement, ev, ui) { var cell = hoverListener.stop(); clearOverlays(); if (cell) { trigger( 'drop', _dragElement, realCellToDate(cell), ev, ui ); } } } ;; function AgendaEventRenderer() { var t = this; // exports t.renderEvents = renderEvents; t.clearEvents = clearEvents; t.slotSegHtml = slotSegHtml; // imports DayEventRenderer.call(t); var opt = t.opt; var trigger = t.trigger; var isEventDraggable = t.isEventDraggable; var isEventResizable = t.isEventResizable; var eventElementHandlers = t.eventElementHandlers; var setHeight = t.setHeight; var getDaySegmentContainer = t.getDaySegmentContainer; var getSlotSegmentContainer = t.getSlotSegmentContainer; var getHoverListener = t.getHoverListener; var computeDateTop = t.computeDateTop; var getIsCellAllDay = t.getIsCellAllDay; var colContentLeft = t.colContentLeft; var colContentRight = t.colContentRight; var cellToDate = t.cellToDate; var getColCnt = t.getColCnt; var getColWidth = t.getColWidth; var getSnapHeight = t.getSnapHeight; var getSnapDuration = t.getSnapDuration; var getSlotHeight = t.getSlotHeight; var getSlotDuration = t.getSlotDuration; var getSlotContainer = t.getSlotContainer; var reportEventElement = t.reportEventElement; var showEvents = t.showEvents; var hideEvents = t.hideEvents; var eventDrop = t.eventDrop; var eventResize = t.eventResize; var renderDayOverlay = t.renderDayOverlay; var clearOverlays = t.clearOverlays; var renderDayEvents = t.renderDayEvents; var getMinTime = t.getMinTime; var getMaxTime = t.getMaxTime; var calendar = t.calendar; var formatDate = calendar.formatDate; var formatRange = calendar.formatRange; var getEventEnd = calendar.getEventEnd; // overrides t.draggableDayEvent = draggableDayEvent; /* Rendering ----------------------------------------------------------------------------*/ function renderEvents(events, modifiedEventId) { var i, len=events.length, dayEvents=[], slotEvents=[]; for (i=0; i<len; i++) { if (events[i].allDay) { dayEvents.push(events[i]); }else{ slotEvents.push(events[i]); } } if (opt('allDaySlot')) { renderDayEvents(dayEvents, modifiedEventId); setHeight(); // no params means set to viewHeight } renderSlotSegs(compileSlotSegs(slotEvents), modifiedEventId); } function clearEvents() { getDaySegmentContainer().empty(); getSlotSegmentContainer().empty(); } function compileSlotSegs(events) { var colCnt = getColCnt(), minTime = getMinTime(), maxTime = getMaxTime(), cellDate, i, j, seg, colSegs, segs = []; for (i=0; i<colCnt; i++) { cellDate = cellToDate(0, i); colSegs = sliceSegs( events, cellDate.clone().time(minTime), cellDate.clone().time(maxTime) ); colSegs = placeSlotSegs(colSegs); // returns a new order for (j=0; j<colSegs.length; j++) { seg = colSegs[j]; seg.col = i; segs.push(seg); } } return segs; } function sliceSegs(events, rangeStart, rangeEnd) { // normalize, because all dates will be compared w/o zones rangeStart = rangeStart.clone().stripZone(); rangeEnd = rangeEnd.clone().stripZone(); var segs = [], i, len=events.length, event, eventStart, eventEnd, segStart, segEnd, isStart, isEnd; for (i=0; i<len; i++) { event = events[i]; // get dates, make copies, then strip zone to normalize eventStart = event.start.clone().stripZone(); eventEnd = getEventEnd(event).stripZone(); if (eventEnd > rangeStart && eventStart < rangeEnd) { if (eventStart < rangeStart) { segStart = rangeStart.clone(); isStart = false; } else { segStart = eventStart; isStart = true; } if (eventEnd > rangeEnd) { segEnd = rangeEnd.clone(); isEnd = false; } else { segEnd = eventEnd; isEnd = true; } segs.push({ event: event, start: segStart, end: segEnd, isStart: isStart, isEnd: isEnd }); } } return segs.sort(compareSlotSegs); } // renders events in the 'time slots' at the bottom // TODO: when we refactor this, when user returns `false` eventRender, don't have empty space // TODO: refactor will include using pixels to detect collisions instead of dates (handy for seg cmp) function renderSlotSegs(segs, modifiedEventId) { var i, segCnt=segs.length, seg, event, top, bottom, columnLeft, columnRight, columnWidth, width, left, right, html = '', eventElements, eventElement, triggerRes, titleElement, height, slotSegmentContainer = getSlotSegmentContainer(), isRTL = opt('isRTL'); // calculate position/dimensions, create html for (i=0; i<segCnt; i++) { seg = segs[i]; event = seg.event; top = computeDateTop(seg.start, seg.start); bottom = computeDateTop(seg.end, seg.start); columnLeft = colContentLeft(seg.col); columnRight = colContentRight(seg.col); columnWidth = columnRight - columnLeft; // shave off space on right near scrollbars (2.5%) // TODO: move this to CSS somehow columnRight -= columnWidth * .025; columnWidth = columnRight - columnLeft; width = columnWidth * (seg.forwardCoord - seg.backwardCoord); if (opt('slotEventOverlap')) { // double the width while making sure resize handle is visible // (assumed to be 20px wide) width = Math.max( (width - (20/2)) * 2, width // narrow columns will want to make the segment smaller than // the natural width. don't allow it ); } if (isRTL) { right = columnRight - seg.backwardCoord * columnWidth; left = right - width; } else { left = columnLeft + seg.backwardCoord * columnWidth; right = left + width; } // make sure horizontal coordinates are in bounds left = Math.max(left, columnLeft); right = Math.min(right, columnRight); width = right - left; seg.top = top; seg.left = left; seg.outerWidth = width; seg.outerHeight = bottom - top; html += slotSegHtml(event, seg); } slotSegmentContainer[0].innerHTML = html; // faster than html() eventElements = slotSegmentContainer.children(); // retrieve elements, run through eventRender callback, bind event handlers for (i=0; i<segCnt; i++) { seg = segs[i]; event = seg.event; eventElement = $(eventElements[i]); // faster than eq() triggerRes = trigger('eventRender', event, event, eventElement); if (triggerRes === false) { eventElement.remove(); }else{ if (triggerRes && triggerRes !== true) { eventElement.remove(); eventElement = $(triggerRes) .css({ position: 'absolute', top: seg.top, left: seg.left }) .appendTo(slotSegmentContainer); } seg.element = eventElement; if (event._id === modifiedEventId) { bindSlotSeg(event, eventElement, seg); }else{ eventElement[0]._fci = i; // for lazySegBind } reportEventElement(event, eventElement); } } lazySegBind(slotSegmentContainer, segs, bindSlotSeg); // record event sides and title positions for (i=0; i<segCnt; i++) { seg = segs[i]; if ((eventElement = seg.element)) { seg.vsides = vsides(eventElement, true); seg.hsides = hsides(eventElement, true); titleElement = eventElement.find('.fc-event-title'); if (titleElement.length) { seg.contentTop = titleElement[0].offsetTop; } } } // set all positions/dimensions at once for (i=0; i<segCnt; i++) { seg = segs[i]; if ((eventElement = seg.element)) { eventElement[0].style.width = Math.max(0, seg.outerWidth - seg.hsides) + 'px'; height = Math.max(0, seg.outerHeight - seg.vsides); eventElement[0].style.height = height + 'px'; event = seg.event; if (seg.contentTop !== undefined && height - seg.contentTop < 10) { // not enough room for title, put it in the time (TODO: maybe make both display:inline instead) eventElement.find('div.fc-event-time') .text( formatDate(event.start, opt('timeFormat')) + ' - ' + event.title ); eventElement.find('div.fc-event-title') .remove(); } trigger('eventAfterRender', event, event, eventElement); } } } function slotSegHtml(event, seg) { var html = "<"; var url = event.url; var skinCss = getSkinCss(event, opt); var classes = ['fc-event', 'fc-event-vert']; if (isEventDraggable(event)) { classes.push('fc-event-draggable'); } if (seg.isStart) { classes.push('fc-event-start'); } if (seg.isEnd) { classes.push('fc-event-end'); } classes = classes.concat(event.className); if (event.source) { classes = classes.concat(event.source.className || []); } if (url) { html += "a href='" + htmlEscape(event.url) + "'"; }else{ html += "div"; } html += " class='" + classes.join(' ') + "'" + " style=" + "'" + "position:absolute;" + "top:" + seg.top + "px;" + "left:" + seg.left + "px;" + skinCss + "'" + ">" + "<div class='fc-event-inner'>" + "<div class='fc-event-time'>"; if (event.end) { html += htmlEscape(formatRange(event.start, event.end, opt('timeFormat'))); }else{ html += htmlEscape(formatDate(event.start, opt('timeFormat'))); } html += "</div>" + "<div class='fc-event-title'>" + htmlEscape(event.title || '') + "</div>" + "</div>" + "<div class='fc-event-bg'></div>"; if (seg.isEnd && isEventResizable(event)) { html += "<div class='ui-resizable-handle ui-resizable-s'>=</div>"; } html += "</" + (url ? "a" : "div") + ">"; return html; } function bindSlotSeg(event, eventElement, seg) { var timeElement = eventElement.find('div.fc-event-time'); if (isEventDraggable(event)) { draggableSlotEvent(event, eventElement, timeElement); } if (seg.isEnd && isEventResizable(event)) { resizableSlotEvent(event, eventElement, timeElement); } eventElementHandlers(event, eventElement); } /* Dragging -----------------------------------------------------------------------------------*/ // when event starts out FULL-DAY // overrides DayEventRenderer's version because it needs to account for dragging elements // to and from the slot area. function draggableDayEvent(event, eventElement, seg) { var isStart = seg.isStart; var origWidth; var revert; var allDay = true; var dayDelta; var hoverListener = getHoverListener(); var colWidth = getColWidth(); var minTime = getMinTime(); var slotDuration = getSlotDuration(); var slotHeight = getSlotHeight(); var snapDuration = getSnapDuration(); var snapHeight = getSnapHeight(); eventElement.draggable({ opacity: opt('dragOpacity', 'month'), // use whatever the month view was using revertDuration: opt('dragRevertDuration'), start: function(ev, ui) { trigger('eventDragStart', eventElement, event, ev, ui); hideEvents(event, eventElement); origWidth = eventElement.width(); hoverListener.start(function(cell, origCell) { clearOverlays(); if (cell) { revert = false; var origDate = cellToDate(0, origCell.col); var date = cellToDate(0, cell.col); dayDelta = date.diff(origDate, 'days'); if (!cell.row) { // on full-days renderDayOverlay( event.start.clone().add('days', dayDelta), getEventEnd(event).add('days', dayDelta) ); resetElement(); } else { // mouse is over bottom slots if (isStart) { if (allDay) { // convert event to temporary slot-event eventElement.width(colWidth - 10); // don't use entire width setOuterHeight(eventElement, calendar.defaultTimedEventDuration / slotDuration * slotHeight); // the default height eventElement.draggable('option', 'grid', [ colWidth, 1 ]); allDay = false; } } else { revert = true; } } revert = revert || (allDay && !dayDelta); } else { resetElement(); revert = true; } eventElement.draggable('option', 'revert', revert); }, ev, 'drag'); }, stop: function(ev, ui) { hoverListener.stop(); clearOverlays(); trigger('eventDragStop', eventElement, event, ev, ui); if (revert) { // hasn't moved or is out of bounds (draggable has already reverted) resetElement(); eventElement.css('filter', ''); // clear IE opacity side-effects showEvents(event, eventElement); } else { // changed! var eventStart = event.start.clone().add('days', dayDelta); // already assumed to have a stripped time var snapTime; var snapIndex; if (!allDay) { snapIndex = Math.round((eventElement.offset().top - getSlotContainer().offset().top) / snapHeight); // why not use ui.offset.top? snapTime = moment.duration(minTime + snapIndex * snapDuration); eventStart = calendar.rezoneDate(eventStart.clone().time(snapTime)); } eventDrop( this, // el event, eventStart, ev, ui ); } } }); function resetElement() { if (!allDay) { eventElement .width(origWidth) .height('') .draggable('option', 'grid', null); allDay = true; } } } // when event starts out IN TIMESLOTS function draggableSlotEvent(event, eventElement, timeElement) { var coordinateGrid = t.getCoordinateGrid(); var colCnt = getColCnt(); var colWidth = getColWidth(); var snapHeight = getSnapHeight(); var snapDuration = getSnapDuration(); // states var origPosition; // original position of the element, not the mouse var origCell; var isInBounds, prevIsInBounds; var isAllDay, prevIsAllDay; var colDelta, prevColDelta; var dayDelta; // derived from colDelta var snapDelta, prevSnapDelta; // the number of snaps away from the original position // newly computed var eventStart, eventEnd; eventElement.draggable({ scroll: false, grid: [ colWidth, snapHeight ], axis: colCnt==1 ? 'y' : false, opacity: opt('dragOpacity'), revertDuration: opt('dragRevertDuration'), start: function(ev, ui) { trigger('eventDragStart', eventElement, event, ev, ui); hideEvents(event, eventElement); coordinateGrid.build(); // initialize states origPosition = eventElement.position(); origCell = coordinateGrid.cell(ev.pageX, ev.pageY); isInBounds = prevIsInBounds = true; isAllDay = prevIsAllDay = getIsCellAllDay(origCell); colDelta = prevColDelta = 0; dayDelta = 0; snapDelta = prevSnapDelta = 0; eventStart = null; eventEnd = null; }, drag: function(ev, ui) { // NOTE: this `cell` value is only useful for determining in-bounds and all-day. // Bad for anything else due to the discrepancy between the mouse position and the // element position while snapping. (problem revealed in PR #55) // // PS- the problem exists for draggableDayEvent() when dragging an all-day event to a slot event. // We should overhaul the dragging system and stop relying on jQuery UI. var cell = coordinateGrid.cell(ev.pageX, ev.pageY); // update states isInBounds = !!cell; if (isInBounds) { isAllDay = getIsCellAllDay(cell); // calculate column delta colDelta = Math.round((ui.position.left - origPosition.left) / colWidth); if (colDelta != prevColDelta) { // calculate the day delta based off of the original clicked column and the column delta var origDate = cellToDate(0, origCell.col); var col = origCell.col + colDelta; col = Math.max(0, col); col = Math.min(colCnt-1, col); var date = cellToDate(0, col); dayDelta = date.diff(origDate, 'days'); } // calculate minute delta (only if over slots) if (!isAllDay) { snapDelta = Math.round((ui.position.top - origPosition.top) / snapHeight); } } // any state changes? if ( isInBounds != prevIsInBounds || isAllDay != prevIsAllDay || colDelta != prevColDelta || snapDelta != prevSnapDelta ) { // compute new dates if (isAllDay) { eventStart = event.start.clone().stripTime().add('days', dayDelta); eventEnd = eventStart.clone().add(calendar.defaultAllDayEventDuration); } else { eventStart = event.start.clone().add(snapDelta * snapDuration).add('days', dayDelta); eventEnd = getEventEnd(event).add(snapDelta * snapDuration).add('days', dayDelta); } updateUI(); // update previous states for next time prevIsInBounds = isInBounds; prevIsAllDay = isAllDay; prevColDelta = colDelta; prevSnapDelta = snapDelta; } // if out-of-bounds, revert when done, and vice versa. eventElement.draggable('option', 'revert', !isInBounds); }, stop: function(ev, ui) { clearOverlays(); trigger('eventDragStop', eventElement, event, ev, ui); if (isInBounds && (isAllDay || dayDelta || snapDelta)) { // changed! eventDrop( this, // el event, eventStart, ev, ui ); } else { // either no change or out-of-bounds (draggable has already reverted) // reset states for next time, and for updateUI() isInBounds = true; isAllDay = false; colDelta = 0; dayDelta = 0; snapDelta = 0; updateUI(); eventElement.css('filter', ''); // clear IE opacity side-effects // sometimes fast drags make event revert to wrong position, so reset. // also, if we dragged the element out of the area because of snapping, // but the *mouse* is still in bounds, we need to reset the position. eventElement.css(origPosition); showEvents(event, eventElement); } } }); function updateUI() { clearOverlays(); if (isInBounds) { if (isAllDay) { timeElement.hide(); eventElement.draggable('option', 'grid', null); // disable grid snapping renderDayOverlay(eventStart, eventEnd); } else { updateTimeText(); timeElement.css('display', ''); // show() was causing display=inline eventElement.draggable('option', 'grid', [colWidth, snapHeight]); // re-enable grid snapping } } } function updateTimeText() { var text; if (eventStart) { // must of had a state change if (event.end) { text = formatRange(eventStart, eventEnd, opt('timeFormat')); } else { text = formatDate(eventStart, opt('timeFormat')); } timeElement.text(text); } } } /* Resizing --------------------------------------------------------------------------------------*/ function resizableSlotEvent(event, eventElement, timeElement) { var snapDelta, prevSnapDelta; var snapHeight = getSnapHeight(); var snapDuration = getSnapDuration(); var eventEnd; eventElement.resizable({ handles: { s: '.ui-resizable-handle' }, grid: snapHeight, start: function(ev, ui) { snapDelta = prevSnapDelta = 0; hideEvents(event, eventElement); trigger('eventResizeStart', this, event, ev, ui); }, resize: function(ev, ui) { // don't rely on ui.size.height, doesn't take grid into account snapDelta = Math.round((Math.max(snapHeight, eventElement.height()) - ui.originalSize.height) / snapHeight); if (snapDelta != prevSnapDelta) { eventEnd = getEventEnd(event).add(snapDuration * snapDelta); var text; if (snapDelta || event.end) { text = formatRange( event.start, eventEnd, opt('timeFormat') ); } else { text = formatDate(event.start, opt('timeFormat')); } timeElement.text(text); prevSnapDelta = snapDelta; } }, stop: function(ev, ui) { trigger('eventResizeStop', this, event, ev, ui); if (snapDelta) { eventResize( this, event, eventEnd, ev, ui ); } else { showEvents(event, eventElement); // BUG: if event was really short, need to put title back in span } } }); } } /* Agenda Event Segment Utilities -----------------------------------------------------------------------------*/ // Sets the seg.backwardCoord and seg.forwardCoord on each segment and returns a new // list in the order they should be placed into the DOM (an implicit z-index). function placeSlotSegs(segs) { var levels = buildSlotSegLevels(segs); var level0 = levels[0]; var i; computeForwardSlotSegs(levels); if (level0) { for (i=0; i<level0.length; i++) { computeSlotSegPressures(level0[i]); } for (i=0; i<level0.length; i++) { computeSlotSegCoords(level0[i], 0, 0); } } return flattenSlotSegLevels(levels); } // Builds an array of segments "levels". The first level will be the leftmost tier of segments // if the calendar is left-to-right, or the rightmost if the calendar is right-to-left. function buildSlotSegLevels(segs) { var levels = []; var i, seg; var j; for (i=0; i<segs.length; i++) { seg = segs[i]; // go through all the levels and stop on the first level where there are no collisions for (j=0; j<levels.length; j++) { if (!computeSlotSegCollisions(seg, levels[j]).length) { break; } } (levels[j] || (levels[j] = [])).push(seg); } return levels; } // For every segment, figure out the other segments that are in subsequent // levels that also occupy the same vertical space. Accumulate in seg.forwardSegs function computeForwardSlotSegs(levels) { var i, level; var j, seg; var k; for (i=0; i<levels.length; i++) { level = levels[i]; for (j=0; j<level.length; j++) { seg = level[j]; seg.forwardSegs = []; for (k=i+1; k<levels.length; k++) { computeSlotSegCollisions(seg, levels[k], seg.forwardSegs); } } } } // Figure out which path forward (via seg.forwardSegs) results in the longest path until // the furthest edge is reached. The number of segments in this path will be seg.forwardPressure function computeSlotSegPressures(seg) { var forwardSegs = seg.forwardSegs; var forwardPressure = 0; var i, forwardSeg; if (seg.forwardPressure === undefined) { // not already computed for (i=0; i<forwardSegs.length; i++) { forwardSeg = forwardSegs[i]; // figure out the child's maximum forward path computeSlotSegPressures(forwardSeg); // either use the existing maximum, or use the child's forward pressure // plus one (for the forwardSeg itself) forwardPressure = Math.max( forwardPressure, 1 + forwardSeg.forwardPressure ); } seg.forwardPressure = forwardPressure; } } // Calculate seg.forwardCoord and seg.backwardCoord for the segment, where both values range // from 0 to 1. If the calendar is left-to-right, the seg.backwardCoord maps to "left" and // seg.forwardCoord maps to "right" (via percentage). Vice-versa if the calendar is right-to-left. // // The segment might be part of a "series", which means consecutive segments with the same pressure // who's width is unknown until an edge has been hit. `seriesBackwardPressure` is the number of // segments behind this one in the current series, and `seriesBackwardCoord` is the starting // coordinate of the first segment in the series. function computeSlotSegCoords(seg, seriesBackwardPressure, seriesBackwardCoord) { var forwardSegs = seg.forwardSegs; var i; if (seg.forwardCoord === undefined) { // not already computed if (!forwardSegs.length) { // if there are no forward segments, this segment should butt up against the edge seg.forwardCoord = 1; } else { // sort highest pressure first forwardSegs.sort(compareForwardSlotSegs); // this segment's forwardCoord will be calculated from the backwardCoord of the // highest-pressure forward segment. computeSlotSegCoords(forwardSegs[0], seriesBackwardPressure + 1, seriesBackwardCoord); seg.forwardCoord = forwardSegs[0].backwardCoord; } // calculate the backwardCoord from the forwardCoord. consider the series seg.backwardCoord = seg.forwardCoord - (seg.forwardCoord - seriesBackwardCoord) / // available width for series (seriesBackwardPressure + 1); // # of segments in the series // use this segment's coordinates to computed the coordinates of the less-pressurized // forward segments for (i=0; i<forwardSegs.length; i++) { computeSlotSegCoords(forwardSegs[i], 0, seg.forwardCoord); } } } // Outputs a flat array of segments, from lowest to highest level function flattenSlotSegLevels(levels) { var segs = []; var i, level; var j; for (i=0; i<levels.length; i++) { level = levels[i]; for (j=0; j<level.length; j++) { segs.push(level[j]); } } return segs; } // Find all the segments in `otherSegs` that vertically collide with `seg`. // Append into an optionally-supplied `results` array and return. function computeSlotSegCollisions(seg, otherSegs, results) { results = results || []; for (var i=0; i<otherSegs.length; i++) { if (isSlotSegCollision(seg, otherSegs[i])) { results.push(otherSegs[i]); } } return results; } // Do these segments occupy the same vertical space? function isSlotSegCollision(seg1, seg2) { return seg1.end > seg2.start && seg1.start < seg2.end; } // A cmp function for determining which forward segment to rely on more when computing coordinates. function compareForwardSlotSegs(seg1, seg2) { // put higher-pressure first return seg2.forwardPressure - seg1.forwardPressure || // put segments that are closer to initial edge first (and favor ones with no coords yet) (seg1.backwardCoord || 0) - (seg2.backwardCoord || 0) || // do normal sorting... compareSlotSegs(seg1, seg2); } // A cmp function for determining which segment should be closer to the initial edge // (the left edge on a left-to-right calendar). function compareSlotSegs(seg1, seg2) { return seg1.start - seg2.start || // earlier start time goes first (seg2.end - seg2.start) - (seg1.end - seg1.start) || // tie? longer-duration goes first (seg1.event.title || '').localeCompare(seg2.event.title); // tie? alphabetically by title } ;; function View(element, calendar, viewName) { var t = this; // exports t.element = element; t.calendar = calendar; t.name = viewName; t.opt = opt; t.trigger = trigger; t.isEventDraggable = isEventDraggable; t.isEventResizable = isEventResizable; t.clearEventData = clearEventData; t.reportEventElement = reportEventElement; t.triggerEventDestroy = triggerEventDestroy; t.eventElementHandlers = eventElementHandlers; t.showEvents = showEvents; t.hideEvents = hideEvents; t.eventDrop = eventDrop; t.eventResize = eventResize; // t.start, t.end // moments with ambiguous-time // t.intervalStart, t.intervalEnd // moments with ambiguous-time // imports var reportEventChange = calendar.reportEventChange; // locals var eventElementsByID = {}; // eventID mapped to array of jQuery elements var eventElementCouples = []; // array of objects, { event, element } // TODO: unify with segment system var options = calendar.options; var nextDayThreshold = moment.duration(options.nextDayThreshold); function opt(name, viewNameOverride) { var v = options[name]; if ($.isPlainObject(v) && !isForcedAtomicOption(name)) { return smartProperty(v, viewNameOverride || viewName); } return v; } function trigger(name, thisObj) { return calendar.trigger.apply( calendar, [name, thisObj || t].concat(Array.prototype.slice.call(arguments, 2), [t]) ); } /* Event Editable Boolean Calculations ------------------------------------------------------------------------------*/ function isEventDraggable(event) { var source = event.source || {}; return firstDefined( event.startEditable, source.startEditable, opt('eventStartEditable'), event.editable, source.editable, opt('editable') ); } function isEventResizable(event) { // but also need to make sure the seg.isEnd == true var source = event.source || {}; return firstDefined( event.durationEditable, source.durationEditable, opt('eventDurationEditable'), event.editable, source.editable, opt('editable') ); } /* Event Data ------------------------------------------------------------------------------*/ function clearEventData() { eventElementsByID = {}; eventElementCouples = []; } /* Event Elements ------------------------------------------------------------------------------*/ // report when view creates an element for an event function reportEventElement(event, element) { eventElementCouples.push({ event: event, element: element }); if (eventElementsByID[event._id]) { eventElementsByID[event._id].push(element); }else{ eventElementsByID[event._id] = [element]; } } function triggerEventDestroy() { $.each(eventElementCouples, function(i, couple) { t.trigger('eventDestroy', couple.event, couple.event, couple.element); }); } // attaches eventClick, eventMouseover, eventMouseout function eventElementHandlers(event, eventElement) { eventElement .click(function(ev) { if (!eventElement.hasClass('ui-draggable-dragging') && !eventElement.hasClass('ui-resizable-resizing')) { return trigger('eventClick', this, event, ev); } }) .hover( function(ev) { trigger('eventMouseover', this, event, ev); }, function(ev) { trigger('eventMouseout', this, event, ev); } ); // TODO: don't fire eventMouseover/eventMouseout *while* dragging is occuring (on subject element) // TODO: same for resizing } function showEvents(event, exceptElement) { eachEventElement(event, exceptElement, 'show'); } function hideEvents(event, exceptElement) { eachEventElement(event, exceptElement, 'hide'); } function eachEventElement(event, exceptElement, funcName) { // NOTE: there may be multiple events per ID (repeating events) // and multiple segments per event var elements = eventElementsByID[event._id], i, len = elements.length; for (i=0; i<len; i++) { if (!exceptElement || elements[i][0] != exceptElement[0]) { elements[i][funcName](); } } } /* Event Modification Reporting ---------------------------------------------------------------------------------*/ function eventDrop(el, event, newStart, ev, ui) { var undoMutation = calendar.mutateEvent(event, newStart, null); trigger( 'eventDrop', el, event, function() { undoMutation(); reportEventChange(event._id); }, ev, ui ); reportEventChange(event._id); } function eventResize(el, event, newEnd, ev, ui) { var undoMutation = calendar.mutateEvent(event, null, newEnd); trigger( 'eventResize', el, event, function() { undoMutation(); reportEventChange(event._id); }, ev, ui ); reportEventChange(event._id); } // ==================================================================================================== // Utilities for day "cells" // ==================================================================================================== // The "basic" views are completely made up of day cells. // The "agenda" views have day cells at the top "all day" slot. // This was the obvious common place to put these utilities, but they should be abstracted out into // a more meaningful class (like DayEventRenderer). // ==================================================================================================== // For determining how a given "cell" translates into a "date": // // 1. Convert the "cell" (row and column) into a "cell offset" (the # of the cell, cronologically from the first). // Keep in mind that column indices are inverted with isRTL. This is taken into account. // // 2. Convert the "cell offset" to a "day offset" (the # of days since the first visible day in the view). // // 3. Convert the "day offset" into a "date" (a Moment). // // The reverse transformation happens when transforming a date into a cell. // exports t.isHiddenDay = isHiddenDay; t.skipHiddenDays = skipHiddenDays; t.getCellsPerWeek = getCellsPerWeek; t.dateToCell = dateToCell; t.dateToDayOffset = dateToDayOffset; t.dayOffsetToCellOffset = dayOffsetToCellOffset; t.cellOffsetToCell = cellOffsetToCell; t.cellToDate = cellToDate; t.cellToCellOffset = cellToCellOffset; t.cellOffsetToDayOffset = cellOffsetToDayOffset; t.dayOffsetToDate = dayOffsetToDate; t.rangeToSegments = rangeToSegments; // internals var hiddenDays = opt('hiddenDays') || []; // array of day-of-week indices that are hidden var isHiddenDayHash = []; // is the day-of-week hidden? (hash with day-of-week-index -> bool) var cellsPerWeek; var dayToCellMap = []; // hash from dayIndex -> cellIndex, for one week var cellToDayMap = []; // hash from cellIndex -> dayIndex, for one week var isRTL = opt('isRTL'); // initialize important internal variables (function() { if (opt('weekends') === false) { hiddenDays.push(0, 6); // 0=sunday, 6=saturday } // Loop through a hypothetical week and determine which // days-of-week are hidden. Record in both hashes (one is the reverse of the other). for (var dayIndex=0, cellIndex=0; dayIndex<7; dayIndex++) { dayToCellMap[dayIndex] = cellIndex; isHiddenDayHash[dayIndex] = $.inArray(dayIndex, hiddenDays) != -1; if (!isHiddenDayHash[dayIndex]) { cellToDayMap[cellIndex] = dayIndex; cellIndex++; } } cellsPerWeek = cellIndex; if (!cellsPerWeek) { throw 'invalid hiddenDays'; // all days were hidden? bad. } })(); // Is the current day hidden? // `day` is a day-of-week index (0-6), or a Moment function isHiddenDay(day) { if (moment.isMoment(day)) { day = day.day(); } return isHiddenDayHash[day]; } function getCellsPerWeek() { return cellsPerWeek; } // Incrementing the current day until it is no longer a hidden day, returning a copy. // If the initial value of `date` is not a hidden day, don't do anything. // Pass `isExclusive` as `true` if you are dealing with an end date. // `inc` defaults to `1` (increment one day forward each time) function skipHiddenDays(date, inc, isExclusive) { var out = date.clone(); inc = inc || 1; while ( isHiddenDayHash[(out.day() + (isExclusive ? inc : 0) + 7) % 7] ) { out.add('days', inc); } return out; } // // TRANSFORMATIONS: cell -> cell offset -> day offset -> date // // cell -> date (combines all transformations) // Possible arguments: // - row, col // - { row:#, col: # } function cellToDate() { var cellOffset = cellToCellOffset.apply(null, arguments); var dayOffset = cellOffsetToDayOffset(cellOffset); var date = dayOffsetToDate(dayOffset); return date; } // cell -> cell offset // Possible arguments: // - row, col // - { row:#, col:# } function cellToCellOffset(row, col) { var colCnt = t.getColCnt(); // rtl variables. wish we could pre-populate these. but where? var dis = isRTL ? -1 : 1; var dit = isRTL ? colCnt - 1 : 0; if (typeof row == 'object') { col = row.col; row = row.row; } var cellOffset = row * colCnt + (col * dis + dit); // column, adjusted for RTL (dis & dit) return cellOffset; } // cell offset -> day offset function cellOffsetToDayOffset(cellOffset) { var day0 = t.start.day(); // first date's day of week cellOffset += dayToCellMap[day0]; // normlize cellOffset to beginning-of-week return Math.floor(cellOffset / cellsPerWeek) * 7 + // # of days from full weeks cellToDayMap[ // # of days from partial last week (cellOffset % cellsPerWeek + cellsPerWeek) % cellsPerWeek // crazy math to handle negative cellOffsets ] - day0; // adjustment for beginning-of-week normalization } // day offset -> date function dayOffsetToDate(dayOffset) { return t.start.clone().add('days', dayOffset); } // // TRANSFORMATIONS: date -> day offset -> cell offset -> cell // // date -> cell (combines all transformations) function dateToCell(date) { var dayOffset = dateToDayOffset(date); var cellOffset = dayOffsetToCellOffset(dayOffset); var cell = cellOffsetToCell(cellOffset); return cell; } // date -> day offset function dateToDayOffset(date) { return date.clone().stripTime().diff(t.start, 'days'); } // day offset -> cell offset function dayOffsetToCellOffset(dayOffset) { var day0 = t.start.day(); // first date's day of week dayOffset += day0; // normalize dayOffset to beginning-of-week return Math.floor(dayOffset / 7) * cellsPerWeek + // # of cells from full weeks dayToCellMap[ // # of cells from partial last week (dayOffset % 7 + 7) % 7 // crazy math to handle negative dayOffsets ] - dayToCellMap[day0]; // adjustment for beginning-of-week normalization } // cell offset -> cell (object with row & col keys) function cellOffsetToCell(cellOffset) { var colCnt = t.getColCnt(); // rtl variables. wish we could pre-populate these. but where? var dis = isRTL ? -1 : 1; var dit = isRTL ? colCnt - 1 : 0; var row = Math.floor(cellOffset / colCnt); var col = ((cellOffset % colCnt + colCnt) % colCnt) * dis + dit; // column, adjusted for RTL (dis & dit) return { row: row, col: col }; } // // Converts a date range into an array of segment objects. // "Segments" are horizontal stretches of time, sliced up by row. // A segment object has the following properties: // - row // - cols // - isStart // - isEnd // function rangeToSegments(start, end) { var rowCnt = t.getRowCnt(); var colCnt = t.getColCnt(); var segments = []; // array of segments to return // day offset for given date range var rangeDayOffsetStart = dateToDayOffset(start); var rangeDayOffsetEnd = dateToDayOffset(end); // an exclusive value var endTimeMS = +end.time(); if (endTimeMS && endTimeMS >= nextDayThreshold) { rangeDayOffsetEnd++; } rangeDayOffsetEnd = Math.max(rangeDayOffsetEnd, rangeDayOffsetStart + 1); // first and last cell offset for the given date range // "last" implies inclusivity var rangeCellOffsetFirst = dayOffsetToCellOffset(rangeDayOffsetStart); var rangeCellOffsetLast = dayOffsetToCellOffset(rangeDayOffsetEnd) - 1; // loop through all the rows in the view for (var row=0; row<rowCnt; row++) { // first and last cell offset for the row var rowCellOffsetFirst = row * colCnt; var rowCellOffsetLast = rowCellOffsetFirst + colCnt - 1; // get the segment's cell offsets by constraining the range's cell offsets to the bounds of the row var segmentCellOffsetFirst = Math.max(rangeCellOffsetFirst, rowCellOffsetFirst); var segmentCellOffsetLast = Math.min(rangeCellOffsetLast, rowCellOffsetLast); // make sure segment's offsets are valid and in view if (segmentCellOffsetFirst <= segmentCellOffsetLast) { // translate to cells var segmentCellFirst = cellOffsetToCell(segmentCellOffsetFirst); var segmentCellLast = cellOffsetToCell(segmentCellOffsetLast); // view might be RTL, so order by leftmost column var cols = [ segmentCellFirst.col, segmentCellLast.col ].sort(); // Determine if segment's first/last cell is the beginning/end of the date range. // We need to compare "day offset" because "cell offsets" are often ambiguous and // can translate to multiple days, and an edge case reveals itself when we the // range's first cell is hidden (we don't want isStart to be true). var isStart = cellOffsetToDayOffset(segmentCellOffsetFirst) == rangeDayOffsetStart; var isEnd = cellOffsetToDayOffset(segmentCellOffsetLast) + 1 == rangeDayOffsetEnd; // +1 for comparing exclusively segments.push({ row: row, leftCol: cols[0], rightCol: cols[1], isStart: isStart, isEnd: isEnd }); } } return segments; } } ;; function DayEventRenderer() { var t = this; // exports t.renderDayEvents = renderDayEvents; t.draggableDayEvent = draggableDayEvent; // made public so that subclasses can override t.resizableDayEvent = resizableDayEvent; // " // imports var opt = t.opt; var trigger = t.trigger; var isEventDraggable = t.isEventDraggable; var isEventResizable = t.isEventResizable; var reportEventElement = t.reportEventElement; var eventElementHandlers = t.eventElementHandlers; var showEvents = t.showEvents; var hideEvents = t.hideEvents; var eventDrop = t.eventDrop; var eventResize = t.eventResize; var getRowCnt = t.getRowCnt; var getColCnt = t.getColCnt; var allDayRow = t.allDayRow; // TODO: rename var colLeft = t.colLeft; var colRight = t.colRight; var colContentLeft = t.colContentLeft; var colContentRight = t.colContentRight; var getDaySegmentContainer = t.getDaySegmentContainer; var renderDayOverlay = t.renderDayOverlay; var clearOverlays = t.clearOverlays; var clearSelection = t.clearSelection; var getHoverListener = t.getHoverListener; var rangeToSegments = t.rangeToSegments; var cellToDate = t.cellToDate; var cellToCellOffset = t.cellToCellOffset; var cellOffsetToDayOffset = t.cellOffsetToDayOffset; var dateToDayOffset = t.dateToDayOffset; var dayOffsetToCellOffset = t.dayOffsetToCellOffset; var calendar = t.calendar; var getEventEnd = calendar.getEventEnd; var formatDate = calendar.formatDate; // Render `events` onto the calendar, attach mouse event handlers, and call the `eventAfterRender` callback for each. // Mouse event will be lazily applied, except if the event has an ID of `modifiedEventId`. // Can only be called when the event container is empty (because it wipes out all innerHTML). function renderDayEvents(events, modifiedEventId) { // do the actual rendering. Receive the intermediate "segment" data structures. var segments = _renderDayEvents( events, false, // don't append event elements true // set the heights of the rows ); // report the elements to the View, for general drag/resize utilities segmentElementEach(segments, function(segment, element) { reportEventElement(segment.event, element); }); // attach mouse handlers attachHandlers(segments, modifiedEventId); // call `eventAfterRender` callback for each event segmentElementEach(segments, function(segment, element) { trigger('eventAfterRender', segment.event, segment.event, element); }); } // Render an event on the calendar, but don't report them anywhere, and don't attach mouse handlers. // Append this event element to the event container, which might already be populated with events. // If an event's segment will have row equal to `adjustRow`, then explicitly set its top coordinate to `adjustTop`. // This hack is used to maintain continuity when user is manually resizing an event. // Returns an array of DOM elements for the event. function renderTempDayEvent(event, adjustRow, adjustTop) { // actually render the event. `true` for appending element to container. // Recieve the intermediate "segment" data structures. var segments = _renderDayEvents( [ event ], true, // append event elements false // don't set the heights of the rows ); var elements = []; // Adjust certain elements' top coordinates segmentElementEach(segments, function(segment, element) { if (segment.row === adjustRow) { element.css('top', adjustTop); } elements.push(element[0]); // accumulate DOM nodes }); return elements; } // Render events onto the calendar. Only responsible for the VISUAL aspect. // Not responsible for attaching handlers or calling callbacks. // Set `doAppend` to `true` for rendering elements without clearing the existing container. // Set `doRowHeights` to allow setting the height of each row, to compensate for vertical event overflow. function _renderDayEvents(events, doAppend, doRowHeights) { // where the DOM nodes will eventually end up var finalContainer = getDaySegmentContainer(); // the container where the initial HTML will be rendered. // If `doAppend`==true, uses a temporary container. var renderContainer = doAppend ? $("<div/>") : finalContainer; var segments = buildSegments(events); var html; var elements; // calculate the desired `left` and `width` properties on each segment object calculateHorizontals(segments); // build the HTML string. relies on `left` property html = buildHTML(segments); // render the HTML. innerHTML is considerably faster than jQuery's .html() renderContainer[0].innerHTML = html; // retrieve the individual elements elements = renderContainer.children(); // if we were appending, and thus using a temporary container, // re-attach elements to the real container. if (doAppend) { finalContainer.append(elements); } // assigns each element to `segment.event`, after filtering them through user callbacks resolveElements(segments, elements); // Calculate the left and right padding+margin for each element. // We need this for setting each element's desired outer width, because of the W3C box model. // It's important we do this in a separate pass from acually setting the width on the DOM elements // because alternating reading/writing dimensions causes reflow for every iteration. segmentElementEach(segments, function(segment, element) { segment.hsides = hsides(element, true); // include margins = `true` }); // Set the width of each element segmentElementEach(segments, function(segment, element) { element.width( Math.max(0, segment.outerWidth - segment.hsides) ); }); // Grab each element's outerHeight (setVerticals uses this). // To get an accurate reading, it's important to have each element's width explicitly set already. segmentElementEach(segments, function(segment, element) { segment.outerHeight = element.outerHeight(true); // include margins = `true` }); // Set the top coordinate on each element (requires segment.outerHeight) setVerticals(segments, doRowHeights); return segments; } // Generate an array of "segments" for all events. function buildSegments(events) { var segments = []; for (var i=0; i<events.length; i++) { var eventSegments = buildSegmentsForEvent(events[i]); segments.push.apply(segments, eventSegments); // append an array to an array } return segments; } // Generate an array of segments for a single event. // A "segment" is the same data structure that View.rangeToSegments produces, // with the addition of the `event` property being set to reference the original event. function buildSegmentsForEvent(event) { var segments = rangeToSegments(event.start, getEventEnd(event)); for (var i=0; i<segments.length; i++) { segments[i].event = event; } return segments; } // Sets the `left` and `outerWidth` property of each segment. // These values are the desired dimensions for the eventual DOM elements. function calculateHorizontals(segments) { var isRTL = opt('isRTL'); for (var i=0; i<segments.length; i++) { var segment = segments[i]; // Determine functions used for calulating the elements left/right coordinates, // depending on whether the view is RTL or not. // NOTE: // colLeft/colRight returns the coordinate butting up the edge of the cell. // colContentLeft/colContentRight is indented a little bit from the edge. var leftFunc = (isRTL ? segment.isEnd : segment.isStart) ? colContentLeft : colLeft; var rightFunc = (isRTL ? segment.isStart : segment.isEnd) ? colContentRight : colRight; var left = leftFunc(segment.leftCol); var right = rightFunc(segment.rightCol); segment.left = left; segment.outerWidth = right - left; } } // Build a concatenated HTML string for an array of segments function buildHTML(segments) { var html = ''; for (var i=0; i<segments.length; i++) { html += buildHTMLForSegment(segments[i]); } return html; } // Build an HTML string for a single segment. // Relies on the following properties: // - `segment.event` (from `buildSegmentsForEvent`) // - `segment.left` (from `calculateHorizontals`) function buildHTMLForSegment(segment) { var html = ''; var isRTL = opt('isRTL'); var event = segment.event; var url = event.url; // generate the list of CSS classNames var classNames = [ 'fc-event', 'fc-event-hori' ]; if (isEventDraggable(event)) { classNames.push('fc-event-draggable'); } if (segment.isStart) { classNames.push('fc-event-start'); } if (segment.isEnd) { classNames.push('fc-event-end'); } // use the event's configured classNames // guaranteed to be an array via `buildEvent` classNames = classNames.concat(event.className); if (event.source) { // use the event's source's classNames, if specified classNames = classNames.concat(event.source.className || []); } // generate a semicolon delimited CSS string for any of the "skin" properties // of the event object (`backgroundColor`, `borderColor` and such) var skinCss = getSkinCss(event, opt); if (url) { html += "<a href='" + htmlEscape(url) + "'"; }else{ html += "<div"; } html += " class='" + classNames.join(' ') + "'" + " style=" + "'" + "position:absolute;" + "left:" + segment.left + "px;" + skinCss + "'" + ">" + "<div class='fc-event-inner'>"; if (!event.allDay && segment.isStart) { html += "<span class='fc-event-time'>" + htmlEscape( formatDate(event.start, opt('timeFormat')) ) + "</span>"; } html += "<span class='fc-event-title'>" + htmlEscape(event.title || '') + "</span>" + "</div>"; if (event.allDay && segment.isEnd && isEventResizable(event)) { html += "<div class='ui-resizable-handle ui-resizable-" + (isRTL ? 'w' : 'e') + "'>" + "&nbsp;&nbsp;&nbsp;" + // makes hit area a lot better for IE6/7 "</div>"; } html += "</" + (url ? "a" : "div") + ">"; // TODO: // When these elements are initially rendered, they will be briefly visibile on the screen, // even though their widths/heights are not set. // SOLUTION: initially set them as visibility:hidden ? return html; } // Associate each segment (an object) with an element (a jQuery object), // by setting each `segment.element`. // Run each element through the `eventRender` filter, which allows developers to // modify an existing element, supply a new one, or cancel rendering. function resolveElements(segments, elements) { for (var i=0; i<segments.length; i++) { var segment = segments[i]; var event = segment.event; var element = elements.eq(i); // call the trigger with the original element var triggerRes = trigger('eventRender', event, event, element); if (triggerRes === false) { // if `false`, remove the event from the DOM and don't assign it to `segment.event` element.remove(); } else { if (triggerRes && triggerRes !== true) { // the trigger returned a new element, but not `true` (which means keep the existing element) // re-assign the important CSS dimension properties that were already assigned in `buildHTMLForSegment` triggerRes = $(triggerRes) .css({ position: 'absolute', left: segment.left }); element.replaceWith(triggerRes); element = triggerRes; } segment.element = element; } } } /* Top-coordinate Methods -------------------------------------------------------------------------------------------------*/ // Sets the "top" CSS property for each element. // If `doRowHeights` is `true`, also sets each row's first cell to an explicit height, // so that if elements vertically overflow, the cell expands vertically to compensate. function setVerticals(segments, doRowHeights) { var rowContentHeights = calculateVerticals(segments); // also sets segment.top var rowContentElements = getRowContentElements(); // returns 1 inner div per row var rowContentTops = []; var i; // Set each row's height by setting height of first inner div if (doRowHeights) { for (i=0; i<rowContentElements.length; i++) { rowContentElements[i].height(rowContentHeights[i]); } } // Get each row's top, relative to the views's origin. // Important to do this after setting each row's height. for (i=0; i<rowContentElements.length; i++) { rowContentTops.push( rowContentElements[i].position().top ); } // Set each segment element's CSS "top" property. // Each segment object has a "top" property, which is relative to the row's top, but... segmentElementEach(segments, function(segment, element) { element.css( 'top', rowContentTops[segment.row] + segment.top // ...now, relative to views's origin ); }); } // Calculate the "top" coordinate for each segment, relative to the "top" of the row. // Also, return an array that contains the "content" height for each row // (the height displaced by the vertically stacked events in the row). // Requires segments to have their `outerHeight` property already set. function calculateVerticals(segments) { var rowCnt = getRowCnt(); var colCnt = getColCnt(); var rowContentHeights = []; // content height for each row var segmentRows = buildSegmentRows(segments); // an array of segment arrays, one for each row var colI; for (var rowI=0; rowI<rowCnt; rowI++) { var segmentRow = segmentRows[rowI]; // an array of running total heights for each column. // initialize with all zeros. var colHeights = []; for (colI=0; colI<colCnt; colI++) { colHeights.push(0); } // loop through every segment for (var segmentI=0; segmentI<segmentRow.length; segmentI++) { var segment = segmentRow[segmentI]; // find the segment's top coordinate by looking at the max height // of all the columns the segment will be in. segment.top = arrayMax( colHeights.slice( segment.leftCol, segment.rightCol + 1 // make exclusive for slice ) ); // adjust the columns to account for the segment's height for (colI=segment.leftCol; colI<=segment.rightCol; colI++) { colHeights[colI] = segment.top + segment.outerHeight; } } // the tallest column in the row should be the "content height" rowContentHeights.push(arrayMax(colHeights)); } return rowContentHeights; } // Build an array of segment arrays, each representing the segments that will // be in a row of the grid, sorted by which event should be closest to the top. function buildSegmentRows(segments) { var rowCnt = getRowCnt(); var segmentRows = []; var segmentI; var segment; var rowI; // group segments by row for (segmentI=0; segmentI<segments.length; segmentI++) { segment = segments[segmentI]; rowI = segment.row; if (segment.element) { // was rendered? if (segmentRows[rowI]) { // already other segments. append to array segmentRows[rowI].push(segment); } else { // first segment in row. create new array segmentRows[rowI] = [ segment ]; } } } // sort each row for (rowI=0; rowI<rowCnt; rowI++) { segmentRows[rowI] = sortSegmentRow( segmentRows[rowI] || [] // guarantee an array, even if no segments ); } return segmentRows; } // Sort an array of segments according to which segment should appear closest to the top function sortSegmentRow(segments) { var sortedSegments = []; // build the subrow array var subrows = buildSegmentSubrows(segments); // flatten it for (var i=0; i<subrows.length; i++) { sortedSegments.push.apply(sortedSegments, subrows[i]); // append an array to an array } return sortedSegments; } // Take an array of segments, which are all assumed to be in the same row, // and sort into subrows. function buildSegmentSubrows(segments) { // Give preference to elements with certain criteria, so they have // a chance to be closer to the top. segments.sort(compareDaySegments); var subrows = []; for (var i=0; i<segments.length; i++) { var segment = segments[i]; // loop through subrows, starting with the topmost, until the segment // doesn't collide with other segments. for (var j=0; j<subrows.length; j++) { if (!isDaySegmentCollision(segment, subrows[j])) { break; } } // `j` now holds the desired subrow index if (subrows[j]) { subrows[j].push(segment); } else { subrows[j] = [ segment ]; } } return subrows; } // Return an array of jQuery objects for the placeholder content containers of each row. // The content containers don't actually contain anything, but their dimensions should match // the events that are overlaid on top. function getRowContentElements() { var i; var rowCnt = getRowCnt(); var rowDivs = []; for (i=0; i<rowCnt; i++) { rowDivs[i] = allDayRow(i) .find('div.fc-day-content > div'); } return rowDivs; } /* Mouse Handlers ---------------------------------------------------------------------------------------------------*/ // TODO: better documentation! function attachHandlers(segments, modifiedEventId) { var segmentContainer = getDaySegmentContainer(); segmentElementEach(segments, function(segment, element, i) { var event = segment.event; if (event._id === modifiedEventId) { bindDaySeg(event, element, segment); }else{ element[0]._fci = i; // for lazySegBind } }); lazySegBind(segmentContainer, segments, bindDaySeg); } function bindDaySeg(event, eventElement, segment) { if (isEventDraggable(event)) { t.draggableDayEvent(event, eventElement, segment); // use `t` so subclasses can override } if ( event.allDay && segment.isEnd && // only allow resizing on the final segment for an event isEventResizable(event) ) { t.resizableDayEvent(event, eventElement, segment); // use `t` so subclasses can override } // attach all other handlers. // needs to be after, because resizableDayEvent might stopImmediatePropagation on click eventElementHandlers(event, eventElement); } function draggableDayEvent(event, eventElement) { var hoverListener = getHoverListener(); var dayDelta; var eventStart; eventElement.draggable({ delay: 50, opacity: opt('dragOpacity'), revertDuration: opt('dragRevertDuration'), start: function(ev, ui) { trigger('eventDragStart', eventElement, event, ev, ui); hideEvents(event, eventElement); hoverListener.start(function(cell, origCell, rowDelta, colDelta) { eventElement.draggable('option', 'revert', !cell || !rowDelta && !colDelta); clearOverlays(); if (cell) { var origCellDate = cellToDate(origCell); var cellDate = cellToDate(cell); dayDelta = cellDate.diff(origCellDate, 'days'); eventStart = event.start.clone().add('days', dayDelta); renderDayOverlay( eventStart, getEventEnd(event).add('days', dayDelta) ); } else { dayDelta = 0; } }, ev, 'drag'); }, stop: function(ev, ui) { hoverListener.stop(); clearOverlays(); trigger('eventDragStop', eventElement, event, ev, ui); if (dayDelta) { eventDrop( this, // el event, eventStart, ev, ui ); } else { eventElement.css('filter', ''); // clear IE opacity side-effects showEvents(event, eventElement); } } }); } function resizableDayEvent(event, element, segment) { var isRTL = opt('isRTL'); var direction = isRTL ? 'w' : 'e'; var handle = element.find('.ui-resizable-' + direction); // TODO: stop using this class because we aren't using jqui for this var isResizing = false; // TODO: look into using jquery-ui mouse widget for this stuff disableTextSelection(element); // prevent native <a> selection for IE element .mousedown(function(ev) { // prevent native <a> selection for others ev.preventDefault(); }) .click(function(ev) { if (isResizing) { ev.preventDefault(); // prevent link from being visited (only method that worked in IE6) ev.stopImmediatePropagation(); // prevent fullcalendar eventClick handler from being called // (eventElementHandlers needs to be bound after resizableDayEvent) } }); handle.mousedown(function(ev) { if (ev.which != 1) { return; // needs to be left mouse button } isResizing = true; var hoverListener = getHoverListener(); var elementTop = element.css('top'); var dayDelta; var eventEnd; var helpers; var eventCopy = $.extend({}, event); var minCellOffset = dayOffsetToCellOffset(dateToDayOffset(event.start)); clearSelection(); $('body') .css('cursor', direction + '-resize') .one('mouseup', mouseup); trigger('eventResizeStart', this, event, ev); hoverListener.start(function(cell, origCell) { if (cell) { var origCellOffset = cellToCellOffset(origCell); var cellOffset = cellToCellOffset(cell); // don't let resizing move earlier than start date cell cellOffset = Math.max(cellOffset, minCellOffset); dayDelta = cellOffsetToDayOffset(cellOffset) - cellOffsetToDayOffset(origCellOffset); eventEnd = getEventEnd(event).add('days', dayDelta); // assumed to already have a stripped time if (dayDelta) { eventCopy.end = eventEnd; var oldHelpers = helpers; helpers = renderTempDayEvent(eventCopy, segment.row, elementTop); helpers = $(helpers); // turn array into a jQuery object helpers.find('*').css('cursor', direction + '-resize'); if (oldHelpers) { oldHelpers.remove(); } hideEvents(event); } else { if (helpers) { showEvents(event); helpers.remove(); helpers = null; } } clearOverlays(); renderDayOverlay( // coordinate grid already rebuilt with hoverListener.start() event.start, eventEnd // TODO: instead of calling renderDayOverlay() with dates, // call _renderDayOverlay (or whatever) with cell offsets. ); } }, ev); function mouseup(ev) { trigger('eventResizeStop', this, event, ev); $('body').css('cursor', ''); hoverListener.stop(); clearOverlays(); if (dayDelta) { eventResize( this, // el event, eventEnd, ev ); // event redraw will clear helpers } // otherwise, the drag handler already restored the old events setTimeout(function() { // make this happen after the element's click event isResizing = false; },0); } }); } } /* Generalized Segment Utilities -------------------------------------------------------------------------------------------------*/ function isDaySegmentCollision(segment, otherSegments) { for (var i=0; i<otherSegments.length; i++) { var otherSegment = otherSegments[i]; if ( otherSegment.leftCol <= segment.rightCol && otherSegment.rightCol >= segment.leftCol ) { return true; } } return false; } function segmentElementEach(segments, callback) { // TODO: use in AgendaView? for (var i=0; i<segments.length; i++) { var segment = segments[i]; var element = segment.element; if (element) { callback(segment, element, i); } } } // A cmp function for determining which segments should appear higher up function compareDaySegments(a, b) { return (b.rightCol - b.leftCol) - (a.rightCol - a.leftCol) || // put wider events first b.event.allDay - a.event.allDay || // if tie, put all-day events first (booleans cast to 0/1) a.event.start - b.event.start || // if a tie, sort by event start date (a.event.title || '').localeCompare(b.event.title); // if a tie, sort by event title } ;; //BUG: unselect needs to be triggered when events are dragged+dropped function SelectionManager() { var t = this; // exports t.select = select; t.unselect = unselect; t.reportSelection = reportSelection; t.daySelectionMousedown = daySelectionMousedown; // imports var calendar = t.calendar; var opt = t.opt; var trigger = t.trigger; var defaultSelectionEnd = t.defaultSelectionEnd; var renderSelection = t.renderSelection; var clearSelection = t.clearSelection; // locals var selected = false; // unselectAuto if (opt('selectable') && opt('unselectAuto')) { // TODO: unbind on destroy $(document).mousedown(function(ev) { var ignore = opt('unselectCancel'); if (ignore) { if ($(ev.target).parents(ignore).length) { // could be optimized to stop after first match return; } } unselect(ev); }); } function select(start, end) { unselect(); start = calendar.moment(start); if (end) { end = calendar.moment(end); } else { end = defaultSelectionEnd(start); } renderSelection(start, end); reportSelection(start, end); } function unselect(ev) { if (selected) { selected = false; clearSelection(); trigger('unselect', null, ev); } } function reportSelection(start, end, ev) { selected = true; trigger('select', null, start, end, ev); } function daySelectionMousedown(ev) { // not really a generic manager method, oh well var cellToDate = t.cellToDate; var getIsCellAllDay = t.getIsCellAllDay; var hoverListener = t.getHoverListener(); var reportDayClick = t.reportDayClick; // this is hacky and sort of weird if (ev.which == 1 && opt('selectable')) { // which==1 means left mouse button unselect(ev); var dates; hoverListener.start(function(cell, origCell) { // TODO: maybe put cellToDate/getIsCellAllDay info in cell clearSelection(); if (cell && getIsCellAllDay(cell)) { dates = [ cellToDate(origCell), cellToDate(cell) ].sort(dateCompare); renderSelection( dates[0], dates[1].clone().add('days', 1) // make exclusive ); }else{ dates = null; } }, ev); $(document).one('mouseup', function(ev) { hoverListener.stop(); if (dates) { if (+dates[0] == +dates[1]) { reportDayClick(dates[0], ev); } reportSelection( dates[0], dates[1].clone().add('days', 1), // make exclusive ev ); } }); } } } ;; function OverlayManager() { var t = this; // exports t.renderOverlay = renderOverlay; t.clearOverlays = clearOverlays; // locals var usedOverlays = []; var unusedOverlays = []; function renderOverlay(rect, parent) { var e = unusedOverlays.shift(); if (!e) { e = $("<div class='fc-cell-overlay' style='position:absolute;z-index:3'/>"); } if (e[0].parentNode != parent[0]) { e.appendTo(parent); } usedOverlays.push(e.css(rect).show()); return e; } function clearOverlays() { var e; while ((e = usedOverlays.shift())) { unusedOverlays.push(e.hide().unbind()); } } } ;; function CoordinateGrid(buildFunc) { var t = this; var rows; var cols; t.build = function() { rows = []; cols = []; buildFunc(rows, cols); }; t.cell = function(x, y) { var rowCnt = rows.length; var colCnt = cols.length; var i, r=-1, c=-1; for (i=0; i<rowCnt; i++) { if (y >= rows[i][0] && y < rows[i][1]) { r = i; break; } } for (i=0; i<colCnt; i++) { if (x >= cols[i][0] && x < cols[i][1]) { c = i; break; } } return (r>=0 && c>=0) ? { row: r, col: c } : null; }; t.rect = function(row0, col0, row1, col1, originElement) { // row1,col1 is inclusive var origin = originElement.offset(); return { top: rows[row0][0] - origin.top, left: cols[col0][0] - origin.left, width: cols[col1][1] - cols[col0][0], height: rows[row1][1] - rows[row0][0] }; }; } ;; function HoverListener(coordinateGrid) { var t = this; var bindType; var change; var firstCell; var cell; t.start = function(_change, ev, _bindType) { change = _change; firstCell = cell = null; coordinateGrid.build(); mouse(ev); bindType = _bindType || 'mousemove'; $(document).bind(bindType, mouse); }; function mouse(ev) { _fixUIEvent(ev); // see below var newCell = coordinateGrid.cell(ev.pageX, ev.pageY); if ( Boolean(newCell) !== Boolean(cell) || newCell && (newCell.row != cell.row || newCell.col != cell.col) ) { if (newCell) { if (!firstCell) { firstCell = newCell; } change(newCell, firstCell, newCell.row-firstCell.row, newCell.col-firstCell.col); }else{ change(newCell, firstCell); } cell = newCell; } } t.stop = function() { $(document).unbind(bindType, mouse); return cell; }; } // this fix was only necessary for jQuery UI 1.8.16 (and jQuery 1.7 or 1.7.1) // upgrading to jQuery UI 1.8.17 (and using either jQuery 1.7 or 1.7.1) fixed the problem // but keep this in here for 1.8.16 users // and maybe remove it down the line function _fixUIEvent(event) { // for issue 1168 if (event.pageX === undefined) { event.pageX = event.originalEvent.pageX; event.pageY = event.originalEvent.pageY; } } ;; function HorizontalPositionCache(getElement) { var t = this, elements = {}, lefts = {}, rights = {}; function e(i) { return (elements[i] = (elements[i] || getElement(i))); } t.left = function(i) { return (lefts[i] = (lefts[i] === undefined ? e(i).position().left : lefts[i])); }; t.right = function(i) { return (rights[i] = (rights[i] === undefined ? t.left(i) + e(i).width() : rights[i])); }; t.clear = function() { elements = {}; lefts = {}; rights = {}; }; } ;; });
JavaScript
/* * File: TableTools.js * Version: 2.1.4 * Description: Tools and buttons for DataTables * Author: Allan Jardine (www.sprymedia.co.uk) * Language: Javascript * License: GPL v2 or BSD 3 point style * Project: DataTables * * Copyright 2009-2012 Allan Jardine, all rights reserved. * * This source file is free software, under either the GPL v2 license or a * BSD style license, available at: * http://datatables.net/license_gpl2 * http://datatables.net/license_bsd */ /* Global scope for TableTools */ var TableTools; (function($, window, document) { /** * TableTools provides flexible buttons and other tools for a DataTables enhanced table * @class TableTools * @constructor * @param {Object} oDT DataTables instance * @param {Object} oOpts TableTools options * @param {String} oOpts.sSwfPath ZeroClipboard SWF path * @param {String} oOpts.sRowSelect Row selection options - 'none', 'single' or 'multi' * @param {Function} oOpts.fnPreRowSelect Callback function just prior to row selection * @param {Function} oOpts.fnRowSelected Callback function just after row selection * @param {Function} oOpts.fnRowDeselected Callback function when row is deselected * @param {Array} oOpts.aButtons List of buttons to be used */ TableTools = function( oDT, oOpts ) { /* Santiy check that we are a new instance */ if ( ! this instanceof TableTools ) { alert( "Warning: TableTools must be initialised with the keyword 'new'" ); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public class variables * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * @namespace Settings object which contains customisable information for TableTools instance */ this.s = { /** * Store 'this' so the instance can be retrieved from the settings object * @property that * @type object * @default this */ "that": this, /** * DataTables settings objects * @property dt * @type object * @default <i>From the oDT init option</i> */ "dt": oDT.fnSettings(), /** * @namespace Print specific information */ "print": { /** * DataTables draw 'start' point before the printing display was shown * @property saveStart * @type int * @default -1 */ "saveStart": -1, /** * DataTables draw 'length' point before the printing display was shown * @property saveLength * @type int * @default -1 */ "saveLength": -1, /** * Page scrolling point before the printing display was shown so it can be restored * @property saveScroll * @type int * @default -1 */ "saveScroll": -1, /** * Wrapped function to end the print display (to maintain scope) * @property funcEnd * @type Function * @default function () {} */ "funcEnd": function () {} }, /** * A unique ID is assigned to each button in each instance * @property buttonCounter * @type int * @default 0 */ "buttonCounter": 0, /** * @namespace Select rows specific information */ "select": { /** * Select type - can be 'none', 'single' or 'multi' * @property type * @type string * @default "" */ "type": "", /** * Array of nodes which are currently selected * @property selected * @type array * @default [] */ "selected": [], /** * Function to run before the selection can take place. Will cancel the select if the * function returns false * @property preRowSelect * @type Function * @default null */ "preRowSelect": null, /** * Function to run when a row is selected * @property postSelected * @type Function * @default null */ "postSelected": null, /** * Function to run when a row is deselected * @property postDeselected * @type Function * @default null */ "postDeselected": null, /** * Indicate if all rows are selected (needed for server-side processing) * @property all * @type boolean * @default false */ "all": false, /** * Class name to add to selected TR nodes * @property selectedClass * @type String * @default "" */ "selectedClass": "" }, /** * Store of the user input customisation object * @property custom * @type object * @default {} */ "custom": {}, /** * SWF movie path * @property swfPath * @type string * @default "" */ "swfPath": "", /** * Default button set * @property buttonSet * @type array * @default [] */ "buttonSet": [], /** * When there is more than one TableTools instance for a DataTable, there must be a * master which controls events (row selection etc) * @property master * @type boolean * @default false */ "master": false, /** * Tag names that are used for creating collections and buttons * @namesapce */ "tags": {} }; /** * @namespace Common and useful DOM elements for the class instance */ this.dom = { /** * DIV element that is create and all TableTools buttons (and their children) put into * @property container * @type node * @default null */ "container": null, /** * The table node to which TableTools will be applied * @property table * @type node * @default null */ "table": null, /** * @namespace Nodes used for the print display */ "print": { /** * Nodes which have been removed from the display by setting them to display none * @property hidden * @type array * @default [] */ "hidden": [], /** * The information display saying telling the user about the print display * @property message * @type node * @default null */ "message": null }, /** * @namespace Nodes used for a collection display. This contains the currently used collection */ "collection": { /** * The div wrapper containing the buttons in the collection (i.e. the menu) * @property collection * @type node * @default null */ "collection": null, /** * Background display to provide focus and capture events * @property background * @type node * @default null */ "background": null } }; /** * @namespace Name space for the classes that this TableTools instance will use * @extends TableTools.classes */ this.classes = $.extend( true, {}, TableTools.classes ); if ( this.s.dt.bJUI ) { $.extend( true, this.classes, TableTools.classes_themeroller ); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public class methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Retreieve the settings object from an instance * @method fnSettings * @returns {object} TableTools settings object */ this.fnSettings = function () { return this.s; }; /* Constructor logic */ if ( typeof oOpts == 'undefined' ) { oOpts = {}; } this._fnConstruct( oOpts ); return this; }; TableTools.prototype = { /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Retreieve the settings object from an instance * @returns {array} List of TR nodes which are currently selected * @param {boolean} [filtered=false] Get only selected rows which are * available given the filtering applied to the table. By default * this is false - i.e. all rows, regardless of filtering are selected. */ "fnGetSelected": function ( filtered ) { var out = [], data = this.s.dt.aoData, displayed = this.s.dt.aiDisplay, i, iLen; if ( filtered ) { // Only consider filtered rows for ( i=0, iLen=displayed.length ; i<iLen ; i++ ) { if ( data[ displayed[i] ]._DTTT_selected ) { out.push( data[ displayed[i] ].nTr ); } } } else { // Use all rows for ( i=0, iLen=data.length ; i<iLen ; i++ ) { if ( data[i]._DTTT_selected ) { out.push( data[i].nTr ); } } } return out; }, /** * Get the data source objects/arrays from DataTables for the selected rows (same as * fnGetSelected followed by fnGetData on each row from the table) * @returns {array} Data from the TR nodes which are currently selected */ "fnGetSelectedData": function () { var out = []; var data=this.s.dt.aoData; var i, iLen; for ( i=0, iLen=data.length ; i<iLen ; i++ ) { if ( data[i]._DTTT_selected ) { out.push( this.s.dt.oInstance.fnGetData(i) ); } } return out; }, /** * Check to see if a current row is selected or not * @param {Node} n TR node to check if it is currently selected or not * @returns {Boolean} true if select, false otherwise */ "fnIsSelected": function ( n ) { var pos = this.s.dt.oInstance.fnGetPosition( n ); return (this.s.dt.aoData[pos]._DTTT_selected===true) ? true : false; }, /** * Select all rows in the table * @param {boolean} [filtered=false] Select only rows which are available * given the filtering applied to the table. By default this is false - * i.e. all rows, regardless of filtering are selected. */ "fnSelectAll": function ( filtered ) { var s = this._fnGetMasterSettings(); this._fnRowSelect( (filtered === true) ? s.dt.aiDisplay : s.dt.aoData ); }, /** * Deselect all rows in the table * @param {boolean} [filtered=false] Deselect only rows which are available * given the filtering applied to the table. By default this is false - * i.e. all rows, regardless of filtering are deselected. */ "fnSelectNone": function ( filtered ) { var s = this._fnGetMasterSettings(); this._fnRowDeselect( this.fnGetSelected(filtered) ); }, /** * Select row(s) * @param {node|object|array} n The row(s) to select. Can be a single DOM * TR node, an array of TR nodes or a jQuery object. */ "fnSelect": function ( n ) { if ( this.s.select.type == "single" ) { this.fnSelectNone(); this._fnRowSelect( n ); } else if ( this.s.select.type == "multi" ) { this._fnRowSelect( n ); } }, /** * Deselect row(s) * @param {node|object|array} n The row(s) to deselect. Can be a single DOM * TR node, an array of TR nodes or a jQuery object. */ "fnDeselect": function ( n ) { this._fnRowDeselect( n ); }, /** * Get the title of the document - useful for file names. The title is retrieved from either * the configuration object's 'title' parameter, or the HTML document title * @param {Object} oConfig Button configuration object * @returns {String} Button title */ "fnGetTitle": function( oConfig ) { var sTitle = ""; if ( typeof oConfig.sTitle != 'undefined' && oConfig.sTitle !== "" ) { sTitle = oConfig.sTitle; } else { var anTitle = document.getElementsByTagName('title'); if ( anTitle.length > 0 ) { sTitle = anTitle[0].innerHTML; } } /* Strip characters which the OS will object to - checking for UTF8 support in the scripting * engine */ if ( "\u00A1".toString().length < 4 ) { return sTitle.replace(/[^a-zA-Z0-9_\u00A1-\uFFFF\.,\-_ !\(\)]/g, ""); } else { return sTitle.replace(/[^a-zA-Z0-9_\.,\-_ !\(\)]/g, ""); } }, /** * Calculate a unity array with the column width by proportion for a set of columns to be * included for a button. This is particularly useful for PDF creation, where we can use the * column widths calculated by the browser to size the columns in the PDF. * @param {Object} oConfig Button configuration object * @returns {Array} Unity array of column ratios */ "fnCalcColRatios": function ( oConfig ) { var aoCols = this.s.dt.aoColumns, aColumnsInc = this._fnColumnTargets( oConfig.mColumns ), aColWidths = [], iWidth = 0, iTotal = 0, i, iLen; for ( i=0, iLen=aColumnsInc.length ; i<iLen ; i++ ) { if ( aColumnsInc[i] ) { iWidth = aoCols[i].nTh.offsetWidth; iTotal += iWidth; aColWidths.push( iWidth ); } } for ( i=0, iLen=aColWidths.length ; i<iLen ; i++ ) { aColWidths[i] = aColWidths[i] / iTotal; } return aColWidths.join('\t'); }, /** * Get the information contained in a table as a string * @param {Object} oConfig Button configuration object * @returns {String} Table data as a string */ "fnGetTableData": function ( oConfig ) { /* In future this could be used to get data from a plain HTML source as well as DataTables */ if ( this.s.dt ) { return this._fnGetDataTablesData( oConfig ); } }, /** * Pass text to a flash button instance, which will be used on the button's click handler * @param {Object} clip Flash button object * @param {String} text Text to set */ "fnSetText": function ( clip, text ) { this._fnFlashSetText( clip, text ); }, /** * Resize the flash elements of the buttons attached to this TableTools instance - this is * useful for when initialising TableTools when it is hidden (display:none) since sizes can't * be calculated at that time. */ "fnResizeButtons": function () { for ( var cli in ZeroClipboard_TableTools.clients ) { if ( cli ) { var client = ZeroClipboard_TableTools.clients[cli]; if ( typeof client.domElement != 'undefined' && client.domElement.parentNode ) { client.positionElement(); } } } }, /** * Check to see if any of the ZeroClipboard client's attached need to be resized */ "fnResizeRequired": function () { for ( var cli in ZeroClipboard_TableTools.clients ) { if ( cli ) { var client = ZeroClipboard_TableTools.clients[cli]; if ( typeof client.domElement != 'undefined' && client.domElement.parentNode == this.dom.container && client.sized === false ) { return true; } } } return false; }, /** * Programmatically enable or disable the print view * @param {boolean} [bView=true] Show the print view if true or not given. If false, then * terminate the print view and return to normal. * @param {object} [oConfig={}] Configuration for the print view * @param {boolean} [oConfig.bShowAll=false] Show all rows in the table if true * @param {string} [oConfig.sInfo] Information message, displayed as an overlay to the * user to let them know what the print view is. * @param {string} [oConfig.sMessage] HTML string to show at the top of the document - will * be included in the printed document. */ "fnPrint": function ( bView, oConfig ) { if ( oConfig === undefined ) { oConfig = {}; } if ( bView === undefined || bView ) { this._fnPrintStart( oConfig ); } else { this._fnPrintEnd(); } }, /** * Show a message to the end user which is nicely styled * @param {string} message The HTML string to show to the user * @param {int} time The duration the message is to be shown on screen for (mS) */ "fnInfo": function ( message, time ) { var nInfo = document.createElement( "div" ); nInfo.className = this.classes.print.info; nInfo.innerHTML = message; document.body.appendChild( nInfo ); setTimeout( function() { $(nInfo).fadeOut( "normal", function() { document.body.removeChild( nInfo ); } ); }, time ); }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Private methods (they are of course public in JS, but recommended as private) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Constructor logic * @method _fnConstruct * @param {Object} oOpts Same as TableTools constructor * @returns void * @private */ "_fnConstruct": function ( oOpts ) { var that = this; this._fnCustomiseSettings( oOpts ); /* Container element */ this.dom.container = document.createElement( this.s.tags.container ); this.dom.container.className = this.classes.container; /* Row selection config */ if ( this.s.select.type != 'none' ) { this._fnRowSelectConfig(); } /* Buttons */ this._fnButtonDefinations( this.s.buttonSet, this.dom.container ); /* Destructor - need to wipe the DOM for IE's garbage collector */ this.s.dt.aoDestroyCallback.push( { "sName": "TableTools", "fn": function () { that.dom.container.innerHTML = ""; } } ); }, /** * Take the user defined settings and the default settings and combine them. * @method _fnCustomiseSettings * @param {Object} oOpts Same as TableTools constructor * @returns void * @private */ "_fnCustomiseSettings": function ( oOpts ) { /* Is this the master control instance or not? */ if ( typeof this.s.dt._TableToolsInit == 'undefined' ) { this.s.master = true; this.s.dt._TableToolsInit = true; } /* We can use the table node from comparisons to group controls */ this.dom.table = this.s.dt.nTable; /* Clone the defaults and then the user options */ this.s.custom = $.extend( {}, TableTools.DEFAULTS, oOpts ); /* Flash file location */ this.s.swfPath = this.s.custom.sSwfPath; if ( typeof ZeroClipboard_TableTools != 'undefined' ) { ZeroClipboard_TableTools.moviePath = this.s.swfPath; } /* Table row selecting */ this.s.select.type = this.s.custom.sRowSelect; this.s.select.preRowSelect = this.s.custom.fnPreRowSelect; this.s.select.postSelected = this.s.custom.fnRowSelected; this.s.select.postDeselected = this.s.custom.fnRowDeselected; // Backwards compatibility - allow the user to specify a custom class in the initialiser if ( this.s.custom.sSelectedClass ) { this.classes.select.row = this.s.custom.sSelectedClass; } this.s.tags = this.s.custom.oTags; /* Button set */ this.s.buttonSet = this.s.custom.aButtons; }, /** * Take the user input arrays and expand them to be fully defined, and then add them to a given * DOM element * @method _fnButtonDefinations * @param {array} buttonSet Set of user defined buttons * @param {node} wrapper Node to add the created buttons to * @returns void * @private */ "_fnButtonDefinations": function ( buttonSet, wrapper ) { var buttonDef; for ( var i=0, iLen=buttonSet.length ; i<iLen ; i++ ) { if ( typeof buttonSet[i] == "string" ) { if ( typeof TableTools.BUTTONS[ buttonSet[i] ] == 'undefined' ) { alert( "TableTools: Warning - unknown button type: "+buttonSet[i] ); continue; } buttonDef = $.extend( {}, TableTools.BUTTONS[ buttonSet[i] ], true ); } else { if ( typeof TableTools.BUTTONS[ buttonSet[i].sExtends ] == 'undefined' ) { alert( "TableTools: Warning - unknown button type: "+buttonSet[i].sExtends ); continue; } var o = $.extend( {}, TableTools.BUTTONS[ buttonSet[i].sExtends ], true ); buttonDef = $.extend( o, buttonSet[i], true ); } wrapper.appendChild( this._fnCreateButton( buttonDef, $(wrapper).hasClass(this.classes.collection.container) ) ); } }, /** * Create and configure a TableTools button * @method _fnCreateButton * @param {Object} oConfig Button configuration object * @returns {Node} Button element * @private */ "_fnCreateButton": function ( oConfig, bCollectionButton ) { var nButton = this._fnButtonBase( oConfig, bCollectionButton ); if ( oConfig.sAction.match(/flash/) ) { this._fnFlashConfig( nButton, oConfig ); } else if ( oConfig.sAction == "text" ) { this._fnTextConfig( nButton, oConfig ); } else if ( oConfig.sAction == "div" ) { this._fnTextConfig( nButton, oConfig ); } else if ( oConfig.sAction == "collection" ) { this._fnTextConfig( nButton, oConfig ); this._fnCollectionConfig( nButton, oConfig ); } return nButton; }, /** * Create the DOM needed for the button and apply some base properties. All buttons start here * @method _fnButtonBase * @param {o} oConfig Button configuration object * @returns {Node} DIV element for the button * @private */ "_fnButtonBase": function ( o, bCollectionButton ) { var sTag, sLiner, sClass; if ( bCollectionButton ) { sTag = o.sTag !== "default" ? o.sTag : this.s.tags.collection.button; sLiner = o.sLinerTag !== "default" ? o.sLiner : this.s.tags.collection.liner; sClass = this.classes.collection.buttons.normal; } else { sTag = o.sTag !== "default" ? o.sTag : this.s.tags.button; sLiner = o.sLinerTag !== "default" ? o.sLiner : this.s.tags.liner; sClass = this.classes.buttons.normal; } var nButton = document.createElement( sTag ), nSpan = document.createElement( sLiner ), masterS = this._fnGetMasterSettings(); nButton.className = sClass+" "+o.sButtonClass; nButton.setAttribute('id', "ToolTables_"+this.s.dt.sInstance+"_"+masterS.buttonCounter ); nButton.appendChild( nSpan ); nSpan.innerHTML = o.sButtonText; masterS.buttonCounter++; return nButton; }, /** * Get the settings object for the master instance. When more than one TableTools instance is * assigned to a DataTable, only one of them can be the 'master' (for the select rows). As such, * we will typically want to interact with that master for global properties. * @method _fnGetMasterSettings * @returns {Object} TableTools settings object * @private */ "_fnGetMasterSettings": function () { if ( this.s.master ) { return this.s; } else { /* Look for the master which has the same DT as this one */ var instances = TableTools._aInstances; for ( var i=0, iLen=instances.length ; i<iLen ; i++ ) { if ( this.dom.table == instances[i].s.dt.nTable ) { return instances[i].s; } } } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Button collection functions */ /** * Create a collection button, when activated will present a drop down list of other buttons * @param {Node} nButton Button to use for the collection activation * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnCollectionConfig": function ( nButton, oConfig ) { var nHidden = document.createElement( this.s.tags.collection.container ); nHidden.style.display = "none"; nHidden.className = this.classes.collection.container; oConfig._collection = nHidden; document.body.appendChild( nHidden ); this._fnButtonDefinations( oConfig.aButtons, nHidden ); }, /** * Show a button collection * @param {Node} nButton Button to use for the collection * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnCollectionShow": function ( nButton, oConfig ) { var that = this, oPos = $(nButton).offset(), nHidden = oConfig._collection, iDivX = oPos.left, iDivY = oPos.top + $(nButton).outerHeight(), iWinHeight = $(window).height(), iDocHeight = $(document).height(), iWinWidth = $(window).width(), iDocWidth = $(document).width(); nHidden.style.position = "absolute"; nHidden.style.left = iDivX+"px"; nHidden.style.top = iDivY+"px"; nHidden.style.display = "block"; $(nHidden).css('opacity',0); var nBackground = document.createElement('div'); nBackground.style.position = "absolute"; nBackground.style.left = "0px"; nBackground.style.top = "0px"; nBackground.style.height = ((iWinHeight>iDocHeight)? iWinHeight : iDocHeight) +"px"; nBackground.style.width = ((iWinWidth>iDocWidth)? iWinWidth : iDocWidth) +"px"; nBackground.className = this.classes.collection.background; $(nBackground).css('opacity',0); document.body.appendChild( nBackground ); document.body.appendChild( nHidden ); /* Visual corrections to try and keep the collection visible */ var iDivWidth = $(nHidden).outerWidth(); var iDivHeight = $(nHidden).outerHeight(); if ( iDivX + iDivWidth > iDocWidth ) { nHidden.style.left = (iDocWidth-iDivWidth)+"px"; } if ( iDivY + iDivHeight > iDocHeight ) { nHidden.style.top = (iDivY-iDivHeight-$(nButton).outerHeight())+"px"; } this.dom.collection.collection = nHidden; this.dom.collection.background = nBackground; /* This results in a very small delay for the end user but it allows the animation to be * much smoother. If you don't want the animation, then the setTimeout can be removed */ setTimeout( function () { $(nHidden).animate({"opacity": 1}, 500); $(nBackground).animate({"opacity": 0.25}, 500); }, 10 ); /* Resize the buttons to the Flash contents fit */ this.fnResizeButtons(); /* Event handler to remove the collection display */ $(nBackground).click( function () { that._fnCollectionHide.call( that, null, null ); } ); }, /** * Hide a button collection * @param {Node} nButton Button to use for the collection * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnCollectionHide": function ( nButton, oConfig ) { if ( oConfig !== null && oConfig.sExtends == 'collection' ) { return; } if ( this.dom.collection.collection !== null ) { $(this.dom.collection.collection).animate({"opacity": 0}, 500, function (e) { this.style.display = "none"; } ); $(this.dom.collection.background).animate({"opacity": 0}, 500, function (e) { this.parentNode.removeChild( this ); } ); this.dom.collection.collection = null; this.dom.collection.background = null; } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Row selection functions */ /** * Add event handlers to a table to allow for row selection * @method _fnRowSelectConfig * @returns void * @private */ "_fnRowSelectConfig": function () { if ( this.s.master ) { var that = this, i, iLen, dt = this.s.dt, aoOpenRows = this.s.dt.aoOpenRows; $(dt.nTable).addClass( this.classes.select.table ); $('tr', dt.nTBody).live( 'click', function(e) { /* Sub-table must be ignored (odd that the selector won't do this with >) */ if ( this.parentNode != dt.nTBody ) { return; } /* Check that we are actually working with a DataTables controlled row */ if ( dt.oInstance.fnGetData(this) === null ) { return; } if ( that.fnIsSelected( this ) ) { that._fnRowDeselect( this, e ); } else if ( that.s.select.type == "single" ) { that.fnSelectNone(); that._fnRowSelect( this, e ); } else if ( that.s.select.type == "multi" ) { that._fnRowSelect( this, e ); } } ); // Bind a listener to the DataTable for when new rows are created. // This allows rows to be visually selected when they should be and // deferred rendering is used. dt.oApi._fnCallbackReg( dt, 'aoRowCreatedCallback', function (tr, data, index) { if ( dt.aoData[index]._DTTT_selected ) { $(tr).addClass( that.classes.select.row ); } }, 'TableTools-SelectAll' ); } }, /** * Select rows * @param {*} src Rows to select - see _fnSelectData for a description of valid inputs * @private */ "_fnRowSelect": function ( src, e ) { var that = this, data = this._fnSelectData( src ), firstTr = data.length===0 ? null : data[0].nTr, anSelected = [], i, len; // Get all the rows that will be selected for ( i=0, len=data.length ; i<len ; i++ ) { if ( data[i].nTr ) { anSelected.push( data[i].nTr ); } } // User defined pre-selection function if ( this.s.select.preRowSelect !== null && !this.s.select.preRowSelect.call(this, e, anSelected, true) ) { return; } // Mark them as selected for ( i=0, len=data.length ; i<len ; i++ ) { data[i]._DTTT_selected = true; if ( data[i].nTr ) { $(data[i].nTr).addClass( that.classes.select.row ); } } // Post-selection function if ( this.s.select.postSelected !== null ) { this.s.select.postSelected.call( this, anSelected ); } TableTools._fnEventDispatch( this, 'select', anSelected, true ); }, /** * Deselect rows * @param {*} src Rows to deselect - see _fnSelectData for a description of valid inputs * @private */ "_fnRowDeselect": function ( src, e ) { var that = this, data = this._fnSelectData( src ), firstTr = data.length===0 ? null : data[0].nTr, anDeselectedTrs = [], i, len; // Get all the rows that will be deselected for ( i=0, len=data.length ; i<len ; i++ ) { if ( data[i].nTr ) { anDeselectedTrs.push( data[i].nTr ); } } // User defined pre-selection function if ( this.s.select.preRowSelect !== null && !this.s.select.preRowSelect.call(this, e, anDeselectedTrs, false) ) { return; } // Mark them as deselected for ( i=0, len=data.length ; i<len ; i++ ) { data[i]._DTTT_selected = false; if ( data[i].nTr ) { $(data[i].nTr).removeClass( that.classes.select.row ); } } // Post-deselection function if ( this.s.select.postDeselected !== null ) { this.s.select.postDeselected.call( this, anDeselectedTrs ); } TableTools._fnEventDispatch( this, 'select', anDeselectedTrs, false ); }, /** * Take a data source for row selection and convert it into aoData points for the DT * @param {*} src Can be a single DOM TR node, an array of TR nodes (including a * a jQuery object), a single aoData point from DataTables, an array of aoData * points or an array of aoData indexes * @returns {array} An array of aoData points */ "_fnSelectData": function ( src ) { var out = [], pos, i, iLen; if ( src.nodeName ) { // Single node pos = this.s.dt.oInstance.fnGetPosition( src ); out.push( this.s.dt.aoData[pos] ); } else if ( typeof src.length !== 'undefined' ) { // jQuery object or an array of nodes, or aoData points for ( i=0, iLen=src.length ; i<iLen ; i++ ) { if ( src[i].nodeName ) { pos = this.s.dt.oInstance.fnGetPosition( src[i] ); out.push( this.s.dt.aoData[pos] ); } else if ( typeof src[i] === 'number' ) { out.push( this.s.dt.aoData[ src[i] ] ); } else { out.push( src[i] ); } } return out; } else { // A single aoData point out.push( src ); } return out; }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Text button functions */ /** * Configure a text based button for interaction events * @method _fnTextConfig * @param {Node} nButton Button element which is being considered * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnTextConfig": function ( nButton, oConfig ) { var that = this; if ( oConfig.fnInit !== null ) { oConfig.fnInit.call( this, nButton, oConfig ); } if ( oConfig.sToolTip !== "" ) { nButton.title = oConfig.sToolTip; } $(nButton).hover( function () { if ( oConfig.fnMouseover !== null ) { oConfig.fnMouseover.call( this, nButton, oConfig, null ); } }, function () { if ( oConfig.fnMouseout !== null ) { oConfig.fnMouseout.call( this, nButton, oConfig, null ); } } ); if ( oConfig.fnSelect !== null ) { TableTools._fnEventListen( this, 'select', function (n) { oConfig.fnSelect.call( that, nButton, oConfig, n ); } ); } $(nButton).click( function (e) { //e.preventDefault(); if ( oConfig.fnClick !== null ) { oConfig.fnClick.call( that, nButton, oConfig, null ); } /* Provide a complete function to match the behaviour of the flash elements */ if ( oConfig.fnComplete !== null ) { oConfig.fnComplete.call( that, nButton, oConfig, null, null ); } that._fnCollectionHide( nButton, oConfig ); } ); }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Flash button functions */ /** * Configure a flash based button for interaction events * @method _fnFlashConfig * @param {Node} nButton Button element which is being considered * @param {o} oConfig Button configuration object * @returns void * @private */ "_fnFlashConfig": function ( nButton, oConfig ) { var that = this; var flash = new ZeroClipboard_TableTools.Client(); if ( oConfig.fnInit !== null ) { oConfig.fnInit.call( this, nButton, oConfig ); } flash.setHandCursor( true ); if ( oConfig.sAction == "flash_save" ) { flash.setAction( 'save' ); flash.setCharSet( (oConfig.sCharSet=="utf16le") ? 'UTF16LE' : 'UTF8' ); flash.setBomInc( oConfig.bBomInc ); flash.setFileName( oConfig.sFileName.replace('*', this.fnGetTitle(oConfig)) ); } else if ( oConfig.sAction == "flash_pdf" ) { flash.setAction( 'pdf' ); flash.setFileName( oConfig.sFileName.replace('*', this.fnGetTitle(oConfig)) ); } else { flash.setAction( 'copy' ); } flash.addEventListener('mouseOver', function(client) { if ( oConfig.fnMouseover !== null ) { oConfig.fnMouseover.call( that, nButton, oConfig, flash ); } } ); flash.addEventListener('mouseOut', function(client) { if ( oConfig.fnMouseout !== null ) { oConfig.fnMouseout.call( that, nButton, oConfig, flash ); } } ); flash.addEventListener('mouseDown', function(client) { if ( oConfig.fnClick !== null ) { oConfig.fnClick.call( that, nButton, oConfig, flash ); } } ); flash.addEventListener('complete', function (client, text) { if ( oConfig.fnComplete !== null ) { oConfig.fnComplete.call( that, nButton, oConfig, flash, text ); } that._fnCollectionHide( nButton, oConfig ); } ); this._fnFlashGlue( flash, nButton, oConfig.sToolTip ); }, /** * Wait until the id is in the DOM before we "glue" the swf. Note that this function will call * itself (using setTimeout) until it completes successfully * @method _fnFlashGlue * @param {Object} clip Zero clipboard object * @param {Node} node node to glue swf to * @param {String} text title of the flash movie * @returns void * @private */ "_fnFlashGlue": function ( flash, node, text ) { var that = this; var id = node.getAttribute('id'); if ( document.getElementById(id) ) { flash.glue( node, text ); } else { setTimeout( function () { that._fnFlashGlue( flash, node, text ); }, 100 ); } }, /** * Set the text for the flash clip to deal with * * This function is required for large information sets. There is a limit on the * amount of data that can be transferred between Javascript and Flash in a single call, so * we use this method to build up the text in Flash by sending over chunks. It is estimated * that the data limit is around 64k, although it is undocumented, and appears to be different * between different flash versions. We chunk at 8KiB. * @method _fnFlashSetText * @param {Object} clip the ZeroClipboard object * @param {String} sData the data to be set * @returns void * @private */ "_fnFlashSetText": function ( clip, sData ) { var asData = this._fnChunkData( sData, 8192 ); clip.clearText(); for ( var i=0, iLen=asData.length ; i<iLen ; i++ ) { clip.appendText( asData[i] ); } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Data retrieval functions */ /** * Convert the mixed columns variable into a boolean array the same size as the columns, which * indicates which columns we want to include * @method _fnColumnTargets * @param {String|Array} mColumns The columns to be included in data retrieval. If a string * then it can take the value of "visible" or "hidden" (to include all visible or * hidden columns respectively). Or an array of column indexes * @returns {Array} A boolean array the length of the columns of the table, which each value * indicating if the column is to be included or not * @private */ "_fnColumnTargets": function ( mColumns ) { var aColumns = []; var dt = this.s.dt; if ( typeof mColumns == "object" ) { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( false ); } for ( i=0, iLen=mColumns.length ; i<iLen ; i++ ) { aColumns[ mColumns[i] ] = true; } } else if ( mColumns == "visible" ) { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( dt.aoColumns[i].bVisible ? true : false ); } } else if ( mColumns == "hidden" ) { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( dt.aoColumns[i].bVisible ? false : true ); } } else if ( mColumns == "sortable" ) { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( dt.aoColumns[i].bSortable ? true : false ); } } else /* all */ { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( true ); } } return aColumns; }, /** * New line character(s) depend on the platforms * @method method * @param {Object} oConfig Button configuration object - only interested in oConfig.sNewLine * @returns {String} Newline character */ "_fnNewline": function ( oConfig ) { if ( oConfig.sNewLine == "auto" ) { return navigator.userAgent.match(/Windows/) ? "\r\n" : "\n"; } else { return oConfig.sNewLine; } }, /** * Get data from DataTables' internals and format it for output * @method _fnGetDataTablesData * @param {Object} oConfig Button configuration object * @param {String} oConfig.sFieldBoundary Field boundary for the data cells in the string * @param {String} oConfig.sFieldSeperator Field separator for the data cells * @param {String} oConfig.sNewline New line options * @param {Mixed} oConfig.mColumns Which columns should be included in the output * @param {Boolean} oConfig.bHeader Include the header * @param {Boolean} oConfig.bFooter Include the footer * @param {Boolean} oConfig.bSelectedOnly Include only the selected rows in the output * @returns {String} Concatenated string of data * @private */ "_fnGetDataTablesData": function ( oConfig ) { var i, iLen, j, jLen; var aRow, aData=[], sLoopData='', arr; var dt = this.s.dt, tr, child; var regex = new RegExp(oConfig.sFieldBoundary, "g"); /* Do it here for speed */ var aColumnsInc = this._fnColumnTargets( oConfig.mColumns ); var bSelectedOnly = (typeof oConfig.bSelectedOnly != 'undefined') ? oConfig.bSelectedOnly : false; /* * Header */ if ( oConfig.bHeader ) { aRow = []; for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { if ( aColumnsInc[i] ) { sLoopData = dt.aoColumns[i].sTitle.replace(/\n/g," ").replace( /<.*?>/g, "" ).replace(/^\s+|\s+$/g,""); sLoopData = this._fnHtmlDecode( sLoopData ); aRow.push( this._fnBoundData( sLoopData, oConfig.sFieldBoundary, regex ) ); } } aData.push( aRow.join(oConfig.sFieldSeperator) ); } /* * Body */ var aDataIndex = dt.aiDisplay; var aSelected = this.fnGetSelected(); if ( this.s.select.type !== "none" && bSelectedOnly && aSelected.length !== 0 ) { aDataIndex = []; for ( i=0, iLen=aSelected.length ; i<iLen ; i++ ) { aDataIndex.push( dt.oInstance.fnGetPosition( aSelected[i] ) ); } } for ( j=0, jLen=aDataIndex.length ; j<jLen ; j++ ) { tr = dt.aoData[ aDataIndex[j] ].nTr; aRow = []; /* Columns */ for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { if ( aColumnsInc[i] ) { /* Convert to strings (with small optimisation) */ var mTypeData = dt.oApi._fnGetCellData( dt, aDataIndex[j], i, 'display' ); if ( oConfig.fnCellRender ) { sLoopData = oConfig.fnCellRender( mTypeData, i, tr, aDataIndex[j] )+""; } else if ( typeof mTypeData == "string" ) { /* Strip newlines, replace img tags with alt attr. and finally strip html... */ sLoopData = mTypeData.replace(/\n/g," "); sLoopData = sLoopData.replace(/<img.*?\s+alt\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+)).*?>/gi, '$1$2$3'); sLoopData = sLoopData.replace( /<.*?>/g, "" ); } else { sLoopData = mTypeData+""; } /* Trim and clean the data */ sLoopData = sLoopData.replace(/^\s+/, '').replace(/\s+$/, ''); sLoopData = this._fnHtmlDecode( sLoopData ); /* Bound it and add it to the total data */ aRow.push( this._fnBoundData( sLoopData, oConfig.sFieldBoundary, regex ) ); } } aData.push( aRow.join(oConfig.sFieldSeperator) ); /* Details rows from fnOpen */ if ( oConfig.bOpenRows ) { arr = $.grep(dt.aoOpenRows, function(o) { return o.nParent === tr; }); if ( arr.length === 1 ) { sLoopData = this._fnBoundData( $('td', arr[0].nTr).html(), oConfig.sFieldBoundary, regex ); aData.push( sLoopData ); } } } /* * Footer */ if ( oConfig.bFooter && dt.nTFoot !== null ) { aRow = []; for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { if ( aColumnsInc[i] && dt.aoColumns[i].nTf !== null ) { sLoopData = dt.aoColumns[i].nTf.innerHTML.replace(/\n/g," ").replace( /<.*?>/g, "" ); sLoopData = this._fnHtmlDecode( sLoopData ); aRow.push( this._fnBoundData( sLoopData, oConfig.sFieldBoundary, regex ) ); } } aData.push( aRow.join(oConfig.sFieldSeperator) ); } _sLastData = aData.join( this._fnNewline(oConfig) ); return _sLastData; }, /** * Wrap data up with a boundary string * @method _fnBoundData * @param {String} sData data to bound * @param {String} sBoundary bounding char(s) * @param {RegExp} regex search for the bounding chars - constructed outside for efficiency * in the loop * @returns {String} bound data * @private */ "_fnBoundData": function ( sData, sBoundary, regex ) { if ( sBoundary === "" ) { return sData; } else { return sBoundary + sData.replace(regex, sBoundary+sBoundary) + sBoundary; } }, /** * Break a string up into an array of smaller strings * @method _fnChunkData * @param {String} sData data to be broken up * @param {Int} iSize chunk size * @returns {Array} String array of broken up text * @private */ "_fnChunkData": function ( sData, iSize ) { var asReturn = []; var iStrlen = sData.length; for ( var i=0 ; i<iStrlen ; i+=iSize ) { if ( i+iSize < iStrlen ) { asReturn.push( sData.substring( i, i+iSize ) ); } else { asReturn.push( sData.substring( i, iStrlen ) ); } } return asReturn; }, /** * Decode HTML entities * @method _fnHtmlDecode * @param {String} sData encoded string * @returns {String} decoded string * @private */ "_fnHtmlDecode": function ( sData ) { if ( sData.indexOf('&') === -1 ) { return sData; } var n = document.createElement('div'); return sData.replace( /&([^\s]*);/g, function( match, match2 ) { if ( match.substr(1, 1) === '#' ) { return String.fromCharCode( Number(match2.substr(1)) ); } else { n.innerHTML = match; return n.childNodes[0].nodeValue; } } ); }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Printing functions */ /** * Show print display * @method _fnPrintStart * @param {Event} e Event object * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnPrintStart": function ( oConfig ) { var that = this; var oSetDT = this.s.dt; /* Parse through the DOM hiding everything that isn't needed for the table */ this._fnPrintHideNodes( oSetDT.nTable ); /* Show the whole table */ this.s.print.saveStart = oSetDT._iDisplayStart; this.s.print.saveLength = oSetDT._iDisplayLength; if ( oConfig.bShowAll ) { oSetDT._iDisplayStart = 0; oSetDT._iDisplayLength = -1; oSetDT.oApi._fnCalculateEnd( oSetDT ); oSetDT.oApi._fnDraw( oSetDT ); } /* Adjust the display for scrolling which might be done by DataTables */ if ( oSetDT.oScroll.sX !== "" || oSetDT.oScroll.sY !== "" ) { this._fnPrintScrollStart( oSetDT ); // If the table redraws while in print view, the DataTables scrolling // setup would hide the header, so we need to readd it on draw $(this.s.dt.nTable).bind('draw.DTTT_Print', function () { that._fnPrintScrollStart( oSetDT ); } ); } /* Remove the other DataTables feature nodes - but leave the table! and info div */ var anFeature = oSetDT.aanFeatures; for ( var cFeature in anFeature ) { if ( cFeature != 'i' && cFeature != 't' && cFeature.length == 1 ) { for ( var i=0, iLen=anFeature[cFeature].length ; i<iLen ; i++ ) { this.dom.print.hidden.push( { "node": anFeature[cFeature][i], "display": "block" } ); anFeature[cFeature][i].style.display = "none"; } } } /* Print class can be used for styling */ $(document.body).addClass( this.classes.print.body ); /* Show information message to let the user know what is happening */ if ( oConfig.sInfo !== "" ) { this.fnInfo( oConfig.sInfo, 3000 ); } /* Add a message at the top of the page */ if ( oConfig.sMessage ) { this.dom.print.message = document.createElement( "div" ); this.dom.print.message.className = this.classes.print.message; this.dom.print.message.innerHTML = oConfig.sMessage; document.body.insertBefore( this.dom.print.message, document.body.childNodes[0] ); } /* Cache the scrolling and the jump to the top of the page */ this.s.print.saveScroll = $(window).scrollTop(); window.scrollTo( 0, 0 ); /* Bind a key event listener to the document for the escape key - * it is removed in the callback */ $(document).bind( "keydown.DTTT", function(e) { /* Only interested in the escape key */ if ( e.keyCode == 27 ) { e.preventDefault(); that._fnPrintEnd.call( that, e ); } } ); }, /** * Printing is finished, resume normal display * @method _fnPrintEnd * @param {Event} e Event object * @returns void * @private */ "_fnPrintEnd": function ( e ) { var that = this; var oSetDT = this.s.dt; var oSetPrint = this.s.print; var oDomPrint = this.dom.print; /* Show all hidden nodes */ this._fnPrintShowNodes(); /* Restore DataTables' scrolling */ if ( oSetDT.oScroll.sX !== "" || oSetDT.oScroll.sY !== "" ) { $(this.s.dt.nTable).unbind('draw.DTTT_Print'); this._fnPrintScrollEnd(); } /* Restore the scroll */ window.scrollTo( 0, oSetPrint.saveScroll ); /* Drop the print message */ if ( oDomPrint.message !== null ) { document.body.removeChild( oDomPrint.message ); oDomPrint.message = null; } /* Styling class */ $(document.body).removeClass( 'DTTT_Print' ); /* Restore the table length */ oSetDT._iDisplayStart = oSetPrint.saveStart; oSetDT._iDisplayLength = oSetPrint.saveLength; oSetDT.oApi._fnCalculateEnd( oSetDT ); oSetDT.oApi._fnDraw( oSetDT ); $(document).unbind( "keydown.DTTT" ); }, /** * Take account of scrolling in DataTables by showing the full table * @returns void * @private */ "_fnPrintScrollStart": function () { var oSetDT = this.s.dt, nScrollHeadInner = oSetDT.nScrollHead.getElementsByTagName('div')[0], nScrollHeadTable = nScrollHeadInner.getElementsByTagName('table')[0], nScrollBody = oSetDT.nTable.parentNode; /* Copy the header in the thead in the body table, this way we show one single table when * in print view. Note that this section of code is more or less verbatim from DT 1.7.0 */ var nTheadSize = oSetDT.nTable.getElementsByTagName('thead'); if ( nTheadSize.length > 0 ) { oSetDT.nTable.removeChild( nTheadSize[0] ); } if ( oSetDT.nTFoot !== null ) { var nTfootSize = oSetDT.nTable.getElementsByTagName('tfoot'); if ( nTfootSize.length > 0 ) { oSetDT.nTable.removeChild( nTfootSize[0] ); } } nTheadSize = oSetDT.nTHead.cloneNode(true); oSetDT.nTable.insertBefore( nTheadSize, oSetDT.nTable.childNodes[0] ); if ( oSetDT.nTFoot !== null ) { nTfootSize = oSetDT.nTFoot.cloneNode(true); oSetDT.nTable.insertBefore( nTfootSize, oSetDT.nTable.childNodes[1] ); } /* Now adjust the table's viewport so we can actually see it */ if ( oSetDT.oScroll.sX !== "" ) { oSetDT.nTable.style.width = $(oSetDT.nTable).outerWidth()+"px"; nScrollBody.style.width = $(oSetDT.nTable).outerWidth()+"px"; nScrollBody.style.overflow = "visible"; } if ( oSetDT.oScroll.sY !== "" ) { nScrollBody.style.height = $(oSetDT.nTable).outerHeight()+"px"; nScrollBody.style.overflow = "visible"; } }, /** * Take account of scrolling in DataTables by showing the full table. Note that the redraw of * the DataTable that we do will actually deal with the majority of the hard work here * @returns void * @private */ "_fnPrintScrollEnd": function () { var oSetDT = this.s.dt, nScrollBody = oSetDT.nTable.parentNode; if ( oSetDT.oScroll.sX !== "" ) { nScrollBody.style.width = oSetDT.oApi._fnStringToCss( oSetDT.oScroll.sX ); nScrollBody.style.overflow = "auto"; } if ( oSetDT.oScroll.sY !== "" ) { nScrollBody.style.height = oSetDT.oApi._fnStringToCss( oSetDT.oScroll.sY ); nScrollBody.style.overflow = "auto"; } }, /** * Resume the display of all TableTools hidden nodes * @method _fnPrintShowNodes * @returns void * @private */ "_fnPrintShowNodes": function ( ) { var anHidden = this.dom.print.hidden; for ( var i=0, iLen=anHidden.length ; i<iLen ; i++ ) { anHidden[i].node.style.display = anHidden[i].display; } anHidden.splice( 0, anHidden.length ); }, /** * Hide nodes which are not needed in order to display the table. Note that this function is * recursive * @method _fnPrintHideNodes * @param {Node} nNode Element which should be showing in a 'print' display * @returns void * @private */ "_fnPrintHideNodes": function ( nNode ) { var anHidden = this.dom.print.hidden; var nParent = nNode.parentNode; var nChildren = nParent.childNodes; for ( var i=0, iLen=nChildren.length ; i<iLen ; i++ ) { if ( nChildren[i] != nNode && nChildren[i].nodeType == 1 ) { /* If our node is shown (don't want to show nodes which were previously hidden) */ var sDisplay = $(nChildren[i]).css("display"); if ( sDisplay != "none" ) { /* Cache the node and it's previous state so we can restore it */ anHidden.push( { "node": nChildren[i], "display": sDisplay } ); nChildren[i].style.display = "none"; } } } if ( nParent.nodeName != "BODY" ) { this._fnPrintHideNodes( nParent ); } } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static variables * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Store of all instances that have been created of TableTools, so one can look up other (when * there is need of a master) * @property _aInstances * @type Array * @default [] * @private */ TableTools._aInstances = []; /** * Store of all listeners and their callback functions * @property _aListeners * @type Array * @default [] */ TableTools._aListeners = []; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Get an array of all the master instances * @method fnGetMasters * @returns {Array} List of master TableTools instances * @static */ TableTools.fnGetMasters = function () { var a = []; for ( var i=0, iLen=TableTools._aInstances.length ; i<iLen ; i++ ) { if ( TableTools._aInstances[i].s.master ) { a.push( TableTools._aInstances[i] ); } } return a; }; /** * Get the master instance for a table node (or id if a string is given) * @method fnGetInstance * @returns {Object} ID of table OR table node, for which we want the TableTools instance * @static */ TableTools.fnGetInstance = function ( node ) { if ( typeof node != 'object' ) { node = document.getElementById(node); } for ( var i=0, iLen=TableTools._aInstances.length ; i<iLen ; i++ ) { if ( TableTools._aInstances[i].s.master && TableTools._aInstances[i].dom.table == node ) { return TableTools._aInstances[i]; } } return null; }; /** * Add a listener for a specific event * @method _fnEventListen * @param {Object} that Scope of the listening function (i.e. 'this' in the caller) * @param {String} type Event type * @param {Function} fn Function * @returns void * @private * @static */ TableTools._fnEventListen = function ( that, type, fn ) { TableTools._aListeners.push( { "that": that, "type": type, "fn": fn } ); }; /** * An event has occurred - look up every listener and fire it off. We check that the event we are * going to fire is attached to the same table (using the table node as reference) before firing * @method _fnEventDispatch * @param {Object} that Scope of the listening function (i.e. 'this' in the caller) * @param {String} type Event type * @param {Node} node Element that the event occurred on (may be null) * @param {boolean} [selected] Indicate if the node was selected (true) or deselected (false) * @returns void * @private * @static */ TableTools._fnEventDispatch = function ( that, type, node, selected ) { var listeners = TableTools._aListeners; for ( var i=0, iLen=listeners.length ; i<iLen ; i++ ) { if ( that.dom.table == listeners[i].that.dom.table && listeners[i].type == type ) { listeners[i].fn( node, selected ); } } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Constants * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ TableTools.buttonBase = { // Button base "sAction": "text", "sTag": "default", "sLinerTag": "default", "sButtonClass": "DTTT_button_text", "sButtonText": "Button text", "sTitle": "", "sToolTip": "", // Common button specific options "sCharSet": "utf8", "bBomInc": false, "sFileName": "*.csv", "sFieldBoundary": "", "sFieldSeperator": "\t", "sNewLine": "auto", "mColumns": "all", /* "all", "visible", "hidden" or array of column integers */ "bHeader": true, "bFooter": true, "bOpenRows": false, "bSelectedOnly": false, // Callbacks "fnMouseover": null, "fnMouseout": null, "fnClick": null, "fnSelect": null, "fnComplete": null, "fnInit": null, "fnCellRender": null }; /** * @namespace Default button configurations */ TableTools.BUTTONS = { "csv": $.extend( {}, TableTools.buttonBase, { "sAction": "flash_save", "sButtonClass": "DTTT_button_csv", "sButtonText": "CSV", "sFieldBoundary": '"', "sFieldSeperator": ",", "fnClick": function( nButton, oConfig, flash ) { this.fnSetText( flash, this.fnGetTableData(oConfig) ); } } ), "xls": $.extend( {}, TableTools.buttonBase, { "sAction": "flash_save", "sCharSet": "utf16le", "bBomInc": true, "sButtonClass": "DTTT_button_xls", "sButtonText": "Excel", "fnClick": function( nButton, oConfig, flash ) { this.fnSetText( flash, this.fnGetTableData(oConfig) ); } } ), "copy": $.extend( {}, TableTools.buttonBase, { "sAction": "flash_copy", "sButtonClass": "DTTT_button_copy", "sButtonText": "Copy", "fnClick": function( nButton, oConfig, flash ) { this.fnSetText( flash, this.fnGetTableData(oConfig) ); }, "fnComplete": function(nButton, oConfig, flash, text) { var lines = text.split('\n').length, len = this.s.dt.nTFoot === null ? lines-1 : lines-2, plural = (len==1) ? "" : "s"; this.fnInfo( '<h6>Table copied</h6>'+ '<p>Copied '+len+' row'+plural+' to the clipboard.</p>', 1500 ); } } ), "pdf": $.extend( {}, TableTools.buttonBase, { "sAction": "flash_pdf", "sNewLine": "\n", "sFileName": "*.pdf", "sButtonClass": "DTTT_button_pdf", "sButtonText": "PDF", "sPdfOrientation": "portrait", "sPdfSize": "A4", "sPdfMessage": "", "fnClick": function( nButton, oConfig, flash ) { this.fnSetText( flash, "title:"+ this.fnGetTitle(oConfig) +"\n"+ "message:"+ oConfig.sPdfMessage +"\n"+ "colWidth:"+ this.fnCalcColRatios(oConfig) +"\n"+ "orientation:"+ oConfig.sPdfOrientation +"\n"+ "size:"+ oConfig.sPdfSize +"\n"+ "--/TableToolsOpts--\n" + this.fnGetTableData(oConfig) ); } } ), "print": $.extend( {}, TableTools.buttonBase, { "sInfo": "<h6>Print view</h6><p>Please use your browser's print function to "+ "print this table. Press escape when finished.", "sMessage": null, "bShowAll": true, "sToolTip": "View print view", "sButtonClass": "DTTT_button_print", "sButtonText": "Print", "fnClick": function ( nButton, oConfig ) { this.fnPrint( true, oConfig ); } } ), "text": $.extend( {}, TableTools.buttonBase ), "select": $.extend( {}, TableTools.buttonBase, { "sButtonText": "Select button", "fnSelect": function( nButton, oConfig ) { if ( this.fnGetSelected().length !== 0 ) { $(nButton).removeClass( this.classes.buttons.disabled ); } else { $(nButton).addClass( this.classes.buttons.disabled ); } }, "fnInit": function( nButton, oConfig ) { $(nButton).addClass( this.classes.buttons.disabled ); } } ), "select_single": $.extend( {}, TableTools.buttonBase, { "sButtonText": "Select button", "fnSelect": function( nButton, oConfig ) { var iSelected = this.fnGetSelected().length; if ( iSelected == 1 ) { $(nButton).removeClass( this.classes.buttons.disabled ); } else { $(nButton).addClass( this.classes.buttons.disabled ); } }, "fnInit": function( nButton, oConfig ) { $(nButton).addClass( this.classes.buttons.disabled ); } } ), "select_all": $.extend( {}, TableTools.buttonBase, { "sButtonText": "Select all", "fnClick": function( nButton, oConfig ) { this.fnSelectAll(); }, "fnSelect": function( nButton, oConfig ) { if ( this.fnGetSelected().length == this.s.dt.fnRecordsDisplay() ) { $(nButton).addClass( this.classes.buttons.disabled ); } else { $(nButton).removeClass( this.classes.buttons.disabled ); } } } ), "select_none": $.extend( {}, TableTools.buttonBase, { "sButtonText": "Deselect all", "fnClick": function( nButton, oConfig ) { this.fnSelectNone(); }, "fnSelect": function( nButton, oConfig ) { if ( this.fnGetSelected().length !== 0 ) { $(nButton).removeClass( this.classes.buttons.disabled ); } else { $(nButton).addClass( this.classes.buttons.disabled ); } }, "fnInit": function( nButton, oConfig ) { $(nButton).addClass( this.classes.buttons.disabled ); } } ), "ajax": $.extend( {}, TableTools.buttonBase, { "sAjaxUrl": "/xhr.php", "sButtonText": "Ajax button", "fnClick": function( nButton, oConfig ) { var sData = this.fnGetTableData(oConfig); $.ajax( { "url": oConfig.sAjaxUrl, "data": [ { "name": "tableData", "value": sData } ], "success": oConfig.fnAjaxComplete, "dataType": "json", "type": "POST", "cache": false, "error": function () { alert( "Error detected when sending table data to server" ); } } ); }, "fnAjaxComplete": function( json ) { alert( 'Ajax complete' ); } } ), "div": $.extend( {}, TableTools.buttonBase, { "sAction": "div", "sTag": "div", "sButtonClass": "DTTT_nonbutton", "sButtonText": "Text button" } ), "collection": $.extend( {}, TableTools.buttonBase, { "sAction": "collection", "sButtonClass": "DTTT_button_collection", "sButtonText": "Collection", "fnClick": function( nButton, oConfig ) { this._fnCollectionShow(nButton, oConfig); } } ) }; /* * on* callback parameters: * 1. node - button element * 2. object - configuration object for this button * 3. object - ZeroClipboard reference (flash button only) * 4. string - Returned string from Flash (flash button only - and only on 'complete') */ /** * @namespace Classes used by TableTools - allows the styles to be override easily. * Note that when TableTools initialises it will take a copy of the classes object * and will use its internal copy for the remainder of its run time. */ TableTools.classes = { "container": "DTTT_container", "buttons": { "normal": "DTTT_button", "disabled": "DTTT_disabled" }, "collection": { "container": "DTTT_collection", "background": "DTTT_collection_background", "buttons": { "normal": "DTTT_button", "disabled": "DTTT_disabled" } }, "select": { "table": "DTTT_selectable", "row": "DTTT_selected" }, "print": { "body": "DTTT_Print", "info": "DTTT_print_info", "message": "DTTT_PrintMessage" } }; /** * @namespace ThemeRoller classes - built in for compatibility with DataTables' * bJQueryUI option. */ TableTools.classes_themeroller = { "container": "DTTT_container ui-buttonset ui-buttonset-multi", "buttons": { "normal": "DTTT_button ui-button ui-state-default" }, "collection": { "container": "DTTT_collection ui-buttonset ui-buttonset-multi" } }; /** * @namespace TableTools default settings for initialisation */ TableTools.DEFAULTS = { "sSwfPath": "media/swf/copy_csv_xls_pdf.swf", "sRowSelect": "none", "sSelectedClass": null, "fnPreRowSelect": null, "fnRowSelected": null, "fnRowDeselected": null, "aButtons": [ "copy", "csv", "xls", "pdf", "print" ], "oTags": { "container": "div", "button": "a", // We really want to use buttons here, but Firefox and IE ignore the // click on the Flash element in the button (but not mouse[in|out]). "liner": "span", "collection": { "container": "div", "button": "a", "liner": "span" } } }; /** * Name of this class * @constant CLASS * @type String * @default TableTools */ TableTools.prototype.CLASS = "TableTools"; /** * TableTools version * @constant VERSION * @type String * @default See code */ TableTools.VERSION = "2.1.4"; TableTools.prototype.VERSION = TableTools.VERSION; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Initialisation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Register a new feature with DataTables */ if ( typeof $.fn.dataTable == "function" && typeof $.fn.dataTableExt.fnVersionCheck == "function" && $.fn.dataTableExt.fnVersionCheck('1.9.0') ) { $.fn.dataTableExt.aoFeatures.push( { "fnInit": function( oDTSettings ) { var oOpts = typeof oDTSettings.oInit.oTableTools != 'undefined' ? oDTSettings.oInit.oTableTools : {}; var oTT = new TableTools( oDTSettings.oInstance, oOpts ); TableTools._aInstances.push( oTT ); return oTT.dom.container; }, "cFeature": "T", "sFeature": "TableTools" } ); } else { alert( "Warning: TableTools 2 requires DataTables 1.9.0 or newer - www.datatables.net/download"); } $.fn.DataTable.TableTools = TableTools; })(jQuery, window, document);
JavaScript
// Simple Set Clipboard System // Author: Joseph Huckaby var ZeroClipboard_TableTools = { version: "1.0.4-TableTools2", clients: {}, // registered upload clients on page, indexed by id moviePath: '', // URL to movie nextId: 1, // ID of next movie $: function(thingy) { // simple DOM lookup utility function if (typeof(thingy) == 'string') thingy = document.getElementById(thingy); if (!thingy.addClass) { // extend element with a few useful methods thingy.hide = function() { this.style.display = 'none'; }; thingy.show = function() { this.style.display = ''; }; thingy.addClass = function(name) { this.removeClass(name); this.className += ' ' + name; }; thingy.removeClass = function(name) { this.className = this.className.replace( new RegExp("\\s*" + name + "\\s*"), " ").replace(/^\s+/, '').replace(/\s+$/, ''); }; thingy.hasClass = function(name) { return !!this.className.match( new RegExp("\\s*" + name + "\\s*") ); } } return thingy; }, setMoviePath: function(path) { // set path to ZeroClipboard.swf this.moviePath = path; }, dispatch: function(id, eventName, args) { // receive event from flash movie, send to client var client = this.clients[id]; if (client) { client.receiveEvent(eventName, args); } }, register: function(id, client) { // register new client to receive events this.clients[id] = client; }, getDOMObjectPosition: function(obj) { // get absolute coordinates for dom element var info = { left: 0, top: 0, width: obj.width ? obj.width : obj.offsetWidth, height: obj.height ? obj.height : obj.offsetHeight }; if ( obj.style.width != "" ) info.width = obj.style.width.replace("px",""); if ( obj.style.height != "" ) info.height = obj.style.height.replace("px",""); while (obj) { info.left += obj.offsetLeft; info.top += obj.offsetTop; obj = obj.offsetParent; } return info; }, Client: function(elem) { // constructor for new simple upload client this.handlers = {}; // unique ID this.id = ZeroClipboard_TableTools.nextId++; this.movieId = 'ZeroClipboard_TableToolsMovie_' + this.id; // register client with singleton to receive flash events ZeroClipboard_TableTools.register(this.id, this); // create movie if (elem) this.glue(elem); } }; ZeroClipboard_TableTools.Client.prototype = { id: 0, // unique ID for us ready: false, // whether movie is ready to receive events or not movie: null, // reference to movie object clipText: '', // text to copy to clipboard fileName: '', // default file save name action: 'copy', // action to perform handCursorEnabled: true, // whether to show hand cursor, or default pointer cursor cssEffects: true, // enable CSS mouse effects on dom container handlers: null, // user event handlers sized: false, glue: function(elem, title) { // glue to DOM element // elem can be ID or actual DOM element object this.domElement = ZeroClipboard_TableTools.$(elem); // float just above object, or zIndex 99 if dom element isn't set var zIndex = 99; if (this.domElement.style.zIndex) { zIndex = parseInt(this.domElement.style.zIndex) + 1; } // find X/Y position of domElement var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement); // create floating DIV above element this.div = document.createElement('div'); var style = this.div.style; style.position = 'absolute'; style.left = '0px'; style.top = '0px'; style.width = (box.width) + 'px'; style.height = box.height + 'px'; style.zIndex = zIndex; if ( typeof title != "undefined" && title != "" ) { this.div.title = title; } if ( box.width != 0 && box.height != 0 ) { this.sized = true; } // style.backgroundColor = '#f00'; // debug if ( this.domElement ) { this.domElement.appendChild(this.div); this.div.innerHTML = this.getHTML( box.width, box.height ); } }, positionElement: function() { var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement); var style = this.div.style; style.position = 'absolute'; //style.left = (this.domElement.offsetLeft)+'px'; //style.top = this.domElement.offsetTop+'px'; style.width = box.width + 'px'; style.height = box.height + 'px'; if ( box.width != 0 && box.height != 0 ) { this.sized = true; } else { return; } var flash = this.div.childNodes[0]; flash.width = box.width; flash.height = box.height; }, getHTML: function(width, height) { // return HTML for movie var html = ''; var flashvars = 'id=' + this.id + '&width=' + width + '&height=' + height; if (navigator.userAgent.match(/MSIE/)) { // IE gets an OBJECT tag var protocol = location.href.match(/^https/i) ? 'https://' : 'http://'; html += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="'+protocol+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0" width="'+width+'" height="'+height+'" id="'+this.movieId+'" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+ZeroClipboard_TableTools.moviePath+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+flashvars+'"/><param name="wmode" value="transparent"/></object>'; } else { // all other browsers get an EMBED tag html += '<embed id="'+this.movieId+'" src="'+ZeroClipboard_TableTools.moviePath+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="'+this.movieId+'" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'" wmode="transparent" />'; } return html; }, hide: function() { // temporarily hide floater offscreen if (this.div) { this.div.style.left = '-2000px'; } }, show: function() { // show ourselves after a call to hide() this.reposition(); }, destroy: function() { // destroy control and floater if (this.domElement && this.div) { this.hide(); this.div.innerHTML = ''; var body = document.getElementsByTagName('body')[0]; try { body.removeChild( this.div ); } catch(e) {;} this.domElement = null; this.div = null; } }, reposition: function(elem) { // reposition our floating div, optionally to new container // warning: container CANNOT change size, only position if (elem) { this.domElement = ZeroClipboard_TableTools.$(elem); if (!this.domElement) this.hide(); } if (this.domElement && this.div) { var box = ZeroClipboard_TableTools.getDOMObjectPosition(this.domElement); var style = this.div.style; style.left = '' + box.left + 'px'; style.top = '' + box.top + 'px'; } }, clearText: function() { // clear the text to be copy / saved this.clipText = ''; if (this.ready) this.movie.clearText(); }, appendText: function(newText) { // append text to that which is to be copied / saved this.clipText += newText; if (this.ready) { this.movie.appendText(newText) ;} }, setText: function(newText) { // set text to be copied to be copied / saved this.clipText = newText; if (this.ready) { this.movie.setText(newText) ;} }, setCharSet: function(charSet) { // set the character set (UTF16LE or UTF8) this.charSet = charSet; if (this.ready) { this.movie.setCharSet(charSet) ;} }, setBomInc: function(bomInc) { // set if the BOM should be included or not this.incBom = bomInc; if (this.ready) { this.movie.setBomInc(bomInc) ;} }, setFileName: function(newText) { // set the file name this.fileName = newText; if (this.ready) this.movie.setFileName(newText); }, setAction: function(newText) { // set action (save or copy) this.action = newText; if (this.ready) this.movie.setAction(newText); }, addEventListener: function(eventName, func) { // add user event listener for event // event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel eventName = eventName.toString().toLowerCase().replace(/^on/, ''); if (!this.handlers[eventName]) this.handlers[eventName] = []; this.handlers[eventName].push(func); }, setHandCursor: function(enabled) { // enable hand cursor (true), or default arrow cursor (false) this.handCursorEnabled = enabled; if (this.ready) this.movie.setHandCursor(enabled); }, setCSSEffects: function(enabled) { // enable or disable CSS effects on DOM container this.cssEffects = !!enabled; }, receiveEvent: function(eventName, args) { // receive event from flash eventName = eventName.toString().toLowerCase().replace(/^on/, ''); // special behavior for certain events switch (eventName) { case 'load': // movie claims it is ready, but in IE this isn't always the case... // bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function this.movie = document.getElementById(this.movieId); if (!this.movie) { var self = this; setTimeout( function() { self.receiveEvent('load', null); }, 1 ); return; } // firefox on pc needs a "kick" in order to set these in certain cases if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) { var self = this; setTimeout( function() { self.receiveEvent('load', null); }, 100 ); this.ready = true; return; } this.ready = true; this.movie.clearText(); this.movie.appendText( this.clipText ); this.movie.setFileName( this.fileName ); this.movie.setAction( this.action ); this.movie.setCharSet( this.charSet ); this.movie.setBomInc( this.incBom ); this.movie.setHandCursor( this.handCursorEnabled ); break; case 'mouseover': if (this.domElement && this.cssEffects) { //this.domElement.addClass('hover'); if (this.recoverActive) this.domElement.addClass('active'); } break; case 'mouseout': if (this.domElement && this.cssEffects) { this.recoverActive = false; if (this.domElement.hasClass('active')) { this.domElement.removeClass('active'); this.recoverActive = true; } //this.domElement.removeClass('hover'); } break; case 'mousedown': if (this.domElement && this.cssEffects) { this.domElement.addClass('active'); } break; case 'mouseup': if (this.domElement && this.cssEffects) { this.domElement.removeClass('active'); this.recoverActive = false; } break; } // switch eventName if (this.handlers[eventName]) { for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) { var func = this.handlers[eventName][idx]; if (typeof(func) == 'function') { // actual function reference func(this, args); } else if ((typeof(func) == 'object') && (func.length == 2)) { // PHP style object + method, i.e. [myObject, 'myMethod'] func[0][ func[1] ](this, args); } else if (typeof(func) == 'string') { // name of function window[func](this, args); } } // foreach event handler defined } // user defined handler for event } };
JavaScript
/* Set the defaults for DataTables initialisation */ $.extend( true, $.fn.dataTable.defaults, { "sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>", "sPaginationType": "bootstrap", "oLanguage": { "sLengthMenu": "_MENU_ records per page" } } ); /* Default class modification */ $.extend( $.fn.dataTableExt.oStdClasses, { "sWrapper": "dataTables_wrapper form-inline" } ); /* API method to get paging information */ $.fn.dataTableExt.oApi.fnPagingInfo = function ( oSettings ) { return { "iStart": oSettings._iDisplayStart, "iEnd": oSettings.fnDisplayEnd(), "iLength": oSettings._iDisplayLength, "iTotal": oSettings.fnRecordsTotal(), "iFilteredTotal": oSettings.fnRecordsDisplay(), "iPage": oSettings._iDisplayLength === -1 ? 0 : Math.ceil( oSettings._iDisplayStart / oSettings._iDisplayLength ), "iTotalPages": oSettings._iDisplayLength === -1 ? 0 : Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength ) }; }; /* Bootstrap style pagination control */ $.extend( $.fn.dataTableExt.oPagination, { "bootstrap": { "fnInit": function( oSettings, nPaging, fnDraw ) { var oLang = oSettings.oLanguage.oPaginate; var fnClickHandler = function ( e ) { e.preventDefault(); if ( oSettings.oApi._fnPageChange(oSettings, e.data.action) ) { fnDraw( oSettings ); } }; $(nPaging).append( '<ul class="pagination">'+ '<li class="prev disabled"><a href="#">&larr; '+oLang.sPrevious+'</a></li>'+ '<li class="next disabled"><a href="#">'+oLang.sNext+' &rarr; </a></li>'+ '</ul>' ); var els = $('a', nPaging); $(els[0]).bind( 'click.DT', { action: "previous" }, fnClickHandler ); $(els[1]).bind( 'click.DT', { action: "next" }, fnClickHandler ); }, "fnUpdate": function ( oSettings, fnDraw ) { var iListLength = 5; var oPaging = oSettings.oInstance.fnPagingInfo(); var an = oSettings.aanFeatures.p; var i, ien, j, sClass, iStart, iEnd, iHalf=Math.floor(iListLength/2); if ( oPaging.iTotalPages < iListLength) { iStart = 1; iEnd = oPaging.iTotalPages; } else if ( oPaging.iPage <= iHalf ) { iStart = 1; iEnd = iListLength; } else if ( oPaging.iPage >= (oPaging.iTotalPages-iHalf) ) { iStart = oPaging.iTotalPages - iListLength + 1; iEnd = oPaging.iTotalPages; } else { iStart = oPaging.iPage - iHalf + 1; iEnd = iStart + iListLength - 1; } for ( i=0, ien=an.length ; i<ien ; i++ ) { // Remove the middle elements $('li:gt(0)', an[i]).filter(':not(:last)').remove(); // Add the new list items and their event handlers for ( j=iStart ; j<=iEnd ; j++ ) { sClass = (j==oPaging.iPage+1) ? 'class="active"' : ''; $('<li '+sClass+'><a href="#">'+j+'</a></li>') .insertBefore( $('li:last', an[i])[0] ) .bind('click', function (e) { e.preventDefault(); oSettings._iDisplayStart = (parseInt($('a', this).text(),10)-1) * oPaging.iLength; fnDraw( oSettings ); } ); } // Add / remove disabled classes from the static elements if ( oPaging.iPage === 0 ) { $('li:first', an[i]).addClass('disabled'); } else { $('li:first', an[i]).removeClass('disabled'); } if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) { $('li:last', an[i]).addClass('disabled'); } else { $('li:last', an[i]).removeClass('disabled'); } } } } } ); /* * TableTools Bootstrap compatibility * Required TableTools 2.1+ */ if ( $.fn.DataTable.TableTools ) { // Set the classes that TableTools uses to something suitable for Bootstrap $.extend( true, $.fn.DataTable.TableTools.classes, { "container": "DTTT btn-group", "buttons": { "normal": "btn", "disabled": "disabled" }, "collection": { "container": "DTTT_dropdown dropdown-menu", "buttons": { "normal": "", "disabled": "disabled" } }, "print": { "info": "DTTT_print_info modal" }, "select": { "row": "active" } } ); // Have the collection use a bootstrap compatible dropdown $.extend( true, $.fn.DataTable.TableTools.DEFAULTS.oTags, { "collection": { "container": "ul", "button": "li", "liner": "a" } } ); }
JavaScript
/* * File: TableTools.js * Version: 2.1.4 * Description: Tools and buttons for DataTables * Author: Allan Jardine (www.sprymedia.co.uk) * Language: Javascript * License: GPL v2 or BSD 3 point style * Project: DataTables * * Copyright 2009-2012 Allan Jardine, all rights reserved. * * This source file is free software, under either the GPL v2 license or a * BSD style license, available at: * http://datatables.net/license_gpl2 * http://datatables.net/license_bsd */ /* Global scope for TableTools */ var TableTools; (function($, window, document) { /** * TableTools provides flexible buttons and other tools for a DataTables enhanced table * @class TableTools * @constructor * @param {Object} oDT DataTables instance * @param {Object} oOpts TableTools options * @param {String} oOpts.sSwfPath ZeroClipboard SWF path * @param {String} oOpts.sRowSelect Row selection options - 'none', 'single' or 'multi' * @param {Function} oOpts.fnPreRowSelect Callback function just prior to row selection * @param {Function} oOpts.fnRowSelected Callback function just after row selection * @param {Function} oOpts.fnRowDeselected Callback function when row is deselected * @param {Array} oOpts.aButtons List of buttons to be used */ TableTools = function( oDT, oOpts ) { /* Santiy check that we are a new instance */ if ( ! this instanceof TableTools ) { alert( "Warning: TableTools must be initialised with the keyword 'new'" ); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public class variables * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * @namespace Settings object which contains customisable information for TableTools instance */ this.s = { /** * Store 'this' so the instance can be retrieved from the settings object * @property that * @type object * @default this */ "that": this, /** * DataTables settings objects * @property dt * @type object * @default <i>From the oDT init option</i> */ "dt": oDT.fnSettings(), /** * @namespace Print specific information */ "print": { /** * DataTables draw 'start' point before the printing display was shown * @property saveStart * @type int * @default -1 */ "saveStart": -1, /** * DataTables draw 'length' point before the printing display was shown * @property saveLength * @type int * @default -1 */ "saveLength": -1, /** * Page scrolling point before the printing display was shown so it can be restored * @property saveScroll * @type int * @default -1 */ "saveScroll": -1, /** * Wrapped function to end the print display (to maintain scope) * @property funcEnd * @type Function * @default function () {} */ "funcEnd": function () {} }, /** * A unique ID is assigned to each button in each instance * @property buttonCounter * @type int * @default 0 */ "buttonCounter": 0, /** * @namespace Select rows specific information */ "select": { /** * Select type - can be 'none', 'single' or 'multi' * @property type * @type string * @default "" */ "type": "", /** * Array of nodes which are currently selected * @property selected * @type array * @default [] */ "selected": [], /** * Function to run before the selection can take place. Will cancel the select if the * function returns false * @property preRowSelect * @type Function * @default null */ "preRowSelect": null, /** * Function to run when a row is selected * @property postSelected * @type Function * @default null */ "postSelected": null, /** * Function to run when a row is deselected * @property postDeselected * @type Function * @default null */ "postDeselected": null, /** * Indicate if all rows are selected (needed for server-side processing) * @property all * @type boolean * @default false */ "all": false, /** * Class name to add to selected TR nodes * @property selectedClass * @type String * @default "" */ "selectedClass": "" }, /** * Store of the user input customisation object * @property custom * @type object * @default {} */ "custom": {}, /** * SWF movie path * @property swfPath * @type string * @default "" */ "swfPath": "", /** * Default button set * @property buttonSet * @type array * @default [] */ "buttonSet": [], /** * When there is more than one TableTools instance for a DataTable, there must be a * master which controls events (row selection etc) * @property master * @type boolean * @default false */ "master": false, /** * Tag names that are used for creating collections and buttons * @namesapce */ "tags": {} }; /** * @namespace Common and useful DOM elements for the class instance */ this.dom = { /** * DIV element that is create and all TableTools buttons (and their children) put into * @property container * @type node * @default null */ "container": null, /** * The table node to which TableTools will be applied * @property table * @type node * @default null */ "table": null, /** * @namespace Nodes used for the print display */ "print": { /** * Nodes which have been removed from the display by setting them to display none * @property hidden * @type array * @default [] */ "hidden": [], /** * The information display saying telling the user about the print display * @property message * @type node * @default null */ "message": null }, /** * @namespace Nodes used for a collection display. This contains the currently used collection */ "collection": { /** * The div wrapper containing the buttons in the collection (i.e. the menu) * @property collection * @type node * @default null */ "collection": null, /** * Background display to provide focus and capture events * @property background * @type node * @default null */ "background": null } }; /** * @namespace Name space for the classes that this TableTools instance will use * @extends TableTools.classes */ this.classes = $.extend( true, {}, TableTools.classes ); if ( this.s.dt.bJUI ) { $.extend( true, this.classes, TableTools.classes_themeroller ); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public class methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Retreieve the settings object from an instance * @method fnSettings * @returns {object} TableTools settings object */ this.fnSettings = function () { return this.s; }; /* Constructor logic */ if ( typeof oOpts == 'undefined' ) { oOpts = {}; } this._fnConstruct( oOpts ); return this; }; TableTools.prototype = { /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Public methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Retreieve the settings object from an instance * @returns {array} List of TR nodes which are currently selected * @param {boolean} [filtered=false] Get only selected rows which are * available given the filtering applied to the table. By default * this is false - i.e. all rows, regardless of filtering are selected. */ "fnGetSelected": function ( filtered ) { var out = [], data = this.s.dt.aoData, displayed = this.s.dt.aiDisplay, i, iLen; if ( filtered ) { // Only consider filtered rows for ( i=0, iLen=displayed.length ; i<iLen ; i++ ) { if ( data[ displayed[i] ]._DTTT_selected ) { out.push( data[ displayed[i] ].nTr ); } } } else { // Use all rows for ( i=0, iLen=data.length ; i<iLen ; i++ ) { if ( data[i]._DTTT_selected ) { out.push( data[i].nTr ); } } } return out; }, /** * Get the data source objects/arrays from DataTables for the selected rows (same as * fnGetSelected followed by fnGetData on each row from the table) * @returns {array} Data from the TR nodes which are currently selected */ "fnGetSelectedData": function () { var out = []; var data=this.s.dt.aoData; var i, iLen; for ( i=0, iLen=data.length ; i<iLen ; i++ ) { if ( data[i]._DTTT_selected ) { out.push( this.s.dt.oInstance.fnGetData(i) ); } } return out; }, /** * Check to see if a current row is selected or not * @param {Node} n TR node to check if it is currently selected or not * @returns {Boolean} true if select, false otherwise */ "fnIsSelected": function ( n ) { var pos = this.s.dt.oInstance.fnGetPosition( n ); return (this.s.dt.aoData[pos]._DTTT_selected===true) ? true : false; }, /** * Select all rows in the table * @param {boolean} [filtered=false] Select only rows which are available * given the filtering applied to the table. By default this is false - * i.e. all rows, regardless of filtering are selected. */ "fnSelectAll": function ( filtered ) { var s = this._fnGetMasterSettings(); this._fnRowSelect( (filtered === true) ? s.dt.aiDisplay : s.dt.aoData ); }, /** * Deselect all rows in the table * @param {boolean} [filtered=false] Deselect only rows which are available * given the filtering applied to the table. By default this is false - * i.e. all rows, regardless of filtering are deselected. */ "fnSelectNone": function ( filtered ) { var s = this._fnGetMasterSettings(); this._fnRowDeselect( this.fnGetSelected(filtered) ); }, /** * Select row(s) * @param {node|object|array} n The row(s) to select. Can be a single DOM * TR node, an array of TR nodes or a jQuery object. */ "fnSelect": function ( n ) { if ( this.s.select.type == "single" ) { this.fnSelectNone(); this._fnRowSelect( n ); } else if ( this.s.select.type == "multi" ) { this._fnRowSelect( n ); } }, /** * Deselect row(s) * @param {node|object|array} n The row(s) to deselect. Can be a single DOM * TR node, an array of TR nodes or a jQuery object. */ "fnDeselect": function ( n ) { this._fnRowDeselect( n ); }, /** * Get the title of the document - useful for file names. The title is retrieved from either * the configuration object's 'title' parameter, or the HTML document title * @param {Object} oConfig Button configuration object * @returns {String} Button title */ "fnGetTitle": function( oConfig ) { var sTitle = ""; if ( typeof oConfig.sTitle != 'undefined' && oConfig.sTitle !== "" ) { sTitle = oConfig.sTitle; } else { var anTitle = document.getElementsByTagName('title'); if ( anTitle.length > 0 ) { sTitle = anTitle[0].innerHTML; } } /* Strip characters which the OS will object to - checking for UTF8 support in the scripting * engine */ if ( "\u00A1".toString().length < 4 ) { return sTitle.replace(/[^a-zA-Z0-9_\u00A1-\uFFFF\.,\-_ !\(\)]/g, ""); } else { return sTitle.replace(/[^a-zA-Z0-9_\.,\-_ !\(\)]/g, ""); } }, /** * Calculate a unity array with the column width by proportion for a set of columns to be * included for a button. This is particularly useful for PDF creation, where we can use the * column widths calculated by the browser to size the columns in the PDF. * @param {Object} oConfig Button configuration object * @returns {Array} Unity array of column ratios */ "fnCalcColRatios": function ( oConfig ) { var aoCols = this.s.dt.aoColumns, aColumnsInc = this._fnColumnTargets( oConfig.mColumns ), aColWidths = [], iWidth = 0, iTotal = 0, i, iLen; for ( i=0, iLen=aColumnsInc.length ; i<iLen ; i++ ) { if ( aColumnsInc[i] ) { iWidth = aoCols[i].nTh.offsetWidth; iTotal += iWidth; aColWidths.push( iWidth ); } } for ( i=0, iLen=aColWidths.length ; i<iLen ; i++ ) { aColWidths[i] = aColWidths[i] / iTotal; } return aColWidths.join('\t'); }, /** * Get the information contained in a table as a string * @param {Object} oConfig Button configuration object * @returns {String} Table data as a string */ "fnGetTableData": function ( oConfig ) { /* In future this could be used to get data from a plain HTML source as well as DataTables */ if ( this.s.dt ) { return this._fnGetDataTablesData( oConfig ); } }, /** * Pass text to a flash button instance, which will be used on the button's click handler * @param {Object} clip Flash button object * @param {String} text Text to set */ "fnSetText": function ( clip, text ) { this._fnFlashSetText( clip, text ); }, /** * Resize the flash elements of the buttons attached to this TableTools instance - this is * useful for when initialising TableTools when it is hidden (display:none) since sizes can't * be calculated at that time. */ "fnResizeButtons": function () { for ( var cli in ZeroClipboard_TableTools.clients ) { if ( cli ) { var client = ZeroClipboard_TableTools.clients[cli]; if ( typeof client.domElement != 'undefined' && client.domElement.parentNode ) { client.positionElement(); } } } }, /** * Check to see if any of the ZeroClipboard client's attached need to be resized */ "fnResizeRequired": function () { for ( var cli in ZeroClipboard_TableTools.clients ) { if ( cli ) { var client = ZeroClipboard_TableTools.clients[cli]; if ( typeof client.domElement != 'undefined' && client.domElement.parentNode == this.dom.container && client.sized === false ) { return true; } } } return false; }, /** * Programmatically enable or disable the print view * @param {boolean} [bView=true] Show the print view if true or not given. If false, then * terminate the print view and return to normal. * @param {object} [oConfig={}] Configuration for the print view * @param {boolean} [oConfig.bShowAll=false] Show all rows in the table if true * @param {string} [oConfig.sInfo] Information message, displayed as an overlay to the * user to let them know what the print view is. * @param {string} [oConfig.sMessage] HTML string to show at the top of the document - will * be included in the printed document. */ "fnPrint": function ( bView, oConfig ) { if ( oConfig === undefined ) { oConfig = {}; } if ( bView === undefined || bView ) { this._fnPrintStart( oConfig ); } else { this._fnPrintEnd(); } }, /** * Show a message to the end user which is nicely styled * @param {string} message The HTML string to show to the user * @param {int} time The duration the message is to be shown on screen for (mS) */ "fnInfo": function ( message, time ) { var nInfo = document.createElement( "div" ); nInfo.className = this.classes.print.info; nInfo.innerHTML = message; document.body.appendChild( nInfo ); setTimeout( function() { $(nInfo).fadeOut( "normal", function() { document.body.removeChild( nInfo ); } ); }, time ); }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Private methods (they are of course public in JS, but recommended as private) * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Constructor logic * @method _fnConstruct * @param {Object} oOpts Same as TableTools constructor * @returns void * @private */ "_fnConstruct": function ( oOpts ) { var that = this; this._fnCustomiseSettings( oOpts ); /* Container element */ this.dom.container = document.createElement( this.s.tags.container ); this.dom.container.className = this.classes.container; /* Row selection config */ if ( this.s.select.type != 'none' ) { this._fnRowSelectConfig(); } /* Buttons */ this._fnButtonDefinations( this.s.buttonSet, this.dom.container ); /* Destructor - need to wipe the DOM for IE's garbage collector */ this.s.dt.aoDestroyCallback.push( { "sName": "TableTools", "fn": function () { that.dom.container.innerHTML = ""; } } ); }, /** * Take the user defined settings and the default settings and combine them. * @method _fnCustomiseSettings * @param {Object} oOpts Same as TableTools constructor * @returns void * @private */ "_fnCustomiseSettings": function ( oOpts ) { /* Is this the master control instance or not? */ if ( typeof this.s.dt._TableToolsInit == 'undefined' ) { this.s.master = true; this.s.dt._TableToolsInit = true; } /* We can use the table node from comparisons to group controls */ this.dom.table = this.s.dt.nTable; /* Clone the defaults and then the user options */ this.s.custom = $.extend( {}, TableTools.DEFAULTS, oOpts ); /* Flash file location */ this.s.swfPath = this.s.custom.sSwfPath; if ( typeof ZeroClipboard_TableTools != 'undefined' ) { ZeroClipboard_TableTools.moviePath = this.s.swfPath; } /* Table row selecting */ this.s.select.type = this.s.custom.sRowSelect; this.s.select.preRowSelect = this.s.custom.fnPreRowSelect; this.s.select.postSelected = this.s.custom.fnRowSelected; this.s.select.postDeselected = this.s.custom.fnRowDeselected; // Backwards compatibility - allow the user to specify a custom class in the initialiser if ( this.s.custom.sSelectedClass ) { this.classes.select.row = this.s.custom.sSelectedClass; } this.s.tags = this.s.custom.oTags; /* Button set */ this.s.buttonSet = this.s.custom.aButtons; }, /** * Take the user input arrays and expand them to be fully defined, and then add them to a given * DOM element * @method _fnButtonDefinations * @param {array} buttonSet Set of user defined buttons * @param {node} wrapper Node to add the created buttons to * @returns void * @private */ "_fnButtonDefinations": function ( buttonSet, wrapper ) { var buttonDef; for ( var i=0, iLen=buttonSet.length ; i<iLen ; i++ ) { if ( typeof buttonSet[i] == "string" ) { if ( typeof TableTools.BUTTONS[ buttonSet[i] ] == 'undefined' ) { alert( "TableTools: Warning - unknown button type: "+buttonSet[i] ); continue; } buttonDef = $.extend( {}, TableTools.BUTTONS[ buttonSet[i] ], true ); } else { if ( typeof TableTools.BUTTONS[ buttonSet[i].sExtends ] == 'undefined' ) { alert( "TableTools: Warning - unknown button type: "+buttonSet[i].sExtends ); continue; } var o = $.extend( {}, TableTools.BUTTONS[ buttonSet[i].sExtends ], true ); buttonDef = $.extend( o, buttonSet[i], true ); } wrapper.appendChild( this._fnCreateButton( buttonDef, $(wrapper).hasClass(this.classes.collection.container) ) ); } }, /** * Create and configure a TableTools button * @method _fnCreateButton * @param {Object} oConfig Button configuration object * @returns {Node} Button element * @private */ "_fnCreateButton": function ( oConfig, bCollectionButton ) { var nButton = this._fnButtonBase( oConfig, bCollectionButton ); if ( oConfig.sAction.match(/flash/) ) { this._fnFlashConfig( nButton, oConfig ); } else if ( oConfig.sAction == "text" ) { this._fnTextConfig( nButton, oConfig ); } else if ( oConfig.sAction == "div" ) { this._fnTextConfig( nButton, oConfig ); } else if ( oConfig.sAction == "collection" ) { this._fnTextConfig( nButton, oConfig ); this._fnCollectionConfig( nButton, oConfig ); } return nButton; }, /** * Create the DOM needed for the button and apply some base properties. All buttons start here * @method _fnButtonBase * @param {o} oConfig Button configuration object * @returns {Node} DIV element for the button * @private */ "_fnButtonBase": function ( o, bCollectionButton ) { var sTag, sLiner, sClass; if ( bCollectionButton ) { sTag = o.sTag !== "default" ? o.sTag : this.s.tags.collection.button; sLiner = o.sLinerTag !== "default" ? o.sLiner : this.s.tags.collection.liner; sClass = this.classes.collection.buttons.normal; } else { sTag = o.sTag !== "default" ? o.sTag : this.s.tags.button; sLiner = o.sLinerTag !== "default" ? o.sLiner : this.s.tags.liner; sClass = this.classes.buttons.normal; } var nButton = document.createElement( sTag ), nSpan = document.createElement( sLiner ), masterS = this._fnGetMasterSettings(); nButton.className = sClass+" "+o.sButtonClass; nButton.setAttribute('id', "ToolTables_"+this.s.dt.sInstance+"_"+masterS.buttonCounter ); nButton.appendChild( nSpan ); nSpan.innerHTML = o.sButtonText; masterS.buttonCounter++; return nButton; }, /** * Get the settings object for the master instance. When more than one TableTools instance is * assigned to a DataTable, only one of them can be the 'master' (for the select rows). As such, * we will typically want to interact with that master for global properties. * @method _fnGetMasterSettings * @returns {Object} TableTools settings object * @private */ "_fnGetMasterSettings": function () { if ( this.s.master ) { return this.s; } else { /* Look for the master which has the same DT as this one */ var instances = TableTools._aInstances; for ( var i=0, iLen=instances.length ; i<iLen ; i++ ) { if ( this.dom.table == instances[i].s.dt.nTable ) { return instances[i].s; } } } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Button collection functions */ /** * Create a collection button, when activated will present a drop down list of other buttons * @param {Node} nButton Button to use for the collection activation * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnCollectionConfig": function ( nButton, oConfig ) { var nHidden = document.createElement( this.s.tags.collection.container ); nHidden.style.display = "none"; nHidden.className = this.classes.collection.container; oConfig._collection = nHidden; document.body.appendChild( nHidden ); this._fnButtonDefinations( oConfig.aButtons, nHidden ); }, /** * Show a button collection * @param {Node} nButton Button to use for the collection * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnCollectionShow": function ( nButton, oConfig ) { var that = this, oPos = $(nButton).offset(), nHidden = oConfig._collection, iDivX = oPos.left, iDivY = oPos.top + $(nButton).outerHeight(), iWinHeight = $(window).height(), iDocHeight = $(document).height(), iWinWidth = $(window).width(), iDocWidth = $(document).width(); nHidden.style.position = "absolute"; nHidden.style.left = iDivX+"px"; nHidden.style.top = iDivY+"px"; nHidden.style.display = "block"; $(nHidden).css('opacity',0); var nBackground = document.createElement('div'); nBackground.style.position = "absolute"; nBackground.style.left = "0px"; nBackground.style.top = "0px"; nBackground.style.height = ((iWinHeight>iDocHeight)? iWinHeight : iDocHeight) +"px"; nBackground.style.width = ((iWinWidth>iDocWidth)? iWinWidth : iDocWidth) +"px"; nBackground.className = this.classes.collection.background; $(nBackground).css('opacity',0); document.body.appendChild( nBackground ); document.body.appendChild( nHidden ); /* Visual corrections to try and keep the collection visible */ var iDivWidth = $(nHidden).outerWidth(); var iDivHeight = $(nHidden).outerHeight(); if ( iDivX + iDivWidth > iDocWidth ) { nHidden.style.left = (iDocWidth-iDivWidth)+"px"; } if ( iDivY + iDivHeight > iDocHeight ) { nHidden.style.top = (iDivY-iDivHeight-$(nButton).outerHeight())+"px"; } this.dom.collection.collection = nHidden; this.dom.collection.background = nBackground; /* This results in a very small delay for the end user but it allows the animation to be * much smoother. If you don't want the animation, then the setTimeout can be removed */ setTimeout( function () { $(nHidden).animate({"opacity": 1}, 500); $(nBackground).animate({"opacity": 0.25}, 500); }, 10 ); /* Resize the buttons to the Flash contents fit */ this.fnResizeButtons(); /* Event handler to remove the collection display */ $(nBackground).click( function () { that._fnCollectionHide.call( that, null, null ); } ); }, /** * Hide a button collection * @param {Node} nButton Button to use for the collection * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnCollectionHide": function ( nButton, oConfig ) { if ( oConfig !== null && oConfig.sExtends == 'collection' ) { return; } if ( this.dom.collection.collection !== null ) { $(this.dom.collection.collection).animate({"opacity": 0}, 500, function (e) { this.style.display = "none"; } ); $(this.dom.collection.background).animate({"opacity": 0}, 500, function (e) { this.parentNode.removeChild( this ); } ); this.dom.collection.collection = null; this.dom.collection.background = null; } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Row selection functions */ /** * Add event handlers to a table to allow for row selection * @method _fnRowSelectConfig * @returns void * @private */ "_fnRowSelectConfig": function () { if ( this.s.master ) { var that = this, i, iLen, dt = this.s.dt, aoOpenRows = this.s.dt.aoOpenRows; $(dt.nTable).addClass( this.classes.select.table ); $('tr', dt.nTBody).live( 'click', function(e) { /* Sub-table must be ignored (odd that the selector won't do this with >) */ if ( this.parentNode != dt.nTBody ) { return; } /* Check that we are actually working with a DataTables controlled row */ if ( dt.oInstance.fnGetData(this) === null ) { return; } if ( that.fnIsSelected( this ) ) { that._fnRowDeselect( this, e ); } else if ( that.s.select.type == "single" ) { that.fnSelectNone(); that._fnRowSelect( this, e ); } else if ( that.s.select.type == "multi" ) { that._fnRowSelect( this, e ); } } ); // Bind a listener to the DataTable for when new rows are created. // This allows rows to be visually selected when they should be and // deferred rendering is used. dt.oApi._fnCallbackReg( dt, 'aoRowCreatedCallback', function (tr, data, index) { if ( dt.aoData[index]._DTTT_selected ) { $(tr).addClass( that.classes.select.row ); } }, 'TableTools-SelectAll' ); } }, /** * Select rows * @param {*} src Rows to select - see _fnSelectData for a description of valid inputs * @private */ "_fnRowSelect": function ( src, e ) { var that = this, data = this._fnSelectData( src ), firstTr = data.length===0 ? null : data[0].nTr, anSelected = [], i, len; // Get all the rows that will be selected for ( i=0, len=data.length ; i<len ; i++ ) { if ( data[i].nTr ) { anSelected.push( data[i].nTr ); } } // User defined pre-selection function if ( this.s.select.preRowSelect !== null && !this.s.select.preRowSelect.call(this, e, anSelected, true) ) { return; } // Mark them as selected for ( i=0, len=data.length ; i<len ; i++ ) { data[i]._DTTT_selected = true; if ( data[i].nTr ) { $(data[i].nTr).addClass( that.classes.select.row ); } } // Post-selection function if ( this.s.select.postSelected !== null ) { this.s.select.postSelected.call( this, anSelected ); } TableTools._fnEventDispatch( this, 'select', anSelected, true ); }, /** * Deselect rows * @param {*} src Rows to deselect - see _fnSelectData for a description of valid inputs * @private */ "_fnRowDeselect": function ( src, e ) { var that = this, data = this._fnSelectData( src ), firstTr = data.length===0 ? null : data[0].nTr, anDeselectedTrs = [], i, len; // Get all the rows that will be deselected for ( i=0, len=data.length ; i<len ; i++ ) { if ( data[i].nTr ) { anDeselectedTrs.push( data[i].nTr ); } } // User defined pre-selection function if ( this.s.select.preRowSelect !== null && !this.s.select.preRowSelect.call(this, e, anDeselectedTrs, false) ) { return; } // Mark them as deselected for ( i=0, len=data.length ; i<len ; i++ ) { data[i]._DTTT_selected = false; if ( data[i].nTr ) { $(data[i].nTr).removeClass( that.classes.select.row ); } } // Post-deselection function if ( this.s.select.postDeselected !== null ) { this.s.select.postDeselected.call( this, anDeselectedTrs ); } TableTools._fnEventDispatch( this, 'select', anDeselectedTrs, false ); }, /** * Take a data source for row selection and convert it into aoData points for the DT * @param {*} src Can be a single DOM TR node, an array of TR nodes (including a * a jQuery object), a single aoData point from DataTables, an array of aoData * points or an array of aoData indexes * @returns {array} An array of aoData points */ "_fnSelectData": function ( src ) { var out = [], pos, i, iLen; if ( src.nodeName ) { // Single node pos = this.s.dt.oInstance.fnGetPosition( src ); out.push( this.s.dt.aoData[pos] ); } else if ( typeof src.length !== 'undefined' ) { // jQuery object or an array of nodes, or aoData points for ( i=0, iLen=src.length ; i<iLen ; i++ ) { if ( src[i].nodeName ) { pos = this.s.dt.oInstance.fnGetPosition( src[i] ); out.push( this.s.dt.aoData[pos] ); } else if ( typeof src[i] === 'number' ) { out.push( this.s.dt.aoData[ src[i] ] ); } else { out.push( src[i] ); } } return out; } else { // A single aoData point out.push( src ); } return out; }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Text button functions */ /** * Configure a text based button for interaction events * @method _fnTextConfig * @param {Node} nButton Button element which is being considered * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnTextConfig": function ( nButton, oConfig ) { var that = this; if ( oConfig.fnInit !== null ) { oConfig.fnInit.call( this, nButton, oConfig ); } if ( oConfig.sToolTip !== "" ) { nButton.title = oConfig.sToolTip; } $(nButton).hover( function () { if ( oConfig.fnMouseover !== null ) { oConfig.fnMouseover.call( this, nButton, oConfig, null ); } }, function () { if ( oConfig.fnMouseout !== null ) { oConfig.fnMouseout.call( this, nButton, oConfig, null ); } } ); if ( oConfig.fnSelect !== null ) { TableTools._fnEventListen( this, 'select', function (n) { oConfig.fnSelect.call( that, nButton, oConfig, n ); } ); } $(nButton).click( function (e) { //e.preventDefault(); if ( oConfig.fnClick !== null ) { oConfig.fnClick.call( that, nButton, oConfig, null ); } /* Provide a complete function to match the behaviour of the flash elements */ if ( oConfig.fnComplete !== null ) { oConfig.fnComplete.call( that, nButton, oConfig, null, null ); } that._fnCollectionHide( nButton, oConfig ); } ); }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Flash button functions */ /** * Configure a flash based button for interaction events * @method _fnFlashConfig * @param {Node} nButton Button element which is being considered * @param {o} oConfig Button configuration object * @returns void * @private */ "_fnFlashConfig": function ( nButton, oConfig ) { var that = this; var flash = new ZeroClipboard_TableTools.Client(); if ( oConfig.fnInit !== null ) { oConfig.fnInit.call( this, nButton, oConfig ); } flash.setHandCursor( true ); if ( oConfig.sAction == "flash_save" ) { flash.setAction( 'save' ); flash.setCharSet( (oConfig.sCharSet=="utf16le") ? 'UTF16LE' : 'UTF8' ); flash.setBomInc( oConfig.bBomInc ); flash.setFileName( oConfig.sFileName.replace('*', this.fnGetTitle(oConfig)) ); } else if ( oConfig.sAction == "flash_pdf" ) { flash.setAction( 'pdf' ); flash.setFileName( oConfig.sFileName.replace('*', this.fnGetTitle(oConfig)) ); } else { flash.setAction( 'copy' ); } flash.addEventListener('mouseOver', function(client) { if ( oConfig.fnMouseover !== null ) { oConfig.fnMouseover.call( that, nButton, oConfig, flash ); } } ); flash.addEventListener('mouseOut', function(client) { if ( oConfig.fnMouseout !== null ) { oConfig.fnMouseout.call( that, nButton, oConfig, flash ); } } ); flash.addEventListener('mouseDown', function(client) { if ( oConfig.fnClick !== null ) { oConfig.fnClick.call( that, nButton, oConfig, flash ); } } ); flash.addEventListener('complete', function (client, text) { if ( oConfig.fnComplete !== null ) { oConfig.fnComplete.call( that, nButton, oConfig, flash, text ); } that._fnCollectionHide( nButton, oConfig ); } ); this._fnFlashGlue( flash, nButton, oConfig.sToolTip ); }, /** * Wait until the id is in the DOM before we "glue" the swf. Note that this function will call * itself (using setTimeout) until it completes successfully * @method _fnFlashGlue * @param {Object} clip Zero clipboard object * @param {Node} node node to glue swf to * @param {String} text title of the flash movie * @returns void * @private */ "_fnFlashGlue": function ( flash, node, text ) { var that = this; var id = node.getAttribute('id'); if ( document.getElementById(id) ) { flash.glue( node, text ); } else { setTimeout( function () { that._fnFlashGlue( flash, node, text ); }, 100 ); } }, /** * Set the text for the flash clip to deal with * * This function is required for large information sets. There is a limit on the * amount of data that can be transferred between Javascript and Flash in a single call, so * we use this method to build up the text in Flash by sending over chunks. It is estimated * that the data limit is around 64k, although it is undocumented, and appears to be different * between different flash versions. We chunk at 8KiB. * @method _fnFlashSetText * @param {Object} clip the ZeroClipboard object * @param {String} sData the data to be set * @returns void * @private */ "_fnFlashSetText": function ( clip, sData ) { var asData = this._fnChunkData( sData, 8192 ); clip.clearText(); for ( var i=0, iLen=asData.length ; i<iLen ; i++ ) { clip.appendText( asData[i] ); } }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Data retrieval functions */ /** * Convert the mixed columns variable into a boolean array the same size as the columns, which * indicates which columns we want to include * @method _fnColumnTargets * @param {String|Array} mColumns The columns to be included in data retrieval. If a string * then it can take the value of "visible" or "hidden" (to include all visible or * hidden columns respectively). Or an array of column indexes * @returns {Array} A boolean array the length of the columns of the table, which each value * indicating if the column is to be included or not * @private */ "_fnColumnTargets": function ( mColumns ) { var aColumns = []; var dt = this.s.dt; if ( typeof mColumns == "object" ) { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( false ); } for ( i=0, iLen=mColumns.length ; i<iLen ; i++ ) { aColumns[ mColumns[i] ] = true; } } else if ( mColumns == "visible" ) { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( dt.aoColumns[i].bVisible ? true : false ); } } else if ( mColumns == "hidden" ) { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( dt.aoColumns[i].bVisible ? false : true ); } } else if ( mColumns == "sortable" ) { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( dt.aoColumns[i].bSortable ? true : false ); } } else /* all */ { for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { aColumns.push( true ); } } return aColumns; }, /** * New line character(s) depend on the platforms * @method method * @param {Object} oConfig Button configuration object - only interested in oConfig.sNewLine * @returns {String} Newline character */ "_fnNewline": function ( oConfig ) { if ( oConfig.sNewLine == "auto" ) { return navigator.userAgent.match(/Windows/) ? "\r\n" : "\n"; } else { return oConfig.sNewLine; } }, /** * Get data from DataTables' internals and format it for output * @method _fnGetDataTablesData * @param {Object} oConfig Button configuration object * @param {String} oConfig.sFieldBoundary Field boundary for the data cells in the string * @param {String} oConfig.sFieldSeperator Field separator for the data cells * @param {String} oConfig.sNewline New line options * @param {Mixed} oConfig.mColumns Which columns should be included in the output * @param {Boolean} oConfig.bHeader Include the header * @param {Boolean} oConfig.bFooter Include the footer * @param {Boolean} oConfig.bSelectedOnly Include only the selected rows in the output * @returns {String} Concatenated string of data * @private */ "_fnGetDataTablesData": function ( oConfig ) { var i, iLen, j, jLen; var aRow, aData=[], sLoopData='', arr; var dt = this.s.dt, tr, child; var regex = new RegExp(oConfig.sFieldBoundary, "g"); /* Do it here for speed */ var aColumnsInc = this._fnColumnTargets( oConfig.mColumns ); var bSelectedOnly = (typeof oConfig.bSelectedOnly != 'undefined') ? oConfig.bSelectedOnly : false; /* * Header */ if ( oConfig.bHeader ) { aRow = []; for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { if ( aColumnsInc[i] ) { sLoopData = dt.aoColumns[i].sTitle.replace(/\n/g," ").replace( /<.*?>/g, "" ).replace(/^\s+|\s+$/g,""); sLoopData = this._fnHtmlDecode( sLoopData ); aRow.push( this._fnBoundData( sLoopData, oConfig.sFieldBoundary, regex ) ); } } aData.push( aRow.join(oConfig.sFieldSeperator) ); } /* * Body */ var aDataIndex = dt.aiDisplay; var aSelected = this.fnGetSelected(); if ( this.s.select.type !== "none" && bSelectedOnly && aSelected.length !== 0 ) { aDataIndex = []; for ( i=0, iLen=aSelected.length ; i<iLen ; i++ ) { aDataIndex.push( dt.oInstance.fnGetPosition( aSelected[i] ) ); } } for ( j=0, jLen=aDataIndex.length ; j<jLen ; j++ ) { tr = dt.aoData[ aDataIndex[j] ].nTr; aRow = []; /* Columns */ for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { if ( aColumnsInc[i] ) { /* Convert to strings (with small optimisation) */ var mTypeData = dt.oApi._fnGetCellData( dt, aDataIndex[j], i, 'display' ); if ( oConfig.fnCellRender ) { sLoopData = oConfig.fnCellRender( mTypeData, i, tr, aDataIndex[j] )+""; } else if ( typeof mTypeData == "string" ) { /* Strip newlines, replace img tags with alt attr. and finally strip html... */ sLoopData = mTypeData.replace(/\n/g," "); sLoopData = sLoopData.replace(/<img.*?\s+alt\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s>]+)).*?>/gi, '$1$2$3'); sLoopData = sLoopData.replace( /<.*?>/g, "" ); } else { sLoopData = mTypeData+""; } /* Trim and clean the data */ sLoopData = sLoopData.replace(/^\s+/, '').replace(/\s+$/, ''); sLoopData = this._fnHtmlDecode( sLoopData ); /* Bound it and add it to the total data */ aRow.push( this._fnBoundData( sLoopData, oConfig.sFieldBoundary, regex ) ); } } aData.push( aRow.join(oConfig.sFieldSeperator) ); /* Details rows from fnOpen */ if ( oConfig.bOpenRows ) { arr = $.grep(dt.aoOpenRows, function(o) { return o.nParent === tr; }); if ( arr.length === 1 ) { sLoopData = this._fnBoundData( $('td', arr[0].nTr).html(), oConfig.sFieldBoundary, regex ); aData.push( sLoopData ); } } } /* * Footer */ if ( oConfig.bFooter && dt.nTFoot !== null ) { aRow = []; for ( i=0, iLen=dt.aoColumns.length ; i<iLen ; i++ ) { if ( aColumnsInc[i] && dt.aoColumns[i].nTf !== null ) { sLoopData = dt.aoColumns[i].nTf.innerHTML.replace(/\n/g," ").replace( /<.*?>/g, "" ); sLoopData = this._fnHtmlDecode( sLoopData ); aRow.push( this._fnBoundData( sLoopData, oConfig.sFieldBoundary, regex ) ); } } aData.push( aRow.join(oConfig.sFieldSeperator) ); } _sLastData = aData.join( this._fnNewline(oConfig) ); return _sLastData; }, /** * Wrap data up with a boundary string * @method _fnBoundData * @param {String} sData data to bound * @param {String} sBoundary bounding char(s) * @param {RegExp} regex search for the bounding chars - constructed outside for efficiency * in the loop * @returns {String} bound data * @private */ "_fnBoundData": function ( sData, sBoundary, regex ) { if ( sBoundary === "" ) { return sData; } else { return sBoundary + sData.replace(regex, sBoundary+sBoundary) + sBoundary; } }, /** * Break a string up into an array of smaller strings * @method _fnChunkData * @param {String} sData data to be broken up * @param {Int} iSize chunk size * @returns {Array} String array of broken up text * @private */ "_fnChunkData": function ( sData, iSize ) { var asReturn = []; var iStrlen = sData.length; for ( var i=0 ; i<iStrlen ; i+=iSize ) { if ( i+iSize < iStrlen ) { asReturn.push( sData.substring( i, i+iSize ) ); } else { asReturn.push( sData.substring( i, iStrlen ) ); } } return asReturn; }, /** * Decode HTML entities * @method _fnHtmlDecode * @param {String} sData encoded string * @returns {String} decoded string * @private */ "_fnHtmlDecode": function ( sData ) { if ( sData.indexOf('&') === -1 ) { return sData; } var n = document.createElement('div'); return sData.replace( /&([^\s]*);/g, function( match, match2 ) { if ( match.substr(1, 1) === '#' ) { return String.fromCharCode( Number(match2.substr(1)) ); } else { n.innerHTML = match; return n.childNodes[0].nodeValue; } } ); }, /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Printing functions */ /** * Show print display * @method _fnPrintStart * @param {Event} e Event object * @param {Object} oConfig Button configuration object * @returns void * @private */ "_fnPrintStart": function ( oConfig ) { var that = this; var oSetDT = this.s.dt; /* Parse through the DOM hiding everything that isn't needed for the table */ this._fnPrintHideNodes( oSetDT.nTable ); /* Show the whole table */ this.s.print.saveStart = oSetDT._iDisplayStart; this.s.print.saveLength = oSetDT._iDisplayLength; if ( oConfig.bShowAll ) { oSetDT._iDisplayStart = 0; oSetDT._iDisplayLength = -1; oSetDT.oApi._fnCalculateEnd( oSetDT ); oSetDT.oApi._fnDraw( oSetDT ); } /* Adjust the display for scrolling which might be done by DataTables */ if ( oSetDT.oScroll.sX !== "" || oSetDT.oScroll.sY !== "" ) { this._fnPrintScrollStart( oSetDT ); // If the table redraws while in print view, the DataTables scrolling // setup would hide the header, so we need to readd it on draw $(this.s.dt.nTable).bind('draw.DTTT_Print', function () { that._fnPrintScrollStart( oSetDT ); } ); } /* Remove the other DataTables feature nodes - but leave the table! and info div */ var anFeature = oSetDT.aanFeatures; for ( var cFeature in anFeature ) { if ( cFeature != 'i' && cFeature != 't' && cFeature.length == 1 ) { for ( var i=0, iLen=anFeature[cFeature].length ; i<iLen ; i++ ) { this.dom.print.hidden.push( { "node": anFeature[cFeature][i], "display": "block" } ); anFeature[cFeature][i].style.display = "none"; } } } /* Print class can be used for styling */ $(document.body).addClass( this.classes.print.body ); /* Show information message to let the user know what is happening */ if ( oConfig.sInfo !== "" ) { this.fnInfo( oConfig.sInfo, 3000 ); } /* Add a message at the top of the page */ if ( oConfig.sMessage ) { this.dom.print.message = document.createElement( "div" ); this.dom.print.message.className = this.classes.print.message; this.dom.print.message.innerHTML = oConfig.sMessage; document.body.insertBefore( this.dom.print.message, document.body.childNodes[0] ); } /* Cache the scrolling and the jump to the top of the page */ this.s.print.saveScroll = $(window).scrollTop(); window.scrollTo( 0, 0 ); /* Bind a key event listener to the document for the escape key - * it is removed in the callback */ $(document).bind( "keydown.DTTT", function(e) { /* Only interested in the escape key */ if ( e.keyCode == 27 ) { e.preventDefault(); that._fnPrintEnd.call( that, e ); } } ); }, /** * Printing is finished, resume normal display * @method _fnPrintEnd * @param {Event} e Event object * @returns void * @private */ "_fnPrintEnd": function ( e ) { var that = this; var oSetDT = this.s.dt; var oSetPrint = this.s.print; var oDomPrint = this.dom.print; /* Show all hidden nodes */ this._fnPrintShowNodes(); /* Restore DataTables' scrolling */ if ( oSetDT.oScroll.sX !== "" || oSetDT.oScroll.sY !== "" ) { $(this.s.dt.nTable).unbind('draw.DTTT_Print'); this._fnPrintScrollEnd(); } /* Restore the scroll */ window.scrollTo( 0, oSetPrint.saveScroll ); /* Drop the print message */ if ( oDomPrint.message !== null ) { document.body.removeChild( oDomPrint.message ); oDomPrint.message = null; } /* Styling class */ $(document.body).removeClass( 'DTTT_Print' ); /* Restore the table length */ oSetDT._iDisplayStart = oSetPrint.saveStart; oSetDT._iDisplayLength = oSetPrint.saveLength; oSetDT.oApi._fnCalculateEnd( oSetDT ); oSetDT.oApi._fnDraw( oSetDT ); $(document).unbind( "keydown.DTTT" ); }, /** * Take account of scrolling in DataTables by showing the full table * @returns void * @private */ "_fnPrintScrollStart": function () { var oSetDT = this.s.dt, nScrollHeadInner = oSetDT.nScrollHead.getElementsByTagName('div')[0], nScrollHeadTable = nScrollHeadInner.getElementsByTagName('table')[0], nScrollBody = oSetDT.nTable.parentNode; /* Copy the header in the thead in the body table, this way we show one single table when * in print view. Note that this section of code is more or less verbatim from DT 1.7.0 */ var nTheadSize = oSetDT.nTable.getElementsByTagName('thead'); if ( nTheadSize.length > 0 ) { oSetDT.nTable.removeChild( nTheadSize[0] ); } if ( oSetDT.nTFoot !== null ) { var nTfootSize = oSetDT.nTable.getElementsByTagName('tfoot'); if ( nTfootSize.length > 0 ) { oSetDT.nTable.removeChild( nTfootSize[0] ); } } nTheadSize = oSetDT.nTHead.cloneNode(true); oSetDT.nTable.insertBefore( nTheadSize, oSetDT.nTable.childNodes[0] ); if ( oSetDT.nTFoot !== null ) { nTfootSize = oSetDT.nTFoot.cloneNode(true); oSetDT.nTable.insertBefore( nTfootSize, oSetDT.nTable.childNodes[1] ); } /* Now adjust the table's viewport so we can actually see it */ if ( oSetDT.oScroll.sX !== "" ) { oSetDT.nTable.style.width = $(oSetDT.nTable).outerWidth()+"px"; nScrollBody.style.width = $(oSetDT.nTable).outerWidth()+"px"; nScrollBody.style.overflow = "visible"; } if ( oSetDT.oScroll.sY !== "" ) { nScrollBody.style.height = $(oSetDT.nTable).outerHeight()+"px"; nScrollBody.style.overflow = "visible"; } }, /** * Take account of scrolling in DataTables by showing the full table. Note that the redraw of * the DataTable that we do will actually deal with the majority of the hard work here * @returns void * @private */ "_fnPrintScrollEnd": function () { var oSetDT = this.s.dt, nScrollBody = oSetDT.nTable.parentNode; if ( oSetDT.oScroll.sX !== "" ) { nScrollBody.style.width = oSetDT.oApi._fnStringToCss( oSetDT.oScroll.sX ); nScrollBody.style.overflow = "auto"; } if ( oSetDT.oScroll.sY !== "" ) { nScrollBody.style.height = oSetDT.oApi._fnStringToCss( oSetDT.oScroll.sY ); nScrollBody.style.overflow = "auto"; } }, /** * Resume the display of all TableTools hidden nodes * @method _fnPrintShowNodes * @returns void * @private */ "_fnPrintShowNodes": function ( ) { var anHidden = this.dom.print.hidden; for ( var i=0, iLen=anHidden.length ; i<iLen ; i++ ) { anHidden[i].node.style.display = anHidden[i].display; } anHidden.splice( 0, anHidden.length ); }, /** * Hide nodes which are not needed in order to display the table. Note that this function is * recursive * @method _fnPrintHideNodes * @param {Node} nNode Element which should be showing in a 'print' display * @returns void * @private */ "_fnPrintHideNodes": function ( nNode ) { var anHidden = this.dom.print.hidden; var nParent = nNode.parentNode; var nChildren = nParent.childNodes; for ( var i=0, iLen=nChildren.length ; i<iLen ; i++ ) { if ( nChildren[i] != nNode && nChildren[i].nodeType == 1 ) { /* If our node is shown (don't want to show nodes which were previously hidden) */ var sDisplay = $(nChildren[i]).css("display"); if ( sDisplay != "none" ) { /* Cache the node and it's previous state so we can restore it */ anHidden.push( { "node": nChildren[i], "display": sDisplay } ); nChildren[i].style.display = "none"; } } } if ( nParent.nodeName != "BODY" ) { this._fnPrintHideNodes( nParent ); } } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static variables * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Store of all instances that have been created of TableTools, so one can look up other (when * there is need of a master) * @property _aInstances * @type Array * @default [] * @private */ TableTools._aInstances = []; /** * Store of all listeners and their callback functions * @property _aListeners * @type Array * @default [] */ TableTools._aListeners = []; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Static methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * Get an array of all the master instances * @method fnGetMasters * @returns {Array} List of master TableTools instances * @static */ TableTools.fnGetMasters = function () { var a = []; for ( var i=0, iLen=TableTools._aInstances.length ; i<iLen ; i++ ) { if ( TableTools._aInstances[i].s.master ) { a.push( TableTools._aInstances[i] ); } } return a; }; /** * Get the master instance for a table node (or id if a string is given) * @method fnGetInstance * @returns {Object} ID of table OR table node, for which we want the TableTools instance * @static */ TableTools.fnGetInstance = function ( node ) { if ( typeof node != 'object' ) { node = document.getElementById(node); } for ( var i=0, iLen=TableTools._aInstances.length ; i<iLen ; i++ ) { if ( TableTools._aInstances[i].s.master && TableTools._aInstances[i].dom.table == node ) { return TableTools._aInstances[i]; } } return null; }; /** * Add a listener for a specific event * @method _fnEventListen * @param {Object} that Scope of the listening function (i.e. 'this' in the caller) * @param {String} type Event type * @param {Function} fn Function * @returns void * @private * @static */ TableTools._fnEventListen = function ( that, type, fn ) { TableTools._aListeners.push( { "that": that, "type": type, "fn": fn } ); }; /** * An event has occurred - look up every listener and fire it off. We check that the event we are * going to fire is attached to the same table (using the table node as reference) before firing * @method _fnEventDispatch * @param {Object} that Scope of the listening function (i.e. 'this' in the caller) * @param {String} type Event type * @param {Node} node Element that the event occurred on (may be null) * @param {boolean} [selected] Indicate if the node was selected (true) or deselected (false) * @returns void * @private * @static */ TableTools._fnEventDispatch = function ( that, type, node, selected ) { var listeners = TableTools._aListeners; for ( var i=0, iLen=listeners.length ; i<iLen ; i++ ) { if ( that.dom.table == listeners[i].that.dom.table && listeners[i].type == type ) { listeners[i].fn( node, selected ); } } }; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Constants * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ TableTools.buttonBase = { // Button base "sAction": "text", "sTag": "default", "sLinerTag": "default", "sButtonClass": "DTTT_button_text", "sButtonText": "Button text", "sTitle": "", "sToolTip": "", // Common button specific options "sCharSet": "utf8", "bBomInc": false, "sFileName": "*.csv", "sFieldBoundary": "", "sFieldSeperator": "\t", "sNewLine": "auto", "mColumns": "all", /* "all", "visible", "hidden" or array of column integers */ "bHeader": true, "bFooter": true, "bOpenRows": false, "bSelectedOnly": false, // Callbacks "fnMouseover": null, "fnMouseout": null, "fnClick": null, "fnSelect": null, "fnComplete": null, "fnInit": null, "fnCellRender": null }; /** * @namespace Default button configurations */ TableTools.BUTTONS = { "csv": $.extend( {}, TableTools.buttonBase, { "sAction": "flash_save", "sButtonClass": "DTTT_button_csv", "sButtonText": "CSV", "sFieldBoundary": '"', "sFieldSeperator": ",", "fnClick": function( nButton, oConfig, flash ) { this.fnSetText( flash, this.fnGetTableData(oConfig) ); } } ), "xls": $.extend( {}, TableTools.buttonBase, { "sAction": "flash_save", "sCharSet": "utf16le", "bBomInc": true, "sButtonClass": "DTTT_button_xls", "sButtonText": "Excel", "fnClick": function( nButton, oConfig, flash ) { this.fnSetText( flash, this.fnGetTableData(oConfig) ); } } ), "copy": $.extend( {}, TableTools.buttonBase, { "sAction": "flash_copy", "sButtonClass": "DTTT_button_copy", "sButtonText": "Copy", "fnClick": function( nButton, oConfig, flash ) { this.fnSetText( flash, this.fnGetTableData(oConfig) ); }, "fnComplete": function(nButton, oConfig, flash, text) { var lines = text.split('\n').length, len = this.s.dt.nTFoot === null ? lines-1 : lines-2, plural = (len==1) ? "" : "s"; this.fnInfo( '<h6>Table copied</h6>'+ '<p>Copied '+len+' row'+plural+' to the clipboard.</p>', 1500 ); } } ), "pdf": $.extend( {}, TableTools.buttonBase, { "sAction": "flash_pdf", "sNewLine": "\n", "sFileName": "*.pdf", "sButtonClass": "DTTT_button_pdf", "sButtonText": "PDF", "sPdfOrientation": "portrait", "sPdfSize": "A4", "sPdfMessage": "", "fnClick": function( nButton, oConfig, flash ) { this.fnSetText( flash, "title:"+ this.fnGetTitle(oConfig) +"\n"+ "message:"+ oConfig.sPdfMessage +"\n"+ "colWidth:"+ this.fnCalcColRatios(oConfig) +"\n"+ "orientation:"+ oConfig.sPdfOrientation +"\n"+ "size:"+ oConfig.sPdfSize +"\n"+ "--/TableToolsOpts--\n" + this.fnGetTableData(oConfig) ); } } ), "print": $.extend( {}, TableTools.buttonBase, { "sInfo": "<h6>Print view</h6><p>Please use your browser's print function to "+ "print this table. Press escape when finished.", "sMessage": null, "bShowAll": true, "sToolTip": "View print view", "sButtonClass": "DTTT_button_print", "sButtonText": "Print", "fnClick": function ( nButton, oConfig ) { this.fnPrint( true, oConfig ); } } ), "text": $.extend( {}, TableTools.buttonBase ), "select": $.extend( {}, TableTools.buttonBase, { "sButtonText": "Select button", "fnSelect": function( nButton, oConfig ) { if ( this.fnGetSelected().length !== 0 ) { $(nButton).removeClass( this.classes.buttons.disabled ); } else { $(nButton).addClass( this.classes.buttons.disabled ); } }, "fnInit": function( nButton, oConfig ) { $(nButton).addClass( this.classes.buttons.disabled ); } } ), "select_single": $.extend( {}, TableTools.buttonBase, { "sButtonText": "Select button", "fnSelect": function( nButton, oConfig ) { var iSelected = this.fnGetSelected().length; if ( iSelected == 1 ) { $(nButton).removeClass( this.classes.buttons.disabled ); } else { $(nButton).addClass( this.classes.buttons.disabled ); } }, "fnInit": function( nButton, oConfig ) { $(nButton).addClass( this.classes.buttons.disabled ); } } ), "select_all": $.extend( {}, TableTools.buttonBase, { "sButtonText": "Select all", "fnClick": function( nButton, oConfig ) { this.fnSelectAll(); }, "fnSelect": function( nButton, oConfig ) { if ( this.fnGetSelected().length == this.s.dt.fnRecordsDisplay() ) { $(nButton).addClass( this.classes.buttons.disabled ); } else { $(nButton).removeClass( this.classes.buttons.disabled ); } } } ), "select_none": $.extend( {}, TableTools.buttonBase, { "sButtonText": "Deselect all", "fnClick": function( nButton, oConfig ) { this.fnSelectNone(); }, "fnSelect": function( nButton, oConfig ) { if ( this.fnGetSelected().length !== 0 ) { $(nButton).removeClass( this.classes.buttons.disabled ); } else { $(nButton).addClass( this.classes.buttons.disabled ); } }, "fnInit": function( nButton, oConfig ) { $(nButton).addClass( this.classes.buttons.disabled ); } } ), "ajax": $.extend( {}, TableTools.buttonBase, { "sAjaxUrl": "/xhr.php", "sButtonText": "Ajax button", "fnClick": function( nButton, oConfig ) { var sData = this.fnGetTableData(oConfig); $.ajax( { "url": oConfig.sAjaxUrl, "data": [ { "name": "tableData", "value": sData } ], "success": oConfig.fnAjaxComplete, "dataType": "json", "type": "POST", "cache": false, "error": function () { alert( "Error detected when sending table data to server" ); } } ); }, "fnAjaxComplete": function( json ) { alert( 'Ajax complete' ); } } ), "div": $.extend( {}, TableTools.buttonBase, { "sAction": "div", "sTag": "div", "sButtonClass": "DTTT_nonbutton", "sButtonText": "Text button" } ), "collection": $.extend( {}, TableTools.buttonBase, { "sAction": "collection", "sButtonClass": "DTTT_button_collection", "sButtonText": "Collection", "fnClick": function( nButton, oConfig ) { this._fnCollectionShow(nButton, oConfig); } } ) }; /* * on* callback parameters: * 1. node - button element * 2. object - configuration object for this button * 3. object - ZeroClipboard reference (flash button only) * 4. string - Returned string from Flash (flash button only - and only on 'complete') */ /** * @namespace Classes used by TableTools - allows the styles to be override easily. * Note that when TableTools initialises it will take a copy of the classes object * and will use its internal copy for the remainder of its run time. */ TableTools.classes = { "container": "DTTT_container", "buttons": { "normal": "DTTT_button", "disabled": "DTTT_disabled" }, "collection": { "container": "DTTT_collection", "background": "DTTT_collection_background", "buttons": { "normal": "DTTT_button", "disabled": "DTTT_disabled" } }, "select": { "table": "DTTT_selectable", "row": "DTTT_selected" }, "print": { "body": "DTTT_Print", "info": "DTTT_print_info", "message": "DTTT_PrintMessage" } }; /** * @namespace ThemeRoller classes - built in for compatibility with DataTables' * bJQueryUI option. */ TableTools.classes_themeroller = { "container": "DTTT_container ui-buttonset ui-buttonset-multi", "buttons": { "normal": "DTTT_button ui-button ui-state-default" }, "collection": { "container": "DTTT_collection ui-buttonset ui-buttonset-multi" } }; /** * @namespace TableTools default settings for initialisation */ TableTools.DEFAULTS = { "sSwfPath": "media/swf/copy_csv_xls_pdf.swf", "sRowSelect": "none", "sSelectedClass": null, "fnPreRowSelect": null, "fnRowSelected": null, "fnRowDeselected": null, "aButtons": [ "copy", "csv", "xls", "pdf", "print" ], "oTags": { "container": "div", "button": "a", // We really want to use buttons here, but Firefox and IE ignore the // click on the Flash element in the button (but not mouse[in|out]). "liner": "span", "collection": { "container": "div", "button": "a", "liner": "span" } } }; /** * Name of this class * @constant CLASS * @type String * @default TableTools */ TableTools.prototype.CLASS = "TableTools"; /** * TableTools version * @constant VERSION * @type String * @default See code */ TableTools.VERSION = "2.1.4"; TableTools.prototype.VERSION = TableTools.VERSION; /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Initialisation * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * Register a new feature with DataTables */ if ( typeof $.fn.dataTable == "function" && typeof $.fn.dataTableExt.fnVersionCheck == "function" && $.fn.dataTableExt.fnVersionCheck('1.9.0') ) { $.fn.dataTableExt.aoFeatures.push( { "fnInit": function( oDTSettings ) { var oOpts = typeof oDTSettings.oInit.oTableTools != 'undefined' ? oDTSettings.oInit.oTableTools : {}; var oTT = new TableTools( oDTSettings.oInstance, oOpts ); TableTools._aInstances.push( oTT ); return oTT.dom.container; }, "cFeature": "T", "sFeature": "TableTools" } ); } else { alert( "Warning: TableTools 2 requires DataTables 1.9.0 or newer - www.datatables.net/download"); } $.fn.DataTable.TableTools = TableTools; })(jQuery, window, document);
JavaScript
(function() { "use strict"; var match = /(\{.*\})/.exec(document.body.innerHTML); if (match) { parent.postMessage(match[1], "*"); } }());
JavaScript
/*! * Fine Uploader * * Copyright 2013, Widen Enterprises, Inc. info@fineuploader.com * * Version: 4.3.1 * * Homepage: http://fineuploader.com * * Repository: git://github.com/Widen/fine-uploader.git * * Licensed under GNU GPL v3, see LICENSE */ /*globals window, navigator, document, FormData, File, HTMLInputElement, XMLHttpRequest, Blob, Storage, ActiveXObject */ var qq = function(element) { "use strict"; return { hide: function() { element.style.display = "none"; return this; }, /** Returns the function which detaches attached event */ attach: function(type, fn) { if (element.addEventListener){ element.addEventListener(type, fn, false); } else if (element.attachEvent){ element.attachEvent("on" + type, fn); } return function() { qq(element).detach(type, fn); }; }, detach: function(type, fn) { if (element.removeEventListener){ element.removeEventListener(type, fn, false); } else if (element.attachEvent){ element.detachEvent("on" + type, fn); } return this; }, contains: function(descendant) { // The [W3C spec](http://www.w3.org/TR/domcore/#dom-node-contains) // says a `null` (or ostensibly `undefined`) parameter // passed into `Node.contains` should result in a false return value. // IE7 throws an exception if the parameter is `undefined` though. if (!descendant) { return false; } // compareposition returns false in this case if (element === descendant) { return true; } if (element.contains){ return element.contains(descendant); } else { /*jslint bitwise: true*/ return !!(descendant.compareDocumentPosition(element) & 8); } }, /** * Insert this element before elementB. */ insertBefore: function(elementB) { elementB.parentNode.insertBefore(element, elementB); return this; }, remove: function() { element.parentNode.removeChild(element); return this; }, /** * Sets styles for an element. * Fixes opacity in IE6-8. */ css: function(styles) { /*jshint eqnull: true*/ if (element.style == null) { throw new qq.Error("Can't apply style to node as it is not on the HTMLElement prototype chain!"); } /*jshint -W116*/ if (styles.opacity != null){ if (typeof element.style.opacity !== "string" && typeof(element.filters) !== "undefined"){ styles.filter = "alpha(opacity=" + Math.round(100 * styles.opacity) + ")"; } } qq.extend(element.style, styles); return this; }, hasClass: function(name) { var re = new RegExp("(^| )" + name + "( |$)"); return re.test(element.className); }, addClass: function(name) { if (!qq(element).hasClass(name)){ element.className += " " + name; } return this; }, removeClass: function(name) { var re = new RegExp("(^| )" + name + "( |$)"); element.className = element.className.replace(re, " ").replace(/^\s+|\s+$/g, ""); return this; }, getByClass: function(className) { var candidates, result = []; if (element.querySelectorAll){ return element.querySelectorAll("." + className); } candidates = element.getElementsByTagName("*"); qq.each(candidates, function(idx, val) { if (qq(val).hasClass(className)){ result.push(val); } }); return result; }, children: function() { var children = [], child = element.firstChild; while (child){ if (child.nodeType === 1){ children.push(child); } child = child.nextSibling; } return children; }, setText: function(text) { element.innerText = text; element.textContent = text; return this; }, clearText: function() { return qq(element).setText(""); }, // Returns true if the attribute exists on the element // AND the value of the attribute is NOT "false" (case-insensitive) hasAttribute: function(attrName) { var attrVal; if (element.hasAttribute) { if (!element.hasAttribute(attrName)) { return false; } /*jshint -W116*/ return (/^false$/i).exec(element.getAttribute(attrName)) == null; } else { attrVal = element[attrName]; if (attrVal === undefined) { return false; } /*jshint -W116*/ return (/^false$/i).exec(attrVal) == null; } } }; }; (function(){ "use strict"; qq.log = function(message, level) { if (window.console) { if (!level || level === "info") { window.console.log(message); } else { if (window.console[level]) { window.console[level](message); } else { window.console.log("<" + level + "> " + message); } } } }; qq.isObject = function(variable) { return variable && !variable.nodeType && Object.prototype.toString.call(variable) === "[object Object]"; }; qq.isFunction = function(variable) { return typeof(variable) === "function"; }; /** * Check the type of a value. Is it an "array"? * * @param value value to test. * @returns true if the value is an array or associated with an `ArrayBuffer` */ qq.isArray = function(value) { return Object.prototype.toString.call(value) === "[object Array]" || (value && window.ArrayBuffer && value.buffer && value.buffer.constructor === ArrayBuffer); }; // Looks for an object on a `DataTransfer` object that is associated with drop events when utilizing the Filesystem API. qq.isItemList = function(maybeItemList) { return Object.prototype.toString.call(maybeItemList) === "[object DataTransferItemList]"; }; // Looks for an object on a `NodeList` or an `HTMLCollection`|`HTMLFormElement`|`HTMLSelectElement` // object that is associated with collections of Nodes. qq.isNodeList = function(maybeNodeList) { return Object.prototype.toString.call(maybeNodeList) === "[object NodeList]" || // If `HTMLCollection` is the actual type of the object, we must determine this // by checking for expected properties/methods on the object (maybeNodeList.item && maybeNodeList.namedItem); }; qq.isString = function(maybeString) { return Object.prototype.toString.call(maybeString) === "[object String]"; }; qq.trimStr = function(string) { if (String.prototype.trim) { return string.trim(); } return string.replace(/^\s+|\s+$/g,""); }; /** * @param str String to format. * @returns {string} A string, swapping argument values with the associated occurrence of {} in the passed string. */ qq.format = function(str) { var args = Array.prototype.slice.call(arguments, 1), newStr = str, nextIdxToReplace = newStr.indexOf("{}"); qq.each(args, function(idx, val) { var strBefore = newStr.substring(0, nextIdxToReplace), strAfter = newStr.substring(nextIdxToReplace+2); newStr = strBefore + val + strAfter; nextIdxToReplace = newStr.indexOf("{}", nextIdxToReplace + val.length); // End the loop if we have run out of tokens (when the arguments exceed the # of tokens) if (nextIdxToReplace < 0) { return false; } }); return newStr; }; qq.isFile = function(maybeFile) { return window.File && Object.prototype.toString.call(maybeFile) === "[object File]"; }; qq.isFileList = function(maybeFileList) { return window.FileList && Object.prototype.toString.call(maybeFileList) === "[object FileList]"; }; qq.isFileOrInput = function(maybeFileOrInput) { return qq.isFile(maybeFileOrInput) || qq.isInput(maybeFileOrInput); }; qq.isInput = function(maybeInput, notFile) { var evaluateType = function(type) { var normalizedType = type.toLowerCase(); if (notFile) { return normalizedType !== "file"; } return normalizedType === "file"; }; if (window.HTMLInputElement) { if (Object.prototype.toString.call(maybeInput) === "[object HTMLInputElement]") { if (maybeInput.type && evaluateType(maybeInput.type)) { return true; } } } if (maybeInput.tagName) { if (maybeInput.tagName.toLowerCase() === "input") { if (maybeInput.type && evaluateType(maybeInput.type)) { return true; } } } return false; }; qq.isBlob = function(maybeBlob) { return window.Blob && Object.prototype.toString.call(maybeBlob) === "[object Blob]"; }; qq.isXhrUploadSupported = function() { var input = document.createElement("input"); input.type = "file"; return ( input.multiple !== undefined && typeof File !== "undefined" && typeof FormData !== "undefined" && typeof (qq.createXhrInstance()).upload !== "undefined" ); }; // Fall back to ActiveX is native XHR is disabled (possible in any version of IE). qq.createXhrInstance = function() { if (window.XMLHttpRequest) { return new XMLHttpRequest(); } try { return new ActiveXObject("MSXML2.XMLHTTP.3.0"); } catch(error) { qq.log("Neither XHR or ActiveX are supported!", "error"); return null; } }; qq.isFolderDropSupported = function(dataTransfer) { return (dataTransfer.items && dataTransfer.items[0].webkitGetAsEntry); }; qq.isFileChunkingSupported = function() { return !qq.android() && //android's impl of Blob.slice is broken qq.isXhrUploadSupported() && (File.prototype.slice !== undefined || File.prototype.webkitSlice !== undefined || File.prototype.mozSlice !== undefined); }; qq.sliceBlob = function(fileOrBlob, start, end) { var slicer = fileOrBlob.slice || fileOrBlob.mozSlice || fileOrBlob.webkitSlice; return slicer.call(fileOrBlob, start, end); }; qq.arrayBufferToHex = function(buffer) { var bytesAsHex = "", bytes = new Uint8Array(buffer); qq.each(bytes, function(idx, byte) { var byteAsHexStr = byte.toString(16); if (byteAsHexStr.length < 2) { byteAsHexStr = "0" + byteAsHexStr; } bytesAsHex += byteAsHexStr; }); return bytesAsHex; }; qq.readBlobToHex = function(blob, startOffset, length) { var initialBlob = qq.sliceBlob(blob, startOffset, startOffset + length), fileReader = new FileReader(), promise = new qq.Promise(); fileReader.onload = function() { promise.success(qq.arrayBufferToHex(fileReader.result)); }; fileReader.readAsArrayBuffer(initialBlob); return promise; }; qq.extend = function(first, second, extendNested) { qq.each(second, function(prop, val) { if (extendNested && qq.isObject(val)) { if (first[prop] === undefined) { first[prop] = {}; } qq.extend(first[prop], val, true); } else { first[prop] = val; } }); return first; }; /** * Allow properties in one object to override properties in another, * keeping track of the original values from the target object. * * Note that the pre-overriden properties to be overriden by the source will be passed into the `sourceFn` when it is invoked. * * @param target Update properties in this object from some source * @param sourceFn A function that, when invoked, will return properties that will replace properties with the same name in the target. * @returns {object} The target object */ qq.override = function(target, sourceFn) { var super_ = {}, source = sourceFn(super_); qq.each(source, function(srcPropName, srcPropVal) { if (target[srcPropName] !== undefined) { super_[srcPropName] = target[srcPropName]; } target[srcPropName] = srcPropVal; }); return target; }; /** * Searches for a given element in the array, returns -1 if it is not present. * @param {Number} [from] The index at which to begin the search */ qq.indexOf = function(arr, elt, from){ if (arr.indexOf) { return arr.indexOf(elt, from); } from = from || 0; var len = arr.length; if (from < 0) { from += len; } for (; from < len; from+=1){ if (arr.hasOwnProperty(from) && arr[from] === elt){ return from; } } return -1; }; //this is a version 4 UUID qq.getUniqueId = function(){ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) { /*jslint eqeq: true, bitwise: true*/ var r = Math.random()*16|0, v = c == "x" ? r : (r&0x3|0x8); return v.toString(16); }); }; // // Browsers and platforms detection qq.ie = function(){ return navigator.userAgent.indexOf("MSIE") !== -1; }; qq.ie7 = function(){ return navigator.userAgent.indexOf("MSIE 7") !== -1; }; qq.ie10 = function(){ return navigator.userAgent.indexOf("MSIE 10") !== -1; }; qq.ie11 = function(){ return (navigator.userAgent.indexOf("Trident") !== -1 && navigator.userAgent.indexOf("rv:11") !== -1); }; qq.safari = function(){ return navigator.vendor !== undefined && navigator.vendor.indexOf("Apple") !== -1; }; qq.chrome = function(){ return navigator.vendor !== undefined && navigator.vendor.indexOf("Google") !== -1; }; qq.opera = function(){ return navigator.vendor !== undefined && navigator.vendor.indexOf("Opera") !== -1; }; qq.firefox = function(){ return (!qq.ie11() && navigator.userAgent.indexOf("Mozilla") !== -1 && navigator.vendor !== undefined && navigator.vendor === ""); }; qq.windows = function(){ return navigator.platform === "Win32"; }; qq.android = function(){ return navigator.userAgent.toLowerCase().indexOf("android") !== -1; }; qq.ios7 = function() { return qq.ios() && navigator.userAgent.indexOf(" OS 7_") !== -1; }; qq.ios = function() { /*jshint -W014 */ return navigator.userAgent.indexOf("iPad") !== -1 || navigator.userAgent.indexOf("iPod") !== -1 || navigator.userAgent.indexOf("iPhone") !== -1; }; // // Events qq.preventDefault = function(e){ if (e.preventDefault){ e.preventDefault(); } else{ e.returnValue = false; } }; /** * Creates and returns element from html string * Uses innerHTML to create an element */ qq.toElement = (function(){ var div = document.createElement("div"); return function(html){ div.innerHTML = html; var element = div.firstChild; div.removeChild(element); return element; }; }()); //key and value are passed to callback for each entry in the iterable item qq.each = function(iterableItem, callback) { var keyOrIndex, retVal; if (iterableItem) { // Iterate through [`Storage`](http://www.w3.org/TR/webstorage/#the-storage-interface) items if (window.Storage && iterableItem.constructor === window.Storage) { for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) { retVal = callback(iterableItem.key(keyOrIndex), iterableItem.getItem(iterableItem.key(keyOrIndex))); if (retVal === false) { break; } } } // `DataTransferItemList` & `NodeList` objects are array-like and should be treated as arrays // when iterating over items inside the object. else if (qq.isArray(iterableItem) || qq.isItemList(iterableItem) || qq.isNodeList(iterableItem)) { for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) { retVal = callback(keyOrIndex, iterableItem[keyOrIndex]); if (retVal === false) { break; } } } else if (qq.isString(iterableItem)) { for (keyOrIndex = 0; keyOrIndex < iterableItem.length; keyOrIndex++) { retVal = callback(keyOrIndex, iterableItem.charAt(keyOrIndex)); if (retVal === false) { break; } } } else { for (keyOrIndex in iterableItem) { if (Object.prototype.hasOwnProperty.call(iterableItem, keyOrIndex)) { retVal = callback(keyOrIndex, iterableItem[keyOrIndex]); if (retVal === false) { break; } } } } } }; //include any args that should be passed to the new function after the context arg qq.bind = function(oldFunc, context) { if (qq.isFunction(oldFunc)) { var args = Array.prototype.slice.call(arguments, 2); return function() { var newArgs = qq.extend([], args); if (arguments.length) { newArgs = newArgs.concat(Array.prototype.slice.call(arguments)); } return oldFunc.apply(context, newArgs); }; } throw new Error("first parameter must be a function!"); }; /** * obj2url() takes a json-object as argument and generates * a querystring. pretty much like jQuery.param() * * how to use: * * `qq.obj2url({a:'b',c:'d'},'http://any.url/upload?otherParam=value');` * * will result in: * * `http://any.url/upload?otherParam=value&a=b&c=d` * * @param Object JSON-Object * @param String current querystring-part * @return String encoded querystring */ qq.obj2url = function(obj, temp, prefixDone){ /*jshint laxbreak: true*/ var uristrings = [], prefix = "&", add = function(nextObj, i){ var nextTemp = temp ? (/\[\]$/.test(temp)) // prevent double-encoding ? temp : temp+"["+i+"]" : i; if ((nextTemp !== "undefined") && (i !== "undefined")) { uristrings.push( (typeof nextObj === "object") ? qq.obj2url(nextObj, nextTemp, true) : (Object.prototype.toString.call(nextObj) === "[object Function]") ? encodeURIComponent(nextTemp) + "=" + encodeURIComponent(nextObj()) : encodeURIComponent(nextTemp) + "=" + encodeURIComponent(nextObj) ); } }; if (!prefixDone && temp) { prefix = (/\?/.test(temp)) ? (/\?$/.test(temp)) ? "" : "&" : "?"; uristrings.push(temp); uristrings.push(qq.obj2url(obj)); } else if ((Object.prototype.toString.call(obj) === "[object Array]") && (typeof obj !== "undefined") ) { qq.each(obj, function(idx, val) { add(val, idx); }); } else if ((typeof obj !== "undefined") && (obj !== null) && (typeof obj === "object")){ qq.each(obj, function(prop, val) { add(val, prop); }); } else { uristrings.push(encodeURIComponent(temp) + "=" + encodeURIComponent(obj)); } if (temp) { return uristrings.join(prefix); } else { return uristrings.join(prefix) .replace(/^&/, "") .replace(/%20/g, "+"); } }; qq.obj2FormData = function(obj, formData, arrayKeyName) { if (!formData) { formData = new FormData(); } qq.each(obj, function(key, val) { key = arrayKeyName ? arrayKeyName + "[" + key + "]" : key; if (qq.isObject(val)) { qq.obj2FormData(val, formData, key); } else if (qq.isFunction(val)) { formData.append(key, val()); } else { formData.append(key, val); } }); return formData; }; qq.obj2Inputs = function(obj, form) { var input; if (!form) { form = document.createElement("form"); } qq.obj2FormData(obj, { append: function(key, val) { input = document.createElement("input"); input.setAttribute("name", key); input.setAttribute("value", val); form.appendChild(input); } }); return form; }; qq.setCookie = function(name, value, days) { var date = new Date(), expires = ""; if (days) { date.setTime(date.getTime()+(days*24*60*60*1000)); expires = "; expires="+date.toGMTString(); } document.cookie = name+"="+value+expires+"; path=/"; }; qq.getCookie = function(name) { var nameEQ = name + "=", ca = document.cookie.split(";"), cookie; qq.each(ca, function(idx, part) { /*jshint -W116 */ var cookiePart = part; while (cookiePart.charAt(0) == " ") { cookiePart = cookiePart.substring(1, cookiePart.length); } if (cookiePart.indexOf(nameEQ) === 0) { cookie = cookiePart.substring(nameEQ.length, cookiePart.length); return false; } }); return cookie; }; qq.getCookieNames = function(regexp) { var cookies = document.cookie.split(";"), cookieNames = []; qq.each(cookies, function(idx, cookie) { cookie = qq.trimStr(cookie); var equalsIdx = cookie.indexOf("="); if (cookie.match(regexp)) { cookieNames.push(cookie.substr(0, equalsIdx)); } }); return cookieNames; }; qq.deleteCookie = function(name) { qq.setCookie(name, "", -1); }; qq.areCookiesEnabled = function() { var randNum = Math.random() * 100000, name = "qqCookieTest:" + randNum; qq.setCookie(name, 1); if (qq.getCookie(name)) { qq.deleteCookie(name); return true; } return false; }; /** * Not recommended for use outside of Fine Uploader since this falls back to an unchecked eval if JSON.parse is not * implemented. For a more secure JSON.parse polyfill, use Douglas Crockford's json2.js. */ qq.parseJson = function(json) { /*jshint evil: true*/ if (window.JSON && qq.isFunction(JSON.parse)) { return JSON.parse(json); } else { return eval("(" + json + ")"); } }; /** * Retrieve the extension of a file, if it exists. * * @param filename * @returns {string || undefined} */ qq.getExtension = function(filename) { var extIdx = filename.lastIndexOf(".") + 1; if (extIdx > 0) { return filename.substr(extIdx, filename.length - extIdx); } }; qq.getFilename = function(blobOrFileInput) { /*jslint regexp: true*/ if (qq.isInput(blobOrFileInput)) { // get input value and remove path to normalize return blobOrFileInput.value.replace(/.*(\/|\\)/, ""); } else if (qq.isFile(blobOrFileInput)) { if (blobOrFileInput.fileName !== null && blobOrFileInput.fileName !== undefined) { return blobOrFileInput.fileName; } } return blobOrFileInput.name; }; /** * A generic module which supports object disposing in dispose() method. * */ qq.DisposeSupport = function() { var disposers = []; return { /** Run all registered disposers */ dispose: function() { var disposer; do { disposer = disposers.shift(); if (disposer) { disposer(); } } while (disposer); }, /** Attach event handler and register de-attacher as a disposer */ attach: function() { var args = arguments; /*jslint undef:true*/ this.addDisposer(qq(args[0]).attach.apply(this, Array.prototype.slice.call(arguments, 1))); }, /** Add disposer to the collection */ addDisposer: function(disposeFunction) { disposers.push(disposeFunction); } }; }; }()); /* globals qq */ /** * Fine Uploader top-level Error container. Inherits from `Error`. */ (function() { "use strict"; qq.Error = function(message) { this.message = "[Fine Uploader " + qq.version + "] " + message; }; qq.Error.prototype = new Error(); }()); /*global qq */ qq.version="4.3.1"; /* globals qq */ qq.supportedFeatures = (function () { "use strict"; var supportsUploading, supportsAjaxFileUploading, supportsFolderDrop, supportsChunking, supportsResume, supportsUploadViaPaste, supportsUploadCors, supportsDeleteFileXdr, supportsDeleteFileCorsXhr, supportsDeleteFileCors, supportsFolderSelection, supportsImagePreviews; function testSupportsFileInputElement() { var supported = true, tempInput; try { tempInput = document.createElement("input"); tempInput.type = "file"; qq(tempInput).hide(); if (tempInput.disabled) { supported = false; } } catch (ex) { supported = false; } return supported; } //only way to test for Filesystem API support since webkit does not expose the DataTransfer interface function isChrome21OrHigher() { return (qq.chrome() || qq.opera()) && navigator.userAgent.match(/Chrome\/[2][1-9]|Chrome\/[3-9][0-9]/) !== undefined; } //only way to test for complete Clipboard API support at this time function isChrome14OrHigher() { return (qq.chrome() || qq.opera()) && navigator.userAgent.match(/Chrome\/[1][4-9]|Chrome\/[2-9][0-9]/) !== undefined; } //Ensure we can send cross-origin `XMLHttpRequest`s function isCrossOriginXhrSupported() { if (window.XMLHttpRequest) { var xhr = qq.createXhrInstance(); //Commonly accepted test for XHR CORS support. return xhr.withCredentials !== undefined; } return false; } //Test for (terrible) cross-origin ajax transport fallback for IE9 and IE8 function isXdrSupported() { return window.XDomainRequest !== undefined; } // CORS Ajax requests are supported if it is either possible to send credentialed `XMLHttpRequest`s, // or if `XDomainRequest` is an available alternative. function isCrossOriginAjaxSupported() { if (isCrossOriginXhrSupported()) { return true; } return isXdrSupported(); } function isFolderSelectionSupported() { // We know that folder selection is only supported in Chrome via this proprietary attribute for now return document.createElement("input").webkitdirectory !== undefined; } supportsUploading = testSupportsFileInputElement(); supportsAjaxFileUploading = supportsUploading && qq.isXhrUploadSupported(); supportsFolderDrop = supportsAjaxFileUploading && isChrome21OrHigher(); supportsChunking = supportsAjaxFileUploading && qq.isFileChunkingSupported(); supportsResume = supportsAjaxFileUploading && supportsChunking && qq.areCookiesEnabled(); supportsUploadViaPaste = supportsAjaxFileUploading && isChrome14OrHigher(); supportsUploadCors = supportsUploading && (window.postMessage !== undefined || supportsAjaxFileUploading); supportsDeleteFileCorsXhr = isCrossOriginXhrSupported(); supportsDeleteFileXdr = isXdrSupported(); supportsDeleteFileCors = isCrossOriginAjaxSupported(); supportsFolderSelection = isFolderSelectionSupported(); supportsImagePreviews = supportsAjaxFileUploading && window.FileReader !== undefined; return { uploading: supportsUploading, ajaxUploading: supportsAjaxFileUploading, fileDrop: supportsAjaxFileUploading, //NOTE: will also return true for touch-only devices. It's not currently possible to accurately test for touch-only devices folderDrop: supportsFolderDrop, chunking: supportsChunking, resume: supportsResume, uploadCustomHeaders: supportsAjaxFileUploading, uploadNonMultipart: supportsAjaxFileUploading, itemSizeValidation: supportsAjaxFileUploading, uploadViaPaste: supportsUploadViaPaste, progressBar: supportsAjaxFileUploading, uploadCors: supportsUploadCors, deleteFileCorsXhr: supportsDeleteFileCorsXhr, deleteFileCorsXdr: supportsDeleteFileXdr, //NOTE: will also return true in IE10, where XDR is also supported deleteFileCors: supportsDeleteFileCors, canDetermineSize: supportsAjaxFileUploading, folderSelection: supportsFolderSelection, imagePreviews: supportsImagePreviews, imageValidation: supportsImagePreviews, pause: supportsChunking }; }()); /*globals qq*/ qq.Promise = function() { "use strict"; var successArgs, failureArgs, successCallbacks = [], failureCallbacks = [], doneCallbacks = [], state = 0; qq.extend(this, { then: function(onSuccess, onFailure) { if (state === 0) { if (onSuccess) { successCallbacks.push(onSuccess); } if (onFailure) { failureCallbacks.push(onFailure); } } else if (state === -1) { onFailure && onFailure.apply(null, failureArgs); } else if (onSuccess) { onSuccess.apply(null,successArgs); } return this; }, done: function(callback) { if (state === 0) { doneCallbacks.push(callback); } else { callback.apply(null, failureArgs === undefined ? successArgs : failureArgs); } return this; }, success: function() { state = 1; successArgs = arguments; if (successCallbacks.length) { qq.each(successCallbacks, function(idx, callback) { callback.apply(null, successArgs); }); } if(doneCallbacks.length) { qq.each(doneCallbacks, function(idx, callback) { callback.apply(null, successArgs); }); } return this; }, failure: function() { state = -1; failureArgs = arguments; if (failureCallbacks.length) { qq.each(failureCallbacks, function(idx, callback) { callback.apply(null, failureArgs); }); } if(doneCallbacks.length) { qq.each(doneCallbacks, function(idx, callback) { callback.apply(null, failureArgs); }); } return this; } }); }; /*globals qq*/ /** * This module represents an upload or "Select File(s)" button. It's job is to embed an opaque `<input type="file">` * element as a child of a provided "container" element. This "container" element (`options.element`) is used to provide * a custom style for the `<input type="file">` element. The ability to change the style of the container element is also * provided here by adding CSS classes to the container on hover/focus. * * TODO Eliminate the mouseover and mouseout event handlers since the :hover CSS pseudo-class should now be * available on all supported browsers. * * @param o Options to override the default values */ qq.UploadButton = function(o) { "use strict"; var disposeSupport = new qq.DisposeSupport(), options = { // "Container" element element: null, // If true adds `multiple` attribute to `<input type="file">` multiple: false, // Corresponds to the `accept` attribute on the associated `<input type="file">` acceptFiles: null, // A true value allows folders to be selected, if supported by the UA folders: false, // `name` attribute of `<input type="file">` name: "qqfile", // Called when the browser invokes the onchange handler on the `<input type="file">` onChange: function(input) {}, // **This option will be removed** in the future as the :hover CSS pseudo-class is available on all supported browsers hoverClass: "qq-upload-button-hover", focusClass: "qq-upload-button-focus" }, input, buttonId; // Overrides any of the default option values with any option values passed in during construction. qq.extend(options, o); buttonId = qq.getUniqueId(); // Embed an opaque `<input type="file">` element as a child of `options.element`. function createInput() { var input = document.createElement("input"); input.setAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME, buttonId); if (options.multiple) { input.setAttribute("multiple", ""); } if (options.folders && qq.supportedFeatures.folderSelection) { // selecting directories is only possible in Chrome now, via a vendor-specific prefixed attribute input.setAttribute("webkitdirectory", ""); } if (options.acceptFiles) { input.setAttribute("accept", options.acceptFiles); } input.setAttribute("type", "file"); input.setAttribute("name", options.name); qq(input).css({ position: "absolute", // in Opera only 'browse' button // is clickable and it is located at // the right side of the input right: 0, top: 0, fontFamily: "Arial", // 4 persons reported this, the max values that worked for them were 243, 236, 236, 118 fontSize: "118px", margin: 0, padding: 0, cursor: "pointer", opacity: 0 }); options.element.appendChild(input); disposeSupport.attach(input, "change", function(){ options.onChange(input); }); // **These event handlers will be removed** in the future as the :hover CSS pseudo-class is available on all supported browsers disposeSupport.attach(input, "mouseover", function(){ qq(options.element).addClass(options.hoverClass); }); disposeSupport.attach(input, "mouseout", function(){ qq(options.element).removeClass(options.hoverClass); }); disposeSupport.attach(input, "focus", function(){ qq(options.element).addClass(options.focusClass); }); disposeSupport.attach(input, "blur", function(){ qq(options.element).removeClass(options.focusClass); }); // IE and Opera, unfortunately have 2 tab stops on file input // which is unacceptable in our case, disable keyboard access if (window.attachEvent) { // it is IE or Opera input.setAttribute("tabIndex", "-1"); } return input; } // Make button suitable container for input qq(options.element).css({ position: "relative", overflow: "hidden", // Make sure browse button is in the right side in Internet Explorer direction: "ltr" }); input = createInput(); // Exposed API qq.extend(this, { getInput: function() { return input; }, getButtonId: function() { return buttonId; }, setMultiple: function(isMultiple) { if (isMultiple !== options.multiple) { if (isMultiple) { input.setAttribute("multiple", ""); } else { input.removeAttribute("multiple"); } } }, setAcceptFiles: function(acceptFiles) { if (acceptFiles !== options.acceptFiles) { input.setAttribute("accept", acceptFiles); } }, reset: function(){ if (input.parentNode){ qq(input).remove(); } qq(options.element).removeClass(options.focusClass); input = createInput(); } }); }; qq.UploadButton.BUTTON_ID_ATTR_NAME = "qq-button-id"; /*globals qq */ qq.UploadData = function(uploaderProxy) { "use strict"; var data = [], byUuid = {}, byStatus = {}; function getDataByIds(idOrIds) { if (qq.isArray(idOrIds)) { var entries = []; qq.each(idOrIds, function(idx, id) { entries.push(data[id]); }); return entries; } return data[idOrIds]; } function getDataByUuids(uuids) { if (qq.isArray(uuids)) { var entries = []; qq.each(uuids, function(idx, uuid) { entries.push(data[byUuid[uuid]]); }); return entries; } return data[byUuid[uuids]]; } function getDataByStatus(status) { var statusResults = [], statuses = [].concat(status); qq.each(statuses, function(index, statusEnum) { var statusResultIndexes = byStatus[statusEnum]; if (statusResultIndexes !== undefined) { qq.each(statusResultIndexes, function(i, dataIndex) { statusResults.push(data[dataIndex]); }); } }); return statusResults; } qq.extend(this, { /** * Adds a new file to the data cache for tracking purposes. * * @param uuid Initial UUID for this file. * @param name Initial name of this file. * @param size Size of this file, -1 if this cannot be determined * @param status Initial `qq.status` for this file. If null/undefined, `qq.status.SUBMITTING`. * @returns {number} Internal ID for this file. */ addFile: function(uuid, name, size, status) { status = status || qq.status.SUBMITTING; var id = data.push({ name: name, originalName: name, uuid: uuid, size: size, status: status }) - 1; data[id].id = id; byUuid[uuid] = id; if (byStatus[status] === undefined) { byStatus[status] = []; } byStatus[status].push(id); uploaderProxy.onStatusChange(id, null, status); return id; }, retrieve: function(optionalFilter) { if (qq.isObject(optionalFilter) && data.length) { if (optionalFilter.id !== undefined) { return getDataByIds(optionalFilter.id); } else if (optionalFilter.uuid !== undefined) { return getDataByUuids(optionalFilter.uuid); } else if (optionalFilter.status) { return getDataByStatus(optionalFilter.status); } } else { return qq.extend([], data, true); } }, reset: function() { data = []; byUuid = {}; byStatus = {}; }, setStatus: function(id, newStatus) { var oldStatus = data[id].status, byStatusOldStatusIndex = qq.indexOf(byStatus[oldStatus], id); byStatus[oldStatus].splice(byStatusOldStatusIndex, 1); data[id].status = newStatus; if (byStatus[newStatus] === undefined) { byStatus[newStatus] = []; } byStatus[newStatus].push(id); uploaderProxy.onStatusChange(id, oldStatus, newStatus); }, uuidChanged: function(id, newUuid) { var oldUuid = data[id].uuid; data[id].uuid = newUuid; byUuid[newUuid] = id; delete byUuid[oldUuid]; }, updateName: function(id, newName) { data[id].name = newName; } }); }; qq.status = { SUBMITTING: "submitting", SUBMITTED: "submitted", REJECTED: "rejected", QUEUED: "queued", CANCELED: "canceled", PAUSED: "paused", UPLOADING: "uploading", UPLOAD_RETRYING: "retrying upload", UPLOAD_SUCCESSFUL: "upload successful", UPLOAD_FAILED: "upload failed", DELETE_FAILED: "delete failed", DELETING: "deleting", DELETED: "deleted" }; /*globals qq*/ /** * Defines the public API for FineUploaderBasic mode. */ (function(){ "use strict"; qq.basePublicApi = { log: function(str, level) { if (this._options.debug && (!level || level === "info")) { qq.log("[Fine Uploader " + qq.version + "] " + str); } else if (level && level !== "info") { qq.log("[Fine Uploader " + qq.version + "] " + str, level); } }, setParams: function(params, id) { this._paramsStore.set(params, id); }, setDeleteFileParams: function(params, id) { this._deleteFileParamsStore.set(params, id); }, // Re-sets the default endpoint, an endpoint for a specific file, or an endpoint for a specific button setEndpoint: function(endpoint, id) { this._endpointStore.set(endpoint, id); }, getInProgress: function() { return this._uploadData.retrieve({ status: [ qq.status.UPLOADING, qq.status.UPLOAD_RETRYING, qq.status.QUEUED ] }).length; }, getNetUploads: function() { return this._netUploaded; }, uploadStoredFiles: function() { var idToUpload; if (this._storedIds.length === 0) { this._itemError("noFilesError"); } else { while (this._storedIds.length) { idToUpload = this._storedIds.shift(); this._uploadFile(idToUpload); } } }, clearStoredFiles: function(){ this._storedIds = []; }, retry: function(id) { return this._manualRetry(id); }, cancel: function(id) { this._handler.cancel(id); }, cancelAll: function() { var storedIdsCopy = [], self = this; qq.extend(storedIdsCopy, this._storedIds); qq.each(storedIdsCopy, function(idx, storedFileId) { self.cancel(storedFileId); }); this._handler.cancelAll(); }, reset: function() { this.log("Resetting uploader..."); this._handler.reset(); this._storedIds = []; this._autoRetries = []; this._retryTimeouts = []; this._preventRetries = []; this._thumbnailUrls = []; qq.each(this._buttons, function(idx, button) { button.reset(); }); this._paramsStore.reset(); this._endpointStore.reset(); this._netUploadedOrQueued = 0; this._netUploaded = 0; this._uploadData.reset(); this._buttonIdsForFileIds = []; this._pasteHandler && this._pasteHandler.reset(); this._options.session.refreshOnReset && this._refreshSessionData(); this._succeededSinceLastAllComplete = []; this._failedSinceLastAllComplete = []; }, addFiles: function(filesOrInputs, params, endpoint) { var verifiedFilesOrInputs = [], fileOrInputIndex, fileOrInput, fileIndex; if (filesOrInputs) { if (!qq.isFileList(filesOrInputs)) { filesOrInputs = [].concat(filesOrInputs); } for (fileOrInputIndex = 0; fileOrInputIndex < filesOrInputs.length; fileOrInputIndex+=1) { fileOrInput = filesOrInputs[fileOrInputIndex]; if (qq.isFileOrInput(fileOrInput)) { if (qq.isInput(fileOrInput) && qq.supportedFeatures.ajaxUploading) { for (fileIndex = 0; fileIndex < fileOrInput.files.length; fileIndex++) { this._handleNewFile(fileOrInput.files[fileIndex], verifiedFilesOrInputs); } } else { this._handleNewFile(fileOrInput, verifiedFilesOrInputs); } } else { this.log(fileOrInput + " is not a File or INPUT element! Ignoring!", "warn"); } } this.log("Received " + verifiedFilesOrInputs.length + " files or inputs."); this._prepareItemsForUpload(verifiedFilesOrInputs, params, endpoint); } }, addBlobs: function(blobDataOrArray, params, endpoint) { if (blobDataOrArray) { var blobDataArray = [].concat(blobDataOrArray), verifiedBlobDataList = [], self = this; qq.each(blobDataArray, function(idx, blobData) { var blobOrBlobData; if (qq.isBlob(blobData) && !qq.isFileOrInput(blobData)) { blobOrBlobData = { blob: blobData, name: self._options.blobs.defaultName }; } else if (qq.isObject(blobData) && blobData.blob && blobData.name) { blobOrBlobData = blobData; } else { self.log("addBlobs: entry at index " + idx + " is not a Blob or a BlobData object", "error"); } blobOrBlobData && self._handleNewFile(blobOrBlobData, verifiedBlobDataList); }); this._prepareItemsForUpload(verifiedBlobDataList, params, endpoint); } else { this.log("undefined or non-array parameter passed into addBlobs", "error"); } }, getUuid: function(id) { return this._uploadData.retrieve({id: id}).uuid; }, setUuid: function(id, newUuid) { return this._uploadData.uuidChanged(id, newUuid); }, getResumableFilesData: function() { return this._handler.getResumableFilesData(); }, getSize: function(id) { return this._uploadData.retrieve({id: id}).size; }, getName: function(id) { return this._uploadData.retrieve({id: id}).name; }, setName: function(id, newName) { this._uploadData.updateName(id, newName); }, getFile: function(fileOrBlobId) { return this._handler.getFile(fileOrBlobId); }, deleteFile: function(id) { return this._onSubmitDelete(id); }, setDeleteFileEndpoint: function(endpoint, id) { this._deleteFileEndpointStore.set(endpoint, id); }, doesExist: function(fileOrBlobId) { return this._handler.isValid(fileOrBlobId); }, getUploads: function(optionalFilter) { return this._uploadData.retrieve(optionalFilter); }, getButton: function(fileId) { return this._getButton(this._buttonIdsForFileIds[fileId]); }, // Generate a variable size thumbnail on an img or canvas, // returning a promise that is fulfilled when the attempt completes. // Thumbnail can either be based off of a URL for an image returned // by the server in the upload response, or the associated `Blob`. drawThumbnail: function(fileId, imgOrCanvas, maxSize, fromServer) { if (this._imageGenerator) { var fileOrUrl = this._thumbnailUrls[fileId], options = { scale: maxSize > 0, maxSize: maxSize > 0 ? maxSize : null }; // If client-side preview generation is possible // and we are not specifically looking for the image URl returned by the server... if (!fromServer && qq.supportedFeatures.imagePreviews) { fileOrUrl = this.getFile(fileId); } /* jshint eqeqeq:false,eqnull:true */ if (fileOrUrl == null) { return new qq.Promise().failure(imgOrCanvas, "File or URL not found."); } return this._imageGenerator.generate(fileOrUrl, imgOrCanvas, options); } }, pauseUpload: function(id) { var uploadData = this._uploadData.retrieve({id: id}); if (!qq.supportedFeatures.pause || !this._options.chunking.enabled) { return false; } // Pause only really makes sense if the file is uploading or retrying if (qq.indexOf([qq.status.UPLOADING, qq.status.UPLOAD_RETRYING], uploadData.status) >= 0) { if (this._handler.pause(id)) { this._uploadData.setStatus(id, qq.status.PAUSED); return true; } else { qq.log(qq.format("Unable to pause file ID {} ({}).", id, this.getName(id)), "error"); } } else { qq.log(qq.format("Ignoring pause for file ID {} ({}). Not in progress.", id, this.getName(id)), "error"); } return false; }, continueUpload: function(id) { var uploadData = this._uploadData.retrieve({id: id}); if (!qq.supportedFeatures.pause || !this._options.chunking.enabled) { return false; } if (uploadData.status === qq.status.PAUSED) { qq.log(qq.format("Paused file ID {} ({}) will be continued. Not paused.", id, this.getName(id))); this._uploadFile(id); return true; } else { qq.log(qq.format("Ignoring continue for file ID {} ({}). Not paused.", id, this.getName(id)), "error"); } return false; }, getRemainingAllowedItems: function() { var allowedItems = this._options.validation.itemLimit; if (allowedItems > 0) { return this._options.validation.itemLimit - this._netUploadedOrQueued; } return null; } }; /** * Defines the private (internal) API for FineUploaderBasic mode. */ qq.basePrivateApi = { _initFormSupportAndParams: function() { this._formSupport = qq.FormSupport && new qq.FormSupport( this._options.form, qq.bind(this.uploadStoredFiles, this), qq.bind(this.log, this) ); if (this._formSupport && this._formSupport.attachedToForm) { this._paramsStore = this._createStore( this._options.request.params, this._formSupport.getFormInputsAsObject ); this._options.autoUpload = this._formSupport.newAutoUpload; if (this._formSupport.newEndpoint) { this._options.request.endpoint = this._formSupport.newEndpoint; } } else { this._paramsStore = this._createStore(this._options.request.params); } }, _uploadFile: function(id) { if (!this._handler.upload(id)) { this._uploadData.setStatus(id, qq.status.QUEUED); } }, // Attempts to refresh session data only if the `qq.Session` module exists // and a session endpoint has been specified. The `onSessionRequestComplete` // callback will be invoked once the refresh is complete. _refreshSessionData: function() { var self = this, options = this._options.session; /* jshint eqnull:true */ if (qq.Session && this._options.session.endpoint != null) { if (!this._session) { qq.extend(options, this._options.cors); options.log = qq.bind(this.log, this); options.addFileRecord = qq.bind(this._addCannedFile, this); this._session = new qq.Session(options); } setTimeout(function() { self._session.refresh().then(function(response, xhrOrXdr) { self._options.callbacks.onSessionRequestComplete(response, true, xhrOrXdr); }, function(response, xhrOrXdr) { self._options.callbacks.onSessionRequestComplete(response, false, xhrOrXdr); }); }, 0); } }, // Updates internal state with a file record (not backed by a live file). Returns the assigned ID. _addCannedFile: function(sessionData) { var id = this._uploadData.addFile(sessionData.uuid, sessionData.name, sessionData.size, qq.status.UPLOAD_SUCCESSFUL); sessionData.deleteFileEndpoint && this.setDeleteFileEndpoint(sessionData.deleteFileEndpoint, id); sessionData.deleteFileParams && this.setDeleteFileParams(sessionData.deleteFileParams, id); if (sessionData.thumbnailUrl) { this._thumbnailUrls[id] = sessionData.thumbnailUrl; } this._netUploaded++; this._netUploadedOrQueued++; return id; }, // Updates internal state when a new file has been received, and adds it along with its ID to a passed array. _handleNewFile: function(file, newFileWrapperList) { var size = -1, uuid = qq.getUniqueId(), name = qq.getFilename(file), id; if (file.size >= 0) { size = file.size; } else if (file.blob) { size = file.blob.size; } id = this._uploadData.addFile(uuid, name, size); this._handler.add(id, file); this._trackButton(id); this._netUploadedOrQueued++; newFileWrapperList.push({id: id, file: file}); }, // Maps a file with the button that was used to select it. _trackButton: function(id) { var buttonId; if (qq.supportedFeatures.ajaxUploading) { buttonId = this._handler.getFile(id).qqButtonId; } else { buttonId = this._getButtonId(this._handler.getInput(id)); } if (buttonId) { this._buttonIdsForFileIds[id] = buttonId; } }, // Creates an internal object that tracks various properties of each extra button, // and then actually creates the extra button. _generateExtraButtonSpecs: function() { var self = this; this._extraButtonSpecs = {}; qq.each(this._options.extraButtons, function(idx, extraButtonOptionEntry) { var multiple = extraButtonOptionEntry.multiple, validation = qq.extend({}, self._options.validation, true), extraButtonSpec = qq.extend({}, extraButtonOptionEntry); if (multiple === undefined) { multiple = self._options.multiple; } if (extraButtonSpec.validation) { qq.extend(validation, extraButtonOptionEntry.validation, true); } qq.extend(extraButtonSpec, { multiple: multiple, validation: validation }, true); self._initExtraButton(extraButtonSpec); }); }, // Creates an extra button element _initExtraButton: function(spec) { var button = this._createUploadButton({ element: spec.element, multiple: spec.multiple, accept: spec.validation.acceptFiles, folders: spec.folders, allowedExtensions: spec.validation.allowedExtensions }); this._extraButtonSpecs[button.getButtonId()] = spec; }, /** * Gets the internally used tracking ID for a button. * * @param buttonOrFileInputOrFile `File`, `<input type="file">`, or a button container element * @returns {*} The button's ID, or undefined if no ID is recoverable * @private */ _getButtonId: function(buttonOrFileInputOrFile) { var inputs, fileInput; // If the item is a `Blob` it will never be associated with a button or drop zone. if (buttonOrFileInputOrFile && !buttonOrFileInputOrFile.blob && !qq.isBlob(buttonOrFileInputOrFile)) { if (qq.isFile(buttonOrFileInputOrFile)) { return buttonOrFileInputOrFile.qqButtonId; } else if (buttonOrFileInputOrFile.tagName.toLowerCase() === "input" && buttonOrFileInputOrFile.type.toLowerCase() === "file") { return buttonOrFileInputOrFile.getAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME); } inputs = buttonOrFileInputOrFile.getElementsByTagName("input"); qq.each(inputs, function(idx, input) { if (input.getAttribute("type") === "file") { fileInput = input; return false; } }); if (fileInput) { return fileInput.getAttribute(qq.UploadButton.BUTTON_ID_ATTR_NAME); } } }, _annotateWithButtonId: function(file, associatedInput) { if (qq.isFile(file)) { file.qqButtonId = this._getButtonId(associatedInput); } }, _getButton: function(buttonId) { var extraButtonsSpec = this._extraButtonSpecs[buttonId]; if (extraButtonsSpec) { return extraButtonsSpec.element; } else if (buttonId === this._defaultButtonId) { return this._options.button; } }, _handleCheckedCallback: function(details) { var self = this, callbackRetVal = details.callback(); if (callbackRetVal instanceof qq.Promise) { this.log(details.name + " - waiting for " + details.name + " promise to be fulfilled for " + details.identifier); return callbackRetVal.then( function(successParam) { self.log(details.name + " promise success for " + details.identifier); details.onSuccess(successParam); }, function() { if (details.onFailure) { self.log(details.name + " promise failure for " + details.identifier); details.onFailure(); } else { self.log(details.name + " promise failure for " + details.identifier); } }); } if (callbackRetVal !== false) { details.onSuccess(callbackRetVal); } else { if (details.onFailure) { this.log(details.name + " - return value was 'false' for " + details.identifier + ". Invoking failure callback."); details.onFailure(); } else { this.log(details.name + " - return value was 'false' for " + details.identifier + ". Will not proceed."); } } return callbackRetVal; }, /** * Generate a tracked upload button. * * @param spec Object containing a required `element` property * along with optional `multiple`, `accept`, and `folders`. * @returns {qq.UploadButton} * @private */ _createUploadButton: function(spec) { var self = this, acceptFiles = spec.accept || this._options.validation.acceptFiles, allowedExtensions = spec.allowedExtensions || this._options.validation.allowedExtensions; function allowMultiple() { if (qq.supportedFeatures.ajaxUploading) { // Workaround for bug in iOS7 (see #1039) if (qq.ios7() && self._isAllowedExtension(allowedExtensions, ".mov")) { return false; } if (spec.multiple === undefined) { return self._options.multiple; } return spec.multiple; } return false; } var button = new qq.UploadButton({ element: spec.element, folders: spec.folders, name: this._options.request.inputName, multiple: allowMultiple(), acceptFiles: acceptFiles, onChange: function(input) { self._onInputChange(input); }, hoverClass: this._options.classes.buttonHover, focusClass: this._options.classes.buttonFocus }); this._disposeSupport.addDisposer(function() { button.dispose(); }); self._buttons.push(button); return button; }, _createUploadHandler: function(additionalOptions, namespace) { var self = this, options = { debug: this._options.debug, maxConnections: this._options.maxConnections, cors: this._options.cors, demoMode: this._options.demoMode, paramsStore: this._paramsStore, endpointStore: this._endpointStore, chunking: this._options.chunking, resume: this._options.resume, blobs: this._options.blobs, log: qq.bind(self.log, self), onProgress: function(id, name, loaded, total){ self._onProgress(id, name, loaded, total); self._options.callbacks.onProgress(id, name, loaded, total); }, onComplete: function(id, name, result, xhr){ var retVal = self._onComplete(id, name, result, xhr); // If the internal `_onComplete` handler returns a promise, don't invoke the `onComplete` callback // until the promise has been fulfilled. if (retVal instanceof qq.Promise) { retVal.done(function() { self._options.callbacks.onComplete(id, name, result, xhr); }); } else { self._options.callbacks.onComplete(id, name, result, xhr); } }, onCancel: function(id, name) { return self._handleCheckedCallback({ name: "onCancel", callback: qq.bind(self._options.callbacks.onCancel, self, id, name), onSuccess: qq.bind(self._onCancel, self, id, name), identifier: id }); }, onUpload: function(id, name) { self._onUpload(id, name); self._options.callbacks.onUpload(id, name); }, onUploadChunk: function(id, name, chunkData) { self._onUploadChunk(id, chunkData); self._options.callbacks.onUploadChunk(id, name, chunkData); }, onUploadChunkSuccess: function(id, chunkData, result, xhr) { self._options.callbacks.onUploadChunkSuccess.apply(self, arguments); }, onResume: function(id, name, chunkData) { return self._options.callbacks.onResume(id, name, chunkData); }, onAutoRetry: function(id, name, responseJSON, xhr) { return self._onAutoRetry.apply(self, arguments); }, onUuidChanged: function(id, newUuid) { self.log("Server requested UUID change from '" + self.getUuid(id) + "' to '" + newUuid + "'"); self.setUuid(id, newUuid); }, getName: qq.bind(self.getName, self), getUuid: qq.bind(self.getUuid, self), getSize: qq.bind(self.getSize, self) }; qq.each(this._options.request, function(prop, val) { options[prop] = val; }); if (additionalOptions) { qq.each(additionalOptions, function(key, val) { options[key] = val; }); } return new qq.UploadHandler(options, namespace); }, _createDeleteHandler: function() { var self = this; return new qq.DeleteFileAjaxRequester({ method: this._options.deleteFile.method.toUpperCase(), maxConnections: this._options.maxConnections, uuidParamName: this._options.request.uuidName, customHeaders: this._options.deleteFile.customHeaders, paramsStore: this._deleteFileParamsStore, endpointStore: this._deleteFileEndpointStore, demoMode: this._options.demoMode, cors: this._options.cors, log: qq.bind(self.log, self), onDelete: function(id) { self._onDelete(id); self._options.callbacks.onDelete(id); }, onDeleteComplete: function(id, xhrOrXdr, isError) { self._onDeleteComplete(id, xhrOrXdr, isError); self._options.callbacks.onDeleteComplete(id, xhrOrXdr, isError); } }); }, _createPasteHandler: function() { var self = this; return new qq.PasteSupport({ targetElement: this._options.paste.targetElement, callbacks: { log: qq.bind(self.log, self), pasteReceived: function(blob) { self._handleCheckedCallback({ name: "onPasteReceived", callback: qq.bind(self._options.callbacks.onPasteReceived, self, blob), onSuccess: qq.bind(self._handlePasteSuccess, self, blob), identifier: "pasted image" }); } } }); }, _createUploadDataTracker: function() { var self = this; return new qq.UploadData({ getName: function(id) { return self.getName(id); }, getUuid: function(id) { return self.getUuid(id); }, getSize: function(id) { return self.getSize(id); }, onStatusChange: function(id, oldStatus, newStatus) { self._onUploadStatusChange(id, oldStatus, newStatus); self._options.callbacks.onStatusChange(id, oldStatus, newStatus); self._maybeAllComplete(id, newStatus); } }); }, _onUploadStatusChange: function(id, oldStatus, newStatus) { // Make sure a "queued" retry attempt is canceled if the upload has been paused if (newStatus === qq.status.PAUSED) { clearTimeout(this._retryTimeouts[id]); } }, _handlePasteSuccess: function(blob, extSuppliedName) { var extension = blob.type.split("/")[1], name = extSuppliedName; /*jshint eqeqeq: true, eqnull: true*/ if (name == null) { name = this._options.paste.defaultName; } name += "." + extension; this.addBlobs({ name: name, blob: blob }); }, _preventLeaveInProgress: function(){ var self = this; this._disposeSupport.attach(window, "beforeunload", function(e){ if (self.getInProgress()) { e = e || window.event; // for ie, ff e.returnValue = self._options.messages.onLeave; // for webkit return self._options.messages.onLeave; } }); }, _onSubmit: function(id, name) { //nothing to do yet in core uploader }, _onProgress: function(id, name, loaded, total) { //nothing to do yet in core uploader }, _onComplete: function(id, name, result, xhr) { if (!result.success) { this._netUploadedOrQueued--; this._uploadData.setStatus(id, qq.status.UPLOAD_FAILED); } else { if (result.thumbnailUrl) { this._thumbnailUrls[id] = result.thumbnailUrl; } this._netUploaded++; this._uploadData.setStatus(id, qq.status.UPLOAD_SUCCESSFUL); } this._maybeParseAndSendUploadError(id, name, result, xhr); return result.success ? true : false; }, _maybeAllComplete: function(id, status) { var self = this, notFinished = this._uploadData.retrieve({ status: [ qq.status.UPLOADING, qq.status.UPLOAD_RETRYING, qq.status.QUEUED, qq.status.SUBMITTING, qq.status.SUBMITTED, qq.status.PAUSED, ] }).length; if (status === qq.status.UPLOAD_SUCCESSFUL) { this._succeededSinceLastAllComplete.push(id); } else if (status === qq.status.UPLOAD_FAILED) { this._failedSinceLastAllComplete.push(id); } if (notFinished === 0 && (this._succeededSinceLastAllComplete.length || this._failedSinceLastAllComplete.length)) { // Attempt to ensure onAllComplete is not invoked before other callbacks, such as onCancel & onComplete setTimeout(function() { self._options.callbacks.onAllComplete( qq.extend([], self._succeededSinceLastAllComplete), qq.extend([], self._failedSinceLastAllComplete) ); self._succeededSinceLastAllComplete = []; self._failedSinceLastAllComplete = []; }, 0); } }, _onCancel: function(id, name) { this._netUploadedOrQueued--; clearTimeout(this._retryTimeouts[id]); var storedItemIndex = qq.indexOf(this._storedIds, id); if (!this._options.autoUpload && storedItemIndex >= 0) { this._storedIds.splice(storedItemIndex, 1); } this._uploadData.setStatus(id, qq.status.CANCELED); }, _isDeletePossible: function() { if (!qq.DeleteFileAjaxRequester || !this._options.deleteFile.enabled) { return false; } if (this._options.cors.expected) { if (qq.supportedFeatures.deleteFileCorsXhr) { return true; } if (qq.supportedFeatures.deleteFileCorsXdr && this._options.cors.allowXdr) { return true; } return false; } return true; }, _onSubmitDelete: function(id, onSuccessCallback, additionalMandatedParams) { var uuid = this.getUuid(id), adjustedOnSuccessCallback; if (onSuccessCallback) { adjustedOnSuccessCallback = qq.bind(onSuccessCallback, this, id, uuid, additionalMandatedParams); } if (this._isDeletePossible()) { this._handleCheckedCallback({ name: "onSubmitDelete", callback: qq.bind(this._options.callbacks.onSubmitDelete, this, id), onSuccess: adjustedOnSuccessCallback || qq.bind(this._deleteHandler.sendDelete, this, id, uuid, additionalMandatedParams), identifier: id }); return true; } else { this.log("Delete request ignored for ID " + id + ", delete feature is disabled or request not possible " + "due to CORS on a user agent that does not support pre-flighting.", "warn"); return false; } }, _onDelete: function(id) { this._uploadData.setStatus(id, qq.status.DELETING); }, _onDeleteComplete: function(id, xhrOrXdr, isError) { var name = this.getName(id); if (isError) { this._uploadData.setStatus(id, qq.status.DELETE_FAILED); this.log("Delete request for '" + name + "' has failed.", "error"); // For error reporing, we only have accesss to the response status if this is not // an `XDomainRequest`. if (xhrOrXdr.withCredentials === undefined) { this._options.callbacks.onError(id, name, "Delete request failed", xhrOrXdr); } else { this._options.callbacks.onError(id, name, "Delete request failed with response code " + xhrOrXdr.status, xhrOrXdr); } } else { this._netUploadedOrQueued--; this._netUploaded--; this._handler.expunge(id); this._uploadData.setStatus(id, qq.status.DELETED); this.log("Delete request for '" + name + "' has succeeded."); } }, _onUpload: function(id, name) { this._uploadData.setStatus(id, qq.status.UPLOADING); }, _onUploadChunk: function(id, chunkData) { //nothing to do in the base uploader }, _onInputChange: function(input) { var fileIndex; if (qq.supportedFeatures.ajaxUploading) { for (fileIndex = 0; fileIndex < input.files.length; fileIndex++) { this._annotateWithButtonId(input.files[fileIndex], input); } this.addFiles(input.files); } // Android 2.3.x will fire `onchange` even if no file has been selected else if (input.value.length > 0) { this.addFiles(input); } qq.each(this._buttons, function(idx, button) { button.reset(); }); }, _onBeforeAutoRetry: function(id, name) { this.log("Waiting " + this._options.retry.autoAttemptDelay + " seconds before retrying " + name + "..."); }, /** * Attempt to automatically retry a failed upload. * * @param id The file ID of the failed upload * @param name The name of the file associated with the failed upload * @param responseJSON Response from the server, parsed into a javascript object * @param xhr Ajax transport used to send the failed request * @param callback Optional callback to be invoked if a retry is prudent. * Invoked in lieu of asking the upload handler to retry. * @returns {boolean} true if an auto-retry will occur * @private */ _onAutoRetry: function(id, name, responseJSON, xhr, callback) { var self = this; self._preventRetries[id] = responseJSON[self._options.retry.preventRetryResponseProperty]; if (self._shouldAutoRetry(id, name, responseJSON)) { self._maybeParseAndSendUploadError.apply(self, arguments); self._options.callbacks.onAutoRetry(id, name, self._autoRetries[id] + 1); self._onBeforeAutoRetry(id, name); self._retryTimeouts[id] = setTimeout(function() { self.log("Retrying " + name + "..."); self._autoRetries[id]++; self._uploadData.setStatus(id, qq.status.UPLOAD_RETRYING); if (callback) { callback(id); } else { self._handler.retry(id); } }, self._options.retry.autoAttemptDelay * 1000); return true; } }, _shouldAutoRetry: function(id, name, responseJSON) { var uploadData = this._uploadData.retrieve({id: id}); /*jshint laxbreak: true */ if (!this._preventRetries[id] && this._options.retry.enableAuto && uploadData.status !== qq.status.PAUSED) { if (this._autoRetries[id] === undefined) { this._autoRetries[id] = 0; } return this._autoRetries[id] < this._options.retry.maxAutoAttempts; } return false; }, //return false if we should not attempt the requested retry _onBeforeManualRetry: function(id) { var itemLimit = this._options.validation.itemLimit; if (this._preventRetries[id]) { this.log("Retries are forbidden for id " + id, "warn"); return false; } else if (this._handler.isValid(id)) { var fileName = this.getName(id); if (this._options.callbacks.onManualRetry(id, fileName) === false) { return false; } if (itemLimit > 0 && this._netUploadedOrQueued+1 > itemLimit) { this._itemError("retryFailTooManyItems"); return false; } this.log("Retrying upload for '" + fileName + "' (id: " + id + ")..."); return true; } else { this.log("'" + id + "' is not a valid file ID", "error"); return false; } }, /** * Conditionally orders a manual retry of a failed upload. * * @param id File ID of the failed upload * @param callback Optional callback to invoke if a retry is prudent. * In lieu of asking the upload handler to retry. * @returns {boolean} true if a manual retry will occur * @private */ _manualRetry: function(id, callback) { if (this._onBeforeManualRetry(id)) { this._netUploadedOrQueued++; this._uploadData.setStatus(id, qq.status.UPLOAD_RETRYING); if (callback) { callback(id); } else { this._handler.retry(id); } return true; } }, _maybeParseAndSendUploadError: function(id, name, response, xhr) { // Assuming no one will actually set the response code to something other than 200 // and still set 'success' to true... if (!response.success){ if (xhr && xhr.status !== 200 && !response.error) { this._options.callbacks.onError(id, name, "XHR returned response code " + xhr.status, xhr); } else { var errorReason = response.error ? response.error : this._options.text.defaultResponseError; this._options.callbacks.onError(id, name, errorReason, xhr); } } }, _prepareItemsForUpload: function(items, params, endpoint) { if (items.length === 0) { this._itemError("noFilesError"); return; } var validationDescriptors = this._getValidationDescriptors(items), buttonId = this._getButtonId(items[0].file), button = this._getButton(buttonId); this._handleCheckedCallback({ name: "onValidateBatch", callback: qq.bind(this._options.callbacks.onValidateBatch, this, validationDescriptors, button), onSuccess: qq.bind(this._onValidateBatchCallbackSuccess, this, validationDescriptors, items, params, endpoint, button), onFailure: qq.bind(this._onValidateBatchCallbackFailure, this, items), identifier: "batch validation" }); }, _upload: function(id, params, endpoint) { var name = this.getName(id); if (params) { this.setParams(params, id); } if (endpoint) { this.setEndpoint(endpoint, id); } this._handleCheckedCallback({ name: "onSubmit", callback: qq.bind(this._options.callbacks.onSubmit, this, id, name), onSuccess: qq.bind(this._onSubmitCallbackSuccess, this, id, name), onFailure: qq.bind(this._fileOrBlobRejected, this, id, name), identifier: id }); }, _onSubmitCallbackSuccess: function(id, name) { this._onSubmit.apply(this, arguments); this._uploadData.setStatus(id, qq.status.SUBMITTED); this._onSubmitted.apply(this, arguments); this._options.callbacks.onSubmitted.apply(this, arguments); if (this._options.autoUpload) { this._uploadFile(id); } else { this._storeForLater(id); } }, _onSubmitted: function(id) { //nothing to do in the base uploader }, _storeForLater: function(id) { this._storedIds.push(id); }, _onValidateBatchCallbackSuccess: function(validationDescriptors, items, params, endpoint, button) { var errorMessage, itemLimit = this._options.validation.itemLimit, proposedNetFilesUploadedOrQueued = this._netUploadedOrQueued; if (itemLimit === 0 || proposedNetFilesUploadedOrQueued <= itemLimit) { if (items.length > 0) { this._handleCheckedCallback({ name: "onValidate", callback: qq.bind(this._options.callbacks.onValidate, this, validationDescriptors[0], button), onSuccess: qq.bind(this._onValidateCallbackSuccess, this, items, 0, params, endpoint), onFailure: qq.bind(this._onValidateCallbackFailure, this, items, 0, params, endpoint), identifier: "Item '" + items[0].file.name + "', size: " + items[0].file.size }); } else { this._itemError("noFilesError"); } } else { this._onValidateBatchCallbackFailure(items); errorMessage = this._options.messages.tooManyItemsError .replace(/\{netItems\}/g, proposedNetFilesUploadedOrQueued) .replace(/\{itemLimit\}/g, itemLimit); this._batchError(errorMessage); } }, _onValidateBatchCallbackFailure: function(fileWrappers) { var self = this; qq.each(fileWrappers, function(idx, fileWrapper) { self._fileOrBlobRejected(fileWrapper.id); }); }, _onValidateCallbackSuccess: function(items, index, params, endpoint) { var self = this, nextIndex = index+1, validationDescriptor = this._getValidationDescriptor(items[index].file); this._validateFileOrBlobData(items[index], validationDescriptor) .then( function() { self._upload(items[index].id, params, endpoint); self._maybeProcessNextItemAfterOnValidateCallback(true, items, nextIndex, params, endpoint); }, function() { self._maybeProcessNextItemAfterOnValidateCallback(false, items, nextIndex, params, endpoint); } ); }, _onValidateCallbackFailure: function(items, index, params, endpoint) { var nextIndex = index+ 1; this._fileOrBlobRejected(items[0].id, items[0].file.name); this._maybeProcessNextItemAfterOnValidateCallback(false, items, nextIndex, params, endpoint); }, _maybeProcessNextItemAfterOnValidateCallback: function(validItem, items, index, params, endpoint) { var self = this; if (items.length > index) { if (validItem || !this._options.validation.stopOnFirstInvalidFile) { //use setTimeout to prevent a stack overflow with a large number of files in the batch & non-promissory callbacks setTimeout(function() { var validationDescriptor = self._getValidationDescriptor(items[index].file); self._handleCheckedCallback({ name: "onValidate", callback: qq.bind(self._options.callbacks.onValidate, self, items[index].file), onSuccess: qq.bind(self._onValidateCallbackSuccess, self, items, index, params, endpoint), onFailure: qq.bind(self._onValidateCallbackFailure, self, items, index, params, endpoint), identifier: "Item '" + validationDescriptor.name + "', size: " + validationDescriptor.size }); }, 0); } else if (!validItem) { for (; index < items.length; index++) { self._fileOrBlobRejected(items[index].id); } } } }, /** * Performs some internal validation checks on an item, defined in the `validation` option. * * @param fileWrapper Wrapper containing a `file` along with an `id` * @param validationDescriptor Normalized information about the item (`size`, `name`). * @returns qq.Promise with appropriate callbacks invoked depending on the validity of the file * @private */ _validateFileOrBlobData: function(fileWrapper, validationDescriptor) { var self = this, file = fileWrapper.file, name = validationDescriptor.name, size = validationDescriptor.size, buttonId = this._getButtonId(file), validationBase = this._getValidationBase(buttonId), validityChecker = new qq.Promise(); validityChecker.then( function() {}, function() { self._fileOrBlobRejected(fileWrapper.id, name); }); if (qq.isFileOrInput(file) && !this._isAllowedExtension(validationBase.allowedExtensions, name)) { this._itemError("typeError", name, file); return validityChecker.failure(); } if (size === 0) { this._itemError("emptyError", name, file); return validityChecker.failure(); } if (size && validationBase.sizeLimit && size > validationBase.sizeLimit) { this._itemError("sizeError", name, file); return validityChecker.failure(); } if (size && size < validationBase.minSizeLimit) { this._itemError("minSizeError", name, file); return validityChecker.failure(); } if (qq.ImageValidation && qq.supportedFeatures.imagePreviews && qq.isFile(file)) { new qq.ImageValidation(file, qq.bind(self.log, self)).validate(validationBase.image).then( validityChecker.success, function(errorCode) { self._itemError(errorCode + "ImageError", name, file); validityChecker.failure(); } ); } else { validityChecker.success(); } return validityChecker; }, _fileOrBlobRejected: function(id) { this._netUploadedOrQueued--; this._uploadData.setStatus(id, qq.status.REJECTED); }, /** * Constructs and returns a message that describes an item/file error. Also calls `onError` callback. * * @param code REQUIRED - a code that corresponds to a stock message describing this type of error * @param maybeNameOrNames names of the items that have failed, if applicable * @param item `File`, `Blob`, or `<input type="file">` * @private */ _itemError: function(code, maybeNameOrNames, item) { var message = this._options.messages[code], allowedExtensions = [], names = [].concat(maybeNameOrNames), name = names[0], buttonId = this._getButtonId(item), validationBase = this._getValidationBase(buttonId), extensionsForMessage, placeholderMatch; function r(name, replacement){ message = message.replace(name, replacement); } qq.each(validationBase.allowedExtensions, function(idx, allowedExtension) { /** * If an argument is not a string, ignore it. Added when a possible issue with MooTools hijacking the * `allowedExtensions` array was discovered. See case #735 in the issue tracker for more details. */ if (qq.isString(allowedExtension)) { allowedExtensions.push(allowedExtension); } }); extensionsForMessage = allowedExtensions.join(", ").toLowerCase(); r("{file}", this._options.formatFileName(name)); r("{extensions}", extensionsForMessage); r("{sizeLimit}", this._formatSize(validationBase.sizeLimit)); r("{minSizeLimit}", this._formatSize(validationBase.minSizeLimit)); placeholderMatch = message.match(/(\{\w+\})/g); if (placeholderMatch !== null) { qq.each(placeholderMatch, function(idx, placeholder) { r(placeholder, names[idx]); }); } this._options.callbacks.onError(null, name, message, undefined); return message; }, _batchError: function(message) { this._options.callbacks.onError(null, null, message, undefined); }, _isAllowedExtension: function(allowed, fileName) { var valid = false; if (!allowed.length) { return true; } qq.each(allowed, function(idx, allowedExt) { /** * If an argument is not a string, ignore it. Added when a possible issue with MooTools hijacking the * `allowedExtensions` array was discovered. See case #735 in the issue tracker for more details. */ if (qq.isString(allowedExt)) { /*jshint eqeqeq: true, eqnull: true*/ var extRegex = new RegExp("\\." + allowedExt + "$", "i"); if (fileName.match(extRegex) != null) { valid = true; return false; } } }); return valid; }, _formatSize: function(bytes){ var i = -1; do { bytes = bytes / 1000; i++; } while (bytes > 999); return Math.max(bytes, 0.1).toFixed(1) + this._options.text.sizeSymbols[i]; }, _wrapCallbacks: function() { var self, safeCallback; self = this; safeCallback = function(name, callback, args) { var errorMsg; try { return callback.apply(self, args); } catch (exception) { errorMsg = exception.message || exception.toString(); self.log("Caught exception in '" + name + "' callback - " + errorMsg, "error"); } }; /* jshint forin: false, loopfunc: true */ for (var prop in this._options.callbacks) { (function() { var callbackName, callbackFunc; callbackName = prop; callbackFunc = self._options.callbacks[callbackName]; self._options.callbacks[callbackName] = function() { return safeCallback(callbackName, callbackFunc, arguments); }; }()); } }, _parseFileOrBlobDataName: function(fileOrBlobData) { var name; if (qq.isFileOrInput(fileOrBlobData)) { if (fileOrBlobData.value) { // it is a file input // get input value and remove path to normalize name = fileOrBlobData.value.replace(/.*(\/|\\)/, ""); } else { // fix missing properties in Safari 4 and firefox 11.0a2 name = (fileOrBlobData.fileName !== null && fileOrBlobData.fileName !== undefined) ? fileOrBlobData.fileName : fileOrBlobData.name; } } else { name = fileOrBlobData.name; } return name; }, _parseFileOrBlobDataSize: function(fileOrBlobData) { var size; if (qq.isFileOrInput(fileOrBlobData)) { if (fileOrBlobData.value === undefined) { // fix missing properties in Safari 4 and firefox 11.0a2 size = (fileOrBlobData.fileSize !== null && fileOrBlobData.fileSize !== undefined) ? fileOrBlobData.fileSize : fileOrBlobData.size; } } else { size = fileOrBlobData.blob.size; } return size; }, _getValidationDescriptor: function(fileOrBlobData) { var fileDescriptor = {}, name = this._parseFileOrBlobDataName(fileOrBlobData), size = this._parseFileOrBlobDataSize(fileOrBlobData); fileDescriptor.name = name; if (size !== undefined) { fileDescriptor.size = size; } return fileDescriptor; }, _getValidationDescriptors: function(fileWrappers) { var self = this, fileDescriptors = []; qq.each(fileWrappers, function(idx, fileWrapper) { fileDescriptors.push(self._getValidationDescriptor(fileWrapper.file)); }); return fileDescriptors; }, _createStore: function(initialValue, readOnlyValues) { var store = {}, catchall = initialValue, copy = function(orig) { if (qq.isObject(orig)) { return qq.extend({}, orig); } return orig; }, getReadOnlyValues = function() { if (qq.isFunction(readOnlyValues)) { return readOnlyValues(); } return readOnlyValues; }, includeReadOnlyValues = function(existing) { if (readOnlyValues && qq.isObject(existing)) { qq.extend(existing, getReadOnlyValues()); } }; return { set: function(val, id) { /*jshint eqeqeq: true, eqnull: true*/ if (id == null) { store = {}; catchall = copy(val); } else { store[id] = copy(val); } }, get: function(id) { var values; /*jshint eqeqeq: true, eqnull: true*/ if (id != null && store[id]) { values = store[id]; } else { values = catchall; } includeReadOnlyValues(values); return copy(values); }, remove: function(fileId) { return delete store[fileId]; }, reset: function() { store = {}; catchall = initialValue; } }; }, // Allows camera access on either the default or an extra button for iOS devices. _handleCameraAccess: function() { if (this._options.camera.ios && qq.ios()) { var acceptIosCamera = "image/*;capture=camera", button = this._options.camera.button, buttonId = button ? this._getButtonId(button) : this._defaultButtonId, optionRoot = this._options; // If we are not targeting the default button, it is an "extra" button if (buttonId && buttonId !== this._defaultButtonId) { optionRoot = this._extraButtonSpecs[buttonId]; } // Camera access won't work in iOS if the `multiple` attribute is present on the file input optionRoot.multiple = false; // update the options if (optionRoot.validation.acceptFiles === null) { optionRoot.validation.acceptFiles = acceptIosCamera; } else { optionRoot.validation.acceptFiles += "," + acceptIosCamera; } // update the already-created button qq.each(this._buttons, function(idx, button) { if (button.getButtonId() === buttonId) { button.setMultiple(optionRoot.multiple); button.setAcceptFiles(optionRoot.acceptFiles); return false; } }); } }, // Get the validation options for this button. Could be the default validation option // or a specific one assigned to this particular button. _getValidationBase: function(buttonId) { var extraButtonSpec = this._extraButtonSpecs[buttonId]; return extraButtonSpec ? extraButtonSpec.validation : this._options.validation; } }; }()); /*globals qq*/ (function(){ "use strict"; qq.FineUploaderBasic = function(o) { // These options define FineUploaderBasic mode. this._options = { debug: false, button: null, multiple: true, maxConnections: 3, disableCancelForFormUploads: false, autoUpload: true, request: { endpoint: "/server/upload", params: {}, paramsInBody: true, customHeaders: {}, forceMultipart: true, inputName: "qqfile", uuidName: "qquuid", totalFileSizeName: "qqtotalfilesize", filenameParam: "qqfilename" }, validation: { allowedExtensions: [], sizeLimit: 0, minSizeLimit: 0, itemLimit: 0, stopOnFirstInvalidFile: true, acceptFiles: null, image: { maxHeight: 0, maxWidth: 0, minHeight: 0, minWidth: 0 } }, callbacks: { onSubmit: function(id, name){}, onSubmitted: function(id, name){}, onComplete: function(id, name, responseJSON, maybeXhr){}, onAllComplete: function(successful, failed) {}, onCancel: function(id, name){}, onUpload: function(id, name){}, onUploadChunk: function(id, name, chunkData){}, onUploadChunkSuccess: function(id, chunkData, responseJSON, xhr){}, onResume: function(id, fileName, chunkData){}, onProgress: function(id, name, loaded, total){}, onError: function(id, name, reason, maybeXhrOrXdr) {}, onAutoRetry: function(id, name, attemptNumber) {}, onManualRetry: function(id, name) {}, onValidateBatch: function(fileOrBlobData) {}, onValidate: function(fileOrBlobData) {}, onSubmitDelete: function(id) {}, onDelete: function(id){}, onDeleteComplete: function(id, xhrOrXdr, isError){}, onPasteReceived: function(blob) {}, onStatusChange: function(id, oldStatus, newStatus) {}, onSessionRequestComplete: function(response, success, xhrOrXdr) {} }, messages: { typeError: "{file} has an invalid extension. Valid extension(s): {extensions}.", sizeError: "{file} is too large, maximum file size is {sizeLimit}.", minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.", emptyError: "{file} is empty, please select files again without it.", noFilesError: "No files to upload.", tooManyItemsError: "Too many items ({netItems}) would be uploaded. Item limit is {itemLimit}.", maxHeightImageError: "Image is too tall.", maxWidthImageError: "Image is too wide.", minHeightImageError: "Image is not tall enough.", minWidthImageError: "Image is not wide enough.", retryFailTooManyItems: "Retry failed - you have reached your file limit.", onLeave: "The files are being uploaded, if you leave now the upload will be canceled." }, retry: { enableAuto: false, maxAutoAttempts: 3, autoAttemptDelay: 5, preventRetryResponseProperty: "preventRetry" }, classes: { buttonHover: "qq-upload-button-hover", buttonFocus: "qq-upload-button-focus" }, chunking: { enabled: false, partSize: 2000000, paramNames: { partIndex: "qqpartindex", partByteOffset: "qqpartbyteoffset", chunkSize: "qqchunksize", totalFileSize: "qqtotalfilesize", totalParts: "qqtotalparts" } }, resume: { enabled: false, id: null, cookiesExpireIn: 7, //days paramNames: { resuming: "qqresume" } }, formatFileName: function(fileOrBlobName) { if (fileOrBlobName !== undefined && fileOrBlobName.length > 33) { fileOrBlobName = fileOrBlobName.slice(0, 19) + "..." + fileOrBlobName.slice(-14); } return fileOrBlobName; }, text: { defaultResponseError: "Upload failure reason unknown", sizeSymbols: ["kB", "MB", "GB", "TB", "PB", "EB"] }, deleteFile : { enabled: false, method: "DELETE", endpoint: "/server/upload", customHeaders: {}, params: {} }, cors: { expected: false, sendCredentials: false, allowXdr: false }, blobs: { defaultName: "misc_data" }, paste: { targetElement: null, defaultName: "pasted_image" }, camera: { ios: false, // if ios is true: button is null means target the default button, otherwise target the button specified button: null }, // This refers to additional upload buttons to be handled by Fine Uploader. // Each element is an object, containing `element` as the only required // property. The `element` must be a container that will ultimately // contain an invisible `<input type="file">` created by Fine Uploader. // Optional properties of each object include `multiple`, `validation`, // and `folders`. extraButtons: [], // Depends on the session module. Used to query the server for an initial file list // during initialization and optionally after a `reset`. session: { endpoint: null, params: {}, customHeaders: {}, refreshOnReset: true }, // Send parameters associated with an existing form along with the files form: { // Element ID, HTMLElement, or null element: "qq-form", // Overrides the base `autoUpload`, unless `element` is null. autoUpload: false, // true = upload files on form submission (and squelch submit event) interceptSubmit: true } }; // Replace any default options with user defined ones qq.extend(this._options, o, true); this._buttons = []; this._extraButtonSpecs = {}; this._buttonIdsForFileIds = []; this._wrapCallbacks(); this._disposeSupport = new qq.DisposeSupport(); this._storedIds = []; this._autoRetries = []; this._retryTimeouts = []; this._preventRetries = []; this._thumbnailUrls = []; this._netUploadedOrQueued = 0; this._netUploaded = 0; this._uploadData = this._createUploadDataTracker(); this._initFormSupportAndParams(); this._deleteFileParamsStore = this._createStore(this._options.deleteFile.params); this._endpointStore = this._createStore(this._options.request.endpoint); this._deleteFileEndpointStore = this._createStore(this._options.deleteFile.endpoint); this._handler = this._createUploadHandler(); this._deleteHandler = qq.DeleteFileAjaxRequester && this._createDeleteHandler(); if (this._options.button) { this._defaultButtonId = this._createUploadButton({element: this._options.button}).getButtonId(); } this._generateExtraButtonSpecs(); this._handleCameraAccess(); if (this._options.paste.targetElement) { if (qq.PasteSupport) { this._pasteHandler = this._createPasteHandler(); } else { qq.log("Paste support module not found", "info"); } } this._preventLeaveInProgress(); this._imageGenerator = qq.ImageGenerator && new qq.ImageGenerator(qq.bind(this.log, this)); this._refreshSessionData(); this._succeededSinceLastAllComplete = []; this._failedSinceLastAllComplete = []; }; // Define the private & public API methods. qq.FineUploaderBasic.prototype = qq.basePublicApi; qq.extend(qq.FineUploaderBasic.prototype, qq.basePrivateApi); }()); /*globals qq, XDomainRequest*/ /** Generic class for sending non-upload ajax requests and handling the associated responses **/ qq.AjaxRequester = function (o) { "use strict"; var log, shouldParamsBeInQueryString, queue = [], requestData = {}, options = { validMethods: ["POST"], method: "POST", contentType: "application/x-www-form-urlencoded", maxConnections: 3, customHeaders: {}, endpointStore: {}, paramsStore: {}, mandatedParams: {}, allowXRequestedWithAndCacheControl: true, successfulResponseCodes: { "DELETE": [200, 202, 204], "POST": [200, 204], "GET": [200] }, cors: { expected: false, sendCredentials: false }, log: function (str, level) {}, onSend: function (id) {}, onComplete: function (id, xhrOrXdr, isError) {}, onProgress: null }; qq.extend(options, o); log = options.log; if (qq.indexOf(options.validMethods, options.method) < 0) { throw new Error("'" + options.method + "' is not a supported method for this type of request!"); } // [Simple methods](http://www.w3.org/TR/cors/#simple-method) // are defined by the W3C in the CORS spec as a list of methods that, in part, // make a CORS request eligible to be exempt from preflighting. function isSimpleMethod() { return qq.indexOf(["GET", "POST", "HEAD"], options.method) >= 0; } // [Simple headers](http://www.w3.org/TR/cors/#simple-header) // are defined by the W3C in the CORS spec as a list of headers that, in part, // make a CORS request eligible to be exempt from preflighting. function containsNonSimpleHeaders(headers) { var containsNonSimple = false; qq.each(containsNonSimple, function(idx, header) { if (qq.indexOf(["Accept", "Accept-Language", "Content-Language", "Content-Type"], header) < 0) { containsNonSimple = true; return false; } }); return containsNonSimple; } function isXdr(xhr) { //The `withCredentials` test is a commonly accepted way to determine if XHR supports CORS. return options.cors.expected && xhr.withCredentials === undefined; } // Returns either a new `XMLHttpRequest` or `XDomainRequest` instance. function getCorsAjaxTransport() { var xhrOrXdr; if (window.XMLHttpRequest || window.ActiveXObject) { xhrOrXdr = qq.createXhrInstance(); if (xhrOrXdr.withCredentials === undefined) { xhrOrXdr = new XDomainRequest(); } } return xhrOrXdr; } // Returns either a new XHR/XDR instance, or an existing one for the associated `File` or `Blob`. function getXhrOrXdr(id, dontCreateIfNotExist) { var xhrOrXdr = requestData[id].xhr; if (!xhrOrXdr && !dontCreateIfNotExist) { if (options.cors.expected) { xhrOrXdr = getCorsAjaxTransport(); } else { xhrOrXdr = qq.createXhrInstance(); } requestData[id].xhr = xhrOrXdr; } return xhrOrXdr; } // Removes element from queue, sends next request function dequeue(id) { var i = qq.indexOf(queue, id), max = options.maxConnections, nextId; delete requestData[id]; queue.splice(i, 1); if (queue.length >= max && i < max) { nextId = queue[max - 1]; sendRequest(nextId); } } function onComplete(id, xdrError) { var xhr = getXhrOrXdr(id), method = options.method, isError = xdrError === true; dequeue(id); if (isError) { log(method + " request for " + id + " has failed", "error"); } else if (!isXdr(xhr) && !isResponseSuccessful(xhr.status)) { isError = true; log(method + " request for " + id + " has failed - response code " + xhr.status, "error"); } options.onComplete(id, xhr, isError); } function getParams(id) { var onDemandParams = requestData[id].additionalParams, mandatedParams = options.mandatedParams, params; if (options.paramsStore.get) { params = options.paramsStore.get(id); } if (onDemandParams) { qq.each(onDemandParams, function (name, val) { params = params || {}; params[name] = val; }); } if (mandatedParams) { qq.each(mandatedParams, function (name, val) { params = params || {}; params[name] = val; }); } return params; } function sendRequest(id) { var xhr = getXhrOrXdr(id), method = options.method, params = getParams(id), payload = requestData[id].payload, url; options.onSend(id); url = createUrl(id, params); // XDR and XHR status detection APIs differ a bit. if (isXdr(xhr)) { xhr.onload = getXdrLoadHandler(id); xhr.onerror = getXdrErrorHandler(id); } else { xhr.onreadystatechange = getXhrReadyStateChangeHandler(id); } registerForUploadProgress(id); // The last parameter is assumed to be ignored if we are actually using `XDomainRequest`. xhr.open(method, url, true); // Instruct the transport to send cookies along with the CORS request, // unless we are using `XDomainRequest`, which is not capable of this. if (options.cors.expected && options.cors.sendCredentials && !isXdr(xhr)) { xhr.withCredentials = true; } setHeaders(id); log("Sending " + method + " request for " + id); if (payload) { xhr.send(payload); } else if (shouldParamsBeInQueryString || !params) { xhr.send(); } else if (params && options.contentType && options.contentType.toLowerCase().indexOf("application/x-www-form-urlencoded") >= 0) { xhr.send(qq.obj2url(params, "")); } else if (params && options.contentType && options.contentType.toLowerCase().indexOf("application/json") >= 0) { xhr.send(JSON.stringify(params)); } else { xhr.send(params); } return xhr; } function createUrl(id, params) { var endpoint = options.endpointStore.get(id), addToPath = requestData[id].addToPath; /*jshint -W116,-W041 */ if (addToPath != undefined) { endpoint += "/" + addToPath; } if (shouldParamsBeInQueryString && params) { return qq.obj2url(params, endpoint); } else { return endpoint; } } // Invoked by the UA to indicate a number of possible states that describe // a live `XMLHttpRequest` transport. function getXhrReadyStateChangeHandler(id) { return function () { if (getXhrOrXdr(id).readyState === 4) { onComplete(id); } }; } function registerForUploadProgress(id) { var onProgress = options.onProgress; if (onProgress) { getXhrOrXdr(id).upload.onprogress = function(e) { if (e.lengthComputable) { onProgress(id, e.loaded, e.total); } }; } } // This will be called by IE to indicate **success** for an associated // `XDomainRequest` transported request. function getXdrLoadHandler(id) { return function () { onComplete(id); }; } // This will be called by IE to indicate **failure** for an associated // `XDomainRequest` transported request. function getXdrErrorHandler(id) { return function () { onComplete(id, true); }; } function setHeaders(id) { var xhr = getXhrOrXdr(id), customHeaders = options.customHeaders, onDemandHeaders = requestData[id].additionalHeaders || {}, method = options.method, allHeaders = {}; // If XDomainRequest is being used, we can't set headers, so just ignore this block. if (!isXdr(xhr)) { // Only attempt to add X-Requested-With & Cache-Control if permitted if (options.allowXRequestedWithAndCacheControl) { // Do not add X-Requested-With & Cache-Control if this is a cross-origin request // OR the cross-origin request contains a non-simple method or header. // This is done to ensure a preflight is not triggered exclusively based on the // addition of these 2 non-simple headers. if (!options.cors.expected || (!isSimpleMethod() || containsNonSimpleHeaders(customHeaders))) { xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); xhr.setRequestHeader("Cache-Control", "no-cache"); } } if (options.contentType && (method === "POST" || method === "PUT")) { xhr.setRequestHeader("Content-Type", options.contentType); } qq.extend(allHeaders, qq.isFunction(customHeaders) ? customHeaders(id) : customHeaders); qq.extend(allHeaders, onDemandHeaders); qq.each(allHeaders, function (name, val) { xhr.setRequestHeader(name, val); }); } } function isResponseSuccessful(responseCode) { return qq.indexOf(options.successfulResponseCodes[options.method], responseCode) >= 0; } function prepareToSend(id, addToPath, additionalParams, additionalHeaders, payload) { requestData[id] = { addToPath: addToPath, additionalParams: additionalParams, additionalHeaders: additionalHeaders, payload: payload }; var len = queue.push(id); // if too many active connections, wait... if (len <= options.maxConnections) { return sendRequest(id); } } shouldParamsBeInQueryString = options.method === "GET" || options.method === "DELETE"; qq.extend(this, { // Start the process of sending the request. The ID refers to the file associated with the request. initTransport: function(id) { var path, params, headers, payload, cacheBuster; return { // Optionally specify the end of the endpoint path for the request. withPath: function(appendToPath) { path = appendToPath; return this; }, // Optionally specify additional parameters to send along with the request. // These will be added to the query string for GET/DELETE requests or the payload // for POST/PUT requests. The Content-Type of the request will be used to determine // how these parameters should be formatted as well. withParams: function(additionalParams) { params = additionalParams; return this; }, // Optionally specify additional headers to send along with the request. withHeaders: function(additionalHeaders) { headers = additionalHeaders; return this; }, // Optionally specify a payload/body for the request. withPayload: function(thePayload) { payload = thePayload; return this; }, // Appends a cache buster (timestamp) to the request URL as a query parameter (only if GET or DELETE) withCacheBuster: function() { cacheBuster = true; return this; }, // Send the constructed request. send: function() { if (cacheBuster && qq.indexOf(["GET", "DELETE"], options.method) >= 0) { params.qqtimestamp = new Date().getTime(); } return prepareToSend(id, path, params, headers, payload); } }; }, canceled: function(id) { dequeue(id); } }); }; /*globals qq*/ /** * Base upload handler module. Delegates to more specific handlers. * * @param o Options. Passed along to the specific handler submodule as well. * @param namespace [optional] Namespace for the specific handler. */ qq.UploadHandler = function(o, namespace) { "use strict"; var queue = [], options, log, handlerImpl; // Default options, can be overridden by the user options = { debug: false, forceMultipart: true, paramsInBody: false, paramsStore: {}, endpointStore: {}, filenameParam: "qqfilename", cors: { expected: false, sendCredentials: false }, maxConnections: 3, // maximum number of concurrent uploads uuidName: "qquuid", totalFileSizeName: "qqtotalfilesize", chunking: { enabled: false, partSize: 2000000, //bytes paramNames: { partIndex: "qqpartindex", partByteOffset: "qqpartbyteoffset", chunkSize: "qqchunksize", totalParts: "qqtotalparts", filename: "qqfilename" } }, resume: { enabled: false, id: null, cookiesExpireIn: 7, //days paramNames: { resuming: "qqresume" } }, log: function(str, level) {}, onProgress: function(id, fileName, loaded, total){}, onComplete: function(id, fileName, response, xhr){}, onCancel: function(id, fileName){}, onUpload: function(id, fileName){}, onUploadChunk: function(id, fileName, chunkData){}, onUploadChunkSuccess: function(id, chunkData, response, xhr){}, onAutoRetry: function(id, fileName, response, xhr){}, onResume: function(id, fileName, chunkData){}, onUuidChanged: function(id, newUuid){}, getName: function(id) {} }; qq.extend(options, o); log = options.log; /** * Removes element from queue, starts upload of next */ function dequeue(id) { var i = qq.indexOf(queue, id), max = options.maxConnections, nextId; if (i >= 0) { queue.splice(i, 1); if (queue.length >= max && i < max){ nextId = queue[max-1]; handlerImpl.upload(nextId); } } } function cancelSuccess(id) { log("Cancelling " + id); options.paramsStore.remove(id); dequeue(id); } function determineHandlerImpl() { var handlerType = namespace ? qq[namespace] : qq, handlerModuleSubtype = qq.supportedFeatures.ajaxUploading ? "Xhr" : "Form"; handlerImpl = new handlerType["UploadHandler" + handlerModuleSubtype]( options, {onUploadComplete: dequeue, onUuidChanged: options.onUuidChanged, getName: options.getName, getUuid: options.getUuid, getSize: options.getSize, log: log} ); } qq.extend(this, { /** * Adds file or file input to the queue * @returns id **/ add: function(id, file) { return handlerImpl.add.apply(this, arguments); }, /** * Sends the file identified by id */ upload: function(id) { var len = queue.push(id); // if too many active uploads, wait... if (len <= options.maxConnections){ handlerImpl.upload(id); return true; } return false; }, retry: function(id) { var i = qq.indexOf(queue, id); if (i >= 0) { return handlerImpl.upload(id, true); } else { return this.upload(id); } }, /** * Cancels file upload by id */ cancel: function(id) { var cancelRetVal = handlerImpl.cancel(id); if (cancelRetVal instanceof qq.Promise) { cancelRetVal.then(function() { cancelSuccess(id); }); } else if (cancelRetVal !== false) { cancelSuccess(id); } }, /** * Cancels all queued or in-progress uploads */ cancelAll: function() { var self = this, queueCopy = []; qq.extend(queueCopy, queue); qq.each(queueCopy, function(idx, fileId) { self.cancel(fileId); }); queue = []; }, getFile: function(id) { if (handlerImpl.getFile) { return handlerImpl.getFile(id); } }, getInput: function(id) { if (handlerImpl.getInput) { return handlerImpl.getInput(id); } }, reset: function() { log("Resetting upload handler"); this.cancelAll(); queue = []; handlerImpl.reset(); }, expunge: function(id) { if (this.isValid(id)) { return handlerImpl.expunge(id); } }, /** * Determine if the file exists. */ isValid: function(id) { return handlerImpl.isValid(id); }, getResumableFilesData: function() { if (handlerImpl.getResumableFilesData) { return handlerImpl.getResumableFilesData(); } return []; }, /** * This may or may not be implemented, depending on the handler. For handlers where a third-party ID is * available (such as the "key" for Amazon S3), this will return that value. Otherwise, the return value * will be undefined. * * @param id Internal file ID * @returns {*} Some identifier used by a 3rd-party service involved in the upload process */ getThirdPartyFileId: function(id) { if (handlerImpl.getThirdPartyFileId && this.isValid(id)) { return handlerImpl.getThirdPartyFileId(id); } }, /** * Attempts to pause the associated upload if the specific handler supports this and the file is "valid". * @param id ID of the upload/file to pause * @returns {boolean} true if the upload was paused */ pause: function(id) { if (handlerImpl.pause && this.isValid(id) && handlerImpl.pause(id)) { dequeue(id); return true; } } }); determineHandlerImpl(); }; /* globals qq */ /** * Common APIs exposed to creators of upload via form/iframe handlers. This is reused and possibly overridden * in some cases by specific form upload handlers. * * @constructor */ qq.AbstractUploadHandlerForm = function(spec) { "use strict"; var options = spec.options, handler = this, proxy = spec.proxy, formHandlerInstanceId = qq.getUniqueId(), onloadCallbacks = {}, detachLoadEvents = {}, postMessageCallbackTimers = {}, isCors = options.isCors, fileState = {}, inputName = options.inputName, onCancel = proxy.onCancel, onUuidChanged = proxy.onUuidChanged, getName = proxy.getName, getUuid = proxy.getUuid, log = proxy.log, corsMessageReceiver = new qq.WindowReceiveMessage({log: log}); /** * Remove any trace of the file from the handler. * * @param id ID of the associated file */ function expungeFile(id) { delete detachLoadEvents[id]; delete fileState[id]; // If we are dealing with CORS, we might still be waiting for a response from a loaded iframe. // In that case, terminate the timer waiting for a message from the loaded iframe // and stop listening for any more messages coming from this iframe. if (isCors) { clearTimeout(postMessageCallbackTimers[id]); delete postMessageCallbackTimers[id]; corsMessageReceiver.stopReceivingMessages(id); } var iframe = document.getElementById(handler._getIframeName(id)); if (iframe) { // To cancel request set src to something else. We use src="javascript:false;" // because it doesn't trigger ie6 prompt on https iframe.setAttribute("src", "java" + String.fromCharCode(115) + "cript:false;"); //deal with "JSLint: javascript URL" warning, which apparently cannot be turned off qq(iframe).remove(); } } /** * If we are in CORS mode, we must listen for messages (containing the server response) from the associated * iframe, since we cannot directly parse the content of the iframe due to cross-origin restrictions. * * @param iframe Listen for messages on this iframe. * @param callback Invoke this callback with the message from the iframe. */ function registerPostMessageCallback(iframe, callback) { var iframeName = iframe.id, fileId = getFileIdForIframeName(iframeName), uuid = getUuid(fileId); onloadCallbacks[uuid] = callback; // When the iframe has loaded (after the server responds to an upload request) // declare the attempt a failure if we don't receive a valid message shortly after the response comes in. detachLoadEvents[fileId] = qq(iframe).attach("load", function() { if (fileState[fileId].input) { log("Received iframe load event for CORS upload request (iframe name " + iframeName + ")"); postMessageCallbackTimers[iframeName] = setTimeout(function() { var errorMessage = "No valid message received from loaded iframe for iframe name " + iframeName; log(errorMessage, "error"); callback({ error: errorMessage }); }, 1000); } }); // Listen for messages coming from this iframe. When a message has been received, cancel the timer // that declares the upload a failure if a message is not received within a reasonable amount of time. corsMessageReceiver.receiveMessage(iframeName, function(message) { log("Received the following window message: '" + message + "'"); var fileId = getFileIdForIframeName(iframeName), response = handler._parseJsonResponse(fileId, message), uuid = response.uuid, onloadCallback; if (uuid && onloadCallbacks[uuid]) { log("Handling response for iframe name " + iframeName); clearTimeout(postMessageCallbackTimers[iframeName]); delete postMessageCallbackTimers[iframeName]; handler._detachLoadEvent(iframeName); onloadCallback = onloadCallbacks[uuid]; delete onloadCallbacks[uuid]; corsMessageReceiver.stopReceivingMessages(iframeName); onloadCallback(response); } else if (!uuid) { log("'" + message + "' does not contain a UUID - ignoring."); } }); } /** * Generates an iframe to be used as a target for upload-related form submits. This also adds the iframe * to the current `document`. Note that the iframe is hidden from view. * * @param name Name of the iframe. * @returns {HTMLIFrameElement} The created iframe */ function initIframeForUpload(name) { var iframe = qq.toElement("<iframe src='javascript:false;' name='" + name + "' />"); iframe.setAttribute("id", name); iframe.style.display = "none"; document.body.appendChild(iframe); return iframe; } /** * @param iframeName `document`-unique Name of the associated iframe * @returns {*} ID of the associated file */ function getFileIdForIframeName(iframeName) { return iframeName.split("_")[0]; } qq.extend(this, { add: function(id, fileInput) { fileState[id] = {input: fileInput}; fileInput.setAttribute("name", inputName); // remove file input from DOM if (fileInput.parentNode){ qq(fileInput).remove(); } }, getInput: function(id) { return fileState[id].input; }, isValid: function(id) { return fileState[id] !== undefined && fileState[id].input !== undefined; }, reset: function() { fileState.length = 0; }, expunge: function(id) { return expungeFile(id); }, cancel: function(id) { var onCancelRetVal = onCancel(id, getName(id)); if (onCancelRetVal instanceof qq.Promise) { return onCancelRetVal.then(function() { this.expunge(id); }); } else if (onCancelRetVal !== false) { this.expunge(id); return true; } return false; }, upload: function(id) { // implementation-specific }, /** * @param fileId ID of the associated file * @returns {string} The `document`-unique name of the iframe */ _getIframeName: function(fileId) { return fileId + "_" + formHandlerInstanceId; }, /** * Creates an iframe with a specific document-unique name. * * @param id ID of the associated file * @returns {HTMLIFrameElement} */ _createIframe: function(id) { var iframeName = handler._getIframeName(id); return initIframeForUpload(iframeName); }, /** * @param id ID of the associated file * @param innerHtmlOrMessage JSON message * @returns {*} The parsed response, or an empty object if the response could not be parsed */ _parseJsonResponse: function(id, innerHtmlOrMessage) { var response; try { response = qq.parseJson(innerHtmlOrMessage); if (response.newUuid !== undefined) { onUuidChanged(id, response.newUuid); } } catch(error) { log("Error when attempting to parse iframe upload response (" + error.message + ")", "error"); response = {}; } return response; }, /** * Generates a form element and appends it to the `document`. When the form is submitted, a specific iframe is targeted. * The name of the iframe is passed in as a property of the spec parameter, and must be unique in the `document`. Note * that the form is hidden from view. * * @param spec An object containing various properties to be used when constructing the form. Required properties are * currently: `method`, `endpoint`, `params`, `paramsInBody`, and `targetName`. * @returns {HTMLFormElement} The created form */ _initFormForUpload: function(spec) { var method = spec.method, endpoint = spec.endpoint, params = spec.params, paramsInBody = spec.paramsInBody, targetName = spec.targetName, form = qq.toElement("<form method='" + method + "' enctype='multipart/form-data'></form>"), url = endpoint; if (paramsInBody) { qq.obj2Inputs(params, form); } else { url = qq.obj2url(params, endpoint); } form.setAttribute("action", url); form.setAttribute("target", targetName); form.style.display = "none"; document.body.appendChild(form); return form; }, /** * This function either delegates to a more specific message handler if CORS is involved, * or simply registers a callback when the iframe has been loaded that invokes the passed callback * after determining if the content of the iframe is accessible. * * @param iframe Associated iframe * @param callback Callback to invoke after we have determined if the iframe content is accessible. */ _attachLoadEvent: function(iframe, callback) { /*jslint eqeq: true*/ var responseDescriptor; if (isCors) { registerPostMessageCallback(iframe, callback); } else { detachLoadEvents[iframe.id] = qq(iframe).attach("load", function(){ log("Received response for " + iframe.id); // when we remove iframe from dom // the request stops, but in IE load // event fires if (!iframe.parentNode){ return; } try { // fixing Opera 10.53 if (iframe.contentDocument && iframe.contentDocument.body && iframe.contentDocument.body.innerHTML == "false"){ // In Opera event is fired second time // when body.innerHTML changed from false // to server response approx. after 1 sec // when we upload file with iframe return; } } catch (error) { //IE may throw an "access is denied" error when attempting to access contentDocument on the iframe in some cases log("Error when attempting to access iframe during handling of upload response (" + error.message + ")", "error"); responseDescriptor = {success: false}; } callback(responseDescriptor); }); } }, /** * Called when we are no longer interested in being notified when an iframe has loaded. * * @param id Associated file ID */ _detachLoadEvent: function(id) { if (detachLoadEvents[id] !== undefined) { detachLoadEvents[id](); delete detachLoadEvents[id]; } }, _getFileState: function(id) { return fileState[id]; } }); }; /* globals qq */ /** * Common API exposed to creators of XHR handlers. This is reused and possibly overriding in some cases by specific * XHR upload handlers. * * @constructor */ qq.AbstractUploadHandlerXhr = function(spec) { "use strict"; var publicApi = this, options = spec.options, proxy = spec.proxy, fileState = {}, chunking = options.chunking, onUpload = proxy.onUpload, onCancel = proxy.onCancel, getName = proxy.getName, getSize = proxy.getSize, log = proxy.log; function getChunk(fileOrBlob, startByte, endByte) { if (fileOrBlob.slice) { return fileOrBlob.slice(startByte, endByte); } else if (fileOrBlob.mozSlice) { return fileOrBlob.mozSlice(startByte, endByte); } else if (fileOrBlob.webkitSlice) { return fileOrBlob.webkitSlice(startByte, endByte); } } function abort(id) { var xhr = fileState[id].xhr, ajaxRequester = fileState[id].currentAjaxRequester; xhr.onreadystatechange = null; xhr.upload.onprogress = null; xhr.abort(); ajaxRequester && ajaxRequester.canceled && ajaxRequester.canceled(id); } qq.extend(this, { /** * Adds File or Blob to the queue **/ add: function(id, fileOrBlobData) { if (qq.isFile(fileOrBlobData)) { fileState[id] = {file: fileOrBlobData}; } else if (qq.isBlob(fileOrBlobData.blob)) { fileState[id] = {blobData: fileOrBlobData}; } else { throw new Error("Passed obj is not a File or BlobData (in qq.UploadHandlerXhr)"); } }, getFile: function(id) { if (fileState[id]) { return fileState[id].file || fileState[id].blobData.blob; } }, isValid: function(id) { return fileState[id] !== undefined; }, reset: function() { fileState.length = 0; }, expunge: function(id) { var xhr = fileState[id].xhr; xhr && abort(id); delete fileState[id]; }, /** * Sends the file identified by id to the server */ upload: function(id, retry) { fileState[id] && delete fileState[id].paused; return onUpload(id, retry); }, cancel: function(id) { var onCancelRetVal = onCancel(id, getName(id)); if (onCancelRetVal instanceof qq.Promise) { return onCancelRetVal.then(function() { fileState[id].canceled = true; this.expunge(id); }); } else if (onCancelRetVal !== false) { fileState[id].canceled = true; this.expunge(id); return true; } return false; }, pause: function(id) { var xhr = fileState[id].xhr; if(xhr) { log(qq.format("Aborting XHR upload for {} '{}' due to pause instruction.", id, getName(id))); fileState[id].paused = true; abort(id); return true; } }, /** * Creates an XHR instance for this file and stores it in the fileState. * * @param id File ID * @returns {XMLHttpRequest} */ _createXhr: function(id) { return this._registerXhr(id, qq.createXhrInstance()); }, /** * Registers an XHR transport instance created elsewhere. * * @param id ID of the associated file * @param xhr XMLHttpRequest object instance * @returns {XMLHttpRequest} */ _registerXhr: function(id, xhr, ajaxRequester) { fileState[id].xhr = xhr; fileState[id].currentAjaxRequester = ajaxRequester; return xhr; }, _getMimeType: function(id) { return publicApi.getFile(id).type; }, /** * @param id ID of the associated file * @returns {number} Number of parts this file can be divided into, or undefined if chunking is not supported in this UA */ _getTotalChunks: function(id) { if (chunking) { var fileSize = getSize(id), chunkSize = chunking.partSize; return Math.ceil(fileSize / chunkSize); } }, _getChunkData: function(id, chunkIndex) { var chunkSize = chunking.partSize, fileSize = getSize(id), fileOrBlob = publicApi.getFile(id), startBytes = chunkSize * chunkIndex, endBytes = startBytes+chunkSize >= fileSize ? fileSize : startBytes+chunkSize, totalChunks = this._getTotalChunks(id); return { part: chunkIndex, start: startBytes, end: endBytes, count: totalChunks, blob: getChunk(fileOrBlob, startBytes, endBytes), size: endBytes - startBytes }; }, _getChunkDataForCallback: function(chunkData) { return { partIndex: chunkData.part, startByte: chunkData.start + 1, endByte: chunkData.end, totalParts: chunkData.count }; }, _getFileState: function(id) { return fileState[id]; } }); }; /*globals qq */ /*jshint -W117 */ qq.WindowReceiveMessage = function(o) { "use strict"; var options = { log: function(message, level) {} }, callbackWrapperDetachers = {}; qq.extend(options, o); qq.extend(this, { receiveMessage : function(id, callback) { var onMessageCallbackWrapper = function(event) { callback(event.data); }; if (window.postMessage) { callbackWrapperDetachers[id] = qq(window).attach("message", onMessageCallbackWrapper); } else { log("iframe message passing not supported in this browser!", "error"); } }, stopReceivingMessages : function(id) { if (window.postMessage) { var detacher = callbackWrapperDetachers[id]; if (detacher) { detacher(); } } } }); }; /*globals qq */ /** * Defines the public API for FineUploader mode. */ (function(){ "use strict"; qq.uiPublicApi = { clearStoredFiles: function() { this._parent.prototype.clearStoredFiles.apply(this, arguments); this._templating.clearFiles(); }, addExtraDropzone: function(element){ this._dnd && this._dnd.setupExtraDropzone(element); }, removeExtraDropzone: function(element){ if (this._dnd) { return this._dnd.removeDropzone(element); } }, getItemByFileId: function(id) { return this._templating.getFileContainer(id); }, reset: function() { this._parent.prototype.reset.apply(this, arguments); this._templating.reset(); if (!this._options.button && this._templating.getButton()) { this._defaultButtonId = this._createUploadButton({element: this._templating.getButton()}).getButtonId(); } if (this._dnd) { this._dnd.dispose(); this._dnd = this._setupDragAndDrop(); } this._totalFilesInBatch = 0; this._filesInBatchAddedToUi = 0; this._setupClickAndEditEventHandlers(); }, pauseUpload: function(id) { var paused = this._parent.prototype.pauseUpload.apply(this, arguments); paused && this._templating.uploadPaused(id); return paused; }, continueUpload: function(id) { var continued = this._parent.prototype.continueUpload.apply(this, arguments); continued && this._templating.uploadContinued(id); return continued; }, getId: function(fileContainerOrChildEl) { return this._templating.getFileId(fileContainerOrChildEl); }, getDropTarget: function(fileId) { var file = this.getFile(fileId); return file.qqDropTarget; } }; /** * Defines the private (internal) API for FineUploader mode. */ qq.uiPrivateApi = { _getButton: function(buttonId) { var button = this._parent.prototype._getButton.apply(this, arguments); if (!button) { if (buttonId === this._defaultButtonId) { button = this._templating.getButton(); } } return button; }, _removeFileItem: function(fileId) { this._templating.removeFile(fileId); }, _setupClickAndEditEventHandlers: function() { this._fileButtonsClickHandler = qq.FileButtonsClickHandler && this._bindFileButtonsClickEvent(); // A better approach would be to check specifically for focusin event support by querying the DOM API, // but the DOMFocusIn event is not exposed as a property, so we have to resort to UA string sniffing. this._focusinEventSupported = !qq.firefox(); if (this._isEditFilenameEnabled()) { this._filenameClickHandler = this._bindFilenameClickEvent(); this._filenameInputFocusInHandler = this._bindFilenameInputFocusInEvent(); this._filenameInputFocusHandler = this._bindFilenameInputFocusEvent(); } }, _setupDragAndDrop: function() { var self = this, dropZoneElements = this._options.dragAndDrop.extraDropzones, templating = this._templating, defaultDropZone = templating.getDropZone(); defaultDropZone && dropZoneElements.push(defaultDropZone); return new qq.DragAndDrop({ dropZoneElements: dropZoneElements, allowMultipleItems: this._options.multiple, classes: { dropActive: this._options.classes.dropActive }, callbacks: { processingDroppedFiles: function() { templating.showDropProcessing(); }, processingDroppedFilesComplete: function(files, targetEl) { templating.hideDropProcessing(); qq.each(files, function(idx, file) { file.qqDropTarget = targetEl; }); if (files.length) { self.addFiles(files, null, null); } }, dropError: function(code, errorData) { self._itemError(code, errorData); }, dropLog: function(message, level) { self.log(message, level); } } }); }, _bindFileButtonsClickEvent: function() { var self = this; return new qq.FileButtonsClickHandler({ templating: this._templating, log: function(message, lvl) { self.log(message, lvl); }, onDeleteFile: function(fileId) { self.deleteFile(fileId); }, onCancel: function(fileId) { self.cancel(fileId); }, onRetry: function(fileId) { qq(self._templating.getFileContainer(fileId)).removeClass(self._classes.retryable); self.retry(fileId); }, onPause: function(fileId) { self.pauseUpload(fileId); }, onContinue: function(fileId) { self.continueUpload(fileId); }, onGetName: function(fileId) { return self.getName(fileId); } }); }, _isEditFilenameEnabled: function() { /*jshint -W014 */ return this._templating.isEditFilenamePossible() && !this._options.autoUpload && qq.FilenameClickHandler && qq.FilenameInputFocusHandler && qq.FilenameInputFocusHandler; }, _filenameEditHandler: function() { var self = this, templating = this._templating; return { templating: templating, log: function(message, lvl) { self.log(message, lvl); }, onGetUploadStatus: function(fileId) { return self.getUploads({id: fileId}).status; }, onGetName: function(fileId) { return self.getName(fileId); }, onSetName: function(id, newName) { var formattedFilename = self._options.formatFileName(newName); templating.updateFilename(id, formattedFilename); self.setName(id, newName); }, onEditingStatusChange: function(id, isEditing) { var qqInput = qq(templating.getEditInput(id)), qqFileContainer = qq(templating.getFileContainer(id)); if (isEditing) { qqInput.addClass("qq-editing"); templating.hideFilename(id); templating.hideEditIcon(id); } else { qqInput.removeClass("qq-editing"); templating.showFilename(id); templating.showEditIcon(id); } // Force IE8 and older to repaint qqFileContainer.addClass("qq-temp").removeClass("qq-temp"); } }; }, _onUploadStatusChange: function(id, oldStatus, newStatus) { this._parent.prototype._onUploadStatusChange.apply(this, arguments); if (this._isEditFilenameEnabled()) { // Status for a file exists before it has been added to the DOM, so we must be careful here. if (this._templating.getFileContainer(id) && newStatus !== qq.status.SUBMITTED) { this._templating.markFilenameEditable(id); this._templating.hideEditIcon(id); } } }, _bindFilenameInputFocusInEvent: function() { var spec = qq.extend({}, this._filenameEditHandler()); return new qq.FilenameInputFocusInHandler(spec); }, _bindFilenameInputFocusEvent: function() { var spec = qq.extend({}, this._filenameEditHandler()); return new qq.FilenameInputFocusHandler(spec); }, _bindFilenameClickEvent: function() { var spec = qq.extend({}, this._filenameEditHandler()); return new qq.FilenameClickHandler(spec); }, _storeForLater: function(id) { this._parent.prototype._storeForLater.apply(this, arguments); this._templating.hideSpinner(id); }, _onSubmit: function(id, name) { this._parent.prototype._onSubmit.apply(this, arguments); this._addToList(id, name); }, // The file item has been added to the DOM. _onSubmitted: function(id) { // If the edit filename feature is enabled, mark the filename element as "editable" and the associated edit icon if (this._isEditFilenameEnabled()) { this._templating.markFilenameEditable(id); this._templating.showEditIcon(id); // If the focusin event is not supported, we must add a focus handler to the newly create edit filename text input if (!this._focusinEventSupported) { this._filenameInputFocusHandler.addHandler(this._templating.getEditInput(id)); } } }, // Update the progress bar & percentage as the file is uploaded _onProgress: function(id, name, loaded, total){ this._parent.prototype._onProgress.apply(this, arguments); this._templating.updateProgress(id, loaded, total); if (loaded === total) { this._templating.hideCancel(id); this._templating.hidePause(id); this._templating.setStatusText(id, this._options.text.waitingForResponse); // If last byte was sent, display total file size this._displayFileSize(id); } else { // If still uploading, display percentage - total size is actually the total request(s) size this._displayFileSize(id, loaded, total); } }, _onComplete: function(id, name, result, xhr) { var parentRetVal = this._parent.prototype._onComplete.apply(this, arguments), templating = this._templating, self = this; function completeUpload(result) { templating.setStatusText(id); qq(templating.getFileContainer(id)).removeClass(self._classes.retrying); templating.hideProgress(id); if (!self._options.disableCancelForFormUploads || qq.supportedFeatures.ajaxUploading) { templating.hideCancel(id); } templating.hideSpinner(id); if (result.success) { self._markFileAsSuccessful(id); } else { qq(templating.getFileContainer(id)).addClass(self._classes.fail); if (self._templating.isRetryPossible() && !self._preventRetries[id]) { qq(templating.getFileContainer(id)).addClass(self._classes.retryable); } self._controlFailureTextDisplay(id, result); } } // The parent may need to perform some async operation before we can accurately determine the status of the upload. if (parentRetVal instanceof qq.Promise) { parentRetVal.done(function(newResult) { completeUpload(newResult); }); } else { completeUpload(result); } return parentRetVal; }, _markFileAsSuccessful: function(id) { var templating = this._templating; if (this._isDeletePossible()) { templating.showDeleteButton(id); } qq(templating.getFileContainer(id)).addClass(this._classes.success); this._maybeUpdateThumbnail(id); }, _onUpload: function(id, name){ var parentRetVal = this._parent.prototype._onUpload.apply(this, arguments); this._templating.showSpinner(id); return parentRetVal; }, _onUploadChunk: function(id, chunkData) { this._parent.prototype._onUploadChunk.apply(this, arguments); // Only display the pause button if we have finished uploading at least one chunk chunkData.partIndex > 0 && this._templating.allowPause(id); }, _onCancel: function(id, name) { this._parent.prototype._onCancel.apply(this, arguments); this._removeFileItem(id); }, _onBeforeAutoRetry: function(id) { var retryNumForDisplay, maxAuto, retryNote; this._parent.prototype._onBeforeAutoRetry.apply(this, arguments); this._showCancelLink(id); if (this._options.retry.showAutoRetryNote) { retryNumForDisplay = this._autoRetries[id] + 1; maxAuto = this._options.retry.maxAutoAttempts; retryNote = this._options.retry.autoRetryNote.replace(/\{retryNum\}/g, retryNumForDisplay); retryNote = retryNote.replace(/\{maxAuto\}/g, maxAuto); this._templating.setStatusText(id, retryNote); qq(this._templating.getFileContainer(id)).addClass(this._classes.retrying); } }, //return false if we should not attempt the requested retry _onBeforeManualRetry: function(id) { if (this._parent.prototype._onBeforeManualRetry.apply(this, arguments)) { this._templating.resetProgress(id); qq(this._templating.getFileContainer(id)).removeClass(this._classes.fail); this._templating.setStatusText(id); this._templating.showSpinner(id); this._showCancelLink(id); return true; } else { qq(this._templating.getFileContainer(id)).addClass(this._classes.retryable); return false; } }, _onSubmitDelete: function(id) { var onSuccessCallback = qq.bind(this._onSubmitDeleteSuccess, this); this._parent.prototype._onSubmitDelete.call(this, id, onSuccessCallback); }, _onSubmitDeleteSuccess: function(id, uuid, additionalMandatedParams) { if (this._options.deleteFile.forceConfirm) { this._showDeleteConfirm.apply(this, arguments); } else { this._sendDeleteRequest.apply(this, arguments); } }, _onDeleteComplete: function(id, xhr, isError) { this._parent.prototype._onDeleteComplete.apply(this, arguments); this._templating.hideSpinner(id); if (isError) { this._templating.setStatusText(id, this._options.deleteFile.deletingFailedText); this._templating.showDeleteButton(id); } else { this._removeFileItem(id); } }, _sendDeleteRequest: function(id, uuid, additionalMandatedParams) { this._templating.hideDeleteButton(id); this._templating.showSpinner(id); this._templating.setStatusText(id, this._options.deleteFile.deletingStatusText); this._deleteHandler.sendDelete.apply(this, arguments); }, _showDeleteConfirm: function(id, uuid, mandatedParams) { /*jshint -W004 */ var fileName = this.getName(id), confirmMessage = this._options.deleteFile.confirmMessage.replace(/\{filename\}/g, fileName), uuid = this.getUuid(id), deleteRequestArgs = arguments, self = this, retVal; retVal = this._options.showConfirm(confirmMessage); if (retVal instanceof qq.Promise) { retVal.then(function () { self._sendDeleteRequest.apply(self, deleteRequestArgs); }); } else if (retVal !== false) { self._sendDeleteRequest.apply(self, deleteRequestArgs); } }, _addToList: function(id, name, canned) { var prependData, prependIndex = 0; if (this._options.display.prependFiles) { if (this._totalFilesInBatch > 1 && this._filesInBatchAddedToUi > 0) { prependIndex = this._filesInBatchAddedToUi - 1; } prependData = { index: prependIndex }; } if (!canned) { if (this._options.disableCancelForFormUploads && !qq.supportedFeatures.ajaxUploading) { this._templating.disableCancel(); } if (!this._options.multiple) { this._handler.cancelAll(); this._clearList(); } } this._templating.addFile(id, this._options.formatFileName(name), prependData); if (canned) { this._thumbnailUrls[id] && this._templating.updateThumbnail(id, this._thumbnailUrls[id], true); } else { this._templating.generatePreview(id, this.getFile(id)); } this._filesInBatchAddedToUi += 1; if (canned || (this._options.display.fileSizeOnSubmit && qq.supportedFeatures.ajaxUploading)) { this._displayFileSize(id); } }, _clearList: function(){ this._templating.clearFiles(); this.clearStoredFiles(); }, _displayFileSize: function(id, loadedSize, totalSize) { var size = this.getSize(id), sizeForDisplay = this._formatSize(size); if (size >= 0) { if (loadedSize !== undefined && totalSize !== undefined) { sizeForDisplay = this._formatProgress(loadedSize, totalSize); } this._templating.updateSize(id, sizeForDisplay); } }, _formatProgress: function (uploadedSize, totalSize) { var message = this._options.text.formatProgress; function r(name, replacement) { message = message.replace(name, replacement); } r("{percent}", Math.round(uploadedSize / totalSize * 100)); r("{total_size}", this._formatSize(totalSize)); return message; }, _controlFailureTextDisplay: function(id, response) { var mode, maxChars, responseProperty, failureReason, shortFailureReason; mode = this._options.failedUploadTextDisplay.mode; maxChars = this._options.failedUploadTextDisplay.maxChars; responseProperty = this._options.failedUploadTextDisplay.responseProperty; if (mode === "custom") { failureReason = response[responseProperty]; if (failureReason) { if (failureReason.length > maxChars) { shortFailureReason = failureReason.substring(0, maxChars) + "..."; } } else { failureReason = this._options.text.failUpload; this.log("'" + responseProperty + "' is not a valid property on the server response.", "warn"); } this._templating.setStatusText(id, shortFailureReason || failureReason); if (this._options.failedUploadTextDisplay.enableTooltip) { this._showTooltip(id, failureReason); } } else if (mode === "default") { this._templating.setStatusText(id, this._options.text.failUpload); } else if (mode !== "none") { this.log("failedUploadTextDisplay.mode value of '" + mode + "' is not valid", "warn"); } }, _showTooltip: function(id, text) { this._templating.getFileContainer(id).title = text; }, _showCancelLink: function(id) { if (!this._options.disableCancelForFormUploads || qq.supportedFeatures.ajaxUploading) { this._templating.showCancel(id); } }, _itemError: function(code, name, item) { var message = this._parent.prototype._itemError.apply(this, arguments); this._options.showMessage(message); }, _batchError: function(message) { this._parent.prototype._batchError.apply(this, arguments); this._options.showMessage(message); }, _setupPastePrompt: function() { var self = this; this._options.callbacks.onPasteReceived = function() { var message = self._options.paste.namePromptMessage, defaultVal = self._options.paste.defaultName; return self._options.showPrompt(message, defaultVal); }; }, _fileOrBlobRejected: function(id, name) { this._totalFilesInBatch -= 1; this._parent.prototype._fileOrBlobRejected.apply(this, arguments); }, _prepareItemsForUpload: function(items, params, endpoint) { this._totalFilesInBatch = items.length; this._filesInBatchAddedToUi = 0; this._parent.prototype._prepareItemsForUpload.apply(this, arguments); }, _maybeUpdateThumbnail: function(fileId) { var thumbnailUrl = this._thumbnailUrls[fileId]; this._templating.updateThumbnail(fileId, thumbnailUrl); }, _addCannedFile: function(sessionData) { var id = this._parent.prototype._addCannedFile.apply(this, arguments); this._addToList(id, this.getName(id), true); this._templating.hideSpinner(id); this._templating.hideCancel(id); this._markFileAsSuccessful(id); return id; } }; }()); /*globals qq */ /** * This defines FineUploader mode, which is a default UI w/ drag & drop uploading. */ qq.FineUploader = function(o, namespace) { "use strict"; // By default this should inherit instance data from FineUploaderBasic, but this can be overridden // if the (internal) caller defines a different parent. The parent is also used by // the private and public API functions that need to delegate to a parent function. this._parent = namespace ? qq[namespace].FineUploaderBasic : qq.FineUploaderBasic; this._parent.apply(this, arguments); // Options provided by FineUploader mode qq.extend(this._options, { element: null, button: null, listElement: null, dragAndDrop: { extraDropzones: [] }, text: { formatProgress: "{percent}% of {total_size}", failUpload: "Upload failed", waitingForResponse: "Processing...", paused: "Paused" }, template: "qq-template", classes: { retrying: "qq-upload-retrying", retryable: "qq-upload-retryable", success: "qq-upload-success", fail: "qq-upload-fail", editable: "qq-editable", hide: "qq-hide", dropActive: "qq-upload-drop-area-active" }, failedUploadTextDisplay: { mode: "default", //default, custom, or none maxChars: 50, responseProperty: "error", enableTooltip: true }, messages: { tooManyFilesError: "You may only drop one file", unsupportedBrowser: "Unrecoverable error - this browser does not permit file uploading of any kind." }, retry: { showAutoRetryNote: true, autoRetryNote: "Retrying {retryNum}/{maxAuto}..." }, deleteFile: { forceConfirm: false, confirmMessage: "Are you sure you want to delete {filename}?", deletingStatusText: "Deleting...", deletingFailedText: "Delete failed" }, display: { fileSizeOnSubmit: false, prependFiles: false }, paste: { promptForName: false, namePromptMessage: "Please name this image" }, thumbnails: { placeholders: { waitUntilResponse: false, notAvailablePath: null, waitingPath: null } }, showMessage: function(message){ setTimeout(function() { window.alert(message); }, 0); }, showConfirm: function(message) { return window.confirm(message); }, showPrompt: function(message, defaultValue) { return window.prompt(message, defaultValue); } }, true); // Replace any default options with user defined ones qq.extend(this._options, o, true); this._templating = new qq.Templating({ log: qq.bind(this.log, this), templateIdOrEl: this._options.template, containerEl: this._options.element, fileContainerEl: this._options.listElement, button: this._options.button, imageGenerator: this._imageGenerator, classes: { hide: this._options.classes.hide, editable: this._options.classes.editable }, placeholders: { waitUntilUpdate: this._options.thumbnails.placeholders.waitUntilResponse, thumbnailNotAvailable: this._options.thumbnails.placeholders.notAvailablePath, waitingForThumbnail: this._options.thumbnails.placeholders.waitingPath }, text: this._options.text }); if (!qq.supportedFeatures.uploading || (this._options.cors.expected && !qq.supportedFeatures.uploadCors)) { this._templating.renderFailure(this._options.messages.unsupportedBrowser); } else { this._wrapCallbacks(); this._templating.render(); this._classes = this._options.classes; if (!this._options.button && this._templating.getButton()) { this._defaultButtonId = this._createUploadButton({element: this._templating.getButton()}).getButtonId(); } this._setupClickAndEditEventHandlers(); if (qq.DragAndDrop && qq.supportedFeatures.fileDrop) { this._dnd = this._setupDragAndDrop(); } if (this._options.paste.targetElement && this._options.paste.promptForName) { if (qq.PasteSupport) { this._setupPastePrompt(); } else { qq.log("Paste support module not found.", "info"); } } this._totalFilesInBatch = 0; this._filesInBatchAddedToUi = 0; } }; // Inherit the base public & private API methods qq.extend(qq.FineUploader.prototype, qq.basePublicApi); qq.extend(qq.FineUploader.prototype, qq.basePrivateApi); // Add the FineUploader/default UI public & private UI methods, which may override some base methods. qq.extend(qq.FineUploader.prototype, qq.uiPublicApi); qq.extend(qq.FineUploader.prototype, qq.uiPrivateApi); /* globals qq */ /* jshint -W065 */ /** * Module responsible for rendering all Fine Uploader UI templates. This module also asserts at least * a limited amount of control over the template elements after they are added to the DOM. * Wherever possible, this module asserts total control over template elements present in the DOM. * * @param spec Specification object used to control various templating behaviors * @constructor */ qq.Templating = function(spec) { "use strict"; var FILE_ID_ATTR = "qq-file-id", FILE_CLASS_PREFIX = "qq-file-id-", THUMBNAIL_MAX_SIZE_ATTR = "qq-max-size", THUMBNAIL_SERVER_SCALE_ATTR = "qq-server-scale", // This variable is duplicated in the DnD module since it can function as a standalone as well HIDE_DROPZONE_ATTR = "qq-hide-dropzone", isCancelDisabled = false, thumbnailMaxSize = -1, options = { log: null, templateIdOrEl: "qq-template", containerEl: null, fileContainerEl: null, button: null, imageGenerator: null, classes: { hide: "qq-hide", editable: "qq-editable" }, placeholders: { waitUntilUpdate: false, thumbnailNotAvailable: null, waitingForThumbnail: null }, text: { paused: "Paused" } }, selectorClasses = { button: "qq-upload-button-selector", drop: "qq-upload-drop-area-selector", list: "qq-upload-list-selector", progressBarContainer: "qq-progress-bar-container-selector", progressBar: "qq-progress-bar-selector", file: "qq-upload-file-selector", spinner: "qq-upload-spinner-selector", size: "qq-upload-size-selector", cancel: "qq-upload-cancel-selector", pause: "qq-upload-pause-selector", continueButton: "qq-upload-continue-selector", deleteButton: "qq-upload-delete-selector", retry: "qq-upload-retry-selector", statusText: "qq-upload-status-text-selector", editFilenameInput: "qq-edit-filename-selector", editNameIcon: "qq-edit-filename-icon-selector", dropProcessing: "qq-drop-processing-selector", dropProcessingSpinner: "qq-drop-processing-spinner-selector", thumbnail: "qq-thumbnail-selector" }, previewGeneration = {}, cachedThumbnailNotAvailableImg = new qq.Promise(), cachedWaitingForThumbnailImg = new qq.Promise(), log, isEditElementsExist, isRetryElementExist, templateHtml, container, fileList, showThumbnails, serverScale; /** * Grabs the HTML from the script tag holding the template markup. This function will also adjust * some internally-tracked state variables based on the contents of the template. * The template is filtered so that irrelevant elements (such as the drop zone if DnD is not supported) * are omitted from the DOM. Useful errors will be thrown if the template cannot be parsed. * * @returns {{template: *, fileTemplate: *}} HTML for the top-level file items templates */ function parseAndGetTemplate() { var scriptEl, scriptHtml, fileListNode, tempTemplateEl, fileListHtml, defaultButton, dropArea, thumbnail, dropProcessing; log("Parsing template"); /*jshint -W116*/ if (options.templateIdOrEl == null) { throw new Error("You MUST specify either a template element or ID!"); } // Grab the contents of the script tag holding the template. if (qq.isString(options.templateIdOrEl)) { scriptEl = document.getElementById(options.templateIdOrEl); if (scriptEl === null) { throw new Error(qq.format("Cannot find template script at ID '{}'!", options.templateIdOrEl)); } scriptHtml = scriptEl.innerHTML; } else { if (options.templateIdOrEl.innerHTML === undefined) { throw new Error("You have specified an invalid value for the template option! " + "It must be an ID or an Element."); } scriptHtml = options.templateIdOrEl.innerHTML; } scriptHtml = qq.trimStr(scriptHtml); tempTemplateEl = document.createElement("div"); tempTemplateEl.appendChild(qq.toElement(scriptHtml)); // Don't include the default template button in the DOM // if an alternate button container has been specified. if (options.button) { defaultButton = qq(tempTemplateEl).getByClass(selectorClasses.button)[0]; if (defaultButton) { qq(defaultButton).remove(); } } // Omit the drop processing element from the DOM if DnD is not supported by the UA, // or the drag and drop module is not found. // NOTE: We are consciously not removing the drop zone if the UA doesn't support DnD // to support layouts where the drop zone is also a container for visible elements, // such as the file list. if (!qq.DragAndDrop || !qq.supportedFeatures.fileDrop) { dropProcessing = qq(tempTemplateEl).getByClass(selectorClasses.dropProcessing)[0]; if (dropProcessing) { qq(dropProcessing).remove(); } } dropArea = qq(tempTemplateEl).getByClass(selectorClasses.drop)[0]; // If DnD is not available then remove // it from the DOM as well. if (dropArea && !qq.DragAndDrop) { qq.log("DnD module unavailable.", "info"); qq(dropArea).remove(); } // If there is a drop area defined in the template, and the current UA doesn't support DnD, // and the drop area is marked as "hide before enter", ensure it is hidden as the DnD module // will not do this (since we will not be loading the DnD module) if (dropArea && !qq.supportedFeatures.fileDrop && qq(dropArea).hasAttribute(HIDE_DROPZONE_ATTR)) { qq(dropArea).css({ display: "none" }); } // Ensure the `showThumbnails` flag is only set if the thumbnail element // is present in the template AND the current UA is capable of generating client-side previews. thumbnail = qq(tempTemplateEl).getByClass(selectorClasses.thumbnail)[0]; if (!showThumbnails) { thumbnail && qq(thumbnail).remove(); } else if (thumbnail) { thumbnailMaxSize = parseInt(thumbnail.getAttribute(THUMBNAIL_MAX_SIZE_ATTR)); // Only enforce max size if the attr value is non-zero thumbnailMaxSize = thumbnailMaxSize > 0 ? thumbnailMaxSize : null; serverScale = qq(thumbnail).hasAttribute(THUMBNAIL_SERVER_SCALE_ATTR); } showThumbnails = showThumbnails && thumbnail; isEditElementsExist = qq(tempTemplateEl).getByClass(selectorClasses.editFilenameInput).length > 0; isRetryElementExist = qq(tempTemplateEl).getByClass(selectorClasses.retry).length > 0; fileListNode = qq(tempTemplateEl).getByClass(selectorClasses.list)[0]; /*jshint -W116*/ if (fileListNode == null) { throw new Error("Could not find the file list container in the template!"); } fileListHtml = fileListNode.innerHTML; fileListNode.innerHTML = ""; log("Template parsing complete"); return { template: qq.trimStr(tempTemplateEl.innerHTML), fileTemplate: qq.trimStr(fileListHtml) }; } function getFile(id) { return qq(fileList).getByClass(FILE_CLASS_PREFIX + id)[0]; } function getTemplateEl(context, cssClass) { return qq(context).getByClass(cssClass)[0]; } function prependFile(el, index) { var parentEl = fileList, beforeEl = parentEl.firstChild; if (index > 0) { beforeEl = qq(parentEl).children()[index].nextSibling; } parentEl.insertBefore(el, beforeEl); } function getCancel(id) { return getTemplateEl(getFile(id), selectorClasses.cancel); } function getPause(id) { return getTemplateEl(getFile(id), selectorClasses.pause); } function getContinue(id) { return getTemplateEl(getFile(id), selectorClasses.continueButton); } function getProgress(id) { return getTemplateEl(getFile(id), selectorClasses.progressBarContainer) || getTemplateEl(getFile(id), selectorClasses.progressBar); } function getSpinner(id) { return getTemplateEl(getFile(id), selectorClasses.spinner); } function getEditIcon(id) { return getTemplateEl(getFile(id), selectorClasses.editNameIcon); } function getSize(id) { return getTemplateEl(getFile(id), selectorClasses.size); } function getDelete(id) { return getTemplateEl(getFile(id), selectorClasses.deleteButton); } function getRetry(id) { return getTemplateEl(getFile(id), selectorClasses.retry); } function getFilename(id) { return getTemplateEl(getFile(id), selectorClasses.file); } function getDropProcessing() { return getTemplateEl(container, selectorClasses.dropProcessing); } function getThumbnail(id) { return showThumbnails && getTemplateEl(getFile(id), selectorClasses.thumbnail); } function hide(el) { el && qq(el).addClass(options.classes.hide); } function show(el) { el && qq(el).removeClass(options.classes.hide); } function setProgressBarWidth(id, percent) { var bar = getProgress(id); if (bar && !qq(bar).hasClass(selectorClasses.progressBar)) { bar = qq(bar).getByClass(selectorClasses.progressBar)[0]; } bar && qq(bar).css({width: percent + "%"}); } // During initialization of the templating module we should cache any // placeholder images so we can quickly swap them into the file list on demand. // Any placeholder images that cannot be loaded/found are simply ignored. function cacheThumbnailPlaceholders() { var notAvailableUrl = options.placeholders.thumbnailNotAvailable, waitingUrl = options.placeholders.waitingForThumbnail, spec = { maxSize: thumbnailMaxSize, scale: serverScale }; if (showThumbnails) { if (notAvailableUrl) { options.imageGenerator.generate(notAvailableUrl, new Image(), spec).then( function(updatedImg) { cachedThumbnailNotAvailableImg.success(updatedImg); }, function() { cachedThumbnailNotAvailableImg.failure(); log("Problem loading 'not available' placeholder image at " + notAvailableUrl, "error"); } ); } else { cachedThumbnailNotAvailableImg.failure(); } if (waitingUrl) { options.imageGenerator.generate(waitingUrl, new Image(), spec).then( function(updatedImg) { cachedWaitingForThumbnailImg.success(updatedImg); }, function() { cachedWaitingForThumbnailImg.failure(); log("Problem loading 'waiting for thumbnail' placeholder image at " + waitingUrl, "error"); } ); } else { cachedWaitingForThumbnailImg.failure(); } } } // Displays a "waiting for thumbnail" type placeholder image // iff we were able to load it during initialization of the templating module. function displayWaitingImg(thumbnail) { cachedWaitingForThumbnailImg.then(function(img) { maybeScalePlaceholderViaCss(img, thumbnail); /* jshint eqnull:true */ if (thumbnail.getAttribute("src") == null) { thumbnail.src = img.src; show(thumbnail); } }, function() { // In some browsers (such as IE9 and older) an img w/out a src attribute // are displayed as "broken" images, so we sohuld just hide the img tag // if we aren't going to display the "waiting" placeholder. hide(thumbnail); }); } // Displays a "thumbnail not available" type placeholder image // iff we were able to load this placeholder during initialization // of the templating module or after preview generation has failed. function maybeSetDisplayNotAvailableImg(id, thumbnail) { var previewing = previewGeneration[id] || new qq.Promise().failure(); cachedThumbnailNotAvailableImg.then(function(img) { previewing.then( function() { delete previewGeneration[id]; }, function() { maybeScalePlaceholderViaCss(img, thumbnail); thumbnail.src = img.src; show(thumbnail); delete previewGeneration[id]; } ); }); } // Ensures a placeholder image does not exceed any max size specified // via `style` attribute properties iff <canvas> was not used to scale // the placeholder AND the target <img> doesn't already have these `style` attribute properties set. function maybeScalePlaceholderViaCss(placeholder, thumbnail) { var maxWidth = placeholder.style.maxWidth, maxHeight = placeholder.style.maxHeight; if (maxHeight && maxWidth && !thumbnail.style.maxWidth && !thumbnail.style.maxHeight) { qq(thumbnail).css({ maxWidth: maxWidth, maxHeight: maxHeight }); } } qq.extend(options, spec); log = options.log; container = options.containerEl; showThumbnails = options.imageGenerator !== undefined; templateHtml = parseAndGetTemplate(); cacheThumbnailPlaceholders(); qq.extend(this, { render: function() { log("Rendering template in DOM."); container.innerHTML = templateHtml.template; hide(getDropProcessing()); fileList = options.fileContainerEl || getTemplateEl(container, selectorClasses.list); log("Template rendering complete"); }, renderFailure: function(message) { var cantRenderEl = qq.toElement(message); container.innerHTML = ""; container.appendChild(cantRenderEl); }, reset: function() { this.render(); }, clearFiles: function() { fileList.innerHTML = ""; }, disableCancel: function() { isCancelDisabled = true; }, addFile: function(id, name, prependInfo) { var fileEl = qq.toElement(templateHtml.fileTemplate), fileNameEl = getTemplateEl(fileEl, selectorClasses.file); qq(fileEl).addClass(FILE_CLASS_PREFIX + id); fileNameEl && qq(fileNameEl).setText(name); fileEl.setAttribute(FILE_ID_ATTR, id); if (prependInfo) { prependFile(fileEl, prependInfo.index); } else { fileList.appendChild(fileEl); } hide(getProgress(id)); hide(getSize(id)); hide(getDelete(id)); hide(getRetry(id)); hide(getPause(id)); hide(getContinue(id)); if (isCancelDisabled) { this.hideCancel(id); } }, removeFile: function(id) { qq(getFile(id)).remove(); }, getFileId: function(el) { var currentNode = el; if (currentNode) { /*jshint -W116*/ while (currentNode.getAttribute(FILE_ID_ATTR) == null) { currentNode = currentNode.parentNode; } return parseInt(currentNode.getAttribute(FILE_ID_ATTR)); } }, getFileList: function() { return fileList; }, markFilenameEditable: function(id) { var filename = getFilename(id); filename && qq(filename).addClass(options.classes.editable); }, updateFilename: function(id, name) { var filename = getFilename(id); filename && qq(filename).setText(name); }, hideFilename: function(id) { hide(getFilename(id)); }, showFilename: function(id) { show(getFilename(id)); }, isFileName: function(el) { return qq(el).hasClass(selectorClasses.file); }, getButton: function() { return options.button || getTemplateEl(container, selectorClasses.button); }, hideDropProcessing: function() { hide(getDropProcessing()); }, showDropProcessing: function() { show(getDropProcessing()); }, getDropZone: function() { return getTemplateEl(container, selectorClasses.drop); }, isEditFilenamePossible: function() { return isEditElementsExist; }, isRetryPossible: function() { return isRetryElementExist; }, getFileContainer: function(id) { return getFile(id); }, showEditIcon: function(id) { var icon = getEditIcon(id); icon && qq(icon).addClass(options.classes.editable); }, hideEditIcon: function(id) { var icon = getEditIcon(id); icon && qq(icon).removeClass(options.classes.editable); }, isEditIcon: function(el) { return qq(el).hasClass(selectorClasses.editNameIcon); }, getEditInput: function(id) { return getTemplateEl(getFile(id), selectorClasses.editFilenameInput); }, isEditInput: function(el) { return qq(el).hasClass(selectorClasses.editFilenameInput); }, updateProgress: function(id, loaded, total) { var bar = getProgress(id), percent; if (bar) { percent = Math.round(loaded / total * 100); if (loaded === total) { hide(bar); } else { show(bar); } setProgressBarWidth(id, percent); } }, hideProgress: function(id) { var bar = getProgress(id); bar && hide(bar); }, resetProgress: function(id) { setProgressBarWidth(id, 0); }, showCancel: function(id) { if (!isCancelDisabled) { var cancel = getCancel(id); cancel && qq(cancel).removeClass(options.classes.hide); } }, hideCancel: function(id) { hide(getCancel(id)); }, isCancel: function(el) { return qq(el).hasClass(selectorClasses.cancel); }, allowPause: function(id) { show(getPause(id)); hide(getContinue(id)); }, uploadPaused: function(id) { this.setStatusText(id, options.text.paused); this.allowContinueButton(id); hide(getSpinner(id)); }, hidePause: function(id) { hide(getPause(id)); }, isPause: function(el) { return qq(el).hasClass(selectorClasses.pause); }, isContinueButton: function(el) { return qq(el).hasClass(selectorClasses.continueButton); }, allowContinueButton: function(id) { show(getContinue(id)); hide(getPause(id)); }, uploadContinued: function(id) { this.setStatusText(id, ""); this.allowPause(id); show(getSpinner(id)); }, showDeleteButton: function(id) { show(getDelete(id)); }, hideDeleteButton: function(id) { hide(getDelete(id)); }, isDeleteButton: function(el) { return qq(el).hasClass(selectorClasses.deleteButton); }, isRetry: function(el) { return qq(el).hasClass(selectorClasses.retry); }, updateSize: function(id, text) { var size = getSize(id); if (size) { show(size); qq(size).setText(text); } }, setStatusText: function(id, text) { var textEl = getTemplateEl(getFile(id), selectorClasses.statusText); if (textEl) { /*jshint -W116*/ if (text == null) { qq(textEl).clearText(); } else { qq(textEl).setText(text); } } }, hideSpinner: function(id) { hide(getSpinner(id)); }, showSpinner: function(id) { show(getSpinner(id)); }, generatePreview: function(id, fileOrBlob) { var thumbnail = getThumbnail(id), spec = { maxSize: thumbnailMaxSize, scale: true, orient: true }; if (qq.supportedFeatures.imagePreviews) { previewGeneration[id] = new qq.Promise(); if (thumbnail) { displayWaitingImg(thumbnail); return options.imageGenerator.generate(fileOrBlob, thumbnail, spec).then( function() { show(thumbnail); previewGeneration[id].success(); }, function() { previewGeneration[id].failure(); // Display the "not available" placeholder img only if we are // not expecting a thumbnail at a later point, such as in a server response. if (!options.placeholders.waitUntilUpdate) { maybeSetDisplayNotAvailableImg(id, thumbnail); } }); } } else if (thumbnail) { displayWaitingImg(thumbnail); } }, updateThumbnail: function(id, thumbnailUrl, showWaitingImg) { var thumbnail = getThumbnail(id), spec = { maxSize: thumbnailMaxSize, scale: serverScale }; if (thumbnail) { if (thumbnailUrl) { if (showWaitingImg) { displayWaitingImg(thumbnail); } return options.imageGenerator.generate(thumbnailUrl, thumbnail, spec).then( function() { show(thumbnail); }, function() { maybeSetDisplayNotAvailableImg(id, thumbnail); } ); } else { maybeSetDisplayNotAvailableImg(id, thumbnail); } } } }); }; /*globals qq*/ /** * Upload handler used that assumes the current user agent does not have any support for the * File API, and, therefore, makes use of iframes and forms to submit the files directly to * a generic server. * * @param options Options passed from the base handler * @param proxy Callbacks & methods used to query for or push out data/changes */ qq.UploadHandlerForm = function(options, proxy) { "use strict"; var handler = this, uploadCompleteCallback = proxy.onUploadComplete, onUuidChanged = proxy.onUuidChanged, getName = proxy.getName, getUuid = proxy.getUuid, uploadComplete = uploadCompleteCallback, log = proxy.log; /** * Returns json object received by iframe from server. */ function getIframeContentJson(id, iframe) { /*jshint evil: true*/ var response; //IE may throw an "access is denied" error when attempting to access contentDocument on the iframe in some cases try { // iframe.contentWindow.document - for IE<7 var doc = iframe.contentDocument || iframe.contentWindow.document, innerHtml = doc.body.innerHTML; log("converting iframe's innerHTML to JSON"); log("innerHTML = " + innerHtml); //plain text response may be wrapped in <pre> tag if (innerHtml && innerHtml.match(/^<pre/i)) { innerHtml = doc.body.firstChild.firstChild.nodeValue; } response = handler._parseJsonResponse(id, innerHtml); } catch(error) { log("Error when attempting to parse form upload response (" + error.message + ")", "error"); response = {success: false}; } return response; } /** * Creates form, that will be submitted to iframe */ function createForm(id, iframe){ var params = options.paramsStore.get(id), method = options.demoMode ? "GET" : "POST", endpoint = options.endpointStore.get(id), name = getName(id); params[options.uuidName] = getUuid(id); params[options.filenameParam] = name; return handler._initFormForUpload({ method: method, endpoint: endpoint, params: params, paramsInBody: options.paramsInBody, targetName: iframe.name }); } qq.extend(this, new qq.AbstractUploadHandlerForm({ options: { isCors: options.cors.expected, inputName: options.inputName }, proxy: { onCancel: options.onCancel, onUuidChanged: onUuidChanged, getName: getName, getUuid: getUuid, log: log } } )); qq.extend(this, { upload: function(id) { var input = handler._getFileState(id).input, fileName = getName(id), iframe = handler._createIframe(id), form; if (!input){ throw new Error("file with passed id was not added, or already uploaded or canceled"); } options.onUpload(id, getName(id)); form = createForm(id, iframe); form.appendChild(input); handler._attachLoadEvent(iframe, function(responseFromMessage){ log("iframe loaded"); var response = responseFromMessage ? responseFromMessage : getIframeContentJson(id, iframe); handler._detachLoadEvent(id); //we can't remove an iframe if the iframe doesn't belong to the same domain if (!options.cors.expected) { qq(iframe).remove(); } if (!response.success) { if (options.onAutoRetry(id, fileName, response)) { return; } } options.onComplete(id, fileName, response); uploadComplete(id); }); log("Sending upload request for " + id); form.submit(); qq(form).remove(); } }); }; /*globals qq*/ /** * Upload handler used to upload to traditional endpoints. It depends on File API support, and, therefore, * makes use of `XMLHttpRequest` level 2 to upload `File`s and `Blob`s to a generic server. * * @param spec Options passed from the base handler * @param proxy Callbacks & methods used to query for or push out data/changes */ qq.UploadHandlerXhr = function(spec, proxy) { "use strict"; var uploadComplete = proxy.onUploadComplete, onUuidChanged = proxy.onUuidChanged, getName = proxy.getName, getUuid = proxy.getUuid, getSize = proxy.getSize, log = proxy.log, cookieItemDelimiter = "|", chunkFiles = spec.chunking.enabled && qq.supportedFeatures.chunking, resumeEnabled = spec.resume.enabled && chunkFiles && qq.supportedFeatures.resume, multipart = spec.forceMultipart || spec.paramsInBody, handler = this, resumeId; function getResumeId() { if (spec.resume.id !== null && spec.resume.id !== undefined && !qq.isFunction(spec.resume.id) && !qq.isObject(spec.resume.id)) { return spec.resume.id; } } resumeId = getResumeId(); function addChunkingSpecificParams(id, params, chunkData) { var size = getSize(id), name = getName(id); params[spec.chunking.paramNames.partIndex] = chunkData.part; params[spec.chunking.paramNames.partByteOffset] = chunkData.start; params[spec.chunking.paramNames.chunkSize] = chunkData.size; params[spec.chunking.paramNames.totalParts] = chunkData.count; params[spec.totalFileSizeName] = size; /** * When a Blob is sent in a multipart request, the filename value in the content-disposition header is either "blob" * or an empty string. So, we will need to include the actual file name as a param in this case. */ if (multipart) { params[spec.filenameParam] = name; } } function addResumeSpecificParams(params) { params[spec.resume.paramNames.resuming] = true; } function getChunk(fileOrBlob, startByte, endByte) { if (fileOrBlob.slice) { return fileOrBlob.slice(startByte, endByte); } else if (fileOrBlob.mozSlice) { return fileOrBlob.mozSlice(startByte, endByte); } else if (fileOrBlob.webkitSlice) { return fileOrBlob.webkitSlice(startByte, endByte); } } function setParamsAndGetEntityToSend(params, xhr, fileOrBlob, id) { var formData = new FormData(), method = spec.demoMode ? "GET" : "POST", endpoint = spec.endpointStore.get(id), url = endpoint, name = getName(id), size = getSize(id); params[spec.uuidName] = getUuid(id); params[spec.filenameParam] = name; if (multipart) { params[spec.totalFileSizeName] = size; } //build query string if (!spec.paramsInBody) { if (!multipart) { params[spec.inputName] = name; } url = qq.obj2url(params, endpoint); } xhr.open(method, url, true); if (spec.cors.expected && spec.cors.sendCredentials) { xhr.withCredentials = true; } if (multipart) { if (spec.paramsInBody) { qq.obj2FormData(params, formData); } formData.append(spec.inputName, fileOrBlob); return formData; } return fileOrBlob; } function setHeaders(id, xhr) { var extraHeaders = spec.customHeaders, fileOrBlob = handler._getFileState(id).file || handler._getFileState(id).blobData.blob; xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); xhr.setRequestHeader("Cache-Control", "no-cache"); if (!multipart) { xhr.setRequestHeader("Content-Type", "application/octet-stream"); //NOTE: return mime type in xhr works on chrome 16.0.9 firefox 11.0a2 xhr.setRequestHeader("X-Mime-Type", fileOrBlob.type); } qq.each(extraHeaders, function(name, val) { xhr.setRequestHeader(name, val); }); } function handleCompletedItem(id, response, xhr) { var name = getName(id), size = getSize(id); handler._getFileState(id).attemptingResume = false; spec.onProgress(id, name, size, size); spec.onComplete(id, name, response, xhr); if (handler._getFileState(id)) { delete handler._getFileState(id).xhr; } uploadComplete(id); } function uploadNextChunk(id) { var chunkIdx = handler._getFileState(id).remainingChunkIdxs[0], chunkData = handler._getChunkData(id, chunkIdx), xhr = handler._createXhr(id), size = getSize(id), name = getName(id), toSend, params; if (handler._getFileState(id).loaded === undefined) { handler._getFileState(id).loaded = 0; } if (resumeEnabled && handler._getFileState(id).file) { persistChunkData(id, chunkData); } xhr.onreadystatechange = getReadyStateChangeHandler(id, xhr); xhr.upload.onprogress = function(e) { if (e.lengthComputable) { var totalLoaded = e.loaded + handler._getFileState(id).loaded, estTotalRequestsSize = calcAllRequestsSizeForChunkedUpload(id, chunkIdx, e.total); spec.onProgress(id, name, totalLoaded, estTotalRequestsSize); } }; spec.onUploadChunk(id, name, handler._getChunkDataForCallback(chunkData)); params = spec.paramsStore.get(id); addChunkingSpecificParams(id, params, chunkData); if (handler._getFileState(id).attemptingResume) { addResumeSpecificParams(params); } toSend = setParamsAndGetEntityToSend(params, xhr, chunkData.blob, id); setHeaders(id, xhr); log("Sending chunked upload request for item " + id + ": bytes " + (chunkData.start+1) + "-" + chunkData.end + " of " + size); xhr.send(toSend); } function calcAllRequestsSizeForChunkedUpload(id, chunkIdx, requestSize) { var chunkData = handler._getChunkData(id, chunkIdx), blobSize = chunkData.size, overhead = requestSize - blobSize, size = getSize(id), chunkCount = chunkData.count, initialRequestOverhead = handler._getFileState(id).initialRequestOverhead, overheadDiff = overhead - initialRequestOverhead; handler._getFileState(id).lastRequestOverhead = overhead; if (chunkIdx === 0) { handler._getFileState(id).lastChunkIdxProgress = 0; handler._getFileState(id).initialRequestOverhead = overhead; handler._getFileState(id).estTotalRequestsSize = size + (chunkCount * overhead); } else if (handler._getFileState(id).lastChunkIdxProgress !== chunkIdx) { handler._getFileState(id).lastChunkIdxProgress = chunkIdx; handler._getFileState(id).estTotalRequestsSize += overheadDiff; } return handler._getFileState(id).estTotalRequestsSize; } function getLastRequestOverhead(id) { if (multipart) { return handler._getFileState(id).lastRequestOverhead; } else { return 0; } } function handleSuccessfullyCompletedChunk(id, response, xhr) { var chunkIdx = handler._getFileState(id).remainingChunkIdxs.shift(), chunkData = handler._getChunkData(id, chunkIdx); handler._getFileState(id).attemptingResume = false; handler._getFileState(id).loaded += chunkData.size + getLastRequestOverhead(id); spec.onUploadChunkSuccess(id, handler._getChunkDataForCallback(chunkData), response, xhr); if (handler._getFileState(id).remainingChunkIdxs.length > 0) { uploadNextChunk(id); } else { if (resumeEnabled) { deletePersistedChunkData(id); } handleCompletedItem(id, response, xhr); } } function isErrorResponse(xhr, response) { return xhr.status !== 200 || !response.success || response.reset; } function parseResponse(id, xhr) { var response; try { log(qq.format("Received response status {} with body: {}", xhr.status, xhr.responseText)); response = qq.parseJson(xhr.responseText); if (response.newUuid !== undefined) { onUuidChanged(id, response.newUuid); } } catch(error) { log("Error when attempting to parse xhr response text (" + error.message + ")", "error"); response = {}; } return response; } function handleResetResponse(id) { log("Server has ordered chunking effort to be restarted on next attempt for item ID " + id, "error"); if (resumeEnabled) { deletePersistedChunkData(id); handler._getFileState(id).attemptingResume = false; } handler._getFileState(id).remainingChunkIdxs = []; delete handler._getFileState(id).loaded; delete handler._getFileState(id).estTotalRequestsSize; delete handler._getFileState(id).initialRequestOverhead; } function handleResetResponseOnResumeAttempt(id) { handler._getFileState(id).attemptingResume = false; log("Server has declared that it cannot handle resume for item ID " + id + " - starting from the first chunk", "error"); handleResetResponse(id); handler.upload(id, true); } function handleNonResetErrorResponse(id, response, xhr) { var name = getName(id); if (spec.onAutoRetry(id, name, response, xhr)) { return; } else { if (xhr.status !== 200) { response.success = false; } handleCompletedItem(id, response, xhr); } } function onComplete(id, xhr) { var state = handler._getFileState(id), attemptingResume = state && state.attemptingResume, paused = state && state.paused, response; // The logic in this function targets uploads that have not been paused or canceled, // so return at once if this is not the case. if (!state || paused) { return; } log("xhr - server response received for " + id); log("responseText = " + xhr.responseText); response = parseResponse(id, xhr); if (isErrorResponse(xhr, response)) { if (response.reset) { handleResetResponse(id); } if (attemptingResume && response.reset) { handleResetResponseOnResumeAttempt(id); } else { handleNonResetErrorResponse(id, response, xhr); } } else if (chunkFiles) { handleSuccessfullyCompletedChunk(id, response, xhr); } else { handleCompletedItem(id, response, xhr); } } function getReadyStateChangeHandler(id, xhr) { return function() { if (xhr.readyState === 4) { onComplete(id, xhr); } }; } function persistChunkData(id, chunkData) { var fileUuid = getUuid(id), lastByteSent = handler._getFileState(id).loaded, initialRequestOverhead = handler._getFileState(id).initialRequestOverhead, estTotalRequestsSize = handler._getFileState(id).estTotalRequestsSize, cookieName = getChunkDataCookieName(id), cookieValue = fileUuid + cookieItemDelimiter + chunkData.part + cookieItemDelimiter + lastByteSent + cookieItemDelimiter + initialRequestOverhead + cookieItemDelimiter + estTotalRequestsSize, cookieExpDays = spec.resume.cookiesExpireIn; qq.setCookie(cookieName, cookieValue, cookieExpDays); } function deletePersistedChunkData(id) { if (handler._getFileState(id).file) { var cookieName = getChunkDataCookieName(id); qq.deleteCookie(cookieName); } } function getPersistedChunkData(id) { var chunkCookieValue = qq.getCookie(getChunkDataCookieName(id)), filename = getName(id), sections, uuid, partIndex, lastByteSent, initialRequestOverhead, estTotalRequestsSize; if (chunkCookieValue) { sections = chunkCookieValue.split(cookieItemDelimiter); if (sections.length === 5) { uuid = sections[0]; partIndex = parseInt(sections[1], 10); lastByteSent = parseInt(sections[2], 10); initialRequestOverhead = parseInt(sections[3], 10); estTotalRequestsSize = parseInt(sections[4], 10); return { uuid: uuid, part: partIndex, lastByteSent: lastByteSent, initialRequestOverhead: initialRequestOverhead, estTotalRequestsSize: estTotalRequestsSize }; } else { log("Ignoring previously stored resume/chunk cookie for " + filename + " - old cookie format", "warn"); } } } function getChunkDataCookieName(id) { var filename = getName(id), fileSize = getSize(id), maxChunkSize = spec.chunking.partSize, cookieName; cookieName = "qqfilechunk" + cookieItemDelimiter + encodeURIComponent(filename) + cookieItemDelimiter + fileSize + cookieItemDelimiter + maxChunkSize; if (resumeId !== undefined) { cookieName += cookieItemDelimiter + resumeId; } return cookieName; } function calculateRemainingChunkIdxsAndUpload(id, firstChunkIndex) { var currentChunkIndex; for (currentChunkIndex = handler._getTotalChunks(id)-1; currentChunkIndex >= firstChunkIndex; currentChunkIndex-=1) { handler._getFileState(id).remainingChunkIdxs.unshift(currentChunkIndex); } uploadNextChunk(id); } function onResumeSuccess(id, name, firstChunkIndex, persistedChunkInfoForResume) { firstChunkIndex = persistedChunkInfoForResume.part; handler._getFileState(id).loaded = persistedChunkInfoForResume.lastByteSent; handler._getFileState(id).estTotalRequestsSize = persistedChunkInfoForResume.estTotalRequestsSize; handler._getFileState(id).initialRequestOverhead = persistedChunkInfoForResume.initialRequestOverhead; handler._getFileState(id).attemptingResume = true; log("Resuming " + name + " at partition index " + firstChunkIndex); calculateRemainingChunkIdxsAndUpload(id, firstChunkIndex); } function handlePossibleResumeAttempt(id, persistedChunkInfoForResume, firstChunkIndex) { var name = getName(id), firstChunkDataForResume = handler._getChunkData(id, persistedChunkInfoForResume.part), onResumeRetVal; onResumeRetVal = spec.onResume(id, name, handler._getChunkDataForCallback(firstChunkDataForResume)); if (onResumeRetVal instanceof qq.Promise) { log("Waiting for onResume promise to be fulfilled for " + id); onResumeRetVal.then( function() { onResumeSuccess(id, name, firstChunkIndex, persistedChunkInfoForResume); }, function() { log("onResume promise fulfilled - failure indicated. Will not resume."); calculateRemainingChunkIdxsAndUpload(id, firstChunkIndex); } ); } else if (onResumeRetVal !== false) { onResumeSuccess(id, name, firstChunkIndex, persistedChunkInfoForResume); } else { log("onResume callback returned false. Will not resume."); calculateRemainingChunkIdxsAndUpload(id, firstChunkIndex); } } function handleFileChunkingUpload(id, retry) { var firstChunkIndex = 0, persistedChunkInfoForResume; if (!handler._getFileState(id).remainingChunkIdxs || handler._getFileState(id).remainingChunkIdxs.length === 0) { handler._getFileState(id).remainingChunkIdxs = []; if (resumeEnabled && !retry && handler._getFileState(id).file) { persistedChunkInfoForResume = getPersistedChunkData(id); if (persistedChunkInfoForResume) { handlePossibleResumeAttempt(id, persistedChunkInfoForResume, firstChunkIndex); } else { calculateRemainingChunkIdxsAndUpload(id, firstChunkIndex); } } else { calculateRemainingChunkIdxsAndUpload(id, firstChunkIndex); } } else { uploadNextChunk(id); } } function handleStandardFileUpload(id) { var fileOrBlob = handler._getFileState(id).file || handler._getFileState(id).blobData.blob, name = getName(id), xhr, params, toSend; handler._getFileState(id).loaded = 0; xhr = handler._createXhr(id); xhr.upload.onprogress = function(e){ if (e.lengthComputable){ handler._getFileState(id).loaded = e.loaded; spec.onProgress(id, name, e.loaded, e.total); } }; xhr.onreadystatechange = getReadyStateChangeHandler(id, xhr); params = spec.paramsStore.get(id); toSend = setParamsAndGetEntityToSend(params, xhr, fileOrBlob, id); setHeaders(id, xhr); log("Sending upload request for " + id); xhr.send(toSend); } function handleUploadSignal(id, retry) { var name = getName(id); if (handler.isValid(id)) { spec.onUpload(id, name); if (chunkFiles) { handleFileChunkingUpload(id, retry); } else { handleStandardFileUpload(id); } } } qq.extend(this, new qq.AbstractUploadHandlerXhr({ options: { chunking: chunkFiles ? spec.chunking : null }, proxy: { onUpload: handleUploadSignal, onCancel: spec.onCancel, onUuidChanged: onUuidChanged, getName: getName, getSize: getSize, getUuid: getUuid, log: log } } )); qq.override(this, function(super_) { return { add: function(id, fileOrBlobData) { var persistedChunkData; super_.add.apply(this, arguments); if (resumeEnabled) { persistedChunkData = getPersistedChunkData(id); if (persistedChunkData) { onUuidChanged(id, persistedChunkData.uuid); } } return id; }, getResumableFilesData: function() { var matchingCookieNames = [], resumableFilesData = []; if (chunkFiles && resumeEnabled) { if (resumeId === undefined) { matchingCookieNames = qq.getCookieNames(new RegExp("^qqfilechunk\\" + cookieItemDelimiter + ".+\\" + cookieItemDelimiter + "\\d+\\" + cookieItemDelimiter + spec.chunking.partSize + "=")); } else { matchingCookieNames = qq.getCookieNames(new RegExp("^qqfilechunk\\" + cookieItemDelimiter + ".+\\" + cookieItemDelimiter + "\\d+\\" + cookieItemDelimiter + spec.chunking.partSize + "\\" + cookieItemDelimiter + resumeId + "=")); } qq.each(matchingCookieNames, function(idx, cookieName) { var cookiesNameParts = cookieName.split(cookieItemDelimiter); var cookieValueParts = qq.getCookie(cookieName).split(cookieItemDelimiter); resumableFilesData.push({ name: decodeURIComponent(cookiesNameParts[1]), size: cookiesNameParts[2], uuid: cookieValueParts[0], partIdx: cookieValueParts[1] }); }); return resumableFilesData; } return []; }, expunge: function(id) { if (resumeEnabled) { deletePersistedChunkData(id); } super_.expunge(id); } }; }); }; /*globals qq*/ qq.PasteSupport = function(o) { "use strict"; var options, detachPasteHandler; options = { targetElement: null, callbacks: { log: function(message, level) {}, pasteReceived: function(blob) {} } }; function isImage(item) { return item.type && item.type.indexOf("image/") === 0; } function registerPasteHandler() { qq(options.targetElement).attach("paste", function(event) { var clipboardData = event.clipboardData; if (clipboardData) { qq.each(clipboardData.items, function(idx, item) { if (isImage(item)) { var blob = item.getAsFile(); options.callbacks.pasteReceived(blob); } }); } }); } function unregisterPasteHandler() { if (detachPasteHandler) { detachPasteHandler(); } } qq.extend(options, o); registerPasteHandler(); qq.extend(this, { reset: function() { unregisterPasteHandler(); } }); }; /*globals qq, document, CustomEvent*/ qq.DragAndDrop = function(o) { "use strict"; var options, HIDE_ZONES_EVENT_NAME = "qq-hidezones", HIDE_BEFORE_ENTER_ATTR = "qq-hide-dropzone", uploadDropZones = [], droppedFiles = [], disposeSupport = new qq.DisposeSupport(); options = { dropZoneElements: [], allowMultipleItems: true, classes: { dropActive: null }, callbacks: new qq.DragAndDrop.callbacks() }; qq.extend(options, o, true); function uploadDroppedFiles(files, uploadDropZone) { // We need to convert the `FileList` to an actual `Array` to avoid iteration issues var filesAsArray = Array.prototype.slice.call(files); options.callbacks.dropLog("Grabbed " + files.length + " dropped files."); uploadDropZone.dropDisabled(false); options.callbacks.processingDroppedFilesComplete(filesAsArray, uploadDropZone.getElement()); } function traverseFileTree(entry) { var dirReader, parseEntryPromise = new qq.Promise(); if (entry.isFile) { entry.file(function(file) { droppedFiles.push(file); parseEntryPromise.success(); }, function(fileError) { options.callbacks.dropLog("Problem parsing '" + entry.fullPath + "'. FileError code " + fileError.code + ".", "error"); parseEntryPromise.failure(); }); } else if (entry.isDirectory) { dirReader = entry.createReader(); dirReader.readEntries(function(entries) { var entriesLeft = entries.length; qq.each(entries, function(idx, entry) { traverseFileTree(entry).done(function() { entriesLeft-=1; if (entriesLeft === 0) { parseEntryPromise.success(); } }); }); if (!entries.length) { parseEntryPromise.success(); } }, function(fileError) { options.callbacks.dropLog("Problem parsing '" + entry.fullPath + "'. FileError code " + fileError.code + ".", "error"); parseEntryPromise.failure(); }); } return parseEntryPromise; } function handleDataTransfer(dataTransfer, uploadDropZone) { var pendingFolderPromises = [], handleDataTransferPromise = new qq.Promise(); options.callbacks.processingDroppedFiles(); uploadDropZone.dropDisabled(true); if (dataTransfer.files.length > 1 && !options.allowMultipleItems) { options.callbacks.processingDroppedFilesComplete([]); options.callbacks.dropError("tooManyFilesError", ""); uploadDropZone.dropDisabled(false); handleDataTransferPromise.failure(); } else { droppedFiles = []; if (qq.isFolderDropSupported(dataTransfer)) { qq.each(dataTransfer.items, function(idx, item) { var entry = item.webkitGetAsEntry(); if (entry) { //due to a bug in Chrome's File System API impl - #149735 if (entry.isFile) { droppedFiles.push(item.getAsFile()); } else { pendingFolderPromises.push(traverseFileTree(entry).done(function() { pendingFolderPromises.pop(); if (pendingFolderPromises.length === 0) { handleDataTransferPromise.success(); } })); } } }); } else { droppedFiles = dataTransfer.files; } if (pendingFolderPromises.length === 0) { handleDataTransferPromise.success(); } } return handleDataTransferPromise; } function setupDropzone(dropArea) { var dropZone = new qq.UploadDropZone({ HIDE_ZONES_EVENT_NAME: HIDE_ZONES_EVENT_NAME, element: dropArea, onEnter: function(e){ qq(dropArea).addClass(options.classes.dropActive); e.stopPropagation(); }, onLeaveNotDescendants: function(e){ qq(dropArea).removeClass(options.classes.dropActive); }, onDrop: function(e){ handleDataTransfer(e.dataTransfer, dropZone).then( function() { uploadDroppedFiles(droppedFiles, dropZone); }, function() { options.callbacks.dropLog("Drop event DataTransfer parsing failed. No files will be uploaded.", "error"); } ); } }); disposeSupport.addDisposer(function() { dropZone.dispose(); }); qq(dropArea).hasAttribute(HIDE_BEFORE_ENTER_ATTR) && qq(dropArea).hide(); uploadDropZones.push(dropZone); return dropZone; } function isFileDrag(dragEvent) { var fileDrag; qq.each(dragEvent.dataTransfer.types, function(key, val) { if (val === "Files") { fileDrag = true; return false; } }); return fileDrag; } function leavingDocumentOut(e) { /* jshint -W041, eqeqeq:false */ // null coords for Chrome and Safari Windows return ((qq.chrome() || (qq.safari() && qq.windows())) && e.clientX == 0 && e.clientY == 0) || // null e.relatedTarget for Firefox (qq.firefox() && !e.relatedTarget); } function setupDragDrop() { var dropZones = options.dropZoneElements; qq.each(dropZones, function(idx, dropZone) { var uploadDropZone = setupDropzone(dropZone); // IE <= 9 does not support the File API used for drag+drop uploads if (dropZones.length && (!qq.ie() || qq.ie10())) { disposeSupport.attach(document, "dragenter", function(e) { if (!uploadDropZone.dropDisabled() && isFileDrag(e)) { qq.each(dropZones, function(idx, dropZone) { // We can't apply styles to non-HTMLElements, since they lack the `style` property if (dropZone instanceof HTMLElement) { qq(dropZone).css({display: "block"}); } }); } }); } }); disposeSupport.attach(document, "dragleave", function(e) { if (leavingDocumentOut(e)) { qq.each(dropZones, function(idx, dropZone) { qq(dropZone).hasAttribute(HIDE_BEFORE_ENTER_ATTR) && qq(dropZone).hide(); }); } }); disposeSupport.attach(document, "drop", function(e){ qq.each(dropZones, function(idx, dropZone) { qq(dropZone).hasAttribute(HIDE_BEFORE_ENTER_ATTR) && qq(dropZone).hide(); }); e.preventDefault(); }); disposeSupport.attach(document, HIDE_ZONES_EVENT_NAME, function(e) { qq.each(options.dropZoneElements, function(idx, zone) { qq(zone).hasAttribute(HIDE_BEFORE_ENTER_ATTR) && qq(zone).hide(); qq(zone).removeClass(options.classes.dropActive); }); }); } setupDragDrop(); qq.extend(this, { setupExtraDropzone: function(element) { options.dropZoneElements.push(element); setupDropzone(element); }, removeDropzone: function(element) { var i, dzs = options.dropZoneElements; for(i in dzs) { if (dzs[i] === element) { return dzs.splice(i, 1); } } }, dispose: function() { disposeSupport.dispose(); qq.each(uploadDropZones, function(idx, dropZone) { dropZone.dispose(); }); } }); }; qq.DragAndDrop.callbacks = function() { "use strict"; return { processingDroppedFiles: function() {}, processingDroppedFilesComplete: function(files, targetEl) {}, dropError: function(code, errorSpecifics) { qq.log("Drag & drop error code '" + code + " with these specifics: '" + errorSpecifics + "'", "error"); }, dropLog: function(message, level) { qq.log(message, level); } }; }; qq.UploadDropZone = function(o){ "use strict"; var disposeSupport = new qq.DisposeSupport(), options, element, preventDrop, dropOutsideDisabled; options = { element: null, onEnter: function(e){}, onLeave: function(e){}, // is not fired when leaving element by hovering descendants onLeaveNotDescendants: function(e){}, onDrop: function(e){} }; qq.extend(options, o); element = options.element; function dragover_should_be_canceled(){ return qq.safari() || (qq.firefox() && qq.windows()); } function disableDropOutside(e){ // run only once for all instances if (!dropOutsideDisabled ){ // for these cases we need to catch onDrop to reset dropArea if (dragover_should_be_canceled){ disposeSupport.attach(document, "dragover", function(e){ e.preventDefault(); }); } else { disposeSupport.attach(document, "dragover", function(e){ if (e.dataTransfer){ e.dataTransfer.dropEffect = "none"; e.preventDefault(); } }); } dropOutsideDisabled = true; } } function isValidFileDrag(e){ // e.dataTransfer currently causing IE errors // IE9 does NOT support file API, so drag-and-drop is not possible if (qq.ie() && !qq.ie10()) { return false; } var effectTest, dt = e.dataTransfer, // do not check dt.types.contains in webkit, because it crashes safari 4 isSafari = qq.safari(); // dt.effectAllowed is none in Safari 5 // dt.types.contains check is for firefox // dt.effectAllowed crashes IE11 when files have been dragged from // the filesystem effectTest = (qq.ie10() || qq.ie11()) ? true : dt.effectAllowed !== "none"; return dt && effectTest && (dt.files || (!isSafari && dt.types.contains && dt.types.contains("Files"))); } function isOrSetDropDisabled(isDisabled) { if (isDisabled !== undefined) { preventDrop = isDisabled; } return preventDrop; } function triggerHidezonesEvent() { var hideZonesEvent; function triggerUsingOldApi() { hideZonesEvent = document.createEvent("Event"); hideZonesEvent.initEvent(options.HIDE_ZONES_EVENT_NAME, true, true); } if (window.CustomEvent) { try { hideZonesEvent = new CustomEvent(options.HIDE_ZONES_EVENT_NAME); } catch (err) { triggerUsingOldApi(); } } else { triggerUsingOldApi(); } document.dispatchEvent(hideZonesEvent); } function attachEvents(){ disposeSupport.attach(element, "dragover", function(e){ if (!isValidFileDrag(e)) { return; } // dt.effectAllowed crashes IE11 when files have been dragged from // the filesystem var effect = (qq.ie() || qq.ie11()) ? null : e.dataTransfer.effectAllowed; if (effect === "move" || effect === "linkMove"){ e.dataTransfer.dropEffect = "move"; // for FF (only move allowed) } else { e.dataTransfer.dropEffect = "copy"; // for Chrome } e.stopPropagation(); e.preventDefault(); }); disposeSupport.attach(element, "dragenter", function(e){ if (!isOrSetDropDisabled()) { if (!isValidFileDrag(e)) { return; } options.onEnter(e); } }); disposeSupport.attach(element, "dragleave", function(e){ if (!isValidFileDrag(e)) { return; } options.onLeave(e); var relatedTarget = document.elementFromPoint(e.clientX, e.clientY); // do not fire when moving a mouse over a descendant if (qq(this).contains(relatedTarget)) { return; } options.onLeaveNotDescendants(e); }); disposeSupport.attach(element, "drop", function(e) { if (!isOrSetDropDisabled()) { if (!isValidFileDrag(e)) { return; } e.preventDefault(); e.stopPropagation(); options.onDrop(e); triggerHidezonesEvent(); } }); } disableDropOutside(); attachEvents(); qq.extend(this, { dropDisabled: function(isDisabled) { return isOrSetDropDisabled(isDisabled); }, dispose: function() { disposeSupport.dispose(); }, getElement: function() { return element; } }); }; /*globals qq, XMLHttpRequest*/ qq.DeleteFileAjaxRequester = function(o) { "use strict"; var requester, options = { method: "DELETE", uuidParamName: "qquuid", endpointStore: {}, maxConnections: 3, customHeaders: {}, paramsStore: {}, demoMode: false, cors: { expected: false, sendCredentials: false }, log: function(str, level) {}, onDelete: function(id) {}, onDeleteComplete: function(id, xhrOrXdr, isError) {} }; qq.extend(options, o); function getMandatedParams() { if (options.method.toUpperCase() === "POST") { return { "_method": "DELETE" }; } return {}; } requester = qq.extend(this, new qq.AjaxRequester({ validMethods: ["POST", "DELETE"], method: options.method, endpointStore: options.endpointStore, paramsStore: options.paramsStore, mandatedParams: getMandatedParams(), maxConnections: options.maxConnections, customHeaders: options.customHeaders, demoMode: options.demoMode, log: options.log, onSend: options.onDelete, onComplete: options.onDeleteComplete, cors: options.cors })); qq.extend(this, { sendDelete: function(id, uuid, additionalMandatedParams) { var additionalOptions = additionalMandatedParams || {}; options.log("Submitting delete file request for " + id); if (options.method === "DELETE") { requester.initTransport(id) .withPath(uuid) .withParams(additionalOptions) .send(); } else { additionalOptions[options.uuidParamName] = uuid; requester.initTransport(id) .withParams(additionalOptions) .send(); } } }); }; /*global qq, define */ /*jshint strict:false,bitwise:false,nonew:false,asi:true,-W064,-W116,-W089 */ /** * Mega pixel image rendering library for iOS6 Safari * * Fixes iOS6 Safari's image file rendering issue for large size image (over mega-pixel), * which causes unexpected subsampling when drawing it in canvas. * By using this library, you can safely render the image with proper stretching. * * Copyright (c) 2012 Shinichi Tomita <shinichi.tomita@gmail.com> * Released under the MIT license */ (function() { /** * Detect subsampling in loaded image. * In iOS, larger images than 2M pixels may be subsampled in rendering. */ function detectSubsampling(img) { var iw = img.naturalWidth, ih = img.naturalHeight; if (iw * ih > 1024 * 1024) { // subsampling may happen over megapixel image var canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; var ctx = canvas.getContext('2d'); ctx.drawImage(img, -iw + 1, 0); // subsampled image becomes half smaller in rendering size. // check alpha channel value to confirm image is covering edge pixel or not. // if alpha value is 0 image is not covering, hence subsampled. return ctx.getImageData(0, 0, 1, 1).data[3] === 0; } else { return false; } } /** * Detecting vertical squash in loaded image. * Fixes a bug which squash image vertically while drawing into canvas for some images. */ function detectVerticalSquash(img, iw, ih) { var canvas = document.createElement('canvas'); canvas.width = 1; canvas.height = ih; var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); var data = ctx.getImageData(0, 0, 1, ih).data; // search image edge pixel position in case it is squashed vertically. var sy = 0; var ey = ih; var py = ih; while (py > sy) { var alpha = data[(py - 1) * 4 + 3]; if (alpha === 0) { ey = py; } else { sy = py; } py = (ey + sy) >> 1; } var ratio = (py / ih); return (ratio===0)?1:ratio; } /** * Rendering image element (with resizing) and get its data URL */ function renderImageToDataURL(img, options, doSquash) { var canvas = document.createElement('canvas'), mime = options.mime || "image/jpeg"; renderImageToCanvas(img, canvas, options, doSquash); return canvas.toDataURL(mime, options.quality || 0.8); } /** * Rendering image element (with resizing) into the canvas element */ function renderImageToCanvas(img, canvas, options, doSquash) { var iw = img.naturalWidth, ih = img.naturalHeight; var width = options.width, height = options.height; var ctx = canvas.getContext('2d'); ctx.save(); transformCoordinate(canvas, width, height, options.orientation); // Fine Uploader specific: Save some CPU cycles if not using iOS // Assumption: This logic is only needed to overcome iOS image sampling issues if (qq.ios()) { var subsampled = detectSubsampling(img); if (subsampled) { iw /= 2; ih /= 2; } var d = 1024; // size of tiling canvas var tmpCanvas = document.createElement('canvas'); tmpCanvas.width = tmpCanvas.height = d; var tmpCtx = tmpCanvas.getContext('2d'); var vertSquashRatio = doSquash ? detectVerticalSquash(img, iw, ih) : 1; var dw = Math.ceil(d * width / iw); var dh = Math.ceil(d * height / ih / vertSquashRatio); var sy = 0; var dy = 0; while (sy < ih) { var sx = 0; var dx = 0; while (sx < iw) { tmpCtx.clearRect(0, 0, d, d); tmpCtx.drawImage(img, -sx, -sy); ctx.drawImage(tmpCanvas, 0, 0, d, d, dx, dy, dw, dh); sx += d; dx += dw; } sy += d; dy += dh; } ctx.restore(); tmpCanvas = tmpCtx = null; } else { ctx.drawImage(img, 0, 0, width, height); } } /** * Transform canvas coordination according to specified frame size and orientation * Orientation value is from EXIF tag */ function transformCoordinate(canvas, width, height, orientation) { switch (orientation) { case 5: case 6: case 7: case 8: canvas.width = height; canvas.height = width; break; default: canvas.width = width; canvas.height = height; } var ctx = canvas.getContext('2d'); switch (orientation) { case 2: // horizontal flip ctx.translate(width, 0); ctx.scale(-1, 1); break; case 3: // 180 rotate left ctx.translate(width, height); ctx.rotate(Math.PI); break; case 4: // vertical flip ctx.translate(0, height); ctx.scale(1, -1); break; case 5: // vertical flip + 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.scale(1, -1); break; case 6: // 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.translate(0, -height); break; case 7: // horizontal flip + 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.translate(width, -height); ctx.scale(-1, 1); break; case 8: // 90 rotate left ctx.rotate(-0.5 * Math.PI); ctx.translate(-width, 0); break; default: break; } } /** * MegaPixImage class */ function MegaPixImage(srcImage, errorCallback) { if (window.Blob && srcImage instanceof Blob) { var img = new Image(); var URL = window.URL && window.URL.createObjectURL ? window.URL : window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL : null; if (!URL) { throw Error("No createObjectURL function found to create blob url"); } img.src = URL.createObjectURL(srcImage); this.blob = srcImage; srcImage = img; } if (!srcImage.naturalWidth && !srcImage.naturalHeight) { var _this = this; srcImage.onload = function() { var listeners = _this.imageLoadListeners; if (listeners) { _this.imageLoadListeners = null; for (var i=0, len=listeners.length; i<len; i++) { listeners[i](); } } }; srcImage.onerror = errorCallback; this.imageLoadListeners = []; } this.srcImage = srcImage; } /** * Rendering megapix image into specified target element */ MegaPixImage.prototype.render = function(target, options) { if (this.imageLoadListeners) { var _this = this; this.imageLoadListeners.push(function() { _this.render(target, options) }); return; } options = options || {}; var imgWidth = this.srcImage.naturalWidth, imgHeight = this.srcImage.naturalHeight, width = options.width, height = options.height, maxWidth = options.maxWidth, maxHeight = options.maxHeight, doSquash = !this.blob || this.blob.type === 'image/jpeg'; if (width && !height) { height = (imgHeight * width / imgWidth) << 0; } else if (height && !width) { width = (imgWidth * height / imgHeight) << 0; } else { width = imgWidth; height = imgHeight; } if (maxWidth && width > maxWidth) { width = maxWidth; height = (imgHeight * width / imgWidth) << 0; } if (maxHeight && height > maxHeight) { height = maxHeight; width = (imgWidth * height / imgHeight) << 0; } var opt = { width : width, height : height }; for (var k in options) opt[k] = options[k]; var tagName = target.tagName.toLowerCase(); if (tagName === 'img') { target.src = renderImageToDataURL(this.srcImage, opt, doSquash); } else if (tagName === 'canvas') { renderImageToCanvas(this.srcImage, target, opt, doSquash); } if (typeof this.onrender === 'function') { this.onrender(target); } }; /** * Export class to global */ if (typeof define === 'function' && define.amd) { define([], function() { return MegaPixImage; }); // for AMD loader } else { this.MegaPixImage = MegaPixImage; } })(); /*globals qq, MegaPixImage */ /** * Draws a thumbnail of a Blob/File/URL onto an <img> or <canvas>. * * @constructor */ qq.ImageGenerator = function(log) { "use strict"; function isImg(el) { return el.tagName.toLowerCase() === "img"; } function isCanvas(el) { return el.tagName.toLowerCase() === "canvas"; } function isImgCorsSupported() { return new Image().crossOrigin !== undefined; } function isCanvasSupported() { var canvas = document.createElement("canvas"); return canvas.getContext && canvas.getContext("2d"); } // This is only meant to determine the MIME type of a renderable image file. // It is used to ensure images drawn from a URL that have transparent backgrounds // are rendered correctly, among other things. function determineMimeOfFileName(nameWithPath) { /*jshint -W015 */ var pathSegments = nameWithPath.split("/"), name = pathSegments[pathSegments.length - 1], extension = qq.getExtension(name); extension = extension && extension.toLowerCase(); switch(extension) { case "jpeg": case "jpg": return "image/jpeg"; case "png": return "image/png"; case "bmp": return "image/bmp"; case "gif": return "image/gif"; case "tiff": case "tif": return "image/tiff"; } } // This will likely not work correctly in IE8 and older. // It's only used as part of a formula to determine // if a canvas can be used to scale a server-hosted thumbnail. // If canvas isn't supported by the UA (IE8 and older) // this method should not even be called. function isCrossOrigin(url) { var targetAnchor = document.createElement("a"), targetProtocol, targetHostname, targetPort; targetAnchor.href = url; targetProtocol = targetAnchor.protocol; targetPort = targetAnchor.port; targetHostname = targetAnchor.hostname; if (targetProtocol.toLowerCase() !== window.location.protocol.toLowerCase()) { return true; } if (targetHostname.toLowerCase() !== window.location.hostname.toLowerCase()) { return true; } // IE doesn't take ports into consideration when determining if two endpoints are same origin. if (targetPort !== window.location.port && !qq.ie()) { return true; } return false; } function registerImgLoadListeners(img, promise) { img.onload = function() { img.onload = null; img.onerror = null; promise.success(img); }; img.onerror = function() { img.onload = null; img.onerror = null; log("Problem drawing thumbnail!", "error"); promise.failure(img, "Problem drawing thumbnail!"); }; } function registerCanvasDrawImageListener(canvas, promise) { var context = canvas.getContext("2d"), oldDrawImage = context.drawImage; // The image is drawn on the canvas by a third-party library, // and we want to know when this happens so we can fulfill the associated promise. context.drawImage = function() { oldDrawImage.apply(this, arguments); promise.success(canvas); context.drawImage = oldDrawImage; }; } // Fulfills a `qq.Promise` when an image has been drawn onto the target, // whether that is a <canvas> or an <img>. The attempt is considered a // failure if the target is not an <img> or a <canvas>, or if the drawing // attempt was not successful. function registerThumbnailRenderedListener(imgOrCanvas, promise) { var registered = isImg(imgOrCanvas) || isCanvas(imgOrCanvas); if (isImg(imgOrCanvas)) { registerImgLoadListeners(imgOrCanvas, promise); } else if (isCanvas(imgOrCanvas)) { registerCanvasDrawImageListener(imgOrCanvas, promise); } else { promise.failure(imgOrCanvas); log(qq.format("Element container of type {} is not supported!", imgOrCanvas.tagName), "error"); } return registered; } // Draw a preview iff the current UA can natively display it. // Also rotate the image if necessary. function draw(fileOrBlob, container, options) { var drawPreview = new qq.Promise(), identifier = new qq.Identify(fileOrBlob, log), maxSize = options.maxSize, megapixErrorHandler = function() { container.onerror = null; container.onload = null; log("Could not render preview, file may be too large!", "error"); drawPreview.failure(container, "Browser cannot render image!"); }; identifier.isPreviewable().then( function(mime) { var exif = new qq.Exif(fileOrBlob, log), mpImg = new MegaPixImage(fileOrBlob, megapixErrorHandler); if (registerThumbnailRenderedListener(container, drawPreview)) { exif.parse().then( function(exif) { var orientation = exif.Orientation; mpImg.render(container, { maxWidth: maxSize, maxHeight: maxSize, orientation: orientation, mime: mime }); }, function(failureMsg) { log(qq.format("EXIF data could not be parsed ({}). Assuming orientation = 1.", failureMsg)); mpImg.render(container, { maxWidth: maxSize, maxHeight: maxSize, mime: mime }); } ); } }, function() { log("Not previewable"); drawPreview.failure(container, "Not previewable"); } ); return drawPreview; } function drawOnCanvasOrImgFromUrl(url, canvasOrImg, draw, maxSize) { var tempImg = new Image(), tempImgRender = new qq.Promise(); registerThumbnailRenderedListener(tempImg, tempImgRender); if (isCrossOrigin(url)) { tempImg.crossOrigin = "anonymous"; } tempImg.src = url; tempImgRender.then(function() { registerThumbnailRenderedListener(canvasOrImg, draw); var mpImg = new MegaPixImage(tempImg); mpImg.render(canvasOrImg, { maxWidth: maxSize, maxHeight: maxSize, mime: determineMimeOfFileName(url) }); }); } function drawOnImgFromUrlWithCssScaling(url, img, draw, maxSize) { registerThumbnailRenderedListener(img, draw); qq(img).css({ maxWidth: maxSize + "px", maxHeight: maxSize + "px" }); img.src = url; } // Draw a (server-hosted) thumbnail given a URL. // This will optionally scale the thumbnail as well. // It attempts to use <canvas> to scale, but will fall back // to max-width and max-height style properties if the UA // doesn't support canvas or if the images is cross-domain and // the UA doesn't support the crossorigin attribute on img tags, // which is required to scale a cross-origin image using <canvas> & // then export it back to an <img>. function drawFromUrl(url, container, options) { var draw = new qq.Promise(), scale = options.scale, maxSize = scale ? options.maxSize : null; // container is an img, scaling needed if (scale && isImg(container)) { // Iff canvas is available in this UA, try to use it for scaling. // Otherwise, fall back to CSS scaling if (isCanvasSupported()) { // Attempt to use <canvas> for image scaling, // but we must fall back to scaling via CSS/styles // if this is a cross-origin image and the UA doesn't support <img> CORS. if (isCrossOrigin(url) && !isImgCorsSupported()) { drawOnImgFromUrlWithCssScaling(url, container, draw, maxSize); } else { drawOnCanvasOrImgFromUrl(url, container, draw, maxSize); } } else { drawOnImgFromUrlWithCssScaling(url, container, draw, maxSize); } } // container is a canvas, scaling optional else if (isCanvas(container)) { drawOnCanvasOrImgFromUrl(url, container, draw, maxSize); } // container is an img & no scaling: just set the src attr to the passed url else if (registerThumbnailRenderedListener(container, draw)) { container.src = url; } return draw; } qq.extend(this, { /** * Generate a thumbnail. Depending on the arguments, this may either result in * a client-side rendering of an image (if a `Blob` is supplied) or a server-generated * image that may optionally be scaled client-side using <canvas> or CSS/styles (as a fallback). * * @param fileBlobOrUrl a `File`, `Blob`, or a URL pointing to the image * @param container <img> or <canvas> to contain the preview * @param options possible properties include `maxSize` (int), `orient` (bool), and `resize` (bool) * @returns qq.Promise fulfilled when the preview has been drawn, or the attempt has failed */ generate: function(fileBlobOrUrl, container, options) { if (qq.isString(fileBlobOrUrl)) { log("Attempting to update thumbnail based on server response."); return drawFromUrl(fileBlobOrUrl, container, options || {}); } else { log("Attempting to draw client-side image preview."); return draw(fileBlobOrUrl, container, options || {}); } } }); /*<testing>*/ this._testing = {}; this._testing.isImg = isImg; this._testing.isCanvas = isCanvas; this._testing.isCrossOrigin = isCrossOrigin; this._testing.determineMimeOfFileName = determineMimeOfFileName; /*</testing>*/ }; /*globals qq */ /** * EXIF image data parser. Currently only parses the Orientation tag value, * but this may be expanded to other tags in the future. * * @param fileOrBlob Attempt to parse EXIF data in this `Blob` * @constructor */ qq.Exif = function(fileOrBlob, log) { "use strict"; // Orientation is the only tag parsed here at this time. var TAG_IDS = [274], TAG_INFO = { 274: { name: "Orientation", bytes: 2 } }; // Convert a little endian (hex string) to big endian (decimal). function parseLittleEndian(hex) { var result = 0, pow = 0; while (hex.length > 0) { result += parseInt(hex.substring(0, 2), 16) * Math.pow(2, pow); hex = hex.substring(2, hex.length); pow += 8; } return result; } // Find the byte offset, of Application Segment 1 (EXIF). // External callers need not supply any arguments. function seekToApp1(offset, promise) { var theOffset = offset, thePromise = promise; if (theOffset === undefined) { theOffset = 2; thePromise = new qq.Promise(); } qq.readBlobToHex(fileOrBlob, theOffset, 4).then(function(hex) { var match = /^ffe([0-9])/.exec(hex); if (match) { if (match[1] !== "1") { var segmentLength = parseInt(hex.slice(4, 8), 16); seekToApp1(theOffset + segmentLength + 2, thePromise); } else { thePromise.success(theOffset); } } else { thePromise.failure("No EXIF header to be found!"); } }); return thePromise; } // Find the byte offset of Application Segment 1 (EXIF) for valid JPEGs only. function getApp1Offset() { var promise = new qq.Promise(); qq.readBlobToHex(fileOrBlob, 0, 6).then(function(hex) { if (hex.indexOf("ffd8") !== 0) { promise.failure("Not a valid JPEG!"); } else { seekToApp1().then(function(offset) { promise.success(offset); }, function(error) { promise.failure(error); }); } }); return promise; } // Determine the byte ordering of the EXIF header. function isLittleEndian(app1Start) { var promise = new qq.Promise(); qq.readBlobToHex(fileOrBlob, app1Start + 10, 2).then(function(hex) { promise.success(hex === "4949"); }); return promise; } // Determine the number of directory entries in the EXIF header. function getDirEntryCount(app1Start, littleEndian) { var promise = new qq.Promise(); qq.readBlobToHex(fileOrBlob, app1Start + 18, 2).then(function(hex) { if (littleEndian) { return promise.success(parseLittleEndian(hex)); } else { promise.success(parseInt(hex, 16)); } }); return promise; } // Get the IFD portion of the EXIF header as a hex string. function getIfd(app1Start, dirEntries) { var offset = app1Start + 20, bytes = dirEntries * 12; return qq.readBlobToHex(fileOrBlob, offset, bytes); } // Obtain an array of all directory entries (as hex strings) in the EXIF header. function getDirEntries(ifdHex) { var entries = [], offset = 0; while (offset+24 <= ifdHex.length) { entries.push(ifdHex.slice(offset, offset + 24)); offset += 24; } return entries; } // Obtain values for all relevant tags and return them. function getTagValues(littleEndian, dirEntries) { var TAG_VAL_OFFSET = 16, tagsToFind = qq.extend([], TAG_IDS), vals = {}; qq.each(dirEntries, function(idx, entry) { var idHex = entry.slice(0, 4), id = littleEndian ? parseLittleEndian(idHex) : parseInt(idHex, 16), tagsToFindIdx = tagsToFind.indexOf(id), tagValHex, tagName, tagValLength; if (tagsToFindIdx >= 0) { tagName = TAG_INFO[id].name; tagValLength = TAG_INFO[id].bytes; tagValHex = entry.slice(TAG_VAL_OFFSET, TAG_VAL_OFFSET + (tagValLength*2)); vals[tagName] = littleEndian ? parseLittleEndian(tagValHex) : parseInt(tagValHex, 16); tagsToFind.splice(tagsToFindIdx, 1); } if (tagsToFind.length === 0) { return false; } }); return vals; } qq.extend(this, { /** * Attempt to parse the EXIF header for the `Blob` associated with this instance. * * @returns {qq.Promise} To be fulfilled when the parsing is complete. * If successful, the parsed EXIF header as an object will be included. */ parse: function() { var parser = new qq.Promise(), onParseFailure = function(message) { log(qq.format("EXIF header parse failed: '{}' ", message)); parser.failure(message); }; getApp1Offset().then(function(app1Offset) { log(qq.format("Moving forward with EXIF header parsing for '{}'", fileOrBlob.name === undefined ? "blob" : fileOrBlob.name)); isLittleEndian(app1Offset).then(function(littleEndian) { log(qq.format("EXIF Byte order is {} endian", littleEndian ? "little" : "big")); getDirEntryCount(app1Offset, littleEndian).then(function(dirEntryCount) { log(qq.format("Found {} APP1 directory entries", dirEntryCount)); getIfd(app1Offset, dirEntryCount).then(function(ifdHex) { var dirEntries = getDirEntries(ifdHex), tagValues = getTagValues(littleEndian, dirEntries); log("Successfully parsed some EXIF tags"); parser.success(tagValues); }, onParseFailure); }, onParseFailure); }, onParseFailure); }, onParseFailure); return parser; } }); /*<testing>*/ this._testing = {}; this._testing.parseLittleEndian = parseLittleEndian; /*</testing>*/ }; /*globals qq */ qq.Identify = function(fileOrBlob, log) { "use strict"; var PREVIEWABLE_MAGIC_BYTES = { "image/jpeg": "ffd8ff", "image/gif": "474946", "image/png": "89504e", "image/bmp": "424d", "image/tiff": ["49492a00", "4d4d002a"] }; function isIdentifiable(magicBytes, questionableBytes) { var identifiable = false, magicBytesEntries = [].concat(magicBytes); qq.each(magicBytesEntries, function(idx, magicBytesArrayEntry) { if (questionableBytes.indexOf(magicBytesArrayEntry) === 0) { identifiable = true; return false; } }); return identifiable; } qq.extend(this, { isPreviewable: function() { var idenitifer = new qq.Promise(), previewable = false, name = fileOrBlob.name === undefined ? "blob" : fileOrBlob.name; log(qq.format("Attempting to determine if {} can be rendered in this browser", name)); qq.readBlobToHex(fileOrBlob, 0, 4).then(function(hex) { qq.each(PREVIEWABLE_MAGIC_BYTES, function(mime, bytes) { if (isIdentifiable(bytes, hex)) { // Safari is the only supported browser that can deal with TIFFs natively, // so, if this is a TIFF and the UA isn't Safari, declare this file "non-previewable". if (mime !== "image/tiff" || qq.safari()) { previewable = true; idenitifer.success(mime); } return false; } }); log(qq.format("'{}' is {} able to be rendered in this browser", name, previewable ? "" : "NOT")); if (!previewable) { idenitifer.failure(); } }); return idenitifer; } }); }; /*globals qq*/ /** * Attempts to validate an image, wherever possible. * * @param blob File or Blob representing a user-selecting image. * @param log Uses this to post log messages to the console. * @constructor */ qq.ImageValidation = function(blob, log) { "use strict"; /** * @param limits Object with possible image-related limits to enforce. * @returns {boolean} true if at least one of the limits has a non-zero value */ function hasNonZeroLimits(limits) { var atLeastOne = false; qq.each(limits, function(limit, value) { if (value > 0) { atLeastOne = true; return false; } }); return atLeastOne; } /** * @returns {qq.Promise} The promise is a failure if we can't obtain the width & height. * Otherwise, `success` is called on the returned promise with an object containing * `width` and `height` properties. */ function getWidthHeight() { var sizeDetermination = new qq.Promise(); new qq.Identify(blob, log).isPreviewable().then(function() { var image = new Image(), url = window.URL && window.URL.createObjectURL ? window.URL : window.webkitURL && window.webkitURL.createObjectURL ? window.webkitURL : null; if (url) { image.onerror = function() { log("Cannot determine dimensions for image. May be too large.", "error"); sizeDetermination.failure(); }; image.onload = function() { sizeDetermination.success({ width: this.width, height: this.height }); }; image.src = url.createObjectURL(blob); } else { log("No createObjectURL function available to generate image URL!", "error"); sizeDetermination.failure(); } }, sizeDetermination.failure); return sizeDetermination; } /** * * @param limits Object with possible image-related limits to enforce. * @param dimensions Object containing `width` & `height` properties for the image to test. * @returns {String || undefined} The name of the failing limit. Undefined if no failing limits. */ function getFailingLimit(limits, dimensions) { var failingLimit; qq.each(limits, function(limitName, limitValue) { if (limitValue > 0) { var limitMatcher = /(max|min)(Width|Height)/.exec(limitName), dimensionPropName = limitMatcher[2].charAt(0).toLowerCase() + limitMatcher[2].slice(1), actualValue = dimensions[dimensionPropName]; /*jshint -W015*/ switch(limitMatcher[1]) { case "min": if (actualValue < limitValue) { failingLimit = limitName; return false; } break; case "max": if (actualValue > limitValue) { failingLimit = limitName; return false; } break; } } }); return failingLimit; } /** * Validate the associated blob. * * @param limits * @returns {qq.Promise} `success` is called on the promise is the image is valid or * if the blob is not an image, or if the image is not verifiable. * Otherwise, `failure` with the name of the failing limit. */ this.validate = function(limits) { var validationEffort = new qq.Promise(); log("Attempting to validate image."); if (hasNonZeroLimits(limits)) { getWidthHeight().then(function(dimensions) { var failingLimit = getFailingLimit(limits, dimensions); if (failingLimit) { validationEffort.failure(failingLimit); } else { validationEffort.success(); } }, validationEffort.success); } else { validationEffort.success(); } return validationEffort; }; }; /* globals qq */ /** * Module used to control populating the initial list of files. * * @constructor */ qq.Session = function(spec) { "use strict"; var options = { endpoint: null, params: {}, customHeaders: {}, cors: {}, addFileRecord: function(sessionData) {}, log: function(message, level) {} }; qq.extend(options, spec, true); function isJsonResponseValid(response) { if (qq.isArray(response)) { return true; } options.log("Session response is not an array.", "error"); } function handleFileItems(fileItems, success, xhrOrXdr, promise) { var someItemsIgnored = false; success = success && isJsonResponseValid(fileItems); if (success) { qq.each(fileItems, function(idx, fileItem) { /* jshint eqnull:true */ if (fileItem.uuid == null) { someItemsIgnored = true; options.log(qq.format("Session response item {} did not include a valid UUID - ignoring.", idx), "error"); } else if (fileItem.name == null) { someItemsIgnored = true; options.log(qq.format("Session response item {} did not include a valid name - ignoring.", idx), "error"); } else { try { options.addFileRecord(fileItem); return true; } catch(err) { someItemsIgnored = true; options.log(err.message, "error"); } } return false; }); } promise[success && !someItemsIgnored ? "success" : "failure"](fileItems, xhrOrXdr); } // Initiate a call to the server that will be used to populate the initial file list. // Returns a `qq.Promise`. this.refresh = function() { /*jshint indent:false */ var refreshEffort = new qq.Promise(), refreshCompleteCallback = function(response, success, xhrOrXdr) { handleFileItems(response, success, xhrOrXdr, refreshEffort); }, requsterOptions = qq.extend({}, options), requester = new qq.SessionAjaxRequester( qq.extend(requsterOptions, {onComplete: refreshCompleteCallback}) ); requester.queryServer(); return refreshEffort; }; }; /*globals qq, XMLHttpRequest*/ /** * Thin module used to send GET requests to the server, expecting information about session * data used to initialize an uploader instance. * * @param spec Various options used to influence the associated request. * @constructor */ qq.SessionAjaxRequester = function(spec) { "use strict"; var requester, options = { endpoint: null, customHeaders: {}, params: {}, cors: { expected: false, sendCredentials: false }, onComplete: function(response, success, xhrOrXdr) {}, log: function(str, level) {} }; qq.extend(options, spec); function onComplete(id, xhrOrXdr, isError) { var response = null; /* jshint eqnull:true */ if (xhrOrXdr.responseText != null) { try { response = qq.parseJson(xhrOrXdr.responseText); } catch(err) { options.log("Problem parsing session response: " + err.message, "error"); isError = true; } } options.onComplete(response, !isError, xhrOrXdr); } requester = qq.extend(this, new qq.AjaxRequester({ validMethods: ["GET"], method: "GET", endpointStore: { get: function() { return options.endpoint; } }, customHeaders: options.customHeaders, log: options.log, onComplete: onComplete, cors: options.cors })); qq.extend(this, { queryServer: function() { var params = qq.extend({}, options.params); options.log("Session query request."); requester.initTransport("sessionRefresh") .withParams(params) .withCacheBuster() .send(); } }); }; /* globals qq */ /** * Module that handles support for existing forms. * * @param options Options passed from the integrator-supplied options related to form support. * @param startUpload Callback to invoke when files "stored" should be uploaded. * @param log Proxy for the logger * @constructor */ qq.FormSupport = function(options, startUpload, log) { "use strict"; var self = this, interceptSubmit = options.interceptSubmit, formEl = options.element, autoUpload = options.autoUpload; // Available on the public API associated with this module. qq.extend(this, { // To be used by the caller to determine if the endpoint will be determined by some processing // that occurs in this module, such as if the form has an action attribute. // Ignore if `attachToForm === false`. newEndpoint: null, // To be used by the caller to determine if auto uploading should be allowed. // Ignore if `attachToForm === false`. newAutoUpload: autoUpload, // true if a form was detected and is being tracked by this module attachedToForm: false, // Returns an object with names and values for all valid form elements associated with the attached form. getFormInputsAsObject: function() { /* jshint eqnull:true */ if (formEl == null) { return null; } return self._form2Obj(formEl); } }); // If the form contains an action attribute, this should be the new upload endpoint. function determineNewEndpoint(formEl) { if (formEl.getAttribute("action")) { self.newEndpoint = formEl.getAttribute("action"); } } // Return true only if the form is valid, or if we cannot make this determination. // If the form is invalid, ensure invalid field(s) are highlighted in the UI. function validateForm(formEl, nativeSubmit) { if (formEl.checkValidity && !formEl.checkValidity()) { log("Form did not pass validation checks - will not upload.", "error"); nativeSubmit(); } else { return true; } } // Intercept form submit attempts, unless the integrator has told us not to do this. function maybeUploadOnSubmit(formEl) { var nativeSubmit = formEl.submit; // Intercept and squelch submit events. qq(formEl).attach("submit", function(event) { event = event || window.event; if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } validateForm(formEl, nativeSubmit) && startUpload(); }); // The form's `submit()` function may be called instead (i.e. via jQuery.submit()). // Intercept that too. formEl.submit = function() { validateForm(formEl, nativeSubmit) && startUpload(); }; } // If the element value passed from the uploader is a string, assume it is an element ID - select it. // The rest of the code in this module depends on this being an HTMLElement. function determineFormEl(formEl) { if (formEl) { if (qq.isString(formEl)) { formEl = document.getElementById(formEl); } if (formEl) { log("Attaching to form element."); determineNewEndpoint(formEl); interceptSubmit && maybeUploadOnSubmit(formEl); } } return formEl; } formEl = determineFormEl(formEl); this.attachedToForm = !!formEl; }; qq.extend(qq.FormSupport.prototype, { // Converts all relevant form fields to key/value pairs. This is meant to mimic the data a browser will // construct from a given form when the form is submitted. _form2Obj: function(form) { "use strict"; var obj = {}, notIrrelevantType = function(type) { var irrelevantTypes = [ "button", "image", "reset", "submit" ]; return qq.indexOf(irrelevantTypes, type.toLowerCase()) < 0; }, radioOrCheckbox = function(type) { return qq.indexOf(["checkbox", "radio"], type.toLowerCase()) >= 0; }, ignoreValue = function(el) { if (radioOrCheckbox(el.type) && !el.checked) { return true; } return el.disabled && el.type.toLowerCase() !== "hidden"; }, selectValue = function(select) { var value = null; qq.each(qq(select).children(), function(idx, child) { if (child.tagName.toLowerCase() === "option" && child.selected) { value = child.value; return false; } }); return value; }; qq.each(form.elements, function(idx, el) { if (qq.isInput(el, true) && notIrrelevantType(el.type) && !ignoreValue(el)) { obj[el.name] = el.value; } else if (el.tagName.toLowerCase() === "select" && !ignoreValue(el)) { var value = selectValue(el); if (value !== null) { obj[el.name] = value; } } }); return obj; } }); /*globals qq */ // Base handler for UI (FineUploader mode) events. // Some more specific handlers inherit from this one. qq.UiEventHandler = function(s, protectedApi) { "use strict"; var disposer = new qq.DisposeSupport(), spec = { eventType: "click", attachTo: null, onHandled: function(target, event) {} }; // This makes up the "public" API methods that will be accessible // to instances constructing a base or child handler qq.extend(this, { addHandler: function(element) { addHandler(element); }, dispose: function() { disposer.dispose(); } }); function addHandler(element) { disposer.attach(element, spec.eventType, function(event) { // Only in IE: the `event` is a property of the `window`. event = event || window.event; // On older browsers, we must check the `srcElement` instead of the `target`. var target = event.target || event.srcElement; spec.onHandled(target, event); }); } // These make up the "protected" API methods that children of this base handler will utilize. qq.extend(protectedApi, { getFileIdFromItem: function(item) { return item.qqFileId; }, getDisposeSupport: function() { return disposer; } }); qq.extend(spec, s); if (spec.attachTo) { addHandler(spec.attachTo); } }; /* global qq */ qq.FileButtonsClickHandler = function(s) { "use strict"; var inheritedInternalApi = {}, spec = { templating: null, log: function(message, lvl) {}, onDeleteFile: function(fileId) {}, onCancel: function(fileId) {}, onRetry: function(fileId) {}, onPause: function(fileId) {}, onContinue: function(fileId) {}, onGetName: function(fileId) {} }, buttonHandlers = { cancel: function(id) { spec.onCancel(id); }, retry: function(id) { spec.onRetry(id); }, deleteButton: function(id) { spec.onDeleteFile(id); }, pause: function(id) { spec.onPause(id); }, continueButton: function(id) { spec.onContinue(id); } }; function examineEvent(target, event) { qq.each(buttonHandlers, function(buttonType, handler) { var firstLetterCapButtonType = buttonType.charAt(0).toUpperCase() + buttonType.slice(1), fileId; if (spec.templating["is" + firstLetterCapButtonType](target)) { fileId = spec.templating.getFileId(target); qq.preventDefault(event); spec.log(qq.format("Detected valid file button click event on file '{}', ID: {}.", spec.onGetName(fileId), fileId)); handler(fileId); return false; } }); } qq.extend(spec, s); spec.eventType = "click"; spec.onHandled = examineEvent; spec.attachTo = spec.templating.getFileList(); qq.extend(this, new qq.UiEventHandler(spec, inheritedInternalApi)); }; /*globals qq */ // Child of FilenameEditHandler. Used to detect click events on filename display elements. qq.FilenameClickHandler = function(s) { "use strict"; var inheritedInternalApi = {}, spec = { templating: null, log: function(message, lvl) {}, classes: { file: "qq-upload-file", editNameIcon: "qq-edit-filename-icon" }, onGetUploadStatus: function(fileId) {}, onGetName: function(fileId) {} }; qq.extend(spec, s); // This will be called by the parent handler when a `click` event is received on the list element. function examineEvent(target, event) { if (spec.templating.isFileName(target) || spec.templating.isEditIcon(target)) { var fileId = spec.templating.getFileId(target), status = spec.onGetUploadStatus(fileId); // We only allow users to change filenames of files that have been submitted but not yet uploaded. if (status === qq.status.SUBMITTED) { spec.log(qq.format("Detected valid filename click event on file '{}', ID: {}.", spec.onGetName(fileId), fileId)); qq.preventDefault(event); inheritedInternalApi.handleFilenameEdit(fileId, target, true); } } } spec.eventType = "click"; spec.onHandled = examineEvent; qq.extend(this, new qq.FilenameEditHandler(spec, inheritedInternalApi)); }; /*globals qq */ // Child of FilenameEditHandler. Used to detect focusin events on file edit input elements. qq.FilenameInputFocusInHandler = function(s, inheritedInternalApi) { "use strict"; var spec = { templating: null, onGetUploadStatus: function(fileId) {}, log: function(message, lvl) {} }; if (!inheritedInternalApi) { inheritedInternalApi = {}; } // This will be called by the parent handler when a `focusin` event is received on the list element. function handleInputFocus(target, event) { if (spec.templating.isEditInput(target)) { var fileId = spec.templating.getFileId(target), status = spec.onGetUploadStatus(fileId); if (status === qq.status.SUBMITTED) { spec.log(qq.format("Detected valid filename input focus event on file '{}', ID: {}.", spec.onGetName(fileId), fileId)); inheritedInternalApi.handleFilenameEdit(fileId, target); } } } spec.eventType = "focusin"; spec.onHandled = handleInputFocus; qq.extend(spec, s); qq.extend(this, new qq.FilenameEditHandler(spec, inheritedInternalApi)); }; /*globals qq */ /** * Child of FilenameInputFocusInHandler. Used to detect focus events on file edit input elements. This child module is only * needed for UAs that do not support the focusin event. Currently, only Firefox lacks this event. * * @param spec Overrides for default specifications */ qq.FilenameInputFocusHandler = function(spec) { "use strict"; spec.eventType = "focus"; spec.attachTo = null; qq.extend(this, new qq.FilenameInputFocusInHandler(spec, {})); }; /*globals qq */ // Handles edit-related events on a file item (FineUploader mode). This is meant to be a parent handler. // Children will delegate to this handler when specific edit-related actions are detected. qq.FilenameEditHandler = function(s, inheritedInternalApi) { "use strict"; var spec = { templating: null, log: function(message, lvl) {}, onGetUploadStatus: function(fileId) {}, onGetName: function(fileId) {}, onSetName: function(fileId, newName) {}, onEditingStatusChange: function(fileId, isEditing) {} }; function getFilenameSansExtension(fileId) { var filenameSansExt = spec.onGetName(fileId), extIdx = filenameSansExt.lastIndexOf("."); if (extIdx > 0) { filenameSansExt = filenameSansExt.substr(0, extIdx); } return filenameSansExt; } function getOriginalExtension(fileId) { var origName = spec.onGetName(fileId); return qq.getExtension(origName); } // Callback iff the name has been changed function handleNameUpdate(newFilenameInputEl, fileId) { var newName = newFilenameInputEl.value, origExtension; if (newName !== undefined && qq.trimStr(newName).length > 0) { origExtension = getOriginalExtension(fileId); if (origExtension !== undefined) { newName = newName + "." + origExtension; } spec.onSetName(fileId, newName); } spec.onEditingStatusChange(fileId, false); } // The name has been updated if the filename edit input loses focus. function registerInputBlurHandler(inputEl, fileId) { inheritedInternalApi.getDisposeSupport().attach(inputEl, "blur", function() { handleNameUpdate(inputEl, fileId); }); } // The name has been updated if the user presses enter. function registerInputEnterKeyHandler(inputEl, fileId) { inheritedInternalApi.getDisposeSupport().attach(inputEl, "keyup", function(event) { var code = event.keyCode || event.which; if (code === 13) { handleNameUpdate(inputEl, fileId); } }); } qq.extend(spec, s); spec.attachTo = spec.templating.getFileList(); qq.extend(this, new qq.UiEventHandler(spec, inheritedInternalApi)); qq.extend(inheritedInternalApi, { handleFilenameEdit: function(id, target, focusInput) { var newFilenameInputEl = spec.templating.getEditInput(id); spec.onEditingStatusChange(id, true); newFilenameInputEl.value = getFilenameSansExtension(id); if (focusInput) { newFilenameInputEl.focus(); } registerInputBlurHandler(newFilenameInputEl, id); registerInputEnterKeyHandler(newFilenameInputEl, id); } }); }; /*globals jQuery, qq*/ (function($) { "use strict"; var $el, pluginOptions = ["uploaderType", "endpointType"]; function init(options) { var xformedOpts = transformVariables(options || {}), newUploaderInstance = getNewUploaderInstance(xformedOpts); uploader(newUploaderInstance); addCallbacks(xformedOpts, newUploaderInstance); return $el; } function getNewUploaderInstance(params) { var uploaderType = pluginOption("uploaderType"), namespace = pluginOption("endpointType"); // If the integrator has defined a specific type of uploader to load, use that, otherwise assume `qq.FineUploader` if (uploaderType) { // We can determine the correct constructor function to invoke by combining "FineUploader" // with the upper camel cased `uploaderType` value. uploaderType = uploaderType.charAt(0).toUpperCase() + uploaderType.slice(1).toLowerCase(); if (namespace) { return new qq[namespace]["FineUploader" + uploaderType](params); } return new qq["FineUploader" + uploaderType](params); } else { if (namespace) { return new qq[namespace].FineUploader(params); } return new qq.FineUploader(params); } } function dataStore(key, val) { var data = $el.data("fineuploader"); if (val) { if (data === undefined) { data = {}; } data[key] = val; $el.data("fineuploader", data); } else { if (data === undefined) { return null; } return data[key]; } } //the underlying Fine Uploader instance is stored in jQuery's data stored, associated with the element // tied to this instance of the plug-in function uploader(instanceToStore) { return dataStore("uploader", instanceToStore); } function pluginOption(option, optionVal) { return dataStore(option, optionVal); } // Implement all callbacks defined in Fine Uploader as functions that trigger appropriately names events and // return the result of executing the bound handler back to Fine Uploader function addCallbacks(transformedOpts, newUploaderInstance) { var callbacks = transformedOpts.callbacks = {}; $.each(newUploaderInstance._options.callbacks, function(prop, nonJqueryCallback) { var name, callbackEventTarget; name = /^on(\w+)/.exec(prop)[1]; name = name.substring(0, 1).toLowerCase() + name.substring(1); callbackEventTarget = $el; callbacks[prop] = function() { var originalArgs = Array.prototype.slice.call(arguments), transformedArgs = [], nonJqueryCallbackRetVal, jqueryEventCallbackRetVal; $.each(originalArgs, function(idx, arg) { transformedArgs.push(maybeWrapInJquery(arg)); }); nonJqueryCallbackRetVal = nonJqueryCallback.apply(this, originalArgs); try { jqueryEventCallbackRetVal = callbackEventTarget.triggerHandler(name, transformedArgs); } catch (error) { qq.log("Caught error in Fine Uploader jQuery event handler: " + error.message, "error"); } /*jshint -W116*/ if (nonJqueryCallbackRetVal != null) { return nonJqueryCallbackRetVal; } return jqueryEventCallbackRetVal; }; }); newUploaderInstance._options.callbacks = callbacks; } //transform jQuery objects into HTMLElements, and pass along all other option properties function transformVariables(source, dest) { var xformed, arrayVals; if (dest === undefined) { if (source.uploaderType !== "basic") { xformed = { element : $el[0] }; } else { xformed = {}; } } else { xformed = dest; } $.each(source, function(prop, val) { if ($.inArray(prop, pluginOptions) >= 0) { pluginOption(prop, val); } else if (val instanceof $) { xformed[prop] = val[0]; } else if ($.isPlainObject(val)) { xformed[prop] = {}; transformVariables(val, xformed[prop]); } else if ($.isArray(val)) { arrayVals = []; $.each(val, function(idx, arrayVal) { var arrayObjDest = {}; if (arrayVal instanceof $) { $.merge(arrayVals, arrayVal); } else if ($.isPlainObject(arrayVal)) { transformVariables(arrayVal, arrayObjDest); arrayVals.push(arrayObjDest); } else { arrayVals.push(arrayVal); } }); xformed[prop] = arrayVals; } else { xformed[prop] = val; } }); if (dest === undefined) { return xformed; } } function isValidCommand(command) { return $.type(command) === "string" && !command.match(/^_/) && //enforce private methods convention uploader()[command] !== undefined; } // Assuming we have already verified that this is a valid command, call the associated function in the underlying // Fine Uploader instance (passing along the arguments from the caller) and return the result of the call back to the caller function delegateCommand(command) { var xformedArgs = [], origArgs = Array.prototype.slice.call(arguments, 1), retVal; transformVariables(origArgs, xformedArgs); retVal = uploader()[command].apply(uploader(), xformedArgs); return maybeWrapInJquery(retVal); } // If the value is an `HTMLElement` or `HTMLDocument`, wrap it in a `jQuery` object function maybeWrapInJquery(val) { var transformedVal = val; // If the command is returning an `HTMLElement` or `HTMLDocument`, wrap it in a `jQuery` object /*jshint -W116*/ if (val != null && typeof val === "object" && (val.nodeType === 1 || val.nodeType === 9) && val.cloneNode) { transformedVal = $(val); } return transformedVal; } $.fn.fineUploader = function(optionsOrCommand) { var self = this, selfArgs = arguments, retVals = []; this.each(function(index, el) { $el = $(el); if (uploader() && isValidCommand(optionsOrCommand)) { retVals.push(delegateCommand.apply(self, selfArgs)); if (self.length === 1) { return false; } } else if (typeof optionsOrCommand === "object" || !optionsOrCommand) { init.apply(self, selfArgs); } else { $.error("Method " + optionsOrCommand + " does not exist on jQuery.fineUploader"); } }); if (retVals.length === 1) { return retVals[0]; } else if (retVals.length > 1) { return retVals; } return this; }; }(jQuery)); /*globals jQuery, qq*/ (function($) { "use strict"; var rootDataKey = "fineUploaderDnd", $el; function init (options) { if (!options) { options = {}; } options.dropZoneElements = [$el]; var xformedOpts = transformVariables(options); addCallbacks(xformedOpts); dnd(new qq.DragAndDrop(xformedOpts)); return $el; } function dataStore(key, val) { var data = $el.data(rootDataKey); if (val) { if (data === undefined) { data = {}; } data[key] = val; $el.data(rootDataKey, data); } else { if (data === undefined) { return null; } return data[key]; } } function dnd(instanceToStore) { return dataStore("dndInstance", instanceToStore); } function addCallbacks(transformedOpts) { var callbacks = transformedOpts.callbacks = {}, dndInst = new qq.FineUploaderBasic(); $.each(new qq.DragAndDrop.callbacks(), function(prop, func) { var name = prop, $callbackEl; $callbackEl = $el; callbacks[prop] = function() { var args = Array.prototype.slice.call(arguments), jqueryHandlerResult = $callbackEl.triggerHandler(name, args); return jqueryHandlerResult; }; }); } //transform jQuery objects into HTMLElements, and pass along all other option properties function transformVariables(source, dest) { var xformed, arrayVals; if (dest === undefined) { xformed = {}; } else { xformed = dest; } $.each(source, function(prop, val) { if (val instanceof $) { xformed[prop] = val[0]; } else if ($.isPlainObject(val)) { xformed[prop] = {}; transformVariables(val, xformed[prop]); } else if ($.isArray(val)) { arrayVals = []; $.each(val, function(idx, arrayVal) { if (arrayVal instanceof $) { $.merge(arrayVals, arrayVal); } else { arrayVals.push(arrayVal); } }); xformed[prop] = arrayVals; } else { xformed[prop] = val; } }); if (dest === undefined) { return xformed; } } function isValidCommand(command) { return $.type(command) === "string" && command === "dispose" && dnd()[command] !== undefined; } function delegateCommand(command) { var xformedArgs = [], origArgs = Array.prototype.slice.call(arguments, 1); transformVariables(origArgs, xformedArgs); return dnd()[command].apply(dnd(), xformedArgs); } $.fn.fineUploaderDnd = function(optionsOrCommand) { var self = this, selfArgs = arguments, retVals = []; this.each(function(index, el) { $el = $(el); if (dnd() && isValidCommand(optionsOrCommand)) { retVals.push(delegateCommand.apply(self, selfArgs)); if (self.length === 1) { return false; } } else if (typeof optionsOrCommand === "object" || !optionsOrCommand) { init.apply(self, selfArgs); } else { $.error("Method " + optionsOrCommand + " does not exist in Fine Uploader's DnD module."); } }); if (retVals.length === 1) { return retVals[0]; } else if (retVals.length > 1) { return retVals; } return this; }; }(jQuery)); /*! 2014-02-16 */
JavaScript
/* Flot plugin for automatically redrawing plots as the placeholder resizes. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. It works by listening for changes on the placeholder div (through the jQuery resize event plugin) - if the size changes, it will redraw the plot. There are no options. If you need to disable the plugin for some plots, you can just fix the size of their placeholders. */ /* Inline dependency: * jQuery resize event - v1.1 - 3/14/2010 * http://benalman.com/projects/jquery-resize-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ (function($,t,n){function p(){for(var n=r.length-1;n>=0;n--){var o=$(r[n]);if(o[0]==t||o.is(":visible")){var h=o.width(),d=o.height(),v=o.data(a);!v||h===v.w&&d===v.h?i[f]=i[l]:(i[f]=i[c],o.trigger(u,[v.w=h,v.h=d]))}else v=o.data(a),v.w=0,v.h=0}s!==null&&(s=t.requestAnimationFrame(p))}var r=[],i=$.resize=$.extend($.resize,{}),s,o="setTimeout",u="resize",a=u+"-special-event",f="delay",l="pendingDelay",c="activeDelay",h="throttleWindow";i[l]=250,i[c]=20,i[f]=i[l],i[h]=!0,$.event.special[u]={setup:function(){if(!i[h]&&this[o])return!1;var t=$(this);r.push(this),t.data(a,{w:t.width(),h:t.height()}),r.length===1&&(s=n,p())},teardown:function(){if(!i[h]&&this[o])return!1;var t=$(this);for(var n=r.length-1;n>=0;n--)if(r[n]==this){r.splice(n,1);break}t.removeData(a),r.length||(cancelAnimationFrame(s),s=null)},add:function(t){function s(t,i,s){var o=$(this),u=o.data(a);u.w=i!==n?i:o.width(),u.h=s!==n?s:o.height(),r.apply(this,arguments)}if(!i[h]&&this[o])return!1;var r;if($.isFunction(t))return r=t,s;r=t.handler,t.handler=s}},t.requestAnimationFrame||(t.requestAnimationFrame=function(){return t.webkitRequestAnimationFrame||t.mozRequestAnimationFrame||t.oRequestAnimationFrame||t.msRequestAnimationFrame||function(e,n){return t.setTimeout(e,i[f])}}()),t.cancelAnimationFrame||(t.cancelAnimationFrame=function(){return t.webkitCancelRequestAnimationFrame||t.mozCancelRequestAnimationFrame||t.oCancelRequestAnimationFrame||t.msCancelRequestAnimationFrame||clearTimeout}())})(jQuery,this); (function ($) { var options = { }; // no options function init(plot) { function onResize() { var placeholder = plot.getPlaceholder(); // somebody might have hidden us and we can't plot // when we don't have the dimensions if (placeholder.width() == 0 || placeholder.height() == 0) return; plot.resize(); plot.setupGrid(); plot.draw(); } function bindEvents(plot, eventHolder) { plot.getPlaceholder().resize(onResize); } function shutdown(plot, eventHolder) { plot.getPlaceholder().unbind("resize", onResize); } plot.hooks.bindEvents.push(bindEvents); plot.hooks.shutdown.push(shutdown); } $.plot.plugins.push({ init: init, options: options, name: 'resize', version: '1.0' }); })(jQuery);
JavaScript
/* Pretty handling of time axes. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. Set axis.mode to "time" to enable. See the section "Time series data" in API.txt for details. */ (function($) { var options = { xaxis: { timezone: null, // "browser" for local to the client or timezone for timezone-js timeformat: null, // format string to use twelveHourClock: false, // 12 or 24 time in time mode monthNames: null // list of names of months } }; // round to nearby lower multiple of base function floorInBase(n, base) { return base * Math.floor(n / base); } // Returns a string with the date d formatted according to fmt. // A subset of the Open Group's strftime format is supported. function formatDate(d, fmt, monthNames, dayNames) { if (typeof d.strftime == "function") { return d.strftime(fmt); } var leftPad = function(n, pad) { n = "" + n; pad = "" + (pad == null ? "0" : pad); return n.length == 1 ? pad + n : n; }; var r = []; var escape = false; var hours = d.getHours(); var isAM = hours < 12; if (monthNames == null) { monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; } if (dayNames == null) { dayNames = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; } var hours12; if (hours > 12) { hours12 = hours - 12; } else if (hours == 0) { hours12 = 12; } else { hours12 = hours; } for (var i = 0; i < fmt.length; ++i) { var c = fmt.charAt(i); if (escape) { switch (c) { case 'a': c = "" + dayNames[d.getDay()]; break; case 'b': c = "" + monthNames[d.getMonth()]; break; case 'd': c = leftPad(d.getDate()); break; case 'e': c = leftPad(d.getDate(), " "); break; case 'h': // For back-compat with 0.7; remove in 1.0 case 'H': c = leftPad(hours); break; case 'I': c = leftPad(hours12); break; case 'l': c = leftPad(hours12, " "); break; case 'm': c = leftPad(d.getMonth() + 1); break; case 'M': c = leftPad(d.getMinutes()); break; // quarters not in Open Group's strftime specification case 'q': c = "" + (Math.floor(d.getMonth() / 3) + 1); break; case 'S': c = leftPad(d.getSeconds()); break; case 'y': c = leftPad(d.getFullYear() % 100); break; case 'Y': c = "" + d.getFullYear(); break; case 'p': c = (isAM) ? ("" + "am") : ("" + "pm"); break; case 'P': c = (isAM) ? ("" + "AM") : ("" + "PM"); break; case 'w': c = "" + d.getDay(); break; } r.push(c); escape = false; } else { if (c == "%") { escape = true; } else { r.push(c); } } } return r.join(""); } // To have a consistent view of time-based data independent of which time // zone the client happens to be in we need a date-like object independent // of time zones. This is done through a wrapper that only calls the UTC // versions of the accessor methods. function makeUtcWrapper(d) { function addProxyMethod(sourceObj, sourceMethod, targetObj, targetMethod) { sourceObj[sourceMethod] = function() { return targetObj[targetMethod].apply(targetObj, arguments); }; }; var utc = { date: d }; // support strftime, if found if (d.strftime != undefined) { addProxyMethod(utc, "strftime", d, "strftime"); } addProxyMethod(utc, "getTime", d, "getTime"); addProxyMethod(utc, "setTime", d, "setTime"); var props = ["Date", "Day", "FullYear", "Hours", "Milliseconds", "Minutes", "Month", "Seconds"]; for (var p = 0; p < props.length; p++) { addProxyMethod(utc, "get" + props[p], d, "getUTC" + props[p]); addProxyMethod(utc, "set" + props[p], d, "setUTC" + props[p]); } return utc; }; // select time zone strategy. This returns a date-like object tied to the // desired timezone function dateGenerator(ts, opts) { if (opts.timezone == "browser") { return new Date(ts); } else if (!opts.timezone || opts.timezone == "utc") { return makeUtcWrapper(new Date(ts)); } else if (typeof timezoneJS != "undefined" && typeof timezoneJS.Date != "undefined") { var d = new timezoneJS.Date(); // timezone-js is fickle, so be sure to set the time zone before // setting the time. d.setTimezone(opts.timezone); d.setTime(ts); return d; } else { return makeUtcWrapper(new Date(ts)); } } // map of app. size of time units in milliseconds var timeUnitSize = { "second": 1000, "minute": 60 * 1000, "hour": 60 * 60 * 1000, "day": 24 * 60 * 60 * 1000, "month": 30 * 24 * 60 * 60 * 1000, "quarter": 3 * 30 * 24 * 60 * 60 * 1000, "year": 365.2425 * 24 * 60 * 60 * 1000 }; // the allowed tick sizes, after 1 year we use // an integer algorithm var baseSpec = [ [1, "second"], [2, "second"], [5, "second"], [10, "second"], [30, "second"], [1, "minute"], [2, "minute"], [5, "minute"], [10, "minute"], [30, "minute"], [1, "hour"], [2, "hour"], [4, "hour"], [8, "hour"], [12, "hour"], [1, "day"], [2, "day"], [3, "day"], [0.25, "month"], [0.5, "month"], [1, "month"], [2, "month"] ]; // we don't know which variant(s) we'll need yet, but generating both is // cheap var specMonths = baseSpec.concat([[3, "month"], [6, "month"], [1, "year"]]); var specQuarters = baseSpec.concat([[1, "quarter"], [2, "quarter"], [1, "year"]]); function init(plot) { plot.hooks.processOptions.push(function (plot, options) { $.each(plot.getAxes(), function(axisName, axis) { var opts = axis.options; if (opts.mode == "time") { axis.tickGenerator = function(axis) { var ticks = []; var d = dateGenerator(axis.min, opts); var minSize = 0; // make quarter use a possibility if quarters are // mentioned in either of these options var spec = (opts.tickSize && opts.tickSize[1] === "quarter") || (opts.minTickSize && opts.minTickSize[1] === "quarter") ? specQuarters : specMonths; if (opts.minTickSize != null) { if (typeof opts.tickSize == "number") { minSize = opts.tickSize; } else { minSize = opts.minTickSize[0] * timeUnitSize[opts.minTickSize[1]]; } } for (var i = 0; i < spec.length - 1; ++i) { if (axis.delta < (spec[i][0] * timeUnitSize[spec[i][1]] + spec[i + 1][0] * timeUnitSize[spec[i + 1][1]]) / 2 && spec[i][0] * timeUnitSize[spec[i][1]] >= minSize) { break; } } var size = spec[i][0]; var unit = spec[i][1]; // special-case the possibility of several years if (unit == "year") { // if given a minTickSize in years, just use it, // ensuring that it's an integer if (opts.minTickSize != null && opts.minTickSize[1] == "year") { size = Math.floor(opts.minTickSize[0]); } else { var magn = Math.pow(10, Math.floor(Math.log(axis.delta / timeUnitSize.year) / Math.LN10)); var norm = (axis.delta / timeUnitSize.year) / magn; if (norm < 1.5) { size = 1; } else if (norm < 3) { size = 2; } else if (norm < 7.5) { size = 5; } else { size = 10; } size *= magn; } // minimum size for years is 1 if (size < 1) { size = 1; } } axis.tickSize = opts.tickSize || [size, unit]; var tickSize = axis.tickSize[0]; unit = axis.tickSize[1]; var step = tickSize * timeUnitSize[unit]; if (unit == "second") { d.setSeconds(floorInBase(d.getSeconds(), tickSize)); } else if (unit == "minute") { d.setMinutes(floorInBase(d.getMinutes(), tickSize)); } else if (unit == "hour") { d.setHours(floorInBase(d.getHours(), tickSize)); } else if (unit == "month") { d.setMonth(floorInBase(d.getMonth(), tickSize)); } else if (unit == "quarter") { d.setMonth(3 * floorInBase(d.getMonth() / 3, tickSize)); } else if (unit == "year") { d.setFullYear(floorInBase(d.getFullYear(), tickSize)); } // reset smaller components d.setMilliseconds(0); if (step >= timeUnitSize.minute) { d.setSeconds(0); } if (step >= timeUnitSize.hour) { d.setMinutes(0); } if (step >= timeUnitSize.day) { d.setHours(0); } if (step >= timeUnitSize.day * 4) { d.setDate(1); } if (step >= timeUnitSize.month * 2) { d.setMonth(floorInBase(d.getMonth(), 3)); } if (step >= timeUnitSize.quarter * 2) { d.setMonth(floorInBase(d.getMonth(), 6)); } if (step >= timeUnitSize.year) { d.setMonth(0); } var carry = 0; var v = Number.NaN; var prev; do { prev = v; v = d.getTime(); ticks.push(v); if (unit == "month" || unit == "quarter") { if (tickSize < 1) { // a bit complicated - we'll divide the // month/quarter up but we need to take // care of fractions so we don't end up in // the middle of a day d.setDate(1); var start = d.getTime(); d.setMonth(d.getMonth() + (unit == "quarter" ? 3 : 1)); var end = d.getTime(); d.setTime(v + carry * timeUnitSize.hour + (end - start) * tickSize); carry = d.getHours(); d.setHours(0); } else { d.setMonth(d.getMonth() + tickSize * (unit == "quarter" ? 3 : 1)); } } else if (unit == "year") { d.setFullYear(d.getFullYear() + tickSize); } else { d.setTime(v + step); } } while (v < axis.max && v != prev); return ticks; }; axis.tickFormatter = function (v, axis) { var d = dateGenerator(v, axis.options); // first check global format if (opts.timeformat != null) { return formatDate(d, opts.timeformat, opts.monthNames, opts.dayNames); } // possibly use quarters if quarters are mentioned in // any of these places var useQuarters = (axis.options.tickSize && axis.options.tickSize[1] == "quarter") || (axis.options.minTickSize && axis.options.minTickSize[1] == "quarter"); var t = axis.tickSize[0] * timeUnitSize[axis.tickSize[1]]; var span = axis.max - axis.min; var suffix = (opts.twelveHourClock) ? " %p" : ""; var hourCode = (opts.twelveHourClock) ? "%I" : "%H"; var fmt; if (t < timeUnitSize.minute) { fmt = hourCode + ":%M:%S" + suffix; } else if (t < timeUnitSize.day) { if (span < 2 * timeUnitSize.day) { fmt = hourCode + ":%M" + suffix; } else { fmt = "%b %d " + hourCode + ":%M" + suffix; } } else if (t < timeUnitSize.month) { fmt = "%b %d"; } else if ((useQuarters && t < timeUnitSize.quarter) || (!useQuarters && t < timeUnitSize.year)) { if (span < timeUnitSize.year) { fmt = "%b"; } else { fmt = "%b %Y"; } } else if (useQuarters && t < timeUnitSize.year) { if (span < timeUnitSize.year) { fmt = "Q%q"; } else { fmt = "Q%q %Y"; } } else { fmt = "%Y"; } var rt = formatDate(d, fmt, opts.monthNames, opts.dayNames); return rt; }; } }); }); } $.plot.plugins.push({ init: init, options: options, name: 'time', version: '1.0' }); // Time-axis support used to be in Flot core, which exposed the // formatDate function on the plot object. Various plugins depend // on the function, so we need to re-expose it here. $.plot.formatDate = formatDate; })(jQuery);
JavaScript
/* Javascript plotting library for jQuery, version 0.8.2. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. */ // first an inline dependency, jquery.colorhelpers.js, we inline it here // for convenience /* Plugin for jQuery for working with colors. * * Version 1.1. * * Inspiration from jQuery color animation plugin by John Resig. * * Released under the MIT license by Ole Laursen, October 2009. * * Examples: * * $.color.parse("#fff").scale('rgb', 0.25).add('a', -0.5).toString() * var c = $.color.extract($("#mydiv"), 'background-color'); * console.log(c.r, c.g, c.b, c.a); * $.color.make(100, 50, 25, 0.4).toString() // returns "rgba(100,50,25,0.4)" * * Note that .scale() and .add() return the same modified object * instead of making a new one. * * V. 1.1: Fix error handling so e.g. parsing an empty string does * produce a color rather than just crashing. */ (function($){$.color={};$.color.make=function(r,g,b,a){var o={};o.r=r||0;o.g=g||0;o.b=b||0;o.a=a!=null?a:1;o.add=function(c,d){for(var i=0;i<c.length;++i)o[c.charAt(i)]+=d;return o.normalize()};o.scale=function(c,f){for(var i=0;i<c.length;++i)o[c.charAt(i)]*=f;return o.normalize()};o.toString=function(){if(o.a>=1){return"rgb("+[o.r,o.g,o.b].join(",")+")"}else{return"rgba("+[o.r,o.g,o.b,o.a].join(",")+")"}};o.normalize=function(){function clamp(min,value,max){return value<min?min:value>max?max:value}o.r=clamp(0,parseInt(o.r),255);o.g=clamp(0,parseInt(o.g),255);o.b=clamp(0,parseInt(o.b),255);o.a=clamp(0,o.a,1);return o};o.clone=function(){return $.color.make(o.r,o.b,o.g,o.a)};return o.normalize()};$.color.extract=function(elem,css){var c;do{c=elem.css(css).toLowerCase();if(c!=""&&c!="transparent")break;elem=elem.parent()}while(elem.length&&!$.nodeName(elem.get(0),"body"));if(c=="rgba(0, 0, 0, 0)")c="transparent";return $.color.parse(c)};$.color.parse=function(str){var res,m=$.color.make;if(res=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(str))return m(parseInt(res[1],10),parseInt(res[2],10),parseInt(res[3],10));if(res=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))return m(parseInt(res[1],10),parseInt(res[2],10),parseInt(res[3],10),parseFloat(res[4]));if(res=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(str))return m(parseFloat(res[1])*2.55,parseFloat(res[2])*2.55,parseFloat(res[3])*2.55);if(res=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(str))return m(parseFloat(res[1])*2.55,parseFloat(res[2])*2.55,parseFloat(res[3])*2.55,parseFloat(res[4]));if(res=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(str))return m(parseInt(res[1],16),parseInt(res[2],16),parseInt(res[3],16));if(res=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(str))return m(parseInt(res[1]+res[1],16),parseInt(res[2]+res[2],16),parseInt(res[3]+res[3],16));var name=$.trim(str).toLowerCase();if(name=="transparent")return m(255,255,255,0);else{res=lookupColors[name]||[0,0,0];return m(res[0],res[1],res[2])}};var lookupColors={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery); // the actual Flot code (function($) { // Cache the prototype hasOwnProperty for faster access var hasOwnProperty = Object.prototype.hasOwnProperty; /////////////////////////////////////////////////////////////////////////// // The Canvas object is a wrapper around an HTML5 <canvas> tag. // // @constructor // @param {string} cls List of classes to apply to the canvas. // @param {element} container Element onto which to append the canvas. // // Requiring a container is a little iffy, but unfortunately canvas // operations don't work unless the canvas is attached to the DOM. function Canvas(cls, container) { var element = container.children("." + cls)[0]; if (element == null) { element = document.createElement("canvas"); element.className = cls; $(element).css({ direction: "ltr", position: "absolute", left: 0, top: 0 }) .appendTo(container); // If HTML5 Canvas isn't available, fall back to [Ex|Flash]canvas if (!element.getContext) { if (window.G_vmlCanvasManager) { element = window.G_vmlCanvasManager.initElement(element); } else { throw new Error("Canvas is not available. If you're using IE with a fall-back such as Excanvas, then there's either a mistake in your conditional include, or the page has no DOCTYPE and is rendering in Quirks Mode."); } } } this.element = element; var context = this.context = element.getContext("2d"); // Determine the screen's ratio of physical to device-independent // pixels. This is the ratio between the canvas width that the browser // advertises and the number of pixels actually present in that space. // The iPhone 4, for example, has a device-independent width of 320px, // but its screen is actually 640px wide. It therefore has a pixel // ratio of 2, while most normal devices have a ratio of 1. var devicePixelRatio = window.devicePixelRatio || 1, backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; this.pixelRatio = devicePixelRatio / backingStoreRatio; // Size the canvas to match the internal dimensions of its container this.resize(container.width(), container.height()); // Collection of HTML div layers for text overlaid onto the canvas this.textContainer = null; this.text = {}; // Cache of text fragments and metrics, so we can avoid expensively // re-calculating them when the plot is re-rendered in a loop. this._textCache = {}; } // Resizes the canvas to the given dimensions. // // @param {number} width New width of the canvas, in pixels. // @param {number} width New height of the canvas, in pixels. Canvas.prototype.resize = function(width, height) { if (width <= 0 || height <= 0) { throw new Error("Invalid dimensions for plot, width = " + width + ", height = " + height); } var element = this.element, context = this.context, pixelRatio = this.pixelRatio; // Resize the canvas, increasing its density based on the display's // pixel ratio; basically giving it more pixels without increasing the // size of its element, to take advantage of the fact that retina // displays have that many more pixels in the same advertised space. // Resizing should reset the state (excanvas seems to be buggy though) if (this.width != width) { element.width = width * pixelRatio; element.style.width = width + "px"; this.width = width; } if (this.height != height) { element.height = height * pixelRatio; element.style.height = height + "px"; this.height = height; } // Save the context, so we can reset in case we get replotted. The // restore ensure that we're really back at the initial state, and // should be safe even if we haven't saved the initial state yet. context.restore(); context.save(); // Scale the coordinate space to match the display density; so even though we // may have twice as many pixels, we still want lines and other drawing to // appear at the same size; the extra pixels will just make them crisper. context.scale(pixelRatio, pixelRatio); }; // Clears the entire canvas area, not including any overlaid HTML text Canvas.prototype.clear = function() { this.context.clearRect(0, 0, this.width, this.height); }; // Finishes rendering the canvas, including managing the text overlay. Canvas.prototype.render = function() { var cache = this._textCache; // For each text layer, add elements marked as active that haven't // already been rendered, and remove those that are no longer active. for (var layerKey in cache) { if (hasOwnProperty.call(cache, layerKey)) { var layer = this.getTextLayer(layerKey), layerCache = cache[layerKey]; layer.hide(); for (var styleKey in layerCache) { if (hasOwnProperty.call(layerCache, styleKey)) { var styleCache = layerCache[styleKey]; for (var key in styleCache) { if (hasOwnProperty.call(styleCache, key)) { var positions = styleCache[key].positions; for (var i = 0, position; position = positions[i]; i++) { if (position.active) { if (!position.rendered) { layer.append(position.element); position.rendered = true; } } else { positions.splice(i--, 1); if (position.rendered) { position.element.detach(); } } } if (positions.length == 0) { delete styleCache[key]; } } } } } layer.show(); } } }; // Creates (if necessary) and returns the text overlay container. // // @param {string} classes String of space-separated CSS classes used to // uniquely identify the text layer. // @return {object} The jQuery-wrapped text-layer div. Canvas.prototype.getTextLayer = function(classes) { var layer = this.text[classes]; // Create the text layer if it doesn't exist if (layer == null) { // Create the text layer container, if it doesn't exist if (this.textContainer == null) { this.textContainer = $("<div class='flot-text'></div>") .css({ position: "absolute", top: 0, left: 0, bottom: 0, right: 0, 'font-size': "smaller", color: "#545454" }) .insertAfter(this.element); } layer = this.text[classes] = $("<div></div>") .addClass(classes) .css({ position: "absolute", top: 0, left: 0, bottom: 0, right: 0 }) .appendTo(this.textContainer); } return layer; }; // Creates (if necessary) and returns a text info object. // // The object looks like this: // // { // width: Width of the text's wrapper div. // height: Height of the text's wrapper div. // element: The jQuery-wrapped HTML div containing the text. // positions: Array of positions at which this text is drawn. // } // // The positions array contains objects that look like this: // // { // active: Flag indicating whether the text should be visible. // rendered: Flag indicating whether the text is currently visible. // element: The jQuery-wrapped HTML div containing the text. // x: X coordinate at which to draw the text. // y: Y coordinate at which to draw the text. // } // // Each position after the first receives a clone of the original element. // // The idea is that that the width, height, and general 'identity' of the // text is constant no matter where it is placed; the placements are a // secondary property. // // Canvas maintains a cache of recently-used text info objects; getTextInfo // either returns the cached element or creates a new entry. // // @param {string} layer A string of space-separated CSS classes uniquely // identifying the layer containing this text. // @param {string} text Text string to retrieve info for. // @param {(string|object)=} font Either a string of space-separated CSS // classes or a font-spec object, defining the text's font and style. // @param {number=} angle Angle at which to rotate the text, in degrees. // Angle is currently unused, it will be implemented in the future. // @param {number=} width Maximum width of the text before it wraps. // @return {object} a text info object. Canvas.prototype.getTextInfo = function(layer, text, font, angle, width) { var textStyle, layerCache, styleCache, info; // Cast the value to a string, in case we were given a number or such text = "" + text; // If the font is a font-spec object, generate a CSS font definition if (typeof font === "object") { textStyle = font.style + " " + font.variant + " " + font.weight + " " + font.size + "px/" + font.lineHeight + "px " + font.family; } else { textStyle = font; } // Retrieve (or create) the cache for the text's layer and styles layerCache = this._textCache[layer]; if (layerCache == null) { layerCache = this._textCache[layer] = {}; } styleCache = layerCache[textStyle]; if (styleCache == null) { styleCache = layerCache[textStyle] = {}; } info = styleCache[text]; // If we can't find a matching element in our cache, create a new one if (info == null) { var element = $("<div></div>").html(text) .css({ position: "absolute", 'max-width': width, top: -9999 }) .appendTo(this.getTextLayer(layer)); if (typeof font === "object") { element.css({ font: textStyle, color: font.color }); } else if (typeof font === "string") { element.addClass(font); } info = styleCache[text] = { width: element.outerWidth(true), height: element.outerHeight(true), element: element, positions: [] }; element.detach(); } return info; }; // Adds a text string to the canvas text overlay. // // The text isn't drawn immediately; it is marked as rendering, which will // result in its addition to the canvas on the next render pass. // // @param {string} layer A string of space-separated CSS classes uniquely // identifying the layer containing this text. // @param {number} x X coordinate at which to draw the text. // @param {number} y Y coordinate at which to draw the text. // @param {string} text Text string to draw. // @param {(string|object)=} font Either a string of space-separated CSS // classes or a font-spec object, defining the text's font and style. // @param {number=} angle Angle at which to rotate the text, in degrees. // Angle is currently unused, it will be implemented in the future. // @param {number=} width Maximum width of the text before it wraps. // @param {string=} halign Horizontal alignment of the text; either "left", // "center" or "right". // @param {string=} valign Vertical alignment of the text; either "top", // "middle" or "bottom". Canvas.prototype.addText = function(layer, x, y, text, font, angle, width, halign, valign) { var info = this.getTextInfo(layer, text, font, angle, width), positions = info.positions; // Tweak the div's position to match the text's alignment if (halign == "center") { x -= info.width / 2; } else if (halign == "right") { x -= info.width; } if (valign == "middle") { y -= info.height / 2; } else if (valign == "bottom") { y -= info.height; } // Determine whether this text already exists at this position. // If so, mark it for inclusion in the next render pass. for (var i = 0, position; position = positions[i]; i++) { if (position.x == x && position.y == y) { position.active = true; return; } } // If the text doesn't exist at this position, create a new entry // For the very first position we'll re-use the original element, // while for subsequent ones we'll clone it. position = { active: true, rendered: false, element: positions.length ? info.element.clone() : info.element, x: x, y: y }; positions.push(position); // Move the element to its final position within the container position.element.css({ top: Math.round(y), left: Math.round(x), 'text-align': halign // In case the text wraps }); }; // Removes one or more text strings from the canvas text overlay. // // If no parameters are given, all text within the layer is removed. // // Note that the text is not immediately removed; it is simply marked as // inactive, which will result in its removal on the next render pass. // This avoids the performance penalty for 'clear and redraw' behavior, // where we potentially get rid of all text on a layer, but will likely // add back most or all of it later, as when redrawing axes, for example. // // @param {string} layer A string of space-separated CSS classes uniquely // identifying the layer containing this text. // @param {number=} x X coordinate of the text. // @param {number=} y Y coordinate of the text. // @param {string=} text Text string to remove. // @param {(string|object)=} font Either a string of space-separated CSS // classes or a font-spec object, defining the text's font and style. // @param {number=} angle Angle at which the text is rotated, in degrees. // Angle is currently unused, it will be implemented in the future. Canvas.prototype.removeText = function(layer, x, y, text, font, angle) { if (text == null) { var layerCache = this._textCache[layer]; if (layerCache != null) { for (var styleKey in layerCache) { if (hasOwnProperty.call(layerCache, styleKey)) { var styleCache = layerCache[styleKey]; for (var key in styleCache) { if (hasOwnProperty.call(styleCache, key)) { var positions = styleCache[key].positions; for (var i = 0, position; position = positions[i]; i++) { position.active = false; } } } } } } } else { var positions = this.getTextInfo(layer, text, font, angle).positions; for (var i = 0, position; position = positions[i]; i++) { if (position.x == x && position.y == y) { position.active = false; } } } }; /////////////////////////////////////////////////////////////////////////// // The top-level container for the entire plot. function Plot(placeholder, data_, options_, plugins) { // data is on the form: // [ series1, series2 ... ] // where series is either just the data as [ [x1, y1], [x2, y2], ... ] // or { data: [ [x1, y1], [x2, y2], ... ], label: "some label", ... } var series = [], options = { // the color theme used for graphs colors: ["#edc240", "#afd8f8", "#cb4b4b", "#4da74d", "#9440ed"], legend: { show: true, noColumns: 1, // number of colums in legend table labelFormatter: null, // fn: string -> string labelBoxBorderColor: "#ccc", // border color for the little label boxes container: null, // container (as jQuery object) to put legend in, null means default on top of graph position: "ne", // position of default legend container within plot margin: 5, // distance from grid edge to default legend container within plot backgroundColor: null, // null means auto-detect backgroundOpacity: 0.85, // set to 0 to avoid background sorted: null // default to no legend sorting }, xaxis: { show: null, // null = auto-detect, true = always, false = never position: "bottom", // or "top" mode: null, // null or "time" font: null, // null (derived from CSS in placeholder) or object like { size: 11, lineHeight: 13, style: "italic", weight: "bold", family: "sans-serif", variant: "small-caps" } color: null, // base color, labels, ticks tickColor: null, // possibly different color of ticks, e.g. "rgba(0,0,0,0.15)" transform: null, // null or f: number -> number to transform axis inverseTransform: null, // if transform is set, this should be the inverse function min: null, // min. value to show, null means set automatically max: null, // max. value to show, null means set automatically autoscaleMargin: null, // margin in % to add if auto-setting min/max ticks: null, // either [1, 3] or [[1, "a"], 3] or (fn: axis info -> ticks) or app. number of ticks for auto-ticks tickFormatter: null, // fn: number -> string labelWidth: null, // size of tick labels in pixels labelHeight: null, reserveSpace: null, // whether to reserve space even if axis isn't shown tickLength: null, // size in pixels of ticks, or "full" for whole line alignTicksWithAxis: null, // axis number or null for no sync tickDecimals: null, // no. of decimals, null means auto tickSize: null, // number or [number, "unit"] minTickSize: null // number or [number, "unit"] }, yaxis: { autoscaleMargin: 0.02, position: "left" // or "right" }, xaxes: [], yaxes: [], series: { points: { show: false, radius: 3, lineWidth: 2, // in pixels fill: true, fillColor: "#ffffff", symbol: "circle" // or callback }, lines: { // we don't put in show: false so we can see // whether lines were actively disabled lineWidth: 2, // in pixels fill: false, fillColor: null, steps: false // Omit 'zero', so we can later default its value to // match that of the 'fill' option. }, bars: { show: false, lineWidth: 2, // in pixels barWidth: 1, // in units of the x axis fill: true, fillColor: null, align: "left", // "left", "right", or "center" horizontal: false, zero: true }, shadowSize: 3, highlightColor: null }, grid: { show: true, aboveData: false, color: "#545454", // primary color used for outline and labels backgroundColor: null, // null for transparent, else color borderColor: null, // set if different from the grid color tickColor: null, // color for the ticks, e.g. "rgba(0,0,0,0.15)" margin: 0, // distance from the canvas edge to the grid labelMargin: 5, // in pixels axisMargin: 8, // in pixels borderWidth: 2, // in pixels minBorderMargin: null, // in pixels, null means taken from points radius markings: null, // array of ranges or fn: axes -> array of ranges markingsColor: "#f4f4f4", markingsLineWidth: 2, // interactive stuff clickable: false, hoverable: false, autoHighlight: true, // highlight in case mouse is near mouseActiveRadius: 10 // how far the mouse can be away to activate an item }, interaction: { redrawOverlayInterval: 1000/60 // time between updates, -1 means in same flow }, hooks: {} }, surface = null, // the canvas for the plot itself overlay = null, // canvas for interactive stuff on top of plot eventHolder = null, // jQuery object that events should be bound to ctx = null, octx = null, xaxes = [], yaxes = [], plotOffset = { left: 0, right: 0, top: 0, bottom: 0}, plotWidth = 0, plotHeight = 0, hooks = { processOptions: [], processRawData: [], processDatapoints: [], processOffset: [], drawBackground: [], drawSeries: [], draw: [], bindEvents: [], drawOverlay: [], shutdown: [] }, plot = this; // public functions plot.setData = setData; plot.setupGrid = setupGrid; plot.draw = draw; plot.getPlaceholder = function() { return placeholder; }; plot.getCanvas = function() { return surface.element; }; plot.getPlotOffset = function() { return plotOffset; }; plot.width = function () { return plotWidth; }; plot.height = function () { return plotHeight; }; plot.offset = function () { var o = eventHolder.offset(); o.left += plotOffset.left; o.top += plotOffset.top; return o; }; plot.getData = function () { return series; }; plot.getAxes = function () { var res = {}, i; $.each(xaxes.concat(yaxes), function (_, axis) { if (axis) res[axis.direction + (axis.n != 1 ? axis.n : "") + "axis"] = axis; }); return res; }; plot.getXAxes = function () { return xaxes; }; plot.getYAxes = function () { return yaxes; }; plot.c2p = canvasToAxisCoords; plot.p2c = axisToCanvasCoords; plot.getOptions = function () { return options; }; plot.highlight = highlight; plot.unhighlight = unhighlight; plot.triggerRedrawOverlay = triggerRedrawOverlay; plot.pointOffset = function(point) { return { left: parseInt(xaxes[axisNumber(point, "x") - 1].p2c(+point.x) + plotOffset.left, 10), top: parseInt(yaxes[axisNumber(point, "y") - 1].p2c(+point.y) + plotOffset.top, 10) }; }; plot.shutdown = shutdown; plot.destroy = function () { shutdown(); placeholder.removeData("plot").empty(); series = []; options = null; surface = null; overlay = null; eventHolder = null; ctx = null; octx = null; xaxes = []; yaxes = []; hooks = null; highlights = []; plot = null; }; plot.resize = function () { var width = placeholder.width(), height = placeholder.height(); surface.resize(width, height); overlay.resize(width, height); }; // public attributes plot.hooks = hooks; // initialize initPlugins(plot); parseOptions(options_); setupCanvases(); setData(data_); setupGrid(); draw(); bindEvents(); function executeHooks(hook, args) { args = [plot].concat(args); for (var i = 0; i < hook.length; ++i) hook[i].apply(this, args); } function initPlugins() { // References to key classes, allowing plugins to modify them var classes = { Canvas: Canvas }; for (var i = 0; i < plugins.length; ++i) { var p = plugins[i]; p.init(plot, classes); if (p.options) $.extend(true, options, p.options); } } function parseOptions(opts) { $.extend(true, options, opts); // $.extend merges arrays, rather than replacing them. When less // colors are provided than the size of the default palette, we // end up with those colors plus the remaining defaults, which is // not expected behavior; avoid it by replacing them here. if (opts && opts.colors) { options.colors = opts.colors; } if (options.xaxis.color == null) options.xaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString(); if (options.yaxis.color == null) options.yaxis.color = $.color.parse(options.grid.color).scale('a', 0.22).toString(); if (options.xaxis.tickColor == null) // grid.tickColor for back-compatibility options.xaxis.tickColor = options.grid.tickColor || options.xaxis.color; if (options.yaxis.tickColor == null) // grid.tickColor for back-compatibility options.yaxis.tickColor = options.grid.tickColor || options.yaxis.color; if (options.grid.borderColor == null) options.grid.borderColor = options.grid.color; if (options.grid.tickColor == null) options.grid.tickColor = $.color.parse(options.grid.color).scale('a', 0.22).toString(); // Fill in defaults for axis options, including any unspecified // font-spec fields, if a font-spec was provided. // If no x/y axis options were provided, create one of each anyway, // since the rest of the code assumes that they exist. var i, axisOptions, axisCount, fontSize = placeholder.css("font-size"), fontSizeDefault = fontSize ? +fontSize.replace("px", "") : 13, fontDefaults = { style: placeholder.css("font-style"), size: Math.round(0.8 * fontSizeDefault), variant: placeholder.css("font-variant"), weight: placeholder.css("font-weight"), family: placeholder.css("font-family") }; axisCount = options.xaxes.length || 1; for (i = 0; i < axisCount; ++i) { axisOptions = options.xaxes[i]; if (axisOptions && !axisOptions.tickColor) { axisOptions.tickColor = axisOptions.color; } axisOptions = $.extend(true, {}, options.xaxis, axisOptions); options.xaxes[i] = axisOptions; if (axisOptions.font) { axisOptions.font = $.extend({}, fontDefaults, axisOptions.font); if (!axisOptions.font.color) { axisOptions.font.color = axisOptions.color; } if (!axisOptions.font.lineHeight) { axisOptions.font.lineHeight = Math.round(axisOptions.font.size * 1.15); } } } axisCount = options.yaxes.length || 1; for (i = 0; i < axisCount; ++i) { axisOptions = options.yaxes[i]; if (axisOptions && !axisOptions.tickColor) { axisOptions.tickColor = axisOptions.color; } axisOptions = $.extend(true, {}, options.yaxis, axisOptions); options.yaxes[i] = axisOptions; if (axisOptions.font) { axisOptions.font = $.extend({}, fontDefaults, axisOptions.font); if (!axisOptions.font.color) { axisOptions.font.color = axisOptions.color; } if (!axisOptions.font.lineHeight) { axisOptions.font.lineHeight = Math.round(axisOptions.font.size * 1.15); } } } // backwards compatibility, to be removed in future if (options.xaxis.noTicks && options.xaxis.ticks == null) options.xaxis.ticks = options.xaxis.noTicks; if (options.yaxis.noTicks && options.yaxis.ticks == null) options.yaxis.ticks = options.yaxis.noTicks; if (options.x2axis) { options.xaxes[1] = $.extend(true, {}, options.xaxis, options.x2axis); options.xaxes[1].position = "top"; } if (options.y2axis) { options.yaxes[1] = $.extend(true, {}, options.yaxis, options.y2axis); options.yaxes[1].position = "right"; } if (options.grid.coloredAreas) options.grid.markings = options.grid.coloredAreas; if (options.grid.coloredAreasColor) options.grid.markingsColor = options.grid.coloredAreasColor; if (options.lines) $.extend(true, options.series.lines, options.lines); if (options.points) $.extend(true, options.series.points, options.points); if (options.bars) $.extend(true, options.series.bars, options.bars); if (options.shadowSize != null) options.series.shadowSize = options.shadowSize; if (options.highlightColor != null) options.series.highlightColor = options.highlightColor; // save options on axes for future reference for (i = 0; i < options.xaxes.length; ++i) getOrCreateAxis(xaxes, i + 1).options = options.xaxes[i]; for (i = 0; i < options.yaxes.length; ++i) getOrCreateAxis(yaxes, i + 1).options = options.yaxes[i]; // add hooks from options for (var n in hooks) if (options.hooks[n] && options.hooks[n].length) hooks[n] = hooks[n].concat(options.hooks[n]); executeHooks(hooks.processOptions, [options]); } function setData(d) { series = parseData(d); fillInSeriesOptions(); processData(); } function parseData(d) { var res = []; for (var i = 0; i < d.length; ++i) { var s = $.extend(true, {}, options.series); if (d[i].data != null) { s.data = d[i].data; // move the data instead of deep-copy delete d[i].data; $.extend(true, s, d[i]); d[i].data = s.data; } else s.data = d[i]; res.push(s); } return res; } function axisNumber(obj, coord) { var a = obj[coord + "axis"]; if (typeof a == "object") // if we got a real axis, extract number a = a.n; if (typeof a != "number") a = 1; // default to first axis return a; } function allAxes() { // return flat array without annoying null entries return $.grep(xaxes.concat(yaxes), function (a) { return a; }); } function canvasToAxisCoords(pos) { // return an object with x/y corresponding to all used axes var res = {}, i, axis; for (i = 0; i < xaxes.length; ++i) { axis = xaxes[i]; if (axis && axis.used) res["x" + axis.n] = axis.c2p(pos.left); } for (i = 0; i < yaxes.length; ++i) { axis = yaxes[i]; if (axis && axis.used) res["y" + axis.n] = axis.c2p(pos.top); } if (res.x1 !== undefined) res.x = res.x1; if (res.y1 !== undefined) res.y = res.y1; return res; } function axisToCanvasCoords(pos) { // get canvas coords from the first pair of x/y found in pos var res = {}, i, axis, key; for (i = 0; i < xaxes.length; ++i) { axis = xaxes[i]; if (axis && axis.used) { key = "x" + axis.n; if (pos[key] == null && axis.n == 1) key = "x"; if (pos[key] != null) { res.left = axis.p2c(pos[key]); break; } } } for (i = 0; i < yaxes.length; ++i) { axis = yaxes[i]; if (axis && axis.used) { key = "y" + axis.n; if (pos[key] == null && axis.n == 1) key = "y"; if (pos[key] != null) { res.top = axis.p2c(pos[key]); break; } } } return res; } function getOrCreateAxis(axes, number) { if (!axes[number - 1]) axes[number - 1] = { n: number, // save the number for future reference direction: axes == xaxes ? "x" : "y", options: $.extend(true, {}, axes == xaxes ? options.xaxis : options.yaxis) }; return axes[number - 1]; } function fillInSeriesOptions() { var neededColors = series.length, maxIndex = -1, i; // Subtract the number of series that already have fixed colors or // color indexes from the number that we still need to generate. for (i = 0; i < series.length; ++i) { var sc = series[i].color; if (sc != null) { neededColors--; if (typeof sc == "number" && sc > maxIndex) { maxIndex = sc; } } } // If any of the series have fixed color indexes, then we need to // generate at least as many colors as the highest index. if (neededColors <= maxIndex) { neededColors = maxIndex + 1; } // Generate all the colors, using first the option colors and then // variations on those colors once they're exhausted. var c, colors = [], colorPool = options.colors, colorPoolSize = colorPool.length, variation = 0; for (i = 0; i < neededColors; i++) { c = $.color.parse(colorPool[i % colorPoolSize] || "#666"); // Each time we exhaust the colors in the pool we adjust // a scaling factor used to produce more variations on // those colors. The factor alternates negative/positive // to produce lighter/darker colors. // Reset the variation after every few cycles, or else // it will end up producing only white or black colors. if (i % colorPoolSize == 0 && i) { if (variation >= 0) { if (variation < 0.5) { variation = -variation - 0.2; } else variation = 0; } else variation = -variation; } colors[i] = c.scale('rgb', 1 + variation); } // Finalize the series options, filling in their colors var colori = 0, s; for (i = 0; i < series.length; ++i) { s = series[i]; // assign colors if (s.color == null) { s.color = colors[colori].toString(); ++colori; } else if (typeof s.color == "number") s.color = colors[s.color].toString(); // turn on lines automatically in case nothing is set if (s.lines.show == null) { var v, show = true; for (v in s) if (s[v] && s[v].show) { show = false; break; } if (show) s.lines.show = true; } // If nothing was provided for lines.zero, default it to match // lines.fill, since areas by default should extend to zero. if (s.lines.zero == null) { s.lines.zero = !!s.lines.fill; } // setup axes s.xaxis = getOrCreateAxis(xaxes, axisNumber(s, "x")); s.yaxis = getOrCreateAxis(yaxes, axisNumber(s, "y")); } } function processData() { var topSentry = Number.POSITIVE_INFINITY, bottomSentry = Number.NEGATIVE_INFINITY, fakeInfinity = Number.MAX_VALUE, i, j, k, m, length, s, points, ps, x, y, axis, val, f, p, data, format; function updateAxis(axis, min, max) { if (min < axis.datamin && min != -fakeInfinity) axis.datamin = min; if (max > axis.datamax && max != fakeInfinity) axis.datamax = max; } $.each(allAxes(), function (_, axis) { // init axis axis.datamin = topSentry; axis.datamax = bottomSentry; axis.used = false; }); for (i = 0; i < series.length; ++i) { s = series[i]; s.datapoints = { points: [] }; executeHooks(hooks.processRawData, [ s, s.data, s.datapoints ]); } // first pass: clean and copy data for (i = 0; i < series.length; ++i) { s = series[i]; data = s.data; format = s.datapoints.format; if (!format) { format = []; // find out how to copy format.push({ x: true, number: true, required: true }); format.push({ y: true, number: true, required: true }); if (s.bars.show || (s.lines.show && s.lines.fill)) { var autoscale = !!((s.bars.show && s.bars.zero) || (s.lines.show && s.lines.zero)); format.push({ y: true, number: true, required: false, defaultValue: 0, autoscale: autoscale }); if (s.bars.horizontal) { delete format[format.length - 1].y; format[format.length - 1].x = true; } } s.datapoints.format = format; } if (s.datapoints.pointsize != null) continue; // already filled in s.datapoints.pointsize = format.length; ps = s.datapoints.pointsize; points = s.datapoints.points; var insertSteps = s.lines.show && s.lines.steps; s.xaxis.used = s.yaxis.used = true; for (j = k = 0; j < data.length; ++j, k += ps) { p = data[j]; var nullify = p == null; if (!nullify) { for (m = 0; m < ps; ++m) { val = p[m]; f = format[m]; if (f) { if (f.number && val != null) { val = +val; // convert to number if (isNaN(val)) val = null; else if (val == Infinity) val = fakeInfinity; else if (val == -Infinity) val = -fakeInfinity; } if (val == null) { if (f.required) nullify = true; if (f.defaultValue != null) val = f.defaultValue; } } points[k + m] = val; } } if (nullify) { for (m = 0; m < ps; ++m) { val = points[k + m]; if (val != null) { f = format[m]; // extract min/max info if (f.autoscale !== false) { if (f.x) { updateAxis(s.xaxis, val, val); } if (f.y) { updateAxis(s.yaxis, val, val); } } } points[k + m] = null; } } else { // a little bit of line specific stuff that // perhaps shouldn't be here, but lacking // better means... if (insertSteps && k > 0 && points[k - ps] != null && points[k - ps] != points[k] && points[k - ps + 1] != points[k + 1]) { // copy the point to make room for a middle point for (m = 0; m < ps; ++m) points[k + ps + m] = points[k + m]; // middle point has same y points[k + 1] = points[k - ps + 1]; // we've added a point, better reflect that k += ps; } } } } // give the hooks a chance to run for (i = 0; i < series.length; ++i) { s = series[i]; executeHooks(hooks.processDatapoints, [ s, s.datapoints]); } // second pass: find datamax/datamin for auto-scaling for (i = 0; i < series.length; ++i) { s = series[i]; points = s.datapoints.points; ps = s.datapoints.pointsize; format = s.datapoints.format; var xmin = topSentry, ymin = topSentry, xmax = bottomSentry, ymax = bottomSentry; for (j = 0; j < points.length; j += ps) { if (points[j] == null) continue; for (m = 0; m < ps; ++m) { val = points[j + m]; f = format[m]; if (!f || f.autoscale === false || val == fakeInfinity || val == -fakeInfinity) continue; if (f.x) { if (val < xmin) xmin = val; if (val > xmax) xmax = val; } if (f.y) { if (val < ymin) ymin = val; if (val > ymax) ymax = val; } } } if (s.bars.show) { // make sure we got room for the bar on the dancing floor var delta; switch (s.bars.align) { case "left": delta = 0; break; case "right": delta = -s.bars.barWidth; break; default: delta = -s.bars.barWidth / 2; } if (s.bars.horizontal) { ymin += delta; ymax += delta + s.bars.barWidth; } else { xmin += delta; xmax += delta + s.bars.barWidth; } } updateAxis(s.xaxis, xmin, xmax); updateAxis(s.yaxis, ymin, ymax); } $.each(allAxes(), function (_, axis) { if (axis.datamin == topSentry) axis.datamin = null; if (axis.datamax == bottomSentry) axis.datamax = null; }); } function setupCanvases() { // Make sure the placeholder is clear of everything except canvases // from a previous plot in this container that we'll try to re-use. placeholder.css("padding", 0) // padding messes up the positioning .children().filter(function(){ return !$(this).hasClass("flot-overlay") && !$(this).hasClass('flot-base'); }).remove(); if (placeholder.css("position") == 'static') placeholder.css("position", "relative"); // for positioning labels and overlay surface = new Canvas("flot-base", placeholder); overlay = new Canvas("flot-overlay", placeholder); // overlay canvas for interactive features ctx = surface.context; octx = overlay.context; // define which element we're listening for events on eventHolder = $(overlay.element).unbind(); // If we're re-using a plot object, shut down the old one var existing = placeholder.data("plot"); if (existing) { existing.shutdown(); overlay.clear(); } // save in case we get replotted placeholder.data("plot", plot); } function bindEvents() { // bind events if (options.grid.hoverable) { eventHolder.mousemove(onMouseMove); // Use bind, rather than .mouseleave, because we officially // still support jQuery 1.2.6, which doesn't define a shortcut // for mouseenter or mouseleave. This was a bug/oversight that // was fixed somewhere around 1.3.x. We can return to using // .mouseleave when we drop support for 1.2.6. eventHolder.bind("mouseleave", onMouseLeave); } if (options.grid.clickable) eventHolder.click(onClick); executeHooks(hooks.bindEvents, [eventHolder]); } function shutdown() { if (redrawTimeout) clearTimeout(redrawTimeout); eventHolder.unbind("mousemove", onMouseMove); eventHolder.unbind("mouseleave", onMouseLeave); eventHolder.unbind("click", onClick); executeHooks(hooks.shutdown, [eventHolder]); } function setTransformationHelpers(axis) { // set helper functions on the axis, assumes plot area // has been computed already function identity(x) { return x; } var s, m, t = axis.options.transform || identity, it = axis.options.inverseTransform; // precompute how much the axis is scaling a point // in canvas space if (axis.direction == "x") { s = axis.scale = plotWidth / Math.abs(t(axis.max) - t(axis.min)); m = Math.min(t(axis.max), t(axis.min)); } else { s = axis.scale = plotHeight / Math.abs(t(axis.max) - t(axis.min)); s = -s; m = Math.max(t(axis.max), t(axis.min)); } // data point to canvas coordinate if (t == identity) // slight optimization axis.p2c = function (p) { return (p - m) * s; }; else axis.p2c = function (p) { return (t(p) - m) * s; }; // canvas coordinate to data point if (!it) axis.c2p = function (c) { return m + c / s; }; else axis.c2p = function (c) { return it(m + c / s); }; } function measureTickLabels(axis) { var opts = axis.options, ticks = axis.ticks || [], labelWidth = opts.labelWidth || 0, labelHeight = opts.labelHeight || 0, maxWidth = labelWidth || (axis.direction == "x" ? Math.floor(surface.width / (ticks.length || 1)) : null), legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis", layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles, font = opts.font || "flot-tick-label tickLabel"; for (var i = 0; i < ticks.length; ++i) { var t = ticks[i]; if (!t.label) continue; var info = surface.getTextInfo(layer, t.label, font, null, maxWidth); labelWidth = Math.max(labelWidth, info.width); labelHeight = Math.max(labelHeight, info.height); } axis.labelWidth = opts.labelWidth || labelWidth; axis.labelHeight = opts.labelHeight || labelHeight; } function allocateAxisBoxFirstPhase(axis) { // find the bounding box of the axis by looking at label // widths/heights and ticks, make room by diminishing the // plotOffset; this first phase only looks at one // dimension per axis, the other dimension depends on the // other axes so will have to wait var lw = axis.labelWidth, lh = axis.labelHeight, pos = axis.options.position, isXAxis = axis.direction === "x", tickLength = axis.options.tickLength, axisMargin = options.grid.axisMargin, padding = options.grid.labelMargin, innermost = true, outermost = true, first = true, found = false; // Determine the axis's position in its direction and on its side $.each(isXAxis ? xaxes : yaxes, function(i, a) { if (a && a.reserveSpace) { if (a === axis) { found = true; } else if (a.options.position === pos) { if (found) { outermost = false; } else { innermost = false; } } if (!found) { first = false; } } }); // The outermost axis on each side has no margin if (outermost) { axisMargin = 0; } // The ticks for the first axis in each direction stretch across if (tickLength == null) { tickLength = first ? "full" : 5; } if (!isNaN(+tickLength)) padding += +tickLength; if (isXAxis) { lh += padding; if (pos == "bottom") { plotOffset.bottom += lh + axisMargin; axis.box = { top: surface.height - plotOffset.bottom, height: lh }; } else { axis.box = { top: plotOffset.top + axisMargin, height: lh }; plotOffset.top += lh + axisMargin; } } else { lw += padding; if (pos == "left") { axis.box = { left: plotOffset.left + axisMargin, width: lw }; plotOffset.left += lw + axisMargin; } else { plotOffset.right += lw + axisMargin; axis.box = { left: surface.width - plotOffset.right, width: lw }; } } // save for future reference axis.position = pos; axis.tickLength = tickLength; axis.box.padding = padding; axis.innermost = innermost; } function allocateAxisBoxSecondPhase(axis) { // now that all axis boxes have been placed in one // dimension, we can set the remaining dimension coordinates if (axis.direction == "x") { axis.box.left = plotOffset.left - axis.labelWidth / 2; axis.box.width = surface.width - plotOffset.left - plotOffset.right + axis.labelWidth; } else { axis.box.top = plotOffset.top - axis.labelHeight / 2; axis.box.height = surface.height - plotOffset.bottom - plotOffset.top + axis.labelHeight; } } function adjustLayoutForThingsStickingOut() { // possibly adjust plot offset to ensure everything stays // inside the canvas and isn't clipped off var minMargin = options.grid.minBorderMargin, axis, i; // check stuff from the plot (FIXME: this should just read // a value from the series, otherwise it's impossible to // customize) if (minMargin == null) { minMargin = 0; for (i = 0; i < series.length; ++i) minMargin = Math.max(minMargin, 2 * (series[i].points.radius + series[i].points.lineWidth/2)); } var margins = { left: minMargin, right: minMargin, top: minMargin, bottom: minMargin }; // check axis labels, note we don't check the actual // labels but instead use the overall width/height to not // jump as much around with replots $.each(allAxes(), function (_, axis) { if (axis.reserveSpace && axis.ticks && axis.ticks.length) { var lastTick = axis.ticks[axis.ticks.length - 1]; if (axis.direction === "x") { margins.left = Math.max(margins.left, axis.labelWidth / 2); if (lastTick.v <= axis.max) { margins.right = Math.max(margins.right, axis.labelWidth / 2); } } else { margins.bottom = Math.max(margins.bottom, axis.labelHeight / 2); if (lastTick.v <= axis.max) { margins.top = Math.max(margins.top, axis.labelHeight / 2); } } } }); plotOffset.left = Math.ceil(Math.max(margins.left, plotOffset.left)); plotOffset.right = Math.ceil(Math.max(margins.right, plotOffset.right)); plotOffset.top = Math.ceil(Math.max(margins.top, plotOffset.top)); plotOffset.bottom = Math.ceil(Math.max(margins.bottom, plotOffset.bottom)); } function setupGrid() { var i, axes = allAxes(), showGrid = options.grid.show; // Initialize the plot's offset from the edge of the canvas for (var a in plotOffset) { var margin = options.grid.margin || 0; plotOffset[a] = typeof margin == "number" ? margin : margin[a] || 0; } executeHooks(hooks.processOffset, [plotOffset]); // If the grid is visible, add its border width to the offset for (var a in plotOffset) { if(typeof(options.grid.borderWidth) == "object") { plotOffset[a] += showGrid ? options.grid.borderWidth[a] : 0; } else { plotOffset[a] += showGrid ? options.grid.borderWidth : 0; } } // init axes $.each(axes, function (_, axis) { axis.show = axis.options.show; if (axis.show == null) axis.show = axis.used; // by default an axis is visible if it's got data axis.reserveSpace = axis.show || axis.options.reserveSpace; setRange(axis); }); if (showGrid) { var allocatedAxes = $.grep(axes, function (axis) { return axis.reserveSpace; }); $.each(allocatedAxes, function (_, axis) { // make the ticks setupTickGeneration(axis); setTicks(axis); snapRangeToTicks(axis, axis.ticks); // find labelWidth/Height for axis measureTickLabels(axis); }); // with all dimensions calculated, we can compute the // axis bounding boxes, start from the outside // (reverse order) for (i = allocatedAxes.length - 1; i >= 0; --i) allocateAxisBoxFirstPhase(allocatedAxes[i]); // make sure we've got enough space for things that // might stick out adjustLayoutForThingsStickingOut(); $.each(allocatedAxes, function (_, axis) { allocateAxisBoxSecondPhase(axis); }); } plotWidth = surface.width - plotOffset.left - plotOffset.right; plotHeight = surface.height - plotOffset.bottom - plotOffset.top; // now we got the proper plot dimensions, we can compute the scaling $.each(axes, function (_, axis) { setTransformationHelpers(axis); }); if (showGrid) { drawAxisLabels(); } insertLegend(); } function setRange(axis) { var opts = axis.options, min = +(opts.min != null ? opts.min : axis.datamin), max = +(opts.max != null ? opts.max : axis.datamax), delta = max - min; if (delta == 0.0) { // degenerate case var widen = max == 0 ? 1 : 0.01; if (opts.min == null) min -= widen; // always widen max if we couldn't widen min to ensure we // don't fall into min == max which doesn't work if (opts.max == null || opts.min != null) max += widen; } else { // consider autoscaling var margin = opts.autoscaleMargin; if (margin != null) { if (opts.min == null) { min -= delta * margin; // make sure we don't go below zero if all values // are positive if (min < 0 && axis.datamin != null && axis.datamin >= 0) min = 0; } if (opts.max == null) { max += delta * margin; if (max > 0 && axis.datamax != null && axis.datamax <= 0) max = 0; } } } axis.min = min; axis.max = max; } function setupTickGeneration(axis) { var opts = axis.options; // estimate number of ticks var noTicks; if (typeof opts.ticks == "number" && opts.ticks > 0) noTicks = opts.ticks; else // heuristic based on the model a*sqrt(x) fitted to // some data points that seemed reasonable noTicks = 0.3 * Math.sqrt(axis.direction == "x" ? surface.width : surface.height); var delta = (axis.max - axis.min) / noTicks, dec = -Math.floor(Math.log(delta) / Math.LN10), maxDec = opts.tickDecimals; if (maxDec != null && dec > maxDec) { dec = maxDec; } var magn = Math.pow(10, -dec), norm = delta / magn, // norm is between 1.0 and 10.0 size; if (norm < 1.5) { size = 1; } else if (norm < 3) { size = 2; // special case for 2.5, requires an extra decimal if (norm > 2.25 && (maxDec == null || dec + 1 <= maxDec)) { size = 2.5; ++dec; } } else if (norm < 7.5) { size = 5; } else { size = 10; } size *= magn; if (opts.minTickSize != null && size < opts.minTickSize) { size = opts.minTickSize; } axis.delta = delta; axis.tickDecimals = Math.max(0, maxDec != null ? maxDec : dec); axis.tickSize = opts.tickSize || size; // Time mode was moved to a plug-in in 0.8, but since so many people use this // we'll add an especially friendly make sure they remembered to include it. if (opts.mode == "time" && !axis.tickGenerator) { throw new Error("Time mode requires the flot.time plugin."); } // Flot supports base-10 axes; any other mode else is handled by a plug-in, // like flot.time.js. if (!axis.tickGenerator) { axis.tickGenerator = function (axis) { var ticks = [], start = floorInBase(axis.min, axis.tickSize), i = 0, v = Number.NaN, prev; do { prev = v; v = start + i * axis.tickSize; ticks.push(v); ++i; } while (v < axis.max && v != prev); return ticks; }; axis.tickFormatter = function (value, axis) { var factor = axis.tickDecimals ? Math.pow(10, axis.tickDecimals) : 1; var formatted = "" + Math.round(value * factor) / factor; // If tickDecimals was specified, ensure that we have exactly that // much precision; otherwise default to the value's own precision. if (axis.tickDecimals != null) { var decimal = formatted.indexOf("."); var precision = decimal == -1 ? 0 : formatted.length - decimal - 1; if (precision < axis.tickDecimals) { return (precision ? formatted : formatted + ".") + ("" + factor).substr(1, axis.tickDecimals - precision); } } return formatted; }; } if ($.isFunction(opts.tickFormatter)) axis.tickFormatter = function (v, axis) { return "" + opts.tickFormatter(v, axis); }; if (opts.alignTicksWithAxis != null) { var otherAxis = (axis.direction == "x" ? xaxes : yaxes)[opts.alignTicksWithAxis - 1]; if (otherAxis && otherAxis.used && otherAxis != axis) { // consider snapping min/max to outermost nice ticks var niceTicks = axis.tickGenerator(axis); if (niceTicks.length > 0) { if (opts.min == null) axis.min = Math.min(axis.min, niceTicks[0]); if (opts.max == null && niceTicks.length > 1) axis.max = Math.max(axis.max, niceTicks[niceTicks.length - 1]); } axis.tickGenerator = function (axis) { // copy ticks, scaled to this axis var ticks = [], v, i; for (i = 0; i < otherAxis.ticks.length; ++i) { v = (otherAxis.ticks[i].v - otherAxis.min) / (otherAxis.max - otherAxis.min); v = axis.min + v * (axis.max - axis.min); ticks.push(v); } return ticks; }; // we might need an extra decimal since forced // ticks don't necessarily fit naturally if (!axis.mode && opts.tickDecimals == null) { var extraDec = Math.max(0, -Math.floor(Math.log(axis.delta) / Math.LN10) + 1), ts = axis.tickGenerator(axis); // only proceed if the tick interval rounded // with an extra decimal doesn't give us a // zero at end if (!(ts.length > 1 && /\..*0$/.test((ts[1] - ts[0]).toFixed(extraDec)))) axis.tickDecimals = extraDec; } } } } function setTicks(axis) { var oticks = axis.options.ticks, ticks = []; if (oticks == null || (typeof oticks == "number" && oticks > 0)) ticks = axis.tickGenerator(axis); else if (oticks) { if ($.isFunction(oticks)) // generate the ticks ticks = oticks(axis); else ticks = oticks; } // clean up/labelify the supplied ticks, copy them over var i, v; axis.ticks = []; for (i = 0; i < ticks.length; ++i) { var label = null; var t = ticks[i]; if (typeof t == "object") { v = +t[0]; if (t.length > 1) label = t[1]; } else v = +t; if (label == null) label = axis.tickFormatter(v, axis); if (!isNaN(v)) axis.ticks.push({ v: v, label: label }); } } function snapRangeToTicks(axis, ticks) { if (axis.options.autoscaleMargin && ticks.length > 0) { // snap to ticks if (axis.options.min == null) axis.min = Math.min(axis.min, ticks[0].v); if (axis.options.max == null && ticks.length > 1) axis.max = Math.max(axis.max, ticks[ticks.length - 1].v); } } function draw() { surface.clear(); executeHooks(hooks.drawBackground, [ctx]); var grid = options.grid; // draw background, if any if (grid.show && grid.backgroundColor) drawBackground(); if (grid.show && !grid.aboveData) { drawGrid(); } for (var i = 0; i < series.length; ++i) { executeHooks(hooks.drawSeries, [ctx, series[i]]); drawSeries(series[i]); } executeHooks(hooks.draw, [ctx]); if (grid.show && grid.aboveData) { drawGrid(); } surface.render(); // A draw implies that either the axes or data have changed, so we // should probably update the overlay highlights as well. triggerRedrawOverlay(); } function extractRange(ranges, coord) { var axis, from, to, key, axes = allAxes(); for (var i = 0; i < axes.length; ++i) { axis = axes[i]; if (axis.direction == coord) { key = coord + axis.n + "axis"; if (!ranges[key] && axis.n == 1) key = coord + "axis"; // support x1axis as xaxis if (ranges[key]) { from = ranges[key].from; to = ranges[key].to; break; } } } // backwards-compat stuff - to be removed in future if (!ranges[key]) { axis = coord == "x" ? xaxes[0] : yaxes[0]; from = ranges[coord + "1"]; to = ranges[coord + "2"]; } // auto-reverse as an added bonus if (from != null && to != null && from > to) { var tmp = from; from = to; to = tmp; } return { from: from, to: to, axis: axis }; } function drawBackground() { ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); ctx.fillStyle = getColorOrGradient(options.grid.backgroundColor, plotHeight, 0, "rgba(255, 255, 255, 0)"); ctx.fillRect(0, 0, plotWidth, plotHeight); ctx.restore(); } function drawGrid() { var i, axes, bw, bc; ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); // draw markings var markings = options.grid.markings; if (markings) { if ($.isFunction(markings)) { axes = plot.getAxes(); // xmin etc. is backwards compatibility, to be // removed in the future axes.xmin = axes.xaxis.min; axes.xmax = axes.xaxis.max; axes.ymin = axes.yaxis.min; axes.ymax = axes.yaxis.max; markings = markings(axes); } for (i = 0; i < markings.length; ++i) { var m = markings[i], xrange = extractRange(m, "x"), yrange = extractRange(m, "y"); // fill in missing if (xrange.from == null) xrange.from = xrange.axis.min; if (xrange.to == null) xrange.to = xrange.axis.max; if (yrange.from == null) yrange.from = yrange.axis.min; if (yrange.to == null) yrange.to = yrange.axis.max; // clip if (xrange.to < xrange.axis.min || xrange.from > xrange.axis.max || yrange.to < yrange.axis.min || yrange.from > yrange.axis.max) continue; xrange.from = Math.max(xrange.from, xrange.axis.min); xrange.to = Math.min(xrange.to, xrange.axis.max); yrange.from = Math.max(yrange.from, yrange.axis.min); yrange.to = Math.min(yrange.to, yrange.axis.max); if (xrange.from == xrange.to && yrange.from == yrange.to) continue; // then draw xrange.from = xrange.axis.p2c(xrange.from); xrange.to = xrange.axis.p2c(xrange.to); yrange.from = yrange.axis.p2c(yrange.from); yrange.to = yrange.axis.p2c(yrange.to); if (xrange.from == xrange.to || yrange.from == yrange.to) { // draw line ctx.beginPath(); ctx.strokeStyle = m.color || options.grid.markingsColor; ctx.lineWidth = m.lineWidth || options.grid.markingsLineWidth; ctx.moveTo(xrange.from, yrange.from); ctx.lineTo(xrange.to, yrange.to); ctx.stroke(); } else { // fill area ctx.fillStyle = m.color || options.grid.markingsColor; ctx.fillRect(xrange.from, yrange.to, xrange.to - xrange.from, yrange.from - yrange.to); } } } // draw the ticks axes = allAxes(); bw = options.grid.borderWidth; for (var j = 0; j < axes.length; ++j) { var axis = axes[j], box = axis.box, t = axis.tickLength, x, y, xoff, yoff; if (!axis.show || axis.ticks.length == 0) continue; ctx.lineWidth = 1; // find the edges if (axis.direction == "x") { x = 0; if (t == "full") y = (axis.position == "top" ? 0 : plotHeight); else y = box.top - plotOffset.top + (axis.position == "top" ? box.height : 0); } else { y = 0; if (t == "full") x = (axis.position == "left" ? 0 : plotWidth); else x = box.left - plotOffset.left + (axis.position == "left" ? box.width : 0); } // draw tick bar if (!axis.innermost) { ctx.strokeStyle = axis.options.color; ctx.beginPath(); xoff = yoff = 0; if (axis.direction == "x") xoff = plotWidth + 1; else yoff = plotHeight + 1; if (ctx.lineWidth == 1) { if (axis.direction == "x") { y = Math.floor(y) + 0.5; } else { x = Math.floor(x) + 0.5; } } ctx.moveTo(x, y); ctx.lineTo(x + xoff, y + yoff); ctx.stroke(); } // draw ticks ctx.strokeStyle = axis.options.tickColor; ctx.beginPath(); for (i = 0; i < axis.ticks.length; ++i) { var v = axis.ticks[i].v; xoff = yoff = 0; if (isNaN(v) || v < axis.min || v > axis.max // skip those lying on the axes if we got a border || (t == "full" && ((typeof bw == "object" && bw[axis.position] > 0) || bw > 0) && (v == axis.min || v == axis.max))) continue; if (axis.direction == "x") { x = axis.p2c(v); yoff = t == "full" ? -plotHeight : t; if (axis.position == "top") yoff = -yoff; } else { y = axis.p2c(v); xoff = t == "full" ? -plotWidth : t; if (axis.position == "left") xoff = -xoff; } if (ctx.lineWidth == 1) { if (axis.direction == "x") x = Math.floor(x) + 0.5; else y = Math.floor(y) + 0.5; } ctx.moveTo(x, y); ctx.lineTo(x + xoff, y + yoff); } ctx.stroke(); } // draw border if (bw) { // If either borderWidth or borderColor is an object, then draw the border // line by line instead of as one rectangle bc = options.grid.borderColor; if(typeof bw == "object" || typeof bc == "object") { if (typeof bw !== "object") { bw = {top: bw, right: bw, bottom: bw, left: bw}; } if (typeof bc !== "object") { bc = {top: bc, right: bc, bottom: bc, left: bc}; } if (bw.top > 0) { ctx.strokeStyle = bc.top; ctx.lineWidth = bw.top; ctx.beginPath(); ctx.moveTo(0 - bw.left, 0 - bw.top/2); ctx.lineTo(plotWidth, 0 - bw.top/2); ctx.stroke(); } if (bw.right > 0) { ctx.strokeStyle = bc.right; ctx.lineWidth = bw.right; ctx.beginPath(); ctx.moveTo(plotWidth + bw.right / 2, 0 - bw.top); ctx.lineTo(plotWidth + bw.right / 2, plotHeight); ctx.stroke(); } if (bw.bottom > 0) { ctx.strokeStyle = bc.bottom; ctx.lineWidth = bw.bottom; ctx.beginPath(); ctx.moveTo(plotWidth + bw.right, plotHeight + bw.bottom / 2); ctx.lineTo(0, plotHeight + bw.bottom / 2); ctx.stroke(); } if (bw.left > 0) { ctx.strokeStyle = bc.left; ctx.lineWidth = bw.left; ctx.beginPath(); ctx.moveTo(0 - bw.left/2, plotHeight + bw.bottom); ctx.lineTo(0- bw.left/2, 0); ctx.stroke(); } } else { ctx.lineWidth = bw; ctx.strokeStyle = options.grid.borderColor; ctx.strokeRect(-bw/2, -bw/2, plotWidth + bw, plotHeight + bw); } } ctx.restore(); } function drawAxisLabels() { $.each(allAxes(), function (_, axis) { var box = axis.box, legacyStyles = axis.direction + "Axis " + axis.direction + axis.n + "Axis", layer = "flot-" + axis.direction + "-axis flot-" + axis.direction + axis.n + "-axis " + legacyStyles, font = axis.options.font || "flot-tick-label tickLabel", tick, x, y, halign, valign; // Remove text before checking for axis.show and ticks.length; // otherwise plugins, like flot-tickrotor, that draw their own // tick labels will end up with both theirs and the defaults. surface.removeText(layer); if (!axis.show || axis.ticks.length == 0) return; for (var i = 0; i < axis.ticks.length; ++i) { tick = axis.ticks[i]; if (!tick.label || tick.v < axis.min || tick.v > axis.max) continue; if (axis.direction == "x") { halign = "center"; x = plotOffset.left + axis.p2c(tick.v); if (axis.position == "bottom") { y = box.top + box.padding; } else { y = box.top + box.height - box.padding; valign = "bottom"; } } else { valign = "middle"; y = plotOffset.top + axis.p2c(tick.v); if (axis.position == "left") { x = box.left + box.width - box.padding; halign = "right"; } else { x = box.left + box.padding; } } surface.addText(layer, x, y, tick.label, font, null, null, halign, valign); } }); } function drawSeries(series) { if (series.lines.show) drawSeriesLines(series); if (series.bars.show) drawSeriesBars(series); if (series.points.show) drawSeriesPoints(series); } function drawSeriesLines(series) { function plotLine(datapoints, xoffset, yoffset, axisx, axisy) { var points = datapoints.points, ps = datapoints.pointsize, prevx = null, prevy = null; ctx.beginPath(); for (var i = ps; i < points.length; i += ps) { var x1 = points[i - ps], y1 = points[i - ps + 1], x2 = points[i], y2 = points[i + 1]; if (x1 == null || x2 == null) continue; // clip with ymin if (y1 <= y2 && y1 < axisy.min) { if (y2 < axisy.min) continue; // line segment is outside // compute new intersection point x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.min; } else if (y2 <= y1 && y2 < axisy.min) { if (y1 < axisy.min) continue; x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.min; } // clip with ymax if (y1 >= y2 && y1 > axisy.max) { if (y2 > axisy.max) continue; x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.max; } else if (y2 >= y1 && y2 > axisy.max) { if (y1 > axisy.max) continue; x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.max; } // clip with xmin if (x1 <= x2 && x1 < axisx.min) { if (x2 < axisx.min) continue; y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.min; } else if (x2 <= x1 && x2 < axisx.min) { if (x1 < axisx.min) continue; y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.min; } // clip with xmax if (x1 >= x2 && x1 > axisx.max) { if (x2 > axisx.max) continue; y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.max; } else if (x2 >= x1 && x2 > axisx.max) { if (x1 > axisx.max) continue; y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.max; } if (x1 != prevx || y1 != prevy) ctx.moveTo(axisx.p2c(x1) + xoffset, axisy.p2c(y1) + yoffset); prevx = x2; prevy = y2; ctx.lineTo(axisx.p2c(x2) + xoffset, axisy.p2c(y2) + yoffset); } ctx.stroke(); } function plotLineArea(datapoints, axisx, axisy) { var points = datapoints.points, ps = datapoints.pointsize, bottom = Math.min(Math.max(0, axisy.min), axisy.max), i = 0, top, areaOpen = false, ypos = 1, segmentStart = 0, segmentEnd = 0; // we process each segment in two turns, first forward // direction to sketch out top, then once we hit the // end we go backwards to sketch the bottom while (true) { if (ps > 0 && i > points.length + ps) break; i += ps; // ps is negative if going backwards var x1 = points[i - ps], y1 = points[i - ps + ypos], x2 = points[i], y2 = points[i + ypos]; if (areaOpen) { if (ps > 0 && x1 != null && x2 == null) { // at turning point segmentEnd = i; ps = -ps; ypos = 2; continue; } if (ps < 0 && i == segmentStart + ps) { // done with the reverse sweep ctx.fill(); areaOpen = false; ps = -ps; ypos = 1; i = segmentStart = segmentEnd + ps; continue; } } if (x1 == null || x2 == null) continue; // clip x values // clip with xmin if (x1 <= x2 && x1 < axisx.min) { if (x2 < axisx.min) continue; y1 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.min; } else if (x2 <= x1 && x2 < axisx.min) { if (x1 < axisx.min) continue; y2 = (axisx.min - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.min; } // clip with xmax if (x1 >= x2 && x1 > axisx.max) { if (x2 > axisx.max) continue; y1 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x1 = axisx.max; } else if (x2 >= x1 && x2 > axisx.max) { if (x1 > axisx.max) continue; y2 = (axisx.max - x1) / (x2 - x1) * (y2 - y1) + y1; x2 = axisx.max; } if (!areaOpen) { // open area ctx.beginPath(); ctx.moveTo(axisx.p2c(x1), axisy.p2c(bottom)); areaOpen = true; } // now first check the case where both is outside if (y1 >= axisy.max && y2 >= axisy.max) { ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.max)); ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.max)); continue; } else if (y1 <= axisy.min && y2 <= axisy.min) { ctx.lineTo(axisx.p2c(x1), axisy.p2c(axisy.min)); ctx.lineTo(axisx.p2c(x2), axisy.p2c(axisy.min)); continue; } // else it's a bit more complicated, there might // be a flat maxed out rectangle first, then a // triangular cutout or reverse; to find these // keep track of the current x values var x1old = x1, x2old = x2; // clip the y values, without shortcutting, we // go through all cases in turn // clip with ymin if (y1 <= y2 && y1 < axisy.min && y2 >= axisy.min) { x1 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.min; } else if (y2 <= y1 && y2 < axisy.min && y1 >= axisy.min) { x2 = (axisy.min - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.min; } // clip with ymax if (y1 >= y2 && y1 > axisy.max && y2 <= axisy.max) { x1 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y1 = axisy.max; } else if (y2 >= y1 && y2 > axisy.max && y1 <= axisy.max) { x2 = (axisy.max - y1) / (y2 - y1) * (x2 - x1) + x1; y2 = axisy.max; } // if the x value was changed we got a rectangle // to fill if (x1 != x1old) { ctx.lineTo(axisx.p2c(x1old), axisy.p2c(y1)); // it goes to (x1, y1), but we fill that below } // fill triangular section, this sometimes result // in redundant points if (x1, y1) hasn't changed // from previous line to, but we just ignore that ctx.lineTo(axisx.p2c(x1), axisy.p2c(y1)); ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2)); // fill the other rectangle if it's there if (x2 != x2old) { ctx.lineTo(axisx.p2c(x2), axisy.p2c(y2)); ctx.lineTo(axisx.p2c(x2old), axisy.p2c(y2)); } } } ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); ctx.lineJoin = "round"; var lw = series.lines.lineWidth, sw = series.shadowSize; // FIXME: consider another form of shadow when filling is turned on if (lw > 0 && sw > 0) { // draw shadow as a thick and thin line with transparency ctx.lineWidth = sw; ctx.strokeStyle = "rgba(0,0,0,0.1)"; // position shadow at angle from the mid of line var angle = Math.PI/18; plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/2), Math.cos(angle) * (lw/2 + sw/2), series.xaxis, series.yaxis); ctx.lineWidth = sw/2; plotLine(series.datapoints, Math.sin(angle) * (lw/2 + sw/4), Math.cos(angle) * (lw/2 + sw/4), series.xaxis, series.yaxis); } ctx.lineWidth = lw; ctx.strokeStyle = series.color; var fillStyle = getFillStyle(series.lines, series.color, 0, plotHeight); if (fillStyle) { ctx.fillStyle = fillStyle; plotLineArea(series.datapoints, series.xaxis, series.yaxis); } if (lw > 0) plotLine(series.datapoints, 0, 0, series.xaxis, series.yaxis); ctx.restore(); } function drawSeriesPoints(series) { function plotPoints(datapoints, radius, fillStyle, offset, shadow, axisx, axisy, symbol) { var points = datapoints.points, ps = datapoints.pointsize; for (var i = 0; i < points.length; i += ps) { var x = points[i], y = points[i + 1]; if (x == null || x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max) continue; ctx.beginPath(); x = axisx.p2c(x); y = axisy.p2c(y) + offset; if (symbol == "circle") ctx.arc(x, y, radius, 0, shadow ? Math.PI : Math.PI * 2, false); else symbol(ctx, x, y, radius, shadow); ctx.closePath(); if (fillStyle) { ctx.fillStyle = fillStyle; ctx.fill(); } ctx.stroke(); } } ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); var lw = series.points.lineWidth, sw = series.shadowSize, radius = series.points.radius, symbol = series.points.symbol; // If the user sets the line width to 0, we change it to a very // small value. A line width of 0 seems to force the default of 1. // Doing the conditional here allows the shadow setting to still be // optional even with a lineWidth of 0. if( lw == 0 ) lw = 0.0001; if (lw > 0 && sw > 0) { // draw shadow in two steps var w = sw / 2; ctx.lineWidth = w; ctx.strokeStyle = "rgba(0,0,0,0.1)"; plotPoints(series.datapoints, radius, null, w + w/2, true, series.xaxis, series.yaxis, symbol); ctx.strokeStyle = "rgba(0,0,0,0.2)"; plotPoints(series.datapoints, radius, null, w/2, true, series.xaxis, series.yaxis, symbol); } ctx.lineWidth = lw; ctx.strokeStyle = series.color; plotPoints(series.datapoints, radius, getFillStyle(series.points, series.color), 0, false, series.xaxis, series.yaxis, symbol); ctx.restore(); } function drawBar(x, y, b, barLeft, barRight, fillStyleCallback, axisx, axisy, c, horizontal, lineWidth) { var left, right, bottom, top, drawLeft, drawRight, drawTop, drawBottom, tmp; // in horizontal mode, we start the bar from the left // instead of from the bottom so it appears to be // horizontal rather than vertical if (horizontal) { drawBottom = drawRight = drawTop = true; drawLeft = false; left = b; right = x; top = y + barLeft; bottom = y + barRight; // account for negative bars if (right < left) { tmp = right; right = left; left = tmp; drawLeft = true; drawRight = false; } } else { drawLeft = drawRight = drawTop = true; drawBottom = false; left = x + barLeft; right = x + barRight; bottom = b; top = y; // account for negative bars if (top < bottom) { tmp = top; top = bottom; bottom = tmp; drawBottom = true; drawTop = false; } } // clip if (right < axisx.min || left > axisx.max || top < axisy.min || bottom > axisy.max) return; if (left < axisx.min) { left = axisx.min; drawLeft = false; } if (right > axisx.max) { right = axisx.max; drawRight = false; } if (bottom < axisy.min) { bottom = axisy.min; drawBottom = false; } if (top > axisy.max) { top = axisy.max; drawTop = false; } left = axisx.p2c(left); bottom = axisy.p2c(bottom); right = axisx.p2c(right); top = axisy.p2c(top); // fill the bar if (fillStyleCallback) { c.fillStyle = fillStyleCallback(bottom, top); c.fillRect(left, top, right - left, bottom - top) } // draw outline if (lineWidth > 0 && (drawLeft || drawRight || drawTop || drawBottom)) { c.beginPath(); // FIXME: inline moveTo is buggy with excanvas c.moveTo(left, bottom); if (drawLeft) c.lineTo(left, top); else c.moveTo(left, top); if (drawTop) c.lineTo(right, top); else c.moveTo(right, top); if (drawRight) c.lineTo(right, bottom); else c.moveTo(right, bottom); if (drawBottom) c.lineTo(left, bottom); else c.moveTo(left, bottom); c.stroke(); } } function drawSeriesBars(series) { function plotBars(datapoints, barLeft, barRight, fillStyleCallback, axisx, axisy) { var points = datapoints.points, ps = datapoints.pointsize; for (var i = 0; i < points.length; i += ps) { if (points[i] == null) continue; drawBar(points[i], points[i + 1], points[i + 2], barLeft, barRight, fillStyleCallback, axisx, axisy, ctx, series.bars.horizontal, series.bars.lineWidth); } } ctx.save(); ctx.translate(plotOffset.left, plotOffset.top); // FIXME: figure out a way to add shadows (for instance along the right edge) ctx.lineWidth = series.bars.lineWidth; ctx.strokeStyle = series.color; var barLeft; switch (series.bars.align) { case "left": barLeft = 0; break; case "right": barLeft = -series.bars.barWidth; break; default: barLeft = -series.bars.barWidth / 2; } var fillStyleCallback = series.bars.fill ? function (bottom, top) { return getFillStyle(series.bars, series.color, bottom, top); } : null; plotBars(series.datapoints, barLeft, barLeft + series.bars.barWidth, fillStyleCallback, series.xaxis, series.yaxis); ctx.restore(); } function getFillStyle(filloptions, seriesColor, bottom, top) { var fill = filloptions.fill; if (!fill) return null; if (filloptions.fillColor) return getColorOrGradient(filloptions.fillColor, bottom, top, seriesColor); var c = $.color.parse(seriesColor); c.a = typeof fill == "number" ? fill : 0.4; c.normalize(); return c.toString(); } function insertLegend() { if (options.legend.container != null) { $(options.legend.container).html(""); } else { placeholder.find(".legend").remove(); } if (!options.legend.show) { return; } var fragments = [], entries = [], rowStarted = false, lf = options.legend.labelFormatter, s, label; // Build a list of legend entries, with each having a label and a color for (var i = 0; i < series.length; ++i) { s = series[i]; if (s.label) { label = lf ? lf(s.label, s) : s.label; if (label) { entries.push({ label: label, color: s.color }); } } } // Sort the legend using either the default or a custom comparator if (options.legend.sorted) { if ($.isFunction(options.legend.sorted)) { entries.sort(options.legend.sorted); } else if (options.legend.sorted == "reverse") { entries.reverse(); } else { var ascending = options.legend.sorted != "descending"; entries.sort(function(a, b) { return a.label == b.label ? 0 : ( (a.label < b.label) != ascending ? 1 : -1 // Logical XOR ); }); } } // Generate markup for the list of entries, in their final order for (var i = 0; i < entries.length; ++i) { var entry = entries[i]; if (i % options.legend.noColumns == 0) { if (rowStarted) fragments.push('</tr>'); fragments.push('<tr>'); rowStarted = true; } fragments.push( '<td class="legendColorBox"><div style="border:1px solid ' + options.legend.labelBoxBorderColor + ';padding:1px"><div style="width:4px;height:0;border:5px solid ' + entry.color + ';overflow:hidden"></div></div></td>' + '<td class="legendLabel">' + entry.label + '</td>' ); } if (rowStarted) fragments.push('</tr>'); if (fragments.length == 0) return; var table = '<table style="font-size:smaller;color:' + options.grid.color + '">' + fragments.join("") + '</table>'; if (options.legend.container != null) $(options.legend.container).html(table); else { var pos = "", p = options.legend.position, m = options.legend.margin; if (m[0] == null) m = [m, m]; if (p.charAt(0) == "n") pos += 'top:' + (m[1] + plotOffset.top) + 'px;'; else if (p.charAt(0) == "s") pos += 'bottom:' + (m[1] + plotOffset.bottom) + 'px;'; if (p.charAt(1) == "e") pos += 'right:' + (m[0] + plotOffset.right) + 'px;'; else if (p.charAt(1) == "w") pos += 'left:' + (m[0] + plotOffset.left) + 'px;'; var legend = $('<div class="legend">' + table.replace('style="', 'style="position:absolute;' + pos +';') + '</div>').appendTo(placeholder); if (options.legend.backgroundOpacity != 0.0) { // put in the transparent background // separately to avoid blended labels and // label boxes var c = options.legend.backgroundColor; if (c == null) { c = options.grid.backgroundColor; if (c && typeof c == "string") c = $.color.parse(c); else c = $.color.extract(legend, 'background-color'); c.a = 1; c = c.toString(); } var div = legend.children(); $('<div style="position:absolute;width:' + div.width() + 'px;height:' + div.height() + 'px;' + pos +'background-color:' + c + ';"> </div>').prependTo(legend).css('opacity', options.legend.backgroundOpacity); } } } // interactive features var highlights = [], redrawTimeout = null; // returns the data item the mouse is over, or null if none is found function findNearbyItem(mouseX, mouseY, seriesFilter) { var maxDistance = options.grid.mouseActiveRadius, smallestDistance = maxDistance * maxDistance + 1, item = null, foundPoint = false, i, j, ps; for (i = series.length - 1; i >= 0; --i) { if (!seriesFilter(series[i])) continue; var s = series[i], axisx = s.xaxis, axisy = s.yaxis, points = s.datapoints.points, mx = axisx.c2p(mouseX), // precompute some stuff to make the loop faster my = axisy.c2p(mouseY), maxx = maxDistance / axisx.scale, maxy = maxDistance / axisy.scale; ps = s.datapoints.pointsize; // with inverse transforms, we can't use the maxx/maxy // optimization, sadly if (axisx.options.inverseTransform) maxx = Number.MAX_VALUE; if (axisy.options.inverseTransform) maxy = Number.MAX_VALUE; if (s.lines.show || s.points.show) { for (j = 0; j < points.length; j += ps) { var x = points[j], y = points[j + 1]; if (x == null) continue; // For points and lines, the cursor must be within a // certain distance to the data point if (x - mx > maxx || x - mx < -maxx || y - my > maxy || y - my < -maxy) continue; // We have to calculate distances in pixels, not in // data units, because the scales of the axes may be different var dx = Math.abs(axisx.p2c(x) - mouseX), dy = Math.abs(axisy.p2c(y) - mouseY), dist = dx * dx + dy * dy; // we save the sqrt // use <= to ensure last point takes precedence // (last generally means on top of) if (dist < smallestDistance) { smallestDistance = dist; item = [i, j / ps]; } } } if (s.bars.show && !item) { // no other point can be nearby var barLeft, barRight; switch (s.bars.align) { case "left": barLeft = 0; break; case "right": barLeft = -s.bars.barWidth; break; default: barLeft = -s.bars.barWidth / 2; } barRight = barLeft + s.bars.barWidth; for (j = 0; j < points.length; j += ps) { var x = points[j], y = points[j + 1], b = points[j + 2]; if (x == null) continue; // for a bar graph, the cursor must be inside the bar if (series[i].bars.horizontal ? (mx <= Math.max(b, x) && mx >= Math.min(b, x) && my >= y + barLeft && my <= y + barRight) : (mx >= x + barLeft && mx <= x + barRight && my >= Math.min(b, y) && my <= Math.max(b, y))) item = [i, j / ps]; } } } if (item) { i = item[0]; j = item[1]; ps = series[i].datapoints.pointsize; return { datapoint: series[i].datapoints.points.slice(j * ps, (j + 1) * ps), dataIndex: j, series: series[i], seriesIndex: i }; } return null; } function onMouseMove(e) { if (options.grid.hoverable) triggerClickHoverEvent("plothover", e, function (s) { return s["hoverable"] != false; }); } function onMouseLeave(e) { if (options.grid.hoverable) triggerClickHoverEvent("plothover", e, function (s) { return false; }); } function onClick(e) { triggerClickHoverEvent("plotclick", e, function (s) { return s["clickable"] != false; }); } // trigger click or hover event (they send the same parameters // so we share their code) function triggerClickHoverEvent(eventname, event, seriesFilter) { var offset = eventHolder.offset(), canvasX = event.pageX - offset.left - plotOffset.left, canvasY = event.pageY - offset.top - plotOffset.top, pos = canvasToAxisCoords({ left: canvasX, top: canvasY }); pos.pageX = event.pageX; pos.pageY = event.pageY; var item = findNearbyItem(canvasX, canvasY, seriesFilter); if (item) { // fill in mouse pos for any listeners out there item.pageX = parseInt(item.series.xaxis.p2c(item.datapoint[0]) + offset.left + plotOffset.left, 10); item.pageY = parseInt(item.series.yaxis.p2c(item.datapoint[1]) + offset.top + plotOffset.top, 10); } if (options.grid.autoHighlight) { // clear auto-highlights for (var i = 0; i < highlights.length; ++i) { var h = highlights[i]; if (h.auto == eventname && !(item && h.series == item.series && h.point[0] == item.datapoint[0] && h.point[1] == item.datapoint[1])) unhighlight(h.series, h.point); } if (item) highlight(item.series, item.datapoint, eventname); } placeholder.trigger(eventname, [ pos, item ]); } function triggerRedrawOverlay() { var t = options.interaction.redrawOverlayInterval; if (t == -1) { // skip event queue drawOverlay(); return; } if (!redrawTimeout) redrawTimeout = setTimeout(drawOverlay, t); } function drawOverlay() { redrawTimeout = null; // draw highlights octx.save(); overlay.clear(); octx.translate(plotOffset.left, plotOffset.top); var i, hi; for (i = 0; i < highlights.length; ++i) { hi = highlights[i]; if (hi.series.bars.show) drawBarHighlight(hi.series, hi.point); else drawPointHighlight(hi.series, hi.point); } octx.restore(); executeHooks(hooks.drawOverlay, [octx]); } function highlight(s, point, auto) { if (typeof s == "number") s = series[s]; if (typeof point == "number") { var ps = s.datapoints.pointsize; point = s.datapoints.points.slice(ps * point, ps * (point + 1)); } var i = indexOfHighlight(s, point); if (i == -1) { highlights.push({ series: s, point: point, auto: auto }); triggerRedrawOverlay(); } else if (!auto) highlights[i].auto = false; } function unhighlight(s, point) { if (s == null && point == null) { highlights = []; triggerRedrawOverlay(); return; } if (typeof s == "number") s = series[s]; if (typeof point == "number") { var ps = s.datapoints.pointsize; point = s.datapoints.points.slice(ps * point, ps * (point + 1)); } var i = indexOfHighlight(s, point); if (i != -1) { highlights.splice(i, 1); triggerRedrawOverlay(); } } function indexOfHighlight(s, p) { for (var i = 0; i < highlights.length; ++i) { var h = highlights[i]; if (h.series == s && h.point[0] == p[0] && h.point[1] == p[1]) return i; } return -1; } function drawPointHighlight(series, point) { var x = point[0], y = point[1], axisx = series.xaxis, axisy = series.yaxis, highlightColor = (typeof series.highlightColor === "string") ? series.highlightColor : $.color.parse(series.color).scale('a', 0.5).toString(); if (x < axisx.min || x > axisx.max || y < axisy.min || y > axisy.max) return; var pointRadius = series.points.radius + series.points.lineWidth / 2; octx.lineWidth = pointRadius; octx.strokeStyle = highlightColor; var radius = 1.5 * pointRadius; x = axisx.p2c(x); y = axisy.p2c(y); octx.beginPath(); if (series.points.symbol == "circle") octx.arc(x, y, radius, 0, 2 * Math.PI, false); else series.points.symbol(octx, x, y, radius, false); octx.closePath(); octx.stroke(); } function drawBarHighlight(series, point) { var highlightColor = (typeof series.highlightColor === "string") ? series.highlightColor : $.color.parse(series.color).scale('a', 0.5).toString(), fillStyle = highlightColor, barLeft; switch (series.bars.align) { case "left": barLeft = 0; break; case "right": barLeft = -series.bars.barWidth; break; default: barLeft = -series.bars.barWidth / 2; } octx.lineWidth = series.bars.lineWidth; octx.strokeStyle = highlightColor; drawBar(point[0], point[1], point[2] || 0, barLeft, barLeft + series.bars.barWidth, function () { return fillStyle; }, series.xaxis, series.yaxis, octx, series.bars.horizontal, series.bars.lineWidth); } function getColorOrGradient(spec, bottom, top, defaultColor) { if (typeof spec == "string") return spec; else { // assume this is a gradient spec; IE currently only // supports a simple vertical gradient properly, so that's // what we support too var gradient = ctx.createLinearGradient(0, top, 0, bottom); for (var i = 0, l = spec.colors.length; i < l; ++i) { var c = spec.colors[i]; if (typeof c != "string") { var co = $.color.parse(defaultColor); if (c.brightness != null) co = co.scale('rgb', c.brightness); if (c.opacity != null) co.a *= c.opacity; c = co.toString(); } gradient.addColorStop(i / (l - 1), c); } return gradient; } } } // Add the plot function to the top level of the jQuery object $.plot = function(placeholder, data, options) { //var t0 = new Date(); var plot = new Plot($(placeholder), data, options, $.plot.plugins); //(window.console ? console.log : alert)("time used (msecs): " + ((new Date()).getTime() - t0.getTime())); return plot; }; $.plot.version = "0.8.2"; $.plot.plugins = []; // Also add the plot function as a chainable property $.fn.plot = function(data, options) { return this.each(function() { $.plot(this, data, options); }); }; // round to nearby lower multiple of base function floorInBase(n, base) { return base * Math.floor(n / base); } })(jQuery);
JavaScript
(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 = $("<div class='" + this.options["class"] + "'></div>"); 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 = "<div class='morris-hover-row-label'>" + row.label + "</div>"; _ref = row.y; for (j = _i = 0, _len = _ref.length; _i < _len; j = ++_i) { y = _ref[j]; content += "<div class='morris-hover-point' style='color: " + (this.colorFor(row, j, 'label')) + "'>\n " + this.options.labels[j] + ":\n " + (this.yLabelFormat(y)) + "\n</div>"; } 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 = "<div class='morris-hover-row-label'>" + row.label + "</div>"; _ref = row.y; for (j = _i = 0, _len = _ref.length; _i < _len; j = ++_i) { y = _ref[j]; content += "<div class='morris-hover-point' style='color: " + (this.colorFor(row, j, 'label')) + "'>\n " + this.options.labels[j] + ":\n " + (this.yLabelFormat(y)) + "\n</div>"; } 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);
JavaScript
// moment.js language configuration // language : Moroccan Arabic (ar-ma) // author : ElFadili Yassine : https://github.com/ElFadiliY // author : Abdel Said : https://github.com/abdelsaid (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('ar-ma', { months : "يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"), monthsShort : "يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"), weekdays : "الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"), weekdaysShort : "احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت".split("_"), weekdaysMin : "ح_ن_ث_ر_خ_ج_س".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[اليوم على الساعة] LT", nextDay: '[غدا على الساعة] LT', nextWeek: 'dddd [على الساعة] LT', lastDay: '[أمس على الساعة] LT', lastWeek: 'dddd [على الساعة] LT', sameElse: 'L' }, relativeTime : { future : "في %s", past : "منذ %s", s : "ثوان", m : "دقيقة", mm : "%d دقائق", h : "ساعة", hh : "%d ساعات", d : "يوم", dd : "%d أيام", M : "شهر", MM : "%d أشهر", y : "سنة", yy : "%d سنوات" }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Arabic (ar) // author : Abdel Said : https://github.com/abdelsaid // changes in months, weekdays : Ahmed Elkhatib (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('ar', { months : "يناير/ كانون الثاني_فبراير/ شباط_مارس/ آذار_أبريل/ نيسان_مايو/ أيار_يونيو/ حزيران_يوليو/ تموز_أغسطس/ آب_سبتمبر/ أيلول_أكتوبر/ تشرين الأول_نوفمبر/ تشرين الثاني_ديسمبر/ كانون الأول".split("_"), monthsShort : "يناير/ كانون الثاني_فبراير/ شباط_مارس/ آذار_أبريل/ نيسان_مايو/ أيار_يونيو/ حزيران_يوليو/ تموز_أغسطس/ آب_سبتمبر/ أيلول_أكتوبر/ تشرين الأول_نوفمبر/ تشرين الثاني_ديسمبر/ كانون الأول".split("_"), weekdays : "الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"), weekdaysShort : "الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"), weekdaysMin : "ح_ن_ث_ر_خ_ج_س".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[اليوم على الساعة] LT", nextDay: '[غدا على الساعة] LT', nextWeek: 'dddd [على الساعة] LT', lastDay: '[أمس على الساعة] LT', lastWeek: 'dddd [على الساعة] LT', sameElse: 'L' }, relativeTime : { future : "في %s", past : "منذ %s", s : "ثوان", m : "دقيقة", mm : "%d دقائق", h : "ساعة", hh : "%d ساعات", d : "يوم", dd : "%d أيام", M : "شهر", MM : "%d أشهر", y : "سنة", yy : "%d سنوات" }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : bulgarian (bg) // author : Krasen Borisov : https://github.com/kraz (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('bg', { months : "януари_февруари_март_април_май_юни_юли_август_септември_октомври_ноември_декември".split("_"), monthsShort : "янр_фев_мар_апр_май_юни_юли_авг_сеп_окт_ное_дек".split("_"), weekdays : "неделя_понеделник_вторник_сряда_четвъртък_петък_събота".split("_"), weekdaysShort : "нед_пон_вто_сря_чет_пет_съб".split("_"), weekdaysMin : "нд_пн_вт_ср_чт_пт_сб".split("_"), longDateFormat : { LT : "H:mm", L : "D.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[Днес в] LT', nextDay : '[Утре в] LT', nextWeek : 'dddd [в] LT', lastDay : '[Вчера в] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: case 6: return '[В изминалата] dddd [в] LT'; case 1: case 2: case 4: case 5: return '[В изминалия] dddd [в] LT'; } }, sameElse : 'L' }, relativeTime : { future : "след %s", past : "преди %s", s : "няколко секунди", m : "минута", mm : "%d минути", h : "час", hh : "%d часа", d : "ден", dd : "%d дни", M : "месец", MM : "%d месеца", y : "година", yy : "%d години" }, ordinal : function (number) { var lastDigit = number % 10, last2Digits = number % 100; if (number === 0) { return number + '-ев'; } else if (last2Digits === 0) { return number + '-ен'; } else if (last2Digits > 10 && last2Digits < 20) { return number + '-ти'; } else if (lastDigit === 1) { return number + '-ви'; } else if (lastDigit === 2) { return number + '-ри'; } else if (lastDigit === 7 || lastDigit === 8) { return number + '-ми'; } else { return number + '-ти'; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : breton (br) // author : Jean-Baptiste Le Duigou : https://github.com/jbleduigou (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function relativeTimeWithMutation(number, withoutSuffix, key) { var format = { 'mm': "munutenn", 'MM': "miz", 'dd': "devezh" }; return number + ' ' + mutation(format[key], number); } function specialMutationForYears(number) { switch (lastNumber(number)) { case 1: case 3: case 4: case 5: case 9: return number + ' bloaz'; default: return number + ' vloaz'; } } function lastNumber(number) { if (number > 9) { return lastNumber(number % 10); } return number; } function mutation(text, number) { if (number === 2) { return softMutation(text); } return text; } function softMutation(text) { var mutationTable = { 'm': 'v', 'b': 'v', 'd': 'z' }; if (mutationTable[text.charAt(0)] === undefined) { return text; } return mutationTable[text.charAt(0)] + text.substring(1); } return moment.lang('br', { months : "Genver_C'hwevrer_Meurzh_Ebrel_Mae_Mezheven_Gouere_Eost_Gwengolo_Here_Du_Kerzu".split("_"), monthsShort : "Gen_C'hwe_Meu_Ebr_Mae_Eve_Gou_Eos_Gwe_Her_Du_Ker".split("_"), weekdays : "Sul_Lun_Meurzh_Merc'her_Yaou_Gwener_Sadorn".split("_"), weekdaysShort : "Sul_Lun_Meu_Mer_Yao_Gwe_Sad".split("_"), weekdaysMin : "Su_Lu_Me_Mer_Ya_Gw_Sa".split("_"), longDateFormat : { LT : "h[e]mm A", L : "DD/MM/YYYY", LL : "D [a viz] MMMM YYYY", LLL : "D [a viz] MMMM YYYY LT", LLLL : "dddd, D [a viz] MMMM YYYY LT" }, calendar : { sameDay : '[Hiziv da] LT', nextDay : '[Warc\'hoazh da] LT', nextWeek : 'dddd [da] LT', lastDay : '[Dec\'h da] LT', lastWeek : 'dddd [paset da] LT', sameElse : 'L' }, relativeTime : { future : "a-benn %s", past : "%s 'zo", s : "un nebeud segondennoù", m : "ur vunutenn", mm : relativeTimeWithMutation, h : "un eur", hh : "%d eur", d : "un devezh", dd : relativeTimeWithMutation, M : "ur miz", MM : relativeTimeWithMutation, y : "ur bloaz", yy : specialMutationForYears }, ordinal : function (number) { var output = (number === 1) ? 'añ' : 'vet'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : bosnian (bs) // author : Nedim Cholich : https://github.com/frontyard // based on (hr) translation by Bojan Marković (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function translate(number, withoutSuffix, key) { var result = number + " "; switch (key) { case 'm': return withoutSuffix ? 'jedna minuta' : 'jedne minute'; case 'mm': if (number === 1) { result += 'minuta'; } else if (number === 2 || number === 3 || number === 4) { result += 'minute'; } else { result += 'minuta'; } return result; case 'h': return withoutSuffix ? 'jedan sat' : 'jednog sata'; case 'hh': if (number === 1) { result += 'sat'; } else if (number === 2 || number === 3 || number === 4) { result += 'sata'; } else { result += 'sati'; } return result; case 'dd': if (number === 1) { result += 'dan'; } else { result += 'dana'; } return result; case 'MM': if (number === 1) { result += 'mjesec'; } else if (number === 2 || number === 3 || number === 4) { result += 'mjeseca'; } else { result += 'mjeseci'; } return result; case 'yy': if (number === 1) { result += 'godina'; } else if (number === 2 || number === 3 || number === 4) { result += 'godine'; } else { result += 'godina'; } return result; } } return moment.lang('bs', { months : "januar_februar_mart_april_maj_juni_juli_avgust_septembar_oktobar_novembar_decembar".split("_"), monthsShort : "jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.".split("_"), weekdays : "nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota".split("_"), weekdaysShort : "ned._pon._uto._sri._čet._pet._sub.".split("_"), weekdaysMin : "ne_po_ut_sr_če_pe_su".split("_"), longDateFormat : { LT : "H:mm", L : "DD. MM. YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay : '[danas u] LT', nextDay : '[sutra u] LT', nextWeek : function () { switch (this.day()) { case 0: return '[u] [nedjelju] [u] LT'; case 3: return '[u] [srijedu] [u] LT'; case 6: return '[u] [subotu] [u] LT'; case 1: case 2: case 4: case 5: return '[u] dddd [u] LT'; } }, lastDay : '[jučer u] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: return '[prošlu] dddd [u] LT'; case 6: return '[prošle] [subote] [u] LT'; case 1: case 2: case 4: case 5: return '[prošli] dddd [u] LT'; } }, sameElse : 'L' }, relativeTime : { future : "za %s", past : "prije %s", s : "par sekundi", m : translate, mm : translate, h : translate, hh : translate, d : "dan", dd : translate, M : "mjesec", MM : translate, y : "godinu", yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : catalan (ca) // author : Juan G. Hurtado : https://github.com/juanghurtado (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('ca', { months : "gener_febrer_març_abril_maig_juny_juliol_agost_setembre_octubre_novembre_desembre".split("_"), monthsShort : "gen._febr._mar._abr._mai._jun._jul._ag._set._oct._nov._des.".split("_"), weekdays : "diumenge_dilluns_dimarts_dimecres_dijous_divendres_dissabte".split("_"), weekdaysShort : "dg._dl._dt._dc._dj._dv._ds.".split("_"), weekdaysMin : "Dg_Dl_Dt_Dc_Dj_Dv_Ds".split("_"), longDateFormat : { LT : "H:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay : function () { return '[avui a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, nextDay : function () { return '[demà a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, nextWeek : function () { return 'dddd [a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, lastDay : function () { return '[ahir a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, lastWeek : function () { return '[el] dddd [passat a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, sameElse : 'L' }, relativeTime : { future : "en %s", past : "fa %s", s : "uns segons", m : "un minut", mm : "%d minuts", h : "una hora", hh : "%d hores", d : "un dia", dd : "%d dies", M : "un mes", MM : "%d mesos", y : "un any", yy : "%d anys" }, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : czech (cs) // author : petrbela : https://github.com/petrbela (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var months = "leden_únor_březen_duben_květen_červen_červenec_srpen_září_říjen_listopad_prosinec".split("_"), monthsShort = "led_úno_bře_dub_kvě_čvn_čvc_srp_zář_říj_lis_pro".split("_"); function plural(n) { return (n > 1) && (n < 5) && (~~(n / 10) !== 1); } function translate(number, withoutSuffix, key, isFuture) { var result = number + " "; switch (key) { case 's': // a few seconds / in a few seconds / a few seconds ago return (withoutSuffix || isFuture) ? 'pár vteřin' : 'pár vteřinami'; case 'm': // a minute / in a minute / a minute ago return withoutSuffix ? 'minuta' : (isFuture ? 'minutu' : 'minutou'); case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'minuty' : 'minut'); } else { return result + 'minutami'; } break; case 'h': // an hour / in an hour / an hour ago return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou'); case 'hh': // 9 hours / in 9 hours / 9 hours ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'hodiny' : 'hodin'); } else { return result + 'hodinami'; } break; case 'd': // a day / in a day / a day ago return (withoutSuffix || isFuture) ? 'den' : 'dnem'; case 'dd': // 9 days / in 9 days / 9 days ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'dny' : 'dní'); } else { return result + 'dny'; } break; case 'M': // a month / in a month / a month ago return (withoutSuffix || isFuture) ? 'měsíc' : 'měsícem'; case 'MM': // 9 months / in 9 months / 9 months ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'měsíce' : 'měsíců'); } else { return result + 'měsíci'; } break; case 'y': // a year / in a year / a year ago return (withoutSuffix || isFuture) ? 'rok' : 'rokem'; case 'yy': // 9 years / in 9 years / 9 years ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'roky' : 'let'); } else { return result + 'lety'; } break; } } return moment.lang('cs', { months : months, monthsShort : monthsShort, monthsParse : (function (months, monthsShort) { var i, _monthsParse = []; for (i = 0; i < 12; i++) { // use custom parser to solve problem with July (červenec) _monthsParse[i] = new RegExp('^' + months[i] + '$|^' + monthsShort[i] + '$', 'i'); } return _monthsParse; }(months, monthsShort)), weekdays : "neděle_pondělí_úterý_středa_čtvrtek_pátek_sobota".split("_"), weekdaysShort : "ne_po_út_st_čt_pá_so".split("_"), weekdaysMin : "ne_po_út_st_čt_pá_so".split("_"), longDateFormat : { LT: "H:mm", L : "DD.MM.YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd D. MMMM YYYY LT" }, calendar : { sameDay: "[dnes v] LT", nextDay: '[zítra v] LT', nextWeek: function () { switch (this.day()) { case 0: return '[v neděli v] LT'; case 1: case 2: return '[v] dddd [v] LT'; case 3: return '[ve středu v] LT'; case 4: return '[ve čtvrtek v] LT'; case 5: return '[v pátek v] LT'; case 6: return '[v sobotu v] LT'; } }, lastDay: '[včera v] LT', lastWeek: function () { switch (this.day()) { case 0: return '[minulou neděli v] LT'; case 1: case 2: return '[minulé] dddd [v] LT'; case 3: return '[minulou středu v] LT'; case 4: case 5: return '[minulý] dddd [v] LT'; case 6: return '[minulou sobotu v] LT'; } }, sameElse: "L" }, relativeTime : { future : "za %s", past : "před %s", s : translate, m : translate, mm : translate, h : translate, hh : translate, d : translate, dd : translate, M : translate, MM : translate, y : translate, yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : chuvash (cv) // author : Anatoly Mironov : https://github.com/mirontoli (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('cv', { months : "кăрлач_нарăс_пуш_ака_май_çĕртме_утă_çурла_авăн_юпа_чӳк_раштав".split("_"), monthsShort : "кăр_нар_пуш_ака_май_çĕр_утă_çур_ав_юпа_чӳк_раш".split("_"), weekdays : "вырсарникун_тунтикун_ытларикун_юнкун_кĕçнерникун_эрнекун_шăматкун".split("_"), weekdaysShort : "выр_тун_ытл_юн_кĕç_эрн_шăм".split("_"), weekdaysMin : "вр_тн_ыт_юн_кç_эр_шм".split("_"), longDateFormat : { LT : "HH:mm", L : "DD-MM-YYYY", LL : "YYYY [çулхи] MMMM [уйăхĕн] D[-мĕшĕ]", LLL : "YYYY [çулхи] MMMM [уйăхĕн] D[-мĕшĕ], LT", LLLL : "dddd, YYYY [çулхи] MMMM [уйăхĕн] D[-мĕшĕ], LT" }, calendar : { sameDay: '[Паян] LT [сехетре]', nextDay: '[Ыран] LT [сехетре]', lastDay: '[Ĕнер] LT [сехетре]', nextWeek: '[Çитес] dddd LT [сехетре]', lastWeek: '[Иртнĕ] dddd LT [сехетре]', sameElse: 'L' }, relativeTime : { future : function (output) { var affix = /сехет$/i.exec(output) ? "рен" : /çул$/i.exec(output) ? "тан" : "ран"; return output + affix; }, past : "%s каялла", s : "пĕр-ик çеккунт", m : "пĕр минут", mm : "%d минут", h : "пĕр сехет", hh : "%d сехет", d : "пĕр кун", dd : "%d кун", M : "пĕр уйăх", MM : "%d уйăх", y : "пĕр çул", yy : "%d çул" }, ordinal : '%d-мĕш', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Welsh (cy) // author : Robert Allen (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang("cy", { months: "Ionawr_Chwefror_Mawrth_Ebrill_Mai_Mehefin_Gorffennaf_Awst_Medi_Hydref_Tachwedd_Rhagfyr".split("_"), monthsShort: "Ion_Chwe_Maw_Ebr_Mai_Meh_Gor_Aws_Med_Hyd_Tach_Rhag".split("_"), weekdays: "Dydd Sul_Dydd Llun_Dydd Mawrth_Dydd Mercher_Dydd Iau_Dydd Gwener_Dydd Sadwrn".split("_"), weekdaysShort: "Sul_Llun_Maw_Mer_Iau_Gwe_Sad".split("_"), weekdaysMin: "Su_Ll_Ma_Me_Ia_Gw_Sa".split("_"), // time formats are the same as en-gb longDateFormat: { LT: "HH:mm", L: "DD/MM/YYYY", LL: "D MMMM YYYY", LLL: "D MMMM YYYY LT", LLLL: "dddd, D MMMM YYYY LT" }, calendar: { sameDay: '[Heddiw am] LT', nextDay: '[Yfory am] LT', nextWeek: 'dddd [am] LT', lastDay: '[Ddoe am] LT', lastWeek: 'dddd [diwethaf am] LT', sameElse: 'L' }, relativeTime: { future: "mewn %s", past: "%s yn àl", s: "ychydig eiliadau", m: "munud", mm: "%d munud", h: "awr", hh: "%d awr", d: "diwrnod", dd: "%d diwrnod", M: "mis", MM: "%d mis", y: "blwyddyn", yy: "%d flynedd" }, // traditional ordinal numbers above 31 are not commonly used in colloquial Welsh ordinal: function (number) { var b = number, output = '', lookup = [ '', 'af', 'il', 'ydd', 'ydd', 'ed', 'ed', 'ed', 'fed', 'fed', 'fed', // 1af to 10fed 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'fed' // 11eg to 20fed ]; if (b > 20) { if (b === 40 || b === 50 || b === 60 || b === 80 || b === 100) { output = 'fed'; // not 30ain, 70ain or 90ain } else { output = 'ain'; } } else if (b > 0) { output = lookup[b]; } return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : danish (da) // author : Ulrik Nielsen : https://github.com/mrbase (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('da', { months : "januar_februar_marts_april_maj_juni_juli_august_september_oktober_november_december".split("_"), monthsShort : "jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec".split("_"), weekdays : "søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag".split("_"), weekdaysShort : "søn_man_tir_ons_tor_fre_lør".split("_"), weekdaysMin : "sø_ma_ti_on_to_fr_lø".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D. MMMM, YYYY LT" }, calendar : { sameDay : '[I dag kl.] LT', nextDay : '[I morgen kl.] LT', nextWeek : 'dddd [kl.] LT', lastDay : '[I går kl.] LT', lastWeek : '[sidste] dddd [kl] LT', sameElse : 'L' }, relativeTime : { future : "om %s", past : "%s siden", s : "få sekunder", m : "et minut", mm : "%d minutter", h : "en time", hh : "%d timer", d : "en dag", dd : "%d dage", M : "en måned", MM : "%d måneder", y : "et år", yy : "%d år" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : german (de) // author : lluchs : https://github.com/lluchs // author: Menelion Elensúle: https://github.com/Oire (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function processRelativeTime(number, withoutSuffix, key, isFuture) { var format = { 'm': ['eine Minute', 'einer Minute'], 'h': ['eine Stunde', 'einer Stunde'], 'd': ['ein Tag', 'einem Tag'], 'dd': [number + ' Tage', number + ' Tagen'], 'M': ['ein Monat', 'einem Monat'], 'MM': [number + ' Monate', number + ' Monaten'], 'y': ['ein Jahr', 'einem Jahr'], 'yy': [number + ' Jahre', number + ' Jahren'] }; return withoutSuffix ? format[key][0] : format[key][1]; } return moment.lang('de', { months : "Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember".split("_"), monthsShort : "Jan._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.".split("_"), weekdays : "Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag".split("_"), weekdaysShort : "So._Mo._Di._Mi._Do._Fr._Sa.".split("_"), weekdaysMin : "So_Mo_Di_Mi_Do_Fr_Sa".split("_"), longDateFormat : { LT: "H:mm [Uhr]", L : "DD.MM.YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay: "[Heute um] LT", sameElse: "L", nextDay: '[Morgen um] LT', nextWeek: 'dddd [um] LT', lastDay: '[Gestern um] LT', lastWeek: '[letzten] dddd [um] LT' }, relativeTime : { future : "in %s", past : "vor %s", s : "ein paar Sekunden", m : processRelativeTime, mm : "%d Minuten", h : processRelativeTime, hh : "%d Stunden", d : processRelativeTime, dd : processRelativeTime, M : processRelativeTime, MM : processRelativeTime, y : processRelativeTime, yy : processRelativeTime }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : modern greek (el) // author : Aggelos Karalias : https://github.com/mehiel (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('el', { monthsNominativeEl : "Ιανουάριος_Φεβρουάριος_Μάρτιος_Απρίλιος_Μάιος_Ιούνιος_Ιούλιος_Αύγουστος_Σεπτέμβριος_Οκτώβριος_Νοέμβριος_Δεκέμβριος".split("_"), monthsGenitiveEl : "Ιανουαρίου_Φεβρουαρίου_Μαρτίου_Απριλίου_Μαΐου_Ιουνίου_Ιουλίου_Αυγούστου_Σεπτεμβρίου_Οκτωβρίου_Νοεμβρίου_Δεκεμβρίου".split("_"), months : function (momentToFormat, format) { if (/D/.test(format.substring(0, format.indexOf("MMMM")))) { // if there is a day number before 'MMMM' return this._monthsGenitiveEl[momentToFormat.month()]; } else { return this._monthsNominativeEl[momentToFormat.month()]; } }, monthsShort : "Ιαν_Φεβ_Μαρ_Απρ_Μαϊ_Ιουν_Ιουλ_Αυγ_Σεπ_Οκτ_Νοε_Δεκ".split("_"), weekdays : "Κυριακή_Δευτέρα_Τρίτη_Τετάρτη_Πέμπτη_Παρασκευή_Σάββατο".split("_"), weekdaysShort : "Κυρ_Δευ_Τρι_Τετ_Πεμ_Παρ_Σαβ".split("_"), weekdaysMin : "Κυ_Δε_Τρ_Τε_Πε_Πα_Σα".split("_"), meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'μμ' : 'ΜΜ'; } else { return isLower ? 'πμ' : 'ΠΜ'; } }, longDateFormat : { LT : "h:mm A", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendarEl : { sameDay : '[Σήμερα {}] LT', nextDay : '[Αύριο {}] LT', nextWeek : 'dddd [{}] LT', lastDay : '[Χθες {}] LT', lastWeek : '[την προηγούμενη] dddd [{}] LT', sameElse : 'L' }, calendar : function (key, mom) { var output = this._calendarEl[key], hours = mom && mom.hours(); return output.replace("{}", (hours % 12 === 1 ? "στη" : "στις")); }, relativeTime : { future : "σε %s", past : "%s πριν", s : "δευτερόλεπτα", m : "ένα λεπτό", mm : "%d λεπτά", h : "μία ώρα", hh : "%d ώρες", d : "μία μέρα", dd : "%d μέρες", M : "ένας μήνας", MM : "%d μήνες", y : "ένας χρόνος", yy : "%d χρόνια" }, ordinal : function (number) { return number + 'η'; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4st is the first week of the year. } }); })); // moment.js language configuration // language : australian english (en-au) (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('en-au', { months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), longDateFormat : { LT : "h:mm A", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, relativeTime : { future : "in %s", past : "%s ago", s : "a few seconds", m : "a minute", mm : "%d minutes", h : "an hour", hh : "%d hours", d : "a day", dd : "%d days", M : "a month", MM : "%d months", y : "a year", yy : "%d years" }, ordinal : function (number) { var b = number % 10, output = (~~ (number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : canadian english (en-ca) // author : Jonathan Abourbih : https://github.com/jonbca (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('en-ca', { months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), longDateFormat : { LT : "h:mm A", L : "YYYY-MM-DD", LL : "D MMMM, YYYY", LLL : "D MMMM, YYYY LT", LLLL : "dddd, D MMMM, YYYY LT" }, calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, relativeTime : { future : "in %s", past : "%s ago", s : "a few seconds", m : "a minute", mm : "%d minutes", h : "an hour", hh : "%d hours", d : "a day", dd : "%d days", M : "a month", MM : "%d months", y : "a year", yy : "%d years" }, ordinal : function (number) { var b = number % 10, output = (~~ (number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); })); // moment.js language configuration // language : great britain english (en-gb) // author : Chris Gedrim : https://github.com/chrisgedrim (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('en-gb', { months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, relativeTime : { future : "in %s", past : "%s ago", s : "a few seconds", m : "a minute", mm : "%d minutes", h : "an hour", hh : "%d hours", d : "a day", dd : "%d days", M : "a month", MM : "%d months", y : "a year", yy : "%d years" }, ordinal : function (number) { var b = number % 10, output = (~~ (number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : esperanto (eo) // author : Colin Dean : https://github.com/colindean // komento: Mi estas malcerta se mi korekte traktis akuzativojn en tiu traduko. // Se ne, bonvolu korekti kaj avizi min por ke mi povas lerni! (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('eo', { months : "januaro_februaro_marto_aprilo_majo_junio_julio_aŭgusto_septembro_oktobro_novembro_decembro".split("_"), monthsShort : "jan_feb_mar_apr_maj_jun_jul_aŭg_sep_okt_nov_dec".split("_"), weekdays : "Dimanĉo_Lundo_Mardo_Merkredo_Ĵaŭdo_Vendredo_Sabato".split("_"), weekdaysShort : "Dim_Lun_Mard_Merk_Ĵaŭ_Ven_Sab".split("_"), weekdaysMin : "Di_Lu_Ma_Me_Ĵa_Ve_Sa".split("_"), longDateFormat : { LT : "HH:mm", L : "YYYY-MM-DD", LL : "D[-an de] MMMM, YYYY", LLL : "D[-an de] MMMM, YYYY LT", LLLL : "dddd, [la] D[-an de] MMMM, YYYY LT" }, meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'p.t.m.' : 'P.T.M.'; } else { return isLower ? 'a.t.m.' : 'A.T.M.'; } }, calendar : { sameDay : '[Hodiaŭ je] LT', nextDay : '[Morgaŭ je] LT', nextWeek : 'dddd [je] LT', lastDay : '[Hieraŭ je] LT', lastWeek : '[pasinta] dddd [je] LT', sameElse : 'L' }, relativeTime : { future : "je %s", past : "antaŭ %s", s : "sekundoj", m : "minuto", mm : "%d minutoj", h : "horo", hh : "%d horoj", d : "tago",//ne 'diurno', ĉar estas uzita por proksimumo dd : "%d tagoj", M : "monato", MM : "%d monatoj", y : "jaro", yy : "%d jaroj" }, ordinal : "%da", week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : spanish (es) // author : Julio Napurí : https://github.com/julionc (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('es', { months : "enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre".split("_"), monthsShort : "ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.".split("_"), weekdays : "domingo_lunes_martes_miércoles_jueves_viernes_sábado".split("_"), weekdaysShort : "dom._lun._mar._mié._jue._vie._sáb.".split("_"), weekdaysMin : "Do_Lu_Ma_Mi_Ju_Vi_Sá".split("_"), longDateFormat : { LT : "H:mm", L : "DD/MM/YYYY", LL : "D [de] MMMM [de] YYYY", LLL : "D [de] MMMM [de] YYYY LT", LLLL : "dddd, D [de] MMMM [de] YYYY LT" }, calendar : { sameDay : function () { return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextDay : function () { return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextWeek : function () { return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastDay : function () { return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastWeek : function () { return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, sameElse : 'L' }, relativeTime : { future : "en %s", past : "hace %s", s : "unos segundos", m : "un minuto", mm : "%d minutos", h : "una hora", hh : "%d horas", d : "un día", dd : "%d días", M : "un mes", MM : "%d meses", y : "un año", yy : "%d años" }, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : estonian (et) // author : Henry Kehlmann : https://github.com/madhenry // improvements : Illimar Tambek : https://github.com/ragulka (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function processRelativeTime(number, withoutSuffix, key, isFuture) { var format = { 's' : ['mõne sekundi', 'mõni sekund', 'paar sekundit'], 'm' : ['ühe minuti', 'üks minut'], 'mm': [number + ' minuti', number + ' minutit'], 'h' : ['ühe tunni', 'tund aega', 'üks tund'], 'hh': [number + ' tunni', number + ' tundi'], 'd' : ['ühe päeva', 'üks päev'], 'M' : ['kuu aja', 'kuu aega', 'üks kuu'], 'MM': [number + ' kuu', number + ' kuud'], 'y' : ['ühe aasta', 'aasta', 'üks aasta'], 'yy': [number + ' aasta', number + ' aastat'] }; if (withoutSuffix) { return format[key][2] ? format[key][2] : format[key][1]; } return isFuture ? format[key][0] : format[key][1]; } return moment.lang('et', { months : "jaanuar_veebruar_märts_aprill_mai_juuni_juuli_august_september_oktoober_november_detsember".split("_"), monthsShort : "jaan_veebr_märts_apr_mai_juuni_juuli_aug_sept_okt_nov_dets".split("_"), weekdays : "pühapäev_esmaspäev_teisipäev_kolmapäev_neljapäev_reede_laupäev".split("_"), weekdaysShort : "P_E_T_K_N_R_L".split("_"), weekdaysMin : "P_E_T_K_N_R_L".split("_"), longDateFormat : { LT : "H:mm", L : "DD.MM.YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay : '[Täna,] LT', nextDay : '[Homme,] LT', nextWeek : '[Järgmine] dddd LT', lastDay : '[Eile,] LT', lastWeek : '[Eelmine] dddd LT', sameElse : 'L' }, relativeTime : { future : "%s pärast", past : "%s tagasi", s : processRelativeTime, m : processRelativeTime, mm : processRelativeTime, h : processRelativeTime, hh : processRelativeTime, d : processRelativeTime, dd : '%d päeva', M : processRelativeTime, MM : processRelativeTime, y : processRelativeTime, yy : processRelativeTime }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : euskara (eu) // author : Eneko Illarramendi : https://github.com/eillarra (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('eu', { months : "urtarrila_otsaila_martxoa_apirila_maiatza_ekaina_uztaila_abuztua_iraila_urria_azaroa_abendua".split("_"), monthsShort : "urt._ots._mar._api._mai._eka._uzt._abu._ira._urr._aza._abe.".split("_"), weekdays : "igandea_astelehena_asteartea_asteazkena_osteguna_ostirala_larunbata".split("_"), weekdaysShort : "ig._al._ar._az._og._ol._lr.".split("_"), weekdaysMin : "ig_al_ar_az_og_ol_lr".split("_"), longDateFormat : { LT : "HH:mm", L : "YYYY-MM-DD", LL : "YYYY[ko] MMMM[ren] D[a]", LLL : "YYYY[ko] MMMM[ren] D[a] LT", LLLL : "dddd, YYYY[ko] MMMM[ren] D[a] LT", l : "YYYY-M-D", ll : "YYYY[ko] MMM D[a]", lll : "YYYY[ko] MMM D[a] LT", llll : "ddd, YYYY[ko] MMM D[a] LT" }, calendar : { sameDay : '[gaur] LT[etan]', nextDay : '[bihar] LT[etan]', nextWeek : 'dddd LT[etan]', lastDay : '[atzo] LT[etan]', lastWeek : '[aurreko] dddd LT[etan]', sameElse : 'L' }, relativeTime : { future : "%s barru", past : "duela %s", s : "segundo batzuk", m : "minutu bat", mm : "%d minutu", h : "ordu bat", hh : "%d ordu", d : "egun bat", dd : "%d egun", M : "hilabete bat", MM : "%d hilabete", y : "urte bat", yy : "%d urte" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Persian Language // author : Ebrahim Byagowi : https://github.com/ebraminio (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var symbolMap = { '1': '۱', '2': '۲', '3': '۳', '4': '۴', '5': '۵', '6': '۶', '7': '۷', '8': '۸', '9': '۹', '0': '۰' }, numberMap = { '۱': '1', '۲': '2', '۳': '3', '۴': '4', '۵': '5', '۶': '6', '۷': '7', '۸': '8', '۹': '9', '۰': '0' }; return moment.lang('fa', { months : 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'), monthsShort : 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'), weekdays : 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'), weekdaysShort : 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'), weekdaysMin : 'ی_د_س_چ_پ_ج_ش'.split('_'), longDateFormat : { LT : 'HH:mm', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY LT', LLLL : 'dddd, D MMMM YYYY LT' }, meridiem : function (hour, minute, isLower) { if (hour < 12) { return "قبل از ظهر"; } else { return "بعد از ظهر"; } }, calendar : { sameDay : '[امروز ساعت] LT', nextDay : '[فردا ساعت] LT', nextWeek : 'dddd [ساعت] LT', lastDay : '[دیروز ساعت] LT', lastWeek : 'dddd [پیش] [ساعت] LT', sameElse : 'L' }, relativeTime : { future : 'در %s', past : '%s پیش', s : 'چندین ثانیه', m : 'یک دقیقه', mm : '%d دقیقه', h : 'یک ساعت', hh : '%d ساعت', d : 'یک روز', dd : '%d روز', M : 'یک ماه', MM : '%d ماه', y : 'یک سال', yy : '%d سال' }, preparse: function (string) { return string.replace(/[۰-۹]/g, function (match) { return numberMap[match]; }).replace(/،/g, ','); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }).replace(/,/g, '،'); }, ordinal : '%dم', week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : finnish (fi) // author : Tarmo Aidantausta : https://github.com/bleadof (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var numbers_past = 'nolla yksi kaksi kolme neljä viisi kuusi seitsemän kahdeksan yhdeksän'.split(' '), numbers_future = ['nolla', 'yhden', 'kahden', 'kolmen', 'neljän', 'viiden', 'kuuden', numbers_past[7], numbers_past[8], numbers_past[9]]; function translate(number, withoutSuffix, key, isFuture) { var result = ""; switch (key) { case 's': return isFuture ? 'muutaman sekunnin' : 'muutama sekunti'; case 'm': return isFuture ? 'minuutin' : 'minuutti'; case 'mm': result = isFuture ? 'minuutin' : 'minuuttia'; break; case 'h': return isFuture ? 'tunnin' : 'tunti'; case 'hh': result = isFuture ? 'tunnin' : 'tuntia'; break; case 'd': return isFuture ? 'päivän' : 'päivä'; case 'dd': result = isFuture ? 'päivän' : 'päivää'; break; case 'M': return isFuture ? 'kuukauden' : 'kuukausi'; case 'MM': result = isFuture ? 'kuukauden' : 'kuukautta'; break; case 'y': return isFuture ? 'vuoden' : 'vuosi'; case 'yy': result = isFuture ? 'vuoden' : 'vuotta'; break; } result = verbal_number(number, isFuture) + " " + result; return result; } function verbal_number(number, isFuture) { return number < 10 ? (isFuture ? numbers_future[number] : numbers_past[number]) : number; } return moment.lang('fi', { months : "tammikuu_helmikuu_maaliskuu_huhtikuu_toukokuu_kesäkuu_heinäkuu_elokuu_syyskuu_lokakuu_marraskuu_joulukuu".split("_"), monthsShort : "tammi_helmi_maalis_huhti_touko_kesä_heinä_elo_syys_loka_marras_joulu".split("_"), weekdays : "sunnuntai_maanantai_tiistai_keskiviikko_torstai_perjantai_lauantai".split("_"), weekdaysShort : "su_ma_ti_ke_to_pe_la".split("_"), weekdaysMin : "su_ma_ti_ke_to_pe_la".split("_"), longDateFormat : { LT : "HH.mm", L : "DD.MM.YYYY", LL : "Do MMMM[ta] YYYY", LLL : "Do MMMM[ta] YYYY, [klo] LT", LLLL : "dddd, Do MMMM[ta] YYYY, [klo] LT", l : "D.M.YYYY", ll : "Do MMM YYYY", lll : "Do MMM YYYY, [klo] LT", llll : "ddd, Do MMM YYYY, [klo] LT" }, calendar : { sameDay : '[tänään] [klo] LT', nextDay : '[huomenna] [klo] LT', nextWeek : 'dddd [klo] LT', lastDay : '[eilen] [klo] LT', lastWeek : '[viime] dddd[na] [klo] LT', sameElse : 'L' }, relativeTime : { future : "%s päästä", past : "%s sitten", s : translate, m : translate, mm : translate, h : translate, hh : translate, d : translate, dd : translate, M : translate, MM : translate, y : translate, yy : translate }, ordinal : "%d.", week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : faroese (fo) // author : Ragnar Johannesen : https://github.com/ragnar123 (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('fo', { months : "januar_februar_mars_apríl_mai_juni_juli_august_september_oktober_november_desember".split("_"), monthsShort : "jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"), weekdays : "sunnudagur_mánadagur_týsdagur_mikudagur_hósdagur_fríggjadagur_leygardagur".split("_"), weekdaysShort : "sun_mán_týs_mik_hós_frí_ley".split("_"), weekdaysMin : "su_má_tý_mi_hó_fr_le".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D. MMMM, YYYY LT" }, calendar : { sameDay : '[Í dag kl.] LT', nextDay : '[Í morgin kl.] LT', nextWeek : 'dddd [kl.] LT', lastDay : '[Í gjár kl.] LT', lastWeek : '[síðstu] dddd [kl] LT', sameElse : 'L' }, relativeTime : { future : "um %s", past : "%s síðani", s : "fá sekund", m : "ein minutt", mm : "%d minuttir", h : "ein tími", hh : "%d tímar", d : "ein dagur", dd : "%d dagar", M : "ein mánaði", MM : "%d mánaðir", y : "eitt ár", yy : "%d ár" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : canadian french (fr-ca) // author : Jonathan Abourbih : https://github.com/jonbca (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('fr-ca', { months : "janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"), monthsShort : "janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"), weekdays : "dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"), weekdaysShort : "dim._lun._mar._mer._jeu._ven._sam.".split("_"), weekdaysMin : "Di_Lu_Ma_Me_Je_Ve_Sa".split("_"), longDateFormat : { LT : "HH:mm", L : "YYYY-MM-DD", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[Aujourd'hui à] LT", nextDay: '[Demain à] LT', nextWeek: 'dddd [à] LT', lastDay: '[Hier à] LT', lastWeek: 'dddd [dernier à] LT', sameElse: 'L' }, relativeTime : { future : "dans %s", past : "il y a %s", s : "quelques secondes", m : "une minute", mm : "%d minutes", h : "une heure", hh : "%d heures", d : "un jour", dd : "%d jours", M : "un mois", MM : "%d mois", y : "un an", yy : "%d ans" }, ordinal : function (number) { return number + (number === 1 ? 'er' : ''); } }); })); // moment.js language configuration // language : french (fr) // author : John Fischer : https://github.com/jfroffice (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('fr', { months : "janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"), monthsShort : "janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"), weekdays : "dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"), weekdaysShort : "dim._lun._mar._mer._jeu._ven._sam.".split("_"), weekdaysMin : "Di_Lu_Ma_Me_Je_Ve_Sa".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[Aujourd'hui à] LT", nextDay: '[Demain à] LT', nextWeek: 'dddd [à] LT', lastDay: '[Hier à] LT', lastWeek: 'dddd [dernier à] LT', sameElse: 'L' }, relativeTime : { future : "dans %s", past : "il y a %s", s : "quelques secondes", m : "une minute", mm : "%d minutes", h : "une heure", hh : "%d heures", d : "un jour", dd : "%d jours", M : "un mois", MM : "%d mois", y : "un an", yy : "%d ans" }, ordinal : function (number) { return number + (number === 1 ? 'er' : ''); }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : galician (gl) // author : Juan G. Hurtado : https://github.com/juanghurtado (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('gl', { months : "Xaneiro_Febreiro_Marzo_Abril_Maio_Xuño_Xullo_Agosto_Setembro_Outubro_Novembro_Decembro".split("_"), monthsShort : "Xan._Feb._Mar._Abr._Mai._Xuñ._Xul._Ago._Set._Out._Nov._Dec.".split("_"), weekdays : "Domingo_Luns_Martes_Mércores_Xoves_Venres_Sábado".split("_"), weekdaysShort : "Dom._Lun._Mar._Mér._Xov._Ven._Sáb.".split("_"), weekdaysMin : "Do_Lu_Ma_Mé_Xo_Ve_Sá".split("_"), longDateFormat : { LT : "H:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay : function () { return '[hoxe ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT'; }, nextDay : function () { return '[mañá ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT'; }, nextWeek : function () { return 'dddd [' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT'; }, lastDay : function () { return '[onte ' + ((this.hours() !== 1) ? 'á' : 'a') + '] LT'; }, lastWeek : function () { return '[o] dddd [pasado ' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT'; }, sameElse : 'L' }, relativeTime : { future : function (str) { if (str === "uns segundos") { return "nuns segundos"; } return "en " + str; }, past : "hai %s", s : "uns segundos", m : "un minuto", mm : "%d minutos", h : "unha hora", hh : "%d horas", d : "un día", dd : "%d días", M : "un mes", MM : "%d meses", y : "un ano", yy : "%d anos" }, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Hebrew (he) // author : Tomer Cohen : https://github.com/tomer // author : Moshe Simantov : https://github.com/DevelopmentIL // author : Tal Ater : https://github.com/TalAter (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('he', { months : "ינואר_פברואר_מרץ_אפריל_מאי_יוני_יולי_אוגוסט_ספטמבר_אוקטובר_נובמבר_דצמבר".split("_"), monthsShort : "ינו׳_פבר׳_מרץ_אפר׳_מאי_יוני_יולי_אוג׳_ספט׳_אוק׳_נוב׳_דצמ׳".split("_"), weekdays : "ראשון_שני_שלישי_רביעי_חמישי_שישי_שבת".split("_"), weekdaysShort : "א׳_ב׳_ג׳_ד׳_ה׳_ו׳_ש׳".split("_"), weekdaysMin : "א_ב_ג_ד_ה_ו_ש".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D [ב]MMMM YYYY", LLL : "D [ב]MMMM YYYY LT", LLLL : "dddd, D [ב]MMMM YYYY LT", l : "D/M/YYYY", ll : "D MMM YYYY", lll : "D MMM YYYY LT", llll : "ddd, D MMM YYYY LT" }, calendar : { sameDay : '[היום ב־]LT', nextDay : '[מחר ב־]LT', nextWeek : 'dddd [בשעה] LT', lastDay : '[אתמול ב־]LT', lastWeek : '[ביום] dddd [האחרון בשעה] LT', sameElse : 'L' }, relativeTime : { future : "בעוד %s", past : "לפני %s", s : "מספר שניות", m : "דקה", mm : "%d דקות", h : "שעה", hh : function (number) { if (number === 2) { return "שעתיים"; } return number + " שעות"; }, d : "יום", dd : function (number) { if (number === 2) { return "יומיים"; } return number + " ימים"; }, M : "חודש", MM : function (number) { if (number === 2) { return "חודשיים"; } return number + " חודשים"; }, y : "שנה", yy : function (number) { if (number === 2) { return "שנתיים"; } return number + " שנים"; } } }); })); // moment.js language configuration // language : hindi (hi) // author : Mayank Singhal : https://github.com/mayanksinghal (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var symbolMap = { '1': '१', '2': '२', '3': '३', '4': '४', '5': '५', '6': '६', '7': '७', '8': '८', '9': '९', '0': '०' }, numberMap = { '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9', '०': '0' }; return moment.lang('hi', { months : 'जनवरी_फ़रवरी_मार्च_अप्रैल_मई_जून_जुलाई_अगस्त_सितम्बर_अक्टूबर_नवम्बर_दिसम्बर'.split("_"), monthsShort : 'जन._फ़र._मार्च_अप्रै._मई_जून_जुल._अग._सित._अक्टू._नव._दिस.'.split("_"), weekdays : 'रविवार_सोमवार_मंगलवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split("_"), weekdaysShort : 'रवि_सोम_मंगल_बुध_गुरू_शुक्र_शनि'.split("_"), weekdaysMin : 'र_सो_मं_बु_गु_शु_श'.split("_"), longDateFormat : { LT : "A h:mm बजे", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY, LT", LLLL : "dddd, D MMMM YYYY, LT" }, calendar : { sameDay : '[आज] LT', nextDay : '[कल] LT', nextWeek : 'dddd, LT', lastDay : '[कल] LT', lastWeek : '[पिछले] dddd, LT', sameElse : 'L' }, relativeTime : { future : "%s में", past : "%s पहले", s : "कुछ ही क्षण", m : "एक मिनट", mm : "%d मिनट", h : "एक घंटा", hh : "%d घंटे", d : "एक दिन", dd : "%d दिन", M : "एक महीने", MM : "%d महीने", y : "एक वर्ष", yy : "%d वर्ष" }, preparse: function (string) { return string.replace(/[१२३४५६७८९०]/g, function (match) { return numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }); }, // Hindi notation for meridiems are quite fuzzy in practice. While there exists // a rigid notion of a 'Pahar' it is not used as rigidly in modern Hindi. meridiem : function (hour, minute, isLower) { if (hour < 4) { return "रात"; } else if (hour < 10) { return "सुबह"; } else if (hour < 17) { return "दोपहर"; } else if (hour < 20) { return "शाम"; } else { return "रात"; } }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : hrvatski (hr) // author : Bojan Marković : https://github.com/bmarkovic // based on (sl) translation by Robert Sedovšek (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function translate(number, withoutSuffix, key) { var result = number + " "; switch (key) { case 'm': return withoutSuffix ? 'jedna minuta' : 'jedne minute'; case 'mm': if (number === 1) { result += 'minuta'; } else if (number === 2 || number === 3 || number === 4) { result += 'minute'; } else { result += 'minuta'; } return result; case 'h': return withoutSuffix ? 'jedan sat' : 'jednog sata'; case 'hh': if (number === 1) { result += 'sat'; } else if (number === 2 || number === 3 || number === 4) { result += 'sata'; } else { result += 'sati'; } return result; case 'dd': if (number === 1) { result += 'dan'; } else { result += 'dana'; } return result; case 'MM': if (number === 1) { result += 'mjesec'; } else if (number === 2 || number === 3 || number === 4) { result += 'mjeseca'; } else { result += 'mjeseci'; } return result; case 'yy': if (number === 1) { result += 'godina'; } else if (number === 2 || number === 3 || number === 4) { result += 'godine'; } else { result += 'godina'; } return result; } } return moment.lang('hr', { months : "sječanj_veljača_ožujak_travanj_svibanj_lipanj_srpanj_kolovoz_rujan_listopad_studeni_prosinac".split("_"), monthsShort : "sje._vel._ožu._tra._svi._lip._srp._kol._ruj._lis._stu._pro.".split("_"), weekdays : "nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota".split("_"), weekdaysShort : "ned._pon._uto._sri._čet._pet._sub.".split("_"), weekdaysMin : "ne_po_ut_sr_če_pe_su".split("_"), longDateFormat : { LT : "H:mm", L : "DD. MM. YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay : '[danas u] LT', nextDay : '[sutra u] LT', nextWeek : function () { switch (this.day()) { case 0: return '[u] [nedjelju] [u] LT'; case 3: return '[u] [srijedu] [u] LT'; case 6: return '[u] [subotu] [u] LT'; case 1: case 2: case 4: case 5: return '[u] dddd [u] LT'; } }, lastDay : '[jučer u] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: return '[prošlu] dddd [u] LT'; case 6: return '[prošle] [subote] [u] LT'; case 1: case 2: case 4: case 5: return '[prošli] dddd [u] LT'; } }, sameElse : 'L' }, relativeTime : { future : "za %s", past : "prije %s", s : "par sekundi", m : translate, mm : translate, h : translate, hh : translate, d : "dan", dd : translate, M : "mjesec", MM : translate, y : "godinu", yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : hungarian (hu) // author : Adam Brunner : https://github.com/adambrunner (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var weekEndings = 'vasárnap hétfőn kedden szerdán csütörtökön pénteken szombaton'.split(' '); function translate(number, withoutSuffix, key, isFuture) { var num = number, suffix; switch (key) { case 's': return (isFuture || withoutSuffix) ? 'néhány másodperc' : 'néhány másodperce'; case 'm': return 'egy' + (isFuture || withoutSuffix ? ' perc' : ' perce'); case 'mm': return num + (isFuture || withoutSuffix ? ' perc' : ' perce'); case 'h': return 'egy' + (isFuture || withoutSuffix ? ' óra' : ' órája'); case 'hh': return num + (isFuture || withoutSuffix ? ' óra' : ' órája'); case 'd': return 'egy' + (isFuture || withoutSuffix ? ' nap' : ' napja'); case 'dd': return num + (isFuture || withoutSuffix ? ' nap' : ' napja'); case 'M': return 'egy' + (isFuture || withoutSuffix ? ' hónap' : ' hónapja'); case 'MM': return num + (isFuture || withoutSuffix ? ' hónap' : ' hónapja'); case 'y': return 'egy' + (isFuture || withoutSuffix ? ' év' : ' éve'); case 'yy': return num + (isFuture || withoutSuffix ? ' év' : ' éve'); } return ''; } function week(isFuture) { return (isFuture ? '' : '[múlt] ') + '[' + weekEndings[this.day()] + '] LT[-kor]'; } return moment.lang('hu', { months : "január_február_március_április_május_június_július_augusztus_szeptember_október_november_december".split("_"), monthsShort : "jan_feb_márc_ápr_máj_jún_júl_aug_szept_okt_nov_dec".split("_"), weekdays : "vasárnap_hétfő_kedd_szerda_csütörtök_péntek_szombat".split("_"), weekdaysShort : "vas_hét_kedd_sze_csüt_pén_szo".split("_"), weekdaysMin : "v_h_k_sze_cs_p_szo".split("_"), longDateFormat : { LT : "H:mm", L : "YYYY.MM.DD.", LL : "YYYY. MMMM D.", LLL : "YYYY. MMMM D., LT", LLLL : "YYYY. MMMM D., dddd LT" }, calendar : { sameDay : '[ma] LT[-kor]', nextDay : '[holnap] LT[-kor]', nextWeek : function () { return week.call(this, true); }, lastDay : '[tegnap] LT[-kor]', lastWeek : function () { return week.call(this, false); }, sameElse : 'L' }, relativeTime : { future : "%s múlva", past : "%s", s : translate, m : translate, mm : translate, h : translate, hh : translate, d : translate, dd : translate, M : translate, MM : translate, y : translate, yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Armenian (hy-am) // author : Armendarabyan : https://github.com/armendarabyan (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function monthsCaseReplace(m, format) { var months = { 'nominative': 'հունվար_փետրվար_մարտ_ապրիլ_մայիս_հունիս_հուլիս_օգոստոս_սեպտեմբեր_հոկտեմբեր_նոյեմբեր_դեկտեմբեր'.split('_'), 'accusative': 'հունվարի_փետրվարի_մարտի_ապրիլի_մայիսի_հունիսի_հուլիսի_օգոստոսի_սեպտեմբերի_հոկտեմբերի_նոյեմբերի_դեկտեմբերի'.split('_') }, nounCase = (/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/).test(format) ? 'accusative' : 'nominative'; return months[nounCase][m.month()]; } function monthsShortCaseReplace(m, format) { var monthsShort = 'հնվ_փտր_մրտ_ապր_մյս_հնս_հլս_օգս_սպտ_հկտ_նմբ_դկտ'.split('_'); return monthsShort[m.month()]; } function weekdaysCaseReplace(m, format) { var weekdays = 'կիրակի_երկուշաբթի_երեքշաբթի_չորեքշաբթի_հինգշաբթի_ուրբաթ_շաբաթ'.split('_'); return weekdays[m.day()]; } return moment.lang('hy-am', { months : monthsCaseReplace, monthsShort : monthsShortCaseReplace, weekdays : weekdaysCaseReplace, weekdaysShort : "կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ".split("_"), weekdaysMin : "կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY թ.", LLL : "D MMMM YYYY թ., LT", LLLL : "dddd, D MMMM YYYY թ., LT" }, calendar : { sameDay: '[այսօր] LT', nextDay: '[վաղը] LT', lastDay: '[երեկ] LT', nextWeek: function () { return 'dddd [օրը ժամը] LT'; }, lastWeek: function () { return '[անցած] dddd [օրը ժամը] LT'; }, sameElse: 'L' }, relativeTime : { future : "%s հետո", past : "%s առաջ", s : "մի քանի վայրկյան", m : "րոպե", mm : "%d րոպե", h : "ժամ", hh : "%d ժամ", d : "օր", dd : "%d օր", M : "ամիս", MM : "%d ամիս", y : "տարի", yy : "%d տարի" }, meridiem : function (hour) { if (hour < 4) { return "գիշերվա"; } else if (hour < 12) { return "առավոտվա"; } else if (hour < 17) { return "ցերեկվա"; } else { return "երեկոյան"; } }, ordinal: function (number, period) { switch (period) { case 'DDD': case 'w': case 'W': case 'DDDo': if (number === 1) { return number + '-ին'; } return number + '-րդ'; default: return number; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Bahasa Indonesia (id) // author : Mohammad Satrio Utomo : https://github.com/tyok // reference: http://id.wikisource.org/wiki/Pedoman_Umum_Ejaan_Bahasa_Indonesia_yang_Disempurnakan (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('id', { months : "Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_November_Desember".split("_"), monthsShort : "Jan_Feb_Mar_Apr_Mei_Jun_Jul_Ags_Sep_Okt_Nov_Des".split("_"), weekdays : "Minggu_Senin_Selasa_Rabu_Kamis_Jumat_Sabtu".split("_"), weekdaysShort : "Min_Sen_Sel_Rab_Kam_Jum_Sab".split("_"), weekdaysMin : "Mg_Sn_Sl_Rb_Km_Jm_Sb".split("_"), longDateFormat : { LT : "HH.mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY [pukul] LT", LLLL : "dddd, D MMMM YYYY [pukul] LT" }, meridiem : function (hours, minutes, isLower) { if (hours < 11) { return 'pagi'; } else if (hours < 15) { return 'siang'; } else if (hours < 19) { return 'sore'; } else { return 'malam'; } }, calendar : { sameDay : '[Hari ini pukul] LT', nextDay : '[Besok pukul] LT', nextWeek : 'dddd [pukul] LT', lastDay : '[Kemarin pukul] LT', lastWeek : 'dddd [lalu pukul] LT', sameElse : 'L' }, relativeTime : { future : "dalam %s", past : "%s yang lalu", s : "beberapa detik", m : "semenit", mm : "%d menit", h : "sejam", hh : "%d jam", d : "sehari", dd : "%d hari", M : "sebulan", MM : "%d bulan", y : "setahun", yy : "%d tahun" }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : icelandic (is) // author : Hinrik Örn Sigurðsson : https://github.com/hinrik (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function plural(n) { if (n % 100 === 11) { return true; } else if (n % 10 === 1) { return false; } return true; } function translate(number, withoutSuffix, key, isFuture) { var result = number + " "; switch (key) { case 's': return withoutSuffix || isFuture ? 'nokkrar sekúndur' : 'nokkrum sekúndum'; case 'm': return withoutSuffix ? 'mínúta' : 'mínútu'; case 'mm': if (plural(number)) { return result + (withoutSuffix || isFuture ? 'mínútur' : 'mínútum'); } else if (withoutSuffix) { return result + 'mínúta'; } return result + 'mínútu'; case 'hh': if (plural(number)) { return result + (withoutSuffix || isFuture ? 'klukkustundir' : 'klukkustundum'); } return result + 'klukkustund'; case 'd': if (withoutSuffix) { return 'dagur'; } return isFuture ? 'dag' : 'degi'; case 'dd': if (plural(number)) { if (withoutSuffix) { return result + 'dagar'; } return result + (isFuture ? 'daga' : 'dögum'); } else if (withoutSuffix) { return result + 'dagur'; } return result + (isFuture ? 'dag' : 'degi'); case 'M': if (withoutSuffix) { return 'mánuður'; } return isFuture ? 'mánuð' : 'mánuði'; case 'MM': if (plural(number)) { if (withoutSuffix) { return result + 'mánuðir'; } return result + (isFuture ? 'mánuði' : 'mánuðum'); } else if (withoutSuffix) { return result + 'mánuður'; } return result + (isFuture ? 'mánuð' : 'mánuði'); case 'y': return withoutSuffix || isFuture ? 'ár' : 'ári'; case 'yy': if (plural(number)) { return result + (withoutSuffix || isFuture ? 'ár' : 'árum'); } return result + (withoutSuffix || isFuture ? 'ár' : 'ári'); } } return moment.lang('is', { months : "janúar_febrúar_mars_apríl_maí_júní_júlí_ágúst_september_október_nóvember_desember".split("_"), monthsShort : "jan_feb_mar_apr_maí_jún_júl_ágú_sep_okt_nóv_des".split("_"), weekdays : "sunnudagur_mánudagur_þriðjudagur_miðvikudagur_fimmtudagur_föstudagur_laugardagur".split("_"), weekdaysShort : "sun_mán_þri_mið_fim_fös_lau".split("_"), weekdaysMin : "Su_Má_Þr_Mi_Fi_Fö_La".split("_"), longDateFormat : { LT : "H:mm", L : "DD/MM/YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY [kl.] LT", LLLL : "dddd, D. MMMM YYYY [kl.] LT" }, calendar : { sameDay : '[í dag kl.] LT', nextDay : '[á morgun kl.] LT', nextWeek : 'dddd [kl.] LT', lastDay : '[í gær kl.] LT', lastWeek : '[síðasta] dddd [kl.] LT', sameElse : 'L' }, relativeTime : { future : "eftir %s", past : "fyrir %s síðan", s : translate, m : translate, mm : translate, h : "klukkustund", hh : translate, d : translate, dd : translate, M : translate, MM : translate, y : translate, yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : italian (it) // author : Lorenzo : https://github.com/aliem // author: Mattia Larentis: https://github.com/nostalgiaz (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('it', { months : "Gennaio_Febbraio_Marzo_Aprile_Maggio_Giugno_Luglio_Agosto_Settembre_Ottobre_Novembre_Dicembre".split("_"), monthsShort : "Gen_Feb_Mar_Apr_Mag_Giu_Lug_Ago_Set_Ott_Nov_Dic".split("_"), weekdays : "Domenica_Lunedì_Martedì_Mercoledì_Giovedì_Venerdì_Sabato".split("_"), weekdaysShort : "Dom_Lun_Mar_Mer_Gio_Ven_Sab".split("_"), weekdaysMin : "D_L_Ma_Me_G_V_S".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay: '[Oggi alle] LT', nextDay: '[Domani alle] LT', nextWeek: 'dddd [alle] LT', lastDay: '[Ieri alle] LT', lastWeek: '[lo scorso] dddd [alle] LT', sameElse: 'L' }, relativeTime : { future : function (s) { return ((/^[0-9].+$/).test(s) ? "tra" : "in") + " " + s; }, past : "%s fa", s : "alcuni secondi", m : "un minuto", mm : "%d minuti", h : "un'ora", hh : "%d ore", d : "un giorno", dd : "%d giorni", M : "un mese", MM : "%d mesi", y : "un anno", yy : "%d anni" }, ordinal: '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : japanese (ja) // author : LI Long : https://github.com/baryon (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('ja', { months : "1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"), monthsShort : "1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"), weekdays : "日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日".split("_"), weekdaysShort : "日_月_火_水_木_金_土".split("_"), weekdaysMin : "日_月_火_水_木_金_土".split("_"), longDateFormat : { LT : "Ah時m分", L : "YYYY/MM/DD", LL : "YYYY年M月D日", LLL : "YYYY年M月D日LT", LLLL : "YYYY年M月D日LT dddd" }, meridiem : function (hour, minute, isLower) { if (hour < 12) { return "午前"; } else { return "午後"; } }, calendar : { sameDay : '[今日] LT', nextDay : '[明日] LT', nextWeek : '[来週]dddd LT', lastDay : '[昨日] LT', lastWeek : '[前週]dddd LT', sameElse : 'L' }, relativeTime : { future : "%s後", past : "%s前", s : "数秒", m : "1分", mm : "%d分", h : "1時間", hh : "%d時間", d : "1日", dd : "%d日", M : "1ヶ月", MM : "%dヶ月", y : "1年", yy : "%d年" } }); })); // moment.js language configuration // language : Georgian (ka) // author : Irakli Janiashvili : https://github.com/irakli-janiashvili (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function monthsCaseReplace(m, format) { var months = { 'nominative': 'იანვარი_თებერვალი_მარტი_აპრილი_მაისი_ივნისი_ივლისი_აგვისტო_სექტემბერი_ოქტომბერი_ნოემბერი_დეკემბერი'.split('_'), 'accusative': 'იანვარს_თებერვალს_მარტს_აპრილის_მაისს_ივნისს_ივლისს_აგვისტს_სექტემბერს_ოქტომბერს_ნოემბერს_დეკემბერს'.split('_') }, nounCase = (/D[oD] *MMMM?/).test(format) ? 'accusative' : 'nominative'; return months[nounCase][m.month()]; } function weekdaysCaseReplace(m, format) { var weekdays = { 'nominative': 'კვირა_ორშაბათი_სამშაბათი_ოთხშაბათი_ხუთშაბათი_პარასკევი_შაბათი'.split('_'), 'accusative': 'კვირას_ორშაბათს_სამშაბათს_ოთხშაბათს_ხუთშაბათს_პარასკევს_შაბათს'.split('_') }, nounCase = (/(წინა|შემდეგ)/).test(format) ? 'accusative' : 'nominative'; return weekdays[nounCase][m.day()]; } return moment.lang('ka', { months : monthsCaseReplace, monthsShort : "იან_თებ_მარ_აპრ_მაი_ივნ_ივლ_აგვ_სექ_ოქტ_ნოე_დეკ".split("_"), weekdays : weekdaysCaseReplace, weekdaysShort : "კვი_ორშ_სამ_ოთხ_ხუთ_პარ_შაბ".split("_"), weekdaysMin : "კვ_ორ_სა_ოთ_ხუ_პა_შა".split("_"), longDateFormat : { LT : "h:mm A", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[დღეს] LT[-ზე]', nextDay : '[ხვალ] LT[-ზე]', lastDay : '[გუშინ] LT[-ზე]', nextWeek : '[შემდეგ] dddd LT[-ზე]', lastWeek : '[წინა] dddd LT-ზე', sameElse : 'L' }, relativeTime : { future : function (s) { return (/(წამი|წუთი|საათი|წელი)/).test(s) ? s.replace(/ი$/, "ში") : s + "ში"; }, past : function (s) { if ((/(წამი|წუთი|საათი|დღე|თვე)/).test(s)) { return s.replace(/(ი|ე)$/, "ის წინ"); } if ((/წელი/).test(s)) { return s.replace(/წელი$/, "წლის წინ"); } }, s : "რამდენიმე წამი", m : "წუთი", mm : "%d წუთი", h : "საათი", hh : "%d საათი", d : "დღე", dd : "%d დღე", M : "თვე", MM : "%d თვე", y : "წელი", yy : "%d წელი" }, ordinal : function (number) { if (number === 0) { return number; } if (number === 1) { return number + "-ლი"; } if ((number < 20) || (number <= 100 && (number % 20 === 0)) || (number % 100 === 0)) { return "მე-" + number; } return number + "-ე"; }, week : { dow : 1, doy : 7 } }); })); // moment.js language configuration // language : korean (ko) // // authors // // - Kyungwook, Park : https://github.com/kyungw00k // - Jeeeyul Lee <jeeeyul@gmail.com> (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('ko', { months : "1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"), monthsShort : "1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"), weekdays : "일요일_월요일_화요일_수요일_목요일_금요일_토요일".split("_"), weekdaysShort : "일_월_화_수_목_금_토".split("_"), weekdaysMin : "일_월_화_수_목_금_토".split("_"), longDateFormat : { LT : "A h시 mm분", L : "YYYY.MM.DD", LL : "YYYY년 MMMM D일", LLL : "YYYY년 MMMM D일 LT", LLLL : "YYYY년 MMMM D일 dddd LT" }, meridiem : function (hour, minute, isUpper) { return hour < 12 ? '오전' : '오후'; }, calendar : { sameDay : '오늘 LT', nextDay : '내일 LT', nextWeek : 'dddd LT', lastDay : '어제 LT', lastWeek : '지난주 dddd LT', sameElse : 'L' }, relativeTime : { future : "%s 후", past : "%s 전", s : "몇초", ss : "%d초", m : "일분", mm : "%d분", h : "한시간", hh : "%d시간", d : "하루", dd : "%d일", M : "한달", MM : "%d달", y : "일년", yy : "%d년" }, ordinal : '%d일', meridiemParse : /(오전|오후)/, isPM : function (token) { return token === "오후"; } }); })); // moment.js language configuration // language : Luxembourgish (lb) // author : mweimerskirch : https://github.com/mweimerskirch // Note: Luxembourgish has a very particular phonological rule ("Eifeler Regel") that causes the // deletion of the final "n" in certain contexts. That's what the "eifelerRegelAppliesToWeekday" // and "eifelerRegelAppliesToNumber" methods are meant for (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function processRelativeTime(number, withoutSuffix, key, isFuture) { var format = { 'm': ['eng Minutt', 'enger Minutt'], 'h': ['eng Stonn', 'enger Stonn'], 'd': ['een Dag', 'engem Dag'], 'dd': [number + ' Deeg', number + ' Deeg'], 'M': ['ee Mount', 'engem Mount'], 'MM': [number + ' Méint', number + ' Méint'], 'y': ['ee Joer', 'engem Joer'], 'yy': [number + ' Joer', number + ' Joer'] }; return withoutSuffix ? format[key][0] : format[key][1]; } function processFutureTime(string) { var number = string.substr(0, string.indexOf(' ')); if (eifelerRegelAppliesToNumber(number)) { return "a " + string; } return "an " + string; } function processPastTime(string) { var number = string.substr(0, string.indexOf(' ')); if (eifelerRegelAppliesToNumber(number)) { return "viru " + string; } return "virun " + string; } function processLastWeek(string1) { var weekday = this.format('d'); if (eifelerRegelAppliesToWeekday(weekday)) { return '[Leschte] dddd [um] LT'; } return '[Leschten] dddd [um] LT'; } /** * Returns true if the word before the given week day loses the "-n" ending. * e.g. "Leschten Dënschdeg" but "Leschte Méindeg" * * @param weekday {integer} * @returns {boolean} */ function eifelerRegelAppliesToWeekday(weekday) { weekday = parseInt(weekday, 10); switch (weekday) { case 0: // Sonndeg case 1: // Méindeg case 3: // Mëttwoch case 5: // Freideg case 6: // Samschdeg return true; default: // 2 Dënschdeg, 4 Donneschdeg return false; } } /** * Returns true if the word before the given number loses the "-n" ending. * e.g. "an 10 Deeg" but "a 5 Deeg" * * @param number {integer} * @returns {boolean} */ function eifelerRegelAppliesToNumber(number) { number = parseInt(number, 10); if (isNaN(number)) { return false; } if (number < 0) { // Negative Number --> always true return true; } else if (number < 10) { // Only 1 digit if (4 <= number && number <= 7) { return true; } return false; } else if (number < 100) { // 2 digits var lastDigit = number % 10, firstDigit = number / 10; if (lastDigit === 0) { return eifelerRegelAppliesToNumber(firstDigit); } return eifelerRegelAppliesToNumber(lastDigit); } else if (number < 10000) { // 3 or 4 digits --> recursively check first digit while (number >= 10) { number = number / 10; } return eifelerRegelAppliesToNumber(number); } else { // Anything larger than 4 digits: recursively check first n-3 digits number = number / 1000; return eifelerRegelAppliesToNumber(number); } } return moment.lang('lb', { months: "Januar_Februar_Mäerz_Abrëll_Mee_Juni_Juli_August_September_Oktober_November_Dezember".split("_"), monthsShort: "Jan._Febr._Mrz._Abr._Mee_Jun._Jul._Aug._Sept._Okt._Nov._Dez.".split("_"), weekdays: "Sonndeg_Méindeg_Dënschdeg_Mëttwoch_Donneschdeg_Freideg_Samschdeg".split("_"), weekdaysShort: "So._Mé._Dë._Më._Do._Fr._Sa.".split("_"), weekdaysMin: "So_Mé_Dë_Më_Do_Fr_Sa".split("_"), longDateFormat: { LT: "H:mm [Auer]", L: "DD.MM.YYYY", LL: "D. MMMM YYYY", LLL: "D. MMMM YYYY LT", LLLL: "dddd, D. MMMM YYYY LT" }, calendar: { sameDay: "[Haut um] LT", sameElse: "L", nextDay: '[Muer um] LT', nextWeek: 'dddd [um] LT', lastDay: '[Gëschter um] LT', lastWeek: processLastWeek }, relativeTime: { future: processFutureTime, past: processPastTime, s: "e puer Sekonnen", m: processRelativeTime, mm: "%d Minutten", h: processRelativeTime, hh: "%d Stonnen", d: processRelativeTime, dd: processRelativeTime, M: processRelativeTime, MM: processRelativeTime, y: processRelativeTime, yy: processRelativeTime }, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : Lithuanian (lt) // author : Mindaugas Mozūras : https://github.com/mmozuras (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var units = { "m" : "minutė_minutės_minutę", "mm": "minutės_minučių_minutes", "h" : "valanda_valandos_valandą", "hh": "valandos_valandų_valandas", "d" : "diena_dienos_dieną", "dd": "dienos_dienų_dienas", "M" : "mėnuo_mėnesio_mėnesį", "MM": "mėnesiai_mėnesių_mėnesius", "y" : "metai_metų_metus", "yy": "metai_metų_metus" }, weekDays = "pirmadienis_antradienis_trečiadienis_ketvirtadienis_penktadienis_šeštadienis_sekmadienis".split("_"); function translateSeconds(number, withoutSuffix, key, isFuture) { if (withoutSuffix) { return "kelios sekundės"; } else { return isFuture ? "kelių sekundžių" : "kelias sekundes"; } } function translateSingular(number, withoutSuffix, key, isFuture) { return withoutSuffix ? forms(key)[0] : (isFuture ? forms(key)[1] : forms(key)[2]); } function special(number) { return number % 10 === 0 || (number > 10 && number < 20); } function forms(key) { return units[key].split("_"); } function translate(number, withoutSuffix, key, isFuture) { var result = number + " "; if (number === 1) { return result + translateSingular(number, withoutSuffix, key[0], isFuture); } else if (withoutSuffix) { return result + (special(number) ? forms(key)[1] : forms(key)[0]); } else { if (isFuture) { return result + forms(key)[1]; } else { return result + (special(number) ? forms(key)[1] : forms(key)[2]); } } } function relativeWeekDay(moment, format) { var nominative = format.indexOf('dddd LT') === -1, weekDay = weekDays[moment.weekday()]; return nominative ? weekDay : weekDay.substring(0, weekDay.length - 2) + "į"; } return moment.lang("lt", { months : "sausio_vasario_kovo_balandžio_gegužės_biržėlio_liepos_rugpjūčio_rugsėjo_spalio_lapkričio_gruodžio".split("_"), monthsShort : "sau_vas_kov_bal_geg_bir_lie_rgp_rgs_spa_lap_grd".split("_"), weekdays : relativeWeekDay, weekdaysShort : "Sek_Pir_Ant_Tre_Ket_Pen_Šeš".split("_"), weekdaysMin : "S_P_A_T_K_Pn_Š".split("_"), longDateFormat : { LT : "HH:mm", L : "YYYY-MM-DD", LL : "YYYY [m.] MMMM D [d.]", LLL : "YYYY [m.] MMMM D [d.], LT [val.]", LLLL : "YYYY [m.] MMMM D [d.], dddd, LT [val.]", l : "YYYY-MM-DD", ll : "YYYY [m.] MMMM D [d.]", lll : "YYYY [m.] MMMM D [d.], LT [val.]", llll : "YYYY [m.] MMMM D [d.], ddd, LT [val.]" }, calendar : { sameDay : "[Šiandien] LT", nextDay : "[Rytoj] LT", nextWeek : "dddd LT", lastDay : "[Vakar] LT", lastWeek : "[Praėjusį] dddd LT", sameElse : "L" }, relativeTime : { future : "po %s", past : "prieš %s", s : translateSeconds, m : translateSingular, mm : translate, h : translateSingular, hh : translate, d : translateSingular, dd : translate, M : translateSingular, MM : translate, y : translateSingular, yy : translate }, ordinal : function (number) { return number + '-oji'; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : latvian (lv) // author : Kristaps Karlsons : https://github.com/skakri (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var units = { 'mm': 'minūti_minūtes_minūte_minūtes', 'hh': 'stundu_stundas_stunda_stundas', 'dd': 'dienu_dienas_diena_dienas', 'MM': 'mēnesi_mēnešus_mēnesis_mēneši', 'yy': 'gadu_gadus_gads_gadi' }; function format(word, number, withoutSuffix) { var forms = word.split('_'); if (withoutSuffix) { return number % 10 === 1 && number !== 11 ? forms[2] : forms[3]; } else { return number % 10 === 1 && number !== 11 ? forms[0] : forms[1]; } } function relativeTimeWithPlural(number, withoutSuffix, key) { return number + ' ' + format(units[key], number, withoutSuffix); } return moment.lang('lv', { months : "janvāris_februāris_marts_aprīlis_maijs_jūnijs_jūlijs_augusts_septembris_oktobris_novembris_decembris".split("_"), monthsShort : "jan_feb_mar_apr_mai_jūn_jūl_aug_sep_okt_nov_dec".split("_"), weekdays : "svētdiena_pirmdiena_otrdiena_trešdiena_ceturtdiena_piektdiena_sestdiena".split("_"), weekdaysShort : "Sv_P_O_T_C_Pk_S".split("_"), weekdaysMin : "Sv_P_O_T_C_Pk_S".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "YYYY. [gada] D. MMMM", LLL : "YYYY. [gada] D. MMMM, LT", LLLL : "YYYY. [gada] D. MMMM, dddd, LT" }, calendar : { sameDay : '[Šodien pulksten] LT', nextDay : '[Rīt pulksten] LT', nextWeek : 'dddd [pulksten] LT', lastDay : '[Vakar pulksten] LT', lastWeek : '[Pagājušā] dddd [pulksten] LT', sameElse : 'L' }, relativeTime : { future : "%s vēlāk", past : "%s agrāk", s : "dažas sekundes", m : "minūti", mm : relativeTimeWithPlural, h : "stundu", hh : relativeTimeWithPlural, d : "dienu", dd : relativeTimeWithPlural, M : "mēnesi", MM : relativeTimeWithPlural, y : "gadu", yy : relativeTimeWithPlural }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : macedonian (mk) // author : Borislav Mickov : https://github.com/B0k0 (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('mk', { months : "јануари_февруари_март_април_мај_јуни_јули_август_септември_октомври_ноември_декември".split("_"), monthsShort : "јан_фев_мар_апр_мај_јун_јул_авг_сеп_окт_ное_дек".split("_"), weekdays : "недела_понеделник_вторник_среда_четврток_петок_сабота".split("_"), weekdaysShort : "нед_пон_вто_сре_чет_пет_саб".split("_"), weekdaysMin : "нe_пo_вт_ср_че_пе_сa".split("_"), longDateFormat : { LT : "H:mm", L : "D.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[Денес во] LT', nextDay : '[Утре во] LT', nextWeek : 'dddd [во] LT', lastDay : '[Вчера во] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: case 6: return '[Во изминатата] dddd [во] LT'; case 1: case 2: case 4: case 5: return '[Во изминатиот] dddd [во] LT'; } }, sameElse : 'L' }, relativeTime : { future : "после %s", past : "пред %s", s : "неколку секунди", m : "минута", mm : "%d минути", h : "час", hh : "%d часа", d : "ден", dd : "%d дена", M : "месец", MM : "%d месеци", y : "година", yy : "%d години" }, ordinal : function (number) { var lastDigit = number % 10, last2Digits = number % 100; if (number === 0) { return number + '-ев'; } else if (last2Digits === 0) { return number + '-ен'; } else if (last2Digits > 10 && last2Digits < 20) { return number + '-ти'; } else if (lastDigit === 1) { return number + '-ви'; } else if (lastDigit === 2) { return number + '-ри'; } else if (lastDigit === 7 || lastDigit === 8) { return number + '-ми'; } else { return number + '-ти'; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : malayalam (ml) // author : Floyd Pink : https://github.com/floydpink (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('ml', { months : 'ജനുവരി_ഫെബ്രുവരി_മാർച്ച്_ഏപ്രിൽ_മേയ്_ജൂൺ_ജൂലൈ_ഓഗസ്റ്റ്_സെപ്റ്റംബർ_ഒക്ടോബർ_നവംബർ_ഡിസംബർ'.split("_"), monthsShort : 'ജനു._ഫെബ്രു._മാർ._ഏപ്രി._മേയ്_ജൂൺ_ജൂലൈ._ഓഗ._സെപ്റ്റ._ഒക്ടോ._നവം._ഡിസം.'.split("_"), weekdays : 'ഞായറാഴ്ച_തിങ്കളാഴ്ച_ചൊവ്വാഴ്ച_ബുധനാഴ്ച_വ്യാഴാഴ്ച_വെള്ളിയാഴ്ച_ശനിയാഴ്ച'.split("_"), weekdaysShort : 'ഞായർ_തിങ്കൾ_ചൊവ്വ_ബുധൻ_വ്യാഴം_വെള്ളി_ശനി'.split("_"), weekdaysMin : 'ഞാ_തി_ചൊ_ബു_വ്യാ_വെ_ശ'.split("_"), longDateFormat : { LT : "A h:mm -നു", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY, LT", LLLL : "dddd, D MMMM YYYY, LT" }, calendar : { sameDay : '[ഇന്ന്] LT', nextDay : '[നാളെ] LT', nextWeek : 'dddd, LT', lastDay : '[ഇന്നലെ] LT', lastWeek : '[കഴിഞ്ഞ] dddd, LT', sameElse : 'L' }, relativeTime : { future : "%s കഴിഞ്ഞ്", past : "%s മുൻപ്", s : "അൽപ നിമിഷങ്ങൾ", m : "ഒരു മിനിറ്റ്", mm : "%d മിനിറ്റ്", h : "ഒരു മണിക്കൂർ", hh : "%d മണിക്കൂർ", d : "ഒരു ദിവസം", dd : "%d ദിവസം", M : "ഒരു മാസം", MM : "%d മാസം", y : "ഒരു വർഷം", yy : "%d വർഷം" }, meridiem : function (hour, minute, isLower) { if (hour < 4) { return "രാത്രി"; } else if (hour < 12) { return "രാവിലെ"; } else if (hour < 17) { return "ഉച്ച കഴിഞ്ഞ്"; } else if (hour < 20) { return "വൈകുന്നേരം"; } else { return "രാത്രി"; } } }); })); // moment.js language configuration // language : Marathi (mr) // author : Harshad Kale : https://github.com/kalehv (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var symbolMap = { '1': '१', '2': '२', '3': '३', '4': '४', '5': '५', '6': '६', '7': '७', '8': '८', '9': '९', '0': '०' }, numberMap = { '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9', '०': '0' }; return moment.lang('mr', { months : 'जानेवारी_फेब्रुवारी_मार्च_एप्रिल_मे_जून_जुलै_ऑगस्ट_सप्टेंबर_ऑक्टोबर_नोव्हेंबर_डिसेंबर'.split("_"), monthsShort: 'जाने._फेब्रु._मार्च._एप्रि._मे._जून._जुलै._ऑग._सप्टें._ऑक्टो._नोव्हें._डिसें.'.split("_"), weekdays : 'रविवार_सोमवार_मंगळवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split("_"), weekdaysShort : 'रवि_सोम_मंगळ_बुध_गुरू_शुक्र_शनि'.split("_"), weekdaysMin : 'र_सो_मं_बु_गु_शु_श'.split("_"), longDateFormat : { LT : "A h:mm वाजता", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY, LT", LLLL : "dddd, D MMMM YYYY, LT" }, calendar : { sameDay : '[आज] LT', nextDay : '[उद्या] LT', nextWeek : 'dddd, LT', lastDay : '[काल] LT', lastWeek: '[मागील] dddd, LT', sameElse : 'L' }, relativeTime : { future : "%s नंतर", past : "%s पूर्वी", s : "सेकंद", m: "एक मिनिट", mm: "%d मिनिटे", h : "एक तास", hh : "%d तास", d : "एक दिवस", dd : "%d दिवस", M : "एक महिना", MM : "%d महिने", y : "एक वर्ष", yy : "%d वर्षे" }, preparse: function (string) { return string.replace(/[१२३४५६७८९०]/g, function (match) { return numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }); }, meridiem: function (hour, minute, isLower) { if (hour < 4) { return "रात्री"; } else if (hour < 10) { return "सकाळी"; } else if (hour < 17) { return "दुपारी"; } else if (hour < 20) { return "सायंकाळी"; } else { return "रात्री"; } }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Bahasa Malaysia (ms-MY) // author : Weldan Jamili : https://github.com/weldan (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('ms-my', { months : "Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember".split("_"), monthsShort : "Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis".split("_"), weekdays : "Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu".split("_"), weekdaysShort : "Ahd_Isn_Sel_Rab_Kha_Jum_Sab".split("_"), weekdaysMin : "Ah_Is_Sl_Rb_Km_Jm_Sb".split("_"), longDateFormat : { LT : "HH.mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY [pukul] LT", LLLL : "dddd, D MMMM YYYY [pukul] LT" }, meridiem : function (hours, minutes, isLower) { if (hours < 11) { return 'pagi'; } else if (hours < 15) { return 'tengahari'; } else if (hours < 19) { return 'petang'; } else { return 'malam'; } }, calendar : { sameDay : '[Hari ini pukul] LT', nextDay : '[Esok pukul] LT', nextWeek : 'dddd [pukul] LT', lastDay : '[Kelmarin pukul] LT', lastWeek : 'dddd [lepas pukul] LT', sameElse : 'L' }, relativeTime : { future : "dalam %s", past : "%s yang lepas", s : "beberapa saat", m : "seminit", mm : "%d minit", h : "sejam", hh : "%d jam", d : "sehari", dd : "%d hari", M : "sebulan", MM : "%d bulan", y : "setahun", yy : "%d tahun" }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : norwegian bokmål (nb) // authors : Espen Hovlandsdal : https://github.com/rexxars // Sigurd Gartmann : https://github.com/sigurdga (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('nb', { months : "januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember".split("_"), monthsShort : "jan._feb._mars_april_mai_juni_juli_aug._sep._okt._nov._des.".split("_"), weekdays : "søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag".split("_"), weekdaysShort : "sø._ma._ti._on._to._fr._lø.".split("_"), weekdaysMin : "sø_ma_ti_on_to_fr_lø".split("_"), longDateFormat : { LT : "H.mm", L : "DD.MM.YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY [kl.] LT", LLLL : "dddd D. MMMM YYYY [kl.] LT" }, calendar : { sameDay: '[i dag kl.] LT', nextDay: '[i morgen kl.] LT', nextWeek: 'dddd [kl.] LT', lastDay: '[i går kl.] LT', lastWeek: '[forrige] dddd [kl.] LT', sameElse: 'L' }, relativeTime : { future : "om %s", past : "for %s siden", s : "noen sekunder", m : "ett minutt", mm : "%d minutter", h : "en time", hh : "%d timer", d : "en dag", dd : "%d dager", M : "en måned", MM : "%d måneder", y : "ett år", yy : "%d år" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : nepali/nepalese // author : suvash : https://github.com/suvash (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var symbolMap = { '1': '१', '2': '२', '3': '३', '4': '४', '5': '५', '6': '६', '7': '७', '8': '८', '9': '९', '0': '०' }, numberMap = { '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9', '०': '0' }; return moment.lang('ne', { months : 'जनवरी_फेब्रुवरी_मार्च_अप्रिल_मई_जुन_जुलाई_अगष्ट_सेप्टेम्बर_अक्टोबर_नोभेम्बर_डिसेम्बर'.split("_"), monthsShort : 'जन._फेब्रु._मार्च_अप्रि._मई_जुन_जुलाई._अग._सेप्ट._अक्टो._नोभे._डिसे.'.split("_"), weekdays : 'आइतबार_सोमबार_मङ्गलबार_बुधबार_बिहिबार_शुक्रबार_शनिबार'.split("_"), weekdaysShort : 'आइत._सोम._मङ्गल._बुध._बिहि._शुक्र._शनि.'.split("_"), weekdaysMin : 'आइ._सो._मङ्_बु._बि._शु._श.'.split("_"), longDateFormat : { LT : "Aको h:mm बजे", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY, LT", LLLL : "dddd, D MMMM YYYY, LT" }, preparse: function (string) { return string.replace(/[१२३४५६७८९०]/g, function (match) { return numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }); }, meridiem : function (hour, minute, isLower) { if (hour < 3) { return "राती"; } else if (hour < 10) { return "बिहान"; } else if (hour < 15) { return "दिउँसो"; } else if (hour < 18) { return "बेलुका"; } else if (hour < 20) { return "साँझ"; } else { return "राती"; } }, calendar : { sameDay : '[आज] LT', nextDay : '[भोली] LT', nextWeek : '[आउँदो] dddd[,] LT', lastDay : '[हिजो] LT', lastWeek : '[गएको] dddd[,] LT', sameElse : 'L' }, relativeTime : { future : "%sमा", past : "%s अगाडी", s : "केही समय", m : "एक मिनेट", mm : "%d मिनेट", h : "एक घण्टा", hh : "%d घण्टा", d : "एक दिन", dd : "%d दिन", M : "एक महिना", MM : "%d महिना", y : "एक बर्ष", yy : "%d बर्ष" }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : dutch (nl) // author : Joris Röling : https://github.com/jjupiter (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var monthsShortWithDots = "jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.".split("_"), monthsShortWithoutDots = "jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec".split("_"); return moment.lang('nl', { months : "januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december".split("_"), monthsShort : function (m, format) { if (/-MMM-/.test(format)) { return monthsShortWithoutDots[m.month()]; } else { return monthsShortWithDots[m.month()]; } }, weekdays : "zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag".split("_"), weekdaysShort : "zo._ma._di._wo._do._vr._za.".split("_"), weekdaysMin : "Zo_Ma_Di_Wo_Do_Vr_Za".split("_"), longDateFormat : { LT : "HH:mm", L : "DD-MM-YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: '[vandaag om] LT', nextDay: '[morgen om] LT', nextWeek: 'dddd [om] LT', lastDay: '[gisteren om] LT', lastWeek: '[afgelopen] dddd [om] LT', sameElse: 'L' }, relativeTime : { future : "over %s", past : "%s geleden", s : "een paar seconden", m : "één minuut", mm : "%d minuten", h : "één uur", hh : "%d uur", d : "één dag", dd : "%d dagen", M : "één maand", MM : "%d maanden", y : "één jaar", yy : "%d jaar" }, ordinal : function (number) { return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de'); }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : norwegian nynorsk (nn) // author : https://github.com/mechuwind (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('nn', { months : "januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember".split("_"), monthsShort : "jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"), weekdays : "sundag_måndag_tysdag_onsdag_torsdag_fredag_laurdag".split("_"), weekdaysShort : "sun_mån_tys_ons_tor_fre_lau".split("_"), weekdaysMin : "su_må_ty_on_to_fr_lø".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: '[I dag klokka] LT', nextDay: '[I morgon klokka] LT', nextWeek: 'dddd [klokka] LT', lastDay: '[I går klokka] LT', lastWeek: '[Føregående] dddd [klokka] LT', sameElse: 'L' }, relativeTime : { future : "om %s", past : "for %s siden", s : "noen sekund", m : "ett minutt", mm : "%d minutt", h : "en time", hh : "%d timar", d : "en dag", dd : "%d dagar", M : "en månad", MM : "%d månader", y : "ett år", yy : "%d år" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : polish (pl) // author : Rafal Hirsz : https://github.com/evoL (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var monthsNominative = "styczeń_luty_marzec_kwiecień_maj_czerwiec_lipiec_sierpień_wrzesień_październik_listopad_grudzień".split("_"), monthsSubjective = "stycznia_lutego_marca_kwietnia_maja_czerwca_lipca_sierpnia_września_października_listopada_grudnia".split("_"); function plural(n) { return (n % 10 < 5) && (n % 10 > 1) && ((~~(n / 10) % 10) !== 1); } function translate(number, withoutSuffix, key) { var result = number + " "; switch (key) { case 'm': return withoutSuffix ? 'minuta' : 'minutę'; case 'mm': return result + (plural(number) ? 'minuty' : 'minut'); case 'h': return withoutSuffix ? 'godzina' : 'godzinę'; case 'hh': return result + (plural(number) ? 'godziny' : 'godzin'); case 'MM': return result + (plural(number) ? 'miesiące' : 'miesięcy'); case 'yy': return result + (plural(number) ? 'lata' : 'lat'); } } return moment.lang('pl', { months : function (momentToFormat, format) { if (/D MMMM/.test(format)) { return monthsSubjective[momentToFormat.month()]; } else { return monthsNominative[momentToFormat.month()]; } }, monthsShort : "sty_lut_mar_kwi_maj_cze_lip_sie_wrz_paź_lis_gru".split("_"), weekdays : "niedziela_poniedziałek_wtorek_środa_czwartek_piątek_sobota".split("_"), weekdaysShort : "nie_pon_wt_śr_czw_pt_sb".split("_"), weekdaysMin : "N_Pn_Wt_Śr_Cz_Pt_So".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay: '[Dziś o] LT', nextDay: '[Jutro o] LT', nextWeek: '[W] dddd [o] LT', lastDay: '[Wczoraj o] LT', lastWeek: function () { switch (this.day()) { case 0: return '[W zeszłą niedzielę o] LT'; case 3: return '[W zeszłą środę o] LT'; case 6: return '[W zeszłą sobotę o] LT'; default: return '[W zeszły] dddd [o] LT'; } }, sameElse: 'L' }, relativeTime : { future : "za %s", past : "%s temu", s : "kilka sekund", m : translate, mm : translate, h : translate, hh : translate, d : "1 dzień", dd : '%d dni', M : "miesiąc", MM : translate, y : "rok", yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : brazilian portuguese (pt-br) // author : Caio Ribeiro Pereira : https://github.com/caio-ribeiro-pereira (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('pt-br', { months : "Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro".split("_"), monthsShort : "Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez".split("_"), weekdays : "Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado".split("_"), weekdaysShort : "Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"), weekdaysMin : "Dom_2ª_3ª_4ª_5ª_6ª_Sáb".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D [de] MMMM [de] YYYY", LLL : "D [de] MMMM [de] YYYY LT", LLLL : "dddd, D [de] MMMM [de] YYYY LT" }, calendar : { sameDay: '[Hoje às] LT', nextDay: '[Amanhã às] LT', nextWeek: 'dddd [às] LT', lastDay: '[Ontem às] LT', lastWeek: function () { return (this.day() === 0 || this.day() === 6) ? '[Último] dddd [às] LT' : // Saturday + Sunday '[Última] dddd [às] LT'; // Monday - Friday }, sameElse: 'L' }, relativeTime : { future : "em %s", past : "%s atrás", s : "segundos", m : "um minuto", mm : "%d minutos", h : "uma hora", hh : "%d horas", d : "um dia", dd : "%d dias", M : "um mês", MM : "%d meses", y : "um ano", yy : "%d anos" }, ordinal : '%dº' }); })); // moment.js language configuration // language : portuguese (pt) // author : Jefferson : https://github.com/jalex79 (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('pt', { months : "Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro".split("_"), monthsShort : "Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez".split("_"), weekdays : "Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado".split("_"), weekdaysShort : "Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"), weekdaysMin : "Dom_2ª_3ª_4ª_5ª_6ª_Sáb".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D [de] MMMM [de] YYYY", LLL : "D [de] MMMM [de] YYYY LT", LLLL : "dddd, D [de] MMMM [de] YYYY LT" }, calendar : { sameDay: '[Hoje às] LT', nextDay: '[Amanhã às] LT', nextWeek: 'dddd [às] LT', lastDay: '[Ontem às] LT', lastWeek: function () { return (this.day() === 0 || this.day() === 6) ? '[Último] dddd [às] LT' : // Saturday + Sunday '[Última] dddd [às] LT'; // Monday - Friday }, sameElse: 'L' }, relativeTime : { future : "em %s", past : "%s atrás", s : "segundos", m : "um minuto", mm : "%d minutos", h : "uma hora", hh : "%d horas", d : "um dia", dd : "%d dias", M : "um mês", MM : "%d meses", y : "um ano", yy : "%d anos" }, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : romanian (ro) // author : Vlad Gurdiga : https://github.com/gurdiga // author : Valentin Agachi : https://github.com/avaly (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function relativeTimeWithPlural(number, withoutSuffix, key) { var format = { 'mm': 'minute', 'hh': 'ore', 'dd': 'zile', 'MM': 'luni', 'yy': 'ani' }, separator = ' '; if (number % 100 >= 20 || (number >= 100 && number % 100 === 0)) { separator = ' de '; } return number + separator + format[key]; } return moment.lang('ro', { months : "ianuarie_februarie_martie_aprilie_mai_iunie_iulie_august_septembrie_octombrie_noiembrie_decembrie".split("_"), monthsShort : "ian_feb_mar_apr_mai_iun_iul_aug_sep_oct_noi_dec".split("_"), weekdays : "duminică_luni_marți_miercuri_joi_vineri_sâmbătă".split("_"), weekdaysShort : "Dum_Lun_Mar_Mie_Joi_Vin_Sâm".split("_"), weekdaysMin : "Du_Lu_Ma_Mi_Jo_Vi_Sâ".split("_"), longDateFormat : { LT : "H:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY H:mm", LLLL : "dddd, D MMMM YYYY H:mm" }, calendar : { sameDay: "[azi la] LT", nextDay: '[mâine la] LT', nextWeek: 'dddd [la] LT', lastDay: '[ieri la] LT', lastWeek: '[fosta] dddd [la] LT', sameElse: 'L' }, relativeTime : { future : "peste %s", past : "%s în urmă", s : "câteva secunde", m : "un minut", mm : relativeTimeWithPlural, h : "o oră", hh : relativeTimeWithPlural, d : "o zi", dd : relativeTimeWithPlural, M : "o lună", MM : relativeTimeWithPlural, y : "un an", yy : relativeTimeWithPlural }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : serbian (rs) // author : Limon Monte : https://github.com/limonte // based on (bs) translation by Nedim Cholich (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function translate(number, withoutSuffix, key) { var result = number + " "; switch (key) { case 'm': return withoutSuffix ? 'jedna minuta' : 'jedne minute'; case 'mm': if (number === 1) { result += 'minuta'; } else if (number === 2 || number === 3 || number === 4) { result += 'minute'; } else { result += 'minuta'; } return result; case 'h': return withoutSuffix ? 'jedan sat' : 'jednog sata'; case 'hh': if (number === 1) { result += 'sat'; } else if (number === 2 || number === 3 || number === 4) { result += 'sata'; } else { result += 'sati'; } return result; case 'dd': if (number === 1) { result += 'dan'; } else { result += 'dana'; } return result; case 'MM': if (number === 1) { result += 'mesec'; } else if (number === 2 || number === 3 || number === 4) { result += 'meseca'; } else { result += 'meseci'; } return result; case 'yy': if (number === 1) { result += 'godina'; } else if (number === 2 || number === 3 || number === 4) { result += 'godine'; } else { result += 'godina'; } return result; } } return moment.lang('rs', { months : "januar_februar_mart_april_maj_jun_jul_avgust_septembar_oktobar_novembar_decembar".split("_"), monthsShort : "jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.".split("_"), weekdays : "nedelja_ponedeljak_utorak_sreda_četvrtak_petak_subota".split("_"), weekdaysShort : "ned._pon._uto._sre._čet._pet._sub.".split("_"), weekdaysMin : "ne_po_ut_sr_če_pe_su".split("_"), longDateFormat : { LT : "H:mm", L : "DD. MM. YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay : '[danas u] LT', nextDay : '[sutra u] LT', nextWeek : function () { switch (this.day()) { case 0: return '[u] [nedelju] [u] LT'; case 3: return '[u] [sredu] [u] LT'; case 6: return '[u] [subotu] [u] LT'; case 1: case 2: case 4: case 5: return '[u] dddd [u] LT'; } }, lastDay : '[juče u] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: return '[prošlu] dddd [u] LT'; case 6: return '[prošle] [subote] [u] LT'; case 1: case 2: case 4: case 5: return '[prošli] dddd [u] LT'; } }, sameElse : 'L' }, relativeTime : { future : "za %s", past : "pre %s", s : "par sekundi", m : translate, mm : translate, h : translate, hh : translate, d : "dan", dd : translate, M : "mesec", MM : translate, y : "godinu", yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : russian (ru) // author : Viktorminator : https://github.com/Viktorminator // Author : Menelion Elensúle : https://github.com/Oire (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function plural(word, num) { var forms = word.split('_'); return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]); } function relativeTimeWithPlural(number, withoutSuffix, key) { var format = { 'mm': 'минута_минуты_минут', 'hh': 'час_часа_часов', 'dd': 'день_дня_дней', 'MM': 'месяц_месяца_месяцев', 'yy': 'год_года_лет' }; if (key === 'm') { return withoutSuffix ? 'минута' : 'минуту'; } else { return number + ' ' + plural(format[key], +number); } } function monthsCaseReplace(m, format) { var months = { 'nominative': 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_'), 'accusative': 'января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря'.split('_') }, nounCase = (/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/).test(format) ? 'accusative' : 'nominative'; return months[nounCase][m.month()]; } function monthsShortCaseReplace(m, format) { var monthsShort = { 'nominative': 'янв_фев_мар_апр_май_июнь_июль_авг_сен_окт_ноя_дек'.split('_'), 'accusative': 'янв_фев_мар_апр_мая_июня_июля_авг_сен_окт_ноя_дек'.split('_') }, nounCase = (/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/).test(format) ? 'accusative' : 'nominative'; return monthsShort[nounCase][m.month()]; } function weekdaysCaseReplace(m, format) { var weekdays = { 'nominative': 'воскресенье_понедельник_вторник_среда_четверг_пятница_суббота'.split('_'), 'accusative': 'воскресенье_понедельник_вторник_среду_четверг_пятницу_субботу'.split('_') }, nounCase = (/\[ ?[Вв] ?(?:прошлую|следующую)? ?\] ?dddd/).test(format) ? 'accusative' : 'nominative'; return weekdays[nounCase][m.day()]; } return moment.lang('ru', { months : monthsCaseReplace, monthsShort : monthsShortCaseReplace, weekdays : weekdaysCaseReplace, weekdaysShort : "вс_пн_вт_ср_чт_пт_сб".split("_"), weekdaysMin : "вс_пн_вт_ср_чт_пт_сб".split("_"), monthsParse : [/^янв/i, /^фев/i, /^мар/i, /^апр/i, /^ма[й|я]/i, /^июн/i, /^июл/i, /^авг/i, /^сен/i, /^окт/i, /^ноя/i, /^дек/i], longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY г.", LLL : "D MMMM YYYY г., LT", LLLL : "dddd, D MMMM YYYY г., LT" }, calendar : { sameDay: '[Сегодня в] LT', nextDay: '[Завтра в] LT', lastDay: '[Вчера в] LT', nextWeek: function () { return this.day() === 2 ? '[Во] dddd [в] LT' : '[В] dddd [в] LT'; }, lastWeek: function () { switch (this.day()) { case 0: return '[В прошлое] dddd [в] LT'; case 1: case 2: case 4: return '[В прошлый] dddd [в] LT'; case 3: case 5: case 6: return '[В прошлую] dddd [в] LT'; } }, sameElse: 'L' }, relativeTime : { future : "через %s", past : "%s назад", s : "несколько секунд", m : relativeTimeWithPlural, mm : relativeTimeWithPlural, h : "час", hh : relativeTimeWithPlural, d : "день", dd : relativeTimeWithPlural, M : "месяц", MM : relativeTimeWithPlural, y : "год", yy : relativeTimeWithPlural }, // M. E.: those two are virtually unused but a user might want to implement them for his/her website for some reason meridiem : function (hour, minute, isLower) { if (hour < 4) { return "ночи"; } else if (hour < 12) { return "утра"; } else if (hour < 17) { return "дня"; } else { return "вечера"; } }, ordinal: function (number, period) { switch (period) { case 'M': case 'd': case 'DDD': return number + '-й'; case 'D': return number + '-го'; case 'w': case 'W': return number + '-я'; default: return number; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : slovak (sk) // author : Martin Minka : https://github.com/k2s // based on work of petrbela : https://github.com/petrbela (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var months = "január_február_marec_apríl_máj_jún_júl_august_september_október_november_december".split("_"), monthsShort = "jan_feb_mar_apr_máj_jún_júl_aug_sep_okt_nov_dec".split("_"); function plural(n) { return (n > 1) && (n < 5); } function translate(number, withoutSuffix, key, isFuture) { var result = number + " "; switch (key) { case 's': // a few seconds / in a few seconds / a few seconds ago return (withoutSuffix || isFuture) ? 'pár sekúnd' : 'pár sekundami'; case 'm': // a minute / in a minute / a minute ago return withoutSuffix ? 'minúta' : (isFuture ? 'minútu' : 'minútou'); case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'minúty' : 'minút'); } else { return result + 'minútami'; } break; case 'h': // an hour / in an hour / an hour ago return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou'); case 'hh': // 9 hours / in 9 hours / 9 hours ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'hodiny' : 'hodín'); } else { return result + 'hodinami'; } break; case 'd': // a day / in a day / a day ago return (withoutSuffix || isFuture) ? 'deň' : 'dňom'; case 'dd': // 9 days / in 9 days / 9 days ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'dni' : 'dní'); } else { return result + 'dňami'; } break; case 'M': // a month / in a month / a month ago return (withoutSuffix || isFuture) ? 'mesiac' : 'mesiacom'; case 'MM': // 9 months / in 9 months / 9 months ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'mesiace' : 'mesiacov'); } else { return result + 'mesiacmi'; } break; case 'y': // a year / in a year / a year ago return (withoutSuffix || isFuture) ? 'rok' : 'rokom'; case 'yy': // 9 years / in 9 years / 9 years ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'roky' : 'rokov'); } else { return result + 'rokmi'; } break; } } return moment.lang('sk', { months : months, monthsShort : monthsShort, monthsParse : (function (months, monthsShort) { var i, _monthsParse = []; for (i = 0; i < 12; i++) { // use custom parser to solve problem with July (červenec) _monthsParse[i] = new RegExp('^' + months[i] + '$|^' + monthsShort[i] + '$', 'i'); } return _monthsParse; }(months, monthsShort)), weekdays : "nedeľa_pondelok_utorok_streda_štvrtok_piatok_sobota".split("_"), weekdaysShort : "ne_po_ut_st_št_pi_so".split("_"), weekdaysMin : "ne_po_ut_st_št_pi_so".split("_"), longDateFormat : { LT: "H:mm", L : "DD.MM.YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd D. MMMM YYYY LT" }, calendar : { sameDay: "[dnes o] LT", nextDay: '[zajtra o] LT', nextWeek: function () { switch (this.day()) { case 0: return '[v nedeľu o] LT'; case 1: case 2: return '[v] dddd [o] LT'; case 3: return '[v stredu o] LT'; case 4: return '[vo štvrtok o] LT'; case 5: return '[v piatok o] LT'; case 6: return '[v sobotu o] LT'; } }, lastDay: '[včera o] LT', lastWeek: function () { switch (this.day()) { case 0: return '[minulú nedeľu o] LT'; case 1: case 2: return '[minulý] dddd [o] LT'; case 3: return '[minulú stredu o] LT'; case 4: case 5: return '[minulý] dddd [o] LT'; case 6: return '[minulú sobotu o] LT'; } }, sameElse: "L" }, relativeTime : { future : "za %s", past : "pred %s", s : translate, m : translate, mm : translate, h : translate, hh : translate, d : translate, dd : translate, M : translate, MM : translate, y : translate, yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : slovenian (sl) // author : Robert Sedovšek : https://github.com/sedovsek (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function translate(number, withoutSuffix, key) { var result = number + " "; switch (key) { case 'm': return withoutSuffix ? 'ena minuta' : 'eno minuto'; case 'mm': if (number === 1) { result += 'minuta'; } else if (number === 2) { result += 'minuti'; } else if (number === 3 || number === 4) { result += 'minute'; } else { result += 'minut'; } return result; case 'h': return withoutSuffix ? 'ena ura' : 'eno uro'; case 'hh': if (number === 1) { result += 'ura'; } else if (number === 2) { result += 'uri'; } else if (number === 3 || number === 4) { result += 'ure'; } else { result += 'ur'; } return result; case 'dd': if (number === 1) { result += 'dan'; } else { result += 'dni'; } return result; case 'MM': if (number === 1) { result += 'mesec'; } else if (number === 2) { result += 'meseca'; } else if (number === 3 || number === 4) { result += 'mesece'; } else { result += 'mesecev'; } return result; case 'yy': if (number === 1) { result += 'leto'; } else if (number === 2) { result += 'leti'; } else if (number === 3 || number === 4) { result += 'leta'; } else { result += 'let'; } return result; } } return moment.lang('sl', { months : "januar_februar_marec_april_maj_junij_julij_avgust_september_oktober_november_december".split("_"), monthsShort : "jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.".split("_"), weekdays : "nedelja_ponedeljek_torek_sreda_četrtek_petek_sobota".split("_"), weekdaysShort : "ned._pon._tor._sre._čet._pet._sob.".split("_"), weekdaysMin : "ne_po_to_sr_če_pe_so".split("_"), longDateFormat : { LT : "H:mm", L : "DD. MM. YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay : '[danes ob] LT', nextDay : '[jutri ob] LT', nextWeek : function () { switch (this.day()) { case 0: return '[v] [nedeljo] [ob] LT'; case 3: return '[v] [sredo] [ob] LT'; case 6: return '[v] [soboto] [ob] LT'; case 1: case 2: case 4: case 5: return '[v] dddd [ob] LT'; } }, lastDay : '[včeraj ob] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: case 6: return '[prejšnja] dddd [ob] LT'; case 1: case 2: case 4: case 5: return '[prejšnji] dddd [ob] LT'; } }, sameElse : 'L' }, relativeTime : { future : "čez %s", past : "%s nazaj", s : "nekaj sekund", m : translate, mm : translate, h : translate, hh : translate, d : "en dan", dd : translate, M : "en mesec", MM : translate, y : "eno leto", yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Albanian (sq) // author : Flakërim Ismani : https://github.com/flakerimi // author: Menelion Elensúle: https://github.com/Oire (tests) (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('sq', { months : "Janar_Shkurt_Mars_Prill_Maj_Qershor_Korrik_Gusht_Shtator_Tetor_Nëntor_Dhjetor".split("_"), monthsShort : "Jan_Shk_Mar_Pri_Maj_Qer_Kor_Gus_Sht_Tet_Nën_Dhj".split("_"), weekdays : "E Diel_E Hënë_E Marte_E Mërkure_E Enjte_E Premte_E Shtunë".split("_"), weekdaysShort : "Die_Hën_Mar_Mër_Enj_Pre_Sht".split("_"), weekdaysMin : "D_H_Ma_Më_E_P_Sh".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[Sot në] LT', nextDay : '[Neser në] LT', nextWeek : 'dddd [në] LT', lastDay : '[Dje në] LT', lastWeek : 'dddd [e kaluar në] LT', sameElse : 'L' }, relativeTime : { future : "në %s", past : "%s me parë", s : "disa sekonda", m : "një minut", mm : "%d minuta", h : "një orë", hh : "%d orë", d : "një ditë", dd : "%d ditë", M : "një muaj", MM : "%d muaj", y : "një vit", yy : "%d vite" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : swedish (sv) // author : Jens Alm : https://github.com/ulmus (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('sv', { months : "januari_februari_mars_april_maj_juni_juli_augusti_september_oktober_november_december".split("_"), monthsShort : "jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec".split("_"), weekdays : "söndag_måndag_tisdag_onsdag_torsdag_fredag_lördag".split("_"), weekdaysShort : "sön_mån_tis_ons_tor_fre_lör".split("_"), weekdaysMin : "sö_må_ti_on_to_fr_lö".split("_"), longDateFormat : { LT : "HH:mm", L : "YYYY-MM-DD", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: '[Idag] LT', nextDay: '[Imorgon] LT', lastDay: '[Igår] LT', nextWeek: 'dddd LT', lastWeek: '[Förra] dddd[en] LT', sameElse: 'L' }, relativeTime : { future : "om %s", past : "för %s sedan", s : "några sekunder", m : "en minut", mm : "%d minuter", h : "en timme", hh : "%d timmar", d : "en dag", dd : "%d dagar", M : "en månad", MM : "%d månader", y : "ett år", yy : "%d år" }, ordinal : function (number) { var b = number % 10, output = (~~ (number % 100 / 10) === 1) ? 'e' : (b === 1) ? 'a' : (b === 2) ? 'a' : (b === 3) ? 'e' : 'e'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : tamil (ta) // author : Arjunkumar Krishnamoorthy : https://github.com/tk120404 (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { /*var symbolMap = { '1': '௧', '2': '௨', '3': '௩', '4': '௪', '5': '௫', '6': '௬', '7': '௭', '8': '௮', '9': '௯', '0': '௦' }, numberMap = { '௧': '1', '௨': '2', '௩': '3', '௪': '4', '௫': '5', '௬': '6', '௭': '7', '௮': '8', '௯': '9', '௦': '0' }; */ return moment.lang('ta', { months : 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split("_"), monthsShort : 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split("_"), weekdays : 'ஞாயிற்றுக்கிழமை_திங்கட்கிழமை_செவ்வாய்கிழமை_புதன்கிழமை_வியாழக்கிழமை_வெள்ளிக்கிழமை_சனிக்கிழமை'.split("_"), weekdaysShort : 'ஞாயிறு_திங்கள்_செவ்வாய்_புதன்_வியாழன்_வெள்ளி_சனி'.split("_"), weekdaysMin : 'ஞா_தி_செ_பு_வி_வெ_ச'.split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY, LT", LLLL : "dddd, D MMMM YYYY, LT" }, calendar : { sameDay : '[இன்று] LT', nextDay : '[நாளை] LT', nextWeek : 'dddd, LT', lastDay : '[நேற்று] LT', lastWeek : '[கடந்த வாரம்] dddd, LT', sameElse : 'L' }, relativeTime : { future : "%s இல்", past : "%s முன்", s : "ஒரு சில விநாடிகள்", m : "ஒரு நிமிடம்", mm : "%d நிமிடங்கள்", h : "ஒரு மணி நேரம்", hh : "%d மணி நேரம்", d : "ஒரு நாள்", dd : "%d நாட்கள்", M : "ஒரு மாதம்", MM : "%d மாதங்கள்", y : "ஒரு வருடம்", yy : "%d ஆண்டுகள்" }, /* preparse: function (string) { return string.replace(/[௧௨௩௪௫௬௭௮௯௦]/g, function (match) { return numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }); },*/ ordinal : function (number) { return number + 'வது'; }, // refer http://ta.wikipedia.org/s/1er1 meridiem : function (hour, minute, isLower) { if (hour >= 6 && hour <= 10) { return " காலை"; } else if (hour >= 10 && hour <= 14) { return " நண்பகல்"; } else if (hour >= 14 && hour <= 18) { return " எற்பாடு"; } else if (hour >= 18 && hour <= 20) { return " மாலை"; } else if (hour >= 20 && hour <= 24) { return " இரவு"; } else if (hour >= 0 && hour <= 6) { return " வைகறை"; } }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : thai (th) // author : Kridsada Thanabulpong : https://github.com/sirn (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('th', { months : "มกราคม_กุมภาพันธ์_มีนาคม_เมษายน_พฤษภาคม_มิถุนายน_กรกฎาคม_สิงหาคม_กันยายน_ตุลาคม_พฤศจิกายน_ธันวาคม".split("_"), monthsShort : "มกรา_กุมภา_มีนา_เมษา_พฤษภา_มิถุนา_กรกฎา_สิงหา_กันยา_ตุลา_พฤศจิกา_ธันวา".split("_"), weekdays : "อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัสบดี_ศุกร์_เสาร์".split("_"), weekdaysShort : "อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัส_ศุกร์_เสาร์".split("_"), // yes, three characters difference weekdaysMin : "อา._จ._อ._พ._พฤ._ศ._ส.".split("_"), longDateFormat : { LT : "H นาฬิกา m นาที", L : "YYYY/MM/DD", LL : "D MMMM YYYY", LLL : "D MMMM YYYY เวลา LT", LLLL : "วันddddที่ D MMMM YYYY เวลา LT" }, meridiem : function (hour, minute, isLower) { if (hour < 12) { return "ก่อนเที่ยง"; } else { return "หลังเที่ยง"; } }, calendar : { sameDay : '[วันนี้ เวลา] LT', nextDay : '[พรุ่งนี้ เวลา] LT', nextWeek : 'dddd[หน้า เวลา] LT', lastDay : '[เมื่อวานนี้ เวลา] LT', lastWeek : '[วัน]dddd[ที่แล้ว เวลา] LT', sameElse : 'L' }, relativeTime : { future : "อีก %s", past : "%sที่แล้ว", s : "ไม่กี่วินาที", m : "1 นาที", mm : "%d นาที", h : "1 ชั่วโมง", hh : "%d ชั่วโมง", d : "1 วัน", dd : "%d วัน", M : "1 เดือน", MM : "%d เดือน", y : "1 ปี", yy : "%d ปี" } }); })); // moment.js language configuration // language : Tagalog/Filipino (tl-ph) // author : Dan Hagman (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('tl-ph', { months : "Enero_Pebrero_Marso_Abril_Mayo_Hunyo_Hulyo_Agosto_Setyembre_Oktubre_Nobyembre_Disyembre".split("_"), monthsShort : "Ene_Peb_Mar_Abr_May_Hun_Hul_Ago_Set_Okt_Nob_Dis".split("_"), weekdays : "Linggo_Lunes_Martes_Miyerkules_Huwebes_Biyernes_Sabado".split("_"), weekdaysShort : "Lin_Lun_Mar_Miy_Huw_Biy_Sab".split("_"), weekdaysMin : "Li_Lu_Ma_Mi_Hu_Bi_Sab".split("_"), longDateFormat : { LT : "HH:mm", L : "MM/D/YYYY", LL : "MMMM D, YYYY", LLL : "MMMM D, YYYY LT", LLLL : "dddd, MMMM DD, YYYY LT" }, calendar : { sameDay: "[Ngayon sa] LT", nextDay: '[Bukas sa] LT', nextWeek: 'dddd [sa] LT', lastDay: '[Kahapon sa] LT', lastWeek: 'dddd [huling linggo] LT', sameElse: 'L' }, relativeTime : { future : "sa loob ng %s", past : "%s ang nakalipas", s : "ilang segundo", m : "isang minuto", mm : "%d minuto", h : "isang oras", hh : "%d oras", d : "isang araw", dd : "%d araw", M : "isang buwan", MM : "%d buwan", y : "isang taon", yy : "%d taon" }, ordinal : function (number) { return number; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : turkish (tr) // authors : Erhan Gundogan : https://github.com/erhangundogan, // Burak Yiğit Kaya: https://github.com/BYK (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var suffixes = { 1: "'inci", 5: "'inci", 8: "'inci", 70: "'inci", 80: "'inci", 2: "'nci", 7: "'nci", 20: "'nci", 50: "'nci", 3: "'üncü", 4: "'üncü", 100: "'üncü", 6: "'ncı", 9: "'uncu", 10: "'uncu", 30: "'uncu", 60: "'ıncı", 90: "'ıncı" }; return moment.lang('tr', { months : "Ocak_Şubat_Mart_Nisan_Mayıs_Haziran_Temmuz_Ağustos_Eylül_Ekim_Kasım_Aralık".split("_"), monthsShort : "Oca_Şub_Mar_Nis_May_Haz_Tem_Ağu_Eyl_Eki_Kas_Ara".split("_"), weekdays : "Pazar_Pazartesi_Salı_Çarşamba_Perşembe_Cuma_Cumartesi".split("_"), weekdaysShort : "Paz_Pts_Sal_Çar_Per_Cum_Cts".split("_"), weekdaysMin : "Pz_Pt_Sa_Ça_Pe_Cu_Ct".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[bugün saat] LT', nextDay : '[yarın saat] LT', nextWeek : '[haftaya] dddd [saat] LT', lastDay : '[dün] LT', lastWeek : '[geçen hafta] dddd [saat] LT', sameElse : 'L' }, relativeTime : { future : "%s sonra", past : "%s önce", s : "birkaç saniye", m : "bir dakika", mm : "%d dakika", h : "bir saat", hh : "%d saat", d : "bir gün", dd : "%d gün", M : "bir ay", MM : "%d ay", y : "bir yıl", yy : "%d yıl" }, ordinal : function (number) { if (number === 0) { // special case for zero return number + "'ıncı"; } var a = number % 10, b = number % 100 - a, c = number >= 100 ? 100 : null; return number + (suffixes[a] || suffixes[b] || suffixes[c]); }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Morocco Central Atlas Tamaziɣt in Latin (tzm-la) // author : Abdel Said : https://github.com/abdelsaid (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('tzm-la', { months : "innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir".split("_"), monthsShort : "innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir".split("_"), weekdays : "asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas".split("_"), weekdaysShort : "asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas".split("_"), weekdaysMin : "asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[asdkh g] LT", nextDay: '[aska g] LT', nextWeek: 'dddd [g] LT', lastDay: '[assant g] LT', lastWeek: 'dddd [g] LT', sameElse: 'L' }, relativeTime : { future : "dadkh s yan %s", past : "yan %s", s : "imik", m : "minuḍ", mm : "%d minuḍ", h : "saɛa", hh : "%d tassaɛin", d : "ass", dd : "%d ossan", M : "ayowr", MM : "%d iyyirn", y : "asgas", yy : "%d isgasn" }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Morocco Central Atlas Tamaziɣt (tzm) // author : Abdel Said : https://github.com/abdelsaid (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('tzm', { months : "ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ".split("_"), monthsShort : "ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ".split("_"), weekdays : "ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ".split("_"), weekdaysShort : "ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ".split("_"), weekdaysMin : "ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[ⴰⵙⴷⵅ ⴴ] LT", nextDay: '[ⴰⵙⴽⴰ ⴴ] LT', nextWeek: 'dddd [ⴴ] LT', lastDay: '[ⴰⵚⴰⵏⵜ ⴴ] LT', lastWeek: 'dddd [ⴴ] LT', sameElse: 'L' }, relativeTime : { future : "ⴷⴰⴷⵅ ⵙ ⵢⴰⵏ %s", past : "ⵢⴰⵏ %s", s : "ⵉⵎⵉⴽ", m : "ⵎⵉⵏⵓⴺ", mm : "%d ⵎⵉⵏⵓⴺ", h : "ⵙⴰⵄⴰ", hh : "%d ⵜⴰⵙⵙⴰⵄⵉⵏ", d : "ⴰⵙⵙ", dd : "%d oⵙⵙⴰⵏ", M : "ⴰⵢoⵓⵔ", MM : "%d ⵉⵢⵢⵉⵔⵏ", y : "ⴰⵙⴳⴰⵙ", yy : "%d ⵉⵙⴳⴰⵙⵏ" }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : ukrainian (uk) // author : zemlanin : https://github.com/zemlanin // Author : Menelion Elensúle : https://github.com/Oire (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { function plural(word, num) { var forms = word.split('_'); return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]); } function relativeTimeWithPlural(number, withoutSuffix, key) { var format = { 'mm': 'хвилина_хвилини_хвилин', 'hh': 'година_години_годин', 'dd': 'день_дні_днів', 'MM': 'місяць_місяці_місяців', 'yy': 'рік_роки_років' }; if (key === 'm') { return withoutSuffix ? 'хвилина' : 'хвилину'; } else if (key === 'h') { return withoutSuffix ? 'година' : 'годину'; } else { return number + ' ' + plural(format[key], +number); } } function monthsCaseReplace(m, format) { var months = { 'nominative': 'січень_лютий_березень_квітень_травень_червень_липень_серпень_вересень_жовтень_листопад_грудень'.split('_'), 'accusative': 'січня_лютого_березня_квітня_травня_червня_липня_серпня_вересня_жовтня_листопада_грудня'.split('_') }, nounCase = (/D[oD]? *MMMM?/).test(format) ? 'accusative' : 'nominative'; return months[nounCase][m.month()]; } function weekdaysCaseReplace(m, format) { var weekdays = { 'nominative': 'неділя_понеділок_вівторок_середа_четвер_п’ятниця_субота'.split('_'), 'accusative': 'неділю_понеділок_вівторок_середу_четвер_п’ятницю_суботу'.split('_'), 'genitive': 'неділі_понеділка_вівторка_середи_четверга_п’ятниці_суботи'.split('_') }, nounCase = (/(\[[ВвУу]\]) ?dddd/).test(format) ? 'accusative' : ((/\[?(?:минулої|наступної)? ?\] ?dddd/).test(format) ? 'genitive' : 'nominative'); return weekdays[nounCase][m.day()]; } function processHoursFunction(str) { return function () { return str + 'о' + (this.hours() === 11 ? 'б' : '') + '] LT'; }; } return moment.lang('uk', { months : monthsCaseReplace, monthsShort : "січ_лют_бер_квіт_трав_черв_лип_серп_вер_жовт_лист_груд".split("_"), weekdays : weekdaysCaseReplace, weekdaysShort : "нд_пн_вт_ср_чт_пт_сб".split("_"), weekdaysMin : "нд_пн_вт_ср_чт_пт_сб".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY р.", LLL : "D MMMM YYYY р., LT", LLLL : "dddd, D MMMM YYYY р., LT" }, calendar : { sameDay: processHoursFunction('[Сьогодні '), nextDay: processHoursFunction('[Завтра '), lastDay: processHoursFunction('[Вчора '), nextWeek: processHoursFunction('[У] dddd ['), lastWeek: function () { switch (this.day()) { case 0: case 3: case 5: case 6: return processHoursFunction('[Минулої] dddd [').call(this); case 1: case 2: case 4: return processHoursFunction('[Минулого] dddd [').call(this); } }, sameElse: 'L' }, relativeTime : { future : "за %s", past : "%s тому", s : "декілька секунд", m : relativeTimeWithPlural, mm : relativeTimeWithPlural, h : "годину", hh : relativeTimeWithPlural, d : "день", dd : relativeTimeWithPlural, M : "місяць", MM : relativeTimeWithPlural, y : "рік", yy : relativeTimeWithPlural }, // M. E.: those two are virtually unused but a user might want to implement them for his/her website for some reason meridiem : function (hour, minute, isLower) { if (hour < 4) { return "ночі"; } else if (hour < 12) { return "ранку"; } else if (hour < 17) { return "дня"; } else { return "вечора"; } }, ordinal: function (number, period) { switch (period) { case 'M': case 'd': case 'DDD': case 'w': case 'W': return number + '-й'; case 'D': return number + '-го'; default: return number; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : uzbek // author : Sardor Muminov : https://github.com/muminoff (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('uz', { months : "январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь".split("_"), monthsShort : "янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек".split("_"), weekdays : "Якшанба_Душанба_Сешанба_Чоршанба_Пайшанба_Жума_Шанба".split("_"), weekdaysShort : "Якш_Душ_Сеш_Чор_Пай_Жум_Шан".split("_"), weekdaysMin : "Як_Ду_Се_Чо_Па_Жу_Ша".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "D MMMM YYYY, dddd LT" }, calendar : { sameDay : '[Бугун соат] LT [да]', nextDay : '[Эртага] LT [да]', nextWeek : 'dddd [куни соат] LT [да]', lastDay : '[Кеча соат] LT [да]', lastWeek : '[Утган] dddd [куни соат] LT [да]', sameElse : 'L' }, relativeTime : { future : "Якин %s ичида", past : "Бир неча %s олдин", s : "фурсат", m : "бир дакика", mm : "%d дакика", h : "бир соат", hh : "%d соат", d : "бир кун", dd : "%d кун", M : "бир ой", MM : "%d ой", y : "бир йил", yy : "%d йил" }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : vietnamese (vn) // author : Bang Nguyen : https://github.com/bangnk (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('vn', { months : "tháng 1_tháng 2_tháng 3_tháng 4_tháng 5_tháng 6_tháng 7_tháng 8_tháng 9_tháng 10_tháng 11_tháng 12".split("_"), monthsShort : "Th01_Th02_Th03_Th04_Th05_Th06_Th07_Th08_Th09_Th10_Th11_Th12".split("_"), weekdays : "chủ nhật_thứ hai_thứ ba_thứ tư_thứ năm_thứ sáu_thứ bảy".split("_"), weekdaysShort : "CN_T2_T3_T4_T5_T6_T7".split("_"), weekdaysMin : "CN_T2_T3_T4_T5_T6_T7".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM [năm] YYYY", LLL : "D MMMM [năm] YYYY LT", LLLL : "dddd, D MMMM [năm] YYYY LT", l : "DD/M/YYYY", ll : "D MMM YYYY", lll : "D MMM YYYY LT", llll : "ddd, D MMM YYYY LT" }, calendar : { sameDay: "[Hôm nay lúc] LT", nextDay: '[Ngày mai lúc] LT', nextWeek: 'dddd [tuần tới lúc] LT', lastDay: '[Hôm qua lúc] LT', lastWeek: 'dddd [tuần rồi lúc] LT', sameElse: 'L' }, relativeTime : { future : "%s tới", past : "%s trước", s : "vài giây", m : "một phút", mm : "%d phút", h : "một giờ", hh : "%d giờ", d : "một ngày", dd : "%d ngày", M : "một tháng", MM : "%d tháng", y : "một năm", yy : "%d năm" }, ordinal : function (number) { return number; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : chinese // author : suupic : https://github.com/suupic // author : Zeno Zeng : https://github.com/zenozeng (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('zh-cn', { months : "一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"), monthsShort : "1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"), weekdays : "星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"), weekdaysShort : "周日_周一_周二_周三_周四_周五_周六".split("_"), weekdaysMin : "日_一_二_三_四_五_六".split("_"), longDateFormat : { LT : "Ah点mm", L : "YYYY-MM-DD", LL : "YYYY年MMMD日", LLL : "YYYY年MMMD日LT", LLLL : "YYYY年MMMD日ddddLT", l : "YYYY-MM-DD", ll : "YYYY年MMMD日", lll : "YYYY年MMMD日LT", llll : "YYYY年MMMD日ddddLT" }, meridiem : function (hour, minute, isLower) { var hm = hour * 100 + minute; if (hm < 600) { return "凌晨"; } else if (hm < 900) { return "早上"; } else if (hm < 1130) { return "上午"; } else if (hm < 1230) { return "中午"; } else if (hm < 1800) { return "下午"; } else { return "晚上"; } }, calendar : { sameDay : function () { return this.minutes() === 0 ? "[今天]Ah[点整]" : "[今天]LT"; }, nextDay : function () { return this.minutes() === 0 ? "[明天]Ah[点整]" : "[明天]LT"; }, lastDay : function () { return this.minutes() === 0 ? "[昨天]Ah[点整]" : "[昨天]LT"; }, nextWeek : function () { var startOfWeek, prefix; startOfWeek = moment().startOf('week'); prefix = this.unix() - startOfWeek.unix() >= 7 * 24 * 3600 ? '[下]' : '[本]'; return this.minutes() === 0 ? prefix + "dddAh点整" : prefix + "dddAh点mm"; }, lastWeek : function () { var startOfWeek, prefix; startOfWeek = moment().startOf('week'); prefix = this.unix() < startOfWeek.unix() ? '[上]' : '[本]'; return this.minutes() === 0 ? prefix + "dddAh点整" : prefix + "dddAh点mm"; }, sameElse : 'LL' }, ordinal : function (number, period) { switch (period) { case "d": case "D": case "DDD": return number + "日"; case "M": return number + "月"; case "w": case "W": return number + "周"; default: return number; } }, relativeTime : { future : "%s内", past : "%s前", s : "几秒", m : "1分钟", mm : "%d分钟", h : "1小时", hh : "%d小时", d : "1天", dd : "%d天", M : "1个月", MM : "%d个月", y : "1年", yy : "%d年" }, week : { // GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效 dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : traditional chinese (zh-tw) // author : Ben : https://github.com/ben-lin (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('zh-tw', { months : "一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"), monthsShort : "1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"), weekdays : "星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"), weekdaysShort : "週日_週一_週二_週三_週四_週五_週六".split("_"), weekdaysMin : "日_一_二_三_四_五_六".split("_"), longDateFormat : { LT : "Ah點mm", L : "YYYY年MMMD日", LL : "YYYY年MMMD日", LLL : "YYYY年MMMD日LT", LLLL : "YYYY年MMMD日ddddLT", l : "YYYY年MMMD日", ll : "YYYY年MMMD日", lll : "YYYY年MMMD日LT", llll : "YYYY年MMMD日ddddLT" }, meridiem : function (hour, minute, isLower) { var hm = hour * 100 + minute; if (hm < 900) { return "早上"; } else if (hm < 1130) { return "上午"; } else if (hm < 1230) { return "中午"; } else if (hm < 1800) { return "下午"; } else { return "晚上"; } }, calendar : { sameDay : '[今天]LT', nextDay : '[明天]LT', nextWeek : '[下]ddddLT', lastDay : '[昨天]LT', lastWeek : '[上]ddddLT', sameElse : 'L' }, ordinal : function (number, period) { switch (period) { case "d" : case "D" : case "DDD" : return number + "日"; case "M" : return number + "月"; case "w" : case "W" : return number + "週"; default : return number; } }, relativeTime : { future : "%s內", past : "%s前", s : "幾秒", m : "一分鐘", mm : "%d分鐘", h : "一小時", hh : "%d小時", d : "一天", dd : "%d天", M : "一個月", MM : "%d個月", y : "一年", yy : "%d年" } }); }));
JavaScript
//! moment.js //! version : 2.5.1 //! authors : Tim Wood, Iskren Chernev, Moment.js contributors //! license : MIT //! momentjs.com (function (undefined) { /************************************ Constants ************************************/ var moment, VERSION = "2.5.1", global = this, round = Math.round, i, YEAR = 0, MONTH = 1, DATE = 2, HOUR = 3, MINUTE = 4, SECOND = 5, MILLISECOND = 6, // internal storage for language config files languages = {}, // moment internal properties momentProperties = { _isAMomentObject: null, _i : null, _f : null, _l : null, _strict : null, _isUTC : null, _offset : null, // optional. Combine with _isUTC _pf : null, _lang : null // optional }, // check for nodeJS hasModule = (typeof module !== 'undefined' && module.exports && typeof require !== 'undefined'), // ASP.NET json date format regex aspNetJsonRegex = /^\/?Date\((\-?\d+)/i, aspNetTimeSpanJsonRegex = /(\-)?(?:(\d*)\.)?(\d+)\:(\d+)(?:\:(\d+)\.?(\d{3})?)?/, // from http://docs.closure-library.googlecode.com/git/closure_goog_date_date.js.source.html // somewhat more in line with 4.4.3.2 2004 spec, but allows decimal anywhere isoDurationRegex = /^(-)?P(?:(?:([0-9,.]*)Y)?(?:([0-9,.]*)M)?(?:([0-9,.]*)D)?(?:T(?:([0-9,.]*)H)?(?:([0-9,.]*)M)?(?:([0-9,.]*)S)?)?|([0-9,.]*)W)$/, // format tokens formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|mm?|ss?|S{1,4}|X|zz?|ZZ?|.)/g, localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g, // parsing token regexes parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99 parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999 parseTokenOneToFourDigits = /\d{1,4}/, // 0 - 9999 parseTokenOneToSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999 parseTokenDigits = /\d+/, // nonzero number of digits parseTokenWord = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i, // any word (or two) characters or numbers including two/three word month in arabic. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/gi, // +00:00 -00:00 +0000 -0000 or Z parseTokenT = /T/i, // T (ISO separator) parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123 //strict parsing regexes parseTokenOneDigit = /\d/, // 0 - 9 parseTokenTwoDigits = /\d\d/, // 00 - 99 parseTokenThreeDigits = /\d{3}/, // 000 - 999 parseTokenFourDigits = /\d{4}/, // 0000 - 9999 parseTokenSixDigits = /[+-]?\d{6}/, // -999,999 - 999,999 parseTokenSignedNumber = /[+-]?\d+/, // -inf - inf // iso 8601 regex // 0000-00-00 0000-W00 or 0000-W00-0 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 or +00) isoRegex = /^\s*(?:[+-]\d{6}|\d{4})-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/, isoFormat = 'YYYY-MM-DDTHH:mm:ssZ', isoDates = [ ['YYYYYY-MM-DD', /[+-]\d{6}-\d{2}-\d{2}/], ['YYYY-MM-DD', /\d{4}-\d{2}-\d{2}/], ['GGGG-[W]WW-E', /\d{4}-W\d{2}-\d/], ['GGGG-[W]WW', /\d{4}-W\d{2}/], ['YYYY-DDD', /\d{4}-\d{3}/] ], // iso time formats and regexes isoTimes = [ ['HH:mm:ss.SSSS', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/], ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/], ['HH:mm', /(T| )\d\d:\d\d/], ['HH', /(T| )\d\d/] ], // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"] parseTimezoneChunker = /([\+\-]|\d\d)/gi, // getter and setter names proxyGettersAndSetters = 'Date|Hours|Minutes|Seconds|Milliseconds'.split('|'), unitMillisecondFactors = { 'Milliseconds' : 1, 'Seconds' : 1e3, 'Minutes' : 6e4, 'Hours' : 36e5, 'Days' : 864e5, 'Months' : 2592e6, 'Years' : 31536e6 }, unitAliases = { ms : 'millisecond', s : 'second', m : 'minute', h : 'hour', d : 'day', D : 'date', w : 'week', W : 'isoWeek', M : 'month', y : 'year', DDD : 'dayOfYear', e : 'weekday', E : 'isoWeekday', gg: 'weekYear', GG: 'isoWeekYear' }, camelFunctions = { dayofyear : 'dayOfYear', isoweekday : 'isoWeekday', isoweek : 'isoWeek', weekyear : 'weekYear', isoweekyear : 'isoWeekYear' }, // format function strings formatFunctions = {}, // tokens to ordinalize and pad ordinalizeTokens = 'DDD w W M D d'.split(' '), paddedTokens = 'M D H h m s w W'.split(' '), formatTokenFunctions = { M : function () { return this.month() + 1; }, MMM : function (format) { return this.lang().monthsShort(this, format); }, MMMM : function (format) { return this.lang().months(this, format); }, D : function () { return this.date(); }, DDD : function () { return this.dayOfYear(); }, d : function () { return this.day(); }, dd : function (format) { return this.lang().weekdaysMin(this, format); }, ddd : function (format) { return this.lang().weekdaysShort(this, format); }, dddd : function (format) { return this.lang().weekdays(this, format); }, w : function () { return this.week(); }, W : function () { return this.isoWeek(); }, YY : function () { return leftZeroFill(this.year() % 100, 2); }, YYYY : function () { return leftZeroFill(this.year(), 4); }, YYYYY : function () { return leftZeroFill(this.year(), 5); }, YYYYYY : function () { var y = this.year(), sign = y >= 0 ? '+' : '-'; return sign + leftZeroFill(Math.abs(y), 6); }, gg : function () { return leftZeroFill(this.weekYear() % 100, 2); }, gggg : function () { return leftZeroFill(this.weekYear(), 4); }, ggggg : function () { return leftZeroFill(this.weekYear(), 5); }, GG : function () { return leftZeroFill(this.isoWeekYear() % 100, 2); }, GGGG : function () { return leftZeroFill(this.isoWeekYear(), 4); }, GGGGG : function () { return leftZeroFill(this.isoWeekYear(), 5); }, e : function () { return this.weekday(); }, E : function () { return this.isoWeekday(); }, a : function () { return this.lang().meridiem(this.hours(), this.minutes(), true); }, A : function () { return this.lang().meridiem(this.hours(), this.minutes(), false); }, H : function () { return this.hours(); }, h : function () { return this.hours() % 12 || 12; }, m : function () { return this.minutes(); }, s : function () { return this.seconds(); }, S : function () { return toInt(this.milliseconds() / 100); }, SS : function () { return leftZeroFill(toInt(this.milliseconds() / 10), 2); }, SSS : function () { return leftZeroFill(this.milliseconds(), 3); }, SSSS : function () { return leftZeroFill(this.milliseconds(), 3); }, Z : function () { var a = -this.zone(), b = "+"; if (a < 0) { a = -a; b = "-"; } return b + leftZeroFill(toInt(a / 60), 2) + ":" + leftZeroFill(toInt(a) % 60, 2); }, ZZ : function () { var a = -this.zone(), b = "+"; if (a < 0) { a = -a; b = "-"; } return b + leftZeroFill(toInt(a / 60), 2) + leftZeroFill(toInt(a) % 60, 2); }, z : function () { return this.zoneAbbr(); }, zz : function () { return this.zoneName(); }, X : function () { return this.unix(); }, Q : function () { return this.quarter(); } }, lists = ['months', 'monthsShort', 'weekdays', 'weekdaysShort', 'weekdaysMin']; function defaultParsingFlags() { // We need to deep clone this object, and es5 standard is not very // helpful. return { empty : false, unusedTokens : [], unusedInput : [], overflow : -2, charsLeftOver : 0, nullInput : false, invalidMonth : null, invalidFormat : false, userInvalidated : false, iso: false }; } function padToken(func, count) { return function (a) { return leftZeroFill(func.call(this, a), count); }; } function ordinalizeToken(func, period) { return function (a) { return this.lang().ordinal(func.call(this, a), period); }; } while (ordinalizeTokens.length) { i = ordinalizeTokens.pop(); formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i], i); } while (paddedTokens.length) { i = paddedTokens.pop(); formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2); } formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3); /************************************ Constructors ************************************/ function Language() { } // Moment prototype object function Moment(config) { checkOverflow(config); extend(this, config); } // Duration Constructor function Duration(duration) { var normalizedInput = normalizeObjectUnits(duration), years = normalizedInput.year || 0, months = normalizedInput.month || 0, weeks = normalizedInput.week || 0, days = normalizedInput.day || 0, hours = normalizedInput.hour || 0, minutes = normalizedInput.minute || 0, seconds = normalizedInput.second || 0, milliseconds = normalizedInput.millisecond || 0; // representation for dateAddRemove this._milliseconds = +milliseconds + seconds * 1e3 + // 1000 minutes * 6e4 + // 1000 * 60 hours * 36e5; // 1000 * 60 * 60 // Because of dateAddRemove treats 24 hours as different from a // day when working around DST, we need to store them separately this._days = +days + weeks * 7; // It is impossible translate months into days without knowing // which months you are are talking about, so we have to store // it separately. this._months = +months + years * 12; this._data = {}; this._bubble(); } /************************************ Helpers ************************************/ function extend(a, b) { for (var i in b) { if (b.hasOwnProperty(i)) { a[i] = b[i]; } } if (b.hasOwnProperty("toString")) { a.toString = b.toString; } if (b.hasOwnProperty("valueOf")) { a.valueOf = b.valueOf; } return a; } function cloneMoment(m) { var result = {}, i; for (i in m) { if (m.hasOwnProperty(i) && momentProperties.hasOwnProperty(i)) { result[i] = m[i]; } } return result; } function absRound(number) { if (number < 0) { return Math.ceil(number); } else { return Math.floor(number); } } // left zero fill a number // see http://jsperf.com/left-zero-filling for performance comparison function leftZeroFill(number, targetLength, forceSign) { var output = '' + Math.abs(number), sign = number >= 0; while (output.length < targetLength) { output = '0' + output; } return (sign ? (forceSign ? '+' : '') : '-') + output; } // helper function for _.addTime and _.subtractTime function addOrSubtractDurationFromMoment(mom, duration, isAdding, ignoreUpdateOffset) { var milliseconds = duration._milliseconds, days = duration._days, months = duration._months, minutes, hours; if (milliseconds) { mom._d.setTime(+mom._d + milliseconds * isAdding); } // store the minutes and hours so we can restore them if (days || months) { minutes = mom.minute(); hours = mom.hour(); } if (days) { mom.date(mom.date() + days * isAdding); } if (months) { mom.month(mom.month() + months * isAdding); } if (milliseconds && !ignoreUpdateOffset) { moment.updateOffset(mom); } // restore the minutes and hours after possibly changing dst if (days || months) { mom.minute(minutes); mom.hour(hours); } } // check if is an array function isArray(input) { return Object.prototype.toString.call(input) === '[object Array]'; } function isDate(input) { return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date; } // compare two arrays, return the number of differences function compareArrays(array1, array2, dontConvert) { var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i; for (i = 0; i < len; i++) { if ((dontConvert && array1[i] !== array2[i]) || (!dontConvert && toInt(array1[i]) !== toInt(array2[i]))) { diffs++; } } return diffs + lengthDiff; } function normalizeUnits(units) { if (units) { var lowered = units.toLowerCase().replace(/(.)s$/, '$1'); units = unitAliases[units] || camelFunctions[lowered] || lowered; } return units; } function normalizeObjectUnits(inputObject) { var normalizedInput = {}, normalizedProp, prop; for (prop in inputObject) { if (inputObject.hasOwnProperty(prop)) { normalizedProp = normalizeUnits(prop); if (normalizedProp) { normalizedInput[normalizedProp] = inputObject[prop]; } } } return normalizedInput; } function makeList(field) { var count, setter; if (field.indexOf('week') === 0) { count = 7; setter = 'day'; } else if (field.indexOf('month') === 0) { count = 12; setter = 'month'; } else { return; } moment[field] = function (format, index) { var i, getter, method = moment.fn._lang[field], results = []; if (typeof format === 'number') { index = format; format = undefined; } getter = function (i) { var m = moment().utc().set(setter, i); return method.call(moment.fn._lang, m, format || ''); }; if (index != null) { return getter(index); } else { for (i = 0; i < count; i++) { results.push(getter(i)); } return results; } }; } function toInt(argumentForCoercion) { var coercedNumber = +argumentForCoercion, value = 0; if (coercedNumber !== 0 && isFinite(coercedNumber)) { if (coercedNumber >= 0) { value = Math.floor(coercedNumber); } else { value = Math.ceil(coercedNumber); } } return value; } function daysInMonth(year, month) { return new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); } function daysInYear(year) { return isLeapYear(year) ? 366 : 365; } function isLeapYear(year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; } function checkOverflow(m) { var overflow; if (m._a && m._pf.overflow === -2) { overflow = m._a[MONTH] < 0 || m._a[MONTH] > 11 ? MONTH : m._a[DATE] < 1 || m._a[DATE] > daysInMonth(m._a[YEAR], m._a[MONTH]) ? DATE : m._a[HOUR] < 0 || m._a[HOUR] > 23 ? HOUR : m._a[MINUTE] < 0 || m._a[MINUTE] > 59 ? MINUTE : m._a[SECOND] < 0 || m._a[SECOND] > 59 ? SECOND : m._a[MILLISECOND] < 0 || m._a[MILLISECOND] > 999 ? MILLISECOND : -1; if (m._pf._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { overflow = DATE; } m._pf.overflow = overflow; } } function isValid(m) { if (m._isValid == null) { m._isValid = !isNaN(m._d.getTime()) && m._pf.overflow < 0 && !m._pf.empty && !m._pf.invalidMonth && !m._pf.nullInput && !m._pf.invalidFormat && !m._pf.userInvalidated; if (m._strict) { m._isValid = m._isValid && m._pf.charsLeftOver === 0 && m._pf.unusedTokens.length === 0; } } return m._isValid; } function normalizeLanguage(key) { return key ? key.toLowerCase().replace('_', '-') : key; } // Return a moment from input, that is local/utc/zone equivalent to model. function makeAs(input, model) { return model._isUTC ? moment(input).zone(model._offset || 0) : moment(input).local(); } /************************************ Languages ************************************/ extend(Language.prototype, { set : function (config) { var prop, i; for (i in config) { prop = config[i]; if (typeof prop === 'function') { this[i] = prop; } else { this['_' + i] = prop; } } }, _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), months : function (m) { return this._months[m.month()]; }, _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), monthsShort : function (m) { return this._monthsShort[m.month()]; }, monthsParse : function (monthName) { var i, mom, regex; if (!this._monthsParse) { this._monthsParse = []; } for (i = 0; i < 12; i++) { // make the regex if we don't have it already if (!this._monthsParse[i]) { mom = moment.utc([2000, i]); regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._monthsParse[i].test(monthName)) { return i; } } }, _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), weekdays : function (m) { return this._weekdays[m.day()]; }, _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), weekdaysShort : function (m) { return this._weekdaysShort[m.day()]; }, _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), weekdaysMin : function (m) { return this._weekdaysMin[m.day()]; }, weekdaysParse : function (weekdayName) { var i, mom, regex; if (!this._weekdaysParse) { this._weekdaysParse = []; } for (i = 0; i < 7; i++) { // make the regex if we don't have it already if (!this._weekdaysParse[i]) { mom = moment([2000, 1]).day(i); regex = '^' + this.weekdays(mom, '') + '|^' + this.weekdaysShort(mom, '') + '|^' + this.weekdaysMin(mom, ''); this._weekdaysParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._weekdaysParse[i].test(weekdayName)) { return i; } } }, _longDateFormat : { LT : "h:mm A", L : "MM/DD/YYYY", LL : "MMMM D YYYY", LLL : "MMMM D YYYY LT", LLLL : "dddd, MMMM D YYYY LT" }, longDateFormat : function (key) { var output = this._longDateFormat[key]; if (!output && this._longDateFormat[key.toUpperCase()]) { output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) { return val.slice(1); }); this._longDateFormat[key] = output; } return output; }, isPM : function (input) { // IE8 Quirks Mode & IE7 Standards Mode do not allow accessing strings like arrays // Using charAt should be more compatible. return ((input + '').toLowerCase().charAt(0) === 'p'); }, _meridiemParse : /[ap]\.?m?\.?/i, meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'pm' : 'PM'; } else { return isLower ? 'am' : 'AM'; } }, _calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, calendar : function (key, mom) { var output = this._calendar[key]; return typeof output === 'function' ? output.apply(mom) : output; }, _relativeTime : { future : "in %s", past : "%s ago", s : "a few seconds", m : "a minute", mm : "%d minutes", h : "an hour", hh : "%d hours", d : "a day", dd : "%d days", M : "a month", MM : "%d months", y : "a year", yy : "%d years" }, relativeTime : function (number, withoutSuffix, string, isFuture) { var output = this._relativeTime[string]; return (typeof output === 'function') ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number); }, pastFuture : function (diff, output) { var format = this._relativeTime[diff > 0 ? 'future' : 'past']; return typeof format === 'function' ? format(output) : format.replace(/%s/i, output); }, ordinal : function (number) { return this._ordinal.replace("%d", number); }, _ordinal : "%d", preparse : function (string) { return string; }, postformat : function (string) { return string; }, week : function (mom) { return weekOfYear(mom, this._week.dow, this._week.doy).week; }, _week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. }, _invalidDate: 'Invalid date', invalidDate: function () { return this._invalidDate; } }); // Loads a language definition into the `languages` cache. The function // takes a key and optionally values. If not in the browser and no values // are provided, it will load the language file module. As a convenience, // this function also returns the language values. function loadLang(key, values) { values.abbr = key; if (!languages[key]) { languages[key] = new Language(); } languages[key].set(values); return languages[key]; } // Remove a language from the `languages` cache. Mostly useful in tests. function unloadLang(key) { delete languages[key]; } // Determines which language definition to use and returns it. // // With no parameters, it will return the global language. If you // pass in a language key, such as 'en', it will return the // definition for 'en', so long as 'en' has already been loaded using // moment.lang. function getLangDefinition(key) { var i = 0, j, lang, next, split, get = function (k) { if (!languages[k] && hasModule) { try { require('./lang/' + k); } catch (e) { } } return languages[k]; }; if (!key) { return moment.fn._lang; } if (!isArray(key)) { //short-circuit everything else lang = get(key); if (lang) { return lang; } key = [key]; } //pick the language from the array //try ['en-au', 'en-gb'] as 'en-au', 'en-gb', 'en', as in move through the list trying each //substring from most specific to least, but move to the next array item if it's a more specific variant than the current root while (i < key.length) { split = normalizeLanguage(key[i]).split('-'); j = split.length; next = normalizeLanguage(key[i + 1]); next = next ? next.split('-') : null; while (j > 0) { lang = get(split.slice(0, j).join('-')); if (lang) { return lang; } if (next && next.length >= j && compareArrays(split, next, true) >= j - 1) { //the next array item is better than a shallower substring of this one break; } j--; } i++; } return moment.fn._lang; } /************************************ Formatting ************************************/ function removeFormattingTokens(input) { if (input.match(/\[[\s\S]/)) { return input.replace(/^\[|\]$/g, ""); } return input.replace(/\\/g, ""); } function makeFormatFunction(format) { var array = format.match(formattingTokens), i, length; for (i = 0, length = array.length; i < length; i++) { if (formatTokenFunctions[array[i]]) { array[i] = formatTokenFunctions[array[i]]; } else { array[i] = removeFormattingTokens(array[i]); } } return function (mom) { var output = ""; for (i = 0; i < length; i++) { output += array[i] instanceof Function ? array[i].call(mom, format) : array[i]; } return output; }; } // format date using native date object function formatMoment(m, format) { if (!m.isValid()) { return m.lang().invalidDate(); } format = expandFormat(format, m.lang()); if (!formatFunctions[format]) { formatFunctions[format] = makeFormatFunction(format); } return formatFunctions[format](m); } function expandFormat(format, lang) { var i = 5; function replaceLongDateFormatTokens(input) { return lang.longDateFormat(input) || input; } localFormattingTokens.lastIndex = 0; while (i >= 0 && localFormattingTokens.test(format)) { format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); localFormattingTokens.lastIndex = 0; i -= 1; } return format; } /************************************ Parsing ************************************/ // get the regex to find the next token function getParseRegexForToken(token, config) { var a, strict = config._strict; switch (token) { case 'DDDD': return parseTokenThreeDigits; case 'YYYY': case 'GGGG': case 'gggg': return strict ? parseTokenFourDigits : parseTokenOneToFourDigits; case 'Y': case 'G': case 'g': return parseTokenSignedNumber; case 'YYYYYY': case 'YYYYY': case 'GGGGG': case 'ggggg': return strict ? parseTokenSixDigits : parseTokenOneToSixDigits; case 'S': if (strict) { return parseTokenOneDigit; } /* falls through */ case 'SS': if (strict) { return parseTokenTwoDigits; } /* falls through */ case 'SSS': if (strict) { return parseTokenThreeDigits; } /* falls through */ case 'DDD': return parseTokenOneToThreeDigits; case 'MMM': case 'MMMM': case 'dd': case 'ddd': case 'dddd': return parseTokenWord; case 'a': case 'A': return getLangDefinition(config._l)._meridiemParse; case 'X': return parseTokenTimestampMs; case 'Z': case 'ZZ': return parseTokenTimezone; case 'T': return parseTokenT; case 'SSSS': return parseTokenDigits; case 'MM': case 'DD': case 'YY': case 'GG': case 'gg': case 'HH': case 'hh': case 'mm': case 'ss': case 'ww': case 'WW': return strict ? parseTokenTwoDigits : parseTokenOneOrTwoDigits; case 'M': case 'D': case 'd': case 'H': case 'h': case 'm': case 's': case 'w': case 'W': case 'e': case 'E': return parseTokenOneOrTwoDigits; default : a = new RegExp(regexpEscape(unescapeFormat(token.replace('\\', '')), "i")); return a; } } function timezoneMinutesFromString(string) { string = string || ""; var possibleTzMatches = (string.match(parseTokenTimezone) || []), tzChunk = possibleTzMatches[possibleTzMatches.length - 1] || [], parts = (tzChunk + '').match(parseTimezoneChunker) || ['-', 0, 0], minutes = +(parts[1] * 60) + toInt(parts[2]); return parts[0] === '+' ? -minutes : minutes; } // function to convert string input to date function addTimeToArrayFromToken(token, input, config) { var a, datePartArray = config._a; switch (token) { // MONTH case 'M' : // fall through to MM case 'MM' : if (input != null) { datePartArray[MONTH] = toInt(input) - 1; } break; case 'MMM' : // fall through to MMMM case 'MMMM' : a = getLangDefinition(config._l).monthsParse(input); // if we didn't find a month name, mark the date as invalid. if (a != null) { datePartArray[MONTH] = a; } else { config._pf.invalidMonth = input; } break; // DAY OF MONTH case 'D' : // fall through to DD case 'DD' : if (input != null) { datePartArray[DATE] = toInt(input); } break; // DAY OF YEAR case 'DDD' : // fall through to DDDD case 'DDDD' : if (input != null) { config._dayOfYear = toInt(input); } break; // YEAR case 'YY' : datePartArray[YEAR] = toInt(input) + (toInt(input) > 68 ? 1900 : 2000); break; case 'YYYY' : case 'YYYYY' : case 'YYYYYY' : datePartArray[YEAR] = toInt(input); break; // AM / PM case 'a' : // fall through to A case 'A' : config._isPm = getLangDefinition(config._l).isPM(input); break; // 24 HOUR case 'H' : // fall through to hh case 'HH' : // fall through to hh case 'h' : // fall through to hh case 'hh' : datePartArray[HOUR] = toInt(input); break; // MINUTE case 'm' : // fall through to mm case 'mm' : datePartArray[MINUTE] = toInt(input); break; // SECOND case 's' : // fall through to ss case 'ss' : datePartArray[SECOND] = toInt(input); break; // MILLISECOND case 'S' : case 'SS' : case 'SSS' : case 'SSSS' : datePartArray[MILLISECOND] = toInt(('0.' + input) * 1000); break; // UNIX TIMESTAMP WITH MS case 'X': config._d = new Date(parseFloat(input) * 1000); break; // TIMEZONE case 'Z' : // fall through to ZZ case 'ZZ' : config._useUTC = true; config._tzm = timezoneMinutesFromString(input); break; case 'w': case 'ww': case 'W': case 'WW': case 'd': case 'dd': case 'ddd': case 'dddd': case 'e': case 'E': token = token.substr(0, 1); /* falls through */ case 'gg': case 'gggg': case 'GG': case 'GGGG': case 'GGGGG': token = token.substr(0, 2); if (input) { config._w = config._w || {}; config._w[token] = input; } break; } } // convert an array to a date. // the array should mirror the parameters below // note: all values past the year are optional and will default to the lowest possible value. // [year, month, day , hour, minute, second, millisecond] function dateFromConfig(config) { var i, date, input = [], currentDate, yearToUse, fixYear, w, temp, lang, weekday, week; if (config._d) { return; } currentDate = currentDateArray(config); //compute day of the year from weeks and weekdays if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { fixYear = function (val) { var int_val = parseInt(val, 10); return val ? (val.length < 3 ? (int_val > 68 ? 1900 + int_val : 2000 + int_val) : int_val) : (config._a[YEAR] == null ? moment().weekYear() : config._a[YEAR]); }; w = config._w; if (w.GG != null || w.W != null || w.E != null) { temp = dayOfYearFromWeeks(fixYear(w.GG), w.W || 1, w.E, 4, 1); } else { lang = getLangDefinition(config._l); weekday = w.d != null ? parseWeekday(w.d, lang) : (w.e != null ? parseInt(w.e, 10) + lang._week.dow : 0); week = parseInt(w.w, 10) || 1; //if we're parsing 'd', then the low day numbers may be next week if (w.d != null && weekday < lang._week.dow) { week++; } temp = dayOfYearFromWeeks(fixYear(w.gg), week, weekday, lang._week.doy, lang._week.dow); } config._a[YEAR] = temp.year; config._dayOfYear = temp.dayOfYear; } //if the day of the year is set, figure out what it is if (config._dayOfYear) { yearToUse = config._a[YEAR] == null ? currentDate[YEAR] : config._a[YEAR]; if (config._dayOfYear > daysInYear(yearToUse)) { config._pf._overflowDayOfYear = true; } date = makeUTCDate(yearToUse, 0, config._dayOfYear); config._a[MONTH] = date.getUTCMonth(); config._a[DATE] = date.getUTCDate(); } // Default to current date. // * if no year, month, day of month are given, default to today // * if day of month is given, default month and year // * if month is given, default only year // * if year is given, don't default anything for (i = 0; i < 3 && config._a[i] == null; ++i) { config._a[i] = input[i] = currentDate[i]; } // Zero out whatever was not defaulted, including time for (; i < 7; i++) { config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; } // add the offsets to the time to be parsed so that we can have a clean array for checking isValid input[HOUR] += toInt((config._tzm || 0) / 60); input[MINUTE] += toInt((config._tzm || 0) % 60); config._d = (config._useUTC ? makeUTCDate : makeDate).apply(null, input); } function dateFromObject(config) { var normalizedInput; if (config._d) { return; } normalizedInput = normalizeObjectUnits(config._i); config._a = [ normalizedInput.year, normalizedInput.month, normalizedInput.day, normalizedInput.hour, normalizedInput.minute, normalizedInput.second, normalizedInput.millisecond ]; dateFromConfig(config); } function currentDateArray(config) { var now = new Date(); if (config._useUTC) { return [ now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() ]; } else { return [now.getFullYear(), now.getMonth(), now.getDate()]; } } // date from string and format string function makeDateFromStringAndFormat(config) { config._a = []; config._pf.empty = true; // This array is used to make a Date, either with `new Date` or `Date.UTC` var lang = getLangDefinition(config._l), string = '' + config._i, i, parsedInput, tokens, token, skipped, stringLength = string.length, totalParsedInputLength = 0; tokens = expandFormat(config._f, lang).match(formattingTokens) || []; for (i = 0; i < tokens.length; i++) { token = tokens[i]; parsedInput = (string.match(getParseRegexForToken(token, config)) || [])[0]; if (parsedInput) { skipped = string.substr(0, string.indexOf(parsedInput)); if (skipped.length > 0) { config._pf.unusedInput.push(skipped); } string = string.slice(string.indexOf(parsedInput) + parsedInput.length); totalParsedInputLength += parsedInput.length; } // don't parse if it's not a known token if (formatTokenFunctions[token]) { if (parsedInput) { config._pf.empty = false; } else { config._pf.unusedTokens.push(token); } addTimeToArrayFromToken(token, parsedInput, config); } else if (config._strict && !parsedInput) { config._pf.unusedTokens.push(token); } } // add remaining unparsed input length to the string config._pf.charsLeftOver = stringLength - totalParsedInputLength; if (string.length > 0) { config._pf.unusedInput.push(string); } // handle am pm if (config._isPm && config._a[HOUR] < 12) { config._a[HOUR] += 12; } // if is 12 am, change hours to 0 if (config._isPm === false && config._a[HOUR] === 12) { config._a[HOUR] = 0; } dateFromConfig(config); checkOverflow(config); } function unescapeFormat(s) { return s.replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (matched, p1, p2, p3, p4) { return p1 || p2 || p3 || p4; }); } // Code from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript function regexpEscape(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); } // date from string and array of format strings function makeDateFromStringAndArray(config) { var tempConfig, bestMoment, scoreToBeat, i, currentScore; if (config._f.length === 0) { config._pf.invalidFormat = true; config._d = new Date(NaN); return; } for (i = 0; i < config._f.length; i++) { currentScore = 0; tempConfig = extend({}, config); tempConfig._pf = defaultParsingFlags(); tempConfig._f = config._f[i]; makeDateFromStringAndFormat(tempConfig); if (!isValid(tempConfig)) { continue; } // if there is any input that was not parsed add a penalty for that format currentScore += tempConfig._pf.charsLeftOver; //or tokens currentScore += tempConfig._pf.unusedTokens.length * 10; tempConfig._pf.score = currentScore; if (scoreToBeat == null || currentScore < scoreToBeat) { scoreToBeat = currentScore; bestMoment = tempConfig; } } extend(config, bestMoment || tempConfig); } // date from iso format function makeDateFromString(config) { var i, l, string = config._i, match = isoRegex.exec(string); if (match) { config._pf.iso = true; for (i = 0, l = isoDates.length; i < l; i++) { if (isoDates[i][1].exec(string)) { // match[5] should be "T" or undefined config._f = isoDates[i][0] + (match[6] || " "); break; } } for (i = 0, l = isoTimes.length; i < l; i++) { if (isoTimes[i][1].exec(string)) { config._f += isoTimes[i][0]; break; } } if (string.match(parseTokenTimezone)) { config._f += "Z"; } makeDateFromStringAndFormat(config); } else { config._d = new Date(string); } } function makeDateFromInput(config) { var input = config._i, matched = aspNetJsonRegex.exec(input); if (input === undefined) { config._d = new Date(); } else if (matched) { config._d = new Date(+matched[1]); } else if (typeof input === 'string') { makeDateFromString(config); } else if (isArray(input)) { config._a = input.slice(0); dateFromConfig(config); } else if (isDate(input)) { config._d = new Date(+input); } else if (typeof(input) === 'object') { dateFromObject(config); } else { config._d = new Date(input); } } function makeDate(y, m, d, h, M, s, ms) { //can't just apply() to create a date: //http://stackoverflow.com/questions/181348/instantiating-a-javascript-object-by-calling-prototype-constructor-apply var date = new Date(y, m, d, h, M, s, ms); //the date constructor doesn't accept years < 1970 if (y < 1970) { date.setFullYear(y); } return date; } function makeUTCDate(y) { var date = new Date(Date.UTC.apply(null, arguments)); if (y < 1970) { date.setUTCFullYear(y); } return date; } function parseWeekday(input, language) { if (typeof input === 'string') { if (!isNaN(input)) { input = parseInt(input, 10); } else { input = language.weekdaysParse(input); if (typeof input !== 'number') { return null; } } } return input; } /************************************ Relative Time ************************************/ // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) { return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture); } function relativeTime(milliseconds, withoutSuffix, lang) { var seconds = round(Math.abs(milliseconds) / 1000), minutes = round(seconds / 60), hours = round(minutes / 60), days = round(hours / 24), years = round(days / 365), args = seconds < 45 && ['s', seconds] || minutes === 1 && ['m'] || minutes < 45 && ['mm', minutes] || hours === 1 && ['h'] || hours < 22 && ['hh', hours] || days === 1 && ['d'] || days <= 25 && ['dd', days] || days <= 45 && ['M'] || days < 345 && ['MM', round(days / 30)] || years === 1 && ['y'] || ['yy', years]; args[2] = withoutSuffix; args[3] = milliseconds > 0; args[4] = lang; return substituteTimeAgo.apply({}, args); } /************************************ Week of Year ************************************/ // firstDayOfWeek 0 = sun, 6 = sat // the day of the week that starts the week // (usually sunday or monday) // firstDayOfWeekOfYear 0 = sun, 6 = sat // the first week is the week that contains the first // of this day of the week // (eg. ISO weeks use thursday (4)) function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) { var end = firstDayOfWeekOfYear - firstDayOfWeek, daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(), adjustedMoment; if (daysToDayOfWeek > end) { daysToDayOfWeek -= 7; } if (daysToDayOfWeek < end - 7) { daysToDayOfWeek += 7; } adjustedMoment = moment(mom).add('d', daysToDayOfWeek); return { week: Math.ceil(adjustedMoment.dayOfYear() / 7), year: adjustedMoment.year() }; } //http://en.wikipedia.org/wiki/ISO_week_date#Calculating_a_date_given_the_year.2C_week_number_and_weekday function dayOfYearFromWeeks(year, week, weekday, firstDayOfWeekOfYear, firstDayOfWeek) { var d = makeUTCDate(year, 0, 1).getUTCDay(), daysToAdd, dayOfYear; weekday = weekday != null ? weekday : firstDayOfWeek; daysToAdd = firstDayOfWeek - d + (d > firstDayOfWeekOfYear ? 7 : 0) - (d < firstDayOfWeek ? 7 : 0); dayOfYear = 7 * (week - 1) + (weekday - firstDayOfWeek) + daysToAdd + 1; return { year: dayOfYear > 0 ? year : year - 1, dayOfYear: dayOfYear > 0 ? dayOfYear : daysInYear(year - 1) + dayOfYear }; } /************************************ Top Level Functions ************************************/ function makeMoment(config) { var input = config._i, format = config._f; if (input === null) { return moment.invalid({nullInput: true}); } if (typeof input === 'string') { config._i = input = getLangDefinition().preparse(input); } if (moment.isMoment(input)) { config = cloneMoment(input); config._d = new Date(+input._d); } else if (format) { if (isArray(format)) { makeDateFromStringAndArray(config); } else { makeDateFromStringAndFormat(config); } } else { makeDateFromInput(config); } return new Moment(config); } moment = function (input, format, lang, strict) { var c; if (typeof(lang) === "boolean") { strict = lang; lang = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c = {}; c._isAMomentObject = true; c._i = input; c._f = format; c._l = lang; c._strict = strict; c._isUTC = false; c._pf = defaultParsingFlags(); return makeMoment(c); }; // creating with utc moment.utc = function (input, format, lang, strict) { var c; if (typeof(lang) === "boolean") { strict = lang; lang = undefined; } // object construction must be done this way. // https://github.com/moment/moment/issues/1423 c = {}; c._isAMomentObject = true; c._useUTC = true; c._isUTC = true; c._l = lang; c._i = input; c._f = format; c._strict = strict; c._pf = defaultParsingFlags(); return makeMoment(c).utc(); }; // creating with unix timestamp (in seconds) moment.unix = function (input) { return moment(input * 1000); }; // duration moment.duration = function (input, key) { var duration = input, // matching against regexp is expensive, do it on demand match = null, sign, ret, parseIso; if (moment.isDuration(input)) { duration = { ms: input._milliseconds, d: input._days, M: input._months }; } else if (typeof input === 'number') { duration = {}; if (key) { duration[key] = input; } else { duration.milliseconds = input; } } else if (!!(match = aspNetTimeSpanJsonRegex.exec(input))) { sign = (match[1] === "-") ? -1 : 1; duration = { y: 0, d: toInt(match[DATE]) * sign, h: toInt(match[HOUR]) * sign, m: toInt(match[MINUTE]) * sign, s: toInt(match[SECOND]) * sign, ms: toInt(match[MILLISECOND]) * sign }; } else if (!!(match = isoDurationRegex.exec(input))) { sign = (match[1] === "-") ? -1 : 1; parseIso = function (inp) { // We'd normally use ~~inp for this, but unfortunately it also // converts floats to ints. // inp may be undefined, so careful calling replace on it. var res = inp && parseFloat(inp.replace(',', '.')); // apply sign while we're at it return (isNaN(res) ? 0 : res) * sign; }; duration = { y: parseIso(match[2]), M: parseIso(match[3]), d: parseIso(match[4]), h: parseIso(match[5]), m: parseIso(match[6]), s: parseIso(match[7]), w: parseIso(match[8]) }; } ret = new Duration(duration); if (moment.isDuration(input) && input.hasOwnProperty('_lang')) { ret._lang = input._lang; } return ret; }; // version number moment.version = VERSION; // default format moment.defaultFormat = isoFormat; // This function will be called whenever a moment is mutated. // It is intended to keep the offset in sync with the timezone. moment.updateOffset = function () {}; // This function will load languages and then set the global language. If // no arguments are passed in, it will simply return the current global // language key. moment.lang = function (key, values) { var r; if (!key) { return moment.fn._lang._abbr; } if (values) { loadLang(normalizeLanguage(key), values); } else if (values === null) { unloadLang(key); key = 'en'; } else if (!languages[key]) { getLangDefinition(key); } r = moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key); return r._abbr; }; // returns language data moment.langData = function (key) { if (key && key._lang && key._lang._abbr) { key = key._lang._abbr; } return getLangDefinition(key); }; // compare moment object moment.isMoment = function (obj) { return obj instanceof Moment || (obj != null && obj.hasOwnProperty('_isAMomentObject')); }; // for typechecking Duration objects moment.isDuration = function (obj) { return obj instanceof Duration; }; for (i = lists.length - 1; i >= 0; --i) { makeList(lists[i]); } moment.normalizeUnits = function (units) { return normalizeUnits(units); }; moment.invalid = function (flags) { var m = moment.utc(NaN); if (flags != null) { extend(m._pf, flags); } else { m._pf.userInvalidated = true; } return m; }; moment.parseZone = function (input) { return moment(input).parseZone(); }; /************************************ Moment Prototype ************************************/ extend(moment.fn = Moment.prototype, { clone : function () { return moment(this); }, valueOf : function () { return +this._d + ((this._offset || 0) * 60000); }, unix : function () { return Math.floor(+this / 1000); }, toString : function () { return this.clone().lang('en').format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ"); }, toDate : function () { return this._offset ? new Date(+this) : this._d; }, toISOString : function () { var m = moment(this).utc(); if (0 < m.year() && m.year() <= 9999) { return formatMoment(m, 'YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } else { return formatMoment(m, 'YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); } }, toArray : function () { var m = this; return [ m.year(), m.month(), m.date(), m.hours(), m.minutes(), m.seconds(), m.milliseconds() ]; }, isValid : function () { return isValid(this); }, isDSTShifted : function () { if (this._a) { return this.isValid() && compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()) > 0; } return false; }, parsingFlags : function () { return extend({}, this._pf); }, invalidAt: function () { return this._pf.overflow; }, utc : function () { return this.zone(0); }, local : function () { this.zone(0); this._isUTC = false; return this; }, format : function (inputString) { var output = formatMoment(this, inputString || moment.defaultFormat); return this.lang().postformat(output); }, add : function (input, val) { var dur; // switch args to support add('s', 1) and add(1, 's') if (typeof input === 'string') { dur = moment.duration(+val, input); } else { dur = moment.duration(input, val); } addOrSubtractDurationFromMoment(this, dur, 1); return this; }, subtract : function (input, val) { var dur; // switch args to support subtract('s', 1) and subtract(1, 's') if (typeof input === 'string') { dur = moment.duration(+val, input); } else { dur = moment.duration(input, val); } addOrSubtractDurationFromMoment(this, dur, -1); return this; }, diff : function (input, units, asFloat) { var that = makeAs(input, this), zoneDiff = (this.zone() - that.zone()) * 6e4, diff, output; units = normalizeUnits(units); if (units === 'year' || units === 'month') { // average number of days in the months in the given dates diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2 // difference in months output = ((this.year() - that.year()) * 12) + (this.month() - that.month()); // adjust by taking difference in days, average number of days // and dst in the given months. output += ((this - moment(this).startOf('month')) - (that - moment(that).startOf('month'))) / diff; // same as above but with zones, to negate all dst output -= ((this.zone() - moment(this).startOf('month').zone()) - (that.zone() - moment(that).startOf('month').zone())) * 6e4 / diff; if (units === 'year') { output = output / 12; } } else { diff = (this - that); output = units === 'second' ? diff / 1e3 : // 1000 units === 'minute' ? diff / 6e4 : // 1000 * 60 units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60 units === 'day' ? (diff - zoneDiff) / 864e5 : // 1000 * 60 * 60 * 24, negate dst units === 'week' ? (diff - zoneDiff) / 6048e5 : // 1000 * 60 * 60 * 24 * 7, negate dst diff; } return asFloat ? output : absRound(output); }, from : function (time, withoutSuffix) { return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix); }, fromNow : function (withoutSuffix) { return this.from(moment(), withoutSuffix); }, calendar : function () { // We want to compare the start of today, vs this. // Getting start-of-today depends on whether we're zone'd or not. var sod = makeAs(moment(), this).startOf('day'), diff = this.diff(sod, 'days', true), format = diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse'; return this.format(this.lang().calendar(format, this)); }, isLeapYear : function () { return isLeapYear(this.year()); }, isDST : function () { return (this.zone() < this.clone().month(0).zone() || this.zone() < this.clone().month(5).zone()); }, day : function (input) { var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); if (input != null) { input = parseWeekday(input, this.lang()); return this.add({ d : input - day }); } else { return day; } }, month : function (input) { var utc = this._isUTC ? 'UTC' : '', dayOfMonth; if (input != null) { if (typeof input === 'string') { input = this.lang().monthsParse(input); if (typeof input !== 'number') { return this; } } dayOfMonth = this.date(); this.date(1); this._d['set' + utc + 'Month'](input); this.date(Math.min(dayOfMonth, this.daysInMonth())); moment.updateOffset(this); return this; } else { return this._d['get' + utc + 'Month'](); } }, startOf: function (units) { units = normalizeUnits(units); // the following switch intentionally omits break keywords // to utilize falling through the cases. switch (units) { case 'year': this.month(0); /* falls through */ case 'month': this.date(1); /* falls through */ case 'week': case 'isoWeek': case 'day': this.hours(0); /* falls through */ case 'hour': this.minutes(0); /* falls through */ case 'minute': this.seconds(0); /* falls through */ case 'second': this.milliseconds(0); /* falls through */ } // weeks are a special case if (units === 'week') { this.weekday(0); } else if (units === 'isoWeek') { this.isoWeekday(1); } return this; }, endOf: function (units) { units = normalizeUnits(units); return this.startOf(units).add((units === 'isoWeek' ? 'week' : units), 1).subtract('ms', 1); }, isAfter: function (input, units) { units = typeof units !== 'undefined' ? units : 'millisecond'; return +this.clone().startOf(units) > +moment(input).startOf(units); }, isBefore: function (input, units) { units = typeof units !== 'undefined' ? units : 'millisecond'; return +this.clone().startOf(units) < +moment(input).startOf(units); }, isSame: function (input, units) { units = units || 'ms'; return +this.clone().startOf(units) === +makeAs(input, this).startOf(units); }, min: function (other) { other = moment.apply(null, arguments); return other < this ? this : other; }, max: function (other) { other = moment.apply(null, arguments); return other > this ? this : other; }, zone : function (input) { var offset = this._offset || 0; if (input != null) { if (typeof input === "string") { input = timezoneMinutesFromString(input); } if (Math.abs(input) < 16) { input = input * 60; } this._offset = input; this._isUTC = true; if (offset !== input) { addOrSubtractDurationFromMoment(this, moment.duration(offset - input, 'm'), 1, true); } } else { return this._isUTC ? offset : this._d.getTimezoneOffset(); } return this; }, zoneAbbr : function () { return this._isUTC ? "UTC" : ""; }, zoneName : function () { return this._isUTC ? "Coordinated Universal Time" : ""; }, parseZone : function () { if (this._tzm) { this.zone(this._tzm); } else if (typeof this._i === 'string') { this.zone(this._i); } return this; }, hasAlignedHourOffset : function (input) { if (!input) { input = 0; } else { input = moment(input).zone(); } return (this.zone() - input) % 60 === 0; }, daysInMonth : function () { return daysInMonth(this.year(), this.month()); }, dayOfYear : function (input) { var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1; return input == null ? dayOfYear : this.add("d", (input - dayOfYear)); }, quarter : function () { return Math.ceil((this.month() + 1.0) / 3.0); }, weekYear : function (input) { var year = weekOfYear(this, this.lang()._week.dow, this.lang()._week.doy).year; return input == null ? year : this.add("y", (input - year)); }, isoWeekYear : function (input) { var year = weekOfYear(this, 1, 4).year; return input == null ? year : this.add("y", (input - year)); }, week : function (input) { var week = this.lang().week(this); return input == null ? week : this.add("d", (input - week) * 7); }, isoWeek : function (input) { var week = weekOfYear(this, 1, 4).week; return input == null ? week : this.add("d", (input - week) * 7); }, weekday : function (input) { var weekday = (this.day() + 7 - this.lang()._week.dow) % 7; return input == null ? weekday : this.add("d", input - weekday); }, isoWeekday : function (input) { // behaves the same as moment#day except // as a getter, returns 7 instead of 0 (1-7 range instead of 0-6) // as a setter, sunday should belong to the previous week. return input == null ? this.day() || 7 : this.day(this.day() % 7 ? input : input - 7); }, get : function (units) { units = normalizeUnits(units); return this[units](); }, set : function (units, value) { units = normalizeUnits(units); if (typeof this[units] === 'function') { this[units](value); } return this; }, // If passed a language key, it will set the language for this // instance. Otherwise, it will return the language configuration // variables for this instance. lang : function (key) { if (key === undefined) { return this._lang; } else { this._lang = getLangDefinition(key); return this; } } }); // helper for adding shortcuts function makeGetterAndSetter(name, key) { moment.fn[name] = moment.fn[name + 's'] = function (input) { var utc = this._isUTC ? 'UTC' : ''; if (input != null) { this._d['set' + utc + key](input); moment.updateOffset(this); return this; } else { return this._d['get' + utc + key](); } }; } // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds) for (i = 0; i < proxyGettersAndSetters.length; i ++) { makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]); } // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear') makeGetterAndSetter('year', 'FullYear'); // add plural methods moment.fn.days = moment.fn.day; moment.fn.months = moment.fn.month; moment.fn.weeks = moment.fn.week; moment.fn.isoWeeks = moment.fn.isoWeek; // add aliased format methods moment.fn.toJSON = moment.fn.toISOString; /************************************ Duration Prototype ************************************/ extend(moment.duration.fn = Duration.prototype, { _bubble : function () { var milliseconds = this._milliseconds, days = this._days, months = this._months, data = this._data, seconds, minutes, hours, years; // The following code bubbles up values, see the tests for // examples of what that means. data.milliseconds = milliseconds % 1000; seconds = absRound(milliseconds / 1000); data.seconds = seconds % 60; minutes = absRound(seconds / 60); data.minutes = minutes % 60; hours = absRound(minutes / 60); data.hours = hours % 24; days += absRound(hours / 24); data.days = days % 30; months += absRound(days / 30); data.months = months % 12; years = absRound(months / 12); data.years = years; }, weeks : function () { return absRound(this.days() / 7); }, valueOf : function () { return this._milliseconds + this._days * 864e5 + (this._months % 12) * 2592e6 + toInt(this._months / 12) * 31536e6; }, humanize : function (withSuffix) { var difference = +this, output = relativeTime(difference, !withSuffix, this.lang()); if (withSuffix) { output = this.lang().pastFuture(difference, output); } return this.lang().postformat(output); }, add : function (input, val) { // supports only 2.0-style add(1, 's') or add(moment) var dur = moment.duration(input, val); this._milliseconds += dur._milliseconds; this._days += dur._days; this._months += dur._months; this._bubble(); return this; }, subtract : function (input, val) { var dur = moment.duration(input, val); this._milliseconds -= dur._milliseconds; this._days -= dur._days; this._months -= dur._months; this._bubble(); return this; }, get : function (units) { units = normalizeUnits(units); return this[units.toLowerCase() + 's'](); }, as : function (units) { units = normalizeUnits(units); return this['as' + units.charAt(0).toUpperCase() + units.slice(1) + 's'](); }, lang : moment.fn.lang, toIsoString : function () { // inspired by https://github.com/dordille/moment-isoduration/blob/master/moment.isoduration.js var years = Math.abs(this.years()), months = Math.abs(this.months()), days = Math.abs(this.days()), hours = Math.abs(this.hours()), minutes = Math.abs(this.minutes()), seconds = Math.abs(this.seconds() + this.milliseconds() / 1000); if (!this.asSeconds()) { // this is the same as C#'s (Noda) and python (isodate)... // but not other JS (goog.date) return 'P0D'; } return (this.asSeconds() < 0 ? '-' : '') + 'P' + (years ? years + 'Y' : '') + (months ? months + 'M' : '') + (days ? days + 'D' : '') + ((hours || minutes || seconds) ? 'T' : '') + (hours ? hours + 'H' : '') + (minutes ? minutes + 'M' : '') + (seconds ? seconds + 'S' : ''); } }); function makeDurationGetter(name) { moment.duration.fn[name] = function () { return this._data[name]; }; } function makeDurationAsGetter(name, factor) { moment.duration.fn['as' + name] = function () { return +this / factor; }; } for (i in unitMillisecondFactors) { if (unitMillisecondFactors.hasOwnProperty(i)) { makeDurationAsGetter(i, unitMillisecondFactors[i]); makeDurationGetter(i.toLowerCase()); } } makeDurationAsGetter('Weeks', 6048e5); moment.duration.fn.asMonths = function () { return (+this - this.years() * 31536e6) / 2592e6 + this.years() * 12; }; /************************************ Default Lang ************************************/ // Set default language, other languages will inherit from English. moment.lang('en', { ordinal : function (number) { var b = number % 10, output = (toInt(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); // moment.js language configuration // language : Moroccan Arabic (ar-ma) // author : ElFadili Yassine : https://github.com/ElFadiliY // author : Abdel Said : https://github.com/abdelsaid (function (factory) { factory(moment); }(function (moment) { return moment.lang('ar-ma', { months : "يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"), monthsShort : "يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر".split("_"), weekdays : "الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"), weekdaysShort : "احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت".split("_"), weekdaysMin : "ح_ن_ث_ر_خ_ج_س".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[اليوم على الساعة] LT", nextDay: '[غدا على الساعة] LT', nextWeek: 'dddd [على الساعة] LT', lastDay: '[أمس على الساعة] LT', lastWeek: 'dddd [على الساعة] LT', sameElse: 'L' }, relativeTime : { future : "في %s", past : "منذ %s", s : "ثوان", m : "دقيقة", mm : "%d دقائق", h : "ساعة", hh : "%d ساعات", d : "يوم", dd : "%d أيام", M : "شهر", MM : "%d أشهر", y : "سنة", yy : "%d سنوات" }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Arabic (ar) // author : Abdel Said : https://github.com/abdelsaid // changes in months, weekdays : Ahmed Elkhatib (function (factory) { factory(moment); }(function (moment) { return moment.lang('ar', { months : "يناير/ كانون الثاني_فبراير/ شباط_مارس/ آذار_أبريل/ نيسان_مايو/ أيار_يونيو/ حزيران_يوليو/ تموز_أغسطس/ آب_سبتمبر/ أيلول_أكتوبر/ تشرين الأول_نوفمبر/ تشرين الثاني_ديسمبر/ كانون الأول".split("_"), monthsShort : "يناير/ كانون الثاني_فبراير/ شباط_مارس/ آذار_أبريل/ نيسان_مايو/ أيار_يونيو/ حزيران_يوليو/ تموز_أغسطس/ آب_سبتمبر/ أيلول_أكتوبر/ تشرين الأول_نوفمبر/ تشرين الثاني_ديسمبر/ كانون الأول".split("_"), weekdays : "الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"), weekdaysShort : "الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت".split("_"), weekdaysMin : "ح_ن_ث_ر_خ_ج_س".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[اليوم على الساعة] LT", nextDay: '[غدا على الساعة] LT', nextWeek: 'dddd [على الساعة] LT', lastDay: '[أمس على الساعة] LT', lastWeek: 'dddd [على الساعة] LT', sameElse: 'L' }, relativeTime : { future : "في %s", past : "منذ %s", s : "ثوان", m : "دقيقة", mm : "%d دقائق", h : "ساعة", hh : "%d ساعات", d : "يوم", dd : "%d أيام", M : "شهر", MM : "%d أشهر", y : "سنة", yy : "%d سنوات" }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : bulgarian (bg) // author : Krasen Borisov : https://github.com/kraz (function (factory) { factory(moment); }(function (moment) { return moment.lang('bg', { months : "януари_февруари_март_април_май_юни_юли_август_септември_октомври_ноември_декември".split("_"), monthsShort : "янр_фев_мар_апр_май_юни_юли_авг_сеп_окт_ное_дек".split("_"), weekdays : "неделя_понеделник_вторник_сряда_четвъртък_петък_събота".split("_"), weekdaysShort : "нед_пон_вто_сря_чет_пет_съб".split("_"), weekdaysMin : "нд_пн_вт_ср_чт_пт_сб".split("_"), longDateFormat : { LT : "H:mm", L : "D.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[Днес в] LT', nextDay : '[Утре в] LT', nextWeek : 'dddd [в] LT', lastDay : '[Вчера в] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: case 6: return '[В изминалата] dddd [в] LT'; case 1: case 2: case 4: case 5: return '[В изминалия] dddd [в] LT'; } }, sameElse : 'L' }, relativeTime : { future : "след %s", past : "преди %s", s : "няколко секунди", m : "минута", mm : "%d минути", h : "час", hh : "%d часа", d : "ден", dd : "%d дни", M : "месец", MM : "%d месеца", y : "година", yy : "%d години" }, ordinal : function (number) { var lastDigit = number % 10, last2Digits = number % 100; if (number === 0) { return number + '-ев'; } else if (last2Digits === 0) { return number + '-ен'; } else if (last2Digits > 10 && last2Digits < 20) { return number + '-ти'; } else if (lastDigit === 1) { return number + '-ви'; } else if (lastDigit === 2) { return number + '-ри'; } else if (lastDigit === 7 || lastDigit === 8) { return number + '-ми'; } else { return number + '-ти'; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : breton (br) // author : Jean-Baptiste Le Duigou : https://github.com/jbleduigou (function (factory) { factory(moment); }(function (moment) { function relativeTimeWithMutation(number, withoutSuffix, key) { var format = { 'mm': "munutenn", 'MM': "miz", 'dd': "devezh" }; return number + ' ' + mutation(format[key], number); } function specialMutationForYears(number) { switch (lastNumber(number)) { case 1: case 3: case 4: case 5: case 9: return number + ' bloaz'; default: return number + ' vloaz'; } } function lastNumber(number) { if (number > 9) { return lastNumber(number % 10); } return number; } function mutation(text, number) { if (number === 2) { return softMutation(text); } return text; } function softMutation(text) { var mutationTable = { 'm': 'v', 'b': 'v', 'd': 'z' }; if (mutationTable[text.charAt(0)] === undefined) { return text; } return mutationTable[text.charAt(0)] + text.substring(1); } return moment.lang('br', { months : "Genver_C'hwevrer_Meurzh_Ebrel_Mae_Mezheven_Gouere_Eost_Gwengolo_Here_Du_Kerzu".split("_"), monthsShort : "Gen_C'hwe_Meu_Ebr_Mae_Eve_Gou_Eos_Gwe_Her_Du_Ker".split("_"), weekdays : "Sul_Lun_Meurzh_Merc'her_Yaou_Gwener_Sadorn".split("_"), weekdaysShort : "Sul_Lun_Meu_Mer_Yao_Gwe_Sad".split("_"), weekdaysMin : "Su_Lu_Me_Mer_Ya_Gw_Sa".split("_"), longDateFormat : { LT : "h[e]mm A", L : "DD/MM/YYYY", LL : "D [a viz] MMMM YYYY", LLL : "D [a viz] MMMM YYYY LT", LLLL : "dddd, D [a viz] MMMM YYYY LT" }, calendar : { sameDay : '[Hiziv da] LT', nextDay : '[Warc\'hoazh da] LT', nextWeek : 'dddd [da] LT', lastDay : '[Dec\'h da] LT', lastWeek : 'dddd [paset da] LT', sameElse : 'L' }, relativeTime : { future : "a-benn %s", past : "%s 'zo", s : "un nebeud segondennoù", m : "ur vunutenn", mm : relativeTimeWithMutation, h : "un eur", hh : "%d eur", d : "un devezh", dd : relativeTimeWithMutation, M : "ur miz", MM : relativeTimeWithMutation, y : "ur bloaz", yy : specialMutationForYears }, ordinal : function (number) { var output = (number === 1) ? 'añ' : 'vet'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : bosnian (bs) // author : Nedim Cholich : https://github.com/frontyard // based on (hr) translation by Bojan Marković (function (factory) { factory(moment); }(function (moment) { function translate(number, withoutSuffix, key) { var result = number + " "; switch (key) { case 'm': return withoutSuffix ? 'jedna minuta' : 'jedne minute'; case 'mm': if (number === 1) { result += 'minuta'; } else if (number === 2 || number === 3 || number === 4) { result += 'minute'; } else { result += 'minuta'; } return result; case 'h': return withoutSuffix ? 'jedan sat' : 'jednog sata'; case 'hh': if (number === 1) { result += 'sat'; } else if (number === 2 || number === 3 || number === 4) { result += 'sata'; } else { result += 'sati'; } return result; case 'dd': if (number === 1) { result += 'dan'; } else { result += 'dana'; } return result; case 'MM': if (number === 1) { result += 'mjesec'; } else if (number === 2 || number === 3 || number === 4) { result += 'mjeseca'; } else { result += 'mjeseci'; } return result; case 'yy': if (number === 1) { result += 'godina'; } else if (number === 2 || number === 3 || number === 4) { result += 'godine'; } else { result += 'godina'; } return result; } } return moment.lang('bs', { months : "januar_februar_mart_april_maj_juni_juli_avgust_septembar_oktobar_novembar_decembar".split("_"), monthsShort : "jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.".split("_"), weekdays : "nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota".split("_"), weekdaysShort : "ned._pon._uto._sri._čet._pet._sub.".split("_"), weekdaysMin : "ne_po_ut_sr_če_pe_su".split("_"), longDateFormat : { LT : "H:mm", L : "DD. MM. YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay : '[danas u] LT', nextDay : '[sutra u] LT', nextWeek : function () { switch (this.day()) { case 0: return '[u] [nedjelju] [u] LT'; case 3: return '[u] [srijedu] [u] LT'; case 6: return '[u] [subotu] [u] LT'; case 1: case 2: case 4: case 5: return '[u] dddd [u] LT'; } }, lastDay : '[jučer u] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: return '[prošlu] dddd [u] LT'; case 6: return '[prošle] [subote] [u] LT'; case 1: case 2: case 4: case 5: return '[prošli] dddd [u] LT'; } }, sameElse : 'L' }, relativeTime : { future : "za %s", past : "prije %s", s : "par sekundi", m : translate, mm : translate, h : translate, hh : translate, d : "dan", dd : translate, M : "mjesec", MM : translate, y : "godinu", yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : catalan (ca) // author : Juan G. Hurtado : https://github.com/juanghurtado (function (factory) { factory(moment); }(function (moment) { return moment.lang('ca', { months : "gener_febrer_març_abril_maig_juny_juliol_agost_setembre_octubre_novembre_desembre".split("_"), monthsShort : "gen._febr._mar._abr._mai._jun._jul._ag._set._oct._nov._des.".split("_"), weekdays : "diumenge_dilluns_dimarts_dimecres_dijous_divendres_dissabte".split("_"), weekdaysShort : "dg._dl._dt._dc._dj._dv._ds.".split("_"), weekdaysMin : "Dg_Dl_Dt_Dc_Dj_Dv_Ds".split("_"), longDateFormat : { LT : "H:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay : function () { return '[avui a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, nextDay : function () { return '[demà a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, nextWeek : function () { return 'dddd [a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, lastDay : function () { return '[ahir a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, lastWeek : function () { return '[el] dddd [passat a ' + ((this.hours() !== 1) ? 'les' : 'la') + '] LT'; }, sameElse : 'L' }, relativeTime : { future : "en %s", past : "fa %s", s : "uns segons", m : "un minut", mm : "%d minuts", h : "una hora", hh : "%d hores", d : "un dia", dd : "%d dies", M : "un mes", MM : "%d mesos", y : "un any", yy : "%d anys" }, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : czech (cs) // author : petrbela : https://github.com/petrbela (function (factory) { factory(moment); }(function (moment) { var months = "leden_únor_březen_duben_květen_červen_červenec_srpen_září_říjen_listopad_prosinec".split("_"), monthsShort = "led_úno_bře_dub_kvě_čvn_čvc_srp_zář_říj_lis_pro".split("_"); function plural(n) { return (n > 1) && (n < 5) && (~~(n / 10) !== 1); } function translate(number, withoutSuffix, key, isFuture) { var result = number + " "; switch (key) { case 's': // a few seconds / in a few seconds / a few seconds ago return (withoutSuffix || isFuture) ? 'pár vteřin' : 'pár vteřinami'; case 'm': // a minute / in a minute / a minute ago return withoutSuffix ? 'minuta' : (isFuture ? 'minutu' : 'minutou'); case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'minuty' : 'minut'); } else { return result + 'minutami'; } break; case 'h': // an hour / in an hour / an hour ago return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou'); case 'hh': // 9 hours / in 9 hours / 9 hours ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'hodiny' : 'hodin'); } else { return result + 'hodinami'; } break; case 'd': // a day / in a day / a day ago return (withoutSuffix || isFuture) ? 'den' : 'dnem'; case 'dd': // 9 days / in 9 days / 9 days ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'dny' : 'dní'); } else { return result + 'dny'; } break; case 'M': // a month / in a month / a month ago return (withoutSuffix || isFuture) ? 'měsíc' : 'měsícem'; case 'MM': // 9 months / in 9 months / 9 months ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'měsíce' : 'měsíců'); } else { return result + 'měsíci'; } break; case 'y': // a year / in a year / a year ago return (withoutSuffix || isFuture) ? 'rok' : 'rokem'; case 'yy': // 9 years / in 9 years / 9 years ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'roky' : 'let'); } else { return result + 'lety'; } break; } } return moment.lang('cs', { months : months, monthsShort : monthsShort, monthsParse : (function (months, monthsShort) { var i, _monthsParse = []; for (i = 0; i < 12; i++) { // use custom parser to solve problem with July (červenec) _monthsParse[i] = new RegExp('^' + months[i] + '$|^' + monthsShort[i] + '$', 'i'); } return _monthsParse; }(months, monthsShort)), weekdays : "neděle_pondělí_úterý_středa_čtvrtek_pátek_sobota".split("_"), weekdaysShort : "ne_po_út_st_čt_pá_so".split("_"), weekdaysMin : "ne_po_út_st_čt_pá_so".split("_"), longDateFormat : { LT: "H:mm", L : "DD.MM.YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd D. MMMM YYYY LT" }, calendar : { sameDay: "[dnes v] LT", nextDay: '[zítra v] LT', nextWeek: function () { switch (this.day()) { case 0: return '[v neděli v] LT'; case 1: case 2: return '[v] dddd [v] LT'; case 3: return '[ve středu v] LT'; case 4: return '[ve čtvrtek v] LT'; case 5: return '[v pátek v] LT'; case 6: return '[v sobotu v] LT'; } }, lastDay: '[včera v] LT', lastWeek: function () { switch (this.day()) { case 0: return '[minulou neděli v] LT'; case 1: case 2: return '[minulé] dddd [v] LT'; case 3: return '[minulou středu v] LT'; case 4: case 5: return '[minulý] dddd [v] LT'; case 6: return '[minulou sobotu v] LT'; } }, sameElse: "L" }, relativeTime : { future : "za %s", past : "před %s", s : translate, m : translate, mm : translate, h : translate, hh : translate, d : translate, dd : translate, M : translate, MM : translate, y : translate, yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : chuvash (cv) // author : Anatoly Mironov : https://github.com/mirontoli (function (factory) { factory(moment); }(function (moment) { return moment.lang('cv', { months : "кăрлач_нарăс_пуш_ака_май_çĕртме_утă_çурла_авăн_юпа_чӳк_раштав".split("_"), monthsShort : "кăр_нар_пуш_ака_май_çĕр_утă_çур_ав_юпа_чӳк_раш".split("_"), weekdays : "вырсарникун_тунтикун_ытларикун_юнкун_кĕçнерникун_эрнекун_шăматкун".split("_"), weekdaysShort : "выр_тун_ытл_юн_кĕç_эрн_шăм".split("_"), weekdaysMin : "вр_тн_ыт_юн_кç_эр_шм".split("_"), longDateFormat : { LT : "HH:mm", L : "DD-MM-YYYY", LL : "YYYY [çулхи] MMMM [уйăхĕн] D[-мĕшĕ]", LLL : "YYYY [çулхи] MMMM [уйăхĕн] D[-мĕшĕ], LT", LLLL : "dddd, YYYY [çулхи] MMMM [уйăхĕн] D[-мĕшĕ], LT" }, calendar : { sameDay: '[Паян] LT [сехетре]', nextDay: '[Ыран] LT [сехетре]', lastDay: '[Ĕнер] LT [сехетре]', nextWeek: '[Çитес] dddd LT [сехетре]', lastWeek: '[Иртнĕ] dddd LT [сехетре]', sameElse: 'L' }, relativeTime : { future : function (output) { var affix = /сехет$/i.exec(output) ? "рен" : /çул$/i.exec(output) ? "тан" : "ран"; return output + affix; }, past : "%s каялла", s : "пĕр-ик çеккунт", m : "пĕр минут", mm : "%d минут", h : "пĕр сехет", hh : "%d сехет", d : "пĕр кун", dd : "%d кун", M : "пĕр уйăх", MM : "%d уйăх", y : "пĕр çул", yy : "%d çул" }, ordinal : '%d-мĕш', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Welsh (cy) // author : Robert Allen (function (factory) { factory(moment); }(function (moment) { return moment.lang("cy", { months: "Ionawr_Chwefror_Mawrth_Ebrill_Mai_Mehefin_Gorffennaf_Awst_Medi_Hydref_Tachwedd_Rhagfyr".split("_"), monthsShort: "Ion_Chwe_Maw_Ebr_Mai_Meh_Gor_Aws_Med_Hyd_Tach_Rhag".split("_"), weekdays: "Dydd Sul_Dydd Llun_Dydd Mawrth_Dydd Mercher_Dydd Iau_Dydd Gwener_Dydd Sadwrn".split("_"), weekdaysShort: "Sul_Llun_Maw_Mer_Iau_Gwe_Sad".split("_"), weekdaysMin: "Su_Ll_Ma_Me_Ia_Gw_Sa".split("_"), // time formats are the same as en-gb longDateFormat: { LT: "HH:mm", L: "DD/MM/YYYY", LL: "D MMMM YYYY", LLL: "D MMMM YYYY LT", LLLL: "dddd, D MMMM YYYY LT" }, calendar: { sameDay: '[Heddiw am] LT', nextDay: '[Yfory am] LT', nextWeek: 'dddd [am] LT', lastDay: '[Ddoe am] LT', lastWeek: 'dddd [diwethaf am] LT', sameElse: 'L' }, relativeTime: { future: "mewn %s", past: "%s yn àl", s: "ychydig eiliadau", m: "munud", mm: "%d munud", h: "awr", hh: "%d awr", d: "diwrnod", dd: "%d diwrnod", M: "mis", MM: "%d mis", y: "blwyddyn", yy: "%d flynedd" }, // traditional ordinal numbers above 31 are not commonly used in colloquial Welsh ordinal: function (number) { var b = number, output = '', lookup = [ '', 'af', 'il', 'ydd', 'ydd', 'ed', 'ed', 'ed', 'fed', 'fed', 'fed', // 1af to 10fed 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'eg', 'fed', 'eg', 'fed' // 11eg to 20fed ]; if (b > 20) { if (b === 40 || b === 50 || b === 60 || b === 80 || b === 100) { output = 'fed'; // not 30ain, 70ain or 90ain } else { output = 'ain'; } } else if (b > 0) { output = lookup[b]; } return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : danish (da) // author : Ulrik Nielsen : https://github.com/mrbase (function (factory) { factory(moment); }(function (moment) { return moment.lang('da', { months : "januar_februar_marts_april_maj_juni_juli_august_september_oktober_november_december".split("_"), monthsShort : "jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec".split("_"), weekdays : "søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag".split("_"), weekdaysShort : "søn_man_tir_ons_tor_fre_lør".split("_"), weekdaysMin : "sø_ma_ti_on_to_fr_lø".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D. MMMM, YYYY LT" }, calendar : { sameDay : '[I dag kl.] LT', nextDay : '[I morgen kl.] LT', nextWeek : 'dddd [kl.] LT', lastDay : '[I går kl.] LT', lastWeek : '[sidste] dddd [kl] LT', sameElse : 'L' }, relativeTime : { future : "om %s", past : "%s siden", s : "få sekunder", m : "et minut", mm : "%d minutter", h : "en time", hh : "%d timer", d : "en dag", dd : "%d dage", M : "en måned", MM : "%d måneder", y : "et år", yy : "%d år" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : german (de) // author : lluchs : https://github.com/lluchs // author: Menelion Elensúle: https://github.com/Oire (function (factory) { factory(moment); }(function (moment) { function processRelativeTime(number, withoutSuffix, key, isFuture) { var format = { 'm': ['eine Minute', 'einer Minute'], 'h': ['eine Stunde', 'einer Stunde'], 'd': ['ein Tag', 'einem Tag'], 'dd': [number + ' Tage', number + ' Tagen'], 'M': ['ein Monat', 'einem Monat'], 'MM': [number + ' Monate', number + ' Monaten'], 'y': ['ein Jahr', 'einem Jahr'], 'yy': [number + ' Jahre', number + ' Jahren'] }; return withoutSuffix ? format[key][0] : format[key][1]; } return moment.lang('de', { months : "Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember".split("_"), monthsShort : "Jan._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.".split("_"), weekdays : "Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag".split("_"), weekdaysShort : "So._Mo._Di._Mi._Do._Fr._Sa.".split("_"), weekdaysMin : "So_Mo_Di_Mi_Do_Fr_Sa".split("_"), longDateFormat : { LT: "H:mm [Uhr]", L : "DD.MM.YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay: "[Heute um] LT", sameElse: "L", nextDay: '[Morgen um] LT', nextWeek: 'dddd [um] LT', lastDay: '[Gestern um] LT', lastWeek: '[letzten] dddd [um] LT' }, relativeTime : { future : "in %s", past : "vor %s", s : "ein paar Sekunden", m : processRelativeTime, mm : "%d Minuten", h : processRelativeTime, hh : "%d Stunden", d : processRelativeTime, dd : processRelativeTime, M : processRelativeTime, MM : processRelativeTime, y : processRelativeTime, yy : processRelativeTime }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : modern greek (el) // author : Aggelos Karalias : https://github.com/mehiel (function (factory) { factory(moment); }(function (moment) { return moment.lang('el', { monthsNominativeEl : "Ιανουάριος_Φεβρουάριος_Μάρτιος_Απρίλιος_Μάιος_Ιούνιος_Ιούλιος_Αύγουστος_Σεπτέμβριος_Οκτώβριος_Νοέμβριος_Δεκέμβριος".split("_"), monthsGenitiveEl : "Ιανουαρίου_Φεβρουαρίου_Μαρτίου_Απριλίου_Μαΐου_Ιουνίου_Ιουλίου_Αυγούστου_Σεπτεμβρίου_Οκτωβρίου_Νοεμβρίου_Δεκεμβρίου".split("_"), months : function (momentToFormat, format) { if (/D/.test(format.substring(0, format.indexOf("MMMM")))) { // if there is a day number before 'MMMM' return this._monthsGenitiveEl[momentToFormat.month()]; } else { return this._monthsNominativeEl[momentToFormat.month()]; } }, monthsShort : "Ιαν_Φεβ_Μαρ_Απρ_Μαϊ_Ιουν_Ιουλ_Αυγ_Σεπ_Οκτ_Νοε_Δεκ".split("_"), weekdays : "Κυριακή_Δευτέρα_Τρίτη_Τετάρτη_Πέμπτη_Παρασκευή_Σάββατο".split("_"), weekdaysShort : "Κυρ_Δευ_Τρι_Τετ_Πεμ_Παρ_Σαβ".split("_"), weekdaysMin : "Κυ_Δε_Τρ_Τε_Πε_Πα_Σα".split("_"), meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'μμ' : 'ΜΜ'; } else { return isLower ? 'πμ' : 'ΠΜ'; } }, longDateFormat : { LT : "h:mm A", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendarEl : { sameDay : '[Σήμερα {}] LT', nextDay : '[Αύριο {}] LT', nextWeek : 'dddd [{}] LT', lastDay : '[Χθες {}] LT', lastWeek : '[την προηγούμενη] dddd [{}] LT', sameElse : 'L' }, calendar : function (key, mom) { var output = this._calendarEl[key], hours = mom && mom.hours(); return output.replace("{}", (hours % 12 === 1 ? "στη" : "στις")); }, relativeTime : { future : "σε %s", past : "%s πριν", s : "δευτερόλεπτα", m : "ένα λεπτό", mm : "%d λεπτά", h : "μία ώρα", hh : "%d ώρες", d : "μία μέρα", dd : "%d μέρες", M : "ένας μήνας", MM : "%d μήνες", y : "ένας χρόνος", yy : "%d χρόνια" }, ordinal : function (number) { return number + 'η'; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4st is the first week of the year. } }); })); // moment.js language configuration // language : australian english (en-au) (function (factory) { factory(moment); }(function (moment) { return moment.lang('en-au', { months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), longDateFormat : { LT : "h:mm A", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, relativeTime : { future : "in %s", past : "%s ago", s : "a few seconds", m : "a minute", mm : "%d minutes", h : "an hour", hh : "%d hours", d : "a day", dd : "%d days", M : "a month", MM : "%d months", y : "a year", yy : "%d years" }, ordinal : function (number) { var b = number % 10, output = (~~ (number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : canadian english (en-ca) // author : Jonathan Abourbih : https://github.com/jonbca (function (factory) { factory(moment); }(function (moment) { return moment.lang('en-ca', { months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), longDateFormat : { LT : "h:mm A", L : "YYYY-MM-DD", LL : "D MMMM, YYYY", LLL : "D MMMM, YYYY LT", LLLL : "dddd, D MMMM, YYYY LT" }, calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, relativeTime : { future : "in %s", past : "%s ago", s : "a few seconds", m : "a minute", mm : "%d minutes", h : "an hour", hh : "%d hours", d : "a day", dd : "%d days", M : "a month", MM : "%d months", y : "a year", yy : "%d years" }, ordinal : function (number) { var b = number % 10, output = (~~ (number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); })); // moment.js language configuration // language : great britain english (en-gb) // author : Chris Gedrim : https://github.com/chrisgedrim (function (factory) { factory(moment); }(function (moment) { return moment.lang('en-gb', { months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, relativeTime : { future : "in %s", past : "%s ago", s : "a few seconds", m : "a minute", mm : "%d minutes", h : "an hour", hh : "%d hours", d : "a day", dd : "%d days", M : "a month", MM : "%d months", y : "a year", yy : "%d years" }, ordinal : function (number) { var b = number % 10, output = (~~ (number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : esperanto (eo) // author : Colin Dean : https://github.com/colindean // komento: Mi estas malcerta se mi korekte traktis akuzativojn en tiu traduko. // Se ne, bonvolu korekti kaj avizi min por ke mi povas lerni! (function (factory) { factory(moment); }(function (moment) { return moment.lang('eo', { months : "januaro_februaro_marto_aprilo_majo_junio_julio_aŭgusto_septembro_oktobro_novembro_decembro".split("_"), monthsShort : "jan_feb_mar_apr_maj_jun_jul_aŭg_sep_okt_nov_dec".split("_"), weekdays : "Dimanĉo_Lundo_Mardo_Merkredo_Ĵaŭdo_Vendredo_Sabato".split("_"), weekdaysShort : "Dim_Lun_Mard_Merk_Ĵaŭ_Ven_Sab".split("_"), weekdaysMin : "Di_Lu_Ma_Me_Ĵa_Ve_Sa".split("_"), longDateFormat : { LT : "HH:mm", L : "YYYY-MM-DD", LL : "D[-an de] MMMM, YYYY", LLL : "D[-an de] MMMM, YYYY LT", LLLL : "dddd, [la] D[-an de] MMMM, YYYY LT" }, meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'p.t.m.' : 'P.T.M.'; } else { return isLower ? 'a.t.m.' : 'A.T.M.'; } }, calendar : { sameDay : '[Hodiaŭ je] LT', nextDay : '[Morgaŭ je] LT', nextWeek : 'dddd [je] LT', lastDay : '[Hieraŭ je] LT', lastWeek : '[pasinta] dddd [je] LT', sameElse : 'L' }, relativeTime : { future : "je %s", past : "antaŭ %s", s : "sekundoj", m : "minuto", mm : "%d minutoj", h : "horo", hh : "%d horoj", d : "tago",//ne 'diurno', ĉar estas uzita por proksimumo dd : "%d tagoj", M : "monato", MM : "%d monatoj", y : "jaro", yy : "%d jaroj" }, ordinal : "%da", week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : spanish (es) // author : Julio Napurí : https://github.com/julionc (function (factory) { factory(moment); }(function (moment) { return moment.lang('es', { months : "enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre".split("_"), monthsShort : "ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.".split("_"), weekdays : "domingo_lunes_martes_miércoles_jueves_viernes_sábado".split("_"), weekdaysShort : "dom._lun._mar._mié._jue._vie._sáb.".split("_"), weekdaysMin : "Do_Lu_Ma_Mi_Ju_Vi_Sá".split("_"), longDateFormat : { LT : "H:mm", L : "DD/MM/YYYY", LL : "D [de] MMMM [de] YYYY", LLL : "D [de] MMMM [de] YYYY LT", LLLL : "dddd, D [de] MMMM [de] YYYY LT" }, calendar : { sameDay : function () { return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextDay : function () { return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextWeek : function () { return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastDay : function () { return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastWeek : function () { return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, sameElse : 'L' }, relativeTime : { future : "en %s", past : "hace %s", s : "unos segundos", m : "un minuto", mm : "%d minutos", h : "una hora", hh : "%d horas", d : "un día", dd : "%d días", M : "un mes", MM : "%d meses", y : "un año", yy : "%d años" }, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : estonian (et) // author : Henry Kehlmann : https://github.com/madhenry // improvements : Illimar Tambek : https://github.com/ragulka (function (factory) { factory(moment); }(function (moment) { function processRelativeTime(number, withoutSuffix, key, isFuture) { var format = { 's' : ['mõne sekundi', 'mõni sekund', 'paar sekundit'], 'm' : ['ühe minuti', 'üks minut'], 'mm': [number + ' minuti', number + ' minutit'], 'h' : ['ühe tunni', 'tund aega', 'üks tund'], 'hh': [number + ' tunni', number + ' tundi'], 'd' : ['ühe päeva', 'üks päev'], 'M' : ['kuu aja', 'kuu aega', 'üks kuu'], 'MM': [number + ' kuu', number + ' kuud'], 'y' : ['ühe aasta', 'aasta', 'üks aasta'], 'yy': [number + ' aasta', number + ' aastat'] }; if (withoutSuffix) { return format[key][2] ? format[key][2] : format[key][1]; } return isFuture ? format[key][0] : format[key][1]; } return moment.lang('et', { months : "jaanuar_veebruar_märts_aprill_mai_juuni_juuli_august_september_oktoober_november_detsember".split("_"), monthsShort : "jaan_veebr_märts_apr_mai_juuni_juuli_aug_sept_okt_nov_dets".split("_"), weekdays : "pühapäev_esmaspäev_teisipäev_kolmapäev_neljapäev_reede_laupäev".split("_"), weekdaysShort : "P_E_T_K_N_R_L".split("_"), weekdaysMin : "P_E_T_K_N_R_L".split("_"), longDateFormat : { LT : "H:mm", L : "DD.MM.YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay : '[Täna,] LT', nextDay : '[Homme,] LT', nextWeek : '[Järgmine] dddd LT', lastDay : '[Eile,] LT', lastWeek : '[Eelmine] dddd LT', sameElse : 'L' }, relativeTime : { future : "%s pärast", past : "%s tagasi", s : processRelativeTime, m : processRelativeTime, mm : processRelativeTime, h : processRelativeTime, hh : processRelativeTime, d : processRelativeTime, dd : '%d päeva', M : processRelativeTime, MM : processRelativeTime, y : processRelativeTime, yy : processRelativeTime }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : euskara (eu) // author : Eneko Illarramendi : https://github.com/eillarra (function (factory) { factory(moment); }(function (moment) { return moment.lang('eu', { months : "urtarrila_otsaila_martxoa_apirila_maiatza_ekaina_uztaila_abuztua_iraila_urria_azaroa_abendua".split("_"), monthsShort : "urt._ots._mar._api._mai._eka._uzt._abu._ira._urr._aza._abe.".split("_"), weekdays : "igandea_astelehena_asteartea_asteazkena_osteguna_ostirala_larunbata".split("_"), weekdaysShort : "ig._al._ar._az._og._ol._lr.".split("_"), weekdaysMin : "ig_al_ar_az_og_ol_lr".split("_"), longDateFormat : { LT : "HH:mm", L : "YYYY-MM-DD", LL : "YYYY[ko] MMMM[ren] D[a]", LLL : "YYYY[ko] MMMM[ren] D[a] LT", LLLL : "dddd, YYYY[ko] MMMM[ren] D[a] LT", l : "YYYY-M-D", ll : "YYYY[ko] MMM D[a]", lll : "YYYY[ko] MMM D[a] LT", llll : "ddd, YYYY[ko] MMM D[a] LT" }, calendar : { sameDay : '[gaur] LT[etan]', nextDay : '[bihar] LT[etan]', nextWeek : 'dddd LT[etan]', lastDay : '[atzo] LT[etan]', lastWeek : '[aurreko] dddd LT[etan]', sameElse : 'L' }, relativeTime : { future : "%s barru", past : "duela %s", s : "segundo batzuk", m : "minutu bat", mm : "%d minutu", h : "ordu bat", hh : "%d ordu", d : "egun bat", dd : "%d egun", M : "hilabete bat", MM : "%d hilabete", y : "urte bat", yy : "%d urte" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Persian Language // author : Ebrahim Byagowi : https://github.com/ebraminio (function (factory) { factory(moment); }(function (moment) { var symbolMap = { '1': '۱', '2': '۲', '3': '۳', '4': '۴', '5': '۵', '6': '۶', '7': '۷', '8': '۸', '9': '۹', '0': '۰' }, numberMap = { '۱': '1', '۲': '2', '۳': '3', '۴': '4', '۵': '5', '۶': '6', '۷': '7', '۸': '8', '۹': '9', '۰': '0' }; return moment.lang('fa', { months : 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'), monthsShort : 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'), weekdays : 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'), weekdaysShort : 'یک\u200cشنبه_دوشنبه_سه\u200cشنبه_چهارشنبه_پنج\u200cشنبه_جمعه_شنبه'.split('_'), weekdaysMin : 'ی_د_س_چ_پ_ج_ش'.split('_'), longDateFormat : { LT : 'HH:mm', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY LT', LLLL : 'dddd, D MMMM YYYY LT' }, meridiem : function (hour, minute, isLower) { if (hour < 12) { return "قبل از ظهر"; } else { return "بعد از ظهر"; } }, calendar : { sameDay : '[امروز ساعت] LT', nextDay : '[فردا ساعت] LT', nextWeek : 'dddd [ساعت] LT', lastDay : '[دیروز ساعت] LT', lastWeek : 'dddd [پیش] [ساعت] LT', sameElse : 'L' }, relativeTime : { future : 'در %s', past : '%s پیش', s : 'چندین ثانیه', m : 'یک دقیقه', mm : '%d دقیقه', h : 'یک ساعت', hh : '%d ساعت', d : 'یک روز', dd : '%d روز', M : 'یک ماه', MM : '%d ماه', y : 'یک سال', yy : '%d سال' }, preparse: function (string) { return string.replace(/[۰-۹]/g, function (match) { return numberMap[match]; }).replace(/،/g, ','); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }).replace(/,/g, '،'); }, ordinal : '%dم', week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : finnish (fi) // author : Tarmo Aidantausta : https://github.com/bleadof (function (factory) { factory(moment); }(function (moment) { var numbers_past = 'nolla yksi kaksi kolme neljä viisi kuusi seitsemän kahdeksan yhdeksän'.split(' '), numbers_future = ['nolla', 'yhden', 'kahden', 'kolmen', 'neljän', 'viiden', 'kuuden', numbers_past[7], numbers_past[8], numbers_past[9]]; function translate(number, withoutSuffix, key, isFuture) { var result = ""; switch (key) { case 's': return isFuture ? 'muutaman sekunnin' : 'muutama sekunti'; case 'm': return isFuture ? 'minuutin' : 'minuutti'; case 'mm': result = isFuture ? 'minuutin' : 'minuuttia'; break; case 'h': return isFuture ? 'tunnin' : 'tunti'; case 'hh': result = isFuture ? 'tunnin' : 'tuntia'; break; case 'd': return isFuture ? 'päivän' : 'päivä'; case 'dd': result = isFuture ? 'päivän' : 'päivää'; break; case 'M': return isFuture ? 'kuukauden' : 'kuukausi'; case 'MM': result = isFuture ? 'kuukauden' : 'kuukautta'; break; case 'y': return isFuture ? 'vuoden' : 'vuosi'; case 'yy': result = isFuture ? 'vuoden' : 'vuotta'; break; } result = verbal_number(number, isFuture) + " " + result; return result; } function verbal_number(number, isFuture) { return number < 10 ? (isFuture ? numbers_future[number] : numbers_past[number]) : number; } return moment.lang('fi', { months : "tammikuu_helmikuu_maaliskuu_huhtikuu_toukokuu_kesäkuu_heinäkuu_elokuu_syyskuu_lokakuu_marraskuu_joulukuu".split("_"), monthsShort : "tammi_helmi_maalis_huhti_touko_kesä_heinä_elo_syys_loka_marras_joulu".split("_"), weekdays : "sunnuntai_maanantai_tiistai_keskiviikko_torstai_perjantai_lauantai".split("_"), weekdaysShort : "su_ma_ti_ke_to_pe_la".split("_"), weekdaysMin : "su_ma_ti_ke_to_pe_la".split("_"), longDateFormat : { LT : "HH.mm", L : "DD.MM.YYYY", LL : "Do MMMM[ta] YYYY", LLL : "Do MMMM[ta] YYYY, [klo] LT", LLLL : "dddd, Do MMMM[ta] YYYY, [klo] LT", l : "D.M.YYYY", ll : "Do MMM YYYY", lll : "Do MMM YYYY, [klo] LT", llll : "ddd, Do MMM YYYY, [klo] LT" }, calendar : { sameDay : '[tänään] [klo] LT', nextDay : '[huomenna] [klo] LT', nextWeek : 'dddd [klo] LT', lastDay : '[eilen] [klo] LT', lastWeek : '[viime] dddd[na] [klo] LT', sameElse : 'L' }, relativeTime : { future : "%s päästä", past : "%s sitten", s : translate, m : translate, mm : translate, h : translate, hh : translate, d : translate, dd : translate, M : translate, MM : translate, y : translate, yy : translate }, ordinal : "%d.", week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : faroese (fo) // author : Ragnar Johannesen : https://github.com/ragnar123 (function (factory) { factory(moment); }(function (moment) { return moment.lang('fo', { months : "januar_februar_mars_apríl_mai_juni_juli_august_september_oktober_november_desember".split("_"), monthsShort : "jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"), weekdays : "sunnudagur_mánadagur_týsdagur_mikudagur_hósdagur_fríggjadagur_leygardagur".split("_"), weekdaysShort : "sun_mán_týs_mik_hós_frí_ley".split("_"), weekdaysMin : "su_má_tý_mi_hó_fr_le".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D. MMMM, YYYY LT" }, calendar : { sameDay : '[Í dag kl.] LT', nextDay : '[Í morgin kl.] LT', nextWeek : 'dddd [kl.] LT', lastDay : '[Í gjár kl.] LT', lastWeek : '[síðstu] dddd [kl] LT', sameElse : 'L' }, relativeTime : { future : "um %s", past : "%s síðani", s : "fá sekund", m : "ein minutt", mm : "%d minuttir", h : "ein tími", hh : "%d tímar", d : "ein dagur", dd : "%d dagar", M : "ein mánaði", MM : "%d mánaðir", y : "eitt ár", yy : "%d ár" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : canadian french (fr-ca) // author : Jonathan Abourbih : https://github.com/jonbca (function (factory) { factory(moment); }(function (moment) { return moment.lang('fr-ca', { months : "janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"), monthsShort : "janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"), weekdays : "dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"), weekdaysShort : "dim._lun._mar._mer._jeu._ven._sam.".split("_"), weekdaysMin : "Di_Lu_Ma_Me_Je_Ve_Sa".split("_"), longDateFormat : { LT : "HH:mm", L : "YYYY-MM-DD", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[Aujourd'hui à] LT", nextDay: '[Demain à] LT', nextWeek: 'dddd [à] LT', lastDay: '[Hier à] LT', lastWeek: 'dddd [dernier à] LT', sameElse: 'L' }, relativeTime : { future : "dans %s", past : "il y a %s", s : "quelques secondes", m : "une minute", mm : "%d minutes", h : "une heure", hh : "%d heures", d : "un jour", dd : "%d jours", M : "un mois", MM : "%d mois", y : "un an", yy : "%d ans" }, ordinal : function (number) { return number + (number === 1 ? 'er' : ''); } }); })); // moment.js language configuration // language : french (fr) // author : John Fischer : https://github.com/jfroffice (function (factory) { factory(moment); }(function (moment) { return moment.lang('fr', { months : "janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre".split("_"), monthsShort : "janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.".split("_"), weekdays : "dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi".split("_"), weekdaysShort : "dim._lun._mar._mer._jeu._ven._sam.".split("_"), weekdaysMin : "Di_Lu_Ma_Me_Je_Ve_Sa".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[Aujourd'hui à] LT", nextDay: '[Demain à] LT', nextWeek: 'dddd [à] LT', lastDay: '[Hier à] LT', lastWeek: 'dddd [dernier à] LT', sameElse: 'L' }, relativeTime : { future : "dans %s", past : "il y a %s", s : "quelques secondes", m : "une minute", mm : "%d minutes", h : "une heure", hh : "%d heures", d : "un jour", dd : "%d jours", M : "un mois", MM : "%d mois", y : "un an", yy : "%d ans" }, ordinal : function (number) { return number + (number === 1 ? 'er' : ''); }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : galician (gl) // author : Juan G. Hurtado : https://github.com/juanghurtado (function (factory) { factory(moment); }(function (moment) { return moment.lang('gl', { months : "Xaneiro_Febreiro_Marzo_Abril_Maio_Xuño_Xullo_Agosto_Setembro_Outubro_Novembro_Decembro".split("_"), monthsShort : "Xan._Feb._Mar._Abr._Mai._Xuñ._Xul._Ago._Set._Out._Nov._Dec.".split("_"), weekdays : "Domingo_Luns_Martes_Mércores_Xoves_Venres_Sábado".split("_"), weekdaysShort : "Dom._Lun._Mar._Mér._Xov._Ven._Sáb.".split("_"), weekdaysMin : "Do_Lu_Ma_Mé_Xo_Ve_Sá".split("_"), longDateFormat : { LT : "H:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay : function () { return '[hoxe ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT'; }, nextDay : function () { return '[mañá ' + ((this.hours() !== 1) ? 'ás' : 'á') + '] LT'; }, nextWeek : function () { return 'dddd [' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT'; }, lastDay : function () { return '[onte ' + ((this.hours() !== 1) ? 'á' : 'a') + '] LT'; }, lastWeek : function () { return '[o] dddd [pasado ' + ((this.hours() !== 1) ? 'ás' : 'a') + '] LT'; }, sameElse : 'L' }, relativeTime : { future : function (str) { if (str === "uns segundos") { return "nuns segundos"; } return "en " + str; }, past : "hai %s", s : "uns segundos", m : "un minuto", mm : "%d minutos", h : "unha hora", hh : "%d horas", d : "un día", dd : "%d días", M : "un mes", MM : "%d meses", y : "un ano", yy : "%d anos" }, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Hebrew (he) // author : Tomer Cohen : https://github.com/tomer // author : Moshe Simantov : https://github.com/DevelopmentIL // author : Tal Ater : https://github.com/TalAter (function (factory) { factory(moment); }(function (moment) { return moment.lang('he', { months : "ינואר_פברואר_מרץ_אפריל_מאי_יוני_יולי_אוגוסט_ספטמבר_אוקטובר_נובמבר_דצמבר".split("_"), monthsShort : "ינו׳_פבר׳_מרץ_אפר׳_מאי_יוני_יולי_אוג׳_ספט׳_אוק׳_נוב׳_דצמ׳".split("_"), weekdays : "ראשון_שני_שלישי_רביעי_חמישי_שישי_שבת".split("_"), weekdaysShort : "א׳_ב׳_ג׳_ד׳_ה׳_ו׳_ש׳".split("_"), weekdaysMin : "א_ב_ג_ד_ה_ו_ש".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D [ב]MMMM YYYY", LLL : "D [ב]MMMM YYYY LT", LLLL : "dddd, D [ב]MMMM YYYY LT", l : "D/M/YYYY", ll : "D MMM YYYY", lll : "D MMM YYYY LT", llll : "ddd, D MMM YYYY LT" }, calendar : { sameDay : '[היום ב־]LT', nextDay : '[מחר ב־]LT', nextWeek : 'dddd [בשעה] LT', lastDay : '[אתמול ב־]LT', lastWeek : '[ביום] dddd [האחרון בשעה] LT', sameElse : 'L' }, relativeTime : { future : "בעוד %s", past : "לפני %s", s : "מספר שניות", m : "דקה", mm : "%d דקות", h : "שעה", hh : function (number) { if (number === 2) { return "שעתיים"; } return number + " שעות"; }, d : "יום", dd : function (number) { if (number === 2) { return "יומיים"; } return number + " ימים"; }, M : "חודש", MM : function (number) { if (number === 2) { return "חודשיים"; } return number + " חודשים"; }, y : "שנה", yy : function (number) { if (number === 2) { return "שנתיים"; } return number + " שנים"; } } }); })); // moment.js language configuration // language : hindi (hi) // author : Mayank Singhal : https://github.com/mayanksinghal (function (factory) { factory(moment); }(function (moment) { var symbolMap = { '1': '१', '2': '२', '3': '३', '4': '४', '5': '५', '6': '६', '7': '७', '8': '८', '9': '९', '0': '०' }, numberMap = { '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9', '०': '0' }; return moment.lang('hi', { months : 'जनवरी_फ़रवरी_मार्च_अप्रैल_मई_जून_जुलाई_अगस्त_सितम्बर_अक्टूबर_नवम्बर_दिसम्बर'.split("_"), monthsShort : 'जन._फ़र._मार्च_अप्रै._मई_जून_जुल._अग._सित._अक्टू._नव._दिस.'.split("_"), weekdays : 'रविवार_सोमवार_मंगलवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split("_"), weekdaysShort : 'रवि_सोम_मंगल_बुध_गुरू_शुक्र_शनि'.split("_"), weekdaysMin : 'र_सो_मं_बु_गु_शु_श'.split("_"), longDateFormat : { LT : "A h:mm बजे", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY, LT", LLLL : "dddd, D MMMM YYYY, LT" }, calendar : { sameDay : '[आज] LT', nextDay : '[कल] LT', nextWeek : 'dddd, LT', lastDay : '[कल] LT', lastWeek : '[पिछले] dddd, LT', sameElse : 'L' }, relativeTime : { future : "%s में", past : "%s पहले", s : "कुछ ही क्षण", m : "एक मिनट", mm : "%d मिनट", h : "एक घंटा", hh : "%d घंटे", d : "एक दिन", dd : "%d दिन", M : "एक महीने", MM : "%d महीने", y : "एक वर्ष", yy : "%d वर्ष" }, preparse: function (string) { return string.replace(/[१२३४५६७८९०]/g, function (match) { return numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }); }, // Hindi notation for meridiems are quite fuzzy in practice. While there exists // a rigid notion of a 'Pahar' it is not used as rigidly in modern Hindi. meridiem : function (hour, minute, isLower) { if (hour < 4) { return "रात"; } else if (hour < 10) { return "सुबह"; } else if (hour < 17) { return "दोपहर"; } else if (hour < 20) { return "शाम"; } else { return "रात"; } }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : hrvatski (hr) // author : Bojan Marković : https://github.com/bmarkovic // based on (sl) translation by Robert Sedovšek (function (factory) { factory(moment); }(function (moment) { function translate(number, withoutSuffix, key) { var result = number + " "; switch (key) { case 'm': return withoutSuffix ? 'jedna minuta' : 'jedne minute'; case 'mm': if (number === 1) { result += 'minuta'; } else if (number === 2 || number === 3 || number === 4) { result += 'minute'; } else { result += 'minuta'; } return result; case 'h': return withoutSuffix ? 'jedan sat' : 'jednog sata'; case 'hh': if (number === 1) { result += 'sat'; } else if (number === 2 || number === 3 || number === 4) { result += 'sata'; } else { result += 'sati'; } return result; case 'dd': if (number === 1) { result += 'dan'; } else { result += 'dana'; } return result; case 'MM': if (number === 1) { result += 'mjesec'; } else if (number === 2 || number === 3 || number === 4) { result += 'mjeseca'; } else { result += 'mjeseci'; } return result; case 'yy': if (number === 1) { result += 'godina'; } else if (number === 2 || number === 3 || number === 4) { result += 'godine'; } else { result += 'godina'; } return result; } } return moment.lang('hr', { months : "sječanj_veljača_ožujak_travanj_svibanj_lipanj_srpanj_kolovoz_rujan_listopad_studeni_prosinac".split("_"), monthsShort : "sje._vel._ožu._tra._svi._lip._srp._kol._ruj._lis._stu._pro.".split("_"), weekdays : "nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota".split("_"), weekdaysShort : "ned._pon._uto._sri._čet._pet._sub.".split("_"), weekdaysMin : "ne_po_ut_sr_če_pe_su".split("_"), longDateFormat : { LT : "H:mm", L : "DD. MM. YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay : '[danas u] LT', nextDay : '[sutra u] LT', nextWeek : function () { switch (this.day()) { case 0: return '[u] [nedjelju] [u] LT'; case 3: return '[u] [srijedu] [u] LT'; case 6: return '[u] [subotu] [u] LT'; case 1: case 2: case 4: case 5: return '[u] dddd [u] LT'; } }, lastDay : '[jučer u] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: return '[prošlu] dddd [u] LT'; case 6: return '[prošle] [subote] [u] LT'; case 1: case 2: case 4: case 5: return '[prošli] dddd [u] LT'; } }, sameElse : 'L' }, relativeTime : { future : "za %s", past : "prije %s", s : "par sekundi", m : translate, mm : translate, h : translate, hh : translate, d : "dan", dd : translate, M : "mjesec", MM : translate, y : "godinu", yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : hungarian (hu) // author : Adam Brunner : https://github.com/adambrunner (function (factory) { factory(moment); }(function (moment) { var weekEndings = 'vasárnap hétfőn kedden szerdán csütörtökön pénteken szombaton'.split(' '); function translate(number, withoutSuffix, key, isFuture) { var num = number, suffix; switch (key) { case 's': return (isFuture || withoutSuffix) ? 'néhány másodperc' : 'néhány másodperce'; case 'm': return 'egy' + (isFuture || withoutSuffix ? ' perc' : ' perce'); case 'mm': return num + (isFuture || withoutSuffix ? ' perc' : ' perce'); case 'h': return 'egy' + (isFuture || withoutSuffix ? ' óra' : ' órája'); case 'hh': return num + (isFuture || withoutSuffix ? ' óra' : ' órája'); case 'd': return 'egy' + (isFuture || withoutSuffix ? ' nap' : ' napja'); case 'dd': return num + (isFuture || withoutSuffix ? ' nap' : ' napja'); case 'M': return 'egy' + (isFuture || withoutSuffix ? ' hónap' : ' hónapja'); case 'MM': return num + (isFuture || withoutSuffix ? ' hónap' : ' hónapja'); case 'y': return 'egy' + (isFuture || withoutSuffix ? ' év' : ' éve'); case 'yy': return num + (isFuture || withoutSuffix ? ' év' : ' éve'); } return ''; } function week(isFuture) { return (isFuture ? '' : '[múlt] ') + '[' + weekEndings[this.day()] + '] LT[-kor]'; } return moment.lang('hu', { months : "január_február_március_április_május_június_július_augusztus_szeptember_október_november_december".split("_"), monthsShort : "jan_feb_márc_ápr_máj_jún_júl_aug_szept_okt_nov_dec".split("_"), weekdays : "vasárnap_hétfő_kedd_szerda_csütörtök_péntek_szombat".split("_"), weekdaysShort : "vas_hét_kedd_sze_csüt_pén_szo".split("_"), weekdaysMin : "v_h_k_sze_cs_p_szo".split("_"), longDateFormat : { LT : "H:mm", L : "YYYY.MM.DD.", LL : "YYYY. MMMM D.", LLL : "YYYY. MMMM D., LT", LLLL : "YYYY. MMMM D., dddd LT" }, calendar : { sameDay : '[ma] LT[-kor]', nextDay : '[holnap] LT[-kor]', nextWeek : function () { return week.call(this, true); }, lastDay : '[tegnap] LT[-kor]', lastWeek : function () { return week.call(this, false); }, sameElse : 'L' }, relativeTime : { future : "%s múlva", past : "%s", s : translate, m : translate, mm : translate, h : translate, hh : translate, d : translate, dd : translate, M : translate, MM : translate, y : translate, yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Armenian (hy-am) // author : Armendarabyan : https://github.com/armendarabyan (function (factory) { factory(moment); }(function (moment) { function monthsCaseReplace(m, format) { var months = { 'nominative': 'հունվար_փետրվար_մարտ_ապրիլ_մայիս_հունիս_հուլիս_օգոստոս_սեպտեմբեր_հոկտեմբեր_նոյեմբեր_դեկտեմբեր'.split('_'), 'accusative': 'հունվարի_փետրվարի_մարտի_ապրիլի_մայիսի_հունիսի_հուլիսի_օգոստոսի_սեպտեմբերի_հոկտեմբերի_նոյեմբերի_դեկտեմբերի'.split('_') }, nounCase = (/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/).test(format) ? 'accusative' : 'nominative'; return months[nounCase][m.month()]; } function monthsShortCaseReplace(m, format) { var monthsShort = 'հնվ_փտր_մրտ_ապր_մյս_հնս_հլս_օգս_սպտ_հկտ_նմբ_դկտ'.split('_'); return monthsShort[m.month()]; } function weekdaysCaseReplace(m, format) { var weekdays = 'կիրակի_երկուշաբթի_երեքշաբթի_չորեքշաբթի_հինգշաբթի_ուրբաթ_շաբաթ'.split('_'); return weekdays[m.day()]; } return moment.lang('hy-am', { months : monthsCaseReplace, monthsShort : monthsShortCaseReplace, weekdays : weekdaysCaseReplace, weekdaysShort : "կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ".split("_"), weekdaysMin : "կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY թ.", LLL : "D MMMM YYYY թ., LT", LLLL : "dddd, D MMMM YYYY թ., LT" }, calendar : { sameDay: '[այսօր] LT', nextDay: '[վաղը] LT', lastDay: '[երեկ] LT', nextWeek: function () { return 'dddd [օրը ժամը] LT'; }, lastWeek: function () { return '[անցած] dddd [օրը ժամը] LT'; }, sameElse: 'L' }, relativeTime : { future : "%s հետո", past : "%s առաջ", s : "մի քանի վայրկյան", m : "րոպե", mm : "%d րոպե", h : "ժամ", hh : "%d ժամ", d : "օր", dd : "%d օր", M : "ամիս", MM : "%d ամիս", y : "տարի", yy : "%d տարի" }, meridiem : function (hour) { if (hour < 4) { return "գիշերվա"; } else if (hour < 12) { return "առավոտվա"; } else if (hour < 17) { return "ցերեկվա"; } else { return "երեկոյան"; } }, ordinal: function (number, period) { switch (period) { case 'DDD': case 'w': case 'W': case 'DDDo': if (number === 1) { return number + '-ին'; } return number + '-րդ'; default: return number; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Bahasa Indonesia (id) // author : Mohammad Satrio Utomo : https://github.com/tyok // reference: http://id.wikisource.org/wiki/Pedoman_Umum_Ejaan_Bahasa_Indonesia_yang_Disempurnakan (function (factory) { factory(moment); }(function (moment) { return moment.lang('id', { months : "Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_November_Desember".split("_"), monthsShort : "Jan_Feb_Mar_Apr_Mei_Jun_Jul_Ags_Sep_Okt_Nov_Des".split("_"), weekdays : "Minggu_Senin_Selasa_Rabu_Kamis_Jumat_Sabtu".split("_"), weekdaysShort : "Min_Sen_Sel_Rab_Kam_Jum_Sab".split("_"), weekdaysMin : "Mg_Sn_Sl_Rb_Km_Jm_Sb".split("_"), longDateFormat : { LT : "HH.mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY [pukul] LT", LLLL : "dddd, D MMMM YYYY [pukul] LT" }, meridiem : function (hours, minutes, isLower) { if (hours < 11) { return 'pagi'; } else if (hours < 15) { return 'siang'; } else if (hours < 19) { return 'sore'; } else { return 'malam'; } }, calendar : { sameDay : '[Hari ini pukul] LT', nextDay : '[Besok pukul] LT', nextWeek : 'dddd [pukul] LT', lastDay : '[Kemarin pukul] LT', lastWeek : 'dddd [lalu pukul] LT', sameElse : 'L' }, relativeTime : { future : "dalam %s", past : "%s yang lalu", s : "beberapa detik", m : "semenit", mm : "%d menit", h : "sejam", hh : "%d jam", d : "sehari", dd : "%d hari", M : "sebulan", MM : "%d bulan", y : "setahun", yy : "%d tahun" }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : icelandic (is) // author : Hinrik Örn Sigurðsson : https://github.com/hinrik (function (factory) { factory(moment); }(function (moment) { function plural(n) { if (n % 100 === 11) { return true; } else if (n % 10 === 1) { return false; } return true; } function translate(number, withoutSuffix, key, isFuture) { var result = number + " "; switch (key) { case 's': return withoutSuffix || isFuture ? 'nokkrar sekúndur' : 'nokkrum sekúndum'; case 'm': return withoutSuffix ? 'mínúta' : 'mínútu'; case 'mm': if (plural(number)) { return result + (withoutSuffix || isFuture ? 'mínútur' : 'mínútum'); } else if (withoutSuffix) { return result + 'mínúta'; } return result + 'mínútu'; case 'hh': if (plural(number)) { return result + (withoutSuffix || isFuture ? 'klukkustundir' : 'klukkustundum'); } return result + 'klukkustund'; case 'd': if (withoutSuffix) { return 'dagur'; } return isFuture ? 'dag' : 'degi'; case 'dd': if (plural(number)) { if (withoutSuffix) { return result + 'dagar'; } return result + (isFuture ? 'daga' : 'dögum'); } else if (withoutSuffix) { return result + 'dagur'; } return result + (isFuture ? 'dag' : 'degi'); case 'M': if (withoutSuffix) { return 'mánuður'; } return isFuture ? 'mánuð' : 'mánuði'; case 'MM': if (plural(number)) { if (withoutSuffix) { return result + 'mánuðir'; } return result + (isFuture ? 'mánuði' : 'mánuðum'); } else if (withoutSuffix) { return result + 'mánuður'; } return result + (isFuture ? 'mánuð' : 'mánuði'); case 'y': return withoutSuffix || isFuture ? 'ár' : 'ári'; case 'yy': if (plural(number)) { return result + (withoutSuffix || isFuture ? 'ár' : 'árum'); } return result + (withoutSuffix || isFuture ? 'ár' : 'ári'); } } return moment.lang('is', { months : "janúar_febrúar_mars_apríl_maí_júní_júlí_ágúst_september_október_nóvember_desember".split("_"), monthsShort : "jan_feb_mar_apr_maí_jún_júl_ágú_sep_okt_nóv_des".split("_"), weekdays : "sunnudagur_mánudagur_þriðjudagur_miðvikudagur_fimmtudagur_föstudagur_laugardagur".split("_"), weekdaysShort : "sun_mán_þri_mið_fim_fös_lau".split("_"), weekdaysMin : "Su_Má_Þr_Mi_Fi_Fö_La".split("_"), longDateFormat : { LT : "H:mm", L : "DD/MM/YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY [kl.] LT", LLLL : "dddd, D. MMMM YYYY [kl.] LT" }, calendar : { sameDay : '[í dag kl.] LT', nextDay : '[á morgun kl.] LT', nextWeek : 'dddd [kl.] LT', lastDay : '[í gær kl.] LT', lastWeek : '[síðasta] dddd [kl.] LT', sameElse : 'L' }, relativeTime : { future : "eftir %s", past : "fyrir %s síðan", s : translate, m : translate, mm : translate, h : "klukkustund", hh : translate, d : translate, dd : translate, M : translate, MM : translate, y : translate, yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : italian (it) // author : Lorenzo : https://github.com/aliem // author: Mattia Larentis: https://github.com/nostalgiaz (function (factory) { factory(moment); }(function (moment) { return moment.lang('it', { months : "Gennaio_Febbraio_Marzo_Aprile_Maggio_Giugno_Luglio_Agosto_Settembre_Ottobre_Novembre_Dicembre".split("_"), monthsShort : "Gen_Feb_Mar_Apr_Mag_Giu_Lug_Ago_Set_Ott_Nov_Dic".split("_"), weekdays : "Domenica_Lunedì_Martedì_Mercoledì_Giovedì_Venerdì_Sabato".split("_"), weekdaysShort : "Dom_Lun_Mar_Mer_Gio_Ven_Sab".split("_"), weekdaysMin : "D_L_Ma_Me_G_V_S".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay: '[Oggi alle] LT', nextDay: '[Domani alle] LT', nextWeek: 'dddd [alle] LT', lastDay: '[Ieri alle] LT', lastWeek: '[lo scorso] dddd [alle] LT', sameElse: 'L' }, relativeTime : { future : function (s) { return ((/^[0-9].+$/).test(s) ? "tra" : "in") + " " + s; }, past : "%s fa", s : "alcuni secondi", m : "un minuto", mm : "%d minuti", h : "un'ora", hh : "%d ore", d : "un giorno", dd : "%d giorni", M : "un mese", MM : "%d mesi", y : "un anno", yy : "%d anni" }, ordinal: '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : japanese (ja) // author : LI Long : https://github.com/baryon (function (factory) { factory(moment); }(function (moment) { return moment.lang('ja', { months : "1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"), monthsShort : "1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"), weekdays : "日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日".split("_"), weekdaysShort : "日_月_火_水_木_金_土".split("_"), weekdaysMin : "日_月_火_水_木_金_土".split("_"), longDateFormat : { LT : "Ah時m分", L : "YYYY/MM/DD", LL : "YYYY年M月D日", LLL : "YYYY年M月D日LT", LLLL : "YYYY年M月D日LT dddd" }, meridiem : function (hour, minute, isLower) { if (hour < 12) { return "午前"; } else { return "午後"; } }, calendar : { sameDay : '[今日] LT', nextDay : '[明日] LT', nextWeek : '[来週]dddd LT', lastDay : '[昨日] LT', lastWeek : '[前週]dddd LT', sameElse : 'L' }, relativeTime : { future : "%s後", past : "%s前", s : "数秒", m : "1分", mm : "%d分", h : "1時間", hh : "%d時間", d : "1日", dd : "%d日", M : "1ヶ月", MM : "%dヶ月", y : "1年", yy : "%d年" } }); })); // moment.js language configuration // language : Georgian (ka) // author : Irakli Janiashvili : https://github.com/irakli-janiashvili (function (factory) { factory(moment); }(function (moment) { function monthsCaseReplace(m, format) { var months = { 'nominative': 'იანვარი_თებერვალი_მარტი_აპრილი_მაისი_ივნისი_ივლისი_აგვისტო_სექტემბერი_ოქტომბერი_ნოემბერი_დეკემბერი'.split('_'), 'accusative': 'იანვარს_თებერვალს_მარტს_აპრილის_მაისს_ივნისს_ივლისს_აგვისტს_სექტემბერს_ოქტომბერს_ნოემბერს_დეკემბერს'.split('_') }, nounCase = (/D[oD] *MMMM?/).test(format) ? 'accusative' : 'nominative'; return months[nounCase][m.month()]; } function weekdaysCaseReplace(m, format) { var weekdays = { 'nominative': 'კვირა_ორშაბათი_სამშაბათი_ოთხშაბათი_ხუთშაბათი_პარასკევი_შაბათი'.split('_'), 'accusative': 'კვირას_ორშაბათს_სამშაბათს_ოთხშაბათს_ხუთშაბათს_პარასკევს_შაბათს'.split('_') }, nounCase = (/(წინა|შემდეგ)/).test(format) ? 'accusative' : 'nominative'; return weekdays[nounCase][m.day()]; } return moment.lang('ka', { months : monthsCaseReplace, monthsShort : "იან_თებ_მარ_აპრ_მაი_ივნ_ივლ_აგვ_სექ_ოქტ_ნოე_დეკ".split("_"), weekdays : weekdaysCaseReplace, weekdaysShort : "კვი_ორშ_სამ_ოთხ_ხუთ_პარ_შაბ".split("_"), weekdaysMin : "კვ_ორ_სა_ოთ_ხუ_პა_შა".split("_"), longDateFormat : { LT : "h:mm A", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[დღეს] LT[-ზე]', nextDay : '[ხვალ] LT[-ზე]', lastDay : '[გუშინ] LT[-ზე]', nextWeek : '[შემდეგ] dddd LT[-ზე]', lastWeek : '[წინა] dddd LT-ზე', sameElse : 'L' }, relativeTime : { future : function (s) { return (/(წამი|წუთი|საათი|წელი)/).test(s) ? s.replace(/ი$/, "ში") : s + "ში"; }, past : function (s) { if ((/(წამი|წუთი|საათი|დღე|თვე)/).test(s)) { return s.replace(/(ი|ე)$/, "ის წინ"); } if ((/წელი/).test(s)) { return s.replace(/წელი$/, "წლის წინ"); } }, s : "რამდენიმე წამი", m : "წუთი", mm : "%d წუთი", h : "საათი", hh : "%d საათი", d : "დღე", dd : "%d დღე", M : "თვე", MM : "%d თვე", y : "წელი", yy : "%d წელი" }, ordinal : function (number) { if (number === 0) { return number; } if (number === 1) { return number + "-ლი"; } if ((number < 20) || (number <= 100 && (number % 20 === 0)) || (number % 100 === 0)) { return "მე-" + number; } return number + "-ე"; }, week : { dow : 1, doy : 7 } }); })); // moment.js language configuration // language : korean (ko) // // authors // // - Kyungwook, Park : https://github.com/kyungw00k // - Jeeeyul Lee <jeeeyul@gmail.com> (function (factory) { factory(moment); }(function (moment) { return moment.lang('ko', { months : "1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"), monthsShort : "1월_2월_3월_4월_5월_6월_7월_8월_9월_10월_11월_12월".split("_"), weekdays : "일요일_월요일_화요일_수요일_목요일_금요일_토요일".split("_"), weekdaysShort : "일_월_화_수_목_금_토".split("_"), weekdaysMin : "일_월_화_수_목_금_토".split("_"), longDateFormat : { LT : "A h시 mm분", L : "YYYY.MM.DD", LL : "YYYY년 MMMM D일", LLL : "YYYY년 MMMM D일 LT", LLLL : "YYYY년 MMMM D일 dddd LT" }, meridiem : function (hour, minute, isUpper) { return hour < 12 ? '오전' : '오후'; }, calendar : { sameDay : '오늘 LT', nextDay : '내일 LT', nextWeek : 'dddd LT', lastDay : '어제 LT', lastWeek : '지난주 dddd LT', sameElse : 'L' }, relativeTime : { future : "%s 후", past : "%s 전", s : "몇초", ss : "%d초", m : "일분", mm : "%d분", h : "한시간", hh : "%d시간", d : "하루", dd : "%d일", M : "한달", MM : "%d달", y : "일년", yy : "%d년" }, ordinal : '%d일', meridiemParse : /(오전|오후)/, isPM : function (token) { return token === "오후"; } }); })); // moment.js language configuration // language : Luxembourgish (lb) // author : mweimerskirch : https://github.com/mweimerskirch // Note: Luxembourgish has a very particular phonological rule ("Eifeler Regel") that causes the // deletion of the final "n" in certain contexts. That's what the "eifelerRegelAppliesToWeekday" // and "eifelerRegelAppliesToNumber" methods are meant for (function (factory) { factory(moment); }(function (moment) { function processRelativeTime(number, withoutSuffix, key, isFuture) { var format = { 'm': ['eng Minutt', 'enger Minutt'], 'h': ['eng Stonn', 'enger Stonn'], 'd': ['een Dag', 'engem Dag'], 'dd': [number + ' Deeg', number + ' Deeg'], 'M': ['ee Mount', 'engem Mount'], 'MM': [number + ' Méint', number + ' Méint'], 'y': ['ee Joer', 'engem Joer'], 'yy': [number + ' Joer', number + ' Joer'] }; return withoutSuffix ? format[key][0] : format[key][1]; } function processFutureTime(string) { var number = string.substr(0, string.indexOf(' ')); if (eifelerRegelAppliesToNumber(number)) { return "a " + string; } return "an " + string; } function processPastTime(string) { var number = string.substr(0, string.indexOf(' ')); if (eifelerRegelAppliesToNumber(number)) { return "viru " + string; } return "virun " + string; } function processLastWeek(string1) { var weekday = this.format('d'); if (eifelerRegelAppliesToWeekday(weekday)) { return '[Leschte] dddd [um] LT'; } return '[Leschten] dddd [um] LT'; } /** * Returns true if the word before the given week day loses the "-n" ending. * e.g. "Leschten Dënschdeg" but "Leschte Méindeg" * * @param weekday {integer} * @returns {boolean} */ function eifelerRegelAppliesToWeekday(weekday) { weekday = parseInt(weekday, 10); switch (weekday) { case 0: // Sonndeg case 1: // Méindeg case 3: // Mëttwoch case 5: // Freideg case 6: // Samschdeg return true; default: // 2 Dënschdeg, 4 Donneschdeg return false; } } /** * Returns true if the word before the given number loses the "-n" ending. * e.g. "an 10 Deeg" but "a 5 Deeg" * * @param number {integer} * @returns {boolean} */ function eifelerRegelAppliesToNumber(number) { number = parseInt(number, 10); if (isNaN(number)) { return false; } if (number < 0) { // Negative Number --> always true return true; } else if (number < 10) { // Only 1 digit if (4 <= number && number <= 7) { return true; } return false; } else if (number < 100) { // 2 digits var lastDigit = number % 10, firstDigit = number / 10; if (lastDigit === 0) { return eifelerRegelAppliesToNumber(firstDigit); } return eifelerRegelAppliesToNumber(lastDigit); } else if (number < 10000) { // 3 or 4 digits --> recursively check first digit while (number >= 10) { number = number / 10; } return eifelerRegelAppliesToNumber(number); } else { // Anything larger than 4 digits: recursively check first n-3 digits number = number / 1000; return eifelerRegelAppliesToNumber(number); } } return moment.lang('lb', { months: "Januar_Februar_Mäerz_Abrëll_Mee_Juni_Juli_August_September_Oktober_November_Dezember".split("_"), monthsShort: "Jan._Febr._Mrz._Abr._Mee_Jun._Jul._Aug._Sept._Okt._Nov._Dez.".split("_"), weekdays: "Sonndeg_Méindeg_Dënschdeg_Mëttwoch_Donneschdeg_Freideg_Samschdeg".split("_"), weekdaysShort: "So._Mé._Dë._Më._Do._Fr._Sa.".split("_"), weekdaysMin: "So_Mé_Dë_Më_Do_Fr_Sa".split("_"), longDateFormat: { LT: "H:mm [Auer]", L: "DD.MM.YYYY", LL: "D. MMMM YYYY", LLL: "D. MMMM YYYY LT", LLLL: "dddd, D. MMMM YYYY LT" }, calendar: { sameDay: "[Haut um] LT", sameElse: "L", nextDay: '[Muer um] LT', nextWeek: 'dddd [um] LT', lastDay: '[Gëschter um] LT', lastWeek: processLastWeek }, relativeTime: { future: processFutureTime, past: processPastTime, s: "e puer Sekonnen", m: processRelativeTime, mm: "%d Minutten", h: processRelativeTime, hh: "%d Stonnen", d: processRelativeTime, dd: processRelativeTime, M: processRelativeTime, MM: processRelativeTime, y: processRelativeTime, yy: processRelativeTime }, ordinal: '%d.', week: { dow: 1, // Monday is the first day of the week. doy: 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : Lithuanian (lt) // author : Mindaugas Mozūras : https://github.com/mmozuras (function (factory) { factory(moment); }(function (moment) { var units = { "m" : "minutė_minutės_minutę", "mm": "minutės_minučių_minutes", "h" : "valanda_valandos_valandą", "hh": "valandos_valandų_valandas", "d" : "diena_dienos_dieną", "dd": "dienos_dienų_dienas", "M" : "mėnuo_mėnesio_mėnesį", "MM": "mėnesiai_mėnesių_mėnesius", "y" : "metai_metų_metus", "yy": "metai_metų_metus" }, weekDays = "pirmadienis_antradienis_trečiadienis_ketvirtadienis_penktadienis_šeštadienis_sekmadienis".split("_"); function translateSeconds(number, withoutSuffix, key, isFuture) { if (withoutSuffix) { return "kelios sekundės"; } else { return isFuture ? "kelių sekundžių" : "kelias sekundes"; } } function translateSingular(number, withoutSuffix, key, isFuture) { return withoutSuffix ? forms(key)[0] : (isFuture ? forms(key)[1] : forms(key)[2]); } function special(number) { return number % 10 === 0 || (number > 10 && number < 20); } function forms(key) { return units[key].split("_"); } function translate(number, withoutSuffix, key, isFuture) { var result = number + " "; if (number === 1) { return result + translateSingular(number, withoutSuffix, key[0], isFuture); } else if (withoutSuffix) { return result + (special(number) ? forms(key)[1] : forms(key)[0]); } else { if (isFuture) { return result + forms(key)[1]; } else { return result + (special(number) ? forms(key)[1] : forms(key)[2]); } } } function relativeWeekDay(moment, format) { var nominative = format.indexOf('dddd LT') === -1, weekDay = weekDays[moment.weekday()]; return nominative ? weekDay : weekDay.substring(0, weekDay.length - 2) + "į"; } return moment.lang("lt", { months : "sausio_vasario_kovo_balandžio_gegužės_biržėlio_liepos_rugpjūčio_rugsėjo_spalio_lapkričio_gruodžio".split("_"), monthsShort : "sau_vas_kov_bal_geg_bir_lie_rgp_rgs_spa_lap_grd".split("_"), weekdays : relativeWeekDay, weekdaysShort : "Sek_Pir_Ant_Tre_Ket_Pen_Šeš".split("_"), weekdaysMin : "S_P_A_T_K_Pn_Š".split("_"), longDateFormat : { LT : "HH:mm", L : "YYYY-MM-DD", LL : "YYYY [m.] MMMM D [d.]", LLL : "YYYY [m.] MMMM D [d.], LT [val.]", LLLL : "YYYY [m.] MMMM D [d.], dddd, LT [val.]", l : "YYYY-MM-DD", ll : "YYYY [m.] MMMM D [d.]", lll : "YYYY [m.] MMMM D [d.], LT [val.]", llll : "YYYY [m.] MMMM D [d.], ddd, LT [val.]" }, calendar : { sameDay : "[Šiandien] LT", nextDay : "[Rytoj] LT", nextWeek : "dddd LT", lastDay : "[Vakar] LT", lastWeek : "[Praėjusį] dddd LT", sameElse : "L" }, relativeTime : { future : "po %s", past : "prieš %s", s : translateSeconds, m : translateSingular, mm : translate, h : translateSingular, hh : translate, d : translateSingular, dd : translate, M : translateSingular, MM : translate, y : translateSingular, yy : translate }, ordinal : function (number) { return number + '-oji'; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : latvian (lv) // author : Kristaps Karlsons : https://github.com/skakri (function (factory) { factory(moment); }(function (moment) { var units = { 'mm': 'minūti_minūtes_minūte_minūtes', 'hh': 'stundu_stundas_stunda_stundas', 'dd': 'dienu_dienas_diena_dienas', 'MM': 'mēnesi_mēnešus_mēnesis_mēneši', 'yy': 'gadu_gadus_gads_gadi' }; function format(word, number, withoutSuffix) { var forms = word.split('_'); if (withoutSuffix) { return number % 10 === 1 && number !== 11 ? forms[2] : forms[3]; } else { return number % 10 === 1 && number !== 11 ? forms[0] : forms[1]; } } function relativeTimeWithPlural(number, withoutSuffix, key) { return number + ' ' + format(units[key], number, withoutSuffix); } return moment.lang('lv', { months : "janvāris_februāris_marts_aprīlis_maijs_jūnijs_jūlijs_augusts_septembris_oktobris_novembris_decembris".split("_"), monthsShort : "jan_feb_mar_apr_mai_jūn_jūl_aug_sep_okt_nov_dec".split("_"), weekdays : "svētdiena_pirmdiena_otrdiena_trešdiena_ceturtdiena_piektdiena_sestdiena".split("_"), weekdaysShort : "Sv_P_O_T_C_Pk_S".split("_"), weekdaysMin : "Sv_P_O_T_C_Pk_S".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "YYYY. [gada] D. MMMM", LLL : "YYYY. [gada] D. MMMM, LT", LLLL : "YYYY. [gada] D. MMMM, dddd, LT" }, calendar : { sameDay : '[Šodien pulksten] LT', nextDay : '[Rīt pulksten] LT', nextWeek : 'dddd [pulksten] LT', lastDay : '[Vakar pulksten] LT', lastWeek : '[Pagājušā] dddd [pulksten] LT', sameElse : 'L' }, relativeTime : { future : "%s vēlāk", past : "%s agrāk", s : "dažas sekundes", m : "minūti", mm : relativeTimeWithPlural, h : "stundu", hh : relativeTimeWithPlural, d : "dienu", dd : relativeTimeWithPlural, M : "mēnesi", MM : relativeTimeWithPlural, y : "gadu", yy : relativeTimeWithPlural }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : macedonian (mk) // author : Borislav Mickov : https://github.com/B0k0 (function (factory) { factory(moment); }(function (moment) { return moment.lang('mk', { months : "јануари_февруари_март_април_мај_јуни_јули_август_септември_октомври_ноември_декември".split("_"), monthsShort : "јан_фев_мар_апр_мај_јун_јул_авг_сеп_окт_ное_дек".split("_"), weekdays : "недела_понеделник_вторник_среда_четврток_петок_сабота".split("_"), weekdaysShort : "нед_пон_вто_сре_чет_пет_саб".split("_"), weekdaysMin : "нe_пo_вт_ср_че_пе_сa".split("_"), longDateFormat : { LT : "H:mm", L : "D.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[Денес во] LT', nextDay : '[Утре во] LT', nextWeek : 'dddd [во] LT', lastDay : '[Вчера во] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: case 6: return '[Во изминатата] dddd [во] LT'; case 1: case 2: case 4: case 5: return '[Во изминатиот] dddd [во] LT'; } }, sameElse : 'L' }, relativeTime : { future : "после %s", past : "пред %s", s : "неколку секунди", m : "минута", mm : "%d минути", h : "час", hh : "%d часа", d : "ден", dd : "%d дена", M : "месец", MM : "%d месеци", y : "година", yy : "%d години" }, ordinal : function (number) { var lastDigit = number % 10, last2Digits = number % 100; if (number === 0) { return number + '-ев'; } else if (last2Digits === 0) { return number + '-ен'; } else if (last2Digits > 10 && last2Digits < 20) { return number + '-ти'; } else if (lastDigit === 1) { return number + '-ви'; } else if (lastDigit === 2) { return number + '-ри'; } else if (lastDigit === 7 || lastDigit === 8) { return number + '-ми'; } else { return number + '-ти'; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : malayalam (ml) // author : Floyd Pink : https://github.com/floydpink (function (factory) { factory(moment); }(function (moment) { return moment.lang('ml', { months : 'ജനുവരി_ഫെബ്രുവരി_മാർച്ച്_ഏപ്രിൽ_മേയ്_ജൂൺ_ജൂലൈ_ഓഗസ്റ്റ്_സെപ്റ്റംബർ_ഒക്ടോബർ_നവംബർ_ഡിസംബർ'.split("_"), monthsShort : 'ജനു._ഫെബ്രു._മാർ._ഏപ്രി._മേയ്_ജൂൺ_ജൂലൈ._ഓഗ._സെപ്റ്റ._ഒക്ടോ._നവം._ഡിസം.'.split("_"), weekdays : 'ഞായറാഴ്ച_തിങ്കളാഴ്ച_ചൊവ്വാഴ്ച_ബുധനാഴ്ച_വ്യാഴാഴ്ച_വെള്ളിയാഴ്ച_ശനിയാഴ്ച'.split("_"), weekdaysShort : 'ഞായർ_തിങ്കൾ_ചൊവ്വ_ബുധൻ_വ്യാഴം_വെള്ളി_ശനി'.split("_"), weekdaysMin : 'ഞാ_തി_ചൊ_ബു_വ്യാ_വെ_ശ'.split("_"), longDateFormat : { LT : "A h:mm -നു", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY, LT", LLLL : "dddd, D MMMM YYYY, LT" }, calendar : { sameDay : '[ഇന്ന്] LT', nextDay : '[നാളെ] LT', nextWeek : 'dddd, LT', lastDay : '[ഇന്നലെ] LT', lastWeek : '[കഴിഞ്ഞ] dddd, LT', sameElse : 'L' }, relativeTime : { future : "%s കഴിഞ്ഞ്", past : "%s മുൻപ്", s : "അൽപ നിമിഷങ്ങൾ", m : "ഒരു മിനിറ്റ്", mm : "%d മിനിറ്റ്", h : "ഒരു മണിക്കൂർ", hh : "%d മണിക്കൂർ", d : "ഒരു ദിവസം", dd : "%d ദിവസം", M : "ഒരു മാസം", MM : "%d മാസം", y : "ഒരു വർഷം", yy : "%d വർഷം" }, meridiem : function (hour, minute, isLower) { if (hour < 4) { return "രാത്രി"; } else if (hour < 12) { return "രാവിലെ"; } else if (hour < 17) { return "ഉച്ച കഴിഞ്ഞ്"; } else if (hour < 20) { return "വൈകുന്നേരം"; } else { return "രാത്രി"; } } }); })); // moment.js language configuration // language : Marathi (mr) // author : Harshad Kale : https://github.com/kalehv (function (factory) { factory(moment); }(function (moment) { var symbolMap = { '1': '१', '2': '२', '3': '३', '4': '४', '5': '५', '6': '६', '7': '७', '8': '८', '9': '९', '0': '०' }, numberMap = { '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9', '०': '0' }; return moment.lang('mr', { months : 'जानेवारी_फेब्रुवारी_मार्च_एप्रिल_मे_जून_जुलै_ऑगस्ट_सप्टेंबर_ऑक्टोबर_नोव्हेंबर_डिसेंबर'.split("_"), monthsShort: 'जाने._फेब्रु._मार्च._एप्रि._मे._जून._जुलै._ऑग._सप्टें._ऑक्टो._नोव्हें._डिसें.'.split("_"), weekdays : 'रविवार_सोमवार_मंगळवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split("_"), weekdaysShort : 'रवि_सोम_मंगळ_बुध_गुरू_शुक्र_शनि'.split("_"), weekdaysMin : 'र_सो_मं_बु_गु_शु_श'.split("_"), longDateFormat : { LT : "A h:mm वाजता", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY, LT", LLLL : "dddd, D MMMM YYYY, LT" }, calendar : { sameDay : '[आज] LT', nextDay : '[उद्या] LT', nextWeek : 'dddd, LT', lastDay : '[काल] LT', lastWeek: '[मागील] dddd, LT', sameElse : 'L' }, relativeTime : { future : "%s नंतर", past : "%s पूर्वी", s : "सेकंद", m: "एक मिनिट", mm: "%d मिनिटे", h : "एक तास", hh : "%d तास", d : "एक दिवस", dd : "%d दिवस", M : "एक महिना", MM : "%d महिने", y : "एक वर्ष", yy : "%d वर्षे" }, preparse: function (string) { return string.replace(/[१२३४५६७८९०]/g, function (match) { return numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }); }, meridiem: function (hour, minute, isLower) { if (hour < 4) { return "रात्री"; } else if (hour < 10) { return "सकाळी"; } else if (hour < 17) { return "दुपारी"; } else if (hour < 20) { return "सायंकाळी"; } else { return "रात्री"; } }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Bahasa Malaysia (ms-MY) // author : Weldan Jamili : https://github.com/weldan (function (factory) { factory(moment); }(function (moment) { return moment.lang('ms-my', { months : "Januari_Februari_Mac_April_Mei_Jun_Julai_Ogos_September_Oktober_November_Disember".split("_"), monthsShort : "Jan_Feb_Mac_Apr_Mei_Jun_Jul_Ogs_Sep_Okt_Nov_Dis".split("_"), weekdays : "Ahad_Isnin_Selasa_Rabu_Khamis_Jumaat_Sabtu".split("_"), weekdaysShort : "Ahd_Isn_Sel_Rab_Kha_Jum_Sab".split("_"), weekdaysMin : "Ah_Is_Sl_Rb_Km_Jm_Sb".split("_"), longDateFormat : { LT : "HH.mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY [pukul] LT", LLLL : "dddd, D MMMM YYYY [pukul] LT" }, meridiem : function (hours, minutes, isLower) { if (hours < 11) { return 'pagi'; } else if (hours < 15) { return 'tengahari'; } else if (hours < 19) { return 'petang'; } else { return 'malam'; } }, calendar : { sameDay : '[Hari ini pukul] LT', nextDay : '[Esok pukul] LT', nextWeek : 'dddd [pukul] LT', lastDay : '[Kelmarin pukul] LT', lastWeek : 'dddd [lepas pukul] LT', sameElse : 'L' }, relativeTime : { future : "dalam %s", past : "%s yang lepas", s : "beberapa saat", m : "seminit", mm : "%d minit", h : "sejam", hh : "%d jam", d : "sehari", dd : "%d hari", M : "sebulan", MM : "%d bulan", y : "setahun", yy : "%d tahun" }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : norwegian bokmål (nb) // authors : Espen Hovlandsdal : https://github.com/rexxars // Sigurd Gartmann : https://github.com/sigurdga (function (factory) { factory(moment); }(function (moment) { return moment.lang('nb', { months : "januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember".split("_"), monthsShort : "jan._feb._mars_april_mai_juni_juli_aug._sep._okt._nov._des.".split("_"), weekdays : "søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag".split("_"), weekdaysShort : "sø._ma._ti._on._to._fr._lø.".split("_"), weekdaysMin : "sø_ma_ti_on_to_fr_lø".split("_"), longDateFormat : { LT : "H.mm", L : "DD.MM.YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY [kl.] LT", LLLL : "dddd D. MMMM YYYY [kl.] LT" }, calendar : { sameDay: '[i dag kl.] LT', nextDay: '[i morgen kl.] LT', nextWeek: 'dddd [kl.] LT', lastDay: '[i går kl.] LT', lastWeek: '[forrige] dddd [kl.] LT', sameElse: 'L' }, relativeTime : { future : "om %s", past : "for %s siden", s : "noen sekunder", m : "ett minutt", mm : "%d minutter", h : "en time", hh : "%d timer", d : "en dag", dd : "%d dager", M : "en måned", MM : "%d måneder", y : "ett år", yy : "%d år" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : nepali/nepalese // author : suvash : https://github.com/suvash (function (factory) { factory(moment); }(function (moment) { var symbolMap = { '1': '१', '2': '२', '3': '३', '4': '४', '5': '५', '6': '६', '7': '७', '8': '८', '9': '९', '0': '०' }, numberMap = { '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9', '०': '0' }; return moment.lang('ne', { months : 'जनवरी_फेब्रुवरी_मार्च_अप्रिल_मई_जुन_जुलाई_अगष्ट_सेप्टेम्बर_अक्टोबर_नोभेम्बर_डिसेम्बर'.split("_"), monthsShort : 'जन._फेब्रु._मार्च_अप्रि._मई_जुन_जुलाई._अग._सेप्ट._अक्टो._नोभे._डिसे.'.split("_"), weekdays : 'आइतबार_सोमबार_मङ्गलबार_बुधबार_बिहिबार_शुक्रबार_शनिबार'.split("_"), weekdaysShort : 'आइत._सोम._मङ्गल._बुध._बिहि._शुक्र._शनि.'.split("_"), weekdaysMin : 'आइ._सो._मङ्_बु._बि._शु._श.'.split("_"), longDateFormat : { LT : "Aको h:mm बजे", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY, LT", LLLL : "dddd, D MMMM YYYY, LT" }, preparse: function (string) { return string.replace(/[१२३४५६७८९०]/g, function (match) { return numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }); }, meridiem : function (hour, minute, isLower) { if (hour < 3) { return "राती"; } else if (hour < 10) { return "बिहान"; } else if (hour < 15) { return "दिउँसो"; } else if (hour < 18) { return "बेलुका"; } else if (hour < 20) { return "साँझ"; } else { return "राती"; } }, calendar : { sameDay : '[आज] LT', nextDay : '[भोली] LT', nextWeek : '[आउँदो] dddd[,] LT', lastDay : '[हिजो] LT', lastWeek : '[गएको] dddd[,] LT', sameElse : 'L' }, relativeTime : { future : "%sमा", past : "%s अगाडी", s : "केही समय", m : "एक मिनेट", mm : "%d मिनेट", h : "एक घण्टा", hh : "%d घण्टा", d : "एक दिन", dd : "%d दिन", M : "एक महिना", MM : "%d महिना", y : "एक बर्ष", yy : "%d बर्ष" }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : dutch (nl) // author : Joris Röling : https://github.com/jjupiter (function (factory) { factory(moment); }(function (moment) { var monthsShortWithDots = "jan._feb._mrt._apr._mei_jun._jul._aug._sep._okt._nov._dec.".split("_"), monthsShortWithoutDots = "jan_feb_mrt_apr_mei_jun_jul_aug_sep_okt_nov_dec".split("_"); return moment.lang('nl', { months : "januari_februari_maart_april_mei_juni_juli_augustus_september_oktober_november_december".split("_"), monthsShort : function (m, format) { if (/-MMM-/.test(format)) { return monthsShortWithoutDots[m.month()]; } else { return monthsShortWithDots[m.month()]; } }, weekdays : "zondag_maandag_dinsdag_woensdag_donderdag_vrijdag_zaterdag".split("_"), weekdaysShort : "zo._ma._di._wo._do._vr._za.".split("_"), weekdaysMin : "Zo_Ma_Di_Wo_Do_Vr_Za".split("_"), longDateFormat : { LT : "HH:mm", L : "DD-MM-YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: '[vandaag om] LT', nextDay: '[morgen om] LT', nextWeek: 'dddd [om] LT', lastDay: '[gisteren om] LT', lastWeek: '[afgelopen] dddd [om] LT', sameElse: 'L' }, relativeTime : { future : "over %s", past : "%s geleden", s : "een paar seconden", m : "één minuut", mm : "%d minuten", h : "één uur", hh : "%d uur", d : "één dag", dd : "%d dagen", M : "één maand", MM : "%d maanden", y : "één jaar", yy : "%d jaar" }, ordinal : function (number) { return number + ((number === 1 || number === 8 || number >= 20) ? 'ste' : 'de'); }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : norwegian nynorsk (nn) // author : https://github.com/mechuwind (function (factory) { factory(moment); }(function (moment) { return moment.lang('nn', { months : "januar_februar_mars_april_mai_juni_juli_august_september_oktober_november_desember".split("_"), monthsShort : "jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des".split("_"), weekdays : "sundag_måndag_tysdag_onsdag_torsdag_fredag_laurdag".split("_"), weekdaysShort : "sun_mån_tys_ons_tor_fre_lau".split("_"), weekdaysMin : "su_må_ty_on_to_fr_lø".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: '[I dag klokka] LT', nextDay: '[I morgon klokka] LT', nextWeek: 'dddd [klokka] LT', lastDay: '[I går klokka] LT', lastWeek: '[Føregående] dddd [klokka] LT', sameElse: 'L' }, relativeTime : { future : "om %s", past : "for %s siden", s : "noen sekund", m : "ett minutt", mm : "%d minutt", h : "en time", hh : "%d timar", d : "en dag", dd : "%d dagar", M : "en månad", MM : "%d månader", y : "ett år", yy : "%d år" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : polish (pl) // author : Rafal Hirsz : https://github.com/evoL (function (factory) { factory(moment); }(function (moment) { var monthsNominative = "styczeń_luty_marzec_kwiecień_maj_czerwiec_lipiec_sierpień_wrzesień_październik_listopad_grudzień".split("_"), monthsSubjective = "stycznia_lutego_marca_kwietnia_maja_czerwca_lipca_sierpnia_września_października_listopada_grudnia".split("_"); function plural(n) { return (n % 10 < 5) && (n % 10 > 1) && ((~~(n / 10) % 10) !== 1); } function translate(number, withoutSuffix, key) { var result = number + " "; switch (key) { case 'm': return withoutSuffix ? 'minuta' : 'minutę'; case 'mm': return result + (plural(number) ? 'minuty' : 'minut'); case 'h': return withoutSuffix ? 'godzina' : 'godzinę'; case 'hh': return result + (plural(number) ? 'godziny' : 'godzin'); case 'MM': return result + (plural(number) ? 'miesiące' : 'miesięcy'); case 'yy': return result + (plural(number) ? 'lata' : 'lat'); } } return moment.lang('pl', { months : function (momentToFormat, format) { if (/D MMMM/.test(format)) { return monthsSubjective[momentToFormat.month()]; } else { return monthsNominative[momentToFormat.month()]; } }, monthsShort : "sty_lut_mar_kwi_maj_cze_lip_sie_wrz_paź_lis_gru".split("_"), weekdays : "niedziela_poniedziałek_wtorek_środa_czwartek_piątek_sobota".split("_"), weekdaysShort : "nie_pon_wt_śr_czw_pt_sb".split("_"), weekdaysMin : "N_Pn_Wt_Śr_Cz_Pt_So".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay: '[Dziś o] LT', nextDay: '[Jutro o] LT', nextWeek: '[W] dddd [o] LT', lastDay: '[Wczoraj o] LT', lastWeek: function () { switch (this.day()) { case 0: return '[W zeszłą niedzielę o] LT'; case 3: return '[W zeszłą środę o] LT'; case 6: return '[W zeszłą sobotę o] LT'; default: return '[W zeszły] dddd [o] LT'; } }, sameElse: 'L' }, relativeTime : { future : "za %s", past : "%s temu", s : "kilka sekund", m : translate, mm : translate, h : translate, hh : translate, d : "1 dzień", dd : '%d dni', M : "miesiąc", MM : translate, y : "rok", yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : brazilian portuguese (pt-br) // author : Caio Ribeiro Pereira : https://github.com/caio-ribeiro-pereira (function (factory) { factory(moment); }(function (moment) { return moment.lang('pt-br', { months : "Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro".split("_"), monthsShort : "Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez".split("_"), weekdays : "Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado".split("_"), weekdaysShort : "Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"), weekdaysMin : "Dom_2ª_3ª_4ª_5ª_6ª_Sáb".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D [de] MMMM [de] YYYY", LLL : "D [de] MMMM [de] YYYY LT", LLLL : "dddd, D [de] MMMM [de] YYYY LT" }, calendar : { sameDay: '[Hoje às] LT', nextDay: '[Amanhã às] LT', nextWeek: 'dddd [às] LT', lastDay: '[Ontem às] LT', lastWeek: function () { return (this.day() === 0 || this.day() === 6) ? '[Último] dddd [às] LT' : // Saturday + Sunday '[Última] dddd [às] LT'; // Monday - Friday }, sameElse: 'L' }, relativeTime : { future : "em %s", past : "%s atrás", s : "segundos", m : "um minuto", mm : "%d minutos", h : "uma hora", hh : "%d horas", d : "um dia", dd : "%d dias", M : "um mês", MM : "%d meses", y : "um ano", yy : "%d anos" }, ordinal : '%dº' }); })); // moment.js language configuration // language : portuguese (pt) // author : Jefferson : https://github.com/jalex79 (function (factory) { factory(moment); }(function (moment) { return moment.lang('pt', { months : "Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro".split("_"), monthsShort : "Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez".split("_"), weekdays : "Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado".split("_"), weekdaysShort : "Dom_Seg_Ter_Qua_Qui_Sex_Sáb".split("_"), weekdaysMin : "Dom_2ª_3ª_4ª_5ª_6ª_Sáb".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D [de] MMMM [de] YYYY", LLL : "D [de] MMMM [de] YYYY LT", LLLL : "dddd, D [de] MMMM [de] YYYY LT" }, calendar : { sameDay: '[Hoje às] LT', nextDay: '[Amanhã às] LT', nextWeek: 'dddd [às] LT', lastDay: '[Ontem às] LT', lastWeek: function () { return (this.day() === 0 || this.day() === 6) ? '[Último] dddd [às] LT' : // Saturday + Sunday '[Última] dddd [às] LT'; // Monday - Friday }, sameElse: 'L' }, relativeTime : { future : "em %s", past : "%s atrás", s : "segundos", m : "um minuto", mm : "%d minutos", h : "uma hora", hh : "%d horas", d : "um dia", dd : "%d dias", M : "um mês", MM : "%d meses", y : "um ano", yy : "%d anos" }, ordinal : '%dº', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : romanian (ro) // author : Vlad Gurdiga : https://github.com/gurdiga // author : Valentin Agachi : https://github.com/avaly (function (factory) { factory(moment); }(function (moment) { function relativeTimeWithPlural(number, withoutSuffix, key) { var format = { 'mm': 'minute', 'hh': 'ore', 'dd': 'zile', 'MM': 'luni', 'yy': 'ani' }, separator = ' '; if (number % 100 >= 20 || (number >= 100 && number % 100 === 0)) { separator = ' de '; } return number + separator + format[key]; } return moment.lang('ro', { months : "ianuarie_februarie_martie_aprilie_mai_iunie_iulie_august_septembrie_octombrie_noiembrie_decembrie".split("_"), monthsShort : "ian_feb_mar_apr_mai_iun_iul_aug_sep_oct_noi_dec".split("_"), weekdays : "duminică_luni_marți_miercuri_joi_vineri_sâmbătă".split("_"), weekdaysShort : "Dum_Lun_Mar_Mie_Joi_Vin_Sâm".split("_"), weekdaysMin : "Du_Lu_Ma_Mi_Jo_Vi_Sâ".split("_"), longDateFormat : { LT : "H:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY H:mm", LLLL : "dddd, D MMMM YYYY H:mm" }, calendar : { sameDay: "[azi la] LT", nextDay: '[mâine la] LT', nextWeek: 'dddd [la] LT', lastDay: '[ieri la] LT', lastWeek: '[fosta] dddd [la] LT', sameElse: 'L' }, relativeTime : { future : "peste %s", past : "%s în urmă", s : "câteva secunde", m : "un minut", mm : relativeTimeWithPlural, h : "o oră", hh : relativeTimeWithPlural, d : "o zi", dd : relativeTimeWithPlural, M : "o lună", MM : relativeTimeWithPlural, y : "un an", yy : relativeTimeWithPlural }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : serbian (rs) // author : Limon Monte : https://github.com/limonte // based on (bs) translation by Nedim Cholich (function (factory) { factory(moment); }(function (moment) { function translate(number, withoutSuffix, key) { var result = number + " "; switch (key) { case 'm': return withoutSuffix ? 'jedna minuta' : 'jedne minute'; case 'mm': if (number === 1) { result += 'minuta'; } else if (number === 2 || number === 3 || number === 4) { result += 'minute'; } else { result += 'minuta'; } return result; case 'h': return withoutSuffix ? 'jedan sat' : 'jednog sata'; case 'hh': if (number === 1) { result += 'sat'; } else if (number === 2 || number === 3 || number === 4) { result += 'sata'; } else { result += 'sati'; } return result; case 'dd': if (number === 1) { result += 'dan'; } else { result += 'dana'; } return result; case 'MM': if (number === 1) { result += 'mesec'; } else if (number === 2 || number === 3 || number === 4) { result += 'meseca'; } else { result += 'meseci'; } return result; case 'yy': if (number === 1) { result += 'godina'; } else if (number === 2 || number === 3 || number === 4) { result += 'godine'; } else { result += 'godina'; } return result; } } return moment.lang('rs', { months : "januar_februar_mart_april_maj_jun_jul_avgust_septembar_oktobar_novembar_decembar".split("_"), monthsShort : "jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.".split("_"), weekdays : "nedelja_ponedeljak_utorak_sreda_četvrtak_petak_subota".split("_"), weekdaysShort : "ned._pon._uto._sre._čet._pet._sub.".split("_"), weekdaysMin : "ne_po_ut_sr_če_pe_su".split("_"), longDateFormat : { LT : "H:mm", L : "DD. MM. YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay : '[danas u] LT', nextDay : '[sutra u] LT', nextWeek : function () { switch (this.day()) { case 0: return '[u] [nedelju] [u] LT'; case 3: return '[u] [sredu] [u] LT'; case 6: return '[u] [subotu] [u] LT'; case 1: case 2: case 4: case 5: return '[u] dddd [u] LT'; } }, lastDay : '[juče u] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: return '[prošlu] dddd [u] LT'; case 6: return '[prošle] [subote] [u] LT'; case 1: case 2: case 4: case 5: return '[prošli] dddd [u] LT'; } }, sameElse : 'L' }, relativeTime : { future : "za %s", past : "pre %s", s : "par sekundi", m : translate, mm : translate, h : translate, hh : translate, d : "dan", dd : translate, M : "mesec", MM : translate, y : "godinu", yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : russian (ru) // author : Viktorminator : https://github.com/Viktorminator // Author : Menelion Elensúle : https://github.com/Oire (function (factory) { factory(moment); }(function (moment) { function plural(word, num) { var forms = word.split('_'); return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]); } function relativeTimeWithPlural(number, withoutSuffix, key) { var format = { 'mm': 'минута_минуты_минут', 'hh': 'час_часа_часов', 'dd': 'день_дня_дней', 'MM': 'месяц_месяца_месяцев', 'yy': 'год_года_лет' }; if (key === 'm') { return withoutSuffix ? 'минута' : 'минуту'; } else { return number + ' ' + plural(format[key], +number); } } function monthsCaseReplace(m, format) { var months = { 'nominative': 'январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь'.split('_'), 'accusative': 'января_февраля_марта_апреля_мая_июня_июля_августа_сентября_октября_ноября_декабря'.split('_') }, nounCase = (/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/).test(format) ? 'accusative' : 'nominative'; return months[nounCase][m.month()]; } function monthsShortCaseReplace(m, format) { var monthsShort = { 'nominative': 'янв_фев_мар_апр_май_июнь_июль_авг_сен_окт_ноя_дек'.split('_'), 'accusative': 'янв_фев_мар_апр_мая_июня_июля_авг_сен_окт_ноя_дек'.split('_') }, nounCase = (/D[oD]?(\[[^\[\]]*\]|\s+)+MMMM?/).test(format) ? 'accusative' : 'nominative'; return monthsShort[nounCase][m.month()]; } function weekdaysCaseReplace(m, format) { var weekdays = { 'nominative': 'воскресенье_понедельник_вторник_среда_четверг_пятница_суббота'.split('_'), 'accusative': 'воскресенье_понедельник_вторник_среду_четверг_пятницу_субботу'.split('_') }, nounCase = (/\[ ?[Вв] ?(?:прошлую|следующую)? ?\] ?dddd/).test(format) ? 'accusative' : 'nominative'; return weekdays[nounCase][m.day()]; } return moment.lang('ru', { months : monthsCaseReplace, monthsShort : monthsShortCaseReplace, weekdays : weekdaysCaseReplace, weekdaysShort : "вс_пн_вт_ср_чт_пт_сб".split("_"), weekdaysMin : "вс_пн_вт_ср_чт_пт_сб".split("_"), monthsParse : [/^янв/i, /^фев/i, /^мар/i, /^апр/i, /^ма[й|я]/i, /^июн/i, /^июл/i, /^авг/i, /^сен/i, /^окт/i, /^ноя/i, /^дек/i], longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY г.", LLL : "D MMMM YYYY г., LT", LLLL : "dddd, D MMMM YYYY г., LT" }, calendar : { sameDay: '[Сегодня в] LT', nextDay: '[Завтра в] LT', lastDay: '[Вчера в] LT', nextWeek: function () { return this.day() === 2 ? '[Во] dddd [в] LT' : '[В] dddd [в] LT'; }, lastWeek: function () { switch (this.day()) { case 0: return '[В прошлое] dddd [в] LT'; case 1: case 2: case 4: return '[В прошлый] dddd [в] LT'; case 3: case 5: case 6: return '[В прошлую] dddd [в] LT'; } }, sameElse: 'L' }, relativeTime : { future : "через %s", past : "%s назад", s : "несколько секунд", m : relativeTimeWithPlural, mm : relativeTimeWithPlural, h : "час", hh : relativeTimeWithPlural, d : "день", dd : relativeTimeWithPlural, M : "месяц", MM : relativeTimeWithPlural, y : "год", yy : relativeTimeWithPlural }, // M. E.: those two are virtually unused but a user might want to implement them for his/her website for some reason meridiem : function (hour, minute, isLower) { if (hour < 4) { return "ночи"; } else if (hour < 12) { return "утра"; } else if (hour < 17) { return "дня"; } else { return "вечера"; } }, ordinal: function (number, period) { switch (period) { case 'M': case 'd': case 'DDD': return number + '-й'; case 'D': return number + '-го'; case 'w': case 'W': return number + '-я'; default: return number; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : slovak (sk) // author : Martin Minka : https://github.com/k2s // based on work of petrbela : https://github.com/petrbela (function (factory) { factory(moment); }(function (moment) { var months = "január_február_marec_apríl_máj_jún_júl_august_september_október_november_december".split("_"), monthsShort = "jan_feb_mar_apr_máj_jún_júl_aug_sep_okt_nov_dec".split("_"); function plural(n) { return (n > 1) && (n < 5); } function translate(number, withoutSuffix, key, isFuture) { var result = number + " "; switch (key) { case 's': // a few seconds / in a few seconds / a few seconds ago return (withoutSuffix || isFuture) ? 'pár sekúnd' : 'pár sekundami'; case 'm': // a minute / in a minute / a minute ago return withoutSuffix ? 'minúta' : (isFuture ? 'minútu' : 'minútou'); case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'minúty' : 'minút'); } else { return result + 'minútami'; } break; case 'h': // an hour / in an hour / an hour ago return withoutSuffix ? 'hodina' : (isFuture ? 'hodinu' : 'hodinou'); case 'hh': // 9 hours / in 9 hours / 9 hours ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'hodiny' : 'hodín'); } else { return result + 'hodinami'; } break; case 'd': // a day / in a day / a day ago return (withoutSuffix || isFuture) ? 'deň' : 'dňom'; case 'dd': // 9 days / in 9 days / 9 days ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'dni' : 'dní'); } else { return result + 'dňami'; } break; case 'M': // a month / in a month / a month ago return (withoutSuffix || isFuture) ? 'mesiac' : 'mesiacom'; case 'MM': // 9 months / in 9 months / 9 months ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'mesiace' : 'mesiacov'); } else { return result + 'mesiacmi'; } break; case 'y': // a year / in a year / a year ago return (withoutSuffix || isFuture) ? 'rok' : 'rokom'; case 'yy': // 9 years / in 9 years / 9 years ago if (withoutSuffix || isFuture) { return result + (plural(number) ? 'roky' : 'rokov'); } else { return result + 'rokmi'; } break; } } return moment.lang('sk', { months : months, monthsShort : monthsShort, monthsParse : (function (months, monthsShort) { var i, _monthsParse = []; for (i = 0; i < 12; i++) { // use custom parser to solve problem with July (červenec) _monthsParse[i] = new RegExp('^' + months[i] + '$|^' + monthsShort[i] + '$', 'i'); } return _monthsParse; }(months, monthsShort)), weekdays : "nedeľa_pondelok_utorok_streda_štvrtok_piatok_sobota".split("_"), weekdaysShort : "ne_po_ut_st_št_pi_so".split("_"), weekdaysMin : "ne_po_ut_st_št_pi_so".split("_"), longDateFormat : { LT: "H:mm", L : "DD.MM.YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd D. MMMM YYYY LT" }, calendar : { sameDay: "[dnes o] LT", nextDay: '[zajtra o] LT', nextWeek: function () { switch (this.day()) { case 0: return '[v nedeľu o] LT'; case 1: case 2: return '[v] dddd [o] LT'; case 3: return '[v stredu o] LT'; case 4: return '[vo štvrtok o] LT'; case 5: return '[v piatok o] LT'; case 6: return '[v sobotu o] LT'; } }, lastDay: '[včera o] LT', lastWeek: function () { switch (this.day()) { case 0: return '[minulú nedeľu o] LT'; case 1: case 2: return '[minulý] dddd [o] LT'; case 3: return '[minulú stredu o] LT'; case 4: case 5: return '[minulý] dddd [o] LT'; case 6: return '[minulú sobotu o] LT'; } }, sameElse: "L" }, relativeTime : { future : "za %s", past : "pred %s", s : translate, m : translate, mm : translate, h : translate, hh : translate, d : translate, dd : translate, M : translate, MM : translate, y : translate, yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : slovenian (sl) // author : Robert Sedovšek : https://github.com/sedovsek (function (factory) { factory(moment); }(function (moment) { function translate(number, withoutSuffix, key) { var result = number + " "; switch (key) { case 'm': return withoutSuffix ? 'ena minuta' : 'eno minuto'; case 'mm': if (number === 1) { result += 'minuta'; } else if (number === 2) { result += 'minuti'; } else if (number === 3 || number === 4) { result += 'minute'; } else { result += 'minut'; } return result; case 'h': return withoutSuffix ? 'ena ura' : 'eno uro'; case 'hh': if (number === 1) { result += 'ura'; } else if (number === 2) { result += 'uri'; } else if (number === 3 || number === 4) { result += 'ure'; } else { result += 'ur'; } return result; case 'dd': if (number === 1) { result += 'dan'; } else { result += 'dni'; } return result; case 'MM': if (number === 1) { result += 'mesec'; } else if (number === 2) { result += 'meseca'; } else if (number === 3 || number === 4) { result += 'mesece'; } else { result += 'mesecev'; } return result; case 'yy': if (number === 1) { result += 'leto'; } else if (number === 2) { result += 'leti'; } else if (number === 3 || number === 4) { result += 'leta'; } else { result += 'let'; } return result; } } return moment.lang('sl', { months : "januar_februar_marec_april_maj_junij_julij_avgust_september_oktober_november_december".split("_"), monthsShort : "jan._feb._mar._apr._maj._jun._jul._avg._sep._okt._nov._dec.".split("_"), weekdays : "nedelja_ponedeljek_torek_sreda_četrtek_petek_sobota".split("_"), weekdaysShort : "ned._pon._tor._sre._čet._pet._sob.".split("_"), weekdaysMin : "ne_po_to_sr_če_pe_so".split("_"), longDateFormat : { LT : "H:mm", L : "DD. MM. YYYY", LL : "D. MMMM YYYY", LLL : "D. MMMM YYYY LT", LLLL : "dddd, D. MMMM YYYY LT" }, calendar : { sameDay : '[danes ob] LT', nextDay : '[jutri ob] LT', nextWeek : function () { switch (this.day()) { case 0: return '[v] [nedeljo] [ob] LT'; case 3: return '[v] [sredo] [ob] LT'; case 6: return '[v] [soboto] [ob] LT'; case 1: case 2: case 4: case 5: return '[v] dddd [ob] LT'; } }, lastDay : '[včeraj ob] LT', lastWeek : function () { switch (this.day()) { case 0: case 3: case 6: return '[prejšnja] dddd [ob] LT'; case 1: case 2: case 4: case 5: return '[prejšnji] dddd [ob] LT'; } }, sameElse : 'L' }, relativeTime : { future : "čez %s", past : "%s nazaj", s : "nekaj sekund", m : translate, mm : translate, h : translate, hh : translate, d : "en dan", dd : translate, M : "en mesec", MM : translate, y : "eno leto", yy : translate }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Albanian (sq) // author : Flakërim Ismani : https://github.com/flakerimi // author: Menelion Elensúle: https://github.com/Oire (tests) (function (factory) { factory(moment); }(function (moment) { return moment.lang('sq', { months : "Janar_Shkurt_Mars_Prill_Maj_Qershor_Korrik_Gusht_Shtator_Tetor_Nëntor_Dhjetor".split("_"), monthsShort : "Jan_Shk_Mar_Pri_Maj_Qer_Kor_Gus_Sht_Tet_Nën_Dhj".split("_"), weekdays : "E Diel_E Hënë_E Marte_E Mërkure_E Enjte_E Premte_E Shtunë".split("_"), weekdaysShort : "Die_Hën_Mar_Mër_Enj_Pre_Sht".split("_"), weekdaysMin : "D_H_Ma_Më_E_P_Sh".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[Sot në] LT', nextDay : '[Neser në] LT', nextWeek : 'dddd [në] LT', lastDay : '[Dje në] LT', lastWeek : 'dddd [e kaluar në] LT', sameElse : 'L' }, relativeTime : { future : "në %s", past : "%s me parë", s : "disa sekonda", m : "një minut", mm : "%d minuta", h : "një orë", hh : "%d orë", d : "një ditë", dd : "%d ditë", M : "një muaj", MM : "%d muaj", y : "një vit", yy : "%d vite" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : swedish (sv) // author : Jens Alm : https://github.com/ulmus (function (factory) { factory(moment); }(function (moment) { return moment.lang('sv', { months : "januari_februari_mars_april_maj_juni_juli_augusti_september_oktober_november_december".split("_"), monthsShort : "jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec".split("_"), weekdays : "söndag_måndag_tisdag_onsdag_torsdag_fredag_lördag".split("_"), weekdaysShort : "sön_mån_tis_ons_tor_fre_lör".split("_"), weekdaysMin : "sö_må_ti_on_to_fr_lö".split("_"), longDateFormat : { LT : "HH:mm", L : "YYYY-MM-DD", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: '[Idag] LT', nextDay: '[Imorgon] LT', lastDay: '[Igår] LT', nextWeek: 'dddd LT', lastWeek: '[Förra] dddd[en] LT', sameElse: 'L' }, relativeTime : { future : "om %s", past : "för %s sedan", s : "några sekunder", m : "en minut", mm : "%d minuter", h : "en timme", hh : "%d timmar", d : "en dag", dd : "%d dagar", M : "en månad", MM : "%d månader", y : "ett år", yy : "%d år" }, ordinal : function (number) { var b = number % 10, output = (~~ (number % 100 / 10) === 1) ? 'e' : (b === 1) ? 'a' : (b === 2) ? 'a' : (b === 3) ? 'e' : 'e'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : tamil (ta) // author : Arjunkumar Krishnamoorthy : https://github.com/tk120404 (function (factory) { factory(moment); }(function (moment) { /*var symbolMap = { '1': '௧', '2': '௨', '3': '௩', '4': '௪', '5': '௫', '6': '௬', '7': '௭', '8': '௮', '9': '௯', '0': '௦' }, numberMap = { '௧': '1', '௨': '2', '௩': '3', '௪': '4', '௫': '5', '௬': '6', '௭': '7', '௮': '8', '௯': '9', '௦': '0' }; */ return moment.lang('ta', { months : 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split("_"), monthsShort : 'ஜனவரி_பிப்ரவரி_மார்ச்_ஏப்ரல்_மே_ஜூன்_ஜூலை_ஆகஸ்ட்_செப்டெம்பர்_அக்டோபர்_நவம்பர்_டிசம்பர்'.split("_"), weekdays : 'ஞாயிற்றுக்கிழமை_திங்கட்கிழமை_செவ்வாய்கிழமை_புதன்கிழமை_வியாழக்கிழமை_வெள்ளிக்கிழமை_சனிக்கிழமை'.split("_"), weekdaysShort : 'ஞாயிறு_திங்கள்_செவ்வாய்_புதன்_வியாழன்_வெள்ளி_சனி'.split("_"), weekdaysMin : 'ஞா_தி_செ_பு_வி_வெ_ச'.split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY, LT", LLLL : "dddd, D MMMM YYYY, LT" }, calendar : { sameDay : '[இன்று] LT', nextDay : '[நாளை] LT', nextWeek : 'dddd, LT', lastDay : '[நேற்று] LT', lastWeek : '[கடந்த வாரம்] dddd, LT', sameElse : 'L' }, relativeTime : { future : "%s இல்", past : "%s முன்", s : "ஒரு சில விநாடிகள்", m : "ஒரு நிமிடம்", mm : "%d நிமிடங்கள்", h : "ஒரு மணி நேரம்", hh : "%d மணி நேரம்", d : "ஒரு நாள்", dd : "%d நாட்கள்", M : "ஒரு மாதம்", MM : "%d மாதங்கள்", y : "ஒரு வருடம்", yy : "%d ஆண்டுகள்" }, /* preparse: function (string) { return string.replace(/[௧௨௩௪௫௬௭௮௯௦]/g, function (match) { return numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }); },*/ ordinal : function (number) { return number + 'வது'; }, // refer http://ta.wikipedia.org/s/1er1 meridiem : function (hour, minute, isLower) { if (hour >= 6 && hour <= 10) { return " காலை"; } else if (hour >= 10 && hour <= 14) { return " நண்பகல்"; } else if (hour >= 14 && hour <= 18) { return " எற்பாடு"; } else if (hour >= 18 && hour <= 20) { return " மாலை"; } else if (hour >= 20 && hour <= 24) { return " இரவு"; } else if (hour >= 0 && hour <= 6) { return " வைகறை"; } }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : thai (th) // author : Kridsada Thanabulpong : https://github.com/sirn (function (factory) { factory(moment); }(function (moment) { return moment.lang('th', { months : "มกราคม_กุมภาพันธ์_มีนาคม_เมษายน_พฤษภาคม_มิถุนายน_กรกฎาคม_สิงหาคม_กันยายน_ตุลาคม_พฤศจิกายน_ธันวาคม".split("_"), monthsShort : "มกรา_กุมภา_มีนา_เมษา_พฤษภา_มิถุนา_กรกฎา_สิงหา_กันยา_ตุลา_พฤศจิกา_ธันวา".split("_"), weekdays : "อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัสบดี_ศุกร์_เสาร์".split("_"), weekdaysShort : "อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัส_ศุกร์_เสาร์".split("_"), // yes, three characters difference weekdaysMin : "อา._จ._อ._พ._พฤ._ศ._ส.".split("_"), longDateFormat : { LT : "H นาฬิกา m นาที", L : "YYYY/MM/DD", LL : "D MMMM YYYY", LLL : "D MMMM YYYY เวลา LT", LLLL : "วันddddที่ D MMMM YYYY เวลา LT" }, meridiem : function (hour, minute, isLower) { if (hour < 12) { return "ก่อนเที่ยง"; } else { return "หลังเที่ยง"; } }, calendar : { sameDay : '[วันนี้ เวลา] LT', nextDay : '[พรุ่งนี้ เวลา] LT', nextWeek : 'dddd[หน้า เวลา] LT', lastDay : '[เมื่อวานนี้ เวลา] LT', lastWeek : '[วัน]dddd[ที่แล้ว เวลา] LT', sameElse : 'L' }, relativeTime : { future : "อีก %s", past : "%sที่แล้ว", s : "ไม่กี่วินาที", m : "1 นาที", mm : "%d นาที", h : "1 ชั่วโมง", hh : "%d ชั่วโมง", d : "1 วัน", dd : "%d วัน", M : "1 เดือน", MM : "%d เดือน", y : "1 ปี", yy : "%d ปี" } }); })); // moment.js language configuration // language : Tagalog/Filipino (tl-ph) // author : Dan Hagman (function (factory) { factory(moment); }(function (moment) { return moment.lang('tl-ph', { months : "Enero_Pebrero_Marso_Abril_Mayo_Hunyo_Hulyo_Agosto_Setyembre_Oktubre_Nobyembre_Disyembre".split("_"), monthsShort : "Ene_Peb_Mar_Abr_May_Hun_Hul_Ago_Set_Okt_Nob_Dis".split("_"), weekdays : "Linggo_Lunes_Martes_Miyerkules_Huwebes_Biyernes_Sabado".split("_"), weekdaysShort : "Lin_Lun_Mar_Miy_Huw_Biy_Sab".split("_"), weekdaysMin : "Li_Lu_Ma_Mi_Hu_Bi_Sab".split("_"), longDateFormat : { LT : "HH:mm", L : "MM/D/YYYY", LL : "MMMM D, YYYY", LLL : "MMMM D, YYYY LT", LLLL : "dddd, MMMM DD, YYYY LT" }, calendar : { sameDay: "[Ngayon sa] LT", nextDay: '[Bukas sa] LT', nextWeek: 'dddd [sa] LT', lastDay: '[Kahapon sa] LT', lastWeek: 'dddd [huling linggo] LT', sameElse: 'L' }, relativeTime : { future : "sa loob ng %s", past : "%s ang nakalipas", s : "ilang segundo", m : "isang minuto", mm : "%d minuto", h : "isang oras", hh : "%d oras", d : "isang araw", dd : "%d araw", M : "isang buwan", MM : "%d buwan", y : "isang taon", yy : "%d taon" }, ordinal : function (number) { return number; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : turkish (tr) // authors : Erhan Gundogan : https://github.com/erhangundogan, // Burak Yiğit Kaya: https://github.com/BYK (function (factory) { factory(moment); }(function (moment) { var suffixes = { 1: "'inci", 5: "'inci", 8: "'inci", 70: "'inci", 80: "'inci", 2: "'nci", 7: "'nci", 20: "'nci", 50: "'nci", 3: "'üncü", 4: "'üncü", 100: "'üncü", 6: "'ncı", 9: "'uncu", 10: "'uncu", 30: "'uncu", 60: "'ıncı", 90: "'ıncı" }; return moment.lang('tr', { months : "Ocak_Şubat_Mart_Nisan_Mayıs_Haziran_Temmuz_Ağustos_Eylül_Ekim_Kasım_Aralık".split("_"), monthsShort : "Oca_Şub_Mar_Nis_May_Haz_Tem_Ağu_Eyl_Eki_Kas_Ara".split("_"), weekdays : "Pazar_Pazartesi_Salı_Çarşamba_Perşembe_Cuma_Cumartesi".split("_"), weekdaysShort : "Paz_Pts_Sal_Çar_Per_Cum_Cts".split("_"), weekdaysMin : "Pz_Pt_Sa_Ça_Pe_Cu_Ct".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd, D MMMM YYYY LT" }, calendar : { sameDay : '[bugün saat] LT', nextDay : '[yarın saat] LT', nextWeek : '[haftaya] dddd [saat] LT', lastDay : '[dün] LT', lastWeek : '[geçen hafta] dddd [saat] LT', sameElse : 'L' }, relativeTime : { future : "%s sonra", past : "%s önce", s : "birkaç saniye", m : "bir dakika", mm : "%d dakika", h : "bir saat", hh : "%d saat", d : "bir gün", dd : "%d gün", M : "bir ay", MM : "%d ay", y : "bir yıl", yy : "%d yıl" }, ordinal : function (number) { if (number === 0) { // special case for zero return number + "'ıncı"; } var a = number % 10, b = number % 100 - a, c = number >= 100 ? 100 : null; return number + (suffixes[a] || suffixes[b] || suffixes[c]); }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Morocco Central Atlas Tamaziɣt in Latin (tzm-la) // author : Abdel Said : https://github.com/abdelsaid (function (factory) { factory(moment); }(function (moment) { return moment.lang('tzm-la', { months : "innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir".split("_"), monthsShort : "innayr_brˤayrˤ_marˤsˤ_ibrir_mayyw_ywnyw_ywlywz_ɣwšt_šwtanbir_ktˤwbrˤ_nwwanbir_dwjnbir".split("_"), weekdays : "asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas".split("_"), weekdaysShort : "asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas".split("_"), weekdaysMin : "asamas_aynas_asinas_akras_akwas_asimwas_asiḍyas".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[asdkh g] LT", nextDay: '[aska g] LT', nextWeek: 'dddd [g] LT', lastDay: '[assant g] LT', lastWeek: 'dddd [g] LT', sameElse: 'L' }, relativeTime : { future : "dadkh s yan %s", past : "yan %s", s : "imik", m : "minuḍ", mm : "%d minuḍ", h : "saɛa", hh : "%d tassaɛin", d : "ass", dd : "%d ossan", M : "ayowr", MM : "%d iyyirn", y : "asgas", yy : "%d isgasn" }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : Morocco Central Atlas Tamaziɣt (tzm) // author : Abdel Said : https://github.com/abdelsaid (function (factory) { factory(moment); }(function (moment) { return moment.lang('tzm', { months : "ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ".split("_"), monthsShort : "ⵉⵏⵏⴰⵢⵔ_ⴱⵕⴰⵢⵕ_ⵎⴰⵕⵚ_ⵉⴱⵔⵉⵔ_ⵎⴰⵢⵢⵓ_ⵢⵓⵏⵢⵓ_ⵢⵓⵍⵢⵓⵣ_ⵖⵓⵛⵜ_ⵛⵓⵜⴰⵏⴱⵉⵔ_ⴽⵟⵓⴱⵕ_ⵏⵓⵡⴰⵏⴱⵉⵔ_ⴷⵓⵊⵏⴱⵉⵔ".split("_"), weekdays : "ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ".split("_"), weekdaysShort : "ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ".split("_"), weekdaysMin : "ⴰⵙⴰⵎⴰⵙ_ⴰⵢⵏⴰⵙ_ⴰⵙⵉⵏⴰⵙ_ⴰⴽⵔⴰⵙ_ⴰⴽⵡⴰⵙ_ⴰⵙⵉⵎⵡⴰⵙ_ⴰⵙⵉⴹⵢⴰⵙ".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "dddd D MMMM YYYY LT" }, calendar : { sameDay: "[ⴰⵙⴷⵅ ⴴ] LT", nextDay: '[ⴰⵙⴽⴰ ⴴ] LT', nextWeek: 'dddd [ⴴ] LT', lastDay: '[ⴰⵚⴰⵏⵜ ⴴ] LT', lastWeek: 'dddd [ⴴ] LT', sameElse: 'L' }, relativeTime : { future : "ⴷⴰⴷⵅ ⵙ ⵢⴰⵏ %s", past : "ⵢⴰⵏ %s", s : "ⵉⵎⵉⴽ", m : "ⵎⵉⵏⵓⴺ", mm : "%d ⵎⵉⵏⵓⴺ", h : "ⵙⴰⵄⴰ", hh : "%d ⵜⴰⵙⵙⴰⵄⵉⵏ", d : "ⴰⵙⵙ", dd : "%d oⵙⵙⴰⵏ", M : "ⴰⵢoⵓⵔ", MM : "%d ⵉⵢⵢⵉⵔⵏ", y : "ⴰⵙⴳⴰⵙ", yy : "%d ⵉⵙⴳⴰⵙⵏ" }, week : { dow : 6, // Saturday is the first day of the week. doy : 12 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : ukrainian (uk) // author : zemlanin : https://github.com/zemlanin // Author : Menelion Elensúle : https://github.com/Oire (function (factory) { factory(moment); }(function (moment) { function plural(word, num) { var forms = word.split('_'); return num % 10 === 1 && num % 100 !== 11 ? forms[0] : (num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20) ? forms[1] : forms[2]); } function relativeTimeWithPlural(number, withoutSuffix, key) { var format = { 'mm': 'хвилина_хвилини_хвилин', 'hh': 'година_години_годин', 'dd': 'день_дні_днів', 'MM': 'місяць_місяці_місяців', 'yy': 'рік_роки_років' }; if (key === 'm') { return withoutSuffix ? 'хвилина' : 'хвилину'; } else if (key === 'h') { return withoutSuffix ? 'година' : 'годину'; } else { return number + ' ' + plural(format[key], +number); } } function monthsCaseReplace(m, format) { var months = { 'nominative': 'січень_лютий_березень_квітень_травень_червень_липень_серпень_вересень_жовтень_листопад_грудень'.split('_'), 'accusative': 'січня_лютого_березня_квітня_травня_червня_липня_серпня_вересня_жовтня_листопада_грудня'.split('_') }, nounCase = (/D[oD]? *MMMM?/).test(format) ? 'accusative' : 'nominative'; return months[nounCase][m.month()]; } function weekdaysCaseReplace(m, format) { var weekdays = { 'nominative': 'неділя_понеділок_вівторок_середа_четвер_п’ятниця_субота'.split('_'), 'accusative': 'неділю_понеділок_вівторок_середу_четвер_п’ятницю_суботу'.split('_'), 'genitive': 'неділі_понеділка_вівторка_середи_четверга_п’ятниці_суботи'.split('_') }, nounCase = (/(\[[ВвУу]\]) ?dddd/).test(format) ? 'accusative' : ((/\[?(?:минулої|наступної)? ?\] ?dddd/).test(format) ? 'genitive' : 'nominative'); return weekdays[nounCase][m.day()]; } function processHoursFunction(str) { return function () { return str + 'о' + (this.hours() === 11 ? 'б' : '') + '] LT'; }; } return moment.lang('uk', { months : monthsCaseReplace, monthsShort : "січ_лют_бер_квіт_трав_черв_лип_серп_вер_жовт_лист_груд".split("_"), weekdays : weekdaysCaseReplace, weekdaysShort : "нд_пн_вт_ср_чт_пт_сб".split("_"), weekdaysMin : "нд_пн_вт_ср_чт_пт_сб".split("_"), longDateFormat : { LT : "HH:mm", L : "DD.MM.YYYY", LL : "D MMMM YYYY р.", LLL : "D MMMM YYYY р., LT", LLLL : "dddd, D MMMM YYYY р., LT" }, calendar : { sameDay: processHoursFunction('[Сьогодні '), nextDay: processHoursFunction('[Завтра '), lastDay: processHoursFunction('[Вчора '), nextWeek: processHoursFunction('[У] dddd ['), lastWeek: function () { switch (this.day()) { case 0: case 3: case 5: case 6: return processHoursFunction('[Минулої] dddd [').call(this); case 1: case 2: case 4: return processHoursFunction('[Минулого] dddd [').call(this); } }, sameElse: 'L' }, relativeTime : { future : "за %s", past : "%s тому", s : "декілька секунд", m : relativeTimeWithPlural, mm : relativeTimeWithPlural, h : "годину", hh : relativeTimeWithPlural, d : "день", dd : relativeTimeWithPlural, M : "місяць", MM : relativeTimeWithPlural, y : "рік", yy : relativeTimeWithPlural }, // M. E.: those two are virtually unused but a user might want to implement them for his/her website for some reason meridiem : function (hour, minute, isLower) { if (hour < 4) { return "ночі"; } else if (hour < 12) { return "ранку"; } else if (hour < 17) { return "дня"; } else { return "вечора"; } }, ordinal: function (number, period) { switch (period) { case 'M': case 'd': case 'DDD': case 'w': case 'W': return number + '-й'; case 'D': return number + '-го'; default: return number; } }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); })); // moment.js language configuration // language : uzbek // author : Sardor Muminov : https://github.com/muminoff (function (factory) { factory(moment); }(function (moment) { return moment.lang('uz', { months : "январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь".split("_"), monthsShort : "янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек".split("_"), weekdays : "Якшанба_Душанба_Сешанба_Чоршанба_Пайшанба_Жума_Шанба".split("_"), weekdaysShort : "Якш_Душ_Сеш_Чор_Пай_Жум_Шан".split("_"), weekdaysMin : "Як_Ду_Се_Чо_Па_Жу_Ша".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "D MMMM YYYY, dddd LT" }, calendar : { sameDay : '[Бугун соат] LT [да]', nextDay : '[Эртага] LT [да]', nextWeek : 'dddd [куни соат] LT [да]', lastDay : '[Кеча соат] LT [да]', lastWeek : '[Утган] dddd [куни соат] LT [да]', sameElse : 'L' }, relativeTime : { future : "Якин %s ичида", past : "Бир неча %s олдин", s : "фурсат", m : "бир дакика", mm : "%d дакика", h : "бир соат", hh : "%d соат", d : "бир кун", dd : "%d кун", M : "бир ой", MM : "%d ой", y : "бир йил", yy : "%d йил" }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : vietnamese (vn) // author : Bang Nguyen : https://github.com/bangnk (function (factory) { factory(moment); }(function (moment) { return moment.lang('vn', { months : "tháng 1_tháng 2_tháng 3_tháng 4_tháng 5_tháng 6_tháng 7_tháng 8_tháng 9_tháng 10_tháng 11_tháng 12".split("_"), monthsShort : "Th01_Th02_Th03_Th04_Th05_Th06_Th07_Th08_Th09_Th10_Th11_Th12".split("_"), weekdays : "chủ nhật_thứ hai_thứ ba_thứ tư_thứ năm_thứ sáu_thứ bảy".split("_"), weekdaysShort : "CN_T2_T3_T4_T5_T6_T7".split("_"), weekdaysMin : "CN_T2_T3_T4_T5_T6_T7".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM [năm] YYYY", LLL : "D MMMM [năm] YYYY LT", LLLL : "dddd, D MMMM [năm] YYYY LT", l : "DD/M/YYYY", ll : "D MMM YYYY", lll : "D MMM YYYY LT", llll : "ddd, D MMM YYYY LT" }, calendar : { sameDay: "[Hôm nay lúc] LT", nextDay: '[Ngày mai lúc] LT', nextWeek: 'dddd [tuần tới lúc] LT', lastDay: '[Hôm qua lúc] LT', lastWeek: 'dddd [tuần rồi lúc] LT', sameElse: 'L' }, relativeTime : { future : "%s tới", past : "%s trước", s : "vài giây", m : "một phút", mm : "%d phút", h : "một giờ", hh : "%d giờ", d : "một ngày", dd : "%d ngày", M : "một tháng", MM : "%d tháng", y : "một năm", yy : "%d năm" }, ordinal : function (number) { return number; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : chinese // author : suupic : https://github.com/suupic // author : Zeno Zeng : https://github.com/zenozeng (function (factory) { factory(moment); }(function (moment) { return moment.lang('zh-cn', { months : "一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"), monthsShort : "1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"), weekdays : "星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"), weekdaysShort : "周日_周一_周二_周三_周四_周五_周六".split("_"), weekdaysMin : "日_一_二_三_四_五_六".split("_"), longDateFormat : { LT : "Ah点mm", L : "YYYY-MM-DD", LL : "YYYY年MMMD日", LLL : "YYYY年MMMD日LT", LLLL : "YYYY年MMMD日ddddLT", l : "YYYY-MM-DD", ll : "YYYY年MMMD日", lll : "YYYY年MMMD日LT", llll : "YYYY年MMMD日ddddLT" }, meridiem : function (hour, minute, isLower) { var hm = hour * 100 + minute; if (hm < 600) { return "凌晨"; } else if (hm < 900) { return "早上"; } else if (hm < 1130) { return "上午"; } else if (hm < 1230) { return "中午"; } else if (hm < 1800) { return "下午"; } else { return "晚上"; } }, calendar : { sameDay : function () { return this.minutes() === 0 ? "[今天]Ah[点整]" : "[今天]LT"; }, nextDay : function () { return this.minutes() === 0 ? "[明天]Ah[点整]" : "[明天]LT"; }, lastDay : function () { return this.minutes() === 0 ? "[昨天]Ah[点整]" : "[昨天]LT"; }, nextWeek : function () { var startOfWeek, prefix; startOfWeek = moment().startOf('week'); prefix = this.unix() - startOfWeek.unix() >= 7 * 24 * 3600 ? '[下]' : '[本]'; return this.minutes() === 0 ? prefix + "dddAh点整" : prefix + "dddAh点mm"; }, lastWeek : function () { var startOfWeek, prefix; startOfWeek = moment().startOf('week'); prefix = this.unix() < startOfWeek.unix() ? '[上]' : '[本]'; return this.minutes() === 0 ? prefix + "dddAh点整" : prefix + "dddAh点mm"; }, sameElse : 'LL' }, ordinal : function (number, period) { switch (period) { case "d": case "D": case "DDD": return number + "日"; case "M": return number + "月"; case "w": case "W": return number + "周"; default: return number; } }, relativeTime : { future : "%s内", past : "%s前", s : "几秒", m : "1分钟", mm : "%d分钟", h : "1小时", hh : "%d小时", d : "1天", dd : "%d天", M : "1个月", MM : "%d个月", y : "1年", yy : "%d年" }, week : { // GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效 dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); })); // moment.js language configuration // language : traditional chinese (zh-tw) // author : Ben : https://github.com/ben-lin (function (factory) { factory(moment); }(function (moment) { return moment.lang('zh-tw', { months : "一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"), monthsShort : "1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"), weekdays : "星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"), weekdaysShort : "週日_週一_週二_週三_週四_週五_週六".split("_"), weekdaysMin : "日_一_二_三_四_五_六".split("_"), longDateFormat : { LT : "Ah點mm", L : "YYYY年MMMD日", LL : "YYYY年MMMD日", LLL : "YYYY年MMMD日LT", LLLL : "YYYY年MMMD日ddddLT", l : "YYYY年MMMD日", ll : "YYYY年MMMD日", lll : "YYYY年MMMD日LT", llll : "YYYY年MMMD日ddddLT" }, meridiem : function (hour, minute, isLower) { var hm = hour * 100 + minute; if (hm < 900) { return "早上"; } else if (hm < 1130) { return "上午"; } else if (hm < 1230) { return "中午"; } else if (hm < 1800) { return "下午"; } else { return "晚上"; } }, calendar : { sameDay : '[今天]LT', nextDay : '[明天]LT', nextWeek : '[下]ddddLT', lastDay : '[昨天]LT', lastWeek : '[上]ddddLT', sameElse : 'L' }, ordinal : function (number, period) { switch (period) { case "d" : case "D" : case "DDD" : return number + "日"; case "M" : return number + "月"; case "w" : case "W" : return number + "週"; default : return number; } }, relativeTime : { future : "%s內", past : "%s前", s : "幾秒", m : "一分鐘", mm : "%d分鐘", h : "一小時", hh : "%d小時", d : "一天", dd : "%d天", M : "一個月", MM : "%d個月", y : "一年", yy : "%d年" } }); })); moment.lang('en'); /************************************ Exposing Moment ************************************/ function makeGlobal(deprecate) { var warned = false, local_moment = moment; /*global ender:false */ if (typeof ender !== 'undefined') { return; } // here, `this` means `window` in the browser, or `global` on the server // add `moment` as a global object via a string identifier, // for Closure Compiler "advanced" mode if (deprecate) { global.moment = function () { if (!warned && console && console.warn) { warned = true; console.warn( "Accessing Moment through the global scope is " + "deprecated, and will be removed in an upcoming " + "release."); } return local_moment.apply(null, arguments); }; extend(global.moment, local_moment); } else { global['moment'] = moment; } } // CommonJS module is defined if (hasModule) { module.exports = moment; makeGlobal(true); } else if (typeof define === "function" && define.amd) { define("moment", function (require, exports, module) { if (module.config && module.config() && module.config().noGlobal !== true) { // If user provided noGlobal, he is aware of global makeGlobal(module.config().noGlobal === undefined); } return moment; }); } else { makeGlobal(); } }).call(this);
JavaScript
/* Justified Gallery Version: 2.1 Author: Miro Mannino Author URI: http://miromannino.it Copyright 2012 Miro Mannino (miro.mannino@gmail.com) This file is part of Justified Gallery. This work is licensed under the Creative Commons Attribution 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by/3.0/ or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA. */ (function($){ $.fn.justifiedGallery = function(options){ //TODO fare impostazione 'rel' che sostituisce tutti i link con il rel specificato var settings = $.extend( { 'sizeRangeSuffixes' : {'lt100':'_t', 'lt240':'_m', 'lt320':'_n', 'lt500':'', 'lt640':'_z', 'lt1024':'_b'}, 'rowHeight' : 120, 'margins' : 1, 'justifyLastRow' : true, 'fixedHeight' : false, 'captions' : true, 'rel' : null, //rewrite the rel of each analyzed links 'target' : null, //rewrite the target of all links 'extension' : /\.[^.]+$/, 'refreshTime' : 500, 'onComplete' : null }, options); function getErrorHtml(message, classOfError){ return "<div class=\"jg-error " + classOfError + "\"style=\"\">" + message + "</div>"; } return this.each(function(index, cont){ $(cont).addClass("justifiedGallery"); var loaded = 0; var images = new Array($(cont).find("img").length); if(images.length == 0) return; $(cont).append("<div class=\"jg-loading\"><div class=\"jg-loading-img\"></div></div>"); $(cont).find("a").each(function(index, entry){ var imgEntry = $(entry).find("img"); images[index] = new Array(5); images[index]["src"] = (typeof $(imgEntry).data("safe-src") != 'undefined') ? $(imgEntry).data("safe-src") : $(imgEntry).attr("src"); images[index]["alt"] = $(imgEntry).attr("alt"); images[index]["href"] = $(entry).attr("href"); images[index]["title"] = $(entry).attr("title"); images[index]["rel"] = (settings.rel != null) ? settings.rel : $(entry).attr("rel"); images[index]["target"] = (settings.target != null) ? settings.target : $(entry).attr("target"); images[index]["extension"] = images[index]["src"].match(settings.extension)[0]; $(entry).remove(); //remove the image, we have its data var img = new Image(); $(img).load(function() { if(images[index]["height"] != settings.rowHeight) images[index]["width"] = Math.ceil(this.width / (this.height / settings.rowHeight)); else images[index]["width"] = this.width; images[index]["height"] = settings.rowHeight; var usedSizeRangeRegExp = new RegExp("(" + settings.sizeRangeSuffixes.lt100 + "|" + settings.sizeRangeSuffixes.lt240 + "|" + settings.sizeRangeSuffixes.lt320 + "|" + settings.sizeRangeSuffixes.lt500 + "|" + settings.sizeRangeSuffixes.lt640 + "|" + settings.sizeRangeSuffixes.lt1024 + ")$"); images[index]["src"] = images[index]["src"].replace(settings.extension, "").replace(usedSizeRangeRegExp, ""); if(++loaded == images.length) startProcess(cont, images, settings); }); $(img).error(function() { $(cont).prepend(getErrorHtml("The image can't be loaded: \"" + images[index]["src"] +"\"", "jg-usedPrefixImageNotFound")); images[index] = null; if(++loaded == images.length) startProcess(cont, images, settings); }); $(img).attr('src', images[index]["src"]); }); }); function startProcess(cont, images, settings){ //FadeOut the loading image and FadeIn the images after their loading $(cont).find(".jg-loading").fadeOut(500, function(){ $(this).remove(); //remove the loading image processesImages($, cont, images, 0, settings); if($.isFunction(settings.onComplete)) settings.onComplete.call(this, cont); }); } function buildImage(image, suffix, nw, nh, l, minRowHeight, settings){ var ris; ris = "<div class=\"jg-image\" style=\"left:" + l + "px\">"; ris += " <a href=\"" + image["href"] + "\" "; if (typeof image["rel"] != 'undefined') ris += "rel=\"" + image["rel"] + "\""; if (typeof image["target"] != 'undefined') ris += "target=\"" + image["target"] + "\""; ris += "title=\"" + image["title"] + "\">"; ris += " <img alt=\"" + image["alt"] + "\" src=\"" + image["src"] + suffix + image.extension + "\""; ris += "style=\"width: " + nw + "px; height: " + nh + "px;\">"; if(settings.captions) ris += " <div style=\"bottom:" + (nh - minRowHeight) + "px;\" class=\"jg-image-label\">" + image["alt"] + "</div>"; ris += " </a></div>"; return ris; } function buildContRow(row, images, extraW, settings){ var j, l = 0; var minRowHeight; for(var j = 0; j < row.length; j++){ row[j]["nh"] = Math.ceil(images[row[j]["indx"]]["height"] * ((images[row[j]["indx"]]["width"] + extraW) / images[row[j]["indx"]]["width"])); row[j]["nw"] = images[row[j]["indx"]]["width"] + extraW; row[j]["suffix"] = getSuffix(row[j]["nw"], row[j]["nh"], settings); row[j]["l"] = l; if(!settings.fixedHeight){ if(j == 0) minRowHeight = row[j]["nh"]; else if(minRowHeight > row[j]["nh"]) minRowHeight = row[j]["nh"]; } l += row[j]["nw"] + settings.margins; } if(settings.fixedHeight) minRowHeight = settings.rowHeight; var rowCont = ""; for(var j = 0; j < row.length; j++){ rowCont += buildImage(images[row[j]["indx"]], row[j]["suffix"], row[j]["nw"], row[j]["nh"], row[j]["l"], minRowHeight, settings); } return "<div class=\"jg-row\" style=\"height: " + minRowHeight + "px; margin-bottom:" + settings.margins + "px;\">" + rowCont + "</div>"; } function getSuffix(nw, nh, settings){ var n; if(nw > nh) n = nw; else n = nh; if(n <= 100){ return settings.sizeRangeSuffixes.lt100; //thumbnail (longest side:100) }else if(n <= 240){ return settings.sizeRangeSuffixes.lt240; //small (longest side:240) }else if(n <= 320){ return settings.sizeRangeSuffixes.lt320; //small (longest side:320) }else if(n <= 500){ return settings.sizeRangeSuffixes.lt500; //small (longest side:320) }else if(n <= 640){ return settings.sizeRangeSuffixes.lt640; //medium (longest side:640) }else{ return settings.sizeRangeSuffixes.lt1024; //large (longest side:1024) } } function processesImages($, cont, images, lastRowWidth, settings){ var row = new Array(); var row_i, i; var partialRowWidth = 0; var extraW; var rowWidth = $(cont).width(); for(i = 0, row_i = 0; i < images.length; i++){ if(images[i] == null) continue; if(partialRowWidth + images[i]["width"] + settings.margins <= rowWidth){ //we can add the image partialRowWidth += images[i]["width"] + settings.margins; row[row_i] = new Array(5); row[row_i]["indx"] = i; row_i++; }else{ //the row is full extraW = Math.ceil((rowWidth - partialRowWidth + 1) / row.length); $(cont).append(buildContRow(row, images, extraW, settings)); row = new Array(); row[0] = new Array(5); row[0]["indx"] = i; row_i = 1; partialRowWidth = images[i]["width"] + settings.margins; } } //last row---------------------- //now we have all the images index loaded in the row arra if(settings.justifyLastRow){ extraW = Math.ceil((rowWidth - partialRowWidth + 1) / row.length); }else{ extraW = 0; } $(cont).append(buildContRow(row, images, extraW, settings)); //--------------------------- //Captions--------------------- if(settings.captions){ $(cont).find(".jg-image").mouseenter(function(sender){ $(sender.currentTarget).find(".jg-image-label").stop(); $(sender.currentTarget).find(".jg-image-label").fadeTo(500, 0.7); }); $(cont).find(".jg-image").mouseleave(function(sender){ $(sender.currentTarget).find(".jg-image-label").stop(); $(sender.currentTarget).find(".jg-image-label").fadeTo(500, 0); }); } $(cont).find(".jg-resizedImageNotFound").remove(); //fade in the images that we have changed and need to be reloaded $(cont).find(".jg-image img").load(function(){ $(this).fadeTo(500, 1); }).error(function(){ $(cont).prepend(getErrorHtml("The image can't be loaded: \"" + $(this).attr("src") +"\"", "jg-resizedImageNotFound")); }).each(function(){ if(this.complete) $(this).load(); }); checkWidth($, cont, images, rowWidth, settings); } function checkWidth($, cont, images, lastRowWidth, settings){ var id = setInterval(function(){ if(lastRowWidth != $(cont).width()){ $(cont).find(".jg-row").remove(); clearInterval(id); processesImages($, cont, images, lastRowWidth, settings); return; } }, settings.refreshTime); } } })(jQuery);
JavaScript
/** * * jquery.sparkline.js * * v2.1.2 * (c) Splunk, Inc * Contact: Gareth Watts (gareth@splunk.com) * http://omnipotent.net/jquery.sparkline/ * * Generates inline sparkline charts from data supplied either to the method * or inline in HTML * * Compatible with Internet Explorer 6.0+ and modern browsers equipped with the canvas tag * (Firefox 2.0+, Safari, Opera, etc) * * License: New BSD License * * Copyright (c) 2012, Splunk Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Splunk Inc nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * Usage: * $(selector).sparkline(values, options) * * If values is undefined or set to 'html' then the data values are read from the specified tag: * <p>Sparkline: <span class="sparkline">1,4,6,6,8,5,3,5</span></p> * $('.sparkline').sparkline(); * There must be no spaces in the enclosed data set * * Otherwise values must be an array of numbers or null values * <p>Sparkline: <span id="sparkline1">This text replaced if the browser is compatible</span></p> * $('#sparkline1').sparkline([1,4,6,6,8,5,3,5]) * $('#sparkline2').sparkline([1,4,6,null,null,5,3,5]) * * Values can also be specified in an HTML comment, or as a values attribute: * <p>Sparkline: <span class="sparkline"><!--1,4,6,6,8,5,3,5 --></span></p> * <p>Sparkline: <span class="sparkline" values="1,4,6,6,8,5,3,5"></span></p> * $('.sparkline').sparkline(); * * For line charts, x values can also be specified: * <p>Sparkline: <span class="sparkline">1:1,2.7:4,3.4:6,5:6,6:8,8.7:5,9:3,10:5</span></p> * $('#sparkline1').sparkline([ [1,1], [2.7,4], [3.4,6], [5,6], [6,8], [8.7,5], [9,3], [10,5] ]) * * By default, options should be passed in as teh second argument to the sparkline function: * $('.sparkline').sparkline([1,2,3,4], {type: 'bar'}) * * Options can also be set by passing them on the tag itself. This feature is disabled by default though * as there's a slight performance overhead: * $('.sparkline').sparkline([1,2,3,4], {enableTagOptions: true}) * <p>Sparkline: <span class="sparkline" sparkType="bar" sparkBarColor="red">loading</span></p> * Prefix all options supplied as tag attribute with "spark" (configurable by setting tagOptionPrefix) * * Supported options: * lineColor - Color of the line used for the chart * fillColor - Color used to fill in the chart - Set to '' or false for a transparent chart * width - Width of the chart - Defaults to 3 times the number of values in pixels * height - Height of the chart - Defaults to the height of the containing element * chartRangeMin - Specify the minimum value to use for the Y range of the chart - Defaults to the minimum value supplied * chartRangeMax - Specify the maximum value to use for the Y range of the chart - Defaults to the maximum value supplied * chartRangeClip - Clip out of range values to the max/min specified by chartRangeMin and chartRangeMax * chartRangeMinX - Specify the minimum value to use for the X range of the chart - Defaults to the minimum value supplied * chartRangeMaxX - Specify the maximum value to use for the X range of the chart - Defaults to the maximum value supplied * composite - If true then don't erase any existing chart attached to the tag, but draw * another chart over the top - Note that width and height are ignored if an * existing chart is detected. * tagValuesAttribute - Name of tag attribute to check for data values - Defaults to 'values' * enableTagOptions - Whether to check tags for sparkline options * tagOptionPrefix - Prefix used for options supplied as tag attributes - Defaults to 'spark' * disableHiddenCheck - If set to true, then the plugin will assume that charts will never be drawn into a * hidden dom element, avoding a browser reflow * disableInteraction - If set to true then all mouseover/click interaction behaviour will be disabled, * making the plugin perform much like it did in 1.x * disableTooltips - If set to true then tooltips will be disabled - Defaults to false (tooltips enabled) * disableHighlight - If set to true then highlighting of selected chart elements on mouseover will be disabled * defaults to false (highlights enabled) * highlightLighten - Factor to lighten/darken highlighted chart values by - Defaults to 1.4 for a 40% increase * tooltipContainer - Specify which DOM element the tooltip should be rendered into - defaults to document.body * tooltipClassname - Optional CSS classname to apply to tooltips - If not specified then a default style will be applied * tooltipOffsetX - How many pixels away from the mouse pointer to render the tooltip on the X axis * tooltipOffsetY - How many pixels away from the mouse pointer to render the tooltip on the r axis * tooltipFormatter - Optional callback that allows you to override the HTML displayed in the tooltip * callback is given arguments of (sparkline, options, fields) * tooltipChartTitle - If specified then the tooltip uses the string specified by this setting as a title * tooltipFormat - A format string or SPFormat object (or an array thereof for multiple entries) * to control the format of the tooltip * tooltipPrefix - A string to prepend to each field displayed in a tooltip * tooltipSuffix - A string to append to each field displayed in a tooltip * tooltipSkipNull - If true then null values will not have a tooltip displayed (defaults to true) * tooltipValueLookups - An object or range map to map field values to tooltip strings * (eg. to map -1 to "Lost", 0 to "Draw", and 1 to "Win") * numberFormatter - Optional callback for formatting numbers in tooltips * numberDigitGroupSep - Character to use for group separator in numbers "1,234" - Defaults to "," * numberDecimalMark - Character to use for the decimal point when formatting numbers - Defaults to "." * numberDigitGroupCount - Number of digits between group separator - Defaults to 3 * * There are 7 types of sparkline, selected by supplying a "type" option of 'line' (default), * 'bar', 'tristate', 'bullet', 'discrete', 'pie' or 'box' * line - Line chart. Options: * spotColor - Set to '' to not end each line in a circular spot * minSpotColor - If set, color of spot at minimum value * maxSpotColor - If set, color of spot at maximum value * spotRadius - Radius in pixels * lineWidth - Width of line in pixels * normalRangeMin * normalRangeMax - If set draws a filled horizontal bar between these two values marking the "normal" * or expected range of values * normalRangeColor - Color to use for the above bar * drawNormalOnTop - Draw the normal range above the chart fill color if true * defaultPixelsPerValue - Defaults to 3 pixels of width for each value in the chart * highlightSpotColor - The color to use for drawing a highlight spot on mouseover - Set to null to disable * highlightLineColor - The color to use for drawing a highlight line on mouseover - Set to null to disable * valueSpots - Specify which points to draw spots on, and in which color. Accepts a range map * * bar - Bar chart. Options: * barColor - Color of bars for postive values * negBarColor - Color of bars for negative values * zeroColor - Color of bars with zero values * nullColor - Color of bars with null values - Defaults to omitting the bar entirely * barWidth - Width of bars in pixels * colorMap - Optional mappnig of values to colors to override the *BarColor values above * can be an Array of values to control the color of individual bars or a range map * to specify colors for individual ranges of values * barSpacing - Gap between bars in pixels * zeroAxis - Centers the y-axis around zero if true * * tristate - Charts values of win (>0), lose (<0) or draw (=0) * posBarColor - Color of win values * negBarColor - Color of lose values * zeroBarColor - Color of draw values * barWidth - Width of bars in pixels * barSpacing - Gap between bars in pixels * colorMap - Optional mappnig of values to colors to override the *BarColor values above * can be an Array of values to control the color of individual bars or a range map * to specify colors for individual ranges of values * * discrete - Options: * lineHeight - Height of each line in pixels - Defaults to 30% of the graph height * thesholdValue - Values less than this value will be drawn using thresholdColor instead of lineColor * thresholdColor * * bullet - Values for bullet graphs msut be in the order: target, performance, range1, range2, range3, ... * options: * targetColor - The color of the vertical target marker * targetWidth - The width of the target marker in pixels * performanceColor - The color of the performance measure horizontal bar * rangeColors - Colors to use for each qualitative range background color * * pie - Pie chart. Options: * sliceColors - An array of colors to use for pie slices * offset - Angle in degrees to offset the first slice - Try -90 or +90 * borderWidth - Width of border to draw around the pie chart, in pixels - Defaults to 0 (no border) * borderColor - Color to use for the pie chart border - Defaults to #000 * * box - Box plot. Options: * raw - Set to true to supply pre-computed plot points as values * values should be: low_outlier, low_whisker, q1, median, q3, high_whisker, high_outlier * When set to false you can supply any number of values and the box plot will * be computed for you. Default is false. * showOutliers - Set to true (default) to display outliers as circles * outlierIQR - Interquartile range used to determine outliers. Default 1.5 * boxLineColor - Outline color of the box * boxFillColor - Fill color for the box * whiskerColor - Line color used for whiskers * outlierLineColor - Outline color of outlier circles * outlierFillColor - Fill color of the outlier circles * spotRadius - Radius of outlier circles * medianColor - Line color of the median line * target - Draw a target cross hair at the supplied value (default undefined) * * * * Examples: * $('#sparkline1').sparkline(myvalues, { lineColor: '#f00', fillColor: false }); * $('.barsparks').sparkline('html', { type:'bar', height:'40px', barWidth:5 }); * $('#tristate').sparkline([1,1,-1,1,0,0,-1], { type:'tristate' }): * $('#discrete').sparkline([1,3,4,5,5,3,4,5], { type:'discrete' }); * $('#bullet').sparkline([10,12,12,9,7], { type:'bullet' }); * $('#pie').sparkline([1,1,2], { type:'pie' }); */ /*jslint regexp: true, browser: true, jquery: true, white: true, nomen: false, plusplus: false, maxerr: 500, indent: 4 */ (function(document, Math, undefined) { // performance/minified-size optimization (function(factory) { if(typeof define === 'function' && define.amd) { define(['jquery'], factory); } else if (jQuery && !jQuery.fn.sparkline) { factory(jQuery); } } (function($) { 'use strict'; var UNSET_OPTION = {}, getDefaults, createClass, SPFormat, clipval, quartile, normalizeValue, normalizeValues, remove, isNumber, all, sum, addCSS, ensureArray, formatNumber, RangeMap, MouseHandler, Tooltip, barHighlightMixin, line, bar, tristate, discrete, bullet, pie, box, defaultStyles, initStyles, VShape, VCanvas_base, VCanvas_canvas, VCanvas_vml, pending, shapeCount = 0; /** * Default configuration settings */ getDefaults = function () { return { // Settings common to most/all chart types common: { type: 'line', lineColor: '#00f', fillColor: '#cdf', defaultPixelsPerValue: 3, width: 'auto', height: 'auto', composite: false, tagValuesAttribute: 'values', tagOptionsPrefix: 'spark', enableTagOptions: false, enableHighlight: true, highlightLighten: 1.4, tooltipSkipNull: true, tooltipPrefix: '', tooltipSuffix: '', disableHiddenCheck: false, numberFormatter: false, numberDigitGroupCount: 3, numberDigitGroupSep: ',', numberDecimalMark: '.', disableTooltips: false, disableInteraction: false }, // Defaults for line charts line: { spotColor: '#f80', highlightSpotColor: '#5f5', highlightLineColor: '#f22', spotRadius: 1.5, minSpotColor: '#f80', maxSpotColor: '#f80', lineWidth: 1, normalRangeMin: undefined, normalRangeMax: undefined, normalRangeColor: '#ccc', drawNormalOnTop: false, chartRangeMin: undefined, chartRangeMax: undefined, chartRangeMinX: undefined, chartRangeMaxX: undefined, tooltipFormat: new SPFormat('<span style="color: {{color}}">&#9679;</span> {{prefix}}{{y}}{{suffix}}') }, // Defaults for bar charts bar: { barColor: '#3366cc', negBarColor: '#f44', stackedBarColor: ['#3366cc', '#dc3912', '#ff9900', '#109618', '#66aa00', '#dd4477', '#0099c6', '#990099'], zeroColor: undefined, nullColor: undefined, zeroAxis: true, barWidth: 4, barSpacing: 1, chartRangeMax: undefined, chartRangeMin: undefined, chartRangeClip: false, colorMap: undefined, tooltipFormat: new SPFormat('<span style="color: {{color}}">&#9679;</span> {{prefix}}{{value}}{{suffix}}') }, // Defaults for tristate charts tristate: { barWidth: 4, barSpacing: 1, posBarColor: '#6f6', negBarColor: '#f44', zeroBarColor: '#999', colorMap: {}, tooltipFormat: new SPFormat('<span style="color: {{color}}">&#9679;</span> {{value:map}}'), tooltipValueLookups: { map: { '-1': 'Loss', '0': 'Draw', '1': 'Win' } } }, // Defaults for discrete charts discrete: { lineHeight: 'auto', thresholdColor: undefined, thresholdValue: 0, chartRangeMax: undefined, chartRangeMin: undefined, chartRangeClip: false, tooltipFormat: new SPFormat('{{prefix}}{{value}}{{suffix}}') }, // Defaults for bullet charts bullet: { targetColor: '#f33', targetWidth: 3, // width of the target bar in pixels performanceColor: '#33f', rangeColors: ['#d3dafe', '#a8b6ff', '#7f94ff'], base: undefined, // set this to a number to change the base start number tooltipFormat: new SPFormat('{{fieldkey:fields}} - {{value}}'), tooltipValueLookups: { fields: {r: 'Range', p: 'Performance', t: 'Target'} } }, // Defaults for pie charts pie: { offset: 0, sliceColors: ['#3366cc', '#dc3912', '#ff9900', '#109618', '#66aa00', '#dd4477', '#0099c6', '#990099'], borderWidth: 0, borderColor: '#000', tooltipFormat: new SPFormat('<span style="color: {{color}}">&#9679;</span> {{value}} ({{percent.1}}%)') }, // Defaults for box plots box: { raw: false, boxLineColor: '#000', boxFillColor: '#cdf', whiskerColor: '#000', outlierLineColor: '#333', outlierFillColor: '#fff', medianColor: '#f00', showOutliers: true, outlierIQR: 1.5, spotRadius: 1.5, target: undefined, targetColor: '#4a2', chartRangeMax: undefined, chartRangeMin: undefined, tooltipFormat: new SPFormat('{{field:fields}}: {{value}}'), tooltipFormatFieldlistKey: 'field', tooltipValueLookups: { fields: { lq: 'Lower Quartile', med: 'Median', uq: 'Upper Quartile', lo: 'Left Outlier', ro: 'Right Outlier', lw: 'Left Whisker', rw: 'Right Whisker'} } } }; }; // You can have tooltips use a css class other than jqstooltip by specifying tooltipClassname defaultStyles = '.jqstooltip { ' + 'position: absolute;' + 'left: 0px;' + 'top: 0px;' + 'visibility: hidden;' + 'background: rgb(0, 0, 0) transparent;' + 'background-color: rgba(0,0,0,0.6);' + 'filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);' + '-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";' + 'color: white;' + 'font: 10px arial, san serif;' + 'text-align: left;' + 'white-space: nowrap;' + 'padding: 5px;' + 'border: 1px solid white;' + 'z-index: 10000;' + '}' + '.jqsfield { ' + 'color: white;' + 'font: 10px arial, san serif;' + 'text-align: left;' + '}'; /** * Utilities */ createClass = function (/* [baseclass, [mixin, ...]], definition */) { var Class, args; Class = function () { this.init.apply(this, arguments); }; if (arguments.length > 1) { if (arguments[0]) { Class.prototype = $.extend(new arguments[0](), arguments[arguments.length - 1]); Class._super = arguments[0].prototype; } else { Class.prototype = arguments[arguments.length - 1]; } if (arguments.length > 2) { args = Array.prototype.slice.call(arguments, 1, -1); args.unshift(Class.prototype); $.extend.apply($, args); } } else { Class.prototype = arguments[0]; } Class.prototype.cls = Class; return Class; }; /** * Wraps a format string for tooltips * {{x}} * {{x.2} * {{x:months}} */ $.SPFormatClass = SPFormat = createClass({ fre: /\{\{([\w.]+?)(:(.+?))?\}\}/g, precre: /(\w+)\.(\d+)/, init: function (format, fclass) { this.format = format; this.fclass = fclass; }, render: function (fieldset, lookups, options) { var self = this, fields = fieldset, match, token, lookupkey, fieldvalue, prec; return this.format.replace(this.fre, function () { var lookup; token = arguments[1]; lookupkey = arguments[3]; match = self.precre.exec(token); if (match) { prec = match[2]; token = match[1]; } else { prec = false; } fieldvalue = fields[token]; if (fieldvalue === undefined) { return ''; } if (lookupkey && lookups && lookups[lookupkey]) { lookup = lookups[lookupkey]; if (lookup.get) { // RangeMap return lookups[lookupkey].get(fieldvalue) || fieldvalue; } else { return lookups[lookupkey][fieldvalue] || fieldvalue; } } if (isNumber(fieldvalue)) { if (options.get('numberFormatter')) { fieldvalue = options.get('numberFormatter')(fieldvalue); } else { fieldvalue = formatNumber(fieldvalue, prec, options.get('numberDigitGroupCount'), options.get('numberDigitGroupSep'), options.get('numberDecimalMark')); } } return fieldvalue; }); } }); // convience method to avoid needing the new operator $.spformat = function(format, fclass) { return new SPFormat(format, fclass); }; clipval = function (val, min, max) { if (val < min) { return min; } if (val > max) { return max; } return val; }; quartile = function (values, q) { var vl; if (q === 2) { vl = Math.floor(values.length / 2); return values.length % 2 ? values[vl] : (values[vl-1] + values[vl]) / 2; } else { if (values.length % 2 ) { // odd vl = (values.length * q + q) / 4; return vl % 1 ? (values[Math.floor(vl)] + values[Math.floor(vl) - 1]) / 2 : values[vl-1]; } else { //even vl = (values.length * q + 2) / 4; return vl % 1 ? (values[Math.floor(vl)] + values[Math.floor(vl) - 1]) / 2 : values[vl-1]; } } }; normalizeValue = function (val) { var nf; switch (val) { case 'undefined': val = undefined; break; case 'null': val = null; break; case 'true': val = true; break; case 'false': val = false; break; default: nf = parseFloat(val); if (val == nf) { val = nf; } } return val; }; normalizeValues = function (vals) { var i, result = []; for (i = vals.length; i--;) { result[i] = normalizeValue(vals[i]); } return result; }; remove = function (vals, filter) { var i, vl, result = []; for (i = 0, vl = vals.length; i < vl; i++) { if (vals[i] !== filter) { result.push(vals[i]); } } return result; }; isNumber = function (num) { return !isNaN(parseFloat(num)) && isFinite(num); }; formatNumber = function (num, prec, groupsize, groupsep, decsep) { var p, i; num = (prec === false ? parseFloat(num).toString() : num.toFixed(prec)).split(''); p = (p = $.inArray('.', num)) < 0 ? num.length : p; if (p < num.length) { num[p] = decsep; } for (i = p - groupsize; i > 0; i -= groupsize) { num.splice(i, 0, groupsep); } return num.join(''); }; // determine if all values of an array match a value // returns true if the array is empty all = function (val, arr, ignoreNull) { var i; for (i = arr.length; i--; ) { if (ignoreNull && arr[i] === null) continue; if (arr[i] !== val) { return false; } } return true; }; // sums the numeric values in an array, ignoring other values sum = function (vals) { var total = 0, i; for (i = vals.length; i--;) { total += typeof vals[i] === 'number' ? vals[i] : 0; } return total; }; ensureArray = function (val) { return $.isArray(val) ? val : [val]; }; // http://paulirish.com/2008/bookmarklet-inject-new-css-rules/ addCSS = function(css) { var tag; //if ('\v' == 'v') /* ie only */ { if (document.createStyleSheet) { document.createStyleSheet().cssText = css; } else { tag = document.createElement('style'); tag.type = 'text/css'; document.getElementsByTagName('head')[0].appendChild(tag); tag[(typeof document.body.style.WebkitAppearance == 'string') /* webkit only */ ? 'innerText' : 'innerHTML'] = css; } }; // Provide a cross-browser interface to a few simple drawing primitives $.fn.simpledraw = function (width, height, useExisting, interact) { var target, mhandler; if (useExisting && (target = this.data('_jqs_vcanvas'))) { return target; } if ($.fn.sparkline.canvas === false) { // We've already determined that neither Canvas nor VML are available return false; } else if ($.fn.sparkline.canvas === undefined) { // No function defined yet -- need to see if we support Canvas or VML var el = document.createElement('canvas'); if (!!(el.getContext && el.getContext('2d'))) { // Canvas is available $.fn.sparkline.canvas = function(width, height, target, interact) { return new VCanvas_canvas(width, height, target, interact); }; } else if (document.namespaces && !document.namespaces.v) { // VML is available document.namespaces.add('v', 'urn:schemas-microsoft-com:vml', '#default#VML'); $.fn.sparkline.canvas = function(width, height, target, interact) { return new VCanvas_vml(width, height, target); }; } else { // Neither Canvas nor VML are available $.fn.sparkline.canvas = false; return false; } } if (width === undefined) { width = $(this).innerWidth(); } if (height === undefined) { height = $(this).innerHeight(); } target = $.fn.sparkline.canvas(width, height, this, interact); mhandler = $(this).data('_jqs_mhandler'); if (mhandler) { mhandler.registerCanvas(target); } return target; }; $.fn.cleardraw = function () { var target = this.data('_jqs_vcanvas'); if (target) { target.reset(); } }; $.RangeMapClass = RangeMap = createClass({ init: function (map) { var key, range, rangelist = []; for (key in map) { if (map.hasOwnProperty(key) && typeof key === 'string' && key.indexOf(':') > -1) { range = key.split(':'); range[0] = range[0].length === 0 ? -Infinity : parseFloat(range[0]); range[1] = range[1].length === 0 ? Infinity : parseFloat(range[1]); range[2] = map[key]; rangelist.push(range); } } this.map = map; this.rangelist = rangelist || false; }, get: function (value) { var rangelist = this.rangelist, i, range, result; if ((result = this.map[value]) !== undefined) { return result; } if (rangelist) { for (i = rangelist.length; i--;) { range = rangelist[i]; if (range[0] <= value && range[1] >= value) { return range[2]; } } } return undefined; } }); // Convenience function $.range_map = function(map) { return new RangeMap(map); }; MouseHandler = createClass({ init: function (el, options) { var $el = $(el); this.$el = $el; this.options = options; this.currentPageX = 0; this.currentPageY = 0; this.el = el; this.splist = []; this.tooltip = null; this.over = false; this.displayTooltips = !options.get('disableTooltips'); this.highlightEnabled = !options.get('disableHighlight'); }, registerSparkline: function (sp) { this.splist.push(sp); if (this.over) { this.updateDisplay(); } }, registerCanvas: function (canvas) { var $canvas = $(canvas.canvas); this.canvas = canvas; this.$canvas = $canvas; $canvas.mouseenter($.proxy(this.mouseenter, this)); $canvas.mouseleave($.proxy(this.mouseleave, this)); $canvas.click($.proxy(this.mouseclick, this)); }, reset: function (removeTooltip) { this.splist = []; if (this.tooltip && removeTooltip) { this.tooltip.remove(); this.tooltip = undefined; } }, mouseclick: function (e) { var clickEvent = $.Event('sparklineClick'); clickEvent.originalEvent = e; clickEvent.sparklines = this.splist; this.$el.trigger(clickEvent); }, mouseenter: function (e) { $(document.body).unbind('mousemove.jqs'); $(document.body).bind('mousemove.jqs', $.proxy(this.mousemove, this)); this.over = true; this.currentPageX = e.pageX; this.currentPageY = e.pageY; this.currentEl = e.target; if (!this.tooltip && this.displayTooltips) { this.tooltip = new Tooltip(this.options); this.tooltip.updatePosition(e.pageX, e.pageY); } this.updateDisplay(); }, mouseleave: function () { $(document.body).unbind('mousemove.jqs'); var splist = this.splist, spcount = splist.length, needsRefresh = false, sp, i; this.over = false; this.currentEl = null; if (this.tooltip) { this.tooltip.remove(); this.tooltip = null; } for (i = 0; i < spcount; i++) { sp = splist[i]; if (sp.clearRegionHighlight()) { needsRefresh = true; } } if (needsRefresh) { this.canvas.render(); } }, mousemove: function (e) { this.currentPageX = e.pageX; this.currentPageY = e.pageY; this.currentEl = e.target; if (this.tooltip) { this.tooltip.updatePosition(e.pageX, e.pageY); } this.updateDisplay(); }, updateDisplay: function () { var splist = this.splist, spcount = splist.length, needsRefresh = false, offset = this.$canvas.offset(), localX = this.currentPageX - offset.left, localY = this.currentPageY - offset.top, tooltiphtml, sp, i, result, changeEvent; if (!this.over) { return; } for (i = 0; i < spcount; i++) { sp = splist[i]; result = sp.setRegionHighlight(this.currentEl, localX, localY); if (result) { needsRefresh = true; } } if (needsRefresh) { changeEvent = $.Event('sparklineRegionChange'); changeEvent.sparklines = this.splist; this.$el.trigger(changeEvent); if (this.tooltip) { tooltiphtml = ''; for (i = 0; i < spcount; i++) { sp = splist[i]; tooltiphtml += sp.getCurrentRegionTooltip(); } this.tooltip.setContent(tooltiphtml); } if (!this.disableHighlight) { this.canvas.render(); } } if (result === null) { this.mouseleave(); } } }); Tooltip = createClass({ sizeStyle: 'position: static !important;' + 'display: block !important;' + 'visibility: hidden !important;' + 'float: left !important;', init: function (options) { var tooltipClassname = options.get('tooltipClassname', 'jqstooltip'), sizetipStyle = this.sizeStyle, offset; this.container = options.get('tooltipContainer') || document.body; this.tooltipOffsetX = options.get('tooltipOffsetX', 10); this.tooltipOffsetY = options.get('tooltipOffsetY', 12); // remove any previous lingering tooltip $('#jqssizetip').remove(); $('#jqstooltip').remove(); this.sizetip = $('<div/>', { id: 'jqssizetip', style: sizetipStyle, 'class': tooltipClassname }); this.tooltip = $('<div/>', { id: 'jqstooltip', 'class': tooltipClassname }).appendTo(this.container); // account for the container's location offset = this.tooltip.offset(); this.offsetLeft = offset.left; this.offsetTop = offset.top; this.hidden = true; $(window).unbind('resize.jqs scroll.jqs'); $(window).bind('resize.jqs scroll.jqs', $.proxy(this.updateWindowDims, this)); this.updateWindowDims(); }, updateWindowDims: function () { this.scrollTop = $(window).scrollTop(); this.scrollLeft = $(window).scrollLeft(); this.scrollRight = this.scrollLeft + $(window).width(); this.updatePosition(); }, getSize: function (content) { this.sizetip.html(content).appendTo(this.container); this.width = this.sizetip.width() + 1; this.height = this.sizetip.height(); this.sizetip.remove(); }, setContent: function (content) { if (!content) { this.tooltip.css('visibility', 'hidden'); this.hidden = true; return; } this.getSize(content); this.tooltip.html(content) .css({ 'width': this.width, 'height': this.height, 'visibility': 'visible' }); if (this.hidden) { this.hidden = false; this.updatePosition(); } }, updatePosition: function (x, y) { if (x === undefined) { if (this.mousex === undefined) { return; } x = this.mousex - this.offsetLeft; y = this.mousey - this.offsetTop; } else { this.mousex = x = x - this.offsetLeft; this.mousey = y = y - this.offsetTop; } if (!this.height || !this.width || this.hidden) { return; } y -= this.height + this.tooltipOffsetY; x += this.tooltipOffsetX; if (y < this.scrollTop) { y = this.scrollTop; } if (x < this.scrollLeft) { x = this.scrollLeft; } else if (x + this.width > this.scrollRight) { x = this.scrollRight - this.width; } this.tooltip.css({ 'left': x, 'top': y }); }, remove: function () { this.tooltip.remove(); this.sizetip.remove(); this.sizetip = this.tooltip = undefined; $(window).unbind('resize.jqs scroll.jqs'); } }); initStyles = function() { addCSS(defaultStyles); }; $(initStyles); pending = []; $.fn.sparkline = function (userValues, userOptions) { return this.each(function () { var options = new $.fn.sparkline.options(this, userOptions), $this = $(this), render, i; render = function () { var values, width, height, tmp, mhandler, sp, vals; if (userValues === 'html' || userValues === undefined) { vals = this.getAttribute(options.get('tagValuesAttribute')); if (vals === undefined || vals === null) { vals = $this.html(); } values = vals.replace(/(^\s*<!--)|(-->\s*$)|\s+/g, '').split(','); } else { values = userValues; } width = options.get('width') === 'auto' ? values.length * options.get('defaultPixelsPerValue') : options.get('width'); if (options.get('height') === 'auto') { if (!options.get('composite') || !$.data(this, '_jqs_vcanvas')) { // must be a better way to get the line height tmp = document.createElement('span'); tmp.innerHTML = 'a'; $this.html(tmp); height = $(tmp).innerHeight() || $(tmp).height(); $(tmp).remove(); tmp = null; } } else { height = options.get('height'); } if (!options.get('disableInteraction')) { mhandler = $.data(this, '_jqs_mhandler'); if (!mhandler) { mhandler = new MouseHandler(this, options); $.data(this, '_jqs_mhandler', mhandler); } else if (!options.get('composite')) { mhandler.reset(); } } else { mhandler = false; } if (options.get('composite') && !$.data(this, '_jqs_vcanvas')) { if (!$.data(this, '_jqs_errnotify')) { alert('Attempted to attach a composite sparkline to an element with no existing sparkline'); $.data(this, '_jqs_errnotify', true); } return; } sp = new $.fn.sparkline[options.get('type')](this, values, options, width, height); sp.render(); if (mhandler) { mhandler.registerSparkline(sp); } }; if (($(this).html() && !options.get('disableHiddenCheck') && $(this).is(':hidden')) || !$(this).parents('body').length) { if (!options.get('composite') && $.data(this, '_jqs_pending')) { // remove any existing references to the element for (i = pending.length; i; i--) { if (pending[i - 1][0] == this) { pending.splice(i - 1, 1); } } } pending.push([this, render]); $.data(this, '_jqs_pending', true); } else { render.call(this); } }); }; $.fn.sparkline.defaults = getDefaults(); $.sparkline_display_visible = function () { var el, i, pl; var done = []; for (i = 0, pl = pending.length; i < pl; i++) { el = pending[i][0]; if ($(el).is(':visible') && !$(el).parents().is(':hidden')) { pending[i][1].call(el); $.data(pending[i][0], '_jqs_pending', false); done.push(i); } else if (!$(el).closest('html').length && !$.data(el, '_jqs_pending')) { // element has been inserted and removed from the DOM // If it was not yet inserted into the dom then the .data request // will return true. // removing from the dom causes the data to be removed. $.data(pending[i][0], '_jqs_pending', false); done.push(i); } } for (i = done.length; i; i--) { pending.splice(done[i - 1], 1); } }; /** * User option handler */ $.fn.sparkline.options = createClass({ init: function (tag, userOptions) { var extendedOptions, defaults, base, tagOptionType; this.userOptions = userOptions = userOptions || {}; this.tag = tag; this.tagValCache = {}; defaults = $.fn.sparkline.defaults; base = defaults.common; this.tagOptionsPrefix = userOptions.enableTagOptions && (userOptions.tagOptionsPrefix || base.tagOptionsPrefix); tagOptionType = this.getTagSetting('type'); if (tagOptionType === UNSET_OPTION) { extendedOptions = defaults[userOptions.type || base.type]; } else { extendedOptions = defaults[tagOptionType]; } this.mergedOptions = $.extend({}, base, extendedOptions, userOptions); }, getTagSetting: function (key) { var prefix = this.tagOptionsPrefix, val, i, pairs, keyval; if (prefix === false || prefix === undefined) { return UNSET_OPTION; } if (this.tagValCache.hasOwnProperty(key)) { val = this.tagValCache.key; } else { val = this.tag.getAttribute(prefix + key); if (val === undefined || val === null) { val = UNSET_OPTION; } else if (val.substr(0, 1) === '[') { val = val.substr(1, val.length - 2).split(','); for (i = val.length; i--;) { val[i] = normalizeValue(val[i].replace(/(^\s*)|(\s*$)/g, '')); } } else if (val.substr(0, 1) === '{') { pairs = val.substr(1, val.length - 2).split(','); val = {}; for (i = pairs.length; i--;) { keyval = pairs[i].split(':', 2); val[keyval[0].replace(/(^\s*)|(\s*$)/g, '')] = normalizeValue(keyval[1].replace(/(^\s*)|(\s*$)/g, '')); } } else { val = normalizeValue(val); } this.tagValCache.key = val; } return val; }, get: function (key, defaultval) { var tagOption = this.getTagSetting(key), result; if (tagOption !== UNSET_OPTION) { return tagOption; } return (result = this.mergedOptions[key]) === undefined ? defaultval : result; } }); $.fn.sparkline._base = createClass({ disabled: false, init: function (el, values, options, width, height) { this.el = el; this.$el = $(el); this.values = values; this.options = options; this.width = width; this.height = height; this.currentRegion = undefined; }, /** * Setup the canvas */ initTarget: function () { var interactive = !this.options.get('disableInteraction'); if (!(this.target = this.$el.simpledraw(this.width, this.height, this.options.get('composite'), interactive))) { this.disabled = true; } else { this.canvasWidth = this.target.pixelWidth; this.canvasHeight = this.target.pixelHeight; } }, /** * Actually render the chart to the canvas */ render: function () { if (this.disabled) { this.el.innerHTML = ''; return false; } return true; }, /** * Return a region id for a given x/y co-ordinate */ getRegion: function (x, y) { }, /** * Highlight an item based on the moused-over x,y co-ordinate */ setRegionHighlight: function (el, x, y) { var currentRegion = this.currentRegion, highlightEnabled = !this.options.get('disableHighlight'), newRegion; if (x > this.canvasWidth || y > this.canvasHeight || x < 0 || y < 0) { return null; } newRegion = this.getRegion(el, x, y); if (currentRegion !== newRegion) { if (currentRegion !== undefined && highlightEnabled) { this.removeHighlight(); } this.currentRegion = newRegion; if (newRegion !== undefined && highlightEnabled) { this.renderHighlight(); } return true; } return false; }, /** * Reset any currently highlighted item */ clearRegionHighlight: function () { if (this.currentRegion !== undefined) { this.removeHighlight(); this.currentRegion = undefined; return true; } return false; }, renderHighlight: function () { this.changeHighlight(true); }, removeHighlight: function () { this.changeHighlight(false); }, changeHighlight: function (highlight) {}, /** * Fetch the HTML to display as a tooltip */ getCurrentRegionTooltip: function () { var options = this.options, header = '', entries = [], fields, formats, formatlen, fclass, text, i, showFields, showFieldsKey, newFields, fv, formatter, format, fieldlen, j; if (this.currentRegion === undefined) { return ''; } fields = this.getCurrentRegionFields(); formatter = options.get('tooltipFormatter'); if (formatter) { return formatter(this, options, fields); } if (options.get('tooltipChartTitle')) { header += '<div class="jqs jqstitle">' + options.get('tooltipChartTitle') + '</div>\n'; } formats = this.options.get('tooltipFormat'); if (!formats) { return ''; } if (!$.isArray(formats)) { formats = [formats]; } if (!$.isArray(fields)) { fields = [fields]; } showFields = this.options.get('tooltipFormatFieldlist'); showFieldsKey = this.options.get('tooltipFormatFieldlistKey'); if (showFields && showFieldsKey) { // user-selected ordering of fields newFields = []; for (i = fields.length; i--;) { fv = fields[i][showFieldsKey]; if ((j = $.inArray(fv, showFields)) != -1) { newFields[j] = fields[i]; } } fields = newFields; } formatlen = formats.length; fieldlen = fields.length; for (i = 0; i < formatlen; i++) { format = formats[i]; if (typeof format === 'string') { format = new SPFormat(format); } fclass = format.fclass || 'jqsfield'; for (j = 0; j < fieldlen; j++) { if (!fields[j].isNull || !options.get('tooltipSkipNull')) { $.extend(fields[j], { prefix: options.get('tooltipPrefix'), suffix: options.get('tooltipSuffix') }); text = format.render(fields[j], options.get('tooltipValueLookups'), options); entries.push('<div class="' + fclass + '">' + text + '</div>'); } } } if (entries.length) { return header + entries.join('\n'); } return ''; }, getCurrentRegionFields: function () {}, calcHighlightColor: function (color, options) { var highlightColor = options.get('highlightColor'), lighten = options.get('highlightLighten'), parse, mult, rgbnew, i; if (highlightColor) { return highlightColor; } if (lighten) { // extract RGB values parse = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec(color) || /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(color); if (parse) { rgbnew = []; mult = color.length === 4 ? 16 : 1; for (i = 0; i < 3; i++) { rgbnew[i] = clipval(Math.round(parseInt(parse[i + 1], 16) * mult * lighten), 0, 255); } return 'rgb(' + rgbnew.join(',') + ')'; } } return color; } }); barHighlightMixin = { changeHighlight: function (highlight) { var currentRegion = this.currentRegion, target = this.target, shapeids = this.regionShapes[currentRegion], newShapes; // will be null if the region value was null if (shapeids) { newShapes = this.renderRegion(currentRegion, highlight); if ($.isArray(newShapes) || $.isArray(shapeids)) { target.replaceWithShapes(shapeids, newShapes); this.regionShapes[currentRegion] = $.map(newShapes, function (newShape) { return newShape.id; }); } else { target.replaceWithShape(shapeids, newShapes); this.regionShapes[currentRegion] = newShapes.id; } } }, render: function () { var values = this.values, target = this.target, regionShapes = this.regionShapes, shapes, ids, i, j; if (!this.cls._super.render.call(this)) { return; } for (i = values.length; i--;) { shapes = this.renderRegion(i); if (shapes) { if ($.isArray(shapes)) { ids = []; for (j = shapes.length; j--;) { shapes[j].append(); ids.push(shapes[j].id); } regionShapes[i] = ids; } else { shapes.append(); regionShapes[i] = shapes.id; // store just the shapeid } } else { // null value regionShapes[i] = null; } } target.render(); } }; /** * Line charts */ $.fn.sparkline.line = line = createClass($.fn.sparkline._base, { type: 'line', init: function (el, values, options, width, height) { line._super.init.call(this, el, values, options, width, height); this.vertices = []; this.regionMap = []; this.xvalues = []; this.yvalues = []; this.yminmax = []; this.hightlightSpotId = null; this.lastShapeId = null; this.initTarget(); }, getRegion: function (el, x, y) { var i, regionMap = this.regionMap; // maps regions to value positions for (i = regionMap.length; i--;) { if (regionMap[i] !== null && x >= regionMap[i][0] && x <= regionMap[i][1]) { return regionMap[i][2]; } } return undefined; }, getCurrentRegionFields: function () { var currentRegion = this.currentRegion; return { isNull: this.yvalues[currentRegion] === null, x: this.xvalues[currentRegion], y: this.yvalues[currentRegion], color: this.options.get('lineColor'), fillColor: this.options.get('fillColor'), offset: currentRegion }; }, renderHighlight: function () { var currentRegion = this.currentRegion, target = this.target, vertex = this.vertices[currentRegion], options = this.options, spotRadius = options.get('spotRadius'), highlightSpotColor = options.get('highlightSpotColor'), highlightLineColor = options.get('highlightLineColor'), highlightSpot, highlightLine; if (!vertex) { return; } if (spotRadius && highlightSpotColor) { highlightSpot = target.drawCircle(vertex[0], vertex[1], spotRadius, undefined, highlightSpotColor); this.highlightSpotId = highlightSpot.id; target.insertAfterShape(this.lastShapeId, highlightSpot); } if (highlightLineColor) { highlightLine = target.drawLine(vertex[0], this.canvasTop, vertex[0], this.canvasTop + this.canvasHeight, highlightLineColor); this.highlightLineId = highlightLine.id; target.insertAfterShape(this.lastShapeId, highlightLine); } }, removeHighlight: function () { var target = this.target; if (this.highlightSpotId) { target.removeShapeId(this.highlightSpotId); this.highlightSpotId = null; } if (this.highlightLineId) { target.removeShapeId(this.highlightLineId); this.highlightLineId = null; } }, scanValues: function () { var values = this.values, valcount = values.length, xvalues = this.xvalues, yvalues = this.yvalues, yminmax = this.yminmax, i, val, isStr, isArray, sp; for (i = 0; i < valcount; i++) { val = values[i]; isStr = typeof(values[i]) === 'string'; isArray = typeof(values[i]) === 'object' && values[i] instanceof Array; sp = isStr && values[i].split(':'); if (isStr && sp.length === 2) { // x:y xvalues.push(Number(sp[0])); yvalues.push(Number(sp[1])); yminmax.push(Number(sp[1])); } else if (isArray) { xvalues.push(val[0]); yvalues.push(val[1]); yminmax.push(val[1]); } else { xvalues.push(i); if (values[i] === null || values[i] === 'null') { yvalues.push(null); } else { yvalues.push(Number(val)); yminmax.push(Number(val)); } } } if (this.options.get('xvalues')) { xvalues = this.options.get('xvalues'); } this.maxy = this.maxyorg = Math.max.apply(Math, yminmax); this.miny = this.minyorg = Math.min.apply(Math, yminmax); this.maxx = Math.max.apply(Math, xvalues); this.minx = Math.min.apply(Math, xvalues); this.xvalues = xvalues; this.yvalues = yvalues; this.yminmax = yminmax; }, processRangeOptions: function () { var options = this.options, normalRangeMin = options.get('normalRangeMin'), normalRangeMax = options.get('normalRangeMax'); if (normalRangeMin !== undefined) { if (normalRangeMin < this.miny) { this.miny = normalRangeMin; } if (normalRangeMax > this.maxy) { this.maxy = normalRangeMax; } } if (options.get('chartRangeMin') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMin') < this.miny)) { this.miny = options.get('chartRangeMin'); } if (options.get('chartRangeMax') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMax') > this.maxy)) { this.maxy = options.get('chartRangeMax'); } if (options.get('chartRangeMinX') !== undefined && (options.get('chartRangeClipX') || options.get('chartRangeMinX') < this.minx)) { this.minx = options.get('chartRangeMinX'); } if (options.get('chartRangeMaxX') !== undefined && (options.get('chartRangeClipX') || options.get('chartRangeMaxX') > this.maxx)) { this.maxx = options.get('chartRangeMaxX'); } }, drawNormalRange: function (canvasLeft, canvasTop, canvasHeight, canvasWidth, rangey) { var normalRangeMin = this.options.get('normalRangeMin'), normalRangeMax = this.options.get('normalRangeMax'), ytop = canvasTop + Math.round(canvasHeight - (canvasHeight * ((normalRangeMax - this.miny) / rangey))), height = Math.round((canvasHeight * (normalRangeMax - normalRangeMin)) / rangey); this.target.drawRect(canvasLeft, ytop, canvasWidth, height, undefined, this.options.get('normalRangeColor')).append(); }, render: function () { var options = this.options, target = this.target, canvasWidth = this.canvasWidth, canvasHeight = this.canvasHeight, vertices = this.vertices, spotRadius = options.get('spotRadius'), regionMap = this.regionMap, rangex, rangey, yvallast, canvasTop, canvasLeft, vertex, path, paths, x, y, xnext, xpos, xposnext, last, next, yvalcount, lineShapes, fillShapes, plen, valueSpots, hlSpotsEnabled, color, xvalues, yvalues, i; if (!line._super.render.call(this)) { return; } this.scanValues(); this.processRangeOptions(); xvalues = this.xvalues; yvalues = this.yvalues; if (!this.yminmax.length || this.yvalues.length < 2) { // empty or all null valuess return; } canvasTop = canvasLeft = 0; rangex = this.maxx - this.minx === 0 ? 1 : this.maxx - this.minx; rangey = this.maxy - this.miny === 0 ? 1 : this.maxy - this.miny; yvallast = this.yvalues.length - 1; if (spotRadius && (canvasWidth < (spotRadius * 4) || canvasHeight < (spotRadius * 4))) { spotRadius = 0; } if (spotRadius) { // adjust the canvas size as required so that spots will fit hlSpotsEnabled = options.get('highlightSpotColor') && !options.get('disableInteraction'); if (hlSpotsEnabled || options.get('minSpotColor') || (options.get('spotColor') && yvalues[yvallast] === this.miny)) { canvasHeight -= Math.ceil(spotRadius); } if (hlSpotsEnabled || options.get('maxSpotColor') || (options.get('spotColor') && yvalues[yvallast] === this.maxy)) { canvasHeight -= Math.ceil(spotRadius); canvasTop += Math.ceil(spotRadius); } if (hlSpotsEnabled || ((options.get('minSpotColor') || options.get('maxSpotColor')) && (yvalues[0] === this.miny || yvalues[0] === this.maxy))) { canvasLeft += Math.ceil(spotRadius); canvasWidth -= Math.ceil(spotRadius); } if (hlSpotsEnabled || options.get('spotColor') || (options.get('minSpotColor') || options.get('maxSpotColor') && (yvalues[yvallast] === this.miny || yvalues[yvallast] === this.maxy))) { canvasWidth -= Math.ceil(spotRadius); } } canvasHeight--; if (options.get('normalRangeMin') !== undefined && !options.get('drawNormalOnTop')) { this.drawNormalRange(canvasLeft, canvasTop, canvasHeight, canvasWidth, rangey); } path = []; paths = [path]; last = next = null; yvalcount = yvalues.length; for (i = 0; i < yvalcount; i++) { x = xvalues[i]; xnext = xvalues[i + 1]; y = yvalues[i]; xpos = canvasLeft + Math.round((x - this.minx) * (canvasWidth / rangex)); xposnext = i < yvalcount - 1 ? canvasLeft + Math.round((xnext - this.minx) * (canvasWidth / rangex)) : canvasWidth; next = xpos + ((xposnext - xpos) / 2); regionMap[i] = [last || 0, next, i]; last = next; if (y === null) { if (i) { if (yvalues[i - 1] !== null) { path = []; paths.push(path); } vertices.push(null); } } else { if (y < this.miny) { y = this.miny; } if (y > this.maxy) { y = this.maxy; } if (!path.length) { // previous value was null path.push([xpos, canvasTop + canvasHeight]); } vertex = [xpos, canvasTop + Math.round(canvasHeight - (canvasHeight * ((y - this.miny) / rangey)))]; path.push(vertex); vertices.push(vertex); } } lineShapes = []; fillShapes = []; plen = paths.length; for (i = 0; i < plen; i++) { path = paths[i]; if (path.length) { if (options.get('fillColor')) { path.push([path[path.length - 1][0], (canvasTop + canvasHeight)]); fillShapes.push(path.slice(0)); path.pop(); } // if there's only a single point in this path, then we want to display it // as a vertical line which means we keep path[0] as is if (path.length > 2) { // else we want the first value path[0] = [path[0][0], path[1][1]]; } lineShapes.push(path); } } // draw the fill first, then optionally the normal range, then the line on top of that plen = fillShapes.length; for (i = 0; i < plen; i++) { target.drawShape(fillShapes[i], options.get('fillColor'), options.get('fillColor')).append(); } if (options.get('normalRangeMin') !== undefined && options.get('drawNormalOnTop')) { this.drawNormalRange(canvasLeft, canvasTop, canvasHeight, canvasWidth, rangey); } plen = lineShapes.length; for (i = 0; i < plen; i++) { target.drawShape(lineShapes[i], options.get('lineColor'), undefined, options.get('lineWidth')).append(); } if (spotRadius && options.get('valueSpots')) { valueSpots = options.get('valueSpots'); if (valueSpots.get === undefined) { valueSpots = new RangeMap(valueSpots); } for (i = 0; i < yvalcount; i++) { color = valueSpots.get(yvalues[i]); if (color) { target.drawCircle(canvasLeft + Math.round((xvalues[i] - this.minx) * (canvasWidth / rangex)), canvasTop + Math.round(canvasHeight - (canvasHeight * ((yvalues[i] - this.miny) / rangey))), spotRadius, undefined, color).append(); } } } if (spotRadius && options.get('spotColor') && yvalues[yvallast] !== null) { target.drawCircle(canvasLeft + Math.round((xvalues[xvalues.length - 1] - this.minx) * (canvasWidth / rangex)), canvasTop + Math.round(canvasHeight - (canvasHeight * ((yvalues[yvallast] - this.miny) / rangey))), spotRadius, undefined, options.get('spotColor')).append(); } if (this.maxy !== this.minyorg) { if (spotRadius && options.get('minSpotColor')) { x = xvalues[$.inArray(this.minyorg, yvalues)]; target.drawCircle(canvasLeft + Math.round((x - this.minx) * (canvasWidth / rangex)), canvasTop + Math.round(canvasHeight - (canvasHeight * ((this.minyorg - this.miny) / rangey))), spotRadius, undefined, options.get('minSpotColor')).append(); } if (spotRadius && options.get('maxSpotColor')) { x = xvalues[$.inArray(this.maxyorg, yvalues)]; target.drawCircle(canvasLeft + Math.round((x - this.minx) * (canvasWidth / rangex)), canvasTop + Math.round(canvasHeight - (canvasHeight * ((this.maxyorg - this.miny) / rangey))), spotRadius, undefined, options.get('maxSpotColor')).append(); } } this.lastShapeId = target.getLastShapeId(); this.canvasTop = canvasTop; target.render(); } }); /** * Bar charts */ $.fn.sparkline.bar = bar = createClass($.fn.sparkline._base, barHighlightMixin, { type: 'bar', init: function (el, values, options, width, height) { var barWidth = parseInt(options.get('barWidth'), 10), barSpacing = parseInt(options.get('barSpacing'), 10), chartRangeMin = options.get('chartRangeMin'), chartRangeMax = options.get('chartRangeMax'), chartRangeClip = options.get('chartRangeClip'), stackMin = Infinity, stackMax = -Infinity, isStackString, groupMin, groupMax, stackRanges, numValues, i, vlen, range, zeroAxis, xaxisOffset, min, max, clipMin, clipMax, stacked, vlist, j, slen, svals, val, yoffset, yMaxCalc, canvasHeightEf; bar._super.init.call(this, el, values, options, width, height); // scan values to determine whether to stack bars for (i = 0, vlen = values.length; i < vlen; i++) { val = values[i]; isStackString = typeof(val) === 'string' && val.indexOf(':') > -1; if (isStackString || $.isArray(val)) { stacked = true; if (isStackString) { val = values[i] = normalizeValues(val.split(':')); } val = remove(val, null); // min/max will treat null as zero groupMin = Math.min.apply(Math, val); groupMax = Math.max.apply(Math, val); if (groupMin < stackMin) { stackMin = groupMin; } if (groupMax > stackMax) { stackMax = groupMax; } } } this.stacked = stacked; this.regionShapes = {}; this.barWidth = barWidth; this.barSpacing = barSpacing; this.totalBarWidth = barWidth + barSpacing; this.width = width = (values.length * barWidth) + ((values.length - 1) * barSpacing); this.initTarget(); if (chartRangeClip) { clipMin = chartRangeMin === undefined ? -Infinity : chartRangeMin; clipMax = chartRangeMax === undefined ? Infinity : chartRangeMax; } numValues = []; stackRanges = stacked ? [] : numValues; var stackTotals = []; var stackRangesNeg = []; for (i = 0, vlen = values.length; i < vlen; i++) { if (stacked) { vlist = values[i]; values[i] = svals = []; stackTotals[i] = 0; stackRanges[i] = stackRangesNeg[i] = 0; for (j = 0, slen = vlist.length; j < slen; j++) { val = svals[j] = chartRangeClip ? clipval(vlist[j], clipMin, clipMax) : vlist[j]; if (val !== null) { if (val > 0) { stackTotals[i] += val; } if (stackMin < 0 && stackMax > 0) { if (val < 0) { stackRangesNeg[i] += Math.abs(val); } else { stackRanges[i] += val; } } else { stackRanges[i] += Math.abs(val - (val < 0 ? stackMax : stackMin)); } numValues.push(val); } } } else { val = chartRangeClip ? clipval(values[i], clipMin, clipMax) : values[i]; val = values[i] = normalizeValue(val); if (val !== null) { numValues.push(val); } } } this.max = max = Math.max.apply(Math, numValues); this.min = min = Math.min.apply(Math, numValues); this.stackMax = stackMax = stacked ? Math.max.apply(Math, stackTotals) : max; this.stackMin = stackMin = stacked ? Math.min.apply(Math, numValues) : min; if (options.get('chartRangeMin') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMin') < min)) { min = options.get('chartRangeMin'); } if (options.get('chartRangeMax') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMax') > max)) { max = options.get('chartRangeMax'); } this.zeroAxis = zeroAxis = options.get('zeroAxis', true); if (min <= 0 && max >= 0 && zeroAxis) { xaxisOffset = 0; } else if (zeroAxis == false) { xaxisOffset = min; } else if (min > 0) { xaxisOffset = min; } else { xaxisOffset = max; } this.xaxisOffset = xaxisOffset; range = stacked ? (Math.max.apply(Math, stackRanges) + Math.max.apply(Math, stackRangesNeg)) : max - min; // as we plot zero/min values a single pixel line, we add a pixel to all other // values - Reduce the effective canvas size to suit this.canvasHeightEf = (zeroAxis && min < 0) ? this.canvasHeight - 2 : this.canvasHeight - 1; if (min < xaxisOffset) { yMaxCalc = (stacked && max >= 0) ? stackMax : max; yoffset = (yMaxCalc - xaxisOffset) / range * this.canvasHeight; if (yoffset !== Math.ceil(yoffset)) { this.canvasHeightEf -= 2; yoffset = Math.ceil(yoffset); } } else { yoffset = this.canvasHeight; } this.yoffset = yoffset; if ($.isArray(options.get('colorMap'))) { this.colorMapByIndex = options.get('colorMap'); this.colorMapByValue = null; } else { this.colorMapByIndex = null; this.colorMapByValue = options.get('colorMap'); if (this.colorMapByValue && this.colorMapByValue.get === undefined) { this.colorMapByValue = new RangeMap(this.colorMapByValue); } } this.range = range; }, getRegion: function (el, x, y) { var result = Math.floor(x / this.totalBarWidth); return (result < 0 || result >= this.values.length) ? undefined : result; }, getCurrentRegionFields: function () { var currentRegion = this.currentRegion, values = ensureArray(this.values[currentRegion]), result = [], value, i; for (i = values.length; i--;) { value = values[i]; result.push({ isNull: value === null, value: value, color: this.calcColor(i, value, currentRegion), offset: currentRegion }); } return result; }, calcColor: function (stacknum, value, valuenum) { var colorMapByIndex = this.colorMapByIndex, colorMapByValue = this.colorMapByValue, options = this.options, color, newColor; if (this.stacked) { color = options.get('stackedBarColor'); } else { color = (value < 0) ? options.get('negBarColor') : options.get('barColor'); } if (value === 0 && options.get('zeroColor') !== undefined) { color = options.get('zeroColor'); } if (colorMapByValue && (newColor = colorMapByValue.get(value))) { color = newColor; } else if (colorMapByIndex && colorMapByIndex.length > valuenum) { color = colorMapByIndex[valuenum]; } return $.isArray(color) ? color[stacknum % color.length] : color; }, /** * Render bar(s) for a region */ renderRegion: function (valuenum, highlight) { var vals = this.values[valuenum], options = this.options, xaxisOffset = this.xaxisOffset, result = [], range = this.range, stacked = this.stacked, target = this.target, x = valuenum * this.totalBarWidth, canvasHeightEf = this.canvasHeightEf, yoffset = this.yoffset, y, height, color, isNull, yoffsetNeg, i, valcount, val, minPlotted, allMin; vals = $.isArray(vals) ? vals : [vals]; valcount = vals.length; val = vals[0]; isNull = all(null, vals); allMin = all(xaxisOffset, vals, true); if (isNull) { if (options.get('nullColor')) { color = highlight ? options.get('nullColor') : this.calcHighlightColor(options.get('nullColor'), options); y = (yoffset > 0) ? yoffset - 1 : yoffset; return target.drawRect(x, y, this.barWidth - 1, 0, color, color); } else { return undefined; } } yoffsetNeg = yoffset; for (i = 0; i < valcount; i++) { val = vals[i]; if (stacked && val === xaxisOffset) { if (!allMin || minPlotted) { continue; } minPlotted = true; } if (range > 0) { height = Math.floor(canvasHeightEf * ((Math.abs(val - xaxisOffset) / range))) + 1; } else { height = 1; } if (val < xaxisOffset || (val === xaxisOffset && yoffset === 0)) { y = yoffsetNeg; yoffsetNeg += height; } else { y = yoffset - height; yoffset -= height; } color = this.calcColor(i, val, valuenum); if (highlight) { color = this.calcHighlightColor(color, options); } result.push(target.drawRect(x, y, this.barWidth - 1, height - 1, color, color)); } if (result.length === 1) { return result[0]; } return result; } }); /** * Tristate charts */ $.fn.sparkline.tristate = tristate = createClass($.fn.sparkline._base, barHighlightMixin, { type: 'tristate', init: function (el, values, options, width, height) { var barWidth = parseInt(options.get('barWidth'), 10), barSpacing = parseInt(options.get('barSpacing'), 10); tristate._super.init.call(this, el, values, options, width, height); this.regionShapes = {}; this.barWidth = barWidth; this.barSpacing = barSpacing; this.totalBarWidth = barWidth + barSpacing; this.values = $.map(values, Number); this.width = width = (values.length * barWidth) + ((values.length - 1) * barSpacing); if ($.isArray(options.get('colorMap'))) { this.colorMapByIndex = options.get('colorMap'); this.colorMapByValue = null; } else { this.colorMapByIndex = null; this.colorMapByValue = options.get('colorMap'); if (this.colorMapByValue && this.colorMapByValue.get === undefined) { this.colorMapByValue = new RangeMap(this.colorMapByValue); } } this.initTarget(); }, getRegion: function (el, x, y) { return Math.floor(x / this.totalBarWidth); }, getCurrentRegionFields: function () { var currentRegion = this.currentRegion; return { isNull: this.values[currentRegion] === undefined, value: this.values[currentRegion], color: this.calcColor(this.values[currentRegion], currentRegion), offset: currentRegion }; }, calcColor: function (value, valuenum) { var values = this.values, options = this.options, colorMapByIndex = this.colorMapByIndex, colorMapByValue = this.colorMapByValue, color, newColor; if (colorMapByValue && (newColor = colorMapByValue.get(value))) { color = newColor; } else if (colorMapByIndex && colorMapByIndex.length > valuenum) { color = colorMapByIndex[valuenum]; } else if (values[valuenum] < 0) { color = options.get('negBarColor'); } else if (values[valuenum] > 0) { color = options.get('posBarColor'); } else { color = options.get('zeroBarColor'); } return color; }, renderRegion: function (valuenum, highlight) { var values = this.values, options = this.options, target = this.target, canvasHeight, height, halfHeight, x, y, color; canvasHeight = target.pixelHeight; halfHeight = Math.round(canvasHeight / 2); x = valuenum * this.totalBarWidth; if (values[valuenum] < 0) { y = halfHeight; height = halfHeight - 1; } else if (values[valuenum] > 0) { y = 0; height = halfHeight - 1; } else { y = halfHeight - 1; height = 2; } color = this.calcColor(values[valuenum], valuenum); if (color === null) { return; } if (highlight) { color = this.calcHighlightColor(color, options); } return target.drawRect(x, y, this.barWidth - 1, height - 1, color, color); } }); /** * Discrete charts */ $.fn.sparkline.discrete = discrete = createClass($.fn.sparkline._base, barHighlightMixin, { type: 'discrete', init: function (el, values, options, width, height) { discrete._super.init.call(this, el, values, options, width, height); this.regionShapes = {}; this.values = values = $.map(values, Number); this.min = Math.min.apply(Math, values); this.max = Math.max.apply(Math, values); this.range = this.max - this.min; this.width = width = options.get('width') === 'auto' ? values.length * 2 : this.width; this.interval = Math.floor(width / values.length); this.itemWidth = width / values.length; if (options.get('chartRangeMin') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMin') < this.min)) { this.min = options.get('chartRangeMin'); } if (options.get('chartRangeMax') !== undefined && (options.get('chartRangeClip') || options.get('chartRangeMax') > this.max)) { this.max = options.get('chartRangeMax'); } this.initTarget(); if (this.target) { this.lineHeight = options.get('lineHeight') === 'auto' ? Math.round(this.canvasHeight * 0.3) : options.get('lineHeight'); } }, getRegion: function (el, x, y) { return Math.floor(x / this.itemWidth); }, getCurrentRegionFields: function () { var currentRegion = this.currentRegion; return { isNull: this.values[currentRegion] === undefined, value: this.values[currentRegion], offset: currentRegion }; }, renderRegion: function (valuenum, highlight) { var values = this.values, options = this.options, min = this.min, max = this.max, range = this.range, interval = this.interval, target = this.target, canvasHeight = this.canvasHeight, lineHeight = this.lineHeight, pheight = canvasHeight - lineHeight, ytop, val, color, x; val = clipval(values[valuenum], min, max); x = valuenum * interval; ytop = Math.round(pheight - pheight * ((val - min) / range)); color = (options.get('thresholdColor') && val < options.get('thresholdValue')) ? options.get('thresholdColor') : options.get('lineColor'); if (highlight) { color = this.calcHighlightColor(color, options); } return target.drawLine(x, ytop, x, ytop + lineHeight, color); } }); /** * Bullet charts */ $.fn.sparkline.bullet = bullet = createClass($.fn.sparkline._base, { type: 'bullet', init: function (el, values, options, width, height) { var min, max, vals; bullet._super.init.call(this, el, values, options, width, height); // values: target, performance, range1, range2, range3 this.values = values = normalizeValues(values); // target or performance could be null vals = values.slice(); vals[0] = vals[0] === null ? vals[2] : vals[0]; vals[1] = values[1] === null ? vals[2] : vals[1]; min = Math.min.apply(Math, values); max = Math.max.apply(Math, values); if (options.get('base') === undefined) { min = min < 0 ? min : 0; } else { min = options.get('base'); } this.min = min; this.max = max; this.range = max - min; this.shapes = {}; this.valueShapes = {}; this.regiondata = {}; this.width = width = options.get('width') === 'auto' ? '4.0em' : width; this.target = this.$el.simpledraw(width, height, options.get('composite')); if (!values.length) { this.disabled = true; } this.initTarget(); }, getRegion: function (el, x, y) { var shapeid = this.target.getShapeAt(el, x, y); return (shapeid !== undefined && this.shapes[shapeid] !== undefined) ? this.shapes[shapeid] : undefined; }, getCurrentRegionFields: function () { var currentRegion = this.currentRegion; return { fieldkey: currentRegion.substr(0, 1), value: this.values[currentRegion.substr(1)], region: currentRegion }; }, changeHighlight: function (highlight) { var currentRegion = this.currentRegion, shapeid = this.valueShapes[currentRegion], shape; delete this.shapes[shapeid]; switch (currentRegion.substr(0, 1)) { case 'r': shape = this.renderRange(currentRegion.substr(1), highlight); break; case 'p': shape = this.renderPerformance(highlight); break; case 't': shape = this.renderTarget(highlight); break; } this.valueShapes[currentRegion] = shape.id; this.shapes[shape.id] = currentRegion; this.target.replaceWithShape(shapeid, shape); }, renderRange: function (rn, highlight) { var rangeval = this.values[rn], rangewidth = Math.round(this.canvasWidth * ((rangeval - this.min) / this.range)), color = this.options.get('rangeColors')[rn - 2]; if (highlight) { color = this.calcHighlightColor(color, this.options); } return this.target.drawRect(0, 0, rangewidth - 1, this.canvasHeight - 1, color, color); }, renderPerformance: function (highlight) { var perfval = this.values[1], perfwidth = Math.round(this.canvasWidth * ((perfval - this.min) / this.range)), color = this.options.get('performanceColor'); if (highlight) { color = this.calcHighlightColor(color, this.options); } return this.target.drawRect(0, Math.round(this.canvasHeight * 0.3), perfwidth - 1, Math.round(this.canvasHeight * 0.4) - 1, color, color); }, renderTarget: function (highlight) { var targetval = this.values[0], x = Math.round(this.canvasWidth * ((targetval - this.min) / this.range) - (this.options.get('targetWidth') / 2)), targettop = Math.round(this.canvasHeight * 0.10), targetheight = this.canvasHeight - (targettop * 2), color = this.options.get('targetColor'); if (highlight) { color = this.calcHighlightColor(color, this.options); } return this.target.drawRect(x, targettop, this.options.get('targetWidth') - 1, targetheight - 1, color, color); }, render: function () { var vlen = this.values.length, target = this.target, i, shape; if (!bullet._super.render.call(this)) { return; } for (i = 2; i < vlen; i++) { shape = this.renderRange(i).append(); this.shapes[shape.id] = 'r' + i; this.valueShapes['r' + i] = shape.id; } if (this.values[1] !== null) { shape = this.renderPerformance().append(); this.shapes[shape.id] = 'p1'; this.valueShapes.p1 = shape.id; } if (this.values[0] !== null) { shape = this.renderTarget().append(); this.shapes[shape.id] = 't0'; this.valueShapes.t0 = shape.id; } target.render(); } }); /** * Pie charts */ $.fn.sparkline.pie = pie = createClass($.fn.sparkline._base, { type: 'pie', init: function (el, values, options, width, height) { var total = 0, i; pie._super.init.call(this, el, values, options, width, height); this.shapes = {}; // map shape ids to value offsets this.valueShapes = {}; // maps value offsets to shape ids this.values = values = $.map(values, Number); if (options.get('width') === 'auto') { this.width = this.height; } if (values.length > 0) { for (i = values.length; i--;) { total += values[i]; } } this.total = total; this.initTarget(); this.radius = Math.floor(Math.min(this.canvasWidth, this.canvasHeight) / 2); }, getRegion: function (el, x, y) { var shapeid = this.target.getShapeAt(el, x, y); return (shapeid !== undefined && this.shapes[shapeid] !== undefined) ? this.shapes[shapeid] : undefined; }, getCurrentRegionFields: function () { var currentRegion = this.currentRegion; return { isNull: this.values[currentRegion] === undefined, value: this.values[currentRegion], percent: this.values[currentRegion] / this.total * 100, color: this.options.get('sliceColors')[currentRegion % this.options.get('sliceColors').length], offset: currentRegion }; }, changeHighlight: function (highlight) { var currentRegion = this.currentRegion, newslice = this.renderSlice(currentRegion, highlight), shapeid = this.valueShapes[currentRegion]; delete this.shapes[shapeid]; this.target.replaceWithShape(shapeid, newslice); this.valueShapes[currentRegion] = newslice.id; this.shapes[newslice.id] = currentRegion; }, renderSlice: function (valuenum, highlight) { var target = this.target, options = this.options, radius = this.radius, borderWidth = options.get('borderWidth'), offset = options.get('offset'), circle = 2 * Math.PI, values = this.values, total = this.total, next = offset ? (2*Math.PI)*(offset/360) : 0, start, end, i, vlen, color; vlen = values.length; for (i = 0; i < vlen; i++) { start = next; end = next; if (total > 0) { // avoid divide by zero end = next + (circle * (values[i] / total)); } if (valuenum === i) { color = options.get('sliceColors')[i % options.get('sliceColors').length]; if (highlight) { color = this.calcHighlightColor(color, options); } return target.drawPieSlice(radius, radius, radius - borderWidth, start, end, undefined, color); } next = end; } }, render: function () { var target = this.target, values = this.values, options = this.options, radius = this.radius, borderWidth = options.get('borderWidth'), shape, i; if (!pie._super.render.call(this)) { return; } if (borderWidth) { target.drawCircle(radius, radius, Math.floor(radius - (borderWidth / 2)), options.get('borderColor'), undefined, borderWidth).append(); } for (i = values.length; i--;) { if (values[i]) { // don't render zero values shape = this.renderSlice(i).append(); this.valueShapes[i] = shape.id; // store just the shapeid this.shapes[shape.id] = i; } } target.render(); } }); /** * Box plots */ $.fn.sparkline.box = box = createClass($.fn.sparkline._base, { type: 'box', init: function (el, values, options, width, height) { box._super.init.call(this, el, values, options, width, height); this.values = $.map(values, Number); this.width = options.get('width') === 'auto' ? '4.0em' : width; this.initTarget(); if (!this.values.length) { this.disabled = 1; } }, /** * Simulate a single region */ getRegion: function () { return 1; }, getCurrentRegionFields: function () { var result = [ { field: 'lq', value: this.quartiles[0] }, { field: 'med', value: this.quartiles[1] }, { field: 'uq', value: this.quartiles[2] } ]; if (this.loutlier !== undefined) { result.push({ field: 'lo', value: this.loutlier}); } if (this.routlier !== undefined) { result.push({ field: 'ro', value: this.routlier}); } if (this.lwhisker !== undefined) { result.push({ field: 'lw', value: this.lwhisker}); } if (this.rwhisker !== undefined) { result.push({ field: 'rw', value: this.rwhisker}); } return result; }, render: function () { var target = this.target, values = this.values, vlen = values.length, options = this.options, canvasWidth = this.canvasWidth, canvasHeight = this.canvasHeight, minValue = options.get('chartRangeMin') === undefined ? Math.min.apply(Math, values) : options.get('chartRangeMin'), maxValue = options.get('chartRangeMax') === undefined ? Math.max.apply(Math, values) : options.get('chartRangeMax'), canvasLeft = 0, lwhisker, loutlier, iqr, q1, q2, q3, rwhisker, routlier, i, size, unitSize; if (!box._super.render.call(this)) { return; } if (options.get('raw')) { if (options.get('showOutliers') && values.length > 5) { loutlier = values[0]; lwhisker = values[1]; q1 = values[2]; q2 = values[3]; q3 = values[4]; rwhisker = values[5]; routlier = values[6]; } else { lwhisker = values[0]; q1 = values[1]; q2 = values[2]; q3 = values[3]; rwhisker = values[4]; } } else { values.sort(function (a, b) { return a - b; }); q1 = quartile(values, 1); q2 = quartile(values, 2); q3 = quartile(values, 3); iqr = q3 - q1; if (options.get('showOutliers')) { lwhisker = rwhisker = undefined; for (i = 0; i < vlen; i++) { if (lwhisker === undefined && values[i] > q1 - (iqr * options.get('outlierIQR'))) { lwhisker = values[i]; } if (values[i] < q3 + (iqr * options.get('outlierIQR'))) { rwhisker = values[i]; } } loutlier = values[0]; routlier = values[vlen - 1]; } else { lwhisker = values[0]; rwhisker = values[vlen - 1]; } } this.quartiles = [q1, q2, q3]; this.lwhisker = lwhisker; this.rwhisker = rwhisker; this.loutlier = loutlier; this.routlier = routlier; unitSize = canvasWidth / (maxValue - minValue + 1); if (options.get('showOutliers')) { canvasLeft = Math.ceil(options.get('spotRadius')); canvasWidth -= 2 * Math.ceil(options.get('spotRadius')); unitSize = canvasWidth / (maxValue - minValue + 1); if (loutlier < lwhisker) { target.drawCircle((loutlier - minValue) * unitSize + canvasLeft, canvasHeight / 2, options.get('spotRadius'), options.get('outlierLineColor'), options.get('outlierFillColor')).append(); } if (routlier > rwhisker) { target.drawCircle((routlier - minValue) * unitSize + canvasLeft, canvasHeight / 2, options.get('spotRadius'), options.get('outlierLineColor'), options.get('outlierFillColor')).append(); } } // box target.drawRect( Math.round((q1 - minValue) * unitSize + canvasLeft), Math.round(canvasHeight * 0.1), Math.round((q3 - q1) * unitSize), Math.round(canvasHeight * 0.8), options.get('boxLineColor'), options.get('boxFillColor')).append(); // left whisker target.drawLine( Math.round((lwhisker - minValue) * unitSize + canvasLeft), Math.round(canvasHeight / 2), Math.round((q1 - minValue) * unitSize + canvasLeft), Math.round(canvasHeight / 2), options.get('lineColor')).append(); target.drawLine( Math.round((lwhisker - minValue) * unitSize + canvasLeft), Math.round(canvasHeight / 4), Math.round((lwhisker - minValue) * unitSize + canvasLeft), Math.round(canvasHeight - canvasHeight / 4), options.get('whiskerColor')).append(); // right whisker target.drawLine(Math.round((rwhisker - minValue) * unitSize + canvasLeft), Math.round(canvasHeight / 2), Math.round((q3 - minValue) * unitSize + canvasLeft), Math.round(canvasHeight / 2), options.get('lineColor')).append(); target.drawLine( Math.round((rwhisker - minValue) * unitSize + canvasLeft), Math.round(canvasHeight / 4), Math.round((rwhisker - minValue) * unitSize + canvasLeft), Math.round(canvasHeight - canvasHeight / 4), options.get('whiskerColor')).append(); // median line target.drawLine( Math.round((q2 - minValue) * unitSize + canvasLeft), Math.round(canvasHeight * 0.1), Math.round((q2 - minValue) * unitSize + canvasLeft), Math.round(canvasHeight * 0.9), options.get('medianColor')).append(); if (options.get('target')) { size = Math.ceil(options.get('spotRadius')); target.drawLine( Math.round((options.get('target') - minValue) * unitSize + canvasLeft), Math.round((canvasHeight / 2) - size), Math.round((options.get('target') - minValue) * unitSize + canvasLeft), Math.round((canvasHeight / 2) + size), options.get('targetColor')).append(); target.drawLine( Math.round((options.get('target') - minValue) * unitSize + canvasLeft - size), Math.round(canvasHeight / 2), Math.round((options.get('target') - minValue) * unitSize + canvasLeft + size), Math.round(canvasHeight / 2), options.get('targetColor')).append(); } target.render(); } }); // Setup a very simple "virtual canvas" to make drawing the few shapes we need easier // This is accessible as $(foo).simpledraw() VShape = createClass({ init: function (target, id, type, args) { this.target = target; this.id = id; this.type = type; this.args = args; }, append: function () { this.target.appendShape(this); return this; } }); VCanvas_base = createClass({ _pxregex: /(\d+)(px)?\s*$/i, init: function (width, height, target) { if (!width) { return; } this.width = width; this.height = height; this.target = target; this.lastShapeId = null; if (target[0]) { target = target[0]; } $.data(target, '_jqs_vcanvas', this); }, drawLine: function (x1, y1, x2, y2, lineColor, lineWidth) { return this.drawShape([[x1, y1], [x2, y2]], lineColor, lineWidth); }, drawShape: function (path, lineColor, fillColor, lineWidth) { return this._genShape('Shape', [path, lineColor, fillColor, lineWidth]); }, drawCircle: function (x, y, radius, lineColor, fillColor, lineWidth) { return this._genShape('Circle', [x, y, radius, lineColor, fillColor, lineWidth]); }, drawPieSlice: function (x, y, radius, startAngle, endAngle, lineColor, fillColor) { return this._genShape('PieSlice', [x, y, radius, startAngle, endAngle, lineColor, fillColor]); }, drawRect: function (x, y, width, height, lineColor, fillColor) { return this._genShape('Rect', [x, y, width, height, lineColor, fillColor]); }, getElement: function () { return this.canvas; }, /** * Return the most recently inserted shape id */ getLastShapeId: function () { return this.lastShapeId; }, /** * Clear and reset the canvas */ reset: function () { alert('reset not implemented'); }, _insert: function (el, target) { $(target).html(el); }, /** * Calculate the pixel dimensions of the canvas */ _calculatePixelDims: function (width, height, canvas) { // XXX This should probably be a configurable option var match; match = this._pxregex.exec(height); if (match) { this.pixelHeight = match[1]; } else { this.pixelHeight = $(canvas).height(); } match = this._pxregex.exec(width); if (match) { this.pixelWidth = match[1]; } else { this.pixelWidth = $(canvas).width(); } }, /** * Generate a shape object and id for later rendering */ _genShape: function (shapetype, shapeargs) { var id = shapeCount++; shapeargs.unshift(id); return new VShape(this, id, shapetype, shapeargs); }, /** * Add a shape to the end of the render queue */ appendShape: function (shape) { alert('appendShape not implemented'); }, /** * Replace one shape with another */ replaceWithShape: function (shapeid, shape) { alert('replaceWithShape not implemented'); }, /** * Insert one shape after another in the render queue */ insertAfterShape: function (shapeid, shape) { alert('insertAfterShape not implemented'); }, /** * Remove a shape from the queue */ removeShapeId: function (shapeid) { alert('removeShapeId not implemented'); }, /** * Find a shape at the specified x/y co-ordinates */ getShapeAt: function (el, x, y) { alert('getShapeAt not implemented'); }, /** * Render all queued shapes onto the canvas */ render: function () { alert('render not implemented'); } }); VCanvas_canvas = createClass(VCanvas_base, { init: function (width, height, target, interact) { VCanvas_canvas._super.init.call(this, width, height, target); this.canvas = document.createElement('canvas'); if (target[0]) { target = target[0]; } $.data(target, '_jqs_vcanvas', this); $(this.canvas).css({ display: 'inline-block', width: width, height: height, verticalAlign: 'top' }); this._insert(this.canvas, target); this._calculatePixelDims(width, height, this.canvas); this.canvas.width = this.pixelWidth; this.canvas.height = this.pixelHeight; this.interact = interact; this.shapes = {}; this.shapeseq = []; this.currentTargetShapeId = undefined; $(this.canvas).css({width: this.pixelWidth, height: this.pixelHeight}); }, _getContext: function (lineColor, fillColor, lineWidth) { var context = this.canvas.getContext('2d'); if (lineColor !== undefined) { context.strokeStyle = lineColor; } context.lineWidth = lineWidth === undefined ? 1 : lineWidth; if (fillColor !== undefined) { context.fillStyle = fillColor; } return context; }, reset: function () { var context = this._getContext(); context.clearRect(0, 0, this.pixelWidth, this.pixelHeight); this.shapes = {}; this.shapeseq = []; this.currentTargetShapeId = undefined; }, _drawShape: function (shapeid, path, lineColor, fillColor, lineWidth) { var context = this._getContext(lineColor, fillColor, lineWidth), i, plen; context.beginPath(); context.moveTo(path[0][0] + 0.5, path[0][1] + 0.5); for (i = 1, plen = path.length; i < plen; i++) { context.lineTo(path[i][0] + 0.5, path[i][1] + 0.5); // the 0.5 offset gives us crisp pixel-width lines } if (lineColor !== undefined) { context.stroke(); } if (fillColor !== undefined) { context.fill(); } if (this.targetX !== undefined && this.targetY !== undefined && context.isPointInPath(this.targetX, this.targetY)) { this.currentTargetShapeId = shapeid; } }, _drawCircle: function (shapeid, x, y, radius, lineColor, fillColor, lineWidth) { var context = this._getContext(lineColor, fillColor, lineWidth); context.beginPath(); context.arc(x, y, radius, 0, 2 * Math.PI, false); if (this.targetX !== undefined && this.targetY !== undefined && context.isPointInPath(this.targetX, this.targetY)) { this.currentTargetShapeId = shapeid; } if (lineColor !== undefined) { context.stroke(); } if (fillColor !== undefined) { context.fill(); } }, _drawPieSlice: function (shapeid, x, y, radius, startAngle, endAngle, lineColor, fillColor) { var context = this._getContext(lineColor, fillColor); context.beginPath(); context.moveTo(x, y); context.arc(x, y, radius, startAngle, endAngle, false); context.lineTo(x, y); context.closePath(); if (lineColor !== undefined) { context.stroke(); } if (fillColor) { context.fill(); } if (this.targetX !== undefined && this.targetY !== undefined && context.isPointInPath(this.targetX, this.targetY)) { this.currentTargetShapeId = shapeid; } }, _drawRect: function (shapeid, x, y, width, height, lineColor, fillColor) { return this._drawShape(shapeid, [[x, y], [x + width, y], [x + width, y + height], [x, y + height], [x, y]], lineColor, fillColor); }, appendShape: function (shape) { this.shapes[shape.id] = shape; this.shapeseq.push(shape.id); this.lastShapeId = shape.id; return shape.id; }, replaceWithShape: function (shapeid, shape) { var shapeseq = this.shapeseq, i; this.shapes[shape.id] = shape; for (i = shapeseq.length; i--;) { if (shapeseq[i] == shapeid) { shapeseq[i] = shape.id; } } delete this.shapes[shapeid]; }, replaceWithShapes: function (shapeids, shapes) { var shapeseq = this.shapeseq, shapemap = {}, sid, i, first; for (i = shapeids.length; i--;) { shapemap[shapeids[i]] = true; } for (i = shapeseq.length; i--;) { sid = shapeseq[i]; if (shapemap[sid]) { shapeseq.splice(i, 1); delete this.shapes[sid]; first = i; } } for (i = shapes.length; i--;) { shapeseq.splice(first, 0, shapes[i].id); this.shapes[shapes[i].id] = shapes[i]; } }, insertAfterShape: function (shapeid, shape) { var shapeseq = this.shapeseq, i; for (i = shapeseq.length; i--;) { if (shapeseq[i] === shapeid) { shapeseq.splice(i + 1, 0, shape.id); this.shapes[shape.id] = shape; return; } } }, removeShapeId: function (shapeid) { var shapeseq = this.shapeseq, i; for (i = shapeseq.length; i--;) { if (shapeseq[i] === shapeid) { shapeseq.splice(i, 1); break; } } delete this.shapes[shapeid]; }, getShapeAt: function (el, x, y) { this.targetX = x; this.targetY = y; this.render(); return this.currentTargetShapeId; }, render: function () { var shapeseq = this.shapeseq, shapes = this.shapes, shapeCount = shapeseq.length, context = this._getContext(), shapeid, shape, i; context.clearRect(0, 0, this.pixelWidth, this.pixelHeight); for (i = 0; i < shapeCount; i++) { shapeid = shapeseq[i]; shape = shapes[shapeid]; this['_draw' + shape.type].apply(this, shape.args); } if (!this.interact) { // not interactive so no need to keep the shapes array this.shapes = {}; this.shapeseq = []; } } }); VCanvas_vml = createClass(VCanvas_base, { init: function (width, height, target) { var groupel; VCanvas_vml._super.init.call(this, width, height, target); if (target[0]) { target = target[0]; } $.data(target, '_jqs_vcanvas', this); this.canvas = document.createElement('span'); $(this.canvas).css({ display: 'inline-block', position: 'relative', overflow: 'hidden', width: width, height: height, margin: '0px', padding: '0px', verticalAlign: 'top'}); this._insert(this.canvas, target); this._calculatePixelDims(width, height, this.canvas); this.canvas.width = this.pixelWidth; this.canvas.height = this.pixelHeight; groupel = '<v:group coordorigin="0 0" coordsize="' + this.pixelWidth + ' ' + this.pixelHeight + '"' + ' style="position:absolute;top:0;left:0;width:' + this.pixelWidth + 'px;height=' + this.pixelHeight + 'px;"></v:group>'; this.canvas.insertAdjacentHTML('beforeEnd', groupel); this.group = $(this.canvas).children()[0]; this.rendered = false; this.prerender = ''; }, _drawShape: function (shapeid, path, lineColor, fillColor, lineWidth) { var vpath = [], initial, stroke, fill, closed, vel, plen, i; for (i = 0, plen = path.length; i < plen; i++) { vpath[i] = '' + (path[i][0]) + ',' + (path[i][1]); } initial = vpath.splice(0, 1); lineWidth = lineWidth === undefined ? 1 : lineWidth; stroke = lineColor === undefined ? ' stroked="false" ' : ' strokeWeight="' + lineWidth + 'px" strokeColor="' + lineColor + '" '; fill = fillColor === undefined ? ' filled="false"' : ' fillColor="' + fillColor + '" filled="true" '; closed = vpath[0] === vpath[vpath.length - 1] ? 'x ' : ''; vel = '<v:shape coordorigin="0 0" coordsize="' + this.pixelWidth + ' ' + this.pixelHeight + '" ' + ' id="jqsshape' + shapeid + '" ' + stroke + fill + ' style="position:absolute;left:0px;top:0px;height:' + this.pixelHeight + 'px;width:' + this.pixelWidth + 'px;padding:0px;margin:0px;" ' + ' path="m ' + initial + ' l ' + vpath.join(', ') + ' ' + closed + 'e">' + ' </v:shape>'; return vel; }, _drawCircle: function (shapeid, x, y, radius, lineColor, fillColor, lineWidth) { var stroke, fill, vel; x -= radius; y -= radius; stroke = lineColor === undefined ? ' stroked="false" ' : ' strokeWeight="' + lineWidth + 'px" strokeColor="' + lineColor + '" '; fill = fillColor === undefined ? ' filled="false"' : ' fillColor="' + fillColor + '" filled="true" '; vel = '<v:oval ' + ' id="jqsshape' + shapeid + '" ' + stroke + fill + ' style="position:absolute;top:' + y + 'px; left:' + x + 'px; width:' + (radius * 2) + 'px; height:' + (radius * 2) + 'px"></v:oval>'; return vel; }, _drawPieSlice: function (shapeid, x, y, radius, startAngle, endAngle, lineColor, fillColor) { var vpath, startx, starty, endx, endy, stroke, fill, vel; if (startAngle === endAngle) { return ''; // VML seems to have problem when start angle equals end angle. } if ((endAngle - startAngle) === (2 * Math.PI)) { startAngle = 0.0; // VML seems to have a problem when drawing a full circle that doesn't start 0 endAngle = (2 * Math.PI); } startx = x + Math.round(Math.cos(startAngle) * radius); starty = y + Math.round(Math.sin(startAngle) * radius); endx = x + Math.round(Math.cos(endAngle) * radius); endy = y + Math.round(Math.sin(endAngle) * radius); if (startx === endx && starty === endy) { if ((endAngle - startAngle) < Math.PI) { // Prevent very small slices from being mistaken as a whole pie return ''; } // essentially going to be the entire circle, so ignore startAngle startx = endx = x + radius; starty = endy = y; } if (startx === endx && starty === endy && (endAngle - startAngle) < Math.PI) { return ''; } vpath = [x - radius, y - radius, x + radius, y + radius, startx, starty, endx, endy]; stroke = lineColor === undefined ? ' stroked="false" ' : ' strokeWeight="1px" strokeColor="' + lineColor + '" '; fill = fillColor === undefined ? ' filled="false"' : ' fillColor="' + fillColor + '" filled="true" '; vel = '<v:shape coordorigin="0 0" coordsize="' + this.pixelWidth + ' ' + this.pixelHeight + '" ' + ' id="jqsshape' + shapeid + '" ' + stroke + fill + ' style="position:absolute;left:0px;top:0px;height:' + this.pixelHeight + 'px;width:' + this.pixelWidth + 'px;padding:0px;margin:0px;" ' + ' path="m ' + x + ',' + y + ' wa ' + vpath.join(', ') + ' x e">' + ' </v:shape>'; return vel; }, _drawRect: function (shapeid, x, y, width, height, lineColor, fillColor) { return this._drawShape(shapeid, [[x, y], [x, y + height], [x + width, y + height], [x + width, y], [x, y]], lineColor, fillColor); }, reset: function () { this.group.innerHTML = ''; }, appendShape: function (shape) { var vel = this['_draw' + shape.type].apply(this, shape.args); if (this.rendered) { this.group.insertAdjacentHTML('beforeEnd', vel); } else { this.prerender += vel; } this.lastShapeId = shape.id; return shape.id; }, replaceWithShape: function (shapeid, shape) { var existing = $('#jqsshape' + shapeid), vel = this['_draw' + shape.type].apply(this, shape.args); existing[0].outerHTML = vel; }, replaceWithShapes: function (shapeids, shapes) { // replace the first shapeid with all the new shapes then toast the remaining old shapes var existing = $('#jqsshape' + shapeids[0]), replace = '', slen = shapes.length, i; for (i = 0; i < slen; i++) { replace += this['_draw' + shapes[i].type].apply(this, shapes[i].args); } existing[0].outerHTML = replace; for (i = 1; i < shapeids.length; i++) { $('#jqsshape' + shapeids[i]).remove(); } }, insertAfterShape: function (shapeid, shape) { var existing = $('#jqsshape' + shapeid), vel = this['_draw' + shape.type].apply(this, shape.args); existing[0].insertAdjacentHTML('afterEnd', vel); }, removeShapeId: function (shapeid) { var existing = $('#jqsshape' + shapeid); this.group.removeChild(existing[0]); }, getShapeAt: function (el, x, y) { var shapeid = el.id.substr(8); return shapeid; }, render: function () { if (!this.rendered) { // batch the intial render into a single repaint this.group.innerHTML = this.prerender; this.rendered = true; } } }); }))}(document, Math));
JavaScript
var TRACKING = { contextPath : '/tracker/', eventStack : new Array(), createEvent : function(type, payload, reference) { var event = new Object(); if (!type || type == null || type == "") throw new NullPointerException('type'); event.type = type; event.payload = payload; event.reference = reference; event.time = new Date(); event.HTMLSender = this.getHTMLSender(); event.session = this.getSession(); TRACKING.eventStack[this.eventStack.length] = event; return event; }, getHTMLSender : function() { var sender = new Object(); sender.secure = location.protocol == 'https:'; sender.hostName = location.host; sender.uri = location.pathname; sender.parameters = location.search; return sender; }, getSession : function() { var session = getCookie('tr_cookie'); if (session == undefined) { session = TRACKING.generateSession(); setCookie('tr_cookie', session, 14); } return session; }, generateSession : function() { var req = new XMLHttpRequest(); var r; req.open('GET', this.contextPath + 'CreateSession', false); req.send(); r = req.responseText; return r; }, convertEventToXML : function(event) { xmlBody = '<Event>'; xmlBody += '<Type><EventName>' + event.type + '</EventName></Type>'; xmlBody += '<HTMLSender>'; xmlBody += '<Secure>' + event.HTMLSender.secure + '</Secure>'; xmlBody += '<HostName>' + event.HTMLSender.hostName + '</HostName>'; xmlBody += '<URL>' + event.HTMLSender.uri + '</URL>'; xmlBody += '<Parameters>' + escape(event.HTMLSender.parameters) + '</Parameters>'; xmlBody += '</HTMLSender>'; xmlBody += '<Session><TokenID>' + event.session + '</TokenID></Session>'; xmlBody += '<Payload>' + escape(event.payload) + '</Payload>'; // 2006-08-29T01:18:15.001Z xmlBody += '<Time>' + event.time.getFullYear() + '-'; xmlBody += (((event.time.getMonth() + 1) + '').length == 1 ? '0' + (event.time.getMonth() + 1) : (event.time.getMonth() + 1)) + '-'; xmlBody += ((event.time.getDate() + '').length == 1 ? '0' + event.time.getDate() : event.time.getDate()) + 'T'; xmlBody += ((event.time.getHours() + '').length == 1 ? '0' + event.time.getDate() : event.time.getDate()) + ':'; xmlBody += event.time.getMinutes() + ':'; xmlBody += event.time.getSeconds() + '.'; xmlBody += event.time.getMilliseconds() + '</Time>'; // xmlBody += '<Reference>' + event.reference + '</Reference>'; xmlBody += '</Event>'; return xmlBody; }, commit : function() { if (this.retroUnload != undefined) this.retroUnload(); var xmlBody = '<?xml version="1.0"?>'; xmlBody += '<Events xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://' + location.hostname + ':' + location.port + TRACKING.contextPath + 'EventSchemaV3.xsd">'; for (i = 0; i < TRACKING.eventStack.length; i++) { xmlBody += TRACKING.convertEventToXML(TRACKING.eventStack[i]); } TRACKING.eventStack = new Array(); xmlBody += '</Events>'; var req = new XMLHttpRequest(); req.open('POST', TRACKING.contextPath + 'Submit', true); req.setRequestHeader("Content-type", "text/xml"); req.send(xmlBody); } }; // Source http://www.w3schools.com/js/js_cookies.asp // TODO: replace this. function getCookie(c_name) { var i, x, y, ARRcookies = document.cookie.split(";"); for (i = 0; i < ARRcookies.length; i++) { x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("=")); y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1); x = x.replace(/^\s+|\s+$/g, ""); if (x == c_name) return unescape(y); } }; function setCookie(c_name, value, exdays) { var exdate = new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString()); document.cookie = c_name + "=" + c_value; }; // End borrowed code. // TODO: add routine updates TRACKING.retroUnload = window.onbeforeunload; window.onbeforeunload = TRACKING.commit;
JavaScript
var TRACKING = { contextPath : '/tracker/', eventStack : new Array(), createEvent : function(type, payload, reference) { var event = new Object(); if (!type || type == null || type == "") throw new NullPointerException('type'); event.type = type; event.payload = payload; event.reference = reference; event.time = new Date(); event.HTMLSender = this.getHTMLSender(); event.session = this.getSession(); TRACKING.eventStack[this.eventStack.length] = event; return event; }, getHTMLSender : function() { var sender = new Object(); sender.secure = location.protocol == 'https:'; sender.hostName = location.host; sender.uri = location.pathname; sender.parameters = location.search; return sender; }, getSession : function() { var session = getCookie('tr_cookie'); if (session == undefined) { session = TRACKING.generateSession(); setCookie('tr_cookie', session, 14); } return session; }, generateSession : function() { var req = new XMLHttpRequest(); var r; req.open('GET', this.contextPath + 'CreateSession', false); req.send(); r = req.responseText; return r; }, convertEventToXML : function(event) { xmlBody = '<Event>\n'; xmlBody += ' <Type><EventName>' + event.type + '</EventName></Type>\n'; xmlBody += ' <HTMLSender>\n'; xmlBody += ' <Secure>' + event.HTMLSender.secure + '</Secure>\n'; xmlBody += ' <HostName>' + event.HTMLSender.hostName + '</HostName>\n'; xmlBody += ' <URL>' + event.HTMLSender.uri + '</URL>\n'; xmlBody += ' <Parameters>' + escape(event.HTMLSender.parameters) + '</Parameters>\n'; xmlBody += ' </HTMLSender>\n'; xmlBody += ' <Session><TokenID>' + event.session + '</TokenID></Session>\n'; xmlBody += ' <Payload>' + escape(event.payload) + '</Payload>\n'; // 2006-08-29T01:18:15.001Z xmlBody += ' <Time>' + event.time.getFullYear() + '-'; xmlBody += (((event.time.getMonth() + 1) + '').length == 1 ? '0' + (event.time.getMonth() + 1) : (event.time.getMonth() + 1)) + '-'; xmlBody += ((event.time.getDate() + '').length == 1 ? '0' + event.time.getDate() : event.time.getDate()) + 'T'; xmlBody += ((event.time.getHours() + '').length == 1 ? '0' + event.time.getDate() : event.time.getDate()) + ':'; xmlBody += event.time.getMinutes() + ':'; xmlBody += event.time.getSeconds() + '.'; xmlBody += event.time.getMilliseconds() + '</Time>\n'; // xmlBody += '<Reference>' + event.reference + '</Reference>'; xmlBody += '</Event>\n'; return xmlBody; }, commit : function() { if (this.retroUnload != undefined) this.retroUnload(); var xmlBody = '<?xml version="1.0"?>\n'; xmlBody += '<Events xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://' + location.hostname + ':' + location.port + TRACKING.contextPath + 'EventSchemaV3.xsd">'; for (i = 0; i < TRACKING.eventStack.length; i++) { xmlBody += TRACKING.convertEventToXML(TRACKING.eventStack[i]); } TRACKING.eventStack = new Array(); xmlBody += '</Events>'; var req = new XMLHttpRequest(); req.open('POST', TRACKING.contextPath + 'submit', true); req.setRequestHeader("Content-type", "text/xml"); req.send(xmlBody); } }; // Source http://www.w3schools.com/js/js_cookies.asp // TODO: replace this. function getCookie(c_name) { var i, x, y, ARRcookies = document.cookie.split(";"); for (i = 0; i < ARRcookies.length; i++) { x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("=")); y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1); x = x.replace(/^\s+|\s+$/g, ""); if (x == c_name) return unescape(y); } }; function setCookie(c_name, value, exdays) { var exdate = new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString()); document.cookie = c_name + "=" + c_value; }; // End borrowed code. // TODO: add routine updates TRACKING.retroUnload = window.onbeforeunload; window.onbeforeunload = TRACKING.commit;
JavaScript
function toggleVisibility(linkObj) { var base = $(linkObj).attr('id'); var summary = $('#'+base+'-summary'); var content = $('#'+base+'-content'); var trigger = $('#'+base+'-trigger'); var src=$(trigger).attr('src'); if (content.is(':visible')===true) { content.hide(); summary.show(); $(linkObj).addClass('closed').removeClass('opened'); $(trigger).attr('src',src.substring(0,src.length-8)+'closed.png'); } else { content.show(); summary.hide(); $(linkObj).removeClass('closed').addClass('opened'); $(trigger).attr('src',src.substring(0,src.length-10)+'open.png'); } return false; } function updateStripes() { $('table.directory tr'). removeClass('even').filter(':visible:even').addClass('even'); } function toggleLevel(level) { $('table.directory tr').each(function() { var l = this.id.split('_').length-1; var i = $('#img'+this.id.substring(3)); var a = $('#arr'+this.id.substring(3)); if (l<level+1) { i.removeClass('iconfopen iconfclosed').addClass('iconfopen'); a.html('&#9660;'); $(this).show(); } else if (l==level+1) { i.removeClass('iconfclosed iconfopen').addClass('iconfclosed'); a.html('&#9658;'); $(this).show(); } else { $(this).hide(); } }); updateStripes(); } function toggleFolder(id) { // the clicked row var currentRow = $('#row_'+id); // all rows after the clicked row var rows = currentRow.nextAll("tr"); var re = new RegExp('^row_'+id+'\\d+_$', "i"); //only one sub // only match elements AFTER this one (can't hide elements before) var childRows = rows.filter(function() { return this.id.match(re); }); // first row is visible we are HIDING if (childRows.filter(':first').is(':visible')===true) { // replace down arrow by right arrow for current row var currentRowSpans = currentRow.find("span"); currentRowSpans.filter(".iconfopen").removeClass("iconfopen").addClass("iconfclosed"); currentRowSpans.filter(".arrow").html('&#9658;'); rows.filter("[id^=row_"+id+"]").hide(); // hide all children } else { // we are SHOWING // replace right arrow by down arrow for current row var currentRowSpans = currentRow.find("span"); currentRowSpans.filter(".iconfclosed").removeClass("iconfclosed").addClass("iconfopen"); currentRowSpans.filter(".arrow").html('&#9660;'); // replace down arrows by right arrows for child rows var childRowsSpans = childRows.find("span"); childRowsSpans.filter(".iconfopen").removeClass("iconfopen").addClass("iconfclosed"); childRowsSpans.filter(".arrow").html('&#9658;'); childRows.show(); //show all children } updateStripes(); } function toggleInherit(id) { var rows = $('tr.inherit.'+id); var img = $('tr.inherit_header.'+id+' img'); var src = $(img).attr('src'); if (rows.filter(':first').is(':visible')===true) { rows.css('display','none'); $(img).attr('src',src.substring(0,src.length-8)+'closed.png'); } else { rows.css('display','table-row'); // using show() causes jump in firefox $(img).attr('src',src.substring(0,src.length-10)+'open.png'); } }
JavaScript
 /** * @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * This file was added automatically by CKEditor builder. * You may re-use it at any time at http://ckeditor.com/builder to build CKEditor again. * * NOTE: * This file is not used by CKEditor, you may remove it. * Changing this file will not change your CKEditor configuration. */ var CKBUILDER_CONFIG = { skin: 'moono', preset: 'standard', ignore: [ 'dev', '.gitignore', '.gitattributes', 'README.md', '.mailmap' ], plugins : { 'about' : 1, 'a11yhelp' : 1, 'basicstyles' : 1, 'blockquote' : 1, 'clipboard' : 1, 'contextmenu' : 1, 'resize' : 1, 'toolbar' : 1, 'elementspath' : 1, 'enterkey' : 1, 'entities' : 1, 'filebrowser' : 1, 'floatingspace' : 1, 'format' : 1, 'htmlwriter' : 1, 'horizontalrule' : 1, 'wysiwygarea' : 1, 'image' : 1, 'indent' : 1, 'link' : 1, 'list' : 1, 'magicline' : 1, 'maximize' : 1, 'pastetext' : 1, 'pastefromword' : 1, 'removeformat' : 1, 'sourcearea' : 1, 'specialchar' : 1, 'scayt' : 1, 'stylescombo' : 1, 'tab' : 1, 'table' : 1, 'tabletools' : 1, 'undo' : 1, 'wsc' : 1, 'dialog' : 1, 'dialogui' : 1, 'menu' : 1, 'floatpanel' : 1, 'panel' : 1, 'button' : 1, 'popup' : 1, 'richcombo' : 1, 'listblock' : 1, 'fakeobjects' : 1, 'menubutton' : 1 }, languages : { 'af' : 1, 'ar' : 1, 'eu' : 1, 'bn' : 1, 'bs' : 1, 'bg' : 1, 'ca' : 1, 'zh-cn' : 1, 'zh' : 1, 'hr' : 1, 'cs' : 1, 'da' : 1, 'nl' : 1, 'en' : 1, 'en-au' : 1, 'en-ca' : 1, 'en-gb' : 1, 'eo' : 1, 'et' : 1, 'fo' : 1, 'fi' : 1, 'fr' : 1, 'fr-ca' : 1, 'gl' : 1, 'ka' : 1, 'de' : 1, 'el' : 1, 'gu' : 1, 'he' : 1, 'hi' : 1, 'hu' : 1, 'is' : 1, 'it' : 1, 'ja' : 1, 'km' : 1, 'ko' : 1, 'ku' : 1, 'lv' : 1, 'lt' : 1, 'mk' : 1, 'ms' : 1, 'mn' : 1, 'no' : 1, 'nb' : 1, 'fa' : 1, 'pl' : 1, 'pt-br' : 1, 'pt' : 1, 'ro' : 1, 'ru' : 1, 'sr' : 1, 'sr-latn' : 1, 'sk' : 1, 'sl' : 1, 'es' : 1, 'sv' : 1, 'th' : 1, 'tr' : 1, 'ug' : 1, 'uk' : 1, 'vi' : 1, 'cy' : 1, } };
JavaScript
/** * @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ /** * @fileOverview The "filebrowser" plugin that adds support for file uploads and * browsing. * * When a file is uploaded or selected inside the file browser, its URL is * inserted automatically into a field defined in the <code>filebrowser</code> * attribute. In order to specify a field that should be updated, pass the tab ID and * the element ID, separated with a colon.<br /><br /> * * <strong>Example 1: (Browse)</strong> * * <pre> * { * type : 'button', * id : 'browse', * filebrowser : 'tabId:elementId', * label : editor.lang.common.browseServer * } * </pre> * * If you set the <code>filebrowser</code> attribute for an element other than * the <code>fileButton</code>, the <code>Browse</code> action will be triggered.<br /><br /> * * <strong>Example 2: (Quick Upload)</strong> * * <pre> * { * type : 'fileButton', * id : 'uploadButton', * filebrowser : 'tabId:elementId', * label : editor.lang.common.uploadSubmit, * 'for' : [ 'upload', 'upload' ] * } * </pre> * * If you set the <code>filebrowser</code> attribute for a <code>fileButton</code> * element, the <code>QuickUpload</code> action will be executed.<br /><br /> * * The filebrowser plugin also supports more advanced configuration performed through * a JavaScript object. * * The following settings are supported: * * <ul> * <li><code>action</code> &ndash; <code>Browse</code> or <code>QuickUpload</code>.</li> * <li><code>target</code> &ndash; the field to update in the <code><em>tabId:elementId</em></code> format.</li> * <li><code>params</code> &ndash; additional arguments to be passed to the server connector (optional).</li> * <li><code>onSelect</code> &ndash; a function to execute when the file is selected/uploaded (optional).</li> * <li><code>url</code> &ndash; the URL to be called (optional).</li> * </ul> * * <strong>Example 3: (Quick Upload)</strong> * * <pre> * { * type : 'fileButton', * label : editor.lang.common.uploadSubmit, * id : 'buttonId', * filebrowser : * { * action : 'QuickUpload', // required * target : 'tab1:elementId', // required * params : // optional * { * type : 'Files', * currentFolder : '/folder/' * }, * onSelect : function( fileUrl, errorMessage ) // optional * { * // Do not call the built-in selectFuntion. * // return false; * } * }, * 'for' : [ 'tab1', 'myFile' ] * } * </pre> * * Suppose you have a file element with an ID of <code>myFile</code>, a text * field with an ID of <code>elementId</code> and a <code>fileButton</code>. * If the <code>filebowser.url</code> attribute is not specified explicitly, * the form action will be set to <code>filebrowser[<em>DialogWindowName</em>]UploadUrl</code> * or, if not specified, to <code>filebrowserUploadUrl</code>. Additional parameters * from the <code>params</code> object will be added to the query string. It is * possible to create your own <code>uploadHandler</code> and cancel the built-in * <code>updateTargetElement</code> command.<br /><br /> * * <strong>Example 4: (Browse)</strong> * * <pre> * { * type : 'button', * id : 'buttonId', * label : editor.lang.common.browseServer, * filebrowser : * { * action : 'Browse', * url : '/ckfinder/ckfinder.html&amp;type=Images', * target : 'tab1:elementId' * } * } * </pre> * * In this example, when the button is pressed, the file browser will be opened in a * popup window. If you do not specify the <code>filebrowser.url</code> attribute, * <code>filebrowser[<em>DialogName</em>]BrowseUrl</code> or * <code>filebrowserBrowseUrl</code> will be used. After selecting a file in the file * browser, an element with an ID of <code>elementId</code> will be updated. Just * like in the third example, a custom <code>onSelect</code> function may be defined. */ (function() { // Adds (additional) arguments to given url. // // @param {String} // url The url. // @param {Object} // params Additional parameters. function addQueryString( url, params ) { var queryString = []; if ( !params ) return url; else { for ( var i in params ) queryString.push( i + "=" + encodeURIComponent( params[ i ] ) ); } return url + ( ( url.indexOf( "?" ) != -1 ) ? "&" : "?" ) + queryString.join( "&" ); } // Make a string's first character uppercase. // // @param {String} // str String. function ucFirst( str ) { str += ''; var f = str.charAt( 0 ).toUpperCase(); return f + str.substr( 1 ); } // The onlick function assigned to the 'Browse Server' button. Opens the // file browser and updates target field when file is selected. // // @param {CKEDITOR.event} // evt The event object. function browseServer( evt ) { var dialog = this.getDialog(); var editor = dialog.getParentEditor(); editor._.filebrowserSe = this; var width = editor.config[ 'filebrowser' + ucFirst( dialog.getName() ) + 'WindowWidth' ] || editor.config.filebrowserWindowWidth || '80%'; var height = editor.config[ 'filebrowser' + ucFirst( dialog.getName() ) + 'WindowHeight' ] || editor.config.filebrowserWindowHeight || '70%'; var params = this.filebrowser.params || {}; params.CKEditor = editor.name; params.CKEditorFuncNum = editor._.filebrowserFn; if ( !params.langCode ) params.langCode = editor.langCode; var url = addQueryString( this.filebrowser.url, params ); // TODO: V4: Remove backward compatibility (#8163). editor.popup( url, width, height, editor.config.filebrowserWindowFeatures || editor.config.fileBrowserWindowFeatures ); } // The onlick function assigned to the 'Upload' button. Makes the final // decision whether form is really submitted and updates target field when // file is uploaded. // // @param {CKEDITOR.event} // evt The event object. function uploadFile( evt ) { var dialog = this.getDialog(); var editor = dialog.getParentEditor(); editor._.filebrowserSe = this; // If user didn't select the file, stop the upload. if ( !dialog.getContentElement( this[ 'for' ][ 0 ], this[ 'for' ][ 1 ] ).getInputElement().$.value ) return false; if ( !dialog.getContentElement( this[ 'for' ][ 0 ], this[ 'for' ][ 1 ] ).getAction() ) return false; return true; } // Setups the file element. // // @param {CKEDITOR.ui.dialog.file} // fileInput The file element used during file upload. // @param {Object} // filebrowser Object containing filebrowser settings assigned to // the fileButton associated with this file element. function setupFileElement( editor, fileInput, filebrowser ) { var params = filebrowser.params || {}; params.CKEditor = editor.name; params.CKEditorFuncNum = editor._.filebrowserFn; if ( !params.langCode ) params.langCode = editor.langCode; fileInput.action = addQueryString( filebrowser.url, params ); fileInput.filebrowser = filebrowser; } // Traverse through the content definition and attach filebrowser to // elements with 'filebrowser' attribute. // // @param String // dialogName Dialog name. // @param {CKEDITOR.dialog.definitionObject} // definition Dialog definition. // @param {Array} // elements Array of {@link CKEDITOR.dialog.definition.content} // objects. function attachFileBrowser( editor, dialogName, definition, elements ) { if ( !elements || !elements.length ) return; var element, fileInput; for ( var i = elements.length; i--; ) { element = elements[ i ]; if ( element.type == 'hbox' || element.type == 'vbox' || element.type == 'fieldset' ) attachFileBrowser( editor, dialogName, definition, element.children ); if ( !element.filebrowser ) continue; if ( typeof element.filebrowser == 'string' ) { var fb = { action: ( element.type == 'fileButton' ) ? 'QuickUpload' : 'Browse', target: element.filebrowser }; element.filebrowser = fb; } if ( element.filebrowser.action == 'Browse' ) { var url = element.filebrowser.url; if ( url === undefined ) { url = editor.config[ 'filebrowser' + ucFirst( dialogName ) + 'BrowseUrl' ]; if ( url === undefined ) url = editor.config.filebrowserBrowseUrl; } if ( url ) { element.onClick = browseServer; element.filebrowser.url = url; element.hidden = false; } } else if ( element.filebrowser.action == 'QuickUpload' && element[ 'for' ] ) { url = element.filebrowser.url; if ( url === undefined ) { url = editor.config[ 'filebrowser' + ucFirst( dialogName ) + 'UploadUrl' ]; if ( url === undefined ) url = editor.config.filebrowserUploadUrl; } if ( url ) { var onClick = element.onClick; element.onClick = function( evt ) { // "element" here means the definition object, so we need to find the correct // button to scope the event call var sender = evt.sender; if ( onClick && onClick.call( sender, evt ) === false ) return false; return uploadFile.call( sender, evt ); }; element.filebrowser.url = url; element.hidden = false; setupFileElement( editor, definition.getContents( element[ 'for' ][ 0 ] ).get( element[ 'for' ][ 1 ] ), element.filebrowser ); } } } } // Updates the target element with the url of uploaded/selected file. // // @param {String} // url The url of a file. function updateTargetElement( url, sourceElement ) { var dialog = sourceElement.getDialog(); var targetElement = sourceElement.filebrowser.target || null; // If there is a reference to targetElement, update it. if ( targetElement ) { var target = targetElement.split( ':' ); var element = dialog.getContentElement( target[ 0 ], target[ 1 ] ); if ( element ) { element.setValue( url ); dialog.selectPage( target[ 0 ] ); } } } // Returns true if filebrowser is configured in one of the elements. // // @param {CKEDITOR.dialog.definitionObject} // definition Dialog definition. // @param String // tabId The tab id where element(s) can be found. // @param String // elementId The element id (or ids, separated with a semicolon) to check. function isConfigured( definition, tabId, elementId ) { if ( elementId.indexOf( ";" ) !== -1 ) { var ids = elementId.split( ";" ); for ( var i = 0; i < ids.length; i++ ) { if ( isConfigured( definition, tabId, ids[ i ] ) ) return true; } return false; } var elementFileBrowser = definition.getContents( tabId ).get( elementId ).filebrowser; return ( elementFileBrowser && elementFileBrowser.url ); } function setUrl( fileUrl, data ) { var dialog = this._.filebrowserSe.getDialog(), targetInput = this._.filebrowserSe[ 'for' ], onSelect = this._.filebrowserSe.filebrowser.onSelect; if ( targetInput ) dialog.getContentElement( targetInput[ 0 ], targetInput[ 1 ] ).reset(); if ( typeof data == 'function' && data.call( this._.filebrowserSe ) === false ) return; if ( onSelect && onSelect.call( this._.filebrowserSe, fileUrl, data ) === false ) return; // The "data" argument may be used to pass the error message to the editor. if ( typeof data == 'string' && data ) alert( data ); if ( fileUrl ) updateTargetElement( fileUrl, this._.filebrowserSe ); } CKEDITOR.plugins.add( 'filebrowser', { requires: 'popup', init: function( editor, pluginPath ) { editor._.filebrowserFn = CKEDITOR.tools.addFunction( setUrl, editor ); editor.on( 'destroy', function() { CKEDITOR.tools.removeFunction( this._.filebrowserFn ); }); } }); CKEDITOR.on( 'dialogDefinition', function( evt ) { var definition = evt.data.definition, element; // Associate filebrowser to elements with 'filebrowser' attribute. for ( var i = 0; i < definition.contents.length; ++i ) { if ( ( element = definition.contents[ i ] ) ) { attachFileBrowser( evt.editor, evt.data.name, definition, element.elements ); if ( element.hidden && element.filebrowser ) { element.hidden = !isConfigured( definition, element[ 'id' ], element.filebrowser ); } } } }); })(); /** * The location of an external file browser that should be launched when the **Browse Server** * button is pressed. If configured, the **Browse Server** button will appear in the * **Link**, **Image**, and **Flash** dialog windows. * * See the [File Browser/Uploader](http://docs.cksource.com/CKEditor_3.x/Developers_Guide/File_Browser_(Uploader\)) documentation. * * config.filebrowserBrowseUrl = '/browser/browse.php'; * * @since 3.0 * @cfg {String} [filebrowserBrowseUrl='' (empty string = disabled)] * @member CKEDITOR.config */ /** * The location of the script that handles file uploads. * If set, the **Upload** tab will appear in the **Link**, **Image**, * and **Flash** dialog windows. * * See the [File Browser/Uploader](http://docs.cksource.com/CKEditor_3.x/Developers_Guide/File_Browser_(Uploader\)) documentation. * * config.filebrowserUploadUrl = '/uploader/upload.php'; * * @since 3.0 * @cfg {String} [filebrowserUploadUrl='' (empty string = disabled)] * @member CKEDITOR.config */ /** * The location of an external file browser that should be launched when the **Browse Server** * button is pressed in the **Image** dialog window. * * If not set, CKEditor will use {@link CKEDITOR.config#filebrowserBrowseUrl}. * * config.filebrowserImageBrowseUrl = '/browser/browse.php?type=Images'; * * @since 3.0 * @cfg {String} [filebrowserImageBrowseUrl='' (empty string = disabled)] * @member CKEDITOR.config */ /** * The location of an external file browser that should be launched when the **Browse Server** * button is pressed in the **Flash** dialog window. * * If not set, CKEditor will use {@link CKEDITOR.config#filebrowserBrowseUrl}. * * config.filebrowserFlashBrowseUrl = '/browser/browse.php?type=Flash'; * * @since 3.0 * @cfg {String} [filebrowserFlashBrowseUrl='' (empty string = disabled)] * @member CKEDITOR.config */ /** * The location of the script that handles file uploads in the **Image** dialog window. * * If not set, CKEditor will use {@link CKEDITOR.config#filebrowserUploadUrl}. * * config.filebrowserImageUploadUrl = '/uploader/upload.php?type=Images'; * * @since 3.0 * @cfg {String} [filebrowserImageUploadUrl='' (empty string = disabled)] * @member CKEDITOR.config */ /** * The location of the script that handles file uploads in the **Flash** dialog window. * * If not set, CKEditor will use {@link CKEDITOR.config#filebrowserUploadUrl}. * * config.filebrowserFlashUploadUrl = '/uploader/upload.php?type=Flash'; * * @since 3.0 * @cfg {String} filebrowserFlashUploadUrl='' (empty string = disabled)] * @member CKEDITOR.config */ /** * The location of an external file browser that should be launched when the **Browse Server** * button is pressed in the **Link** tab of the **Image** dialog window. * * If not set, CKEditor will use {@link CKEDITOR.config#filebrowserBrowseUrl}. * * config.filebrowserImageBrowseLinkUrl = '/browser/browse.php'; * * @since 3.2 * @cfg {String} [filebrowserImageBrowseLinkUrl='' (empty string = disabled)] * @member CKEDITOR.config */ /** * The features to use in the file browser popup window. * * config.filebrowserWindowFeatures = 'resizable=yes,scrollbars=no'; * * @since 3.4.1 * @cfg {String} [filebrowserWindowFeatures='location=no,menubar=no,toolbar=no,dependent=yes,minimizable=no,modal=yes,alwaysRaised=yes,resizable=yes,scrollbars=yes'] * @member CKEDITOR.config */ /** * The width of the file browser popup window. It can be a number denoting a value in * pixels or a percent string. * * config.filebrowserWindowWidth = 750; * * config.filebrowserWindowWidth = '50%'; * * @cfg {Number/String} [filebrowserWindowWidth='80%'] * @member CKEDITOR.config */ /** * The height of the file browser popup window. It can be a number denoting a value in * pixels or a percent string. * * config.filebrowserWindowHeight = 580; * * config.filebrowserWindowHeight = '50%'; * * @cfg {Number/String} [filebrowserWindowHeight='70%'] * @member CKEDITOR.config */
JavaScript
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */
JavaScript
/** * @license Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. // For the complete reference: // http://docs.ckeditor.com/#!/api/CKEDITOR.config // The toolbar groups arrangement, optimized for two toolbar rows. config.toolbarGroups = [ { name: 'clipboard', groups: [ 'clipboard', 'undo' ] }, { name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ] }, { name: 'links' }, { name: 'insert' }, { name: 'forms' }, { name: 'tools' }, { name: 'document', groups: [ 'mode', 'document', 'doctools' ] }, { name: 'others' }, '/', { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] }, { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align' ] }, { name: 'styles' }, { name: 'colors' }, { name: 'about' } ]; // Remove some buttons, provided by the standard plugins, which we don't // need to have in the Standard(s) toolbar. config.removeButtons = 'Underline,Subscript,Superscript'; };
JavaScript
/** * Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.html or http://ckeditor.com/license */ // This file contains style definitions that can be used by CKEditor plugins. // // The most common use for it is the "stylescombo" plugin, which shows a combo // in the editor toolbar, containing all styles. Other plugins instead, like // the div plugin, use a subset of the styles on their feature. // // If you don't have plugins that depend on this file, you can simply ignore it. // Otherwise it is strongly recommended to customize this file to match your // website requirements and design properly. CKEDITOR.stylesSet.add( 'default', [ /* Block Styles */ // These styles are already available in the "Format" combo ("format" plugin), // so they are not needed here by default. You may enable them to avoid // placing the "Format" combo in the toolbar, maintaining the same features. /* { name: 'Paragraph', element: 'p' }, { name: 'Heading 1', element: 'h1' }, { name: 'Heading 2', element: 'h2' }, { name: 'Heading 3', element: 'h3' }, { name: 'Heading 4', element: 'h4' }, { name: 'Heading 5', element: 'h5' }, { name: 'Heading 6', element: 'h6' }, { name: 'Preformatted Text',element: 'pre' }, { name: 'Address', element: 'address' }, */ { name: 'Italic Title', element: 'h2', styles: { 'font-style': 'italic' } }, { name: 'Subtitle', element: 'h3', styles: { 'color': '#aaa', 'font-style': 'italic' } }, { name: 'Special Container', element: 'div', styles: { padding: '5px 10px', background: '#eee', border: '1px solid #ccc' } }, /* Inline Styles */ // These are core styles available as toolbar buttons. You may opt enabling // some of them in the Styles combo, removing them from the toolbar. // (This requires the "stylescombo" plugin) /* { name: 'Strong', element: 'strong', overrides: 'b' }, { name: 'Emphasis', element: 'em' , overrides: 'i' }, { name: 'Underline', element: 'u' }, { name: 'Strikethrough', element: 'strike' }, { name: 'Subscript', element: 'sub' }, { name: 'Superscript', element: 'sup' }, */ { name: 'Marker: Yellow', element: 'span', styles: { 'background-color': 'Yellow' } }, { name: 'Marker: Green', element: 'span', styles: { 'background-color': 'Lime' } }, { name: 'Big', element: 'big' }, { name: 'Small', element: 'small' }, { name: 'Typewriter', element: 'tt' }, { name: 'Computer Code', element: 'code' }, { name: 'Keyboard Phrase', element: 'kbd' }, { name: 'Sample Text', element: 'samp' }, { name: 'Variable', element: 'var' }, { name: 'Deleted Text', element: 'del' }, { name: 'Inserted Text', element: 'ins' }, { name: 'Cited Work', element: 'cite' }, { name: 'Inline Quotation', element: 'q' }, { name: 'Language: RTL', element: 'span', attributes: { 'dir': 'rtl' } }, { name: 'Language: LTR', element: 'span', attributes: { 'dir': 'ltr' } }, /* Object Styles */ { name: 'Styled image (left)', element: 'img', attributes: { 'class': 'left' } }, { name: 'Styled image (right)', element: 'img', attributes: { 'class': 'right' } }, { name: 'Compact table', element: 'table', attributes: { cellpadding: '5', cellspacing: '0', border: '1', bordercolor: '#ccc' }, styles: { 'border-collapse': 'collapse' } }, { name: 'Borderless Table', element: 'table', styles: { 'border-style': 'hidden', 'background-color': '#E6E6FA' } }, { name: 'Square Bulleted List', element: 'ul', styles: { 'list-style-type': 'square' } } ]);
JavaScript
$(document).ready(function(){ $('input[name=radio-sort]').click(function(){ var li=$(this).data('item'); $('.filters label').removeClass("btn-inverse"); $('#'+li).addClass("btn-inverse"); if(li=='ff-item-type-all'){ $('.grid li').show(300); }else{ if($(this).is(':checked')){ $('.grid li').not('.'+li).hide(300); $('.grid li.'+li).show(300); } } }); $('#full-img').click(function(){$('#previewLightbox').lightbox('hide'); }); $('.upload-btn').click(function(){ $('.uploader').show(500); }); $('.close-uploader').click(function(){ $('.uploader').hide(500); window.location.href = $('#refresh').attr('href') + '&' + new Date().getTime();; }); $('.preview').click(function(){ $('#full-img').attr('src',$(this).data('url')); if(!$(this).hasClass('disabled')) show_animation(); return true; }); $('.new-folder').click(function(){ folder_name=window.prompt($('#insert_folder_name').val(),$('#new_folder').val()); if(folder_name){ folder_path=$('#root').val()+$('#cur_dir').val()+ folder_name; folder_path_thumb=$('#cur_dir_thumb').val()+ folder_name; $.ajax({ type: "POST", url: "create_folder.php", data: {path: folder_path, path_thumb: folder_path_thumb} }).done(function( msg ) { window.location.href = $('#refresh').attr('href') + '&' + new Date().getTime(); }); } }); if (!Modernizr.touch) { $('#help').hide(); }else{ //Enable swiping... $(".box").swipe( { //Generic swipe handler for all directions swipe:function(event, direction, distance, duration, fingerCount) { //$(this).parent().toggleClass('cs-hover'); if ($(this).attr('toggle')==1) { $(this).attr('toggle',0); $(this).animate({top: "0px"} ,{queue:false,duration:300}); }else{ $(this).attr('toggle',1); $(this).animate({top: "-30px"} ,{queue:false,duration:300}); } }, //Default is 75px, set to 0 for demo so any distance triggers swipe threshold:30 }); } if(!Modernizr.csstransitions) { // Test if CSS transitions are supported $('figure').bind('mouseover',function(){ $(this).find('.box').animate({top: "-30px"} ,{queue:false,duration:300}); }); $('figure').mouseout(function(){ $(this).find('.box').animate({top: "0px"} ,{queue:false,duration:300}); }); } var boxes = $('.d'); boxes.height('auto'); var maxHeight = Math.max.apply( Math, boxes.map(function() { return $(this).height(); }).get()); boxes.height(maxHeight); }); function apply(file){ if ($('#popup').val()==1) var window_parent=window.opener; else var window_parent=window.parent; var path = $('#cur_dir').val(); var base_url = $('#base_url').val(); var track = $('#track').val(); var target = window_parent.document.getElementById(track+'_ifr'); var closed = window_parent.document.getElementsByClassName('mce-filemanager'); var ext=file.split('.').pop(); var fill=''; if($.inArray(ext, ext_img) > -1){ fill=$("<img />",{"src":path+file}); }else{ fill=$("<a />").attr("href", path+file).text(file.replace(/\..+$/, '')); } $(target).contents().find('#tinymce').append(fill); $(closed).find('.mce-close').trigger('click'); } function apply_link(file,type_file,external){ if ($('#popup').val()==1) var window_parent=window.opener; else var window_parent=window.parent; var path = $('#cur_dir').val(); var base_url = $('#base_url').val(); var track = $('#track').val(); if (external=="") { $('.mce-link_'+track, window_parent.document).val(base_url+path+file); var closed = window_parent.document.getElementsByClassName('mce-filemanager'); if($('.mce-text_'+track, window_parent.document).val()=='') $('.mce-text_'+track, window_parent.document).val(file.replace(/\..+$/, '')); $(closed).find('.mce-close').trigger('click'); }else{ var target = window_parent.document.getElementById(external); $(target).val(base_url+path+file); close_window(); } } function apply_none(file,type_file,external){ return false; } function apply_img(file,type_file,external){ if ($('#popup').val()==1) var window_parent=window.opener; else var window_parent=window.parent; var path = $('#cur_dir').val(); var base_url = $('#base_url').val(); var track = $('#track').val(); if (external=="") { var target = window_parent.document.getElementsByClassName('mce-img_'+track); var closed = window_parent.document.getElementsByClassName('mce-filemanager'); $(target).val(base_url+path+file); $(closed).find('.mce-close').trigger('click'); }else{ var target = window_parent.document.getElementById(external); $(target).val(base_url+path+file); close_window(); } } function apply_video(file,type_file,external){ if ($('#popup').val()==1) var window_parent=window.opener; else var window_parent=window.parent; var path = $('#cur_dir').val(); var base_url = $('#base_url').val(); var track = $('#track').val(); if (external=="") { var target = window_parent.document.getElementsByClassName('mce-video'+ type_file +'_'+track); var closed = window_parent.document.getElementsByClassName('mce-filemanager'); $(target).val(base_url+path+file); $(closed).find('.mce-close').trigger('click'); }else{ var target = window_parent.document.getElementById(external); $(target).val(base_url+path+file); close_window(); } } function close_window() { if ($('#popup').val()==1) window.close(); else parent.$.fancybox.close(); } function delete_file(file1,file2) { $.ajax({ type: "POST", url: "delete_file.php", data: {path: file1, path_thumb: file2} }).done(function( msg ) { }); } function delete_folder(folder1,folder2) { $.ajax({ type: "POST", url: "delete_folder.php", data: {path: folder1, path_thumb: folder2} }).done(function( msg ) { }); } function show_animation() { $('#loading_container').css('display', 'block'); $('#loading').css('opacity', '.7'); } function hide_animation() { $('#loading_container').fadeOut(); }
JavaScript
/*! * Media helper for fancyBox * version: 1.0.5 (Tue, 23 Oct 2012) * @requires fancyBox v2.0 or later * * Usage: * $(".fancybox").fancybox({ * helpers : { * media: true * } * }); * * Set custom URL parameters: * $(".fancybox").fancybox({ * helpers : { * media: { * youtube : { * params : { * autoplay : 0 * } * } * } * } * }); * * Or: * $(".fancybox").fancybox({, * helpers : { * media: true * }, * youtube : { * autoplay: 0 * } * }); * * Supports: * * Youtube * http://www.youtube.com/watch?v=opj24KnzrWo * http://www.youtube.com/embed/opj24KnzrWo * http://youtu.be/opj24KnzrWo * Vimeo * http://vimeo.com/40648169 * http://vimeo.com/channels/staffpicks/38843628 * http://vimeo.com/groups/surrealism/videos/36516384 * http://player.vimeo.com/video/45074303 * Metacafe * http://www.metacafe.com/watch/7635964/dr_seuss_the_lorax_movie_trailer/ * http://www.metacafe.com/watch/7635964/ * Dailymotion * http://www.dailymotion.com/video/xoytqh_dr-seuss-the-lorax-premiere_people * Twitvid * http://twitvid.com/QY7MD * Twitpic * http://twitpic.com/7p93st * Instagram * http://instagr.am/p/IejkuUGxQn/ * http://instagram.com/p/IejkuUGxQn/ * Google maps * http://maps.google.com/maps?q=Eiffel+Tower,+Avenue+Gustave+Eiffel,+Paris,+France&t=h&z=17 * http://maps.google.com/?ll=48.857995,2.294297&spn=0.007666,0.021136&t=m&z=16 * http://maps.google.com/?ll=48.859463,2.292626&spn=0.000965,0.002642&t=m&z=19&layer=c&cbll=48.859524,2.292532&panoid=YJ0lq28OOy3VT2IqIuVY0g&cbp=12,151.58,,0,-15.56 */ (function ($) { "use strict"; //Shortcut for fancyBox object var F = $.fancybox, format = function( url, rez, params ) { params = params || ''; if ( $.type( params ) === "object" ) { params = $.param(params, true); } $.each(rez, function(key, value) { url = url.replace( '$' + key, value || '' ); }); if (params.length) { url += ( url.indexOf('?') > 0 ? '&' : '?' ) + params; } return url; }; //Add helper object F.helpers.media = { defaults : { youtube : { matcher : /(youtube\.com|youtu\.be)\/(watch\?v=|v\/|u\/|embed\/?)?(videoseries\?list=(.*)|[\w-]{11}|\?listType=(.*)&list=(.*)).*/i, params : { autoplay : 1, autohide : 1, fs : 1, rel : 0, hd : 1, wmode : 'opaque', enablejsapi : 1 }, type : 'iframe', url : '//www.youtube.com/embed/$3' }, vimeo : { matcher : /(?:vimeo(?:pro)?.com)\/(?:[^\d]+)?(\d+)(?:.*)/, params : { autoplay : 1, hd : 1, show_title : 1, show_byline : 1, show_portrait : 0, fullscreen : 1 }, type : 'iframe', url : '//player.vimeo.com/video/$1' }, metacafe : { matcher : /metacafe.com\/(?:watch|fplayer)\/([\w\-]{1,10})/, params : { autoPlay : 'yes' }, type : 'swf', url : function( rez, params, obj ) { obj.swf.flashVars = 'playerVars=' + $.param( params, true ); return '//www.metacafe.com/fplayer/' + rez[1] + '/.swf'; } }, dailymotion : { matcher : /dailymotion.com\/video\/(.*)\/?(.*)/, params : { additionalInfos : 0, autoStart : 1 }, type : 'swf', url : '//www.dailymotion.com/swf/video/$1' }, twitvid : { matcher : /twitvid\.com\/([a-zA-Z0-9_\-\?\=]+)/i, params : { autoplay : 0 }, type : 'iframe', url : '//www.twitvid.com/embed.php?guid=$1' }, twitpic : { matcher : /twitpic\.com\/(?!(?:place|photos|events)\/)([a-zA-Z0-9\?\=\-]+)/i, type : 'image', url : '//twitpic.com/show/full/$1/' }, instagram : { matcher : /(instagr\.am|instagram\.com)\/p\/([a-zA-Z0-9_\-]+)\/?/i, type : 'image', url : '//$1/p/$2/media/' }, google_maps : { matcher : /maps\.google\.([a-z]{2,3}(\.[a-z]{2})?)\/(\?ll=|maps\?)(.*)/i, type : 'iframe', url : function( rez ) { return '//maps.google.' + rez[1] + '/' + rez[3] + '' + rez[4] + '&output=' + (rez[4].indexOf('layer=c') > 0 ? 'svembed' : 'embed'); } } }, beforeLoad : function(opts, obj) { var url = obj.href || '', type = false, what, item, rez, params; for (what in opts) { item = opts[ what ]; rez = url.match( item.matcher ); if (rez) { type = item.type; params = $.extend(true, {}, item.params, obj[ what ] || ($.isPlainObject(opts[ what ]) ? opts[ what ].params : null)); url = $.type( item.url ) === "function" ? item.url.call( this, rez, params, obj ) : format( item.url, rez, params ); break; } } if (type) { obj.href = url; obj.type = type; obj.autoHeight = false; } } }; }(jQuery));
JavaScript
/*! * Buttons helper for fancyBox * version: 1.0.5 (Mon, 15 Oct 2012) * @requires fancyBox v2.0 or later * * Usage: * $(".fancybox").fancybox({ * helpers : { * buttons: { * position : 'top' * } * } * }); * */ (function ($) { //Shortcut for fancyBox object var F = $.fancybox; //Add helper object F.helpers.buttons = { defaults : { skipSingle : false, // disables if gallery contains single image position : 'top', // 'top' or 'bottom' tpl : '<div id="fancybox-buttons"><ul><li><a class="btnPrev" title="Previous" href="javascript:;"></a></li><li><a class="btnPlay" title="Start slideshow" href="javascript:;"></a></li><li><a class="btnNext" title="Next" href="javascript:;"></a></li><li><a class="btnToggle" title="Toggle size" href="javascript:;"></a></li><li><a class="btnClose" title="Close" href="javascript:jQuery.fancybox.close();"></a></li></ul></div>' }, list : null, buttons: null, beforeLoad: function (opts, obj) { //Remove self if gallery do not have at least two items if (opts.skipSingle && obj.group.length < 2) { obj.helpers.buttons = false; obj.closeBtn = true; return; } //Increase top margin to give space for buttons obj.margin[ opts.position === 'bottom' ? 2 : 0 ] += 30; }, onPlayStart: function () { if (this.buttons) { this.buttons.play.attr('title', 'Pause slideshow').addClass('btnPlayOn'); } }, onPlayEnd: function () { if (this.buttons) { this.buttons.play.attr('title', 'Start slideshow').removeClass('btnPlayOn'); } }, afterShow: function (opts, obj) { var buttons = this.buttons; if (!buttons) { this.list = $(opts.tpl).addClass(opts.position).appendTo('body'); buttons = { prev : this.list.find('.btnPrev').click( F.prev ), next : this.list.find('.btnNext').click( F.next ), play : this.list.find('.btnPlay').click( F.play ), toggle : this.list.find('.btnToggle').click( F.toggle ) } } //Prev if (obj.index > 0 || obj.loop) { buttons.prev.removeClass('btnDisabled'); } else { buttons.prev.addClass('btnDisabled'); } //Next / Play if (obj.loop || obj.index < obj.group.length - 1) { buttons.next.removeClass('btnDisabled'); buttons.play.removeClass('btnDisabled'); } else { buttons.next.addClass('btnDisabled'); buttons.play.addClass('btnDisabled'); } this.buttons = buttons; this.onUpdate(opts, obj); }, onUpdate: function (opts, obj) { var toggle; if (!this.buttons) { return; } toggle = this.buttons.toggle.removeClass('btnDisabled btnToggleOn'); //Size toggle button if (obj.canShrink) { toggle.addClass('btnToggleOn'); } else if (!obj.canExpand) { toggle.addClass('btnDisabled'); } }, beforeClose: function () { if (this.list) { this.list.remove(); } this.list = null; this.buttons = null; } }; }(jQuery));
JavaScript
/*! * Thumbnail helper for fancyBox * version: 1.0.7 (Mon, 01 Oct 2012) * @requires fancyBox v2.0 or later * * Usage: * $(".fancybox").fancybox({ * helpers : { * thumbs: { * width : 50, * height : 50 * } * } * }); * */ (function ($) { //Shortcut for fancyBox object var F = $.fancybox; //Add helper object F.helpers.thumbs = { defaults : { width : 50, // thumbnail width height : 50, // thumbnail height position : 'bottom', // 'top' or 'bottom' source : function ( item ) { // function to obtain the URL of the thumbnail image var href; if (item.element) { href = $(item.element).find('img').attr('src'); } if (!href && item.type === 'image' && item.href) { href = item.href; } return href; } }, wrap : null, list : null, width : 0, init: function (opts, obj) { var that = this, list, thumbWidth = opts.width, thumbHeight = opts.height, thumbSource = opts.source; //Build list structure list = ''; for (var n = 0; n < obj.group.length; n++) { list += '<li><a style="width:' + thumbWidth + 'px;height:' + thumbHeight + 'px;" href="javascript:jQuery.fancybox.jumpto(' + n + ');"></a></li>'; } this.wrap = $('<div id="fancybox-thumbs"></div>').addClass(opts.position).appendTo('body'); this.list = $('<ul>' + list + '</ul>').appendTo(this.wrap); //Load each thumbnail $.each(obj.group, function (i) { var href = thumbSource( obj.group[ i ] ); if (!href) { return; } $("<img />").load(function () { var width = this.width, height = this.height, widthRatio, heightRatio, parent; if (!that.list || !width || !height) { return; } //Calculate thumbnail width/height and center it widthRatio = width / thumbWidth; heightRatio = height / thumbHeight; parent = that.list.children().eq(i).find('a'); if (widthRatio >= 1 && heightRatio >= 1) { if (widthRatio > heightRatio) { width = Math.floor(width / heightRatio); height = thumbHeight; } else { width = thumbWidth; height = Math.floor(height / widthRatio); } } $(this).css({ width : width, height : height, top : Math.floor(thumbHeight / 2 - height / 2), left : Math.floor(thumbWidth / 2 - width / 2) }); parent.width(thumbWidth).height(thumbHeight); $(this).hide().appendTo(parent).fadeIn(300); }).attr('src', href); }); //Set initial width this.width = this.list.children().eq(0).outerWidth(true); this.list.width(this.width * (obj.group.length + 1)).css('left', Math.floor($(window).width() * 0.5 - (obj.index * this.width + this.width * 0.5))); }, beforeLoad: function (opts, obj) { //Remove self if gallery do not have at least two items if (obj.group.length < 2) { obj.helpers.thumbs = false; return; } //Increase bottom margin to give space for thumbs obj.margin[ opts.position === 'top' ? 0 : 2 ] += ((opts.height) + 15); }, afterShow: function (opts, obj) { //Check if exists and create or update list if (this.list) { this.onUpdate(opts, obj); } else { this.init(opts, obj); } //Set active element this.list.children().removeClass('active').eq(obj.index).addClass('active'); }, //Center list onUpdate: function (opts, obj) { if (this.list) { this.list.stop(true).animate({ 'left': Math.floor($(window).width() * 0.5 - (obj.index * this.width + this.width * 0.5)) }, 150); } }, beforeClose: function () { if (this.wrap) { this.wrap.remove(); } this.wrap = null; this.list = null; this.width = 0; } } }(jQuery));
JavaScript
// Copyright 2010 htmldrive.net Inc. /** * @projectHomepage http://www.htmldrive.net/go/to/simple-images-scroller * @projectDescription Simple images scroller with jquery plugin * @author htmldrive.net * More script and css style : htmldrive.net * @version 1.0 * @license http://www.apache.org/licenses/LICENSE-2.0 */ (function(a){ a.fn.scroller_roll=function(p){ var p=p||{}; var g=p&&p.time_interval?p.time_interval:"100"; var h=p&&p.title_show?p.title_show:"enable"; var i=p&&p.window_background_color?p.window_background_color:"white"; var j=p&&p.window_padding?p.window_padding:"5"; var k=p&&p.border_size?p.border_size:"1"; var l=p&&p.border_color?p.border_color:"black"; var m=p&&p.images_width?p.images_width:"45"; var n=p&&p.images_height?p.images_height:"70"; var o=p&&p.title_size?p.title_size:"12"; var q=p&&p.title_color?p.title_color:"blue"; var r=p&&p.show_count?p.show_count:"5"; var i_m = p&&p.images_margin?p.images_margin:"3"; j += "px"; k += "px"; m += "px"; n += "px"; o += "px"; var s; var t=0; var u; var v; var w; var x; var y=a(this); var z=y.children("ul").children("li").length; var A=Math.ceil(z/r); if(y.find("ul").length==0||a("li").length==0){ dom.append("Require content"); return null } y.children("ul").children("li").children("a").children("img").css("width",m).css("height",n); if(h=='enable'){ y.children("ul").children("li").children("a").each(function(){ $(this).append('<br/>'+$(this).attr("title")) }) } s_s_ul(y,j,k,l,i); m=parseInt(m); y.children("ul").children("li").css("width",m+"px"); y.children("ul").children("li").css("margin-left",i_m+"px"); y.children("ul").children("li").children("a").css("color",q); y.children("ul").children("li").children("a").css("font-size",o); y.hover(function(){ stop() },function(){ play() }); begin(); play(); function begin(){ x=y.children("ul").width(); y.children("ul").children("li").hide(); y.children("ul").children("li").slice(0,r).show(); u=y.children("ul").outerWidth(); v=y.children("ul").outerHeight(); y.children("ul").width(x); y.width(u); y.height(v); y.children("ul").children("li").show(); y.css("position","relative"); y.children("ul").css("position","absolute"); y.children("ul").clone().prependTo(y); j=parseInt(j); y.children("ul").css("left","0px"); y.find("ul:last").css("left",x); w=x-i_m; } function play(){ if(parseInt(y.find("ul").eq(t).css("left"))<=-(x)){ var a=x; y.find("ul").eq(t).css("left",a); if(t==0){ t=1 }else{ t=0 } } y.find("ul").each(function(){ $(this).css("left",(parseInt($(this).css("left"))-1)+"px") }); s=setTimeout(play,g) } function stop(){ clearTimeout(s) } function s_s_ul(a,b,c,d,e){ b=parseInt(b); c=parseInt(c); var f="border: "+d+" solid "+" "+c+"px; padding:"+b+"px; background-color:"+e; a.attr("style",f) } } })(jQuery);
JavaScript
switch(mod){ case "penduduk": $('#tahun').numberbox({ min:0 }); $('#jumlah_penduduk').numberbox({ min:0, groupSeparator:',' }); $('#jumlah_pencari_kerja').numberbox({ min:0, groupSeparator:',' }); break; case "kondisi_jalan": $('#tahun').numberbox({ min:0 }); $('#panjang_jalan').numberbox({ min:0, groupSeparator:',' }); $('#baik').numberbox({ min:0, groupSeparator:',' }); $('#sedang').numberbox({ min:0, groupSeparator:',' }); $('#ringan').numberbox({ min:0, groupSeparator:',' }); $('#berat').numberbox({ min:0, groupSeparator:',' }); break; case "panjang_jalan": $('#tahun').numberbox({ min:0 }); $('#arteri').numberbox({ min:0, groupSeparator:',' }); $('#kolektor').numberbox({ min:0, groupSeparator:',' }); $('#lokal').numberbox({ min:0, groupSeparator:',' }); $('#inspeksi_kanal').numberbox({ min:0, groupSeparator:',' }); break; case "kendaraan_uji": $('#tahun').numberbox({ min:0 }); $('#penumpang').numberbox({ min:0, groupSeparator:',' }); $('#bus').numberbox({ min:0, groupSeparator:',' }); $('#truk').numberbox({ min:0, groupSeparator:',' }); $('#pick_up').numberbox({ min:0, groupSeparator:',' }); $('#khusus').numberbox({ min:0, groupSeparator:',' }); $('#tempelan').numberbox({ min:0, groupSeparator:',' }); break; case "kapal_pelayaran": $('#tahun').numberbox({ min:0 }); $('#samudra').numberbox({ min:0, groupSeparator:',' }); $('#nusantara').numberbox({ min:0, groupSeparator:',' }); $('#khusus').numberbox({ min:0, groupSeparator:',' }); $('#lokal').numberbox({ min:0, groupSeparator:',' }); break; case "kapal_tambatan": $('#tahun').numberbox({ min:0 }); $('#dermaga_umum').numberbox({ min:0, groupSeparator:',' }); $('#dermaga_khusus').numberbox({ min:0, groupSeparator:',' }); break; case "petikemas_dn": $('#tahun').numberbox({ min:0 }); $('#bongkar').numberbox({ min:0, groupSeparator:',' }); $('#muat').numberbox({ min:0, groupSeparator:',' }); break; case "petikemas_ln": $('#tahun').numberbox({ min:0 }); $('#export').numberbox({ min:0, groupSeparator:',' }); $('#import').numberbox({ min:0, groupSeparator:',' }); break; case "telp": $('#tahun').numberbox({ min:0 }); $('#pelanggan').numberbox({ min:0, groupSeparator:',' }); $('#line_service').numberbox({ min:0, groupSeparator:',' }); $('#connected_line').numberbox({ min:0, groupSeparator:',' }); break; case "headline": break; case "potensi": $('#tahun').numberbox({ min:0 }); $('#jumlah').numberbox({ min:0, groupSeparator:',' }); break; case "pdrb": $('#tahun').numberbox({ min:0 }); $('#pmdn').numberbox({ min:0, groupSeparator:',' }); $('#pma').numberbox({ min:0, groupSeparator:',' }); $('#pdrb').numberbox({ min:0, groupSeparator:',' }); break; case "ekonomi": $('#tahun').numberbox({ min:0 }); $('#pendatan_kapita').numberbox({ min:0, groupSeparator:',' }); $('#pdrb').numberbox({ min:0, groupSeparator:',' }); $('#inflasi').numberbox({ min:0, groupSeparator:',' }); break; case "berita": var today = new Date(); var dd = today.getDate(); var mm = today.getMonth()+1; //January is 0! var yyyy = today.getFullYear(); //$('#tool_vr').css('width',frmWidth-20) if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} today = yyyy+'-'+mm+'-'+dd; val_date = today; console.log(today); $('#tanggal').datebox({ required: true, formatter: formatDate } ); $('#tanggal').datebox('setValue',today); break; } $('#simpan').die(); $('#simpan').live('click',function(){ load_na('show'); if(mod=='headline' || mod=='berita' ){ tinyMCE.get("isi").save(); } submitform1('form_'+mod,function(r){ if(r==1){ $.messager.alert("Sukses","Data Tersimpan",'info'); load_na('hide'); $(tabel).datagrid('reload'); if(mod!='berita'){ window_na_close(); }else{ $('#data_na').css('display','inline');$('#form_na').css('display','none'); } } else{ console.log(r); $.messager.alert("Sukses","Data Gagal Disimpan",'error'); load_na('hide'); } }); }); $('#batal').die(); $('#batal').live('click',function(){ if(mod!='berita'){ window_na_close(); }else{ //$('#data_na').css('display','inline');$('#form_na').css('display','none'); loadUrl(this,'adminpanel/getdisplay/get_formna/berita','Manajemen Konten BeritaBerita'); } });
JavaScript
function msglogin() { $.msgBox({ title: "Warning", content: "Silahkan login terlebih dahulu.", type: "warn", buttons: [{ value: "Ok" }], success: function (result) { $("#username").focus(); } }); } tinyMCE.init({ // General options mode : "textareas", editor_selector : "thread_content", theme : "modern", skin : "lightgray", skin_variant : "red", plugins : "autolink,lists,pagebreak,layer,table,save,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,template,autosave", //plugins : "advlist,anchor,autolink,autoresize,autosave,bbcode,charmap,code,compat3x,contextmenu,directionality,emoticons,example,example_dependency,fullpage,fullscreen,hr,image,importcss,insertdatetime,layer,legacyoutput,link,lists,media,nonbreaking,noneditable,pagebreak,paste,preview,print,save,searchreplace,spellchecker,tabfocus,table,template,textcolor,visualblocks,visualchars,wordcount", // Theme options theme_advanced_buttons1 : "fullscreen,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontselect,fontsizeselect", theme_advanced_buttons2 : "bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,image,code,|,forecolor,backcolor", theme_advanced_toolbar_location : "top", theme_advanced_toolbar_align : "left", theme_advanced_statusbar_location : "bottom", theme_advanced_resizing: true, theme_advanced_resizing_use_cookie : false, // Example content CSS (should be your site CSS) content_css : "tinymce/css/content.css", // Drop lists for link/image/media/template dialogs template_external_list_url : "tinymce/lists/template_list.js", external_link_list_url : "tinymce/lists/link_list.js", external_image_list_url : "tinymce/lists/image_list.js", media_external_list_url : "tinymce/lists/media_list.js", convert_urls: false, });
JavaScript
var kolom ={}; var kolomkaku={}; var tabel = "#grid_"+mod; switch(mod){ case "penduduk": kolom[mod]=[ {field:'ck', checkbox:true}, {field:'tahun',title:'Tahun',width:150}, {field:'jumlah_penduduk',title:'Jml. Penduduk',width:250,align:'right'}, {field:'jumlah_pencari_kerja',title:'Jml. Pencari Kerja',width:200,align:'right'}, ]; judul="Data Kependudukan"; break; case "headline": kolom[mod]=[ {field:'ck', checkbox:true}, {field:'judul',title:'Judul',width:150}, {field:'isi',title:'Isi Headline',width:550,align:'left'}, ]; judul="Data Headline"; break; case "potensi": kolom[mod]=[ {field:'ck', checkbox:true}, {field:'komoditi',title:'Komoditi',width:450}, {field:'tahun',title:'Tahun',width:100,align:'center'}, {field:'jumlah',title:'Jumlah',width:100,align:'right'}, {field:'satuan',title:'Satuan',width:100,align:'center'}, ]; judul="Data Potensi"; break; case "pdrb": kolom[mod]=[ {field:'ck', checkbox:true}, {field:'tahun',title:'Tahun',width:100,align:'center'}, {field:'pmdn',title:'PMDN',width:100,align:'right'}, {field:'satuan_pmdn',title:'Satuan',width:100,align:'center'}, {field:'pma',title:'PMA',width:100,align:'right'}, {field:'satuan_pma',title:'Satuan',width:100,align:'center'}, {field:'pdrb',title:'PDRB',width:100,align:'right'}, {field:'satuan_pdrb',title:'Satuan',width:100,align:'center'}, ]; judul="Data PDRB"; break; case "ekonomi": kolom[mod]=[ {field:'ck', checkbox:true}, {field:'tahun',title:'Tahun',width:100,align:'center'}, {field:'pdrb',title:'PDRB',width:100,align:'right'}, {field:'satuan_pdrb',title:'Satuan',width:100,align:'center'}, {field:'pendatan_kapita',title:'Pendapatan PerKapita',width:150,align:'right'}, {field:'satuan_pendapatan',title:'Satuan',width:100,align:'center'}, {field:'inflasi',title:'Inflasi (%)',width:100,align:'right'}, ]; judul="Data Pertumbuhan Ekonomi"; break; case "kondisi_jalan": kolom[mod]=[ {field:'ck', checkbox:true}, {field:'tahun',title:'Tahun',width:100,align:'center'}, {field:'panjang_jalan',title:'Panjang Jalan',width:150,align:'right'}, {field:'baik',title:'Kondisi Baik',width:150,align:'right'}, {field:'sedang',title:'Kondisi Sedang',width:150,align:'right'}, {field:'ringan',title:'Kondisi Ringan',width:150,align:'right'}, {field:'berat',title:'Kondisi Rusak Berat',width:150,align:'right'}, ]; judul="Data Kondisi Jalan Kota Makassar"; break; case "panjang_jalan": kolom[mod]=[ {field:'ck', checkbox:true}, {field:'tahun',title:'Tahun',width:100,align:'center'}, {field:'arteri',title:'Arteri',width:150,align:'right'}, {field:'kolektor',title:'kolektor',width:150,align:'right'}, {field:'lokal',title:'Lokal',width:150,align:'right'}, {field:'inspeksi_kanal',title:'Inspeksi Kanal',width:150,align:'right'}, ]; judul="Data Panjang Jalan Kota Makassar"; break; case "kendaraan_uji": kolom[mod]=[ {field:'ck', checkbox:true}, {field:'tahun',title:'Tahun',width:100,align:'center'}, {field:'penumpang',title:'Kendaraan Penumpang',width:150,align:'right'}, {field:'bus',title:'Bus',width:150,align:'right'}, {field:'truk',title:'Truk',width:150,align:'right'}, {field:'pick_up',title:'Pickup',width:150,align:'right'}, {field:'khusus',title:'Kendaraan Khusus',width:150,align:'right'}, {field:'tempelan',title:'Kendaraan Tempelan',width:150,align:'right'}, ]; judul="Data Kendaraan Yang Diuji Kota Makassar"; break; case "kapal_pelayaran": kolom[mod]=[ {field:'ck', checkbox:true}, {field:'tahun',title:'Tahun',width:100,align:'center'}, {field:'samudra',title:'Samudra',width:150,align:'right'}, {field:'nusantara',title:'Nusantara',width:150,align:'right'}, {field:'khusus',title:'Khusus',width:150,align:'right'}, {field:'lokal',title:'Lokal',width:150,align:'right'}, ]; judul="Data Kunjungan Kapal Menurut Pelayaran "; break; case "kapal_tambatan": kolom[mod]=[ {field:'ck', checkbox:true}, {field:'tahun',title:'Tahun',width:100,align:'center'}, {field:'dermaga_umum',title:'Dermaga Umum',width:150,align:'right'}, {field:'dermaga_khusus',title:'Dermaga Khusus',width:150,align:'right'}, ]; judul="Data Kunjungan Kapal Menurut Jenis Tambatan "; break; case "petikemas_dn": kolom[mod]=[ {field:'ck', checkbox:true}, {field:'tahun',title:'Tahun',width:100,align:'center'}, {field:'bongkar',title:'Bongkar',width:150,align:'right'}, {field:'muat',title:'Muat',width:150,align:'right'}, ]; judul="Data Arus Petikemas Perdagangan Dalam Negeri"; break; case "petikemas_ln": kolom[mod]=[ {field:'ck', checkbox:true}, {field:'tahun',title:'Tahun',width:100,align:'center'}, {field:'export',title:'Export',width:150,align:'right'}, {field:'import',title:'Import',width:150,align:'right'}, ]; judul="Data Arus Petikemas Perdagangan Luar Negeri"; break; case "telp": kolom[mod]=[ {field:'ck', checkbox:true}, {field:'tahun',title:'Tahun',width:100,align:'center'}, {field:'pelanggan',title:'Pelanggan',width:150,align:'right'}, {field:'line_service',title:'Line Services',width:150,align:'right'}, {field:'connected_line',title:'Connected Line',width:150,align:'right'}, ]; judul="Data Sambungan Telpon Kandatel"; break; } $(tabel).datagrid({ title:judul, height:frmHeight-200, width:frmWidth-300, iconCls: 'table', rownumbers:true, // fit:true, striped:true, pagination:true, sortable:true, url:host+"adminpanel/get_data/"+mod, // fit:true, nowrap: false, singleSelect:true, frozenColumns:[ kolomkaku[mod] ], columns:[ kolom[mod] ], toolbar:[ { text:'Tambah', iconCls:'add', handler:function(){ cek_grid('add'); }, disabled:(mod=='headline' ? true : false) },'-', { text:'Edit', iconCls:'edit', handler:function(){ cek_grid('edit'); } },'-', { text:'Hapus', iconCls:'remove', handler:function(){ cek_grid('delete'); } } ], }); function cek_grid(tbl){ var w,h,t; var row = $(tabel).datagrid('getSelected'); switch(mod){ case "penduduk": w=frmWidth-800; h=frmHeight-280; t="Form Data Kependudukan"; break; case "headline": w=frmWidth-600; h=frmHeight-150; t="Form Data Headline"; break; case "potensi": t="Form Data Potensi"; break; case "pdrb": w=frmWidth-800; h=frmHeight-150; t="Form Data PDRB"; break; case "ekonomi": w=frmWidth-800; h=frmHeight-150; t="Form Data Pertumbuhan Ekonomi"; break; } if(tbl!='add'){ if(row){ if(tbl=='delete'){ $.messager.confirm('Confirm','Yakin Data Ini Akan Dihapus ?',function(r){ if (r==true){ $.post(host+'adminpanel/hapus/'+mod,{id:row.id,},function(resp){ if(resp==1){$.messager.alert("Data","Data Sudah Terhapus",'info');$(tabel).datagrid('reload');} }); } }); } else{ $.post(host+'adminpanel/get_formna/'+mod,{sts:'edit',id:row.id},function(r){ window_na(r,t,w,h); tinyMCE.init({ selector : "textarea", plugins : "pagebreak,table,code,save,insertdatetime,preview,media,searchreplace,contextmenu,paste,directionality,image", }); }); } } else{$.messager.alert("Data","Pilih Salah Satu Data",'error');} } else{ $.post(host+'adminpanel/get_formna/'+mod,{sts:'add'},function(r){ window_na(r,t,w,h); }); } }
JavaScript
// Copyright 2010 htmldrive.net Inc. /** * @projectHomepage http://www.htmldrive.net/welcome/amazon-scroller * @projectDescription Amazon style image and title scroller * @author htmldrive.net * More script and css style : htmldrive.net * @version 1.0 * @license http://www.apache.org/licenses/LICENSE-2.0 */ (function(a){ a.fn.amazon_scroller=function(p){ var p=p||{}; var g=p&&p.scroller_time_interval?p.scroller_time_interval:"3000"; var h=p&&p.scroller_title_show?p.scroller_title_show:"enable"; var i=p&&p.scroller_window_background_color?p.scroller_window_background_color:"white"; var j=p&&p.scroller_window_padding?p.scroller_window_padding:"0"; var k=p&&p.scroller_border_size?p.scroller_border_size:"1"; var l=p&&p.scroller_border_color?p.scroller_border_color:"black"; var m=p&&p.scroller_images_width?p.scroller_images_width:"70"; var n=p&&p.scroller_images_height?p.scroller_images_height:"50"; var o=p&&p.scroller_title_size?p.scroller_title_size:"12"; var q=p&&p.scroller_title_color?p.scroller_title_color:"blue"; var r=p&&p.scroller_show_count?p.scroller_show_count:"3"; var d=p&&p.directory?p.directory:"images"; j += "px"; k += "px"; m += "px"; n += "px"; o += "px"; var dom=a(this); var s; var t=0; var u; var v; var w=dom.find("ul:first").children("li").length; var x=Math.ceil(w/r); if(dom.find("ul").length==0||dom.find("li").length==0){ dom.append("Require content"); return null } dom.find("ul:first").children("li").children("a").children("img").css("width",m).css("height",n); if(h=='enable'){ dom.find("ul:first").children("li").children("a").each(function(){ $(this).append('<div class="amazon_scroller_title">'+$(this).attr("title")+'</div>') }) dom.find("ul:first").children("li").css("height",n+o+"px"); }else{ dom.find("ul:first").children("li").css("height",n+"px"); } dom.find(".amazon_scroller_title").height(parseInt(o)+"px"); s_s_ul(dom,j,k,l,i); s_s_nav(dom.find(".amazon_scroller_nav"),d); m=parseInt(m); dom.find("ul:first").children("li").css("width",m+"px"); n=parseInt(n); dom.find("ul:first").children("li").children("a").css("color",q); dom.find("ul:first").children("li").children("a").css("font-size",o); begin(); s=setTimeout(play,g); dom.find(".amazon_scroller_nav").children("li").hover( function(){ if($(this).parent().children().index($(this))==0){ $(this).css("background-position","left -50px"); }else if($(this).parent().children().index($(this))==1){ $(this).css("background-position","right -50px"); } }, function(){ if($(this).parent().children().index($(this))==0){ $(this).css("background-position","left top"); }else if($(this).parent().children().index($(this))==1){ $(this).css("background-position","right top"); } } ); dom.find(".amazon_scroller_nav").children("li").click(function(){ if($(this).parent().children().index($(this))==0){ previous() }else if($(this).parent().children().index($(this))==1){ next() } }); dom.hover( function(){ clearTimeout(s); }, function(){ s=setTimeout(play,g); } ); function begin(){ var a=dom.find("ul:first").children("li").outerWidth(true)*w; dom.find("ul:first").children("li").hide(); dom.find("ul:first").children("li").slice(0,r).show(); u=dom.find("ul:first").outerWidth(); v=dom.find("ul:first").outerHeight(); dom.find("ul:first").width(a); dom.width(u+60); dom.height(v); dom.children(".amazon_scroller_mask").width(u); dom.children(".amazon_scroller_mask").height(v); dom.find("ul:first").children("li").show(); dom.css("position","relative"); dom.find("ul:first").css("position","absolute"); dom.children(".amazon_scroller_mask").width(u); dom.children(".amazon_scroller_mask").height(v); dom.find(".amazon_scroller_nav").css('top',(v-50)/2+parseInt(j)+"px"); dom.find(".amazon_scroller_nav").width(u+60) dom.find("ul:first").clone().appendTo(dom.children(".amazon_scroller_mask")); dom.children(".amazon_scroller_mask").find("ul:last").css("left",a); } function previous(){ clearTimeout(s); if(t > 0){ t--; dom.children(".amazon_scroller_mask").find("ul").animate({ left: '+='+(m+10) },500); } } function next(){ play(); } function play(){ clearTimeout(s); t++; var a = dom.find("ul:first").children("li").outerWidth(true)*w; if(t >= w+1){ t = 0; dom.children(".amazon_scroller_mask").find("ul:first").css("left","0px"); dom.children(".amazon_scroller_mask").find("ul:last").css("left",a); s=setTimeout(play,0); }else{ dom.children(".amazon_scroller_mask").find("ul").animate({ left: '-='+(m+10) },500); s=setTimeout(play,g); } } function s_s_ul(a,b,c,d,e){ b=parseInt(b); c=parseInt(c); var f="border: "+d+" solid "+" "+c+"px; padding:"+b+"px; background-color:"+e; a.attr("style",f) } function s_s_nav(a,d){ var b=a.children("li:first"); var c=a.children("li:last"); a.children("li").css("width","18px"); a.children("li").css("height","50px"); a.children("li").css('background-image','url("'+d+'/arrow.gif")'); c.css('background-position','right top'); a.children("li").css('background-repeat','no-repeat'); c.css('right','0px'); b.css('left','0px'); } } })(jQuery);
JavaScript
var frmHeight=getClientHeight(); var frmWidth=getClientWidth(); function getClientHeight(){ var theHeight; if (window.innerHeight) { theHeight=window.innerHeight; } else if (document.documentElement && document.documentElement.clientHeight) { theHeight=document.documentElement.clientHeight; } else if (document.body) { theHeight=document.body.clientHeight; } return theHeight; } function getClientWidth(){ var theWidth; if (window.innerWidth) theWidth=window.innerWidth; else if (document.documentElement && document.documentElement.clientWidth) theWidth=document.documentElement.clientWidth; else if (document.body) theWidth=document.body.clientWidth; return theWidth; } function loadUrl(obj,url,judul,desc){ var urls=host+url; $.blockUI({ css: {backgroundColor: '#DF4E49', color: '#fff'}, message: '<h3> <img src="'+host+'assets/images/loading-oi.gif" /> Harap Tunggu...</h3>', baseZ: 10000 }); $("#page").html("").addClass("loading"); $.get(urls,function (html){ $("#page").html(html).removeClass("loading"); $('#judul_na').html(judul); $.unblockUI(); }); } function blokuinya(parcok){ if(parcok == 'add'){ $.blockUI({ css: {backgroundColor: '#DF4E49', color: '#fff'}, message: '<h3> <img src="'+host+'assets/images/loading-oi.gif" /> Harap Tunggu...</h3>', baseZ: 10000 }); }else{ $.unblockUI(); } } function submitform1(frm,func){ var url = $('#'+frm).attr("action"); //$.blockUI({ css: {backgroundColor: '#DF4E49', color: '#fff'}, message: '<h3> <img src="'+host+'assets/images/loading-oi.gif" /> Harap Tunggu...</h3>', baseZ: 10000 }); $('#'+frm).form('submit',{ url:url, onSubmit: function(){ return $(this).form('validate'); }, success:function(data){ if (func == undefined ){ if (data == "1"){ alert('Data Sudah Disimpan '); //$.unblockUI(); }else{ alert('Data Gagal Tersimpan'); //$.unblockUI(); } }else{ func(data); //$.unblockUI(); } }, error:function(data){ if (func == undefined ){ alert('Data Gagal Tersimpan'); //$.unblockUI(); }else{ func(data); //$.unblockUI(); } } }); } function submitform(frm,func){ var url = $('#'+frm).attr("action"); var a=$('#'+frm).serialize(); $.ajax({ type:'post', url:url, data:a, beforeSend:function(){ //launchpreloader(); }, complete:function(){ // stopPreloader(); }, success:function(data){ if (func == undefined ){ if (data == "1"){ pesan('Data Saved ','Success'); }else{ pesan(data,'Result'); } }else{ func(data); } }, error:function(data){ if (func == undefined ){ pesan(data,'Error'); }else{ func(data); } } }); } function bar_chart(id,data,xseries,formatnya,tickser,judul,colors,xjudul,yjudul){ //alert(formatnya); plot1 = $.jqplot(id, [data], { animate: true, // Will animate plot on calls to plot1.replot({resetAxes:true}) animateReplot: true, title: (judul == undefined ? "" : judul), seriesColors : colors, series: [{renderer:$.jqplot.BarRenderer,pointLabels: {show: true}}], axesDefaults: { tickRenderer: $.jqplot.CanvasAxisTickRenderer }, axes: { xaxis: { renderer: $.jqplot.CategoryAxisRenderer, ticks: tickser, label:(xjudul == undefined ? "" : xjudul) }, yaxis: { tickOptions: { formatString: (formatnya == undefined ? "%'d" : formatnya) }, rendererOptions: { forceTickAt0: true }, labelRenderer: $.jqplot.CanvasAxisLabelRenderer, label:(yjudul == undefined ? "" : yjudul) }, }, }); } function chart_na(id_selector,type,title,subtitle,title_y,data_x,data_y,satuan){ $('#'+id_selector).highcharts({ chart: { type: type }, title: { text: title }, subtitle: { text: subtitle }, xAxis: { categories: data_x }, yAxis: { min: 0, title: { text: title_y } }, tooltip: { headerFormat: '<span style="font-size:10px">{point.key}</span><table>', pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' + '<td style="padding:0"><b>{point.y:.1f} '+satuan+'</b></td></tr>', footerFormat: '</table>', shared: true, useHTML: true }, plotOptions: { column: { pointPadding: 0.2, borderWidth: 0 } }, series: data_y }); } function windowLoading(html,judul,width,height){ divcontainerz = "win"+Math.floor(Math.random()*9999); $("<div id="+divcontainerz+"></div>").appendTo("body"); divcontainerz = "#"+divcontainerz; $(divcontainerz).html(html); $(divcontainerz).css('padding','5px'); $(divcontainerz).window({ title:judul, width:width, height:height, autoOpen:false, modal:true, maximizable:false, resizable:false, minimizable:false, closable:false, collapsible:false }); $(divcontainerz).window('open'); } function winLoadingClose(){ $(divcontainerz).window('close'); //$(divcontainer).html(''); } function loadingna(){ windowLoading("<img src='"+host+"assets/images/loading.gif' style='position: fixed;top: 50%;left: 50%;margin-top: -10px;margin-left: -25px;'/>","Please Wait",200,100); } var container3; function window_na(html,judul,width,height){ container3 = "win"+Math.floor(Math.random()*9999); $("<div id="+container3+"></div>").appendTo("body"); container3 = "#"+container3; $(container3).html(html); $(container3).css('padding','5px'); $(container3).window({ title:judul, width:width, height:height, autoOpen:false, maximizable:false, minimizable: false, collapsible: false, resizable: false, closable:true, modal:true, onBeforeClose:function(){ $(container3).window("close",true); //$(container3).window("destroy",true); } }); $(container3).window('open'); } function window_na_close(){ $(container3).html(''); $(container3).window('close'); //$(container3).window("destroy",true); } function load_na(sts){ if(sts=='show') $('#loading-status').show(); else $('#loading-status').hide(); } function formatDate(date) { var bulan=date.getMonth() +1; var tgl=date.getDate(); if(bulan < 10){ bulan='0'+bulan; } if(tgl < 10){ tgl='0'+tgl; } return date.getFullYear() + "-" + bulan + "-" + tgl; }
JavaScript
/*! * jQuery Form Plugin * version: 3.45.0-2013.10.17 * Requires jQuery v1.5 or later * Copyright (c) 2013 M. Alsup * Examples and documentation at: http://malsup.com/jquery/form/ * Project repository: https://github.com/malsup/form * Dual licensed under the MIT and GPL licenses. * https://github.com/malsup/form#copyright-and-license */ /*global ActiveXObject */ ;(function($) { "use strict"; /* Usage Note: ----------- Do not use both ajaxSubmit and ajaxForm on the same form. These functions are mutually exclusive. Use ajaxSubmit if you want to bind your own submit handler to the form. For example, $(document).ready(function() { $('#myForm').on('submit', function(e) { e.preventDefault(); // <-- important $(this).ajaxSubmit({ target: '#output' }); }); }); Use ajaxForm when you want the plugin to manage all the event binding for you. For example, $(document).ready(function() { $('#myForm').ajaxForm({ target: '#output' }); }); You can also use ajaxForm with delegation (requires jQuery v1.7+), so the form does not have to exist when you invoke ajaxForm: $('#myForm').ajaxForm({ delegation: true, target: '#output' }); When using ajaxForm, the ajaxSubmit function will be invoked for you at the appropriate time. */ /** * Feature detection */ var feature = {}; feature.fileapi = $("<input type='file'/>").get(0).files !== undefined; feature.formdata = window.FormData !== undefined; var hasProp = !!$.fn.prop; // attr2 uses prop when it can but checks the return type for // an expected string. this accounts for the case where a form // contains inputs with names like "action" or "method"; in those // cases "prop" returns the element $.fn.attr2 = function() { if ( ! hasProp ) return this.attr.apply(this, arguments); var val = this.prop.apply(this, arguments); if ( ( val && val.jquery ) || typeof val === 'string' ) return val; return this.attr.apply(this, arguments); }; /** * ajaxSubmit() provides a mechanism for immediately submitting * an HTML form using AJAX. */ $.fn.ajaxSubmit = function(options) { /*jshint scripturl:true */ // fast fail if nothing selected (http://dev.jquery.com/ticket/2752) if (!this.length) { log('ajaxSubmit: skipping submit process - no element selected'); return this; } var method, action, url, $form = this; if (typeof options == 'function') { options = { success: options }; } else if ( options === undefined ) { options = {}; } method = options.type || this.attr2('method'); action = options.url || this.attr2('action'); url = (typeof action === 'string') ? $.trim(action) : ''; url = url || window.location.href || ''; if (url) { // clean url (don't include hash vaue) url = (url.match(/^([^#]+)/)||[])[1]; } options = $.extend(true, { url: url, success: $.ajaxSettings.success, type: method || $.ajaxSettings.type, iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank' }, options); // hook for manipulating the form data before it is extracted; // convenient for use with rich editors like tinyMCE or FCKEditor var veto = {}; this.trigger('form-pre-serialize', [this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-pre-serialize trigger'); return this; } // provide opportunity to alter form data before it is serialized if (options.beforeSerialize && options.beforeSerialize(this, options) === false) { log('ajaxSubmit: submit aborted via beforeSerialize callback'); return this; } var traditional = options.traditional; if ( traditional === undefined ) { traditional = $.ajaxSettings.traditional; } var elements = []; var qx, a = this.formToArray(options.semantic, elements); if (options.data) { options.extraData = options.data; qx = $.param(options.data, traditional); } // give pre-submit callback an opportunity to abort the submit if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) { log('ajaxSubmit: submit aborted via beforeSubmit callback'); return this; } // fire vetoable 'validate' event this.trigger('form-submit-validate', [a, this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-submit-validate trigger'); return this; } var q = $.param(a, traditional); if (qx) { q = ( q ? (q + '&' + qx) : qx ); } if (options.type.toUpperCase() == 'GET') { options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q; options.data = null; // data is null for 'get' } else { options.data = q; // data is the query string for 'post' } var callbacks = []; if (options.resetForm) { callbacks.push(function() { $form.resetForm(); }); } if (options.clearForm) { callbacks.push(function() { $form.clearForm(options.includeHidden); }); } // perform a load on the target only if dataType is not provided if (!options.dataType && options.target) { var oldSuccess = options.success || function(){}; callbacks.push(function(data) { var fn = options.replaceTarget ? 'replaceWith' : 'html'; $(options.target)[fn](data).each(oldSuccess, arguments); }); } else if (options.success) { callbacks.push(options.success); } options.success = function(data, status, xhr) { // jQuery 1.4+ passes xhr as 3rd arg var context = options.context || this ; // jQuery 1.4+ supports scope context for (var i=0, max=callbacks.length; i < max; i++) { callbacks[i].apply(context, [data, status, xhr || $form, $form]); } }; if (options.error) { var oldError = options.error; options.error = function(xhr, status, error) { var context = options.context || this; oldError.apply(context, [xhr, status, error, $form]); }; } if (options.complete) { var oldComplete = options.complete; options.complete = function(xhr, status) { var context = options.context || this; oldComplete.apply(context, [xhr, status, $form]); }; } // are there files to upload? // [value] (issue #113), also see comment: // https://github.com/malsup/form/commit/588306aedba1de01388032d5f42a60159eea9228#commitcomment-2180219 var fileInputs = $('input[type=file]:enabled', this).filter(function() { return $(this).val() !== ''; }); var hasFileInputs = fileInputs.length > 0; var mp = 'multipart/form-data'; var multipart = ($form.attr('enctype') == mp || $form.attr('encoding') == mp); var fileAPI = feature.fileapi && feature.formdata; log("fileAPI :" + fileAPI); var shouldUseFrame = (hasFileInputs || multipart) && !fileAPI; var jqxhr; // options.iframe allows user to force iframe mode // 06-NOV-09: now defaulting to iframe mode if file input is detected if (options.iframe !== false && (options.iframe || shouldUseFrame)) { // hack to fix Safari hang (thanks to Tim Molendijk for this) // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d if (options.closeKeepAlive) { $.get(options.closeKeepAlive, function() { jqxhr = fileUploadIframe(a); }); } else { jqxhr = fileUploadIframe(a); } } else if ((hasFileInputs || multipart) && fileAPI) { jqxhr = fileUploadXhr(a); } else { jqxhr = $.ajax(options); } $form.removeData('jqxhr').data('jqxhr', jqxhr); // clear element array for (var k=0; k < elements.length; k++) elements[k] = null; // fire 'notify' event this.trigger('form-submit-notify', [this, options]); return this; // utility fn for deep serialization function deepSerialize(extraData){ var serialized = $.param(extraData, options.traditional).split('&'); var len = serialized.length; var result = []; var i, part; for (i=0; i < len; i++) { // #252; undo param space replacement serialized[i] = serialized[i].replace(/\+/g,' '); part = serialized[i].split('='); // #278; use array instead of object storage, favoring array serializations result.push([decodeURIComponent(part[0]), decodeURIComponent(part[1])]); } return result; } // XMLHttpRequest Level 2 file uploads (big hat tip to francois2metz) function fileUploadXhr(a) { var formdata = new FormData(); for (var i=0; i < a.length; i++) { formdata.append(a[i].name, a[i].value); } if (options.extraData) { var serializedData = deepSerialize(options.extraData); for (i=0; i < serializedData.length; i++) if (serializedData[i]) formdata.append(serializedData[i][0], serializedData[i][1]); } options.data = null; var s = $.extend(true, {}, $.ajaxSettings, options, { contentType: false, processData: false, cache: false, type: method || 'POST' }); if (options.uploadProgress) { // workaround because jqXHR does not expose upload property s.xhr = function() { var xhr = $.ajaxSettings.xhr(); if (xhr.upload) { xhr.upload.addEventListener('progress', function(event) { var percent = 0; var position = event.loaded || event.position; /*event.position is deprecated*/ var total = event.total; if (event.lengthComputable) { percent = Math.ceil(position / total * 100); } options.uploadProgress(event, position, total, percent); }, false); } return xhr; }; } s.data = null; var beforeSend = s.beforeSend; s.beforeSend = function(xhr, o) { //Send FormData() provided by user if (options.formData) o.data = options.formData; else o.data = formdata; if(beforeSend) beforeSend.call(this, xhr, o); }; return $.ajax(s); } // private function for handling file uploads (hat tip to YAHOO!) function fileUploadIframe(a) { var form = $form[0], el, i, s, g, id, $io, io, xhr, sub, n, timedOut, timeoutHandle; var deferred = $.Deferred(); // #341 deferred.abort = function(status) { xhr.abort(status); }; if (a) { // ensure that every serialized input is still enabled for (i=0; i < elements.length; i++) { el = $(elements[i]); if ( hasProp ) el.prop('disabled', false); else el.removeAttr('disabled'); } } s = $.extend(true, {}, $.ajaxSettings, options); s.context = s.context || s; id = 'jqFormIO' + (new Date().getTime()); if (s.iframeTarget) { $io = $(s.iframeTarget); n = $io.attr2('name'); if (!n) $io.attr2('name', id); else id = n; } else { $io = $('<iframe name="' + id + '" src="'+ s.iframeSrc +'" />'); $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' }); } io = $io[0]; xhr = { // mock object aborted: 0, responseText: null, responseXML: null, status: 0, statusText: 'n/a', getAllResponseHeaders: function() {}, getResponseHeader: function() {}, setRequestHeader: function() {}, abort: function(status) { var e = (status === 'timeout' ? 'timeout' : 'aborted'); log('aborting upload... ' + e); this.aborted = 1; try { // #214, #257 if (io.contentWindow.document.execCommand) { io.contentWindow.document.execCommand('Stop'); } } catch(ignore) {} $io.attr('src', s.iframeSrc); // abort op in progress xhr.error = e; if (s.error) s.error.call(s.context, xhr, e, status); if (g) $.event.trigger("ajaxError", [xhr, s, e]); if (s.complete) s.complete.call(s.context, xhr, e); } }; g = s.global; // trigger ajax global events so that activity/block indicators work like normal if (g && 0 === $.active++) { $.event.trigger("ajaxStart"); } if (g) { $.event.trigger("ajaxSend", [xhr, s]); } if (s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false) { if (s.global) { $.active--; } deferred.reject(); return deferred; } if (xhr.aborted) { deferred.reject(); return deferred; } // add submitting element to data if we know it sub = form.clk; if (sub) { n = sub.name; if (n && !sub.disabled) { s.extraData = s.extraData || {}; s.extraData[n] = sub.value; if (sub.type == "image") { s.extraData[n+'.x'] = form.clk_x; s.extraData[n+'.y'] = form.clk_y; } } } var CLIENT_TIMEOUT_ABORT = 1; var SERVER_ABORT = 2; function getDoc(frame) { /* it looks like contentWindow or contentDocument do not * carry the protocol property in ie8, when running under ssl * frame.document is the only valid response document, since * the protocol is know but not on the other two objects. strange? * "Same origin policy" http://en.wikipedia.org/wiki/Same_origin_policy */ var doc = null; // IE8 cascading access check try { if (frame.contentWindow) { doc = frame.contentWindow.document; } } catch(err) { // IE8 access denied under ssl & missing protocol log('cannot get iframe.contentWindow document: ' + err); } if (doc) { // successful getting content return doc; } try { // simply checking may throw in ie8 under ssl or mismatched protocol doc = frame.contentDocument ? frame.contentDocument : frame.document; } catch(err) { // last attempt log('cannot get iframe.contentDocument: ' + err); doc = frame.document; } return doc; } // Rails CSRF hack (thanks to Yvan Barthelemy) var csrf_token = $('meta[name=csrf-token]').attr('content'); var csrf_param = $('meta[name=csrf-param]').attr('content'); if (csrf_param && csrf_token) { s.extraData = s.extraData || {}; s.extraData[csrf_param] = csrf_token; } // take a breath so that pending repaints get some cpu time before the upload starts function doSubmit() { // make sure form attrs are set var t = $form.attr2('target'), a = $form.attr2('action'); // update form attrs in IE friendly way form.setAttribute('target',id); if (!method || /post/i.test(method) ) { form.setAttribute('method', 'POST'); } if (a != s.url) { form.setAttribute('action', s.url); } // ie borks in some cases when setting encoding if (! s.skipEncodingOverride && (!method || /post/i.test(method))) { $form.attr({ encoding: 'multipart/form-data', enctype: 'multipart/form-data' }); } // support timout if (s.timeout) { timeoutHandle = setTimeout(function() { timedOut = true; cb(CLIENT_TIMEOUT_ABORT); }, s.timeout); } // look for server aborts function checkState() { try { var state = getDoc(io).readyState; log('state = ' + state); if (state && state.toLowerCase() == 'uninitialized') setTimeout(checkState,50); } catch(e) { log('Server abort: ' , e, ' (', e.name, ')'); cb(SERVER_ABORT); if (timeoutHandle) clearTimeout(timeoutHandle); timeoutHandle = undefined; } } // add "extra" data to form if provided in options var extraInputs = []; try { if (s.extraData) { for (var n in s.extraData) { if (s.extraData.hasOwnProperty(n)) { // if using the $.param format that allows for multiple values with the same name if($.isPlainObject(s.extraData[n]) && s.extraData[n].hasOwnProperty('name') && s.extraData[n].hasOwnProperty('value')) { extraInputs.push( $('<input type="hidden" name="'+s.extraData[n].name+'">').val(s.extraData[n].value) .appendTo(form)[0]); } else { extraInputs.push( $('<input type="hidden" name="'+n+'">').val(s.extraData[n]) .appendTo(form)[0]); } } } } if (!s.iframeTarget) { // add iframe to doc and submit the form $io.appendTo('body'); } if (io.attachEvent) io.attachEvent('onload', cb); else io.addEventListener('load', cb, false); setTimeout(checkState,15); try { form.submit(); } catch(err) { // just in case form has element with name/id of 'submit' var submitFn = document.createElement('form').submit; submitFn.apply(form); } } finally { // reset attrs and remove "extra" input elements form.setAttribute('action',a); if(t) { form.setAttribute('target', t); } else { $form.removeAttr('target'); } $(extraInputs).remove(); } } if (s.forceSync) { doSubmit(); } else { setTimeout(doSubmit, 10); // this lets dom updates render } var data, doc, domCheckCount = 50, callbackProcessed; function cb(e) { if (xhr.aborted || callbackProcessed) { return; } doc = getDoc(io); if(!doc) { log('cannot access response document'); e = SERVER_ABORT; } if (e === CLIENT_TIMEOUT_ABORT && xhr) { xhr.abort('timeout'); deferred.reject(xhr, 'timeout'); return; } else if (e == SERVER_ABORT && xhr) { xhr.abort('server abort'); deferred.reject(xhr, 'error', 'server abort'); return; } if (!doc || doc.location.href == s.iframeSrc) { // response not received yet if (!timedOut) return; } if (io.detachEvent) io.detachEvent('onload', cb); else io.removeEventListener('load', cb, false); var status = 'success', errMsg; try { if (timedOut) { throw 'timeout'; } var isXml = s.dataType == 'xml' || doc.XMLDocument || $.isXMLDoc(doc); log('isXml='+isXml); if (!isXml && window.opera && (doc.body === null || !doc.body.innerHTML)) { if (--domCheckCount) { // in some browsers (Opera) the iframe DOM is not always traversable when // the onload callback fires, so we loop a bit to accommodate log('requeing onLoad callback, DOM not available'); setTimeout(cb, 250); return; } // let this fall through because server response could be an empty document //log('Could not access iframe DOM after mutiple tries.'); //throw 'DOMException: not available'; } //log('response detected'); var docRoot = doc.body ? doc.body : doc.documentElement; xhr.responseText = docRoot ? docRoot.innerHTML : null; xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc; if (isXml) s.dataType = 'xml'; xhr.getResponseHeader = function(header){ var headers = {'content-type': s.dataType}; return headers[header.toLowerCase()]; }; // support for XHR 'status' & 'statusText' emulation : if (docRoot) { xhr.status = Number( docRoot.getAttribute('status') ) || xhr.status; xhr.statusText = docRoot.getAttribute('statusText') || xhr.statusText; } var dt = (s.dataType || '').toLowerCase(); var scr = /(json|script|text)/.test(dt); if (scr || s.textarea) { // see if user embedded response in textarea var ta = doc.getElementsByTagName('textarea')[0]; if (ta) { xhr.responseText = ta.value; // support for XHR 'status' & 'statusText' emulation : xhr.status = Number( ta.getAttribute('status') ) || xhr.status; xhr.statusText = ta.getAttribute('statusText') || xhr.statusText; } else if (scr) { // account for browsers injecting pre around json response var pre = doc.getElementsByTagName('pre')[0]; var b = doc.getElementsByTagName('body')[0]; if (pre) { xhr.responseText = pre.textContent ? pre.textContent : pre.innerText; } else if (b) { xhr.responseText = b.textContent ? b.textContent : b.innerText; } } } else if (dt == 'xml' && !xhr.responseXML && xhr.responseText) { xhr.responseXML = toXml(xhr.responseText); } try { data = httpData(xhr, dt, s); } catch (err) { status = 'parsererror'; xhr.error = errMsg = (err || status); } } catch (err) { log('error caught: ',err); status = 'error'; xhr.error = errMsg = (err || status); } if (xhr.aborted) { log('upload aborted'); status = null; } if (xhr.status) { // we've set xhr.status status = (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) ? 'success' : 'error'; } // ordering of these callbacks/triggers is odd, but that's how $.ajax does it if (status === 'success') { if (s.success) s.success.call(s.context, data, 'success', xhr); deferred.resolve(xhr.responseText, 'success', xhr); if (g) $.event.trigger("ajaxSuccess", [xhr, s]); } else if (status) { if (errMsg === undefined) errMsg = xhr.statusText; if (s.error) s.error.call(s.context, xhr, status, errMsg); deferred.reject(xhr, 'error', errMsg); if (g) $.event.trigger("ajaxError", [xhr, s, errMsg]); } if (g) $.event.trigger("ajaxComplete", [xhr, s]); if (g && ! --$.active) { $.event.trigger("ajaxStop"); } if (s.complete) s.complete.call(s.context, xhr, status); callbackProcessed = true; if (s.timeout) clearTimeout(timeoutHandle); // clean up setTimeout(function() { if (!s.iframeTarget) $io.remove(); else //adding else to clean up existing iframe response. $io.attr('src', s.iframeSrc); xhr.responseXML = null; }, 100); } var toXml = $.parseXML || function(s, doc) { // use parseXML if available (jQuery 1.5+) if (window.ActiveXObject) { doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = 'false'; doc.loadXML(s); } else { doc = (new DOMParser()).parseFromString(s, 'text/xml'); } return (doc && doc.documentElement && doc.documentElement.nodeName != 'parsererror') ? doc : null; }; var parseJSON = $.parseJSON || function(s) { /*jslint evil:true */ return window['eval']('(' + s + ')'); }; var httpData = function( xhr, type, s ) { // mostly lifted from jq1.4.4 var ct = xhr.getResponseHeader('content-type') || '', xml = type === 'xml' || !type && ct.indexOf('xml') >= 0, data = xml ? xhr.responseXML : xhr.responseText; if (xml && data.documentElement.nodeName === 'parsererror') { if ($.error) $.error('parsererror'); } if (s && s.dataFilter) { data = s.dataFilter(data, type); } if (typeof data === 'string') { if (type === 'json' || !type && ct.indexOf('json') >= 0) { data = parseJSON(data); } else if (type === "script" || !type && ct.indexOf("javascript") >= 0) { $.globalEval(data); } } return data; }; return deferred; } }; /** * ajaxForm() provides a mechanism for fully automating form submission. * * The advantages of using this method instead of ajaxSubmit() are: * * 1: This method will include coordinates for <input type="image" /> elements (if the element * is used to submit the form). * 2. This method will include the submit element's name/value data (for the element that was * used to submit the form). * 3. This method binds the submit() method to the form for you. * * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely * passes the options argument along after properly binding events for submit elements and * the form itself. */ $.fn.ajaxForm = function(options) { options = options || {}; options.delegation = options.delegation && $.isFunction($.fn.on); // in jQuery 1.3+ we can fix mistakes with the ready state if (!options.delegation && this.length === 0) { var o = { s: this.selector, c: this.context }; if (!$.isReady && o.s) { log('DOM not ready, queuing ajaxForm'); $(function() { $(o.s,o.c).ajaxForm(options); }); return this; } // is your DOM ready? http://docs.jquery.com/Tutorials:Introducing_$(document).ready() log('terminating; zero elements found by selector' + ($.isReady ? '' : ' (DOM not ready)')); return this; } if ( options.delegation ) { $(document) .off('submit.form-plugin', this.selector, doAjaxSubmit) .off('click.form-plugin', this.selector, captureSubmittingElement) .on('submit.form-plugin', this.selector, options, doAjaxSubmit) .on('click.form-plugin', this.selector, options, captureSubmittingElement); return this; } return this.ajaxFormUnbind() .bind('submit.form-plugin', options, doAjaxSubmit) .bind('click.form-plugin', options, captureSubmittingElement); }; // private event handlers function doAjaxSubmit(e) { /*jshint validthis:true */ var options = e.data; if (!e.isDefaultPrevented()) { // if event has been canceled, don't proceed e.preventDefault(); $(e.target).ajaxSubmit(options); // #365 } } function captureSubmittingElement(e) { /*jshint validthis:true */ var target = e.target; var $el = $(target); if (!($el.is("[type=submit],[type=image]"))) { // is this a child element of the submit el? (ex: a span within a button) var t = $el.closest('[type=submit]'); if (t.length === 0) { return; } target = t[0]; } var form = this; form.clk = target; if (target.type == 'image') { if (e.offsetX !== undefined) { form.clk_x = e.offsetX; form.clk_y = e.offsetY; } else if (typeof $.fn.offset == 'function') { var offset = $el.offset(); form.clk_x = e.pageX - offset.left; form.clk_y = e.pageY - offset.top; } else { form.clk_x = e.pageX - target.offsetLeft; form.clk_y = e.pageY - target.offsetTop; } } // clear form vars setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 100); } // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm $.fn.ajaxFormUnbind = function() { return this.unbind('submit.form-plugin click.form-plugin'); }; /** * formToArray() gathers form element data into an array of objects that can * be passed to any of the following ajax functions: $.get, $.post, or load. * Each object in the array has both a 'name' and 'value' property. An example of * an array for a simple login form might be: * * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] * * It is this array that is passed to pre-submit callback functions provided to the * ajaxSubmit() and ajaxForm() methods. */ $.fn.formToArray = function(semantic, elements) { var a = []; if (this.length === 0) { return a; } var form = this[0]; var els = semantic ? form.getElementsByTagName('*') : form.elements; if (!els) { return a; } var i,j,n,v,el,max,jmax; for(i=0, max=els.length; i < max; i++) { el = els[i]; n = el.name; if (!n || el.disabled) { continue; } if (semantic && form.clk && el.type == "image") { // handle image inputs on the fly when semantic == true if(form.clk == el) { a.push({name: n, value: $(el).val(), type: el.type }); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } continue; } v = $.fieldValue(el, true); if (v && v.constructor == Array) { if (elements) elements.push(el); for(j=0, jmax=v.length; j < jmax; j++) { a.push({name: n, value: v[j]}); } } else if (feature.fileapi && el.type == 'file') { if (elements) elements.push(el); var files = el.files; if (files.length) { for (j=0; j < files.length; j++) { a.push({name: n, value: files[j], type: el.type}); } } else { // #180 a.push({ name: n, value: '', type: el.type }); } } else if (v !== null && typeof v != 'undefined') { if (elements) elements.push(el); a.push({name: n, value: v, type: el.type, required: el.required}); } } if (!semantic && form.clk) { // input type=='image' are not found in elements array! handle it here var $input = $(form.clk), input = $input[0]; n = input.name; if (n && !input.disabled && input.type == 'image') { a.push({name: n, value: $input.val()}); a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } } return a; }; /** * Serializes form data into a 'submittable' string. This method will return a string * in the format: name1=value1&amp;name2=value2 */ $.fn.formSerialize = function(semantic) { //hand off to jQuery.param for proper encoding return $.param(this.formToArray(semantic)); }; /** * Serializes all field elements in the jQuery object into a query string. * This method will return a string in the format: name1=value1&amp;name2=value2 */ $.fn.fieldSerialize = function(successful) { var a = []; this.each(function() { var n = this.name; if (!n) { return; } var v = $.fieldValue(this, successful); if (v && v.constructor == Array) { for (var i=0,max=v.length; i < max; i++) { a.push({name: n, value: v[i]}); } } else if (v !== null && typeof v != 'undefined') { a.push({name: this.name, value: v}); } }); //hand off to jQuery.param for proper encoding return $.param(a); }; /** * Returns the value(s) of the element in the matched set. For example, consider the following form: * * <form><fieldset> * <input name="A" type="text" /> * <input name="A" type="text" /> * <input name="B" type="checkbox" value="B1" /> * <input name="B" type="checkbox" value="B2"/> * <input name="C" type="radio" value="C1" /> * <input name="C" type="radio" value="C2" /> * </fieldset></form> * * var v = $('input[type=text]').fieldValue(); * // if no values are entered into the text inputs * v == ['',''] * // if values entered into the text inputs are 'foo' and 'bar' * v == ['foo','bar'] * * var v = $('input[type=checkbox]').fieldValue(); * // if neither checkbox is checked * v === undefined * // if both checkboxes are checked * v == ['B1', 'B2'] * * var v = $('input[type=radio]').fieldValue(); * // if neither radio is checked * v === undefined * // if first radio is checked * v == ['C1'] * * The successful argument controls whether or not the field element must be 'successful' * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). * The default value of the successful argument is true. If this value is false the value(s) * for each element is returned. * * Note: This method *always* returns an array. If no valid value can be determined the * array will be empty, otherwise it will contain one or more values. */ $.fn.fieldValue = function(successful) { for (var val=[], i=0, max=this.length; i < max; i++) { var el = this[i]; var v = $.fieldValue(el, successful); if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) { continue; } if (v.constructor == Array) $.merge(val, v); else val.push(v); } return val; }; /** * Returns the value of the field element. */ $.fieldValue = function(el, successful) { var n = el.name, t = el.type, tag = el.tagName.toLowerCase(); if (successful === undefined) { successful = true; } if (successful && (!n || el.disabled || t == 'reset' || t == 'button' || (t == 'checkbox' || t == 'radio') && !el.checked || (t == 'submit' || t == 'image') && el.form && el.form.clk != el || tag == 'select' && el.selectedIndex == -1)) { return null; } if (tag == 'select') { var index = el.selectedIndex; if (index < 0) { return null; } var a = [], ops = el.options; var one = (t == 'select-one'); var max = (one ? index+1 : ops.length); for(var i=(one ? index : 0); i < max; i++) { var op = ops[i]; if (op.selected) { var v = op.value; if (!v) { // extra pain for IE... v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value; } if (one) { return v; } a.push(v); } } return a; } return $(el).val(); }; /** * Clears the form data. Takes the following actions on the form's input fields: * - input text fields will have their 'value' property set to the empty string * - select elements will have their 'selectedIndex' property set to -1 * - checkbox and radio inputs will have their 'checked' property set to false * - inputs of type submit, button, reset, and hidden will *not* be effected * - button elements will *not* be effected */ $.fn.clearForm = function(includeHidden) { return this.each(function() { $('input,select,textarea', this).clearFields(includeHidden); }); }; /** * Clears the selected form elements. */ $.fn.clearFields = $.fn.clearInputs = function(includeHidden) { var re = /^(?:color|date|datetime|email|month|number|password|range|search|tel|text|time|url|week)$/i; // 'hidden' is not in this list return this.each(function() { var t = this.type, tag = this.tagName.toLowerCase(); if (re.test(t) || tag == 'textarea') { this.value = ''; } else if (t == 'checkbox' || t == 'radio') { this.checked = false; } else if (tag == 'select') { this.selectedIndex = -1; } else if (t == "file") { if (/MSIE/.test(navigator.userAgent)) { $(this).replaceWith($(this).clone(true)); } else { $(this).val(''); } } else if (includeHidden) { // includeHidden can be the value true, or it can be a selector string // indicating a special test; for example: // $('#myForm').clearForm('.special:hidden') // the above would clean hidden inputs that have the class of 'special' if ( (includeHidden === true && /hidden/.test(t)) || (typeof includeHidden == 'string' && $(this).is(includeHidden)) ) this.value = ''; } }); }; /** * Resets the form data. Causes all form elements to be reset to their original value. */ $.fn.resetForm = function() { return this.each(function() { // guard against an input with the name of 'reset' // note that IE reports the reset function as an 'object' if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) { this.reset(); } }); }; /** * Enables or disables any matching elements. */ $.fn.enable = function(b) { if (b === undefined) { b = true; } return this.each(function() { this.disabled = !b; }); }; /** * Checks/unchecks any matching checkboxes or radio buttons and * selects/deselects and matching option elements. */ $.fn.selected = function(select) { if (select === undefined) { select = true; } return this.each(function() { var t = this.type; if (t == 'checkbox' || t == 'radio') { this.checked = select; } else if (this.tagName.toLowerCase() == 'option') { var $sel = $(this).parent('select'); if (select && $sel[0] && $sel[0].type == 'select-one') { // deselect all other options $sel.find('option').selected(false); } this.selected = select; } }); }; // expose debug var $.fn.ajaxSubmit.debug = false; // helper fn for console logging function log() { if (!$.fn.ajaxSubmit.debug) return; var msg = '[jquery.form] ' + Array.prototype.join.call(arguments,''); if (window.console && window.console.log) { window.console.log(msg); } else if (window.opera && window.opera.postError) { window.opera.postError(msg); } } })( (typeof(jQuery) != 'undefined') ? jQuery : window.Zepto );
JavaScript
var App = function () { var isMainPage = false; var isMapPage = false; var isIE8 = false; var handleJQVMAP = function () { if (!sample_data) { return; } var showMap = function (name) { jQuery('.vmaps').hide(); jQuery('#vmap_' + name).show(); } var setMap = function (name) { var data = { map: 'world_en', backgroundColor: null, borderColor: '#333333', borderOpacity: 0.5, borderWidth: 1, color: '#c6c6c6', enableZoom: true, hoverColor: '#3daced', hoverOpacity: null, values: sample_data, normalizeFunction: 'linear', scaleColors: ['#e8e8e8', '#b0b0b0'], selectedColor: '#3daced', selectedRegion: null, showTooltip: true, onLabelShow: function (event, label, code) { }, onRegionOver: function (event, code) { if (code == 'ca') { event.preventDefault(); } }, onRegionClick: function (element, code, region) { var message = 'You clicked "' + region + '" which has the code: ' + code.toUpperCase(); alert(message); } }; data.map = name + '_en'; var map = jQuery('#vmap_' + name); map.width(map.parent().parent().width()); map.show(); map.vectorMap(data); map.hide(); } setMap("world"); setMap("usa"); setMap("europe"); setMap("russia"); setMap("germany"); showMap("world"); jQuery('#regional_stat_world').click(function () { showMap("world"); }); jQuery('#regional_stat_usa').click(function () { showMap("usa"); }); jQuery('#regional_stat_europe').click(function () { showMap("europe"); }); jQuery('#regional_stat_russia').click(function () { showMap("russia"); }); jQuery('#regional_stat_germany').click(function () { showMap("germany"); }); $('#region_statistics_loading').hide(); $('#region_statistics_content').show(); } var handleAllJQVMAP = function () { if (!sample_data) { return; } var setMap = function (name) { var data = { map: 'world_en', backgroundColor: null, borderColor: '#333333', borderOpacity: 0.5, borderWidth: 1, color: '#c6c6c6', enableZoom: true, hoverColor: '#3daced', hoverOpacity: null, values: sample_data, normalizeFunction: 'linear', scaleColors: ['#e8e8e8', '#b0b0b0'], selectedColor: '#3daced', selectedRegion: null, showTooltip: true, onRegionOver: function (event, code) { //sample to interact with map if (code == 'ca') { event.preventDefault(); } }, onRegionClick: function (element, code, region) { //sample to interact with map var message = 'You clicked "' + region + '" which has the code: ' + code.toUpperCase(); alert(message); } }; data.map = name + '_en'; var map = jQuery('#vmap_' + name); map.width(map.parent().width()); map.vectorMap(data); } setMap("world"); setMap("usa"); setMap("europe"); setMap("russia"); setMap("germany"); } var handleDashboardCalendar = function () { if (!jQuery().fullCalendar) { return; } var date = new Date(); var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); var h = {}; if ($(window).width() <= 320) { h = { left: 'title, prev,next', center: '', right: 'today,month,agendaWeek,agendaDay' }; } else { h = { left: 'title', center: '', right: 'prev,next,today,month,agendaWeek,agendaDay' }; } $('#calendar').html(""); $('#calendar').fullCalendar({ header: h, editable: true, events: [{ title: 'All Day Event', start: new Date(y, m, 1), className: 'label label-default', }, { title: 'Long Event', start: new Date(y, m, d - 5), end: new Date(y, m, d - 2), className: 'label label-success', }, { title: 'Repeating Event', start: new Date(y, m, d - 3, 16, 0), allDay: false, className: 'label label-default', }, { title: 'Repeating Event', start: new Date(y, m, d + 4, 16, 0), allDay: false, className: 'label label-important', }, { title: 'Meeting', start: new Date(y, m, d, 10, 30), allDay: false, className: 'label label-info', }, { title: 'Lunch', start: new Date(y, m, d, 12, 0), end: new Date(y, m, d, 14, 0), allDay: false, className: 'label label-warning', }, { title: 'Birthday Party', start: new Date(y, m, d + 1, 19, 0), end: new Date(y, m, d + 1, 22, 30), allDay: false, className: 'label label-success', }, { title: 'Click for Google', start: new Date(y, m, 28), end: new Date(y, m, 29), url: 'http://google.com/', className: 'label label-warning', }] }); } var handleCalendar = function () { if (!jQuery().fullCalendar) { return; } var date = new Date(); var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); var h = {}; if ($(window).width() <= 320) { h = { left: 'title, prev,next', center: '', right: 'today,month,agendaWeek,agendaDay' }; } else { h = { left: 'title', center: '', right: 'prev,next,today,month,agendaWeek,agendaDay' }; } var initDrag = function (el) { // create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/) // it doesn't need to have a start or end var eventObject = { title: $.trim(el.text()) // use the element's text as the event title }; // store the Event Object in the DOM element so we can get to it later el.data('eventObject', eventObject); // make the event draggable using jQuery UI el.draggable({ zIndex: 999, revert: true, // will cause the event to go back to its revertDuration: 0 // original position after the drag }); } var addEvent = function (title, priority) { title = title.length == 0 ? "Untitled Event" : title; priority = priority.length == 0 ? "default" : priority; var html = $('<div data-class="label label-' + priority + '" class="external-event label label-' + priority + '">' + title + '</div>'); jQuery('#event_box').append(html); initDrag(html); } $('#external-events div.external-event').each(function () { initDrag($(this)) }); $('#event_add').click(function () { var title = $('#event_title').val(); var priority = $('#event_priority').val(); addEvent(title, priority); }); //modify chosen options var handleDropdown = function () { $('#event_priority_chzn .chzn-search').hide(); //hide search box $('#event_priority_chzn_o_1').html('<span class="label label-default">' + $('#event_priority_chzn_o_1').text() + '</span>'); $('#event_priority_chzn_o_2').html('<span class="label label-success">' + $('#event_priority_chzn_o_2').text() + '</span>'); $('#event_priority_chzn_o_3').html('<span class="label label-info">' + $('#event_priority_chzn_o_3').text() + '</span>'); $('#event_priority_chzn_o_4').html('<span class="label label-warning">' + $('#event_priority_chzn_o_4').text() + '</span>'); $('#event_priority_chzn_o_5').html('<span class="label label-important">' + $('#event_priority_chzn_o_5').text() + '</span>'); } $('#event_priority_chzn').click(handleDropdown); //predefined events addEvent("My Event 1", "default"); addEvent("My Event 2", "success"); addEvent("My Event 3", "info"); addEvent("My Event 4", "warning"); addEvent("My Event 5", "important"); addEvent("My Event 6", "success"); addEvent("My Event 7", "info"); addEvent("My Event 8", "warning"); addEvent("My Event 9", "success"); addEvent("My Event 10", "default"); $('#calendar').fullCalendar({ header: h, editable: true, droppable: true, // this allows things to be dropped onto the calendar !!! drop: function (date, allDay) { // this function is called when something is dropped // retrieve the dropped element's stored Event Object var originalEventObject = $(this).data('eventObject'); // we need to copy it, so that multiple events don't have a reference to the same object var copiedEventObject = $.extend({}, originalEventObject); // assign it the date that was reported copiedEventObject.start = date; copiedEventObject.allDay = allDay; copiedEventObject.className = $(this).attr("data-class"); // render the event on the calendar // the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/) $('#calendar').fullCalendar('renderEvent', copiedEventObject, true); // is the "remove after drop" checkbox checked? if ($('#drop-remove').is(':checked')) { // if so, remove the element from the "Draggable Events" list $(this).remove(); } }, events: [{ title: 'All Day Event', start: new Date(y, m, 1), className: 'label label-default', }, { title: 'Long Event', start: new Date(y, m, d - 5), end: new Date(y, m, d - 2), className: 'label label-success', }, { id: 999, title: 'Repeating Event', start: new Date(y, m, d - 3, 16, 0), allDay: false, className: 'label label-default', }, { id: 999, title: 'Repeating Event', start: new Date(y, m, d + 4, 16, 0), allDay: false, className: 'label label-important', }, { title: 'Meeting', start: new Date(y, m, d, 10, 30), allDay: false, className: 'label label-info', }, { title: 'Lunch', start: new Date(y, m, d, 12, 0), end: new Date(y, m, d, 14, 0), allDay: false, className: 'label label-warning', }, { title: 'Birthday Party', start: new Date(y, m, d + 1, 19, 0), end: new Date(y, m, d + 1, 22, 30), allDay: false, className: 'label label-success', }, { title: 'Click for Google', start: new Date(y, m, 28), end: new Date(y, m, 29), url: 'http://google.com/', className: 'label label-warning', }] }); } var handleChat = function () { var cont = $('#chats'); var list = $('.chats', cont); var form = $('.chat-form', cont); var input = $('input', form); var btn = $('.btn', form); var handleClick = function () { var text = input.val(); if (text.length == 0) { return; } var time = new Date(); var time_str = time.toString('MMM dd, yyyy HH:MM'); var tpl = ''; tpl += '<li class="out">'; tpl += '<img class="avatar" alt="" src="img/avatar1.jpg"/>'; tpl += '<div class="message">'; tpl += '<span class="arrow"></span>'; tpl += '<a href="#" class="name">Sumon Ahmed</a>&nbsp;'; tpl += '<span class="datetime">at ' + time_str + '</span>'; tpl += '<span class="body">'; tpl += text; tpl += '</span>'; tpl += '</div>'; tpl += '</li>'; var msg = list.append(tpl); input.val(""); $('.scroller', cont).slimScroll({ scrollTo: list.height() }); } btn.click(handleClick); input.keypress(function (e) { if (e.which == 13) { handleClick(); return false; //<---- Add this line } }); } var handleClockfaceTimePickers = function () { if (!jQuery().clockface) { return; } $('#clockface_1').clockface(); $('#clockface_2').clockface({ format: 'HH:mm', trigger: 'manual' }); $('#clockface_2_toggle-btn').click(function (e) { e.stopPropagation(); $('#clockface_2').clockface('toggle'); }); $('#clockface_3').clockface({ format: 'H:mm' }).clockface('show', '14:30'); } var handlePortletSortable = function () { if (!jQuery().sortable) { return; } $(".sortable").sortable({ connectWith: '.sortable', iframeFix: false, items: 'div.widget', opacity: 0.8, helper: 'original', revert: true, forceHelperSize: true, placeholder: 'sortable-box-placeholder round-all', forcePlaceholderSize: true, tolerance: 'pointer' }); } var handleMainMenu = function () { jQuery('#sidebar .has-sub > a').click(function () { var last = jQuery('.has-sub.open', $('#sidebar')); last.removeClass("open"); jQuery('.arrow', last).removeClass("open"); jQuery('.sub', last).slideUp(200); var sub = jQuery(this).next(); if (sub.is(":visible")) { jQuery('.arrow', jQuery(this)).removeClass("open"); jQuery(this).parent().removeClass("open"); sub.slideUp(200); } else { jQuery('.arrow', jQuery(this)).addClass("open"); jQuery(this).parent().addClass("open"); sub.slideDown(200); } }); } var handleWidgetTools = function () { jQuery('.widget .tools .icon-remove').click(function () { jQuery(this).parents(".widget").parent().remove(); }); jQuery('.widget .tools .icon-refresh').click(function () { var el = jQuery(this).parents(".widget"); App.blockUI(el); window.setTimeout(function () { App.unblockUI(el); }, 1000); }); jQuery('.widget .tools .icon-chevron-down, .widget .tools .icon-chevron-up').click(function () { var el = jQuery(this).parents(".widget").children(".widget-body"); if (jQuery(this).hasClass("icon-chevron-down")) { jQuery(this).removeClass("icon-chevron-down").addClass("icon-chevron-up"); el.slideUp(200); } else { jQuery(this).removeClass("icon-chevron-up").addClass("icon-chevron-down"); el.slideDown(200); } }); } var handleDashboardCharts = function () { // used by plot functions var data = []; var totalPoints = 200; // random data generator for plot charts function getRandomData() { if (data.length > 0) data = data.slice(1); // do a random walk while (data.length < totalPoints) { var prev = data.length > 0 ? data[data.length - 1] : 50; var y = prev + Math.random() * 10 - 5; if (y < 0) y = 0; if (y > 100) y = 100; data.push(y); } // zip the generated y values with the x values var res = []; for (var i = 0; i < data.length; ++i) res.push([i, data[i]]) return res; } if (!jQuery.plot) { return; } function randValue() { return (Math.floor(Math.random() * (1 + 40 - 20))) + 20; } var pageviews = [ [1, randValue()], [2, randValue()], [3, 2 + randValue()], [4, 3 + randValue()], [5, 5 + randValue()], [6, 10 + randValue()], [7, 15 + randValue()], [8, 20 + randValue()], [9, 25 + randValue()], [10, 30 + randValue()], [11, 35 + randValue()], [12, 25 + randValue()], [13, 15 + randValue()], [14, 20 + randValue()], [15, 45 + randValue()], [16, 50 + randValue()], [17, 65 + randValue()], [18, 70 + randValue()], [19, 85 + randValue()], [20, 80 + randValue()], [21, 75 + randValue()], [22, 80 + randValue()], [23, 75 + randValue()], [24, 70 + randValue()], [25, 65 + randValue()], [26, 75 + randValue()], [27, 80 + randValue()], [28, 85 + randValue()], [29, 90 + randValue()], [30, 95 + randValue()] ]; var visitors = [ [1, randValue() - 5], [2, randValue() - 5], [3, randValue() - 5], [4, 6 + randValue()], [5, 5 + randValue()], [6, 20 + randValue()], [7, 25 + randValue()], [8, 36 + randValue()], [9, 26 + randValue()], [10, 38 + randValue()], [11, 39 + randValue()], [12, 50 + randValue()], [13, 51 + randValue()], [14, 12 + randValue()], [15, 13 + randValue()], [16, 14 + randValue()], [17, 15 + randValue()], [18, 15 + randValue()], [19, 16 + randValue()], [20, 17 + randValue()], [21, 18 + randValue()], [22, 19 + randValue()], [23, 20 + randValue()], [24, 21 + randValue()], [25, 14 + randValue()], [26, 24 + randValue()], [27, 25 + randValue()], [28, 26 + randValue()], [29, 27 + randValue()], [30, 31 + randValue()] ]; $('#site_statistics_loading').hide(); $('#site_statistics_content').show(); var plot = $.plot($("#site_statistics"), [{ data: pageviews, label: "Unique Visits" }, { data: visitors, label: "Page Views" }], { series: { lines: { show: true, lineWidth: 2, fill: true, fillColor: { colors: [{ opacity: 0.05 }, { opacity: 0.01 }] } }, points: { show: true }, shadowSize: 2 }, grid: { hoverable: true, clickable: true, tickColor: "#eee", borderWidth: 0 }, colors: ["#A5D16C", "#FCB322", "#32C2CD"], xaxis: { ticks: 11, tickDecimals: 0 }, yaxis: { ticks: 11, tickDecimals: 0 } }); function showTooltip(x, y, contents) { $('<div id="tooltip">' + contents + '</div>').css({ position: 'absolute', display: 'none', top: y + 5, left: x + 15, border: '1px solid #333', padding: '4px', color: '#fff', 'border-radius': '3px', 'background-color': '#333', opacity: 0.80 }).appendTo("body").fadeIn(200); } var previousPoint = null; $("#site_statistics").bind("plothover", function (event, pos, item) { $("#x").text(pos.x.toFixed(2)); $("#y").text(pos.y.toFixed(2)); if (item) { if (previousPoint != item.dataIndex) { previousPoint = item.dataIndex; $("#tooltip").remove(); var x = item.datapoint[0].toFixed(2), y = item.datapoint[1].toFixed(2); showTooltip(item.pageX, item.pageY, item.series.label + " of " + x + " = " + y); } } else { $("#tooltip").remove(); previousPoint = null; } }); //server load var options = { series: { shadowSize: 1 }, lines: { show: true, lineWidth: 0.5, fill: true, fillColor: { colors: [{ opacity: 0.1 }, { opacity: 1 }] } }, yaxis: { min: 0, max: 100, tickFormatter: function (v) { return v + "%"; } }, xaxis: { show: false }, colors: ["#A5D16C"], grid: { tickColor: "#eaeaea", borderWidth: 0 } }; $('#load_statistics_loading').hide(); $('#load_statistics_content').show(); var updateInterval = 30; var plot = $.plot($("#load_statistics"), [getRandomData()], options); function update() { plot.setData([getRandomData()]); plot.draw(); setTimeout(update, updateInterval); } update(); } var handleCharts = function () { // used by plot functions var data = []; var totalPoints = 250; // random data generator for plot charts function getRandomData() { if (data.length > 0) data = data.slice(1); // do a random walk while (data.length < totalPoints) { var prev = data.length > 0 ? data[data.length - 1] : 50; var y = prev + Math.random() * 10 - 5; if (y < 0) y = 0; if (y > 100) y = 100; data.push(y); } // zip the generated y values with the x values var res = []; for (var i = 0; i < data.length; ++i) res.push([i, data[i]]) return res; } if (!jQuery.plot) { return; } if ($("#chart_1").size() == 0) { return; } //Basic Chart function chart1() { var d1 = []; for (var i = 0; i < Math.PI * 2; i += 0.25) d1.push([i, Math.sin(i)]); var d2 = []; for (var i = 0; i < Math.PI * 2; i += 0.25) d2.push([i, Math.cos(i)]); var d3 = []; for (var i = 0; i < Math.PI * 2; i += 0.1) d3.push([i, Math.tan(i)]); $.plot($("#chart_1"), [{ label: "sin(x)", data: d1 }, { label: "cos(x)", data: d2 }, { label: "tan(x)", data: d3 }], { series: { lines: { show: true }, points: { show: true } }, xaxis: { ticks: [0, [Math.PI / 2, "\u03c0/2"], [Math.PI, "\u03c0"], [Math.PI * 3 / 2, "3\u03c0/2"], [Math.PI * 2, "2\u03c0"] ] }, yaxis: { ticks: 10, min: -2, max: 2 }, grid: { backgroundColor: { colors: ["#fff", "#eee"] } } }); } //Interactive Chart function chart2() { function randValue() { return (Math.floor(Math.random() * (1 + 40 - 20))) + 20; } var pageviews = [ [1, randValue()], [2, randValue()], [3, 2 + randValue()], [4, 3 + randValue()], [5, 5 + randValue()], [6, 10 + randValue()], [7, 15 + randValue()], [8, 20 + randValue()], [9, 25 + randValue()], [10, 30 + randValue()], [11, 35 + randValue()], [12, 25 + randValue()], [13, 15 + randValue()], [14, 20 + randValue()], [15, 45 + randValue()], [16, 50 + randValue()], [17, 65 + randValue()], [18, 70 + randValue()], [19, 85 + randValue()], [20, 80 + randValue()], [21, 75 + randValue()], [22, 80 + randValue()], [23, 75 + randValue()], [24, 70 + randValue()], [25, 65 + randValue()], [26, 75 + randValue()], [27, 80 + randValue()], [28, 85 + randValue()], [29, 90 + randValue()], [30, 95 + randValue()] ]; var visitors = [ [1, randValue() - 5], [2, randValue() - 5], [3, randValue() - 5], [4, 6 + randValue()], [5, 5 + randValue()], [6, 20 + randValue()], [7, 25 + randValue()], [8, 36 + randValue()], [9, 26 + randValue()], [10, 38 + randValue()], [11, 39 + randValue()], [12, 50 + randValue()], [13, 51 + randValue()], [14, 12 + randValue()], [15, 13 + randValue()], [16, 14 + randValue()], [17, 15 + randValue()], [18, 15 + randValue()], [19, 16 + randValue()], [20, 17 + randValue()], [21, 18 + randValue()], [22, 19 + randValue()], [23, 20 + randValue()], [24, 21 + randValue()], [25, 14 + randValue()], [26, 24 + randValue()], [27, 25 + randValue()], [28, 26 + randValue()], [29, 27 + randValue()], [30, 31 + randValue()] ]; var plot = $.plot($("#chart_2"), [{ data: pageviews, label: "Unique Visits" }, { data: visitors, label: "Page Views" }], { series: { lines: { show: true, lineWidth: 2, fill: true, fillColor: { colors: [{ opacity: 0.05 }, { opacity: 0.01 }] } }, points: { show: true }, shadowSize: 2 }, grid: { hoverable: true, clickable: true, tickColor: "#eee", borderWidth: 0 }, colors: ["#FCB322", "#A5D16C", "#52e136"], xaxis: { ticks: 11, tickDecimals: 0 }, yaxis: { ticks: 11, tickDecimals: 0 } }); function showTooltip(x, y, contents) { $('<div id="tooltip">' + contents + '</div>').css({ position: 'absolute', display: 'none', top: y + 5, left: x + 15, border: '1px solid #333', padding: '4px', color: '#fff', 'border-radius': '3px', 'background-color': '#333', opacity: 0.80 }).appendTo("body").fadeIn(200); } var previousPoint = null; $("#chart_2").bind("plothover", function (event, pos, item) { $("#x").text(pos.x.toFixed(2)); $("#y").text(pos.y.toFixed(2)); if (item) { if (previousPoint != item.dataIndex) { previousPoint = item.dataIndex; $("#tooltip").remove(); var x = item.datapoint[0].toFixed(2), y = item.datapoint[1].toFixed(2); showTooltip(item.pageX, item.pageY, item.series.label + " of " + x + " = " + y); } } else { $("#tooltip").remove(); previousPoint = null; } }); } //Tracking Curves function chart3() { //tracking curves: var sin = [], cos = []; for (var i = 0; i < 14; i += 0.1) { sin.push([i, Math.sin(i)]); cos.push([i, Math.cos(i)]); } plot = $.plot($("#chart_3"), [{ data: sin, label: "sin(x) = -0.00" }, { data: cos, label: "cos(x) = -0.00" }], { series: { lines: { show: true } }, crosshair: { mode: "x" }, grid: { hoverable: true, autoHighlight: false }, colors: ["#FCB322", "#A5D16C", "#52e136"], yaxis: { min: -1.2, max: 1.2 } }); var legends = $("#chart_3 .legendLabel"); legends.each(function () { // fix the widths so they don't jump around $(this).css('width', $(this).width()); }); var updateLegendTimeout = null; var latestPosition = null; function updateLegend() { updateLegendTimeout = null; var pos = latestPosition; var axes = plot.getAxes(); if (pos.x < axes.xaxis.min || pos.x > axes.xaxis.max || pos.y < axes.yaxis.min || pos.y > axes.yaxis.max) return; var i, j, dataset = plot.getData(); for (i = 0; i < dataset.length; ++i) { var series = dataset[i]; // find the nearest points, x-wise for (j = 0; j < series.data.length; ++j) if (series.data[j][0] > pos.x) break; // now interpolate var y, p1 = series.data[j - 1], p2 = series.data[j]; if (p1 == null) y = p2[1]; else if (p2 == null) y = p1[1]; else y = p1[1] + (p2[1] - p1[1]) * (pos.x - p1[0]) / (p2[0] - p1[0]); legends.eq(i).text(series.label.replace(/=.*/, "= " + y.toFixed(2))); } } $("#chart_3").bind("plothover", function (event, pos, item) { latestPosition = pos; if (!updateLegendTimeout) updateLegendTimeout = setTimeout(updateLegend, 50); }); } //Dynamic Chart function chart4() { //server load var options = { series: { shadowSize: 1 }, lines: { show: true, lineWidth: 0.5, fill: true, fillColor: { colors: [{ opacity: 0.1 }, { opacity: 1 }] } }, yaxis: { min: 0, max: 100, tickFormatter: function (v) { return v + "%"; } }, xaxis: { show: false }, colors: ["#6ef146"], grid: { tickColor: "#a8a3a3", borderWidth: 0 } }; var updateInterval = 30; var plot = $.plot($("#chart_4"), [getRandomData()], options); function update() { plot.setData([getRandomData()]); plot.draw(); setTimeout(update, updateInterval); } update(); } //bars with controls function chart5() { var d1 = []; for (var i = 0; i <= 10; i += 1) d1.push([i, parseInt(Math.random() * 30)]); var d2 = []; for (var i = 0; i <= 10; i += 1) d2.push([i, parseInt(Math.random() * 30)]); var d3 = []; for (var i = 0; i <= 10; i += 1) d3.push([i, parseInt(Math.random() * 30)]); var stack = 0, bars = true, lines = false, steps = false; function plotWithOptions() { $.plot($("#chart_5"), [d1, d2, d3], { series: { stack: stack, lines: { show: lines, fill: true, steps: steps }, bars: { show: bars, barWidth: 0.6 } } }); } $(".stackControls input").click(function (e) { e.preventDefault(); stack = $(this).val() == "With stacking" ? true : null; plotWithOptions(); }); $(".graphControls input").click(function (e) { e.preventDefault(); bars = $(this).val().indexOf("Bars") != -1; lines = $(this).val().indexOf("Lines") != -1; steps = $(this).val().indexOf("steps") != -1; plotWithOptions(); }); plotWithOptions(); } //graph function graphs() { var graphData = []; var series = Math.floor(Math.random() * 10) + 1; for (var i = 0; i < series; i++) { graphData[i] = { label: "Series" + (i + 1), data: Math.floor((Math.random() - 1) * 100) + 1 } } $.plot($("#graph_1"), graphData, { series: { pie: { show: true, radius: 1, label: { show: true, radius: 1, formatter: function (label, series) { return '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">' + label + '<br/>' + Math.round(series.percent) + '%</div>'; }, background: { opacity: 0.8 } } } }, legend: { show: false } }); $.plot($("#graph_2"), graphData, { series: { pie: { show: true, radius: 1, label: { show: true, radius: 3 / 4, formatter: function (label, series) { return '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">' + label + '<br/>' + Math.round(series.percent) + '%</div>'; }, background: { opacity: 0.5 } } } }, legend: { show: false } }); $.plot($("#graph_3"), graphData, { series: { pie: { show: true } }, grid: { hoverable: true, clickable: true } }); $("#graph_3").bind("plothover", pieHover); $("#graph_3").bind("plotclick", pieClick); function pieHover(event, pos, obj) { if (!obj) return; percent = parseFloat(obj.series.percent).toFixed(2); $("#hover").html('<span style="font-weight: bold; color: ' + obj.series.color + '">' + obj.series.label + ' (' + percent + '%)</span>'); } function pieClick(event, pos, obj) { if (!obj) return; percent = parseFloat(obj.series.percent).toFixed(2); alert('' + obj.series.label + ': ' + percent + '%'); } $.plot($("#graph_4"), graphData, { series: { pie: { innerRadius: 0.5, show: true } } }); } chart1(); chart2(); chart3(); chart4(); chart5(); graphs(); } var handleFancyBox = function () { if (!jQuery().fancybox) { return; } if (jQuery(".fancybox-button").size() > 0) { jQuery(".fancybox-button").fancybox({ groupAttr: 'data-rel', prevEffect: 'none', nextEffect: 'none', closeBtn: true, helpers: { title: { type: 'inside' } } }); } } var handleLoginForm = function () { jQuery('#forget-password').click(function () { jQuery('#loginform').hide(); jQuery('#forgotform').show(200); }); jQuery('#forget-btn').click(function () { jQuery('#loginform').slideDown(200); jQuery('#forgotform').slideUp(200); }); } var handleFixInputPlaceholderForIE = function () { //fix html5 placeholder attribute for ie7 & ie8 if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) <= 9) { // ie7&ie8 jQuery('input[placeholder], textarea[placeholder]').each(function () { var input = jQuery(this); jQuery(input).val(input.attr('placeholder')); jQuery(input).focus(function () { if (input.val() == input.attr('placeholder')) { input.val(''); } }); jQuery(input).blur(function () { if (input.val() == '' || input.val() == input.attr('placeholder')) { input.val(input.attr('placeholder')); } }); }); } } var handleStyler = function () { var scrollHeight = '25px'; jQuery('#theme-change').click(function () { if ($(this).attr("opened") && !$(this).attr("opening") && !$(this).attr("closing")) { $(this).removeAttr("opened"); $(this).attr("closing", "1"); $("#theme-change").css("overflow", "hidden").animate({ width: '20px', height: '22px', 'padding-top': '3px' }, { complete: function () { $(this).removeAttr("closing"); $("#theme-change .settings").hide(); } }); } else if (!$(this).attr("closing") && !$(this).attr("opening")) { $(this).attr("opening", "1"); $("#theme-change").css("overflow", "visible").animate({ width: '190px', height: scrollHeight, 'padding-top': '3px' }, { complete: function () { $(this).removeAttr("opening"); $(this).attr("opened", 1); } }); $("#theme-change .settings").show(); } }); jQuery('#theme-change .colors span').click(function () { var color = $(this).attr("data-style"); setColor(color); }); jQuery('#theme-change .layout input').change(function () { setLayout(); }); var setColor = function (color) { $('#style_color').attr("href", host+"assets/css/style_" + color + ".css"); } } var handlePulsate = function () { if (!jQuery().pulsate) { return; } if (isIE8 == true) { return; // pulsate plugin does not support IE8 and below } if (jQuery().pulsate) { jQuery('#pulsate-regular').pulsate({ color: "#bf1c56" }); jQuery('#pulsate-once').click(function () { $(this).pulsate({ color: "#399bc3", repeat: false }); }); jQuery('#pulsate-hover').pulsate({ color: "#5ebf5e", repeat: false, onHover: true }); jQuery('#pulsate-crazy').click(function () { $(this).pulsate({ color: "#fdbe41", reach: 50, repeat: 10, speed: 100, glow: true }); }); } } var handlePeity = function () { if (!jQuery().peity) { return; } if (jQuery.browser.msie && jQuery.browser.version.substr(0, 2) <= 8) { // ie7&ie8 return; } $(".stat.bad .line-chart").peity("line", { height: 20, width: 50, colour: "#d12610", strokeColour: "#666" }).show(); $(".stat.bad .bar-chart").peity("bar", { height: 20, width: 50, colour: "#d12610", strokeColour: "#666" }).show(); $(".stat.ok .line-chart").peity("line", { height: 20, width: 50, colour: "#37b7f3", strokeColour: "#757575" }).show(); $(".stat.ok .bar-chart").peity("bar", { height: 20, width: 50, colour: "#37b7f3" }).show(); $(".stat.good .line-chart").peity("line", { height: 20, width: 50, colour: "#52e136" }).show(); $(".stat.good .bar-chart").peity("bar", { height: 20, width: 50, colour: "#52e136" }).show(); // $(".stat.bad.huge .line-chart").peity("line", { height: 20, width: 40, colour: "#d12610", strokeColour: "#666" }).show(); $(".stat.bad.huge .bar-chart").peity("bar", { height: 20, width: 40, colour: "#d12610", strokeColour: "#666" }).show(); $(".stat.ok.huge .line-chart").peity("line", { height: 20, width: 40, colour: "#37b7f3", strokeColour: "#757575" }).show(); $(".stat.ok.huge .bar-chart").peity("bar", { height: 20, width: 40, colour: "#37b7f3" }).show(); $(".stat.good.huge .line-chart").peity("line", { height: 20, width: 40, colour: "#52e136" }).show(); $(".stat.good.huge .bar-chart").peity("bar", { height: 20, width: 40, colour: "#52e136" }).show(); } var handleDeviceWidth = function () { function fixWidth(e) { var winHeight = $(window).height(); var winWidth = $(window).width(); //alert(winWidth); //for tablet and small desktops if (winWidth < 1125 && winWidth > 767) { $(".responsive").each(function () { var forTablet = $(this).attr('data-tablet'); var forDesktop = $(this).attr('data-desktop'); if (forTablet) { $(this).removeClass(forDesktop); $(this).addClass(forTablet); } }); } else { $(".responsive").each(function () { var forTablet = $(this).attr('data-tablet'); var forDesktop = $(this).attr('data-desktop'); if (forTablet) { $(this).removeClass(forTablet); $(this).addClass(forDesktop); } }); } } fixWidth(); running = false; jQuery(window).resize(function () { if (running == false) { running = true; setTimeout(function () { // fix layout width fixWidth(); // fix calendar width by just reinitializing handleDashboardCalendar(); if (isMainPage) { handleDashboardCalendar(); // handles full calendar for main page } else { handleCalendar(); // handles full calendars } // fix vector maps width if (isMainPage) { jQuery('.vmaps').each(function () { var map = jQuery(this); map.width(map.parent().parent().width()); }); } if (isMapPage) { jQuery('.vmaps').each(function () { var map = jQuery(this); map.width(map.parent().width()); }); } // fix event form chosen dropdowns $('#event_priority_chzn').width($('#event_title').width() + 15); $('#event_priority_chzn .chzn-drop').width($('#event_title').width() + 13); $(".chzn-select").val('').trigger("liszt:updated"); //finish running = false; }, 200); // wait for 200ms on resize event } }); } var handleGritterNotifications = function () { if (!jQuery.gritter) { return; } $('#gritter-sticky').click(function () { var unique_id = $.gritter.add({ // (string | mandatory) the heading of the notification title: 'This is a sticky notice!', // (string | mandatory) the text inside the notification text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus eget tincidunt velit. Cum sociis natoque penatibus et <a href="#" style="color:#ccc">magnis dis parturient</a> montes, nascetur ridiculus mus.', // (string | optional) the image to display on the left image: 'img/avatar-mini.png', // (bool | optional) if you want it to fade out on its own or just sit there sticky: true, // (int | optional) the time you want it to be alive for before fading out time: '', // (string | optional) the class name you want to apply to that specific message class_name: 'my-sticky-class' }); return false; }); $('#gritter-regular').click(function () { $.gritter.add({ // (string | mandatory) the heading of the notification title: 'This is a regular notice!', // (string | mandatory) the text inside the notification text: 'This will fade out after a certain amount of time. Vivamus eget tincidunt velit. Cum sociis natoque penatibus et <a href="#" style="color:#ccc">magnis dis parturient</a> montes, nascetur ridiculus mus.', // (string | optional) the image to display on the left image: 'img/avatar-mini.png', // (bool | optional) if you want it to fade out on its own or just sit there sticky: false, // (int | optional) the time you want it to be alive for before fading out time: '' }); return false; }); $('#gritter-max').click(function () { $.gritter.add({ // (string | mandatory) the heading of the notification title: 'This is a notice with a max of 3 on screen at one time!', // (string | mandatory) the text inside the notification text: 'This will fade out after a certain amount of time. Vivamus eget tincidunt velit. Cum sociis natoque penatibus et <a href="#" style="color:#ccc">magnis dis parturient</a> montes, nascetur ridiculus mus.', // (string | optional) the image to display on the left image: 'img/avatar-mini.png', // (bool | optional) if you want it to fade out on its own or just sit there sticky: false, // (function) before the gritter notice is opened before_open: function () { if ($('.gritter-item-wrapper').length == 3) { // Returning false prevents a new gritter from opening return false; } } }); return false; }); $('#gritter-without-image').click(function () { $.gritter.add({ // (string | mandatory) the heading of the notification title: 'This is a notice without an image!', // (string | mandatory) the text inside the notification text: 'This will fade out after a certain amount of time. Vivamus eget tincidunt velit. Cum sociis natoque penatibus et <a href="#" style="color:#ccc">magnis dis parturient</a> montes, nascetur ridiculus mus.' }); return false; }); $('#gritter-light').click(function () { $.gritter.add({ // (string | mandatory) the heading of the notification title: 'This is a light notification', // (string | mandatory) the text inside the notification text: 'Just add a "gritter-light" class_name to your $.gritter.add or globally to $.gritter.options.class_name', class_name: 'gritter-light' }); return false; }); $("#gritter-remove-all").click(function () { $.gritter.removeAll(); return false; }); } var handleTooltip = function () { jQuery('.tooltips').tooltip(); } var handlePopover = function () { jQuery('.popovers').popover(); } var handleChoosenSelect = function () { if (!jQuery().chosen) { return; } $(".chosen").chosen(); $(".chosen-with-diselect").chosen({ allow_single_deselect: true }); } var handleUniform = function () { if (!jQuery().uniform) { return; } if (test = $("input[type=checkbox]:not(.toggle), input[type=radio]:not(.toggle)")) { test.uniform(); } } var handleWysihtml5 = function () { if (!jQuery().wysihtml5) { return; } if ($('.wysihtml5').size() > 0) { $('.wysihtml5').wysihtml5(); } } var handleToggleButtons = function () { if (!jQuery().toggleButtons) { return; } $('.basic-toggle-button').toggleButtons(); $('.text-toggle-button').toggleButtons({ width: 200, label: { enabled: "Lorem Ipsum", disabled: "Dolor Sit" } }); $('.danger-toggle-button').toggleButtons({ style: { // Accepted values ["primary", "danger", "info", "success", "warning"] or nothing enabled: "danger", disabled: "info" } }); $('.info-toggle-button').toggleButtons({ style: { enabled: "info", disabled: "" } }); $('.success-toggle-button').toggleButtons({ style: { enabled: "success", disabled: "danger" } }); $('.warning-toggle-button').toggleButtons({ style: { enabled: "warning", disabled: "success" } }); $('.height-toggle-button').toggleButtons({ height: 100, font: { 'line-height': '100px', 'font-size': '20px', 'font-style': 'italic' } }); $('.not-animated-toggle-button').toggleButtons({ animated: false }); $('.transition-value-toggle-button').toggleButtons({ transitionspeed: 1 // default value: 0.05 }); } var handleTables = function () { if (!jQuery().dataTable) { return; } // begin first table $('#sample_1').dataTable({ "sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>", "sPaginationType": "bootstrap", "oLanguage": { "sLengthMenu": "_MENU_ records per page", "oPaginate": { "sPrevious": "Prev", "sNext": "Next" } }, "aoColumnDefs": [{ 'bSortable': false, 'aTargets': [0] }] }); jQuery('#sample_1 .group-checkable').change(function () { var set = jQuery(this).attr("data-set"); var checked = jQuery(this).is(":checked"); jQuery(set).each(function () { if (checked) { $(this).attr("checked", true); } else { $(this).attr("checked", false); } }); jQuery.uniform.update(set); }); jQuery('#sample_1_wrapper .dataTables_filter input').addClass("input-medium"); // modify table search input jQuery('#sample_1_wrapper .dataTables_length select').addClass("input-mini"); // modify table per page dropdown // begin second table $('#sample_2').dataTable({ "sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>", "sPaginationType": "bootstrap", "oLanguage": { "sLengthMenu": "_MENU_ per page", "oPaginate": { "sPrevious": "Prev", "sNext": "Next" } }, "aoColumnDefs": [{ 'bSortable': false, 'aTargets': [0] }] }); jQuery('#sample_2 .group-checkable').change(function () { var set = jQuery(this).attr("data-set"); var checked = jQuery(this).is(":checked"); jQuery(set).each(function () { if (checked) { $(this).attr("checked", true); } else { $(this).attr("checked", false); } }); jQuery.uniform.update(set); }); jQuery('#sample_2_wrapper .dataTables_filter input').addClass("input-small"); // modify table search input jQuery('#sample_2_wrapper .dataTables_length select').addClass("input-mini"); // modify table per page dropdown // begin: third table $('#sample_3').dataTable({ "sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>", "sPaginationType": "bootstrap", "oLanguage": { "sLengthMenu": "_MENU_ per page", "oPaginate": { "sPrevious": "Prev", "sNext": "Next" } }, "aoColumnDefs": [{ 'bSortable': false, 'aTargets': [0] }] }); jQuery('#sample_3 .group-checkable').change(function () { var set = jQuery(this).attr("data-set"); var checked = jQuery(this).is(":checked"); jQuery(set).each(function () { if (checked) { $(this).attr("checked", true); } else { $(this).attr("checked", false); } }); jQuery.uniform.update(set); }); jQuery('#sample_3_wrapper .dataTables_filter input').addClass("input-small"); // modify table search input jQuery('#sample_3_wrapper .dataTables_length select').addClass("input-mini"); // modify table per page dropdown } var handleDateTimePickers = function () { if (!jQuery().daterangepicker) { return; } $('.date-range').daterangepicker(); $('#dashboard-report-range').daterangepicker({ ranges: { 'Today': ['today', 'today'], 'Yesterday': ['yesterday', 'yesterday'], 'Last 7 Days': [Date.today().add({ days: -6 }), 'today'], 'Last 30 Days': [Date.today().add({ days: -29 }), 'today'], 'This Month': [Date.today().moveToFirstDayOfMonth(), Date.today().moveToLastDayOfMonth()], 'Last Month': [Date.today().moveToFirstDayOfMonth().add({ months: -1 }), Date.today().moveToFirstDayOfMonth().add({ days: -1 })] }, opens: 'left', format: 'MM/dd/yyyy', separator: ' to ', startDate: Date.today().add({ days: -29 }), endDate: Date.today(), minDate: '01/01/2012', maxDate: '12/31/2014', locale: { applyLabel: 'Submit', fromLabel: 'From', toLabel: 'To', customRangeLabel: 'Custom Range', daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], firstDay: 1 }, showWeekNumbers: true, buttonClasses: ['btn-danger'] }, function (start, end) { App.blockUI(jQuery("#page")); setTimeout(function () { App.unblockUI(jQuery("#page")); $.gritter.add({ title: 'Dashboard', text: 'Dashboard date range updated.' }); App.scrollTo(); }, 1000); $('#dashboard-report-range span').html(start.toString('MMMM d, yyyy') + ' - ' + end.toString('MMMM d, yyyy')); }); $('#dashboard-report-range span').html(Date.today().add({ days: -29 }).toString('MMMM d, yyyy') + ' - ' + Date.today().toString('MMMM d, yyyy')); $('#form-date-range').daterangepicker({ ranges: { 'Today': ['today', 'today'], 'Yesterday': ['yesterday', 'yesterday'], 'Last 7 Days': [Date.today().add({ days: -6 }), 'today'], 'Last 30 Days': [Date.today().add({ days: -29 }), 'today'], 'This Month': [Date.today().moveToFirstDayOfMonth(), Date.today().moveToLastDayOfMonth()], 'Last Month': [Date.today().moveToFirstDayOfMonth().add({ months: -1 }), Date.today().moveToFirstDayOfMonth().add({ days: -1 })] }, opens: 'right', format: 'MM/dd/yyyy', separator: ' to ', startDate: Date.today().add({ days: -29 }), endDate: Date.today(), minDate: '01/01/2012', maxDate: '12/31/2014', locale: { applyLabel: 'Submit', fromLabel: 'From', toLabel: 'To', customRangeLabel: 'Custom Range', daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], firstDay: 1 }, showWeekNumbers: true, buttonClasses: ['btn-danger'] }, function (start, end) { $('#form-date-range span').html(start.toString('MMMM d, yyyy') + ' - ' + end.toString('MMMM d, yyyy')); }); $('#form-date-range span').html(Date.today().add({ days: -29 }).toString('MMMM d, yyyy') + ' - ' + Date.today().toString('MMMM d, yyyy')); if (!jQuery().datepicker || !jQuery().timepicker) { return; } $('.date-picker').datepicker(); $('.timepicker-default').timepicker(); $('.timepicker-24').timepicker({ minuteStep: 1, showSeconds: true, showMeridian: false }); } var handleColorPicker = function () { if (!jQuery().colorpicker) { return; } $('.colorpicker-default').colorpicker({ format: 'hex' }); $('.colorpicker-rgba').colorpicker(); } var handleAccordions = function () { $(".accordion").collapse().height('auto'); } var handleScrollers = function () { if (!jQuery().slimScroll) { return; } $('.scroller').each(function () { $(this).slimScroll({ //start: $('.blah:eq(1)'), height: $(this).attr("data-height"), alwaysVisible: ($(this).attr("data-always-visible") == "1" ? true : false), railVisible: ($(this).attr("data-rail-visible") == "1" ? true : false), disableFadeOut: true }); }); } var handleFormWizards = function () { if (!jQuery().bootstrapWizard) { return; } $('#form_wizard_1').bootstrapWizard({ 'nextSelector': '.button-next', 'previousSelector': '.button-previous', onTabClick: function (tab, navigation, index) { alert('on tab click disabled'); return false; }, onNext: function (tab, navigation, index) { var total = navigation.find('li').length; var current = index + 1; // set wizard title $('.step-title', $('#form_wizard_1')).text('Step ' + (index + 1) + ' of ' + total); // set done steps jQuery('li', $('#form_wizard_1')).removeClass("done"); var li_list = navigation.find('li'); for (var i = 0; i < index; i++) { jQuery(li_list[i]).addClass("done"); } if (current == 1) { $('#form_wizard_1').find('.button-previous').hide(); } else { $('#form_wizard_1').find('.button-previous').show(); } if (current >= total) { $('#form_wizard_1').find('.button-next').hide(); $('#form_wizard_1').find('.button-submit').show(); } else { $('#form_wizard_1').find('.button-next').show(); $('#form_wizard_1').find('.button-submit').hide(); } App.scrollTo($('.page-title')); }, onPrevious: function (tab, navigation, index) { var total = navigation.find('li').length; var current = index + 1; // set wizard title $('.step-title', $('#form_wizard_1')).text('Step ' + (index + 1) + ' of ' + total); // set done steps jQuery('li', $('#form_wizard_1')).removeClass("done"); var li_list = navigation.find('li'); for (var i = 0; i < index; i++) { jQuery(li_list[i]).addClass("done"); } if (current == 1) { $('#form_wizard_1').find('.button-previous').hide(); } else { $('#form_wizard_1').find('.button-previous').show(); } if (current >= total) { $('#form_wizard_1').find('.button-next').hide(); $('#form_wizard_1').find('.button-submit').show(); } else { $('#form_wizard_1').find('.button-next').show(); $('#form_wizard_1').find('.button-submit').hide(); } App.scrollTo($('.page-title')); }, onTabShow: function (tab, navigation, index) { var total = navigation.find('li').length; var current = index + 1; var $percent = (current / total) * 100; $('#form_wizard_1').find('.bar').css({ width: $percent + '%' }); } }); $('#form_wizard_1').find('.button-previous').hide(); $('#form_wizard_1 .button-submit').click(function () { alert('Finished!'); }).hide(); } var handleTagsInput = function () { if (!jQuery().tagsInput) { return; } $('#tags_1').tagsInput({ width: 'auto' }); $('#tags_2').tagsInput({ width: 240 }); } var handleGoTop = function () { /* set variables locally for increased performance */ jQuery('#footer .go-top').click(function () { App.scrollTo(); }); } // this is optional to use if you want animated show/hide. But plot charts can make the animation slow. var handleSidebarTogglerAnimated = function () { $('.sidebar-toggler').click(function () { if ($('#sidebar > ul').is(":visible") === true) { $('#main-content').animate({ 'margin-left': '25px' }); $('#sidebar').animate({ 'margin-left': '-190px' }, { complete: function () { $('#sidebar > ul').hide(); $("#container").addClass("sidebar-closed"); } }); } else { $('#main-content').animate({ 'margin-left': '215px' }); $('#sidebar > ul').show(); $('#sidebar').animate({ 'margin-left': '0' }, { complete: function () { $("#container").removeClass("sidebar-closed"); } }); } }) } // by default used simple show/hide without animation due to the issue with handleSidebarTogglerAnimated. var handleSidebarToggler = function () { $('.sidebar-toggler').click(function () { if ($('#sidebar > ul').is(":visible") === true) { $('#main-content').css({ 'margin-left': '25px' }); $('#sidebar').css({ 'margin-left': '-190px' }); $('#sidebar > ul').hide(); $("#container").addClass("sidebar-closed"); } else { $('#main-content').css({ 'margin-left': '215px' }); $('#sidebar > ul').show(); $('#sidebar').css({ 'margin-left': '0' }); $("#container").removeClass("sidebar-closed"); } }) } return { //main function to initiate template pages init: function () { if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) == 8) { isIE8 = true; // checkes for IE8 browser version $('.visible-ie8').show(); } handleDeviceWidth(); // handles proper responsive features of the page handleChoosenSelect(); // handles bootstrap chosen dropdowns if (isMainPage) { handleDashboardCharts(); // handles plot charts for main page handleJQVMAP(); // handles vector maps for home page handleDashboardCalendar(); // handles full calendar for main page handleChat() // handles dashboard chat } else { handleCalendar(); // handles full calendars handlePortletSortable(); // handles portlet draggable sorting } if (isMapPage) { handleAllJQVMAP(); // handles vector maps for interactive map page } handleScrollers(); // handles slim scrolling contents handleUniform(); // handles uniform elements handleClockfaceTimePickers(); //handles form clockface timepickers handleTagsInput() // handles tag input elements handleTables(); // handles data tables handleCharts(); // handles plot charts handleWidgetTools(); // handles portlet action bar functionality(refresh, configure, toggle, remove) handlePulsate(); // handles pulsate functionality on page elements handlePeity(); // handles pierty bar and line charts handleGritterNotifications(); // handles gritter notifications handleTooltip(); // handles bootstrap tooltips handlePopover(); // handles bootstrap popovers handleToggleButtons(); // handles form toogle buttons handleWysihtml5(); //handles WYSIWYG Editor handleDateTimePickers(); //handles form timepickers handleColorPicker(); // handles form color pickers handleFancyBox(); // handles fancy box image previews handleStyler(); // handles style customer tool handleMainMenu(); // handles main menu handleFixInputPlaceholderForIE(); // fixes/enables html5 placeholder attribute for IE9, IE8 handleGoTop(); //handles scroll to top functionality in the footer handleAccordions(); handleFormWizards(); handleSidebarToggler(); if (isMainPage) { // this is for demo purpose. you may remove handleIntro function for your project handleIntro(); } }, // login page setup initLogin: function () { handleLoginForm(); handleFixInputPlaceholderForIE(); }, // wrapper function for page element pulsate pulsate: function (el, options) { var opt = jQuery.extend(options, { color: '#d12610', // set the color of the pulse reach: 15, // how far the pulse goes in px speed: 300, // how long one pulse takes in ms pause: 0, // how long the pause between pulses is in ms glow: false, // if the glow should be shown too repeat: 1, // will repeat forever if true, if given a number will repeat for that many times onHover: false // if true only pulsate if user hovers over the element }); jQuery(el).pulsate(opt); }, // wrapper function to scroll to an element scrollTo: function (el) { pos = el ? el.offset().top : 0; jQuery('html,body').animate({ scrollTop: pos }, 'slow'); }, // wrapper function to block element(indicate loading) blockUI: function (el, loaderOnTop) { lastBlockedUI = el; jQuery(el).block({ message: '<img src="img/loading.gif" align="absmiddle">', css: { border: 'none', padding: '2px', backgroundColor: 'none' }, overlayCSS: { backgroundColor: '#000', opacity: 0.05, cursor: 'wait' } }); }, // wrapper function to un-block element(finish loading) unblockUI: function (el) { jQuery(el).unblock({ onUnblock: function () { jQuery(el).removeAttr("style"); } }); }, // set main page setMainPage: function (flag) { isMainPage = flag; }, // set map page setMapPage: function (flag) { isMapPage = flag; } }; //input mask $('.inputmask').inputmask(); }(); //tooltips $('.element').tooltip(); // Slider input js try{ jQuery("#Slider1").slider({ from: 5, to: 50, step: 2.5, round: 1, dimension: '&nbsp;$', skin: "round_plastic" }); jQuery("#Slider2").slider({ from: 5000, to: 150000, heterogeneity: ['50/50000'], step: 1000, dimension: '&nbsp;$', skin: "round_plastic" }); jQuery("#Slider3").slider({ from: 1, to: 30, heterogeneity: ['50/5', '75/15'], scale: [1, '|', 3, '|', '5', '|', 15, '|', 30], limits: false, step: 1, dimension: '', skin: "round_plastic" }); jQuery("#Slider4").slider({ from: 480, to: 1020, step: 15, dimension: '', scale: ['8:00', '9:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00'], limits: false, skin: "round_plastic", calculate: function( value ){ var hours = Math.floor( value / 60 ); var mins = ( value - hours*60 ); return (hours < 10 ? "0"+hours : hours) + ":" + ( mins == 0 ? "00" : mins ); }}); } catch (e){ errorMessage(e); } //knob //$(".knob").knob();
JavaScript
//** Smooth Navigational Menu- By Dynamic Drive DHTML code library: http://www.dynamicdrive.com //** Script Download/ instructions page: http://www.dynamicdrive.com/dynamicindex1/ddlevelsmenu/ //** Menu created: Nov 12, 2008 //** Dec 12th, 08" (v1.01): Fixed Shadow issue when multiple LIs within the same UL (level) contain sub menus: http://www.dynamicdrive.com/forums/showthread.php?t=39177&highlight=smooth //** Feb 11th, 09" (v1.02): The currently active main menu item (LI A) now gets a CSS class of ".selected", including sub menu items. //** May 1st, 09" (v1.3): //** 1) Now supports vertical (side bar) menu mode- set "orientation" to 'v' //** 2) In IE6, shadows are now always disabled //** July 27th, 09" (v1.31): Fixed bug so shadows can be disabled if desired. //** Feb 2nd, 10" (v1.4): Adds ability to specify delay before sub menus appear and disappear, respectively. See showhidedelay variable below //** Dec 17th, 10" (v1.5): Updated menu shadow to use CSS3 box shadows when the browser is FF3.5+, IE9+, Opera9.5+, or Safari3+/Chrome. Only .js file changed. //** Jun 28th, 2012: Unofficial update adds optional hover images for down and right arrows in the format: filename_over.ext //** These must be present for whichever or both of the arrow(s) are used and will preload. //** Dec 23rd, 2012 Unofficial update to fixed configurable z-index, add method option to init "toggle" which activates on click or "hover" //** which activates on mouse over/out - defaults to "toggle" (click activation), with detection of touch devices to activate on click for them. //** Add option for when there are two or more menus using "toggle" activation, whether or not all previously opened menus collapse //** on new menu activation, or just those within that specific menu //** See: http://www.dynamicdrive.com/forums/showthread.php?72449-PLEASE-HELP-with-Smooth-Navigational-Menu-(v1-51)&p=288466#post288466 //** Feb 7th, 2013 Unofficial update change fixed configurable z-index back to graduated for cases of main UL wrapping. Update off menu click detection in //** ipad/iphone to touchstart because document click wasn't registering. see: http://www.dynamicdrive.com/forums/showthread.php?72825 //** Feb 14th, 2013 Add window.ontouchstart to means tests for detecting touch browsers - thanks DD! //** Feb 15th, 2013 Add 'ontouchstart' in window and 'ontouchstart' in document.documentElement to means tests for detecting touch browsers - thanks DD! //** Feb 20th, 2013 correct for IE 9+ sometimes adding a pixel to the offsetHeight of the top level trigger for horizontal menus //** Feb 23rd, 2013 move CSS3 shadow adjustment for IE 9+ to the script, add resize event for all browsers to reposition open toggle //** menus and shadows in window if they would have gone to a different position at the new window dimensions //** Feb 25th, 2013 (v2.0) All unofficial updates by John merged into official and now called v2.0. Changed "method" option's default value to "hover" //** May 14th, 2013 (v2.1) Adds class 'repositioned' to menus moved due to being too close to the browser's right edge //** May 30th, 2013 (v2.1) Change from version sniffing to means testing for jQuery versions which require added code for click toggle event handling //** Sept 15th, 2013 add workaround for false positives for touch on Chrome //** Sept 22nd, 2013 (v2.2) Add vertical repositioning if sub menu will not fit in the viewable vertical area. May be turned off by setting // repositionv: false, //** in the init. Sub menus that are vertically repositioned will have the class 'repositionedv' added to them. var ddsmoothmenu = { ///////////////////////// Global Configuration Options: ///////////////////////// //Specify full URL to down and right arrow images (23 is padding-right for top level LIs with drop downs, 6 is for vertical top level items with fly outs): arrowimages: {down:['downarrowclass', 'down.gif', 23], right:['rightarrowclass', 'right.gif', 6]}, transition: {overtime:300, outtime:300}, //duration of slide in/ out animation, in milliseconds shadow: true, //enable shadow? (offsets now set in ddsmoothmenu.css stylesheet) showhidedelay: {showdelay: 100, hidedelay: 200}, //set delay in milliseconds before sub menus appear and disappear, respectively zindexvalue: 1000, //set z-index value for menus closeonnonmenuclick: true, //when clicking outside of any "toggle" method menu, should all "toggle" menus close? closeonmouseout: false, //when leaving a "toggle" menu, should all "toggle" menus close? Will not work on touchscreen /////////////////////// End Global Configuration Options //////////////////////// overarrowre: /(?=\.(gif|jpg|jpeg|png|bmp))/i, overarrowaddtofilename: '_over', detecttouch: !!('ontouchstart' in window) || !!('ontouchstart' in document.documentElement) || !!window.ontouchstart || (!!window.Touch && !!window.Touch.length) || !!window.onmsgesturechange || (window.DocumentTouch && window.document instanceof window.DocumentTouch), detectwebkit: navigator.userAgent.toLowerCase().indexOf("applewebkit") > -1, //detect WebKit browsers (Safari, Chrome etc) idevice: /ipad|iphone/i.test(navigator.userAgent), detectie6: (function(){var ie; return (ie = /MSIE (\d+)/.exec(navigator.userAgent)) && ie[1] < 7;})(), detectie9: (function(){var ie; return (ie = /MSIE (\d+)/.exec(navigator.userAgent)) && ie[1] > 8;})(), ie9shadow: function(){}, css3support: typeof document.documentElement.style.boxShadow === 'string' || (!document.all && document.querySelector), //detect browsers that support CSS3 box shadows (ie9+ or FF3.5+, Safari3+, Chrome etc) prevobjs: [], menus: null, executelink: function($, prevobjs, e){ var prevscount = prevobjs.length, link = e.target; while(--prevscount > -1){ if(prevobjs[prevscount] === this){ prevobjs.splice(prevscount, 1); if(link.href !== ddsmoothmenu.emptyhash && link.href && $(link).is('a') && !$(link).children('span.' + ddsmoothmenu.arrowimages.down[0] +', span.' + ddsmoothmenu.arrowimages.right[0]).length){ if(link.target && link.target !== '_self'){ window.open(link.href, link.target); } else { window.location.href = link.href; } e.stopPropagation(); } } } }, repositionv: function($subul, $link, newtop, winheight, doctop, method, menutop){ menutop = menutop || 0; var topinc = 0, doclimit = winheight + doctop; $subul.css({top: newtop, display: 'block'}); while($subul.offset().top < doctop) { $subul.css({top: ++newtop}); ++topinc; } if(!topinc && $link.offset().top + $link.outerHeight() < doclimit && $subul.data('height') + $subul.offset().top > doclimit){ $subul.css({top: doctop - $link.parents('ul').last().offset().top - $link.position().top}); } method === 'toggle' && $subul.css({display: 'none'}); if(newtop !== menutop){$subul.addClass('repositionedv');} return [topinc, newtop]; }, updateprev: function($, prevobjs, $curobj){ var prevscount = prevobjs.length, prevobj, $indexobj = $curobj.parents().add(this); while(--prevscount > -1){ if($indexobj.index((prevobj = prevobjs[prevscount])) < 0){ $(prevobj).trigger('click', [1]); prevobjs.splice(prevscount, 1); } } prevobjs.push(this); }, subulpreventemptyclose: function(e){ var link = e.target; if(link.href === ddsmoothmenu.emptyhash && $(link).parent('li').find('ul').length < 1){ e.preventDefault(); e.stopPropagation(); } }, getajaxmenu: function($, setting, nobuild){ //function to fetch external page containing the panel DIVs var $menucontainer=$('#'+setting.contentsource[0]); //reference empty div on page that will hold menu $menucontainer.html("Loading Menu..."); $.ajax({ url: setting.contentsource[1], //path to external menu file async: true, error: function(ajaxrequest){ $menucontainer.html('Error fetching content. Server Response: '+ajaxrequest.responseText); }, success: function(content){ $menucontainer.html(content); !!!nobuild && ddsmoothmenu.buildmenu($, setting); } }); }, closeall: function(e){ var smoothmenu = ddsmoothmenu, prevscount; if(!smoothmenu.globaltrackopen){return;} if(e.type === 'mouseleave' || ((e.type === 'click' || e.type === 'touchstart') && smoothmenu.menus.index(e.target) < 0)){ prevscount = smoothmenu.prevobjs.length; while(--prevscount > -1){ $(smoothmenu.prevobjs[prevscount]).trigger('click'); smoothmenu.prevobjs.splice(prevscount, 1); } } }, emptyhash: $('<a href="#"></a>').get(0).href, buildmenu: function($, setting){ var smoothmenu = ddsmoothmenu; smoothmenu.globaltrackopen = smoothmenu.closeonnonmenuclick || smoothmenu.closeonmouseout; var zsub = 0; //subtractor to be incremented so that each top level menu can be covered by previous one's drop downs var prevobjs = smoothmenu.globaltrackopen? smoothmenu.prevobjs : []; var $mainparent = $("#"+setting.mainmenuid).removeClass("ddsmoothmenu ddsmoothmenu-v").addClass(setting.classname || "ddsmoothmenu"); setting.repositionv = setting.repositionv !== false; var $mainmenu = $mainparent.find('>ul'); //reference main menu UL var method = smoothmenu.detecttouch? 'toggle' : setting.method === 'toggle'? 'toggle' : 'hover'; var $topheaders = $mainmenu.find('>li>ul').parent();//has('ul'); var orient = setting.orientation!='v'? 'down' : 'right', $parentshadow = $(document.body); $mainmenu.click(function(e){e.target.href === smoothmenu.emptyhash && e.preventDefault();}); if(method === 'toggle') { if(smoothmenu.globaltrackopen){ smoothmenu.menus = smoothmenu.menus? smoothmenu.menus.add($mainmenu.add($mainmenu.find('*'))) : $mainmenu.add($mainmenu.find('*')); } if(smoothmenu.closeonnonmenuclick){ if(orient === 'down'){$mainparent.click(function(e){e.stopPropagation();});} $(document).unbind('click.smoothmenu').bind('click.smoothmenu', smoothmenu.closeall); if(smoothmenu.idevice){ document.removeEventListener('touchstart', smoothmenu.closeall, false); document.addEventListener('touchstart', smoothmenu.closeall, false); } } else if (setting.closeonnonmenuclick){ if(orient === 'down'){$mainparent.click(function(e){e.stopPropagation();});} $(document).bind('click.' + setting.mainmenuid, function(e){$mainmenu.find('li>a.selected').parent().trigger('click');}); if(smoothmenu.idevice){ document.addEventListener('touchstart', function(e){$mainmenu.find('li>a.selected').parent().trigger('click');}, false); } } if(smoothmenu.closeonmouseout){ var $leaveobj = orient === 'down'? $mainparent : $mainmenu; $leaveobj.bind('mouseleave.smoothmenu', smoothmenu.closeall); } else if (setting.closeonmouseout){ var $leaveobj = orient === 'down'? $mainparent : $mainmenu; $leaveobj.bind('mouseleave.smoothmenu', function(){$mainmenu.find('li>a.selected').parent().trigger('click');}); } if(!$('style[title="ddsmoothmenushadowsnone"]').length){ $('head').append('<style title="ddsmoothmenushadowsnone" type="text/css">.ddsmoothmenushadowsnone{display:none!important;}</style>'); } var shadowstimer; $(window).bind('resize scroll', function(){ clearTimeout(shadowstimer); var $selected = $mainmenu.find('li>a.selected').parent(), $shadows = $('.ddshadow').addClass('ddsmoothmenushadowsnone'); $selected.eq(0).trigger('click'); $selected.trigger('click'); shadowstimer = setTimeout(function(){$shadows.removeClass('ddsmoothmenushadowsnone');}, 100); }); } $topheaders.each(function(){ var $curobj=$(this).css({zIndex: (setting.zindexvalue || smoothmenu.zindexvalue) + zsub--}); //reference current LI header var $subul=$curobj.children('ul:eq(0)').css({display:'block'}).data('timers', {}); var $link = $curobj.children("a:eq(0)").css({paddingRight: smoothmenu.arrowimages[orient][2]}).append( //add arrow images '<span style="display: block;" class="' + smoothmenu.arrowimages[orient][0] + '"></span>' ); var dimensions = { w : $link.outerWidth(), h : $curobj.innerHeight(), subulw : $subul.outerWidth(), subulh : $subul.outerHeight() }; var menutop = orient === 'down'? dimensions.h : 0; $subul.css({top: menutop}); function restore(){$link.removeClass('selected');} method === 'toggle' && $subul.click(smoothmenu.subulpreventemptyclose); $curobj[method]( function(e){ if(!$curobj.data('headers')){ smoothmenu.buildsubheaders($, $subul.find('>li>ul').parent(), setting, method, prevobjs); $curobj.data('headers', true).find('>ul').each(function(i, ul){ var $ul = $(ul); $ul.data('height', $ul.outerHeight()); }).css({display:'none', visibility:'visible'}); } method === 'toggle' && smoothmenu.updateprev.call(this, $, prevobjs, $curobj); clearTimeout($subul.data('timers').hidetimer); $link.addClass('selected'); $subul.data('timers').showtimer=setTimeout(function(){ var menuleft = orient === 'down'? 0 : dimensions.w; var menumoved = menuleft, newtop, doctop, winheight, topinc = 0; menuleft=($curobj.offset().left+menuleft+dimensions.subulw>$(window).width())? (orient === 'down'? -dimensions.subulw+dimensions.w : -dimensions.w) : menuleft; //calculate this sub menu's offsets from its parent menumoved = menumoved !== menuleft; $subul.css({top: menutop}).removeClass('repositionedv'); if(setting.repositionv && $link.offset().top + menutop + $subul.data('height') > (winheight = $(window).height()) + (doctop = $(document).scrollTop())){ newtop = (orient === 'down'? 0 : $link.outerHeight()) - $subul.data('height'); topinc = smoothmenu.repositionv($subul, $link, newtop, winheight, doctop, method, menutop)[0]; } $subul.css({left:menuleft, width:dimensions.subulw}).stop(true, true).animate({height:'show',opacity:'show'}, smoothmenu.transition.overtime, function(){this.style.removeAttribute && this.style.removeAttribute('filter');}); if(menumoved){$subul.addClass('repositioned');} else {$subul.removeClass('repositioned');} if (setting.shadow){ if(!$curobj.data('$shadow')){ $curobj.data('$shadow', $('<div></div>').addClass('ddshadow toplevelshadow').prependTo($parentshadow).css({zIndex: $curobj.css('zIndex')})); //insert shadow DIV and set it to parent node for the next shadow div } smoothmenu.ie9shadow($curobj.data('$shadow')); var offsets = $subul.offset(); var shadowleft = offsets.left; var shadowtop = offsets.top; $curobj.data('$shadow').css({overflow: 'visible', width:dimensions.subulw, left:shadowleft, top:shadowtop}).stop(true, true).animate({height:dimensions.subulh}, smoothmenu.transition.overtime); } }, smoothmenu.showhidedelay.showdelay); }, function(e, speed){ var $shadow = $curobj.data('$shadow'); if(method === 'hover'){restore();} else{smoothmenu.executelink.call(this, $, prevobjs, e);} clearTimeout($subul.data('timers').showtimer); $subul.data('timers').hidetimer=setTimeout(function(){ $subul.stop(true, true).animate({height:'hide', opacity:'hide'}, speed || smoothmenu.transition.outtime, function(){method === 'toggle' && restore();}); if ($shadow){ if (!smoothmenu.css3support && smoothmenu.detectwebkit){ //in WebKit browsers, set first child shadow's opacity to 0, as "overflow:hidden" doesn't work in them $shadow.children('div:eq(0)').css({opacity:0}); } $shadow.stop(true, true).animate({height:0}, speed || smoothmenu.transition.outtime, function(){if(method === 'toggle'){this.style.overflow = 'hidden';}}); } }, smoothmenu.showhidedelay.hidedelay); } ); //end hover/toggle }); //end $topheaders.each() }, buildsubheaders: function($, $headers, setting, method, prevobjs){ //setting.$mainparent.data('$headers').add($headers); $headers.each(function(){ //loop through each LI header var smoothmenu = ddsmoothmenu; var $curobj=$(this).css({zIndex: $(this).parent('ul').css('z-index')}); //reference current LI header var $subul=$curobj.children('ul:eq(0)').css({display:'block'}).data('timers', {}), $parentshadow; method === 'toggle' && $subul.click(smoothmenu.subulpreventemptyclose); var $link = $curobj.children("a:eq(0)").append( //add arrow images '<span style="display: block;" class="' + smoothmenu.arrowimages['right'][0] + '"></span>' ); var dimensions = { w : $link.outerWidth(), subulw : $subul.outerWidth(), subulh : $subul.outerHeight() }; $subul.css({top: 0}); function restore(){$link.removeClass('selected');} $curobj[method]( function(e){ if(!$curobj.data('headers')){ smoothmenu.buildsubheaders($, $subul.find('>li>ul').parent(), setting, method, prevobjs); $curobj.data('headers', true).find('>ul').each(function(i, ul){ var $ul = $(ul); $ul.data('height', $ul.height()); }).css({display:'none', visibility:'visible'}); } method === 'toggle' && smoothmenu.updateprev.call(this, $, prevobjs, $curobj); clearTimeout($subul.data('timers').hidetimer); $link.addClass('selected'); $subul.data('timers').showtimer=setTimeout(function(){ var menuleft= dimensions.w; var menumoved = menuleft, newtop, doctop, winheight, topinc = 0; menuleft=($curobj.offset().left+menuleft+dimensions.subulw>$(window).width())? -dimensions.w : menuleft; //calculate this sub menu's offsets from its parent menumoved = menumoved !== menuleft; $subul.css({top: 0}).removeClass('repositionedv'); if(setting.repositionv && $link.offset().top + $subul.data('height') > (winheight = $(window).height()) + (doctop = $(document).scrollTop())){ newtop = $link.outerHeight() - $subul.data('height'); topinc = smoothmenu.repositionv($subul, $link, newtop, winheight, doctop, method); newtop = topinc[1]; topinc = topinc[0]; } $subul.css({left:menuleft, width:dimensions.subulw}).stop(true, true).animate({height:'show',opacity:'show'}, smoothmenu.transition.overtime, function(){this.style.removeAttribute && this.style.removeAttribute('filter');}); if(menumoved){$subul.addClass('repositioned');} else {$subul.removeClass('repositioned');} if (setting.shadow){ if(!$curobj.data('$shadow')){ $parentshadow = $curobj.parents("li:eq(0)").data('$shadow'); $curobj.data('$shadow', $('<div></div>').addClass('ddshadow').prependTo($parentshadow).css({zIndex: $parentshadow.css('z-index')})); //insert shadow DIV and set it to parent node for the next shadow div } var offsets = $subul.offset(); var shadowleft = menuleft; var shadowtop = $curobj.position().top - (newtop? $subul.data('height') - $link.outerHeight() - topinc : 0); if (smoothmenu.detectwebkit && !smoothmenu.css3support){ //in WebKit browsers, restore shadow's opacity to full $curobj.data('$shadow').css({opacity:1}); } $curobj.data('$shadow').css({overflow: 'visible', width:dimensions.subulw, left:shadowleft, top:shadowtop}).stop(true, true).animate({height:dimensions.subulh}, smoothmenu.transition.overtime); } }, smoothmenu.showhidedelay.showdelay); }, function(e, speed){ var $shadow = $curobj.data('$shadow'); if(method === 'hover'){restore();} else{smoothmenu.executelink.call(this, $, prevobjs, e);} clearTimeout($subul.data('timers').showtimer); $subul.data('timers').hidetimer=setTimeout(function(){ $subul.stop(true, true).animate({height:'hide', opacity:'hide'}, speed || smoothmenu.transition.outtime, function(){ method === 'toggle' && restore(); }); if ($shadow){ if (!smoothmenu.css3support && smoothmenu.detectwebkit){ //in WebKit browsers, set first child shadow's opacity to 0, as "overflow:hidden" doesn't work in them $shadow.children('div:eq(0)').css({opacity:0}); } $shadow.stop(true, true).animate({height:0}, speed || smoothmenu.transition.outtime, function(){if(method === 'toggle'){this.style.overflow = 'hidden';}}); } }, smoothmenu.showhidedelay.hidedelay); } ); //end hover/toggle for subheaders }); //end $headers.each() for subheaders }, init: function(setting){ if(this.detectie6 && parseFloat(jQuery.fn.jquery) > 1.3){ this.init = function(setting){ if (typeof setting.contentsource=="object"){ //if external ajax menu jQuery(function($){ddsmoothmenu.getajaxmenu($, setting, 'nobuild');}); } return false; }; jQuery('link[href*="ddsmoothmenu"]').attr('disabled', true); jQuery(function($){ alert('You Seriously Need to Update Your Browser!\n\nDynamic Drive Smooth Navigational Menu Showing Text Only Menu(s)\n\nDEVELOPER\'s NOTE: This script will run in IE 6 when using jQuery 1.3.2 or less,\nbut not real well.'); $('link[href*="ddsmoothmenu"]').attr('disabled', true); }); return this.init(setting); } var mainmenuid = '#' + setting.mainmenuid, right, down, stylestring = ['</style>\n'], stylesleft = setting.arrowswap? 4 : 2; function addstyles(){ if(stylesleft){return;} if (typeof setting.customtheme=="object" && setting.customtheme.length==2){ //override default menu colors (default/hover) with custom set? var mainselector=(setting.orientation=="v")? mainmenuid : mainmenuid+', '+mainmenuid; stylestring.push([mainselector,' ul li a {background:',setting.customtheme[0],';}\n', mainmenuid,' ul li a:hover {background:',setting.customtheme[1],';}'].join('')); } stylestring.push('\n<style type="text/css">'); stylestring.reverse(); jQuery('head').append(stylestring.join('\n')); } if(setting.arrowswap){ right = ddsmoothmenu.arrowimages.right[1].replace(ddsmoothmenu.overarrowre, ddsmoothmenu.overarrowaddtofilename); down = ddsmoothmenu.arrowimages.down[1].replace(ddsmoothmenu.overarrowre, ddsmoothmenu.overarrowaddtofilename); jQuery(new Image()).bind('load error', function(e){ setting.rightswap = e.type === 'load'; if(setting.rightswap){ stylestring.push([mainmenuid, ' ul li a:hover .', ddsmoothmenu.arrowimages.right[0], ', ', mainmenuid, ' ul li a.selected .', ddsmoothmenu.arrowimages.right[0], ' { background-image: url(', this.src, ');}'].join('')); } --stylesleft; addstyles(); }).attr('src', right); jQuery(new Image()).bind('load error', function(e){ setting.downswap = e.type === 'load'; if(setting.downswap){ stylestring.push([mainmenuid, ' ul li a:hover .', ddsmoothmenu.arrowimages.down[0], ', ', mainmenuid, ' ul li a.selected .', ddsmoothmenu.arrowimages.down[0], ' { background-image: url(', this.src, ');}'].join('')); } --stylesleft; addstyles(); }).attr('src', down); } jQuery(new Image()).bind('load error', function(e){ if(e.type === 'load'){ stylestring.push([mainmenuid+' ul li a .', ddsmoothmenu.arrowimages.right[0],' { background: url(', this.src, ') no-repeat;width:', this.width,'px;height:', this.height, 'px;}'].join('')); } --stylesleft; addstyles(); }).attr('src', ddsmoothmenu.arrowimages.right[1]); jQuery(new Image()).bind('load error', function(e){ if(e.type === 'load'){ stylestring.push([mainmenuid+' ul li a .', ddsmoothmenu.arrowimages.down[0],' { background: url(', this.src, ') no-repeat;width:', this.width,'px;height:', this.height, 'px;}'].join('')); } --stylesleft; addstyles(); }).attr('src', ddsmoothmenu.arrowimages.down[1]); setting.shadow = this.detectie6 && (setting.method === 'hover' || setting.orientation === 'v')? false : setting.shadow || this.shadow; //in IE6, always disable shadow except for horizontal toggle menus jQuery(document).ready(function($){ //ajax menu? if (setting.shadow && ddsmoothmenu.css3support){$('body').addClass('ddcss3support');} if (typeof setting.contentsource=="object"){ //if external ajax menu ddsmoothmenu.getajaxmenu($, setting); } else{ //else if markup menu ddsmoothmenu.buildmenu($, setting); } }); } }; //end ddsmoothmenu variable // Patch for jQuery 1.9+ which lack click toggle (deprecated in 1.8, removed in 1.9) // Will not run if using another patch like jQuery Migrate, which also takes care of this if( (function($){ var clicktogglable = false; try { $('<a href="#"></a>').toggle(function(){}, function(){clicktogglable = true;}).trigger('click').trigger('click'); } catch(e){} return !clicktogglable; })(jQuery) ){ (function(){ var toggleDisp = jQuery.fn.toggle; // There's an animation/css method named .toggle() that toggles display. Save a reference to it. jQuery.extend(jQuery.fn, { toggle: function( fn, fn2 ) { // The method fired depends on the arguments passed. if ( !jQuery.isFunction( fn ) || !jQuery.isFunction( fn2 ) ) { return toggleDisp.apply(this, arguments); } // 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 ); } }); })(); } /* TECHNICAL NOTE: To overcome an intermittent layout bug in IE 9+, the script will change margin top and left for the shadows to 1px less than their computed values, and the first two values for the box-shadow property will be changed to 1px larger than computed, ex: -1px top and left margins and 6px 6px 5px #aaa box-shadow results in what appears to be a 5px box-shadow. Other browsers skip this step and it shouldn't affect you in most cases. In some rare cases it will result in slightly narrower (by 1px) box shadows for IE 9+ on one or more of the drop downs. Without this, sometimes the shadows could be 1px beyond their drop down resulting in a gap. This is the first of the two patches below. and also relates to the MS CSSOM which uses decimal fractions of pixels for layout while only reporting rounded values. There appears to be no computedStyle workaround for this one. */ //Scripted CSS Patch for IE 9+ intermittent mis-rendering of box-shadow elements (see above TECHNICAL NOTE for more info) //And jQuery Patch for IE 9+ CSSOM re: offset Width and Height and re: getBoundingClientRect(). Both run only in IE 9 and later. //IE 9 + uses decimal fractions of pixels internally for layout but only reports rounded values using the offset and getBounding methods. //These are sometimes rounded inconsistently. This second patch gets the decimal values directly from computedStyle. if(ddsmoothmenu.detectie9){ (function($){ //begin Scripted CSS Patch function incdec(v, how){return parseInt(v) + how + 'px';} ddsmoothmenu.ie9shadow = function($elem){ //runs once var getter = document.defaultView.getComputedStyle($elem.get(0), null), curshadow = getter.getPropertyValue('box-shadow').split(' '), curmargin = {top: getter.getPropertyValue('margin-top'), left: getter.getPropertyValue('margin-left')}; $('head').append(['\n<style title="ie9shadow" type="text/css">', '.ddcss3support .ddshadow {', '\tbox-shadow: ' + incdec(curshadow[0], 1) + ' ' + incdec(curshadow[1], 1) + ' ' + curshadow[2] + ' ' + curshadow[3] + ';', '}', '.ddcss3support .ddshadow.toplevelshadow {', '\topacity: ' + ($('.ddcss3support .ddshadow').css('opacity') - 0.1) + ';', '\tmargin-top: ' + incdec(curmargin.top, -1) + ';', '\tmargin-left: ' + incdec(curmargin.left, -1) + ';', '}', '</style>\n'].join('\n')); ddsmoothmenu.ie9shadow = function(){}; //becomes empty function after running once }; //end Scripted CSS Patch var jqheight = $.fn.height, jqwidth = $.fn.width; //begin jQuery Patch for IE 9+ .height() and .width() $.extend($.fn, { height: function(){ var obj = this.get(0); if(this.length < 1 || arguments.length || obj === window || obj === document){ return jqheight.apply(this, arguments); } return parseFloat(document.defaultView.getComputedStyle(obj, null).getPropertyValue('height')); }, innerHeight: function(){ if(this.length < 1){return null;} var val = this.height(), obj = this.get(0), getter = document.defaultView.getComputedStyle(obj, null); val += parseInt(getter.getPropertyValue('padding-top')); val += parseInt(getter.getPropertyValue('padding-bottom')); return val; }, outerHeight: function(bool){ if(this.length < 1){return null;} var val = this.innerHeight(), obj = this.get(0), getter = document.defaultView.getComputedStyle(obj, null); val += parseInt(getter.getPropertyValue('border-top-width')); val += parseInt(getter.getPropertyValue('border-bottom-width')); if(bool){ val += parseInt(getter.getPropertyValue('margin-top')); val += parseInt(getter.getPropertyValue('margin-bottom')); } return val; }, width: function(){ var obj = this.get(0); if(this.length < 1 || arguments.length || obj === window || obj === document){ return jqwidth.apply(this, arguments); } return parseFloat(document.defaultView.getComputedStyle(obj, null).getPropertyValue('width')); }, innerWidth: function(){ if(this.length < 1){return null;} var val = this.width(), obj = this.get(0), getter = document.defaultView.getComputedStyle(obj, null); val += parseInt(getter.getPropertyValue('padding-right')); val += parseInt(getter.getPropertyValue('padding-left')); return val; }, outerWidth: function(bool){ if(this.length < 1){return null;} var val = this.innerWidth(), obj = this.get(0), getter = document.defaultView.getComputedStyle(obj, null); val += parseInt(getter.getPropertyValue('border-right-width')); val += parseInt(getter.getPropertyValue('border-left-width')); if(bool){ val += parseInt(getter.getPropertyValue('margin-right')); val += parseInt(getter.getPropertyValue('margin-left')); } return val; } }); //end jQuery Patch for IE 9+ .height() and .width() })(jQuery); }
JavaScript
/** * Skies theme for Highcharts JS * @author Torstein Hønsi */ Highcharts.theme = { colors: ["#514F78", "#42A07B", "#9B5E4A", "#72727F", "#1F949A", "#82914E", "#86777F", "#42A07B"], chart: { className: 'skies', borderWidth: 0, plotShadow: true, plotBackgroundImage: 'http://www.highcharts.com/demo/gfx/skies.jpg', plotBackgroundColor: { linearGradient: [0, 0, 250, 500], stops: [ [0, 'rgba(255, 255, 255, 1)'], [1, 'rgba(255, 255, 255, 0)'] ] }, plotBorderWidth: 1 }, title: { style: { color: '#3E576F', font: '16px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } }, subtitle: { style: { color: '#6D869F', font: '12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } }, xAxis: { gridLineWidth: 0, lineColor: '#C0D0E0', tickColor: '#C0D0E0', labels: { style: { color: '#666', fontWeight: 'bold' } }, title: { style: { color: '#666', font: '12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } } }, yAxis: { alternateGridColor: 'rgba(255, 255, 255, .5)', lineColor: '#C0D0E0', tickColor: '#C0D0E0', tickWidth: 1, labels: { style: { color: '#666', fontWeight: 'bold' } }, title: { style: { color: '#666', font: '12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } } }, legend: { itemStyle: { font: '9pt Trebuchet MS, Verdana, sans-serif', color: '#3E576F' }, itemHoverStyle: { color: 'black' }, itemHiddenStyle: { color: 'silver' } }, labels: { style: { color: '#3E576F' } } }; // Apply the theme var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
JavaScript
/** * Dark blue theme for Highcharts JS * @author Torstein Hønsi */ Highcharts.theme = { colors: ["#DDDF0D", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee", "#ff0066", "#eeaaee", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee"], chart: { backgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 1, y2: 1 }, stops: [ [0, 'rgb(48, 48, 96)'], [1, 'rgb(0, 0, 0)'] ] }, borderColor: '#000000', borderWidth: 2, className: 'dark-container', plotBackgroundColor: 'rgba(255, 255, 255, .1)', plotBorderColor: '#CCCCCC', plotBorderWidth: 1 }, title: { style: { color: '#C0C0C0', font: 'bold 16px "Trebuchet MS", Verdana, sans-serif' } }, subtitle: { style: { color: '#666666', font: 'bold 12px "Trebuchet MS", Verdana, sans-serif' } }, xAxis: { gridLineColor: '#333333', gridLineWidth: 1, labels: { style: { color: '#A0A0A0' } }, lineColor: '#A0A0A0', tickColor: '#A0A0A0', title: { style: { color: '#CCC', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, yAxis: { gridLineColor: '#333333', labels: { style: { color: '#A0A0A0' } }, lineColor: '#A0A0A0', minorTickInterval: null, tickColor: '#A0A0A0', tickWidth: 1, title: { style: { color: '#CCC', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, tooltip: { backgroundColor: 'rgba(0, 0, 0, 0.75)', style: { color: '#F0F0F0' } }, toolbar: { itemStyle: { color: 'silver' } }, plotOptions: { line: { dataLabels: { color: '#CCC' }, marker: { lineColor: '#333' } }, spline: { marker: { lineColor: '#333' } }, scatter: { marker: { lineColor: '#333' } }, candlestick: { lineColor: 'white' } }, legend: { itemStyle: { font: '9pt Trebuchet MS, Verdana, sans-serif', color: '#A0A0A0' }, itemHoverStyle: { color: '#FFF' }, itemHiddenStyle: { color: '#444' } }, credits: { style: { color: '#666' } }, labels: { style: { color: '#CCC' } }, navigation: { buttonOptions: { symbolStroke: '#DDDDDD', hoverSymbolStroke: '#FFFFFF', theme: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#606060'], [0.6, '#333333'] ] }, stroke: '#000000' } } }, // scroll charts rangeSelector: { buttonTheme: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, stroke: '#000000', style: { color: '#CCC', fontWeight: 'bold' }, states: { hover: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#BBB'], [0.6, '#888'] ] }, stroke: '#000000', style: { color: 'white' } }, select: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.1, '#000'], [0.3, '#333'] ] }, stroke: '#000000', style: { color: 'yellow' } } } }, inputStyle: { backgroundColor: '#333', color: 'silver' }, labelStyle: { color: 'silver' } }, navigator: { handles: { backgroundColor: '#666', borderColor: '#AAA' }, outlineColor: '#CCC', maskFill: 'rgba(16, 16, 16, 0.5)', series: { color: '#7798BF', lineColor: '#A6C7ED' } }, scrollbar: { barBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, barBorderColor: '#CCC', buttonArrowColor: '#CCC', buttonBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, buttonBorderColor: '#CCC', rifleColor: '#FFF', trackBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0, '#000'], [1, '#333'] ] }, trackBorderColor: '#666' }, // special colors for some of the legendBackgroundColor: 'rgba(0, 0, 0, 0.5)', legendBackgroundColorSolid: 'rgb(35, 35, 70)', dataLabelsColor: '#444', textColor: '#C0C0C0', maskColor: 'rgba(255,255,255,0.3)' }; // Apply the theme var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
JavaScript
/** * Grid theme for Highcharts JS * @author Torstein Hønsi */ Highcharts.theme = { colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4'], chart: { backgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 1, y2: 1 }, stops: [ [0, 'rgb(255, 255, 255)'], [1, 'rgb(240, 240, 255)'] ] }, borderWidth: 2, plotBackgroundColor: 'rgba(255, 255, 255, .9)', plotShadow: true, plotBorderWidth: 1 }, title: { style: { color: '#000', font: 'bold 16px "Trebuchet MS", Verdana, sans-serif' } }, subtitle: { style: { color: '#666666', font: 'bold 12px "Trebuchet MS", Verdana, sans-serif' } }, xAxis: { gridLineWidth: 1, lineColor: '#000', tickColor: '#000', labels: { style: { color: '#000', font: '11px Trebuchet MS, Verdana, sans-serif' } }, title: { style: { color: '#333', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, yAxis: { minorTickInterval: 'auto', lineColor: '#000', lineWidth: 1, tickWidth: 1, tickColor: '#000', labels: { style: { color: '#000', font: '11px Trebuchet MS, Verdana, sans-serif' } }, title: { style: { color: '#333', fontWeight: 'bold', fontSize: '12px', fontFamily: 'Trebuchet MS, Verdana, sans-serif' } } }, legend: { itemStyle: { font: '9pt Trebuchet MS, Verdana, sans-serif', color: 'black' }, itemHoverStyle: { color: '#039' }, itemHiddenStyle: { color: 'gray' } }, labels: { style: { color: '#99b' } }, navigation: { buttonOptions: { theme: { stroke: '#CCCCCC' } } } }; // Apply the theme var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
JavaScript
/** * Gray theme for Highcharts JS * @author Torstein Hønsi */ Highcharts.theme = { colors: ["#DDDF0D", "#7798BF", "#55BF3B", "#DF5353", "#aaeeee", "#ff0066", "#eeaaee", "#55BF3B", "#DF5353", "#7798BF", "#aaeeee"], chart: { backgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0, 'rgb(96, 96, 96)'], [1, 'rgb(16, 16, 16)'] ] }, borderWidth: 0, borderRadius: 15, plotBackgroundColor: null, plotShadow: false, plotBorderWidth: 0 }, title: { style: { color: '#FFF', font: '16px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } }, subtitle: { style: { color: '#DDD', font: '12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } }, xAxis: { gridLineWidth: 0, lineColor: '#999', tickColor: '#999', labels: { style: { color: '#999', fontWeight: 'bold' } }, title: { style: { color: '#AAA', font: 'bold 12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } } }, yAxis: { alternateGridColor: null, minorTickInterval: null, gridLineColor: 'rgba(255, 255, 255, .1)', minorGridLineColor: 'rgba(255,255,255,0.07)', lineWidth: 0, tickWidth: 0, labels: { style: { color: '#999', fontWeight: 'bold' } }, title: { style: { color: '#AAA', font: 'bold 12px Lucida Grande, Lucida Sans Unicode, Verdana, Arial, Helvetica, sans-serif' } } }, legend: { itemStyle: { color: '#CCC' }, itemHoverStyle: { color: '#FFF' }, itemHiddenStyle: { color: '#333' } }, labels: { style: { color: '#CCC' } }, tooltip: { backgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0, 'rgba(96, 96, 96, .8)'], [1, 'rgba(16, 16, 16, .8)'] ] }, borderWidth: 0, style: { color: '#FFF' } }, plotOptions: { series: { shadow: true }, line: { dataLabels: { color: '#CCC' }, marker: { lineColor: '#333' } }, spline: { marker: { lineColor: '#333' } }, scatter: { marker: { lineColor: '#333' } }, candlestick: { lineColor: 'white' } }, toolbar: { itemStyle: { color: '#CCC' } }, navigation: { buttonOptions: { symbolStroke: '#DDDDDD', hoverSymbolStroke: '#FFFFFF', theme: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#606060'], [0.6, '#333333'] ] }, stroke: '#000000' } } }, // scroll charts rangeSelector: { buttonTheme: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, stroke: '#000000', style: { color: '#CCC', fontWeight: 'bold' }, states: { hover: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#BBB'], [0.6, '#888'] ] }, stroke: '#000000', style: { color: 'white' } }, select: { fill: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.1, '#000'], [0.3, '#333'] ] }, stroke: '#000000', style: { color: 'yellow' } } } }, inputStyle: { backgroundColor: '#333', color: 'silver' }, labelStyle: { color: 'silver' } }, navigator: { handles: { backgroundColor: '#666', borderColor: '#AAA' }, outlineColor: '#CCC', maskFill: 'rgba(16, 16, 16, 0.5)', series: { color: '#7798BF', lineColor: '#A6C7ED' } }, scrollbar: { barBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, barBorderColor: '#CCC', buttonArrowColor: '#CCC', buttonBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0.4, '#888'], [0.6, '#555'] ] }, buttonBorderColor: '#CCC', rifleColor: '#FFF', trackBackgroundColor: { linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 }, stops: [ [0, '#000'], [1, '#333'] ] }, trackBorderColor: '#666' }, // special colors for some of the demo examples legendBackgroundColor: 'rgba(48, 48, 48, 0.8)', legendBackgroundColorSolid: 'rgb(70, 70, 70)', dataLabelsColor: '#444', textColor: '#E0E0E0', maskColor: 'rgba(255,255,255,0.3)' }; // Apply the theme var highchartsOptions = Highcharts.setOptions(Highcharts.theme);
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var DOM = tinymce.DOM, Element = tinymce.dom.Element, Event = tinymce.dom.Event, each = tinymce.each, is = tinymce.is; tinymce.create('tinymce.plugins.InlinePopups', { init : function(ed, url) { // Replace window manager ed.onBeforeRenderUI.add(function() { ed.windowManager = new tinymce.InlineWindowManager(ed); DOM.loadCSS(url + '/skins/' + (ed.settings.inlinepopups_skin || 'clearlooks2') + "/window.css"); }); }, getInfo : function() { return { longname : 'InlinePopups', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/inlinepopups', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); tinymce.create('tinymce.InlineWindowManager:tinymce.WindowManager', { InlineWindowManager : function(ed) { var t = this; t.parent(ed); t.zIndex = 300000; t.count = 0; t.windows = {}; }, open : function(f, p) { var t = this, id, opt = '', ed = t.editor, dw = 0, dh = 0, vp, po, mdf, clf, we, w, u; f = f || {}; p = p || {}; // Run native windows if (!f.inline) return t.parent(f, p); // Only store selection if the type is a normal window if (!f.type) t.bookmark = ed.selection.getBookmark(1); id = DOM.uniqueId(); vp = DOM.getViewPort(); f.width = parseInt(f.width || 320); f.height = parseInt(f.height || 240) + (tinymce.isIE ? 8 : 0); f.min_width = parseInt(f.min_width || 150); f.min_height = parseInt(f.min_height || 100); f.max_width = parseInt(f.max_width || 2000); f.max_height = parseInt(f.max_height || 2000); f.left = f.left || Math.round(Math.max(vp.x, vp.x + (vp.w / 2.0) - (f.width / 2.0))); f.top = f.top || Math.round(Math.max(vp.y, vp.y + (vp.h / 2.0) - (f.height / 2.0))); f.movable = f.resizable = true; p.mce_width = f.width; p.mce_height = f.height; p.mce_inline = true; p.mce_window_id = id; p.mce_auto_focus = f.auto_focus; // Transpose // po = DOM.getPos(ed.getContainer()); // f.left -= po.x; // f.top -= po.y; t.features = f; t.params = p; t.onOpen.dispatch(t, f, p); if (f.type) { opt += ' mceModal'; if (f.type) opt += ' mce' + f.type.substring(0, 1).toUpperCase() + f.type.substring(1); f.resizable = false; } if (f.statusbar) opt += ' mceStatusbar'; if (f.resizable) opt += ' mceResizable'; if (f.minimizable) opt += ' mceMinimizable'; if (f.maximizable) opt += ' mceMaximizable'; if (f.movable) opt += ' mceMovable'; // Create DOM objects t._addAll(DOM.doc.body, ['div', {id : id, 'class' : ed.settings.inlinepopups_skin || 'clearlooks2', style : 'width:100px;height:100px'}, ['div', {id : id + '_wrapper', 'class' : 'mceWrapper' + opt}, ['div', {id : id + '_top', 'class' : 'mceTop'}, ['div', {'class' : 'mceLeft'}], ['div', {'class' : 'mceCenter'}], ['div', {'class' : 'mceRight'}], ['span', {id : id + '_title'}, f.title || ''] ], ['div', {id : id + '_middle', 'class' : 'mceMiddle'}, ['div', {id : id + '_left', 'class' : 'mceLeft'}], ['span', {id : id + '_content'}], ['div', {id : id + '_right', 'class' : 'mceRight'}] ], ['div', {id : id + '_bottom', 'class' : 'mceBottom'}, ['div', {'class' : 'mceLeft'}], ['div', {'class' : 'mceCenter'}], ['div', {'class' : 'mceRight'}], ['span', {id : id + '_status'}, 'Content'] ], ['a', {'class' : 'mceMove', tabindex : '-1', href : 'javascript:;'}], ['a', {'class' : 'mceMin', tabindex : '-1', href : 'javascript:;', onmousedown : 'return false;'}], ['a', {'class' : 'mceMax', tabindex : '-1', href : 'javascript:;', onmousedown : 'return false;'}], ['a', {'class' : 'mceMed', tabindex : '-1', href : 'javascript:;', onmousedown : 'return false;'}], ['a', {'class' : 'mceClose', tabindex : '-1', href : 'javascript:;', onmousedown : 'return false;'}], ['a', {id : id + '_resize_n', 'class' : 'mceResize mceResizeN', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_s', 'class' : 'mceResize mceResizeS', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_w', 'class' : 'mceResize mceResizeW', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_e', 'class' : 'mceResize mceResizeE', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_nw', 'class' : 'mceResize mceResizeNW', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_ne', 'class' : 'mceResize mceResizeNE', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_sw', 'class' : 'mceResize mceResizeSW', tabindex : '-1', href : 'javascript:;'}], ['a', {id : id + '_resize_se', 'class' : 'mceResize mceResizeSE', tabindex : '-1', href : 'javascript:;'}] ] ] ); DOM.setStyles(id, {top : -10000, left : -10000}); // Fix gecko rendering bug, where the editors iframe messed with window contents if (tinymce.isGecko) DOM.setStyle(id, 'overflow', 'auto'); // Measure borders if (!f.type) { dw += DOM.get(id + '_left').clientWidth; dw += DOM.get(id + '_right').clientWidth; dh += DOM.get(id + '_top').clientHeight; dh += DOM.get(id + '_bottom').clientHeight; } // Resize window DOM.setStyles(id, {top : f.top, left : f.left, width : f.width + dw, height : f.height + dh}); u = f.url || f.file; if (u) { if (tinymce.relaxedDomain) u += (u.indexOf('?') == -1 ? '?' : '&') + 'mce_rdomain=' + tinymce.relaxedDomain; u = tinymce._addVer(u); } if (!f.type) { DOM.add(id + '_content', 'iframe', {id : id + '_ifr', src : 'javascript:""', frameBorder : 0, style : 'border:0;width:10px;height:10px'}); DOM.setStyles(id + '_ifr', {width : f.width, height : f.height}); DOM.setAttrib(id + '_ifr', 'src', u); } else { DOM.add(id + '_wrapper', 'a', {id : id + '_ok', 'class' : 'mceButton mceOk', href : 'javascript:;', onmousedown : 'return false;'}, 'Ok'); if (f.type == 'confirm') DOM.add(id + '_wrapper', 'a', {'class' : 'mceButton mceCancel', href : 'javascript:;', onmousedown : 'return false;'}, 'Cancel'); DOM.add(id + '_middle', 'div', {'class' : 'mceIcon'}); DOM.setHTML(id + '_content', f.content.replace('\n', '<br />')); } // Register events mdf = Event.add(id, 'mousedown', function(e) { var n = e.target, w, vp; w = t.windows[id]; t.focus(id); if (n.nodeName == 'A' || n.nodeName == 'a') { if (n.className == 'mceMax') { w.oldPos = w.element.getXY(); w.oldSize = w.element.getSize(); vp = DOM.getViewPort(); // Reduce viewport size to avoid scrollbars vp.w -= 2; vp.h -= 2; w.element.moveTo(vp.x, vp.y); w.element.resizeTo(vp.w, vp.h); DOM.setStyles(id + '_ifr', {width : vp.w - w.deltaWidth, height : vp.h - w.deltaHeight}); DOM.addClass(id + '_wrapper', 'mceMaximized'); } else if (n.className == 'mceMed') { // Reset to old size w.element.moveTo(w.oldPos.x, w.oldPos.y); w.element.resizeTo(w.oldSize.w, w.oldSize.h); w.iframeElement.resizeTo(w.oldSize.w - w.deltaWidth, w.oldSize.h - w.deltaHeight); DOM.removeClass(id + '_wrapper', 'mceMaximized'); } else if (n.className == 'mceMove') return t._startDrag(id, e, n.className); else if (DOM.hasClass(n, 'mceResize')) return t._startDrag(id, e, n.className.substring(13)); } }); clf = Event.add(id, 'click', function(e) { var n = e.target; t.focus(id); if (n.nodeName == 'A' || n.nodeName == 'a') { switch (n.className) { case 'mceClose': t.close(null, id); return Event.cancel(e); case 'mceButton mceOk': case 'mceButton mceCancel': f.button_func(n.className == 'mceButton mceOk'); return Event.cancel(e); } } }); // Add window w = t.windows[id] = { id : id, mousedown_func : mdf, click_func : clf, element : new Element(id, {blocker : 1, container : ed.getContainer()}), iframeElement : new Element(id + '_ifr'), features : f, deltaWidth : dw, deltaHeight : dh }; w.iframeElement.on('focus', function() { t.focus(id); }); // Setup blocker if (t.count == 0 && t.editor.getParam('dialog_type', 'modal') == 'modal') { DOM.add(DOM.doc.body, 'div', { id : 'mceModalBlocker', 'class' : (t.editor.settings.inlinepopups_skin || 'clearlooks2') + '_modalBlocker', style : {zIndex : t.zIndex - 1} }); DOM.show('mceModalBlocker'); // Reduces flicker in IE } else DOM.setStyle('mceModalBlocker', 'z-index', t.zIndex - 1); if (tinymce.isIE6 || /Firefox\/2\./.test(navigator.userAgent) || (tinymce.isIE && !DOM.boxModel)) DOM.setStyles('mceModalBlocker', {position : 'absolute', left : vp.x, top : vp.y, width : vp.w - 2, height : vp.h - 2}); t.focus(id); t._fixIELayout(id, 1); // Focus ok button if (DOM.get(id + '_ok')) DOM.get(id + '_ok').focus(); t.count++; return w; }, focus : function(id) { var t = this, w; if (w = t.windows[id]) { w.zIndex = this.zIndex++; w.element.setStyle('zIndex', w.zIndex); w.element.update(); id = id + '_wrapper'; DOM.removeClass(t.lastId, 'mceFocus'); DOM.addClass(id, 'mceFocus'); t.lastId = id; } }, _addAll : function(te, ne) { var i, n, t = this, dom = tinymce.DOM; if (is(ne, 'string')) te.appendChild(dom.doc.createTextNode(ne)); else if (ne.length) { te = te.appendChild(dom.create(ne[0], ne[1])); for (i=2; i<ne.length; i++) t._addAll(te, ne[i]); } }, _startDrag : function(id, se, ac) { var t = this, mu, mm, d = DOM.doc, eb, w = t.windows[id], we = w.element, sp = we.getXY(), p, sz, ph, cp, vp, sx, sy, sex, sey, dx, dy, dw, dh; // Get positons and sizes // cp = DOM.getPos(t.editor.getContainer()); cp = {x : 0, y : 0}; vp = DOM.getViewPort(); // Reduce viewport size to avoid scrollbars while dragging vp.w -= 2; vp.h -= 2; sex = se.screenX; sey = se.screenY; dx = dy = dw = dh = 0; // Handle mouse up mu = Event.add(d, 'mouseup', function(e) { Event.remove(d, 'mouseup', mu); Event.remove(d, 'mousemove', mm); if (eb) eb.remove(); we.moveBy(dx, dy); we.resizeBy(dw, dh); sz = we.getSize(); DOM.setStyles(id + '_ifr', {width : sz.w - w.deltaWidth, height : sz.h - w.deltaHeight}); t._fixIELayout(id, 1); return Event.cancel(e); }); if (ac != 'Move') startMove(); function startMove() { if (eb) return; t._fixIELayout(id, 0); // Setup event blocker DOM.add(d.body, 'div', { id : 'mceEventBlocker', 'class' : 'mceEventBlocker ' + (t.editor.settings.inlinepopups_skin || 'clearlooks2'), style : {zIndex : t.zIndex + 1} }); if (tinymce.isIE6 || (tinymce.isIE && !DOM.boxModel)) DOM.setStyles('mceEventBlocker', {position : 'absolute', left : vp.x, top : vp.y, width : vp.w - 2, height : vp.h - 2}); eb = new Element('mceEventBlocker'); eb.update(); // Setup placeholder p = we.getXY(); sz = we.getSize(); sx = cp.x + p.x - vp.x; sy = cp.y + p.y - vp.y; DOM.add(eb.get(), 'div', {id : 'mcePlaceHolder', 'class' : 'mcePlaceHolder', style : {left : sx, top : sy, width : sz.w, height : sz.h}}); ph = new Element('mcePlaceHolder'); }; // Handle mouse move/drag mm = Event.add(d, 'mousemove', function(e) { var x, y, v; startMove(); x = e.screenX - sex; y = e.screenY - sey; switch (ac) { case 'ResizeW': dx = x; dw = 0 - x; break; case 'ResizeE': dw = x; break; case 'ResizeN': case 'ResizeNW': case 'ResizeNE': if (ac == "ResizeNW") { dx = x; dw = 0 - x; } else if (ac == "ResizeNE") dw = x; dy = y; dh = 0 - y; break; case 'ResizeS': case 'ResizeSW': case 'ResizeSE': if (ac == "ResizeSW") { dx = x; dw = 0 - x; } else if (ac == "ResizeSE") dw = x; dh = y; break; case 'mceMove': dx = x; dy = y; break; } // Boundary check if (dw < (v = w.features.min_width - sz.w)) { if (dx !== 0) dx += dw - v; dw = v; } if (dh < (v = w.features.min_height - sz.h)) { if (dy !== 0) dy += dh - v; dh = v; } dw = Math.min(dw, w.features.max_width - sz.w); dh = Math.min(dh, w.features.max_height - sz.h); dx = Math.max(dx, vp.x - (sx + vp.x)); dy = Math.max(dy, vp.y - (sy + vp.y)); dx = Math.min(dx, (vp.w + vp.x) - (sx + sz.w + vp.x)); dy = Math.min(dy, (vp.h + vp.y) - (sy + sz.h + vp.y)); // Move if needed if (dx + dy !== 0) { if (sx + dx < 0) dx = 0; if (sy + dy < 0) dy = 0; ph.moveTo(sx + dx, sy + dy); } // Resize if needed if (dw + dh !== 0) ph.resizeTo(sz.w + dw, sz.h + dh); return Event.cancel(e); }); return Event.cancel(se); }, resizeBy : function(dw, dh, id) { var w = this.windows[id]; if (w) { w.element.resizeBy(dw, dh); w.iframeElement.resizeBy(dw, dh); } }, close : function(win, id) { var t = this, w, d = DOM.doc, ix = 0, fw, id; id = t._findId(id || win); // Probably not inline if (!t.windows[id]) { t.parent(win); return; } t.count--; if (t.count == 0) DOM.remove('mceModalBlocker'); if (w = t.windows[id]) { t.onClose.dispatch(t); Event.remove(d, 'mousedown', w.mousedownFunc); Event.remove(d, 'click', w.clickFunc); Event.clear(id); Event.clear(id + '_ifr'); DOM.setAttrib(id + '_ifr', 'src', 'javascript:""'); // Prevent leak w.element.remove(); delete t.windows[id]; // Find front most window and focus that each (t.windows, function(w) { if (w.zIndex > ix) { fw = w; ix = w.zIndex; } }); if (fw) t.focus(fw.id); } }, setTitle : function(w, ti) { var e; w = this._findId(w); if (e = DOM.get(w + '_title')) e.innerHTML = DOM.encode(ti); }, alert : function(txt, cb, s) { var t = this, w; w = t.open({ title : t, type : 'alert', button_func : function(s) { if (cb) cb.call(s || t, s); t.close(null, w.id); }, content : DOM.encode(t.editor.getLang(txt, txt)), inline : 1, width : 400, height : 130 }); }, confirm : function(txt, cb, s) { var t = this, w; w = t.open({ title : t, type : 'confirm', button_func : function(s) { if (cb) cb.call(s || t, s); t.close(null, w.id); }, content : DOM.encode(t.editor.getLang(txt, txt)), inline : 1, width : 400, height : 130 }); }, // Internal functions _findId : function(w) { var t = this; if (typeof(w) == 'string') return w; each(t.windows, function(wo) { var ifr = DOM.get(wo.id + '_ifr'); if (ifr && w == ifr.contentWindow) { w = wo.id; return false; } }); return w; }, _fixIELayout : function(id, s) { var w, img; if (!tinymce.isIE6) return; // Fixes the bug where hover flickers and does odd things in IE6 each(['n','s','w','e','nw','ne','sw','se'], function(v) { var e = DOM.get(id + '_resize_' + v); DOM.setStyles(e, { width : s ? e.clientWidth : '', height : s ? e.clientHeight : '', cursor : DOM.getStyle(e, 'cursor', 1) }); DOM.setStyle(id + "_bottom", 'bottom', '-1px'); e = 0; }); // Fixes graphics glitch if (w = this.windows[id]) { // Fixes rendering bug after resize w.element.hide(); w.element.show(); // Forced a repaint of the window //DOM.get(id).style.filter = ''; // IE has a bug where images used in CSS won't get loaded // sometimes when the cache in the browser is disabled // This fix tries to solve it by loading the images using the image object each(DOM.select('div,a', id), function(e, i) { if (e.currentStyle.backgroundImage != 'none') { img = new Image(); img.src = e.currentStyle.backgroundImage.replace(/url\(\"(.+)\"\)/, '$1'); } }); DOM.get(id).style.filter = ''; } } }); // Register plugin tinymce.PluginManager.add('inlinepopups', tinymce.plugins.InlinePopups); })();
JavaScript
/* Functions for the advlink plugin popup */ tinyMCEPopup.requireLangPack(); var templates = { "window.open" : "window.open('${url}','${target}','${options}')" }; function preinit() { var url; if (url = tinyMCEPopup.getParam("external_link_list_url")) document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>'); } function changeClass() { var f = document.forms[0]; f.classes.value = getSelectValue(f, 'classlist'); } function init() { tinyMCEPopup.resizeToInnerSize(); var formObj = document.forms[0]; var inst = tinyMCEPopup.editor; var elm = inst.selection.getNode(); var action = "insert"; var html; document.getElementById('hrefbrowsercontainer').innerHTML = getBrowserHTML('hrefbrowser','href','file','advlink'); document.getElementById('popupurlbrowsercontainer').innerHTML = getBrowserHTML('popupurlbrowser','popupurl','file','advlink'); document.getElementById('linklisthrefcontainer').innerHTML = getLinkListHTML('linklisthref','href'); document.getElementById('anchorlistcontainer').innerHTML = getAnchorListHTML('anchorlist','href'); document.getElementById('targetlistcontainer').innerHTML = getTargetListHTML('targetlist','target'); // Link list html = getLinkListHTML('linklisthref','href'); if (html == "") document.getElementById("linklisthrefrow").style.display = 'none'; else document.getElementById("linklisthrefcontainer").innerHTML = html; // Resize some elements if (isVisible('hrefbrowser')) document.getElementById('href').style.width = '260px'; if (isVisible('popupurlbrowser')) document.getElementById('popupurl').style.width = '180px'; elm = inst.dom.getParent(elm, "A"); if (elm != null && elm.nodeName == "A") action = "update"; formObj.insert.value = tinyMCEPopup.getLang(action, 'Insert', true); setPopupControlsDisabled(true); if (action == "update") { var href = inst.dom.getAttrib(elm, 'href'); var onclick = inst.dom.getAttrib(elm, 'onclick'); // Setup form data setFormValue('href', href); setFormValue('title', inst.dom.getAttrib(elm, 'title')); setFormValue('id', inst.dom.getAttrib(elm, 'id')); setFormValue('style', inst.dom.getAttrib(elm, "style")); setFormValue('rel', inst.dom.getAttrib(elm, 'rel')); setFormValue('rev', inst.dom.getAttrib(elm, 'rev')); setFormValue('charset', inst.dom.getAttrib(elm, 'charset')); setFormValue('hreflang', inst.dom.getAttrib(elm, 'hreflang')); setFormValue('dir', inst.dom.getAttrib(elm, 'dir')); setFormValue('lang', inst.dom.getAttrib(elm, 'lang')); setFormValue('tabindex', inst.dom.getAttrib(elm, 'tabindex', typeof(elm.tabindex) != "undefined" ? elm.tabindex : "")); setFormValue('accesskey', inst.dom.getAttrib(elm, 'accesskey', typeof(elm.accesskey) != "undefined" ? elm.accesskey : "")); setFormValue('type', inst.dom.getAttrib(elm, 'type')); setFormValue('onfocus', inst.dom.getAttrib(elm, 'onfocus')); setFormValue('onblur', inst.dom.getAttrib(elm, 'onblur')); setFormValue('onclick', onclick); setFormValue('ondblclick', inst.dom.getAttrib(elm, 'ondblclick')); setFormValue('onmousedown', inst.dom.getAttrib(elm, 'onmousedown')); setFormValue('onmouseup', inst.dom.getAttrib(elm, 'onmouseup')); setFormValue('onmouseover', inst.dom.getAttrib(elm, 'onmouseover')); setFormValue('onmousemove', inst.dom.getAttrib(elm, 'onmousemove')); setFormValue('onmouseout', inst.dom.getAttrib(elm, 'onmouseout')); setFormValue('onkeypress', inst.dom.getAttrib(elm, 'onkeypress')); setFormValue('onkeydown', inst.dom.getAttrib(elm, 'onkeydown')); setFormValue('onkeyup', inst.dom.getAttrib(elm, 'onkeyup')); setFormValue('target', inst.dom.getAttrib(elm, 'target')); setFormValue('classes', inst.dom.getAttrib(elm, 'class')); // Parse onclick data if (onclick != null && onclick.indexOf('window.open') != -1) parseWindowOpen(onclick); else parseFunction(onclick); // Select by the values selectByValue(formObj, 'dir', inst.dom.getAttrib(elm, 'dir')); selectByValue(formObj, 'rel', inst.dom.getAttrib(elm, 'rel')); selectByValue(formObj, 'rev', inst.dom.getAttrib(elm, 'rev')); selectByValue(formObj, 'linklisthref', href); if (href.charAt(0) == '#') selectByValue(formObj, 'anchorlist', href); addClassesToList('classlist', 'advlink_styles'); selectByValue(formObj, 'classlist', inst.dom.getAttrib(elm, 'class'), true); selectByValue(formObj, 'targetlist', inst.dom.getAttrib(elm, 'target'), true); } else addClassesToList('classlist', 'advlink_styles'); } function checkPrefix(n) { if (n.value && Validator.isEmail(n) && !/^\s*mailto:/i.test(n.value) && confirm(tinyMCEPopup.getLang('advlink_dlg.is_email'))) n.value = 'mailto:' + n.value; if (/^\s*www\./i.test(n.value) && confirm(tinyMCEPopup.getLang('advlink_dlg.is_external'))) n.value = 'http://' + n.value; } function setFormValue(name, value) { document.forms[0].elements[name].value = value; } function parseWindowOpen(onclick) { var formObj = document.forms[0]; // Preprocess center code if (onclick.indexOf('return false;') != -1) { formObj.popupreturn.checked = true; onclick = onclick.replace('return false;', ''); } else formObj.popupreturn.checked = false; var onClickData = parseLink(onclick); if (onClickData != null) { formObj.ispopup.checked = true; setPopupControlsDisabled(false); var onClickWindowOptions = parseOptions(onClickData['options']); var url = onClickData['url']; formObj.popupname.value = onClickData['target']; formObj.popupurl.value = url; formObj.popupwidth.value = getOption(onClickWindowOptions, 'width'); formObj.popupheight.value = getOption(onClickWindowOptions, 'height'); formObj.popupleft.value = getOption(onClickWindowOptions, 'left'); formObj.popuptop.value = getOption(onClickWindowOptions, 'top'); if (formObj.popupleft.value.indexOf('screen') != -1) formObj.popupleft.value = "c"; if (formObj.popuptop.value.indexOf('screen') != -1) formObj.popuptop.value = "c"; formObj.popuplocation.checked = getOption(onClickWindowOptions, 'location') == "yes"; formObj.popupscrollbars.checked = getOption(onClickWindowOptions, 'scrollbars') == "yes"; formObj.popupmenubar.checked = getOption(onClickWindowOptions, 'menubar') == "yes"; formObj.popupresizable.checked = getOption(onClickWindowOptions, 'resizable') == "yes"; formObj.popuptoolbar.checked = getOption(onClickWindowOptions, 'toolbar') == "yes"; formObj.popupstatus.checked = getOption(onClickWindowOptions, 'status') == "yes"; formObj.popupdependent.checked = getOption(onClickWindowOptions, 'dependent') == "yes"; buildOnClick(); } } function parseFunction(onclick) { var formObj = document.forms[0]; var onClickData = parseLink(onclick); // TODO: Add stuff here } function getOption(opts, name) { return typeof(opts[name]) == "undefined" ? "" : opts[name]; } function setPopupControlsDisabled(state) { var formObj = document.forms[0]; formObj.popupname.disabled = state; formObj.popupurl.disabled = state; formObj.popupwidth.disabled = state; formObj.popupheight.disabled = state; formObj.popupleft.disabled = state; formObj.popuptop.disabled = state; formObj.popuplocation.disabled = state; formObj.popupscrollbars.disabled = state; formObj.popupmenubar.disabled = state; formObj.popupresizable.disabled = state; formObj.popuptoolbar.disabled = state; formObj.popupstatus.disabled = state; formObj.popupreturn.disabled = state; formObj.popupdependent.disabled = state; setBrowserDisabled('popupurlbrowser', state); } function parseLink(link) { link = link.replace(new RegExp('&#39;', 'g'), "'"); var fnName = link.replace(new RegExp("\\s*([A-Za-z0-9\.]*)\\s*\\(.*", "gi"), "$1"); // Is function name a template function var template = templates[fnName]; if (template) { // Build regexp var variableNames = template.match(new RegExp("'?\\$\\{[A-Za-z0-9\.]*\\}'?", "gi")); var regExp = "\\s*[A-Za-z0-9\.]*\\s*\\("; var replaceStr = ""; for (var i=0; i<variableNames.length; i++) { // Is string value if (variableNames[i].indexOf("'${") != -1) regExp += "'(.*)'"; else // Number value regExp += "([0-9]*)"; replaceStr += "$" + (i+1); // Cleanup variable name variableNames[i] = variableNames[i].replace(new RegExp("[^A-Za-z0-9]", "gi"), ""); if (i != variableNames.length-1) { regExp += "\\s*,\\s*"; replaceStr += "<delim>"; } else regExp += ".*"; } regExp += "\\);?"; // Build variable array var variables = []; variables["_function"] = fnName; var variableValues = link.replace(new RegExp(regExp, "gi"), replaceStr).split('<delim>'); for (var i=0; i<variableNames.length; i++) variables[variableNames[i]] = variableValues[i]; return variables; } return null; } function parseOptions(opts) { if (opts == null || opts == "") return []; // Cleanup the options opts = opts.toLowerCase(); opts = opts.replace(/;/g, ","); opts = opts.replace(/[^0-9a-z=,]/g, ""); var optionChunks = opts.split(','); var options = []; for (var i=0; i<optionChunks.length; i++) { var parts = optionChunks[i].split('='); if (parts.length == 2) options[parts[0]] = parts[1]; } return options; } function buildOnClick() { var formObj = document.forms[0]; if (!formObj.ispopup.checked) { formObj.onclick.value = ""; return; } var onclick = "window.open('"; var url = formObj.popupurl.value; onclick += url + "','"; onclick += formObj.popupname.value + "','"; if (formObj.popuplocation.checked) onclick += "location=yes,"; if (formObj.popupscrollbars.checked) onclick += "scrollbars=yes,"; if (formObj.popupmenubar.checked) onclick += "menubar=yes,"; if (formObj.popupresizable.checked) onclick += "resizable=yes,"; if (formObj.popuptoolbar.checked) onclick += "toolbar=yes,"; if (formObj.popupstatus.checked) onclick += "status=yes,"; if (formObj.popupdependent.checked) onclick += "dependent=yes,"; if (formObj.popupwidth.value != "") onclick += "width=" + formObj.popupwidth.value + ","; if (formObj.popupheight.value != "") onclick += "height=" + formObj.popupheight.value + ","; if (formObj.popupleft.value != "") { if (formObj.popupleft.value != "c") onclick += "left=" + formObj.popupleft.value + ","; else onclick += "left='+(screen.availWidth/2-" + (formObj.popupwidth.value/2) + ")+',"; } if (formObj.popuptop.value != "") { if (formObj.popuptop.value != "c") onclick += "top=" + formObj.popuptop.value + ","; else onclick += "top='+(screen.availHeight/2-" + (formObj.popupheight.value/2) + ")+',"; } if (onclick.charAt(onclick.length-1) == ',') onclick = onclick.substring(0, onclick.length-1); onclick += "');"; if (formObj.popupreturn.checked) onclick += "return false;"; // tinyMCE.debug(onclick); formObj.onclick.value = onclick; if (formObj.href.value == "") formObj.href.value = url; } function setAttrib(elm, attrib, value) { var formObj = document.forms[0]; var valueElm = formObj.elements[attrib.toLowerCase()]; var dom = tinyMCEPopup.editor.dom; if (typeof(value) == "undefined" || value == null) { value = ""; if (valueElm) value = valueElm.value; } // Clean up the style if (attrib == 'style') value = dom.serializeStyle(dom.parseStyle(value), 'a'); dom.setAttrib(elm, attrib, value); } function getAnchorListHTML(id, target) { var inst = tinyMCEPopup.editor; var nodes = inst.dom.select('a.mceItemAnchor,img.mceItemAnchor'), name, i; var html = ""; html += '<select id="' + id + '" name="' + id + '" class="mceAnchorList" o2nfocus="tinyMCE.addSelectAccessibility(event, this, window);" onchange="this.form.' + target + '.value='; html += 'this.options[this.selectedIndex].value;">'; html += '<option value="">---</option>'; for (i=0; i<nodes.length; i++) { if ((name = inst.dom.getAttrib(nodes[i], "name")) != "") html += '<option value="#' + name + '">' + name + '</option>'; } html += '</select>'; return html; } function insertAction() { var inst = tinyMCEPopup.editor; var elm, elementArray, i; elm = inst.selection.getNode(); checkPrefix(document.forms[0].href); elm = inst.dom.getParent(elm, "A"); // Remove element if there is no href if (!document.forms[0].href.value) { tinyMCEPopup.execCommand("mceBeginUndoLevel"); i = inst.selection.getBookmark(); inst.dom.remove(elm, 1); inst.selection.moveToBookmark(i); tinyMCEPopup.execCommand("mceEndUndoLevel"); tinyMCEPopup.close(); return; } tinyMCEPopup.execCommand("mceBeginUndoLevel"); // Create new anchor elements if (elm == null) { inst.getDoc().execCommand("unlink", false, null); tinyMCEPopup.execCommand("CreateLink", false, "#mce_temp_url#", {skip_undo : 1}); elementArray = tinymce.grep(inst.dom.select("a"), function(n) {return inst.dom.getAttrib(n, 'href') == '#mce_temp_url#';}); for (i=0; i<elementArray.length; i++) setAllAttribs(elm = elementArray[i]); } else setAllAttribs(elm); // Don't move caret if selection was image if (elm.childNodes.length != 1 || elm.firstChild.nodeName != 'IMG') { inst.focus(); inst.selection.select(elm); inst.selection.collapse(0); tinyMCEPopup.storeSelection(); } tinyMCEPopup.execCommand("mceEndUndoLevel"); tinyMCEPopup.close(); } function setAllAttribs(elm) { var formObj = document.forms[0]; var href = formObj.href.value; var target = getSelectValue(formObj, 'targetlist'); setAttrib(elm, 'href', href); setAttrib(elm, 'title'); setAttrib(elm, 'target', target == '_self' ? '' : target); setAttrib(elm, 'id'); setAttrib(elm, 'style'); setAttrib(elm, 'class', getSelectValue(formObj, 'classlist')); setAttrib(elm, 'rel'); setAttrib(elm, 'rev'); setAttrib(elm, 'charset'); setAttrib(elm, 'hreflang'); setAttrib(elm, 'dir'); setAttrib(elm, 'lang'); setAttrib(elm, 'tabindex'); setAttrib(elm, 'accesskey'); setAttrib(elm, 'type'); setAttrib(elm, 'onfocus'); setAttrib(elm, 'onblur'); setAttrib(elm, 'onclick'); setAttrib(elm, 'ondblclick'); setAttrib(elm, 'onmousedown'); setAttrib(elm, 'onmouseup'); setAttrib(elm, 'onmouseover'); setAttrib(elm, 'onmousemove'); setAttrib(elm, 'onmouseout'); setAttrib(elm, 'onkeypress'); setAttrib(elm, 'onkeydown'); setAttrib(elm, 'onkeyup'); // Refresh in old MSIE if (tinyMCE.isMSIE5) elm.outerHTML = elm.outerHTML; } function getSelectValue(form_obj, field_name) { var elm = form_obj.elements[field_name]; if (!elm || elm.options == null || elm.selectedIndex == -1) return ""; return elm.options[elm.selectedIndex].value; } function getLinkListHTML(elm_id, target_form_element, onchange_func) { if (typeof(tinyMCELinkList) == "undefined" || tinyMCELinkList.length == 0) return ""; var html = ""; html += '<select id="' + elm_id + '" name="' + elm_id + '"'; html += ' class="mceLinkList" onfoc2us="tinyMCE.addSelectAccessibility(event, this, window);" onchange="this.form.' + target_form_element + '.value='; html += 'this.options[this.selectedIndex].value;'; if (typeof(onchange_func) != "undefined") html += onchange_func + '(\'' + target_form_element + '\',this.options[this.selectedIndex].text,this.options[this.selectedIndex].value);'; html += '"><option value="">---</option>'; for (var i=0; i<tinyMCELinkList.length; i++) html += '<option value="' + tinyMCELinkList[i][1] + '">' + tinyMCELinkList[i][0] + '</option>'; html += '</select>'; return html; // tinyMCE.debug('-- image list start --', html, '-- image list end --'); } function getTargetListHTML(elm_id, target_form_element) { var targets = tinyMCEPopup.getParam('theme_advanced_link_targets', '').split(';'); var html = ''; html += '<select id="' + elm_id + '" name="' + elm_id + '" onf2ocus="tinyMCE.addSelectAccessibility(event, this, window);" onchange="this.form.' + target_form_element + '.value='; html += 'this.options[this.selectedIndex].value;">'; html += '<option value="_self">' + tinyMCEPopup.getLang('advlink_dlg.target_same') + '</option>'; html += '<option value="_blank">' + tinyMCEPopup.getLang('advlink_dlg.target_blank') + ' (_blank)</option>'; html += '<option value="_parent">' + tinyMCEPopup.getLang('advlink_dlg.target_parent') + ' (_parent)</option>'; html += '<option value="_top">' + tinyMCEPopup.getLang('advlink_dlg.target_top') + ' (_top)</option>'; for (var i=0; i<targets.length; i++) { var key, value; if (targets[i] == "") continue; key = targets[i].split('=')[0]; value = targets[i].split('=')[1]; html += '<option value="' + key + '">' + value + ' (' + key + ')</option>'; } html += '</select>'; return html; } // While loading preinit(); tinyMCEPopup.onInit.add(init);
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.AdvancedLinkPlugin', { init : function(ed, url) { this.editor = ed; // Register commands ed.addCommand('mceAdvLink', function() { var se = ed.selection; // No selection and not in link if (se.isCollapsed() && !ed.dom.getParent(se.getNode(), 'A')) return; ed.windowManager.open({ file : url + '/link.htm', width : 480 + parseInt(ed.getLang('advlink.delta_width', 0)), height : 400 + parseInt(ed.getLang('advlink.delta_height', 0)), inline : 1 }, { plugin_url : url }); }); // Register buttons ed.addButton('link', { title : 'advlink.link_desc', cmd : 'mceAdvLink' }); ed.addShortcut('ctrl+k', 'advlink.advlink_desc', 'mceAdvLink'); ed.onNodeChange.add(function(ed, cm, n, co) { cm.setDisabled('link', co && n.nodeName != 'A'); cm.setActive('link', n.nodeName == 'A' && !n.name); }); }, getInfo : function() { return { longname : 'Advanced link', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/advlink', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('advlink', tinymce.plugins.AdvancedLinkPlugin); })();
JavaScript
tinyMCE.addI18n('en.advlink_dlg',{ title:"Insert/edit link", url:"Link URL", target:"Target", titlefield:"Title", is_email:"The URL you entered seems to be an email address, do you want to add the required mailto: prefix?", is_external:"The URL you entered seems to external link, do you want to add the required http:// prefix?", list:"Link list", general_tab:"General", popup_tab:"Popup", events_tab:"Events", advanced_tab:"Advanced", general_props:"General properties", popup_props:"Popup properties", event_props:"Events", advanced_props:"Advanced properties", popup_opts:"Options", anchor_names:"Anchors", target_same:"Open in this window / frame", target_parent:"Open in parent window / frame", target_top:"Open in top frame (replaces all frames)", target_blank:"Open in new window", popup:"Javascript popup", popup_url:"Popup URL", popup_name:"Window name", popup_return:"Insert 'return false'", popup_scrollbars:"Show scrollbars", popup_statusbar:"Show status bar", popup_toolbar:"Show toolbars", popup_menubar:"Show menu bar", popup_location:"Show location bar", popup_resizable:"Make window resizable", popup_dependent:"Dependent (Mozilla/Firefox only)", popup_size:"Size", popup_position:"Position (X/Y)", id:"Id", style:"Style", classes:"Classes", target_name:"Target name", langdir:"Language direction", target_langcode:"Target language", langcode:"Language code", encoding:"Target character encoding", mime:"Target MIME type", rel:"Relationship page to target", rev:"Relationship target to page", tabindex:"Tabindex", accesskey:"Accesskey", ltr:"Left to right", rtl:"Right to left", link_list:"Link list" });
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var Event = tinymce.dom.Event, each = tinymce.each, DOM = tinymce.DOM; /** * This plugin a context menu to TinyMCE editor instances. * * @class tinymce.plugins.ContextMenu */ tinymce.create('tinymce.plugins.ContextMenu', { /** * Initializes the plugin, this will be executed after the plugin has been created. * This call is done before the editor instance has finished it's initialization so use the onInit event * of the editor instance to intercept that event. * * @method init * @param {tinymce.Editor} ed Editor instance that the plugin is initialized in. * @param {string} url Absolute URL to where the plugin is located. */ init : function(ed) { var t = this, lastRng; t.editor = ed; /** * This event gets fired when the context menu is shown. * * @event onContextMenu * @param {tinymce.plugins.ContextMenu} sender Plugin instance sending the event. * @param {tinymce.ui.DropMenu} menu Drop down menu to fill with more items if needed. */ t.onContextMenu = new tinymce.util.Dispatcher(this); ed.onContextMenu.add(function(ed, e) { if (!e.ctrlKey) { // Restore the last selection since it was removed if (lastRng) ed.selection.setRng(lastRng); t._getMenu(ed).showMenu(e.clientX, e.clientY); Event.add(ed.getDoc(), 'click', function(e) { hide(ed, e); }); Event.cancel(e); } }); ed.onRemove.add(function() { if (t._menu) t._menu.removeAll(); }); function hide(ed, e) { lastRng = null; // Since the contextmenu event moves // the selection we need to store it away if (e && e.button == 2) { lastRng = ed.selection.getRng(); return; } if (t._menu) { t._menu.removeAll(); t._menu.destroy(); Event.remove(ed.getDoc(), 'click', hide); } }; ed.onMouseDown.add(hide); ed.onKeyDown.add(hide); }, /** * Returns information about the plugin as a name/value array. * The current keys are longname, author, authorurl, infourl and version. * * @method getInfo * @return {Object} Name/value array containing information about the plugin. */ getInfo : function() { return { longname : 'Contextmenu', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/contextmenu', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, _getMenu : function(ed) { var t = this, m = t._menu, se = ed.selection, col = se.isCollapsed(), el = se.getNode() || ed.getBody(), am, p1, p2; if (m) { m.removeAll(); m.destroy(); } p1 = DOM.getPos(ed.getContentAreaContainer()); p2 = DOM.getPos(ed.getContainer()); m = ed.controlManager.createDropMenu('contextmenu', { offset_x : p1.x + ed.getParam('contextmenu_offset_x', 0), offset_y : p1.y + ed.getParam('contextmenu_offset_y', 0), constrain : 1 }); t._menu = m; m.add({title : 'advanced.cut_desc', icon : 'cut', cmd : 'Cut'}).setDisabled(col); m.add({title : 'advanced.copy_desc', icon : 'copy', cmd : 'Copy'}).setDisabled(col); m.add({title : 'advanced.paste_desc', icon : 'paste', cmd : 'Paste'}); if ((el.nodeName == 'A' && !ed.dom.getAttrib(el, 'name')) || !col) { m.addSeparator(); m.add({title : 'advanced.link_desc', icon : 'link', cmd : ed.plugins.advlink ? 'mceAdvLink' : 'mceLink', ui : true}); m.add({title : 'advanced.unlink_desc', icon : 'unlink', cmd : 'UnLink'}); } m.addSeparator(); m.add({title : 'advanced.image_desc', icon : 'image', cmd : ed.plugins.advimage ? 'mceAdvImage' : 'mceImage', ui : true}); m.addSeparator(); am = m.addMenu({title : 'contextmenu.align'}); am.add({title : 'contextmenu.left', icon : 'justifyleft', cmd : 'JustifyLeft'}); am.add({title : 'contextmenu.center', icon : 'justifycenter', cmd : 'JustifyCenter'}); am.add({title : 'contextmenu.right', icon : 'justifyright', cmd : 'JustifyRight'}); am.add({title : 'contextmenu.full', icon : 'justifyfull', cmd : 'JustifyFull'}); t.onContextMenu.dispatch(t, m, el, col); return m; } }); // Register plugin tinymce.PluginManager.add('contextmenu', tinymce.plugins.ContextMenu); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.VisualChars', { init : function(ed, url) { var t = this; t.editor = ed; // Register commands ed.addCommand('mceVisualChars', t._toggleVisualChars, t); // Register buttons ed.addButton('visualchars', {title : 'visualchars.desc', cmd : 'mceVisualChars'}); ed.onBeforeGetContent.add(function(ed, o) { if (t.state && o.format != 'raw' && !o.draft) { t.state = true; t._toggleVisualChars(false); } }); }, getInfo : function() { return { longname : 'Visual characters', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/visualchars', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, // Private methods _toggleVisualChars : function(bookmark) { var t = this, ed = t.editor, nl, i, h, d = ed.getDoc(), b = ed.getBody(), nv, s = ed.selection, bo, div, bm; t.state = !t.state; ed.controlManager.setActive('visualchars', t.state); if (bookmark) bm = s.getBookmark(); if (t.state) { nl = []; tinymce.walk(b, function(n) { if (n.nodeType == 3 && n.nodeValue && n.nodeValue.indexOf('\u00a0') != -1) nl.push(n); }, 'childNodes'); for (i = 0; i < nl.length; i++) { nv = nl[i].nodeValue; nv = nv.replace(/(\u00a0)/g, '<span _mce_bogus="1" class="mceItemHidden mceItemNbsp">$1</span>'); div = ed.dom.create('div', null, nv); while (node = div.lastChild) ed.dom.insertAfter(node, nl[i]); ed.dom.remove(nl[i]); } } else { nl = ed.dom.select('span.mceItemNbsp', b); for (i = nl.length - 1; i >= 0; i--) ed.dom.remove(nl[i], 1); } s.moveToBookmark(bm); } }); // Register plugin tinymce.PluginManager.add('visualchars', tinymce.plugins.VisualChars); })();
JavaScript
var ImageDialog = { preInit : function() { var url; tinyMCEPopup.requireLangPack(); if (url = tinyMCEPopup.getParam("external_image_list_url")) document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>'); }, init : function(ed) { var f = document.forms[0], nl = f.elements, ed = tinyMCEPopup.editor, dom = ed.dom, n = ed.selection.getNode(); tinyMCEPopup.resizeToInnerSize(); this.fillClassList('class_list'); this.fillFileList('src_list', 'tinyMCEImageList'); this.fillFileList('over_list', 'tinyMCEImageList'); this.fillFileList('out_list', 'tinyMCEImageList'); TinyMCE_EditableSelects.init(); if (n.nodeName == 'IMG') { nl.src.value = dom.getAttrib(n, 'src'); nl.width.value = dom.getAttrib(n, 'width'); nl.height.value = dom.getAttrib(n, 'height'); nl.alt.value = dom.getAttrib(n, 'alt'); nl.title.value = dom.getAttrib(n, 'title'); nl.vspace.value = this.getAttrib(n, 'vspace'); nl.hspace.value = this.getAttrib(n, 'hspace'); nl.border.value = this.getAttrib(n, 'border'); selectByValue(f, 'align', this.getAttrib(n, 'align')); selectByValue(f, 'class_list', dom.getAttrib(n, 'class'), true, true); nl.style.value = dom.getAttrib(n, 'style'); nl.id.value = dom.getAttrib(n, 'id'); nl.dir.value = dom.getAttrib(n, 'dir'); nl.lang.value = dom.getAttrib(n, 'lang'); nl.usemap.value = dom.getAttrib(n, 'usemap'); nl.longdesc.value = dom.getAttrib(n, 'longdesc'); nl.insert.value = ed.getLang('update'); if (/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/.test(dom.getAttrib(n, 'onmouseover'))) nl.onmouseoversrc.value = dom.getAttrib(n, 'onmouseover').replace(/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/, '$1'); if (/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/.test(dom.getAttrib(n, 'onmouseout'))) nl.onmouseoutsrc.value = dom.getAttrib(n, 'onmouseout').replace(/^\s*this.src\s*=\s*\'([^\']+)\';?\s*$/, '$1'); if (ed.settings.inline_styles) { // Move attribs to styles if (dom.getAttrib(n, 'align')) this.updateStyle('align'); if (dom.getAttrib(n, 'hspace')) this.updateStyle('hspace'); if (dom.getAttrib(n, 'border')) this.updateStyle('border'); if (dom.getAttrib(n, 'vspace')) this.updateStyle('vspace'); } } // Setup browse button document.getElementById('srcbrowsercontainer').innerHTML = getBrowserHTML('srcbrowser','src','image','theme_advanced_image'); if (isVisible('srcbrowser')) document.getElementById('src').style.width = '260px'; // Setup browse button document.getElementById('onmouseoversrccontainer').innerHTML = getBrowserHTML('overbrowser','onmouseoversrc','image','theme_advanced_image'); if (isVisible('overbrowser')) document.getElementById('onmouseoversrc').style.width = '260px'; // Setup browse button document.getElementById('onmouseoutsrccontainer').innerHTML = getBrowserHTML('outbrowser','onmouseoutsrc','image','theme_advanced_image'); if (isVisible('outbrowser')) document.getElementById('onmouseoutsrc').style.width = '260px'; // If option enabled default contrain proportions to checked if (ed.getParam("advimage_constrain_proportions", true)) f.constrain.checked = true; // Check swap image if valid data if (nl.onmouseoversrc.value || nl.onmouseoutsrc.value) this.setSwapImage(true); else this.setSwapImage(false); this.changeAppearance(); this.showPreviewImage(nl.src.value, 1); }, insert : function(file, title) { var ed = tinyMCEPopup.editor, t = this, f = document.forms[0]; if (f.src.value === '') { if (ed.selection.getNode().nodeName == 'IMG') { ed.dom.remove(ed.selection.getNode()); ed.execCommand('mceRepaint'); } tinyMCEPopup.close(); return; } if (tinyMCEPopup.getParam("accessibility_warnings", 1)) { if (!f.alt.value) { tinyMCEPopup.confirm(tinyMCEPopup.getLang('advimage_dlg.missing_alt'), function(s) { if (s) t.insertAndClose(); }); return; } } t.insertAndClose(); }, insertAndClose : function() { var ed = tinyMCEPopup.editor, f = document.forms[0], nl = f.elements, v, args = {}, el; tinyMCEPopup.restoreSelection(); // Fixes crash in Safari if (tinymce.isWebKit) ed.getWin().focus(); if (!ed.settings.inline_styles) { args = { vspace : nl.vspace.value, hspace : nl.hspace.value, border : nl.border.value, align : getSelectValue(f, 'align') }; } else { // Remove deprecated values args = { vspace : '', hspace : '', border : '', align : '' }; } tinymce.extend(args, { src : nl.src.value, width : nl.width.value, height : nl.height.value, alt : nl.alt.value, title : nl.title.value, 'class' : getSelectValue(f, 'class_list'), style : nl.style.value, id : nl.id.value, dir : nl.dir.value, lang : nl.lang.value, usemap : nl.usemap.value, longdesc : nl.longdesc.value }); args.onmouseover = args.onmouseout = ''; if (f.onmousemovecheck.checked) { if (nl.onmouseoversrc.value) args.onmouseover = "this.src='" + nl.onmouseoversrc.value + "';"; if (nl.onmouseoutsrc.value) args.onmouseout = "this.src='" + nl.onmouseoutsrc.value + "';"; } el = ed.selection.getNode(); if (el && el.nodeName == 'IMG') { ed.dom.setAttribs(el, args); } else { ed.execCommand('mceInsertContent', false, '<img id="__mce_tmp" />', {skip_undo : 1}); ed.dom.setAttribs('__mce_tmp', args); ed.dom.setAttrib('__mce_tmp', 'id', ''); ed.undoManager.add(); } tinyMCEPopup.close(); }, getAttrib : function(e, at) { var ed = tinyMCEPopup.editor, dom = ed.dom, v, v2; if (ed.settings.inline_styles) { switch (at) { case 'align': if (v = dom.getStyle(e, 'float')) return v; if (v = dom.getStyle(e, 'vertical-align')) return v; break; case 'hspace': v = dom.getStyle(e, 'margin-left') v2 = dom.getStyle(e, 'margin-right'); if (v && v == v2) return parseInt(v.replace(/[^0-9]/g, '')); break; case 'vspace': v = dom.getStyle(e, 'margin-top') v2 = dom.getStyle(e, 'margin-bottom'); if (v && v == v2) return parseInt(v.replace(/[^0-9]/g, '')); break; case 'border': v = 0; tinymce.each(['top', 'right', 'bottom', 'left'], function(sv) { sv = dom.getStyle(e, 'border-' + sv + '-width'); // False or not the same as prev if (!sv || (sv != v && v !== 0)) { v = 0; return false; } if (sv) v = sv; }); if (v) return parseInt(v.replace(/[^0-9]/g, '')); break; } } if (v = dom.getAttrib(e, at)) return v; return ''; }, setSwapImage : function(st) { var f = document.forms[0]; f.onmousemovecheck.checked = st; setBrowserDisabled('overbrowser', !st); setBrowserDisabled('outbrowser', !st); if (f.over_list) f.over_list.disabled = !st; if (f.out_list) f.out_list.disabled = !st; f.onmouseoversrc.disabled = !st; f.onmouseoutsrc.disabled = !st; }, fillClassList : function(id) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; if (v = tinyMCEPopup.getParam('theme_advanced_styles')) { cl = []; tinymce.each(v.split(';'), function(v) { var p = v.split('='); cl.push({'title' : p[0], 'class' : p[1]}); }); } else cl = tinyMCEPopup.editor.dom.getClasses(); if (cl.length > 0) { lst.options.length = 0; lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('not_set'), ''); tinymce.each(cl, function(o) { lst.options[lst.options.length] = new Option(o.title || o['class'], o['class']); }); } else dom.remove(dom.getParent(id, 'tr')); }, fillFileList : function(id, l) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; l = window[l]; lst.options.length = 0; if (l && l.length > 0) { lst.options[lst.options.length] = new Option('', ''); tinymce.each(l, function(o) { lst.options[lst.options.length] = new Option(o[0], o[1]); }); } else dom.remove(dom.getParent(id, 'tr')); }, resetImageData : function() { var f = document.forms[0]; f.elements.width.value = f.elements.height.value = ''; }, updateImageData : function(img, st) { var f = document.forms[0]; if (!st) { f.elements.width.value = img.width; f.elements.height.value = img.height; } this.preloadImg = img; }, changeAppearance : function() { var ed = tinyMCEPopup.editor, f = document.forms[0], img = document.getElementById('alignSampleImg'); if (img) { if (ed.getParam('inline_styles')) { ed.dom.setAttrib(img, 'style', f.style.value); } else { img.align = f.align.value; img.border = f.border.value; img.hspace = f.hspace.value; img.vspace = f.vspace.value; } } }, changeHeight : function() { var f = document.forms[0], tp, t = this; if (!f.constrain.checked || !t.preloadImg) { return; } if (f.width.value == "" || f.height.value == "") return; tp = (parseInt(f.width.value) / parseInt(t.preloadImg.width)) * t.preloadImg.height; f.height.value = tp.toFixed(0); }, changeWidth : function() { var f = document.forms[0], tp, t = this; if (!f.constrain.checked || !t.preloadImg) { return; } if (f.width.value == "" || f.height.value == "") return; tp = (parseInt(f.height.value) / parseInt(t.preloadImg.height)) * t.preloadImg.width; f.width.value = tp.toFixed(0); }, updateStyle : function(ty) { var dom = tinyMCEPopup.dom, st, v, f = document.forms[0], img = dom.create('img', {style : dom.get('style').value}); if (tinyMCEPopup.editor.settings.inline_styles) { // Handle align if (ty == 'align') { dom.setStyle(img, 'float', ''); dom.setStyle(img, 'vertical-align', ''); v = getSelectValue(f, 'align'); if (v) { if (v == 'left' || v == 'right') dom.setStyle(img, 'float', v); else img.style.verticalAlign = v; } } // Handle border if (ty == 'border') { dom.setStyle(img, 'border', ''); v = f.border.value; if (v || v == '0') { if (v == '0') img.style.border = '0'; else img.style.border = v + 'px solid black'; } } // Handle hspace if (ty == 'hspace') { dom.setStyle(img, 'marginLeft', ''); dom.setStyle(img, 'marginRight', ''); v = f.hspace.value; if (v) { img.style.marginLeft = v + 'px'; img.style.marginRight = v + 'px'; } } // Handle vspace if (ty == 'vspace') { dom.setStyle(img, 'marginTop', ''); dom.setStyle(img, 'marginBottom', ''); v = f.vspace.value; if (v) { img.style.marginTop = v + 'px'; img.style.marginBottom = v + 'px'; } } // Merge dom.get('style').value = dom.serializeStyle(dom.parseStyle(img.style.cssText), 'img'); } }, changeMouseMove : function() { }, showPreviewImage : function(u, st) { if (!u) { tinyMCEPopup.dom.setHTML('prev', ''); return; } if (!st && tinyMCEPopup.getParam("advimage_update_dimensions_onchange", true)) this.resetImageData(); u = tinyMCEPopup.editor.documentBaseURI.toAbsolute(u); if (!st) tinyMCEPopup.dom.setHTML('prev', '<img id="previewImg" src="' + u + '" border="0" onload="ImageDialog.updateImageData(this);" onerror="ImageDialog.resetImageData();" />'); else tinyMCEPopup.dom.setHTML('prev', '<img id="previewImg" src="' + u + '" border="0" onload="ImageDialog.updateImageData(this, 1);" />'); } }; ImageDialog.preInit(); tinyMCEPopup.onInit.add(ImageDialog.init, ImageDialog);
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.AdvancedImagePlugin', { init : function(ed, url) { // Register commands ed.addCommand('mceAdvImage', function() { // Internal image object like a flash placeholder if (ed.dom.getAttrib(ed.selection.getNode(), 'class').indexOf('mceItem') != -1) return; ed.windowManager.open({ file : url + '/image.htm', width : 480 + parseInt(ed.getLang('advimage.delta_width', 0)), height : 385 + parseInt(ed.getLang('advimage.delta_height', 0)), inline : 1 }, { plugin_url : url }); }); // Register buttons ed.addButton('image', { title : 'advimage.image_desc', cmd : 'mceAdvImage' }); }, getInfo : function() { return { longname : 'Advanced image', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/advimage', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('advimage', tinymce.plugins.AdvancedImagePlugin); })();
JavaScript
tinyMCE.addI18n('en.advimage_dlg',{ tab_general:"General", tab_appearance:"Appearance", tab_advanced:"Advanced", general:"General", title:"Title", preview:"Preview", constrain_proportions:"Constrain proportions", langdir:"Language direction", langcode:"Language code", long_desc:"Long description link", style:"Style", classes:"Classes", ltr:"Left to right", rtl:"Right to left", id:"Id", map:"Image map", swap_image:"Swap image", alt_image:"Alternative image", mouseover:"for mouse over", mouseout:"for mouse out", misc:"Miscellaneous", example_img:"Appearance preview image", missing_alt:"Are you sure you want to continue without including an Image Description? Without it the image may not be accessible to some users with disabilities, or to those using a text browser, or browsing the Web with images turned off.", dialog_title:"Insert/edit image", src:"Image URL", alt:"Image description", list:"Image list", border:"Border", dimensions:"Dimensions", vspace:"Vertical space", hspace:"Horizontal space", align:"Alignment", align_baseline:"Baseline", align_top:"Top", align_middle:"Middle", align_bottom:"Bottom", align_texttop:"Text top", align_textbottom:"Text bottom", align_left:"Left", align_right:"Right", image_list:"Image list" });
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var DOM = tinymce.DOM; tinymce.create('tinymce.plugins.FullScreenPlugin', { init : function(ed, url) { var t = this, s = {}, vp; t.editor = ed; // Register commands ed.addCommand('mceFullScreen', function() { var win, de = DOM.doc.documentElement; if (ed.getParam('fullscreen_is_enabled')) { if (ed.getParam('fullscreen_new_window')) closeFullscreen(); // Call to close in new window else { DOM.win.setTimeout(function() { tinymce.dom.Event.remove(DOM.win, 'resize', t.resizeFunc); tinyMCE.get(ed.getParam('fullscreen_editor_id')).setContent(ed.getContent({format : 'raw'}), {format : 'raw'}); tinyMCE.remove(ed); DOM.remove('mce_fullscreen_container'); de.style.overflow = ed.getParam('fullscreen_html_overflow'); DOM.setStyle(DOM.doc.body, 'overflow', ed.getParam('fullscreen_overflow')); DOM.win.scrollTo(ed.getParam('fullscreen_scrollx'), ed.getParam('fullscreen_scrolly')); tinyMCE.settings = tinyMCE.oldSettings; // Restore old settings }, 10); } return; } if (ed.getParam('fullscreen_new_window')) { win = DOM.win.open(url + "/fullscreen.htm", "mceFullScreenPopup", "fullscreen=yes,menubar=no,toolbar=no,scrollbars=no,resizable=yes,left=0,top=0,width=" + screen.availWidth + ",height=" + screen.availHeight); try { win.resizeTo(screen.availWidth, screen.availHeight); } catch (e) { // Ignore } } else { tinyMCE.oldSettings = tinyMCE.settings; // Store old settings s.fullscreen_overflow = DOM.getStyle(DOM.doc.body, 'overflow', 1) || 'auto'; s.fullscreen_html_overflow = DOM.getStyle(de, 'overflow', 1); vp = DOM.getViewPort(); s.fullscreen_scrollx = vp.x; s.fullscreen_scrolly = vp.y; // Fixes an Opera bug where the scrollbars doesn't reappear if (tinymce.isOpera && s.fullscreen_overflow == 'visible') s.fullscreen_overflow = 'auto'; // Fixes an IE bug where horizontal scrollbars would appear if (tinymce.isIE && s.fullscreen_overflow == 'scroll') s.fullscreen_overflow = 'auto'; // Fixes an IE bug where the scrollbars doesn't reappear if (tinymce.isIE && (s.fullscreen_html_overflow == 'visible' || s.fullscreen_html_overflow == 'scroll')) s.fullscreen_html_overflow = 'auto'; if (s.fullscreen_overflow == '0px') s.fullscreen_overflow = ''; DOM.setStyle(DOM.doc.body, 'overflow', 'hidden'); de.style.overflow = 'hidden'; //Fix for IE6/7 vp = DOM.getViewPort(); DOM.win.scrollTo(0, 0); if (tinymce.isIE) vp.h -= 1; n = DOM.add(DOM.doc.body, 'div', {id : 'mce_fullscreen_container', style : 'position:' + (tinymce.isIE6 || (tinymce.isIE && !DOM.boxModel) ? 'absolute' : 'fixed') + ';top:0;left:0;width:' + vp.w + 'px;height:' + vp.h + 'px;z-index:200000;'}); DOM.add(n, 'div', {id : 'mce_fullscreen'}); tinymce.each(ed.settings, function(v, n) { s[n] = v; }); s.id = 'mce_fullscreen'; s.width = n.clientWidth; s.height = n.clientHeight - 15; s.fullscreen_is_enabled = true; s.fullscreen_editor_id = ed.id; s.theme_advanced_resizing = false; s.save_onsavecallback = function() { ed.setContent(tinyMCE.get(s.id).getContent({format : 'raw'}), {format : 'raw'}); ed.execCommand('mceSave'); }; tinymce.each(ed.getParam('fullscreen_settings'), function(v, k) { s[k] = v; }); if (s.theme_advanced_toolbar_location === 'external') s.theme_advanced_toolbar_location = 'top'; t.fullscreenEditor = new tinymce.Editor('mce_fullscreen', s); t.fullscreenEditor.onInit.add(function() { t.fullscreenEditor.setContent(ed.getContent()); t.fullscreenEditor.focus(); }); t.fullscreenEditor.render(); t.fullscreenElement = new tinymce.dom.Element('mce_fullscreen_container'); t.fullscreenElement.update(); //document.body.overflow = 'hidden'; t.resizeFunc = tinymce.dom.Event.add(DOM.win, 'resize', function() { var vp = tinymce.DOM.getViewPort(), fed = t.fullscreenEditor, outerSize, innerSize; // Get outer/inner size to get a delta size that can be used to calc the new iframe size outerSize = fed.dom.getSize(fed.getContainer().firstChild); innerSize = fed.dom.getSize(fed.getContainer().getElementsByTagName('iframe')[0]); fed.theme.resizeTo(vp.w - outerSize.w + innerSize.w, vp.h - outerSize.h + innerSize.h); }); } }); // Register buttons ed.addButton('fullscreen', {title : 'fullscreen.desc', cmd : 'mceFullScreen'}); ed.onNodeChange.add(function(ed, cm) { cm.setActive('fullscreen', ed.getParam('fullscreen_is_enabled')); }); }, getInfo : function() { return { longname : 'Fullscreen', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/fullscreen', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('fullscreen', tinymce.plugins.FullScreenPlugin); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var DOM = tinymce.DOM, Event = tinymce.dom.Event, each = tinymce.each, explode = tinymce.explode; tinymce.create('tinymce.plugins.TabFocusPlugin', { init : function(ed, url) { function tabCancel(ed, e) { if (e.keyCode === 9) return Event.cancel(e); }; function tabHandler(ed, e) { var x, i, f, el, v; function find(d) { f = DOM.getParent(ed.id, 'form'); el = f.elements; if (f) { each(el, function(e, i) { if (e.id == ed.id) { x = i; return false; } }); if (d > 0) { for (i = x + 1; i < el.length; i++) { if (el[i].type != 'hidden') return el[i]; } } else { for (i = x - 1; i >= 0; i--) { if (el[i].type != 'hidden') return el[i]; } } } return null; }; if (e.keyCode === 9) { v = explode(ed.getParam('tab_focus', ed.getParam('tabfocus_elements', ':prev,:next'))); if (v.length == 1) { v[1] = v[0]; v[0] = ':prev'; } // Find element to focus if (e.shiftKey) { if (v[0] == ':prev') el = find(-1); else el = DOM.get(v[0]); } else { if (v[1] == ':next') el = find(1); else el = DOM.get(v[1]); } if (el) { if (ed = tinymce.get(el.id || el.name)) ed.focus(); else window.setTimeout(function() {window.focus();el.focus();}, 10); return Event.cancel(e); } } }; ed.onKeyUp.add(tabCancel); if (tinymce.isGecko) { ed.onKeyPress.add(tabHandler); ed.onKeyDown.add(tabCancel); } else ed.onKeyDown.add(tabHandler); ed.onInit.add(function() { each(DOM.select('a:first,a:last', ed.getContainer()), function(n) { Event.add(n, 'focus', function() {ed.focus();}); }); }); }, getInfo : function() { return { longname : 'Tabfocus', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/tabfocus', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('tabfocus', tinymce.plugins.TabFocusPlugin); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.InsertDateTime', { init : function(ed, url) { var t = this; t.editor = ed; ed.addCommand('mceInsertDate', function() { var str = t._getDateTime(new Date(), ed.getParam("plugin_insertdate_dateFormat", ed.getLang('insertdatetime.date_fmt'))); ed.execCommand('mceInsertContent', false, str); }); ed.addCommand('mceInsertTime', function() { var str = t._getDateTime(new Date(), ed.getParam("plugin_insertdate_timeFormat", ed.getLang('insertdatetime.time_fmt'))); ed.execCommand('mceInsertContent', false, str); }); ed.addButton('insertdate', {title : 'insertdatetime.insertdate_desc', cmd : 'mceInsertDate'}); ed.addButton('inserttime', {title : 'insertdatetime.inserttime_desc', cmd : 'mceInsertTime'}); }, getInfo : function() { return { longname : 'Insert date/time', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/insertdatetime', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, // Private methods _getDateTime : function(d, fmt) { var ed = this.editor; function addZeros(value, len) { value = "" + value; if (value.length < len) { for (var i=0; i<(len-value.length); i++) value = "0" + value; } return value; }; fmt = fmt.replace("%D", "%m/%d/%y"); fmt = fmt.replace("%r", "%I:%M:%S %p"); fmt = fmt.replace("%Y", "" + d.getFullYear()); fmt = fmt.replace("%y", "" + d.getYear()); fmt = fmt.replace("%m", addZeros(d.getMonth()+1, 2)); fmt = fmt.replace("%d", addZeros(d.getDate(), 2)); fmt = fmt.replace("%H", "" + addZeros(d.getHours(), 2)); fmt = fmt.replace("%M", "" + addZeros(d.getMinutes(), 2)); fmt = fmt.replace("%S", "" + addZeros(d.getSeconds(), 2)); fmt = fmt.replace("%I", "" + ((d.getHours() + 11) % 12 + 1)); fmt = fmt.replace("%p", "" + (d.getHours() < 12 ? "AM" : "PM")); fmt = fmt.replace("%B", "" + ed.getLang("insertdatetime.months_long").split(',')[d.getMonth()]); fmt = fmt.replace("%b", "" + ed.getLang("insertdatetime.months_short").split(',')[d.getMonth()]); fmt = fmt.replace("%A", "" + ed.getLang("insertdatetime.day_long").split(',')[d.getDay()]); fmt = fmt.replace("%a", "" + ed.getLang("insertdatetime.day_short").split(',')[d.getDay()]); fmt = fmt.replace("%%", "%"); return fmt; } }); // Register plugin tinymce.PluginManager.add('insertdatetime', tinymce.plugins.InsertDateTime); })();
JavaScript
tinyMCEPopup.requireLangPack(); var defaultFonts = "" + "Arial, Helvetica, sans-serif=Arial, Helvetica, sans-serif;" + "Times New Roman, Times, serif=Times New Roman, Times, serif;" + "Courier New, Courier, mono=Courier New, Courier, mono;" + "Times New Roman, Times, serif=Times New Roman, Times, serif;" + "Georgia, Times New Roman, Times, serif=Georgia, Times New Roman, Times, serif;" + "Verdana, Arial, Helvetica, sans-serif=Verdana, Arial, Helvetica, sans-serif;" + "Geneva, Arial, Helvetica, sans-serif=Geneva, Arial, Helvetica, sans-serif"; var defaultSizes = "9;10;12;14;16;18;24;xx-small;x-small;small;medium;large;x-large;xx-large;smaller;larger"; var defaultMeasurement = "+pixels=px;points=pt;inches=in;centimetres=cm;millimetres=mm;picas=pc;ems=em;exs=ex;%"; var defaultSpacingMeasurement = "pixels=px;points=pt;inches=in;centimetres=cm;millimetres=mm;picas=pc;+ems=em;exs=ex;%"; var defaultIndentMeasurement = "pixels=px;+points=pt;inches=in;centimetres=cm;millimetres=mm;picas=pc;ems=em;exs=ex;%"; var defaultWeight = "normal;bold;bolder;lighter;100;200;300;400;500;600;700;800;900"; var defaultTextStyle = "normal;italic;oblique"; var defaultVariant = "normal;small-caps"; var defaultLineHeight = "normal"; var defaultAttachment = "fixed;scroll"; var defaultRepeat = "no-repeat;repeat;repeat-x;repeat-y"; var defaultPosH = "left;center;right"; var defaultPosV = "top;center;bottom"; var defaultVAlign = "baseline;sub;super;top;text-top;middle;bottom;text-bottom"; var defaultDisplay = "inline;block;list-item;run-in;compact;marker;table;inline-table;table-row-group;table-header-group;table-footer-group;table-row;table-column-group;table-column;table-cell;table-caption;none"; var defaultBorderStyle = "none;solid;dashed;dotted;double;groove;ridge;inset;outset"; var defaultBorderWidth = "thin;medium;thick"; var defaultListType = "disc;circle;square;decimal;lower-roman;upper-roman;lower-alpha;upper-alpha;none"; function init() { var ce = document.getElementById('container'), h; ce.style.cssText = tinyMCEPopup.getWindowArg('style_text'); h = getBrowserHTML('background_image_browser','background_image','image','advimage'); document.getElementById("background_image_browser").innerHTML = h; document.getElementById('text_color_pickcontainer').innerHTML = getColorPickerHTML('text_color_pick','text_color'); document.getElementById('background_color_pickcontainer').innerHTML = getColorPickerHTML('background_color_pick','background_color'); document.getElementById('border_color_top_pickcontainer').innerHTML = getColorPickerHTML('border_color_top_pick','border_color_top'); document.getElementById('border_color_right_pickcontainer').innerHTML = getColorPickerHTML('border_color_right_pick','border_color_right'); document.getElementById('border_color_bottom_pickcontainer').innerHTML = getColorPickerHTML('border_color_bottom_pick','border_color_bottom'); document.getElementById('border_color_left_pickcontainer').innerHTML = getColorPickerHTML('border_color_left_pick','border_color_left'); fillSelect(0, 'text_font', 'style_font', defaultFonts, ';', true); fillSelect(0, 'text_size', 'style_font_size', defaultSizes, ';', true); fillSelect(0, 'text_size_measurement', 'style_font_size_measurement', defaultMeasurement, ';', true); fillSelect(0, 'text_case', 'style_text_case', "capitalize;uppercase;lowercase", ';', true); fillSelect(0, 'text_weight', 'style_font_weight', defaultWeight, ';', true); fillSelect(0, 'text_style', 'style_font_style', defaultTextStyle, ';', true); fillSelect(0, 'text_variant', 'style_font_variant', defaultVariant, ';', true); fillSelect(0, 'text_lineheight', 'style_font_line_height', defaultLineHeight, ';', true); fillSelect(0, 'text_lineheight_measurement', 'style_font_line_height_measurement', defaultMeasurement, ';', true); fillSelect(0, 'background_attachment', 'style_background_attachment', defaultAttachment, ';', true); fillSelect(0, 'background_repeat', 'style_background_repeat', defaultRepeat, ';', true); fillSelect(0, 'background_hpos_measurement', 'style_background_hpos_measurement', defaultMeasurement, ';', true); fillSelect(0, 'background_vpos_measurement', 'style_background_vpos_measurement', defaultMeasurement, ';', true); fillSelect(0, 'background_hpos', 'style_background_hpos', defaultPosH, ';', true); fillSelect(0, 'background_vpos', 'style_background_vpos', defaultPosV, ';', true); fillSelect(0, 'block_wordspacing', 'style_wordspacing', 'normal', ';', true); fillSelect(0, 'block_wordspacing_measurement', 'style_wordspacing_measurement', defaultSpacingMeasurement, ';', true); fillSelect(0, 'block_letterspacing', 'style_letterspacing', 'normal', ';', true); fillSelect(0, 'block_letterspacing_measurement', 'style_letterspacing_measurement', defaultSpacingMeasurement, ';', true); fillSelect(0, 'block_vertical_alignment', 'style_vertical_alignment', defaultVAlign, ';', true); fillSelect(0, 'block_text_align', 'style_text_align', "left;right;center;justify", ';', true); fillSelect(0, 'block_whitespace', 'style_whitespace', "normal;pre;nowrap", ';', true); fillSelect(0, 'block_display', 'style_display', defaultDisplay, ';', true); fillSelect(0, 'block_text_indent_measurement', 'style_text_indent_measurement', defaultIndentMeasurement, ';', true); fillSelect(0, 'box_width_measurement', 'style_box_width_measurement', defaultMeasurement, ';', true); fillSelect(0, 'box_height_measurement', 'style_box_height_measurement', defaultMeasurement, ';', true); fillSelect(0, 'box_float', 'style_float', 'left;right;none', ';', true); fillSelect(0, 'box_clear', 'style_clear', 'left;right;both;none', ';', true); fillSelect(0, 'box_padding_left_measurement', 'style_padding_left_measurement', defaultMeasurement, ';', true); fillSelect(0, 'box_padding_top_measurement', 'style_padding_top_measurement', defaultMeasurement, ';', true); fillSelect(0, 'box_padding_bottom_measurement', 'style_padding_bottom_measurement', defaultMeasurement, ';', true); fillSelect(0, 'box_padding_right_measurement', 'style_padding_right_measurement', defaultMeasurement, ';', true); fillSelect(0, 'box_margin_left_measurement', 'style_margin_left_measurement', defaultMeasurement, ';', true); fillSelect(0, 'box_margin_top_measurement', 'style_margin_top_measurement', defaultMeasurement, ';', true); fillSelect(0, 'box_margin_bottom_measurement', 'style_margin_bottom_measurement', defaultMeasurement, ';', true); fillSelect(0, 'box_margin_right_measurement', 'style_margin_right_measurement', defaultMeasurement, ';', true); fillSelect(0, 'border_style_top', 'style_border_style_top', defaultBorderStyle, ';', true); fillSelect(0, 'border_style_right', 'style_border_style_right', defaultBorderStyle, ';', true); fillSelect(0, 'border_style_bottom', 'style_border_style_bottom', defaultBorderStyle, ';', true); fillSelect(0, 'border_style_left', 'style_border_style_left', defaultBorderStyle, ';', true); fillSelect(0, 'border_width_top', 'style_border_width_top', defaultBorderWidth, ';', true); fillSelect(0, 'border_width_right', 'style_border_width_right', defaultBorderWidth, ';', true); fillSelect(0, 'border_width_bottom', 'style_border_width_bottom', defaultBorderWidth, ';', true); fillSelect(0, 'border_width_left', 'style_border_width_left', defaultBorderWidth, ';', true); fillSelect(0, 'border_width_top_measurement', 'style_border_width_top_measurement', defaultMeasurement, ';', true); fillSelect(0, 'border_width_right_measurement', 'style_border_width_right_measurement', defaultMeasurement, ';', true); fillSelect(0, 'border_width_bottom_measurement', 'style_border_width_bottom_measurement', defaultMeasurement, ';', true); fillSelect(0, 'border_width_left_measurement', 'style_border_width_left_measurement', defaultMeasurement, ';', true); fillSelect(0, 'list_type', 'style_list_type', defaultListType, ';', true); fillSelect(0, 'list_position', 'style_list_position', "inside;outside", ';', true); fillSelect(0, 'positioning_type', 'style_positioning_type', "absolute;relative;static", ';', true); fillSelect(0, 'positioning_visibility', 'style_positioning_visibility', "inherit;visible;hidden", ';', true); fillSelect(0, 'positioning_width_measurement', 'style_positioning_width_measurement', defaultMeasurement, ';', true); fillSelect(0, 'positioning_height_measurement', 'style_positioning_height_measurement', defaultMeasurement, ';', true); fillSelect(0, 'positioning_overflow', 'style_positioning_overflow', "visible;hidden;scroll;auto", ';', true); fillSelect(0, 'positioning_placement_top_measurement', 'style_positioning_placement_top_measurement', defaultMeasurement, ';', true); fillSelect(0, 'positioning_placement_right_measurement', 'style_positioning_placement_right_measurement', defaultMeasurement, ';', true); fillSelect(0, 'positioning_placement_bottom_measurement', 'style_positioning_placement_bottom_measurement', defaultMeasurement, ';', true); fillSelect(0, 'positioning_placement_left_measurement', 'style_positioning_placement_left_measurement', defaultMeasurement, ';', true); fillSelect(0, 'positioning_clip_top_measurement', 'style_positioning_clip_top_measurement', defaultMeasurement, ';', true); fillSelect(0, 'positioning_clip_right_measurement', 'style_positioning_clip_right_measurement', defaultMeasurement, ';', true); fillSelect(0, 'positioning_clip_bottom_measurement', 'style_positioning_clip_bottom_measurement', defaultMeasurement, ';', true); fillSelect(0, 'positioning_clip_left_measurement', 'style_positioning_clip_left_measurement', defaultMeasurement, ';', true); TinyMCE_EditableSelects.init(); setupFormData(); showDisabledControls(); } function setupFormData() { var ce = document.getElementById('container'), f = document.forms[0], s, b, i; // Setup text fields selectByValue(f, 'text_font', ce.style.fontFamily, true, true); selectByValue(f, 'text_size', getNum(ce.style.fontSize), true, true); selectByValue(f, 'text_size_measurement', getMeasurement(ce.style.fontSize)); selectByValue(f, 'text_weight', ce.style.fontWeight, true, true); selectByValue(f, 'text_style', ce.style.fontStyle, true, true); selectByValue(f, 'text_lineheight', getNum(ce.style.lineHeight), true, true); selectByValue(f, 'text_lineheight_measurement', getMeasurement(ce.style.lineHeight)); selectByValue(f, 'text_case', ce.style.textTransform, true, true); selectByValue(f, 'text_variant', ce.style.fontVariant, true, true); f.text_color.value = tinyMCEPopup.editor.dom.toHex(ce.style.color); updateColor('text_color_pick', 'text_color'); f.text_underline.checked = inStr(ce.style.textDecoration, 'underline'); f.text_overline.checked = inStr(ce.style.textDecoration, 'overline'); f.text_linethrough.checked = inStr(ce.style.textDecoration, 'line-through'); f.text_blink.checked = inStr(ce.style.textDecoration, 'blink'); // Setup background fields f.background_color.value = tinyMCEPopup.editor.dom.toHex(ce.style.backgroundColor); updateColor('background_color_pick', 'background_color'); f.background_image.value = ce.style.backgroundImage.replace(new RegExp("url\\('?([^']*)'?\\)", 'gi'), "$1"); selectByValue(f, 'background_repeat', ce.style.backgroundRepeat, true, true); selectByValue(f, 'background_attachment', ce.style.backgroundAttachment, true, true); selectByValue(f, 'background_hpos', getNum(getVal(ce.style.backgroundPosition, 0)), true, true); selectByValue(f, 'background_hpos_measurement', getMeasurement(getVal(ce.style.backgroundPosition, 0))); selectByValue(f, 'background_vpos', getNum(getVal(ce.style.backgroundPosition, 1)), true, true); selectByValue(f, 'background_vpos_measurement', getMeasurement(getVal(ce.style.backgroundPosition, 1))); // Setup block fields selectByValue(f, 'block_wordspacing', getNum(ce.style.wordSpacing), true, true); selectByValue(f, 'block_wordspacing_measurement', getMeasurement(ce.style.wordSpacing)); selectByValue(f, 'block_letterspacing', getNum(ce.style.letterSpacing), true, true); selectByValue(f, 'block_letterspacing_measurement', getMeasurement(ce.style.letterSpacing)); selectByValue(f, 'block_vertical_alignment', ce.style.verticalAlign, true, true); selectByValue(f, 'block_text_align', ce.style.textAlign, true, true); f.block_text_indent.value = getNum(ce.style.textIndent); selectByValue(f, 'block_text_indent_measurement', getMeasurement(ce.style.textIndent)); selectByValue(f, 'block_whitespace', ce.style.whiteSpace, true, true); selectByValue(f, 'block_display', ce.style.display, true, true); // Setup box fields f.box_width.value = getNum(ce.style.width); selectByValue(f, 'box_width_measurement', getMeasurement(ce.style.width)); f.box_height.value = getNum(ce.style.height); selectByValue(f, 'box_height_measurement', getMeasurement(ce.style.height)); if (tinymce.isGecko) selectByValue(f, 'box_float', ce.style.cssFloat, true, true); else selectByValue(f, 'box_float', ce.style.styleFloat, true, true); selectByValue(f, 'box_clear', ce.style.clear, true, true); setupBox(f, ce, 'box_padding', 'padding', ''); setupBox(f, ce, 'box_margin', 'margin', ''); // Setup border fields setupBox(f, ce, 'border_style', 'border', 'Style'); setupBox(f, ce, 'border_width', 'border', 'Width'); setupBox(f, ce, 'border_color', 'border', 'Color'); updateColor('border_color_top_pick', 'border_color_top'); updateColor('border_color_right_pick', 'border_color_right'); updateColor('border_color_bottom_pick', 'border_color_bottom'); updateColor('border_color_left_pick', 'border_color_left'); f.elements.border_color_top.value = tinyMCEPopup.editor.dom.toHex(f.elements.border_color_top.value); f.elements.border_color_right.value = tinyMCEPopup.editor.dom.toHex(f.elements.border_color_right.value); f.elements.border_color_bottom.value = tinyMCEPopup.editor.dom.toHex(f.elements.border_color_bottom.value); f.elements.border_color_left.value = tinyMCEPopup.editor.dom.toHex(f.elements.border_color_left.value); // Setup list fields selectByValue(f, 'list_type', ce.style.listStyleType, true, true); selectByValue(f, 'list_position', ce.style.listStylePosition, true, true); f.list_bullet_image.value = ce.style.listStyleImage.replace(new RegExp("url\\('?([^']*)'?\\)", 'gi'), "$1"); // Setup box fields selectByValue(f, 'positioning_type', ce.style.position, true, true); selectByValue(f, 'positioning_visibility', ce.style.visibility, true, true); selectByValue(f, 'positioning_overflow', ce.style.overflow, true, true); f.positioning_zindex.value = ce.style.zIndex ? ce.style.zIndex : ""; f.positioning_width.value = getNum(ce.style.width); selectByValue(f, 'positioning_width_measurement', getMeasurement(ce.style.width)); f.positioning_height.value = getNum(ce.style.height); selectByValue(f, 'positioning_height_measurement', getMeasurement(ce.style.height)); setupBox(f, ce, 'positioning_placement', '', '', ['top', 'right', 'bottom', 'left']); s = ce.style.clip.replace(new RegExp("rect\\('?([^']*)'?\\)", 'gi'), "$1"); s = s.replace(/,/g, ' '); if (!hasEqualValues([getVal(s, 0), getVal(s, 1), getVal(s, 2), getVal(s, 3)])) { f.positioning_clip_top.value = getNum(getVal(s, 0)); selectByValue(f, 'positioning_clip_top_measurement', getMeasurement(getVal(s, 0))); f.positioning_clip_right.value = getNum(getVal(s, 1)); selectByValue(f, 'positioning_clip_right_measurement', getMeasurement(getVal(s, 1))); f.positioning_clip_bottom.value = getNum(getVal(s, 2)); selectByValue(f, 'positioning_clip_bottom_measurement', getMeasurement(getVal(s, 2))); f.positioning_clip_left.value = getNum(getVal(s, 3)); selectByValue(f, 'positioning_clip_left_measurement', getMeasurement(getVal(s, 3))); } else { f.positioning_clip_top.value = getNum(getVal(s, 0)); selectByValue(f, 'positioning_clip_top_measurement', getMeasurement(getVal(s, 0))); f.positioning_clip_right.value = f.positioning_clip_bottom.value = f.positioning_clip_left.value; } // setupBox(f, ce, '', 'border', 'Color'); } function getMeasurement(s) { return s.replace(/^([0-9.]+)(.*)$/, "$2"); } function getNum(s) { if (new RegExp('^(?:[0-9.]+)(?:[a-z%]+)$', 'gi').test(s)) return s.replace(/[^0-9.]/g, ''); return s; } function inStr(s, n) { return new RegExp(n, 'gi').test(s); } function getVal(s, i) { var a = s.split(' '); if (a.length > 1) return a[i]; return ""; } function setValue(f, n, v) { if (f.elements[n].type == "text") f.elements[n].value = v; else selectByValue(f, n, v, true, true); } function setupBox(f, ce, fp, pr, sf, b) { if (typeof(b) == "undefined") b = ['Top', 'Right', 'Bottom', 'Left']; if (isSame(ce, pr, sf, b)) { f.elements[fp + "_same"].checked = true; setValue(f, fp + "_top", getNum(ce.style[pr + b[0] + sf])); f.elements[fp + "_top"].disabled = false; f.elements[fp + "_right"].value = ""; f.elements[fp + "_right"].disabled = true; f.elements[fp + "_bottom"].value = ""; f.elements[fp + "_bottom"].disabled = true; f.elements[fp + "_left"].value = ""; f.elements[fp + "_left"].disabled = true; if (f.elements[fp + "_top_measurement"]) { selectByValue(f, fp + '_top_measurement', getMeasurement(ce.style[pr + b[0] + sf])); f.elements[fp + "_left_measurement"].disabled = true; f.elements[fp + "_bottom_measurement"].disabled = true; f.elements[fp + "_right_measurement"].disabled = true; } } else { f.elements[fp + "_same"].checked = false; setValue(f, fp + "_top", getNum(ce.style[pr + b[0] + sf])); f.elements[fp + "_top"].disabled = false; setValue(f, fp + "_right", getNum(ce.style[pr + b[1] + sf])); f.elements[fp + "_right"].disabled = false; setValue(f, fp + "_bottom", getNum(ce.style[pr + b[2] + sf])); f.elements[fp + "_bottom"].disabled = false; setValue(f, fp + "_left", getNum(ce.style[pr + b[3] + sf])); f.elements[fp + "_left"].disabled = false; if (f.elements[fp + "_top_measurement"]) { selectByValue(f, fp + '_top_measurement', getMeasurement(ce.style[pr + b[0] + sf])); selectByValue(f, fp + '_right_measurement', getMeasurement(ce.style[pr + b[1] + sf])); selectByValue(f, fp + '_bottom_measurement', getMeasurement(ce.style[pr + b[2] + sf])); selectByValue(f, fp + '_left_measurement', getMeasurement(ce.style[pr + b[3] + sf])); f.elements[fp + "_left_measurement"].disabled = false; f.elements[fp + "_bottom_measurement"].disabled = false; f.elements[fp + "_right_measurement"].disabled = false; } } } function isSame(e, pr, sf, b) { var a = [], i, x; if (typeof(b) == "undefined") b = ['Top', 'Right', 'Bottom', 'Left']; if (typeof(sf) == "undefined" || sf == null) sf = ""; a[0] = e.style[pr + b[0] + sf]; a[1] = e.style[pr + b[1] + sf]; a[2] = e.style[pr + b[2] + sf]; a[3] = e.style[pr + b[3] + sf]; for (i=0; i<a.length; i++) { if (a[i] == null) return false; for (x=0; x<a.length; x++) { if (a[x] != a[i]) return false; } } return true; }; function hasEqualValues(a) { var i, x; for (i=0; i<a.length; i++) { if (a[i] == null) return false; for (x=0; x<a.length; x++) { if (a[x] != a[i]) return false; } } return true; } function applyAction() { var ce = document.getElementById('container'), ed = tinyMCEPopup.editor; generateCSS(); tinyMCEPopup.restoreSelection(); ed.dom.setAttrib(ed.selection.getNode(), 'style', tinyMCEPopup.editor.dom.serializeStyle(tinyMCEPopup.editor.dom.parseStyle(ce.style.cssText))); } function updateAction() { applyAction(); tinyMCEPopup.close(); } function generateCSS() { var ce = document.getElementById('container'), f = document.forms[0], num = new RegExp('[0-9]+', 'g'), s, t; ce.style.cssText = ""; // Build text styles ce.style.fontFamily = f.text_font.value; ce.style.fontSize = f.text_size.value + (isNum(f.text_size.value) ? (f.text_size_measurement.value || 'px') : ""); ce.style.fontStyle = f.text_style.value; ce.style.lineHeight = f.text_lineheight.value + (isNum(f.text_lineheight.value) ? f.text_lineheight_measurement.value : ""); ce.style.textTransform = f.text_case.value; ce.style.fontWeight = f.text_weight.value; ce.style.fontVariant = f.text_variant.value; ce.style.color = f.text_color.value; s = ""; s += f.text_underline.checked ? " underline" : ""; s += f.text_overline.checked ? " overline" : ""; s += f.text_linethrough.checked ? " line-through" : ""; s += f.text_blink.checked ? " blink" : ""; s = s.length > 0 ? s.substring(1) : s; if (f.text_none.checked) s = "none"; ce.style.textDecoration = s; // Build background styles ce.style.backgroundColor = f.background_color.value; ce.style.backgroundImage = f.background_image.value != "" ? "url(" + f.background_image.value + ")" : ""; ce.style.backgroundRepeat = f.background_repeat.value; ce.style.backgroundAttachment = f.background_attachment.value; if (f.background_hpos.value != "") { s = ""; s += f.background_hpos.value + (isNum(f.background_hpos.value) ? f.background_hpos_measurement.value : "") + " "; s += f.background_vpos.value + (isNum(f.background_vpos.value) ? f.background_vpos_measurement.value : ""); ce.style.backgroundPosition = s; } // Build block styles ce.style.wordSpacing = f.block_wordspacing.value + (isNum(f.block_wordspacing.value) ? f.block_wordspacing_measurement.value : ""); ce.style.letterSpacing = f.block_letterspacing.value + (isNum(f.block_letterspacing.value) ? f.block_letterspacing_measurement.value : ""); ce.style.verticalAlign = f.block_vertical_alignment.value; ce.style.textAlign = f.block_text_align.value; ce.style.textIndent = f.block_text_indent.value + (isNum(f.block_text_indent.value) ? f.block_text_indent_measurement.value : ""); ce.style.whiteSpace = f.block_whitespace.value; ce.style.display = f.block_display.value; // Build box styles ce.style.width = f.box_width.value + (isNum(f.box_width.value) ? f.box_width_measurement.value : ""); ce.style.height = f.box_height.value + (isNum(f.box_height.value) ? f.box_height_measurement.value : ""); ce.style.styleFloat = f.box_float.value; if (tinymce.isGecko) ce.style.cssFloat = f.box_float.value; ce.style.clear = f.box_clear.value; if (!f.box_padding_same.checked) { ce.style.paddingTop = f.box_padding_top.value + (isNum(f.box_padding_top.value) ? f.box_padding_top_measurement.value : ""); ce.style.paddingRight = f.box_padding_right.value + (isNum(f.box_padding_right.value) ? f.box_padding_right_measurement.value : ""); ce.style.paddingBottom = f.box_padding_bottom.value + (isNum(f.box_padding_bottom.value) ? f.box_padding_bottom_measurement.value : ""); ce.style.paddingLeft = f.box_padding_left.value + (isNum(f.box_padding_left.value) ? f.box_padding_left_measurement.value : ""); } else ce.style.padding = f.box_padding_top.value + (isNum(f.box_padding_top.value) ? f.box_padding_top_measurement.value : ""); if (!f.box_margin_same.checked) { ce.style.marginTop = f.box_margin_top.value + (isNum(f.box_margin_top.value) ? f.box_margin_top_measurement.value : ""); ce.style.marginRight = f.box_margin_right.value + (isNum(f.box_margin_right.value) ? f.box_margin_right_measurement.value : ""); ce.style.marginBottom = f.box_margin_bottom.value + (isNum(f.box_margin_bottom.value) ? f.box_margin_bottom_measurement.value : ""); ce.style.marginLeft = f.box_margin_left.value + (isNum(f.box_margin_left.value) ? f.box_margin_left_measurement.value : ""); } else ce.style.margin = f.box_margin_top.value + (isNum(f.box_margin_top.value) ? f.box_margin_top_measurement.value : ""); // Build border styles if (!f.border_style_same.checked) { ce.style.borderTopStyle = f.border_style_top.value; ce.style.borderRightStyle = f.border_style_right.value; ce.style.borderBottomStyle = f.border_style_bottom.value; ce.style.borderLeftStyle = f.border_style_left.value; } else ce.style.borderStyle = f.border_style_top.value; if (!f.border_width_same.checked) { ce.style.borderTopWidth = f.border_width_top.value + (isNum(f.border_width_top.value) ? f.border_width_top_measurement.value : ""); ce.style.borderRightWidth = f.border_width_right.value + (isNum(f.border_width_right.value) ? f.border_width_right_measurement.value : ""); ce.style.borderBottomWidth = f.border_width_bottom.value + (isNum(f.border_width_bottom.value) ? f.border_width_bottom_measurement.value : ""); ce.style.borderLeftWidth = f.border_width_left.value + (isNum(f.border_width_left.value) ? f.border_width_left_measurement.value : ""); } else ce.style.borderWidth = f.border_width_top.value + (isNum(f.border_width_top.value) ? f.border_width_top_measurement.value : ""); if (!f.border_color_same.checked) { ce.style.borderTopColor = f.border_color_top.value; ce.style.borderRightColor = f.border_color_right.value; ce.style.borderBottomColor = f.border_color_bottom.value; ce.style.borderLeftColor = f.border_color_left.value; } else ce.style.borderColor = f.border_color_top.value; // Build list styles ce.style.listStyleType = f.list_type.value; ce.style.listStylePosition = f.list_position.value; ce.style.listStyleImage = f.list_bullet_image.value != "" ? "url(" + f.list_bullet_image.value + ")" : ""; // Build positioning styles ce.style.position = f.positioning_type.value; ce.style.visibility = f.positioning_visibility.value; if (ce.style.width == "") ce.style.width = f.positioning_width.value + (isNum(f.positioning_width.value) ? f.positioning_width_measurement.value : ""); if (ce.style.height == "") ce.style.height = f.positioning_height.value + (isNum(f.positioning_height.value) ? f.positioning_height_measurement.value : ""); ce.style.zIndex = f.positioning_zindex.value; ce.style.overflow = f.positioning_overflow.value; if (!f.positioning_placement_same.checked) { ce.style.top = f.positioning_placement_top.value + (isNum(f.positioning_placement_top.value) ? f.positioning_placement_top_measurement.value : ""); ce.style.right = f.positioning_placement_right.value + (isNum(f.positioning_placement_right.value) ? f.positioning_placement_right_measurement.value : ""); ce.style.bottom = f.positioning_placement_bottom.value + (isNum(f.positioning_placement_bottom.value) ? f.positioning_placement_bottom_measurement.value : ""); ce.style.left = f.positioning_placement_left.value + (isNum(f.positioning_placement_left.value) ? f.positioning_placement_left_measurement.value : ""); } else { s = f.positioning_placement_top.value + (isNum(f.positioning_placement_top.value) ? f.positioning_placement_top_measurement.value : ""); ce.style.top = s; ce.style.right = s; ce.style.bottom = s; ce.style.left = s; } if (!f.positioning_clip_same.checked) { s = "rect("; s += (isNum(f.positioning_clip_top.value) ? f.positioning_clip_top.value + f.positioning_clip_top_measurement.value : "auto") + " "; s += (isNum(f.positioning_clip_right.value) ? f.positioning_clip_right.value + f.positioning_clip_right_measurement.value : "auto") + " "; s += (isNum(f.positioning_clip_bottom.value) ? f.positioning_clip_bottom.value + f.positioning_clip_bottom_measurement.value : "auto") + " "; s += (isNum(f.positioning_clip_left.value) ? f.positioning_clip_left.value + f.positioning_clip_left_measurement.value : "auto"); s += ")"; if (s != "rect(auto auto auto auto)") ce.style.clip = s; } else { s = "rect("; t = isNum(f.positioning_clip_top.value) ? f.positioning_clip_top.value + f.positioning_clip_top_measurement.value : "auto"; s += t + " "; s += t + " "; s += t + " "; s += t + ")"; if (s != "rect(auto auto auto auto)") ce.style.clip = s; } ce.style.cssText = ce.style.cssText; } function isNum(s) { return new RegExp('[0-9]+', 'g').test(s); } function showDisabledControls() { var f = document.forms, i, a; for (i=0; i<f.length; i++) { for (a=0; a<f[i].elements.length; a++) { if (f[i].elements[a].disabled) tinyMCEPopup.editor.dom.addClass(f[i].elements[a], "disabled"); else tinyMCEPopup.editor.dom.removeClass(f[i].elements[a], "disabled"); } } } function fillSelect(f, s, param, dval, sep, em) { var i, ar, p, se; f = document.forms[f]; sep = typeof(sep) == "undefined" ? ";" : sep; if (em) addSelectValue(f, s, "", ""); ar = tinyMCEPopup.getParam(param, dval).split(sep); for (i=0; i<ar.length; i++) { se = false; if (ar[i].charAt(0) == '+') { ar[i] = ar[i].substring(1); se = true; } p = ar[i].split('='); if (p.length > 1) { addSelectValue(f, s, p[0], p[1]); if (se) selectByValue(f, s, p[1]); } else { addSelectValue(f, s, p[0], p[0]); if (se) selectByValue(f, s, p[0]); } } } function toggleSame(ce, pre) { var el = document.forms[0].elements, i; if (ce.checked) { el[pre + "_top"].disabled = false; el[pre + "_right"].disabled = true; el[pre + "_bottom"].disabled = true; el[pre + "_left"].disabled = true; if (el[pre + "_top_measurement"]) { el[pre + "_top_measurement"].disabled = false; el[pre + "_right_measurement"].disabled = true; el[pre + "_bottom_measurement"].disabled = true; el[pre + "_left_measurement"].disabled = true; } } else { el[pre + "_top"].disabled = false; el[pre + "_right"].disabled = false; el[pre + "_bottom"].disabled = false; el[pre + "_left"].disabled = false; if (el[pre + "_top_measurement"]) { el[pre + "_top_measurement"].disabled = false; el[pre + "_right_measurement"].disabled = false; el[pre + "_bottom_measurement"].disabled = false; el[pre + "_left_measurement"].disabled = false; } } showDisabledControls(); } function synch(fr, to) { var f = document.forms[0]; f.elements[to].value = f.elements[fr].value; if (f.elements[fr + "_measurement"]) selectByValue(f, to + "_measurement", f.elements[fr + "_measurement"].value); } tinyMCEPopup.onInit.add(init);
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.StylePlugin', { init : function(ed, url) { // Register commands ed.addCommand('mceStyleProps', function() { ed.windowManager.open({ file : url + '/props.htm', width : 480 + parseInt(ed.getLang('style.delta_width', 0)), height : 320 + parseInt(ed.getLang('style.delta_height', 0)), inline : 1 }, { plugin_url : url, style_text : ed.selection.getNode().style.cssText }); }); ed.addCommand('mceSetElementStyle', function(ui, v) { if (e = ed.selection.getNode()) { ed.dom.setAttrib(e, 'style', v); ed.execCommand('mceRepaint'); } }); ed.onNodeChange.add(function(ed, cm, n) { cm.setDisabled('styleprops', n.nodeName === 'BODY'); }); // Register buttons ed.addButton('styleprops', {title : 'style.desc', cmd : 'mceStyleProps'}); }, getInfo : function() { return { longname : 'Style', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/style', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('style', tinymce.plugins.StylePlugin); })();
JavaScript
tinyMCE.addI18n('en.style_dlg',{ title:"Edit CSS Style", apply:"Apply", text_tab:"Text", background_tab:"Background", block_tab:"Block", box_tab:"Box", border_tab:"Border", list_tab:"List", positioning_tab:"Positioning", text_props:"Text", text_font:"Font", text_size:"Size", text_weight:"Weight", text_style:"Style", text_variant:"Variant", text_lineheight:"Line height", text_case:"Case", text_color:"Color", text_decoration:"Decoration", text_overline:"overline", text_underline:"underline", text_striketrough:"strikethrough", text_blink:"blink", text_none:"none", background_color:"Background color", background_image:"Background image", background_repeat:"Repeat", background_attachment:"Attachment", background_hpos:"Horizontal position", background_vpos:"Vertical position", block_wordspacing:"Word spacing", block_letterspacing:"Letter spacing", block_vertical_alignment:"Vertical alignment", block_text_align:"Text align", block_text_indent:"Text indent", block_whitespace:"Whitespace", block_display:"Display", box_width:"Width", box_height:"Height", box_float:"Float", box_clear:"Clear", padding:"Padding", same:"Same for all", top:"Top", right:"Right", bottom:"Bottom", left:"Left", margin:"Margin", style:"Style", width:"Width", height:"Height", color:"Color", list_type:"Type", bullet_image:"Bullet image", position:"Position", positioning_type:"Type", visibility:"Visibility", zindex:"Z-index", overflow:"Overflow", placement:"Placement", clip:"Clip" });
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var each = tinymce.each; tinymce.create('tinymce.plugins.AdvListPlugin', { init : function(ed, url) { var t = this; t.editor = ed; function buildFormats(str) { var formats = []; each(str.split(/,/), function(type) { formats.push({ title : 'advlist.' + (type == 'default' ? 'def' : type.replace(/-/g, '_')), styles : { listStyleType : type == 'default' ? '' : type } }); }); return formats; }; // Setup number formats from config or default t.numlist = ed.getParam("advlist_number_styles") || buildFormats("default,lower-alpha,lower-greek,lower-roman,upper-alpha,upper-roman"); t.bullist = ed.getParam("advlist_bullet_styles") || buildFormats("default,circle,disc,square"); }, createControl: function(name, cm) { var t = this, btn, format; if (name == 'numlist' || name == 'bullist') { // Default to first item if it's a default item if (t[name][0].title == 'advlist.def') format = t[name][0]; function hasFormat(node, format) { var state = true; each(format.styles, function(value, name) { // Format doesn't match if (t.editor.dom.getStyle(node, name) != value) { state = false; return false; } }); return state; }; function applyListFormat() { var list, ed = t.editor, dom = ed.dom, sel = ed.selection; // Check for existing list element list = dom.getParent(sel.getNode(), 'ol,ul'); // Switch/add list type if needed if (!list || list.nodeName == (name == 'bullist' ? 'OL' : 'UL') || hasFormat(list, format)) ed.execCommand(name == 'bullist' ? 'InsertUnorderedList' : 'InsertOrderedList'); // Append styles to new list element if (format) { list = dom.getParent(sel.getNode(), 'ol,ul'); if (list) { dom.setStyles(list, format.styles); list.removeAttribute('_mce_style'); } } }; btn = cm.createSplitButton(name, { title : 'advanced.' + name + '_desc', 'class' : 'mce_' + name, onclick : function() { applyListFormat(); } }); btn.onRenderMenu.add(function(btn, menu) { menu.onShowMenu.add(function() { var dom = t.editor.dom, list = dom.getParent(t.editor.selection.getNode(), 'ol,ul'), fmtList; if (list || format) { fmtList = t[name]; // Unselect existing items each(menu.items, function(item) { var state = true; item.setSelected(0); if (list && !item.isDisabled()) { each(fmtList, function(fmt) { if (fmt.id == item.id) { if (!hasFormat(list, fmt)) { state = false; return false; } } }); if (state) item.setSelected(1); } }); // Select the current format if (!list) menu.items[format.id].setSelected(1); } }); menu.add({id : t.editor.dom.uniqueId(), title : 'advlist.types', 'class' : 'mceMenuItemTitle'}).setDisabled(1); each(t[name], function(item) { item.id = t.editor.dom.uniqueId(); menu.add({id : item.id, title : item.title, onclick : function() { format = item; applyListFormat(); }}); }); }); return btn; } }, getInfo : function() { return { longname : 'Advanced lists', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/advlist', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('advlist', tinymce.plugins.AdvListPlugin); })();
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.Layer', { init : function(ed, url) { var t = this; t.editor = ed; // Register commands ed.addCommand('mceInsertLayer', t._insertLayer, t); ed.addCommand('mceMoveForward', function() { t._move(1); }); ed.addCommand('mceMoveBackward', function() { t._move(-1); }); ed.addCommand('mceMakeAbsolute', function() { t._toggleAbsolute(); }); // Register buttons ed.addButton('moveforward', {title : 'layer.forward_desc', cmd : 'mceMoveForward'}); ed.addButton('movebackward', {title : 'layer.backward_desc', cmd : 'mceMoveBackward'}); ed.addButton('absolute', {title : 'layer.absolute_desc', cmd : 'mceMakeAbsolute'}); ed.addButton('insertlayer', {title : 'layer.insertlayer_desc', cmd : 'mceInsertLayer'}); ed.onInit.add(function() { if (tinymce.isIE) ed.getDoc().execCommand('2D-Position', false, true); }); ed.onNodeChange.add(t._nodeChange, t); ed.onVisualAid.add(t._visualAid, t); }, getInfo : function() { return { longname : 'Layer', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/layer', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, // Private methods _nodeChange : function(ed, cm, n) { var le, p; le = this._getParentLayer(n); p = ed.dom.getParent(n, 'DIV,P,IMG'); if (!p) { cm.setDisabled('absolute', 1); cm.setDisabled('moveforward', 1); cm.setDisabled('movebackward', 1); } else { cm.setDisabled('absolute', 0); cm.setDisabled('moveforward', !le); cm.setDisabled('movebackward', !le); cm.setActive('absolute', le && le.style.position.toLowerCase() == "absolute"); } }, // Private methods _visualAid : function(ed, e, s) { var dom = ed.dom; tinymce.each(dom.select('div,p', e), function(e) { if (/^(absolute|relative|static)$/i.test(e.style.position)) { if (s) dom.addClass(e, 'mceItemVisualAid'); else dom.removeClass(e, 'mceItemVisualAid'); } }); }, _move : function(d) { var ed = this.editor, i, z = [], le = this._getParentLayer(ed.selection.getNode()), ci = -1, fi = -1, nl; nl = []; tinymce.walk(ed.getBody(), function(n) { if (n.nodeType == 1 && /^(absolute|relative|static)$/i.test(n.style.position)) nl.push(n); }, 'childNodes'); // Find z-indexes for (i=0; i<nl.length; i++) { z[i] = nl[i].style.zIndex ? parseInt(nl[i].style.zIndex) : 0; if (ci < 0 && nl[i] == le) ci = i; } if (d < 0) { // Move back // Try find a lower one for (i=0; i<z.length; i++) { if (z[i] < z[ci]) { fi = i; break; } } if (fi > -1) { nl[ci].style.zIndex = z[fi]; nl[fi].style.zIndex = z[ci]; } else { if (z[ci] > 0) nl[ci].style.zIndex = z[ci] - 1; } } else { // Move forward // Try find a higher one for (i=0; i<z.length; i++) { if (z[i] > z[ci]) { fi = i; break; } } if (fi > -1) { nl[ci].style.zIndex = z[fi]; nl[fi].style.zIndex = z[ci]; } else nl[ci].style.zIndex = z[ci] + 1; } ed.execCommand('mceRepaint'); }, _getParentLayer : function(n) { return this.editor.dom.getParent(n, function(n) { return n.nodeType == 1 && /^(absolute|relative|static)$/i.test(n.style.position); }); }, _insertLayer : function() { var ed = this.editor, p = ed.dom.getPos(ed.dom.getParent(ed.selection.getNode(), '*')); ed.dom.add(ed.getBody(), 'div', { style : { position : 'absolute', left : p.x, top : (p.y > 20 ? p.y : 20), width : 100, height : 100 }, 'class' : 'mceItemVisualAid' }, ed.selection.getContent() || ed.getLang('layer.content')); }, _toggleAbsolute : function() { var ed = this.editor, le = this._getParentLayer(ed.selection.getNode()); if (!le) le = ed.dom.getParent(ed.selection.getNode(), 'DIV,P,IMG'); if (le) { if (le.style.position.toLowerCase() == "absolute") { ed.dom.setStyles(le, { position : '', left : '', top : '', width : '', height : '' }); ed.dom.removeClass(le, 'mceItemVisualAid'); } else { if (le.style.left == "") le.style.left = 20 + 'px'; if (le.style.top == "") le.style.top = 20 + 'px'; if (le.style.width == "") le.style.width = le.width ? (le.width + 'px') : '100px'; if (le.style.height == "") le.style.height = le.height ? (le.height + 'px') : '100px'; le.style.position = "absolute"; ed.addVisual(ed.getBody()); } ed.execCommand('mceRepaint'); ed.nodeChanged(); } } }); // Register plugin tinymce.PluginManager.add('layer', tinymce.plugins.Layer); })();
JavaScript
/** * This script contains embed functions for common plugins. This scripts are complety free to use for any purpose. */ function writeFlash(p) { writeEmbed( 'D27CDB6E-AE6D-11cf-96B8-444553540000', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0', 'application/x-shockwave-flash', p ); } function writeShockWave(p) { writeEmbed( '166B1BCA-3F9C-11CF-8075-444553540000', 'http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0', 'application/x-director', p ); } function writeQuickTime(p) { writeEmbed( '02BF25D5-8C17-4B23-BC80-D3488ABDDC6B', 'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0', 'video/quicktime', p ); } function writeRealMedia(p) { writeEmbed( 'CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0', 'audio/x-pn-realaudio-plugin', p ); } function writeWindowsMedia(p) { p.url = p.src; writeEmbed( '6BF52A52-394A-11D3-B153-00C04F79FAA6', 'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701', 'application/x-mplayer2', p ); } function writeEmbed(cls, cb, mt, p) { var h = '', n; h += '<object classid="clsid:' + cls + '" codebase="' + cb + '"'; h += typeof(p.id) != "undefined" ? 'id="' + p.id + '"' : ''; h += typeof(p.name) != "undefined" ? 'name="' + p.name + '"' : ''; h += typeof(p.width) != "undefined" ? 'width="' + p.width + '"' : ''; h += typeof(p.height) != "undefined" ? 'height="' + p.height + '"' : ''; h += typeof(p.align) != "undefined" ? 'align="' + p.align + '"' : ''; h += '>'; for (n in p) h += '<param name="' + n + '" value="' + p[n] + '">'; h += '<embed type="' + mt + '"'; for (n in p) h += n + '="' + p[n] + '" '; h += '></embed></object>'; document.write(h); }
JavaScript
tinyMCEPopup.requireLangPack(); var oldWidth, oldHeight, ed, url; if (url = tinyMCEPopup.getParam("media_external_list_url")) document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>'); function init() { var pl = "", f, val; var type = "flash", fe, i; ed = tinyMCEPopup.editor; tinyMCEPopup.resizeToInnerSize(); f = document.forms[0] fe = ed.selection.getNode(); if (/mceItem(Flash|ShockWave|WindowsMedia|QuickTime|RealMedia)/.test(ed.dom.getAttrib(fe, 'class'))) { pl = fe.title; switch (ed.dom.getAttrib(fe, 'class')) { case 'mceItemFlash': type = 'flash'; break; case 'mceItemFlashVideo': type = 'flv'; break; case 'mceItemShockWave': type = 'shockwave'; break; case 'mceItemWindowsMedia': type = 'wmp'; break; case 'mceItemQuickTime': type = 'qt'; break; case 'mceItemRealMedia': type = 'rmp'; break; } document.forms[0].insert.value = ed.getLang('update', 'Insert', true); } document.getElementById('filebrowsercontainer').innerHTML = getBrowserHTML('filebrowser','src','media','media'); document.getElementById('qtsrcfilebrowsercontainer').innerHTML = getBrowserHTML('qtsrcfilebrowser','qt_qtsrc','media','media'); document.getElementById('bgcolor_pickcontainer').innerHTML = getColorPickerHTML('bgcolor_pick','bgcolor'); var html = getMediaListHTML('medialist','src','media','media'); if (html == "") document.getElementById("linklistrow").style.display = 'none'; else document.getElementById("linklistcontainer").innerHTML = html; // Resize some elements if (isVisible('filebrowser')) document.getElementById('src').style.width = '230px'; // Setup form if (pl != "") { pl = tinyMCEPopup.editor.plugins.media._parse(pl); switch (type) { case "flash": setBool(pl, 'flash', 'play'); setBool(pl, 'flash', 'loop'); setBool(pl, 'flash', 'menu'); setBool(pl, 'flash', 'swliveconnect'); setStr(pl, 'flash', 'quality'); setStr(pl, 'flash', 'scale'); setStr(pl, 'flash', 'salign'); setStr(pl, 'flash', 'wmode'); setStr(pl, 'flash', 'base'); setStr(pl, 'flash', 'flashvars'); break; case "qt": setBool(pl, 'qt', 'loop'); setBool(pl, 'qt', 'autoplay'); setBool(pl, 'qt', 'cache'); setBool(pl, 'qt', 'controller'); setBool(pl, 'qt', 'correction'); setBool(pl, 'qt', 'enablejavascript'); setBool(pl, 'qt', 'kioskmode'); setBool(pl, 'qt', 'autohref'); setBool(pl, 'qt', 'playeveryframe'); setBool(pl, 'qt', 'tarsetcache'); setStr(pl, 'qt', 'scale'); setStr(pl, 'qt', 'starttime'); setStr(pl, 'qt', 'endtime'); setStr(pl, 'qt', 'tarset'); setStr(pl, 'qt', 'qtsrcchokespeed'); setStr(pl, 'qt', 'volume'); setStr(pl, 'qt', 'qtsrc'); break; case "shockwave": setBool(pl, 'shockwave', 'sound'); setBool(pl, 'shockwave', 'progress'); setBool(pl, 'shockwave', 'autostart'); setBool(pl, 'shockwave', 'swliveconnect'); setStr(pl, 'shockwave', 'swvolume'); setStr(pl, 'shockwave', 'swstretchstyle'); setStr(pl, 'shockwave', 'swstretchhalign'); setStr(pl, 'shockwave', 'swstretchvalign'); break; case "wmp": setBool(pl, 'wmp', 'autostart'); setBool(pl, 'wmp', 'enabled'); setBool(pl, 'wmp', 'enablecontextmenu'); setBool(pl, 'wmp', 'fullscreen'); setBool(pl, 'wmp', 'invokeurls'); setBool(pl, 'wmp', 'mute'); setBool(pl, 'wmp', 'stretchtofit'); setBool(pl, 'wmp', 'windowlessvideo'); setStr(pl, 'wmp', 'balance'); setStr(pl, 'wmp', 'baseurl'); setStr(pl, 'wmp', 'captioningid'); setStr(pl, 'wmp', 'currentmarker'); setStr(pl, 'wmp', 'currentposition'); setStr(pl, 'wmp', 'defaultframe'); setStr(pl, 'wmp', 'playcount'); setStr(pl, 'wmp', 'rate'); setStr(pl, 'wmp', 'uimode'); setStr(pl, 'wmp', 'volume'); break; case "rmp": setBool(pl, 'rmp', 'autostart'); setBool(pl, 'rmp', 'loop'); setBool(pl, 'rmp', 'autogotourl'); setBool(pl, 'rmp', 'center'); setBool(pl, 'rmp', 'imagestatus'); setBool(pl, 'rmp', 'maintainaspect'); setBool(pl, 'rmp', 'nojava'); setBool(pl, 'rmp', 'prefetch'); setBool(pl, 'rmp', 'shuffle'); setStr(pl, 'rmp', 'console'); setStr(pl, 'rmp', 'controls'); setStr(pl, 'rmp', 'numloop'); setStr(pl, 'rmp', 'scriptcallbacks'); break; } setStr(pl, null, 'src'); setStr(pl, null, 'id'); setStr(pl, null, 'name'); setStr(pl, null, 'vspace'); setStr(pl, null, 'hspace'); setStr(pl, null, 'bgcolor'); setStr(pl, null, 'align'); setStr(pl, null, 'width'); setStr(pl, null, 'height'); if ((val = ed.dom.getAttrib(fe, "width")) != "") pl.width = f.width.value = val; if ((val = ed.dom.getAttrib(fe, "height")) != "") pl.height = f.height.value = val; oldWidth = pl.width ? parseInt(pl.width) : 0; oldHeight = pl.height ? parseInt(pl.height) : 0; } else oldWidth = oldHeight = 0; selectByValue(f, 'media_type', type); changedType(type); updateColor('bgcolor_pick', 'bgcolor'); TinyMCE_EditableSelects.init(); generatePreview(); } function insertMedia() { var fe, f = document.forms[0], h; tinyMCEPopup.restoreSelection(); if (!AutoValidator.validate(f)) { tinyMCEPopup.alert(ed.getLang('invalid_data')); return false; } f.width.value = f.width.value == "" ? 100 : f.width.value; f.height.value = f.height.value == "" ? 100 : f.height.value; fe = ed.selection.getNode(); if (fe != null && /mceItem(Flash|ShockWave|WindowsMedia|QuickTime|RealMedia)/.test(ed.dom.getAttrib(fe, 'class'))) { switch (f.media_type.options[f.media_type.selectedIndex].value) { case "flash": fe.className = "mceItemFlash"; break; case "flv": fe.className = "mceItemFlashVideo"; break; case "shockwave": fe.className = "mceItemShockWave"; break; case "qt": fe.className = "mceItemQuickTime"; break; case "wmp": fe.className = "mceItemWindowsMedia"; break; case "rmp": fe.className = "mceItemRealMedia"; break; } if (fe.width != f.width.value || fe.height != f.height.value) ed.execCommand('mceRepaint'); fe.title = serializeParameters(); fe.width = f.width.value; fe.height = f.height.value; fe.style.width = f.width.value + (f.width.value.indexOf('%') == -1 ? 'px' : ''); fe.style.height = f.height.value + (f.height.value.indexOf('%') == -1 ? 'px' : ''); fe.align = f.align.options[f.align.selectedIndex].value; } else { h = '<img src="' + tinyMCEPopup.getWindowArg("plugin_url") + '/img/trans.gif"' ; switch (f.media_type.options[f.media_type.selectedIndex].value) { case "flash": h += ' class="mceItemFlash"'; break; case "flv": h += ' class="mceItemFlashVideo"'; break; case "shockwave": h += ' class="mceItemShockWave"'; break; case "qt": h += ' class="mceItemQuickTime"'; break; case "wmp": h += ' class="mceItemWindowsMedia"'; break; case "rmp": h += ' class="mceItemRealMedia"'; break; } h += ' title="' + serializeParameters() + '"'; h += ' width="' + f.width.value + '"'; h += ' height="' + f.height.value + '"'; h += ' align="' + f.align.options[f.align.selectedIndex].value + '"'; h += ' />'; ed.execCommand('mceInsertContent', false, h); } tinyMCEPopup.close(); } function updatePreview() { var f = document.forms[0], type; f.width.value = f.width.value || '320'; f.height.value = f.height.value || '240'; type = getType(f.src.value); selectByValue(f, 'media_type', type); changedType(type); generatePreview(); } function getMediaListHTML() { if (typeof(tinyMCEMediaList) != "undefined" && tinyMCEMediaList.length > 0) { var html = ""; html += '<select id="linklist" name="linklist" style="width: 250px" onchange="this.form.src.value=this.options[this.selectedIndex].value;updatePreview();">'; html += '<option value="">---</option>'; for (var i=0; i<tinyMCEMediaList.length; i++) html += '<option value="' + tinyMCEMediaList[i][1] + '">' + tinyMCEMediaList[i][0] + '</option>'; html += '</select>'; return html; } return ""; } function getType(v) { var fo, i, c, el, x, f = document.forms[0]; fo = ed.getParam("media_types", "flash=swf;flv=flv;shockwave=dcr;qt=mov,qt,mpg,mp3,mp4,mpeg;shockwave=dcr;wmp=avi,wmv,wm,asf,asx,wmx,wvx;rmp=rm,ra,ram").split(';'); // YouTube if (v.match(/watch\?v=(.+)(.*)/)) { f.width.value = '425'; f.height.value = '350'; f.src.value = 'http://www.youtube.com/v/' + v.match(/v=(.*)(.*)/)[0].split('=')[1]; return 'flash'; } // Google video if (v.indexOf('http://video.google.com/videoplay?docid=') == 0) { f.width.value = '425'; f.height.value = '326'; f.src.value = 'http://video.google.com/googleplayer.swf?docId=' + v.substring('http://video.google.com/videoplay?docid='.length) + '&hl=en'; return 'flash'; } for (i=0; i<fo.length; i++) { c = fo[i].split('='); el = c[1].split(','); for (x=0; x<el.length; x++) if (v.indexOf('.' + el[x]) != -1) return c[0]; } return null; } function switchType(v) { var t = getType(v), d = document, f = d.forms[0]; if (!t) return; selectByValue(d.forms[0], 'media_type', t); changedType(t); // Update qtsrc also if (t == 'qt' && f.src.value.toLowerCase().indexOf('rtsp://') != -1) { alert(ed.getLang("media_qt_stream_warn")); if (f.qt_qtsrc.value == '') f.qt_qtsrc.value = f.src.value; } } function changedType(t) { var d = document; d.getElementById('flash_options').style.display = 'none'; d.getElementById('flv_options').style.display = 'none'; d.getElementById('qt_options').style.display = 'none'; d.getElementById('shockwave_options').style.display = 'none'; d.getElementById('wmp_options').style.display = 'none'; d.getElementById('rmp_options').style.display = 'none'; if (t) d.getElementById(t + '_options').style.display = 'block'; } function serializeParameters() { var d = document, f = d.forms[0], s = ''; switch (f.media_type.options[f.media_type.selectedIndex].value) { case "flash": s += getBool('flash', 'play', true); s += getBool('flash', 'loop', true); s += getBool('flash', 'menu', true); s += getBool('flash', 'swliveconnect', false); s += getStr('flash', 'quality'); s += getStr('flash', 'scale'); s += getStr('flash', 'salign'); s += getStr('flash', 'wmode'); s += getStr('flash', 'base'); s += getStr('flash', 'flashvars'); break; case "qt": s += getBool('qt', 'loop', false); s += getBool('qt', 'autoplay', true); s += getBool('qt', 'cache', false); s += getBool('qt', 'controller', true); s += getBool('qt', 'correction', false, 'none', 'full'); s += getBool('qt', 'enablejavascript', false); s += getBool('qt', 'kioskmode', false); s += getBool('qt', 'autohref', false); s += getBool('qt', 'playeveryframe', false); s += getBool('qt', 'targetcache', false); s += getStr('qt', 'scale'); s += getStr('qt', 'starttime'); s += getStr('qt', 'endtime'); s += getStr('qt', 'target'); s += getStr('qt', 'qtsrcchokespeed'); s += getStr('qt', 'volume'); s += getStr('qt', 'qtsrc'); break; case "shockwave": s += getBool('shockwave', 'sound'); s += getBool('shockwave', 'progress'); s += getBool('shockwave', 'autostart'); s += getBool('shockwave', 'swliveconnect'); s += getStr('shockwave', 'swvolume'); s += getStr('shockwave', 'swstretchstyle'); s += getStr('shockwave', 'swstretchhalign'); s += getStr('shockwave', 'swstretchvalign'); break; case "wmp": s += getBool('wmp', 'autostart', true); s += getBool('wmp', 'enabled', false); s += getBool('wmp', 'enablecontextmenu', true); s += getBool('wmp', 'fullscreen', false); s += getBool('wmp', 'invokeurls', true); s += getBool('wmp', 'mute', false); s += getBool('wmp', 'stretchtofit', false); s += getBool('wmp', 'windowlessvideo', false); s += getStr('wmp', 'balance'); s += getStr('wmp', 'baseurl'); s += getStr('wmp', 'captioningid'); s += getStr('wmp', 'currentmarker'); s += getStr('wmp', 'currentposition'); s += getStr('wmp', 'defaultframe'); s += getStr('wmp', 'playcount'); s += getStr('wmp', 'rate'); s += getStr('wmp', 'uimode'); s += getStr('wmp', 'volume'); break; case "rmp": s += getBool('rmp', 'autostart', false); s += getBool('rmp', 'loop', false); s += getBool('rmp', 'autogotourl', true); s += getBool('rmp', 'center', false); s += getBool('rmp', 'imagestatus', true); s += getBool('rmp', 'maintainaspect', false); s += getBool('rmp', 'nojava', false); s += getBool('rmp', 'prefetch', false); s += getBool('rmp', 'shuffle', false); s += getStr('rmp', 'console'); s += getStr('rmp', 'controls'); s += getStr('rmp', 'numloop'); s += getStr('rmp', 'scriptcallbacks'); break; } s += getStr(null, 'id'); s += getStr(null, 'name'); s += getStr(null, 'src'); s += getStr(null, 'align'); s += getStr(null, 'bgcolor'); s += getInt(null, 'vspace'); s += getInt(null, 'hspace'); s += getStr(null, 'width'); s += getStr(null, 'height'); s = s.length > 0 ? s.substring(0, s.length - 1) : s; return s; } function setBool(pl, p, n) { if (typeof(pl[n]) == "undefined") return; document.forms[0].elements[p + "_" + n].checked = pl[n] != 'false'; } function setStr(pl, p, n) { var f = document.forms[0], e = f.elements[(p != null ? p + "_" : '') + n]; if (typeof(pl[n]) == "undefined") return; if (e.type == "text") e.value = pl[n]; else selectByValue(f, (p != null ? p + "_" : '') + n, pl[n]); } function getBool(p, n, d, tv, fv) { var v = document.forms[0].elements[p + "_" + n].checked; tv = typeof(tv) == 'undefined' ? 'true' : "'" + jsEncode(tv) + "'"; fv = typeof(fv) == 'undefined' ? 'false' : "'" + jsEncode(fv) + "'"; return (v == d) ? '' : n + (v ? ':' + tv + ',' : ":\'" + fv + "\',"); } function getStr(p, n, d) { var e = document.forms[0].elements[(p != null ? p + "_" : "") + n]; var v = e.type == "text" ? e.value : e.options[e.selectedIndex].value; if (n == 'src') v = tinyMCEPopup.editor.convertURL(v, 'src', null); return ((n == d || v == '') ? '' : n + ":'" + jsEncode(v) + "',"); } function getInt(p, n, d) { var e = document.forms[0].elements[(p != null ? p + "_" : "") + n]; var v = e.type == "text" ? e.value : e.options[e.selectedIndex].value; return ((n == d || v == '') ? '' : n + ":" + v.replace(/[^0-9]+/g, '') + ","); } function jsEncode(s) { s = s.replace(new RegExp('\\\\', 'g'), '\\\\'); s = s.replace(new RegExp('"', 'g'), '\\"'); s = s.replace(new RegExp("'", 'g'), "\\'"); return s; } function generatePreview(c) { var f = document.forms[0], p = document.getElementById('prev'), h = '', cls, pl, n, type, codebase, wp, hp, nw, nh; p.innerHTML = '<!-- x --->'; nw = parseInt(f.width.value); nh = parseInt(f.height.value); if (f.width.value != "" && f.height.value != "") { if (f.constrain.checked) { if (c == 'width' && oldWidth != 0) { wp = nw / oldWidth; nh = Math.round(wp * nh); f.height.value = nh; } else if (c == 'height' && oldHeight != 0) { hp = nh / oldHeight; nw = Math.round(hp * nw); f.width.value = nw; } } } if (f.width.value != "") oldWidth = nw; if (f.height.value != "") oldHeight = nh; // After constrain pl = serializeParameters(); switch (f.media_type.options[f.media_type.selectedIndex].value) { case "flash": cls = 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'; codebase = 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0'; type = 'application/x-shockwave-flash'; break; case "shockwave": cls = 'clsid:166B1BCA-3F9C-11CF-8075-444553540000'; codebase = 'http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0'; type = 'application/x-director'; break; case "qt": cls = 'clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B'; codebase = 'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0'; type = 'video/quicktime'; break; case "wmp": cls = ed.getParam('media_wmp6_compatible') ? 'clsid:05589FA1-C356-11CE-BF01-00AA0055595A' : 'clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6'; codebase = 'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701'; type = 'application/x-mplayer2'; break; case "rmp": cls = 'clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA'; codebase = 'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701'; type = 'audio/x-pn-realaudio-plugin'; break; } if (pl == '') { p.innerHTML = ''; return; } pl = tinyMCEPopup.editor.plugins.media._parse(pl); if (!pl.src) { p.innerHTML = ''; return; } pl.src = tinyMCEPopup.editor.documentBaseURI.toAbsolute(pl.src); pl.width = !pl.width ? 100 : pl.width; pl.height = !pl.height ? 100 : pl.height; pl.id = !pl.id ? 'obj' : pl.id; pl.name = !pl.name ? 'eobj' : pl.name; pl.align = !pl.align ? '' : pl.align; // Avoid annoying warning about insecure items if (!tinymce.isIE || document.location.protocol != 'https:') { h += '<object classid="' + cls + '" codebase="' + codebase + '" width="' + pl.width + '" height="' + pl.height + '" id="' + pl.id + '" name="' + pl.name + '" align="' + pl.align + '">'; for (n in pl) { h += '<param name="' + n + '" value="' + pl[n] + '">'; // Add extra url parameter if it's an absolute URL if (n == 'src' && pl[n].indexOf('://') != -1) h += '<param name="url" value="' + pl[n] + '" />'; } } h += '<embed type="' + type + '" '; for (n in pl) h += n + '="' + pl[n] + '" '; h += '></embed>'; // Avoid annoying warning about insecure items if (!tinymce.isIE || document.location.protocol != 'https:') h += '</object>'; p.innerHTML = "<!-- x --->" + h; } tinyMCEPopup.onInit.add(init);
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var each = tinymce.each; tinymce.create('tinymce.plugins.MediaPlugin', { init : function(ed, url) { var t = this; t.editor = ed; t.url = url; function isMediaElm(n) { return /^(mceItemFlash|mceItemShockWave|mceItemWindowsMedia|mceItemQuickTime|mceItemRealMedia)$/.test(n.className); }; ed.onPreInit.add(function() { // Force in _value parameter this extra parameter is required for older Opera versions ed.serializer.addRules('param[name|value|_mce_value]'); }); // Register commands ed.addCommand('mceMedia', function() { ed.windowManager.open({ file : url + '/media.htm', width : 430 + parseInt(ed.getLang('media.delta_width', 0)), height : 470 + parseInt(ed.getLang('media.delta_height', 0)), inline : 1 }, { plugin_url : url }); }); // Register buttons ed.addButton('media', {title : 'media.desc', cmd : 'mceMedia'}); ed.onNodeChange.add(function(ed, cm, n) { cm.setActive('media', n.nodeName == 'IMG' && isMediaElm(n)); }); ed.onInit.add(function() { var lo = { mceItemFlash : 'flash', mceItemShockWave : 'shockwave', mceItemWindowsMedia : 'windowsmedia', mceItemQuickTime : 'quicktime', mceItemRealMedia : 'realmedia' }; ed.selection.onSetContent.add(function() { t._spansToImgs(ed.getBody()); }); ed.selection.onBeforeSetContent.add(t._objectsToSpans, t); if (ed.settings.content_css !== false) ed.dom.loadCSS(url + "/css/content.css"); if (ed.theme && ed.theme.onResolveName) { ed.theme.onResolveName.add(function(th, o) { if (o.name == 'img') { each(lo, function(v, k) { if (ed.dom.hasClass(o.node, k)) { o.name = v; o.title = ed.dom.getAttrib(o.node, 'title'); return false; } }); } }); } if (ed && ed.plugins.contextmenu) { ed.plugins.contextmenu.onContextMenu.add(function(th, m, e) { if (e.nodeName == 'IMG' && /mceItem(Flash|ShockWave|WindowsMedia|QuickTime|RealMedia)/.test(e.className)) { m.add({title : 'media.edit', icon : 'media', cmd : 'mceMedia'}); } }); } }); ed.onBeforeSetContent.add(t._objectsToSpans, t); ed.onSetContent.add(function() { t._spansToImgs(ed.getBody()); }); ed.onPreProcess.add(function(ed, o) { var dom = ed.dom; if (o.set) { t._spansToImgs(o.node); each(dom.select('IMG', o.node), function(n) { var p; if (isMediaElm(n)) { p = t._parse(n.title); dom.setAttrib(n, 'width', dom.getAttrib(n, 'width', p.width || 100)); dom.setAttrib(n, 'height', dom.getAttrib(n, 'height', p.height || 100)); } }); } if (o.get) { each(dom.select('IMG', o.node), function(n) { var ci, cb, mt; if (ed.getParam('media_use_script')) { if (isMediaElm(n)) n.className = n.className.replace(/mceItem/g, 'mceTemp'); return; } switch (n.className) { case 'mceItemFlash': ci = 'd27cdb6e-ae6d-11cf-96b8-444553540000'; cb = 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0'; mt = 'application/x-shockwave-flash'; break; case 'mceItemShockWave': ci = '166b1bca-3f9c-11cf-8075-444553540000'; cb = 'http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab#version=8,5,1,0'; mt = 'application/x-director'; break; case 'mceItemWindowsMedia': ci = ed.getParam('media_wmp6_compatible') ? '05589fa1-c356-11ce-bf01-00aa0055595a' : '6bf52a52-394a-11d3-b153-00c04f79faa6'; cb = 'http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701'; mt = 'application/x-mplayer2'; break; case 'mceItemQuickTime': ci = '02bf25d5-8c17-4b23-bc80-d3488abddc6b'; cb = 'http://www.apple.com/qtactivex/qtplugin.cab#version=6,0,2,0'; mt = 'video/quicktime'; break; case 'mceItemRealMedia': ci = 'cfcdaa03-8be4-11cf-b84b-0020afbbccfa'; cb = 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0'; mt = 'audio/x-pn-realaudio-plugin'; break; } if (ci) { dom.replace(t._buildObj({ classid : ci, codebase : cb, type : mt }, n), n); } }); } }); ed.onPostProcess.add(function(ed, o) { o.content = o.content.replace(/_mce_value=/g, 'value='); }); function getAttr(s, n) { n = new RegExp(n + '=\"([^\"]+)\"', 'g').exec(s); return n ? ed.dom.decode(n[1]) : ''; }; ed.onPostProcess.add(function(ed, o) { if (ed.getParam('media_use_script')) { o.content = o.content.replace(/<img[^>]+>/g, function(im) { var cl = getAttr(im, 'class'); if (/^(mceTempFlash|mceTempShockWave|mceTempWindowsMedia|mceTempQuickTime|mceTempRealMedia)$/.test(cl)) { at = t._parse(getAttr(im, 'title')); at.width = getAttr(im, 'width'); at.height = getAttr(im, 'height'); im = '<script type="text/javascript">write' + cl.substring(7) + '({' + t._serialize(at) + '});</script>'; } return im; }); } }); }, getInfo : function() { return { longname : 'Media', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/media', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, // Private methods _objectsToSpans : function(ed, o) { var t = this, h = o.content; h = h.replace(/<script[^>]*>\s*write(Flash|ShockWave|WindowsMedia|QuickTime|RealMedia)\(\{([^\)]*)\}\);\s*<\/script>/gi, function(a, b, c) { var o = t._parse(c); return '<img class="mceItem' + b + '" title="' + ed.dom.encode(c) + '" src="' + t.url + '/img/trans.gif" width="' + o.width + '" height="' + o.height + '" />' }); h = h.replace(/<object([^>]*)>/gi, '<span class="mceItemObject" $1>'); h = h.replace(/<embed([^>]*)\/?>/gi, '<span class="mceItemEmbed" $1></span>'); h = h.replace(/<embed([^>]*)>/gi, '<span class="mceItemEmbed" $1>'); h = h.replace(/<\/(object)([^>]*)>/gi, '</span>'); h = h.replace(/<\/embed>/gi, ''); h = h.replace(/<param([^>]*)>/gi, function(a, b) {return '<span ' + b.replace(/value=/gi, '_mce_value=') + ' class="mceItemParam"></span>'}); h = h.replace(/\/ class=\"mceItemParam\"><\/span>/gi, 'class="mceItemParam"></span>'); o.content = h; }, _buildObj : function(o, n) { var ob, ed = this.editor, dom = ed.dom, p = this._parse(n.title), stc; stc = ed.getParam('media_strict', true) && o.type == 'application/x-shockwave-flash'; p.width = o.width = dom.getAttrib(n, 'width') || 100; p.height = o.height = dom.getAttrib(n, 'height') || 100; if (p.src) p.src = ed.convertURL(p.src, 'src', n); if (stc) { ob = dom.create('span', { id : p.id, _mce_name : 'object', type : 'application/x-shockwave-flash', data : p.src, style : dom.getAttrib(n, 'style'), width : o.width, height : o.height }); } else { ob = dom.create('span', { id : p.id, _mce_name : 'object', classid : "clsid:" + o.classid, style : dom.getAttrib(n, 'style'), codebase : o.codebase, width : o.width, height : o.height }); } each (p, function(v, k) { if (!/^(width|height|codebase|classid|id|_cx|_cy)$/.test(k)) { // Use url instead of src in IE for Windows media if (o.type == 'application/x-mplayer2' && k == 'src' && !p.url) k = 'url'; if (v) dom.add(ob, 'span', {_mce_name : 'param', name : k, '_mce_value' : v}); } }); if (!stc) dom.add(ob, 'span', tinymce.extend({_mce_name : 'embed', type : o.type, style : dom.getAttrib(n, 'style')}, p)); return ob; }, _spansToImgs : function(p) { var t = this, dom = t.editor.dom, im, ci; each(dom.select('span', p), function(n) { // Convert object into image if (dom.getAttrib(n, 'class') == 'mceItemObject') { ci = dom.getAttrib(n, "classid").toLowerCase().replace(/\s+/g, ''); switch (ci) { case 'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000': dom.replace(t._createImg('mceItemFlash', n), n); break; case 'clsid:166b1bca-3f9c-11cf-8075-444553540000': dom.replace(t._createImg('mceItemShockWave', n), n); break; case 'clsid:6bf52a52-394a-11d3-b153-00c04f79faa6': case 'clsid:22d6f312-b0f6-11d0-94ab-0080c74c7e95': case 'clsid:05589fa1-c356-11ce-bf01-00aa0055595a': dom.replace(t._createImg('mceItemWindowsMedia', n), n); break; case 'clsid:02bf25d5-8c17-4b23-bc80-d3488abddc6b': dom.replace(t._createImg('mceItemQuickTime', n), n); break; case 'clsid:cfcdaa03-8be4-11cf-b84b-0020afbbccfa': dom.replace(t._createImg('mceItemRealMedia', n), n); break; default: dom.replace(t._createImg('mceItemFlash', n), n); } return; } // Convert embed into image if (dom.getAttrib(n, 'class') == 'mceItemEmbed') { switch (dom.getAttrib(n, 'type')) { case 'application/x-shockwave-flash': dom.replace(t._createImg('mceItemFlash', n), n); break; case 'application/x-director': dom.replace(t._createImg('mceItemShockWave', n), n); break; case 'application/x-mplayer2': dom.replace(t._createImg('mceItemWindowsMedia', n), n); break; case 'video/quicktime': dom.replace(t._createImg('mceItemQuickTime', n), n); break; case 'audio/x-pn-realaudio-plugin': dom.replace(t._createImg('mceItemRealMedia', n), n); break; default: dom.replace(t._createImg('mceItemFlash', n), n); } } }); }, _createImg : function(cl, n) { var im, dom = this.editor.dom, pa = {}, ti = '', args; args = ['id', 'name', 'width', 'height', 'bgcolor', 'align', 'flashvars', 'src', 'wmode', 'allowfullscreen', 'quality', 'data']; // Create image im = dom.create('img', { src : this.url + '/img/trans.gif', width : dom.getAttrib(n, 'width') || 100, height : dom.getAttrib(n, 'height') || 100, style : dom.getAttrib(n, 'style'), 'class' : cl }); // Setup base parameters each(args, function(na) { var v = dom.getAttrib(n, na); if (v) pa[na] = v; }); // Add optional parameters each(dom.select('span', n), function(n) { if (dom.hasClass(n, 'mceItemParam')) pa[dom.getAttrib(n, 'name')] = dom.getAttrib(n, '_mce_value'); }); // Use src not movie if (pa.movie) { pa.src = pa.movie; delete pa.movie; } // No src try data if (!pa.src) { pa.src = pa.data; delete pa.data; } // Merge with embed args n = dom.select('.mceItemEmbed', n)[0]; if (n) { each(args, function(na) { var v = dom.getAttrib(n, na); if (v && !pa[na]) pa[na] = v; }); } delete pa.width; delete pa.height; im.title = this._serialize(pa); return im; }, _parse : function(s) { return tinymce.util.JSON.parse('{' + s + '}'); }, _serialize : function(o) { return tinymce.util.JSON.serialize(o).replace(/[{}]/g, ''); } }); // Register plugin tinymce.PluginManager.add('media', tinymce.plugins.MediaPlugin); })();
JavaScript
tinyMCE.addI18n('en.media_dlg',{ title:"Insert / edit embedded media", general:"General", advanced:"Advanced", file:"File/URL", list:"List", size:"Dimensions", preview:"Preview", constrain_proportions:"Constrain proportions", type:"Type", id:"Id", name:"Name", class_name:"Class", vspace:"V-Space", hspace:"H-Space", play:"Auto play", loop:"Loop", menu:"Show menu", quality:"Quality", scale:"Scale", align:"Align", salign:"SAlign", wmode:"WMode", bgcolor:"Background", base:"Base", flashvars:"Flashvars", liveconnect:"SWLiveConnect", autohref:"AutoHREF", cache:"Cache", hidden:"Hidden", controller:"Controller", kioskmode:"Kiosk mode", playeveryframe:"Play every frame", targetcache:"Target cache", correction:"No correction", enablejavascript:"Enable JavaScript", starttime:"Start time", endtime:"End time", href:"Href", qtsrcchokespeed:"Choke speed", target:"Target", volume:"Volume", autostart:"Auto start", enabled:"Enabled", fullscreen:"Fullscreen", invokeurls:"Invoke URLs", mute:"Mute", stretchtofit:"Stretch to fit", windowlessvideo:"Windowless video", balance:"Balance", baseurl:"Base URL", captioningid:"Captioning id", currentmarker:"Current marker", currentposition:"Current position", defaultframe:"Default frame", playcount:"Play count", rate:"Rate", uimode:"UI Mode", flash_options:"Flash options", qt_options:"Quicktime options", wmp_options:"Windows media player options", rmp_options:"Real media player options", shockwave_options:"Shockwave options", autogotourl:"Auto goto URL", center:"Center", imagestatus:"Image status", maintainaspect:"Maintain aspect", nojava:"No java", prefetch:"Prefetch", shuffle:"Shuffle", console:"Console", numloop:"Num loops", controls:"Controls", scriptcallbacks:"Script callbacks", swstretchstyle:"Stretch style", swstretchhalign:"Stretch H-Align", swstretchvalign:"Stretch V-Align", sound:"Sound", progress:"Progress", qtsrc:"QT Src", qt_stream_warn:"Streamed rtsp resources should be added to the QT Src field under the advanced tab.\nYou should also add a non streamed version to the Src field..", align_top:"Top", align_right:"Right", align_bottom:"Bottom", align_left:"Left", align_center:"Center", align_top_left:"Top left", align_top_right:"Top right", align_bottom_left:"Bottom left", align_bottom_right:"Bottom right", flv_options:"Flash video options", flv_scalemode:"Scale mode", flv_buffer:"Buffer", flv_startimage:"Start image", flv_starttime:"Start time", flv_defaultvolume:"Default volumne", flv_hiddengui:"Hidden GUI", flv_autostart:"Auto start", flv_loop:"Loop", flv_showscalemodes:"Show scale modes", flv_smoothvideo:"Smooth video", flv_jscallback:"JS Callback" });
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.Directionality', { init : function(ed, url) { var t = this; t.editor = ed; ed.addCommand('mceDirectionLTR', function() { var e = ed.dom.getParent(ed.selection.getNode(), ed.dom.isBlock); if (e) { if (ed.dom.getAttrib(e, "dir") != "ltr") ed.dom.setAttrib(e, "dir", "ltr"); else ed.dom.setAttrib(e, "dir", ""); } ed.nodeChanged(); }); ed.addCommand('mceDirectionRTL', function() { var e = ed.dom.getParent(ed.selection.getNode(), ed.dom.isBlock); if (e) { if (ed.dom.getAttrib(e, "dir") != "rtl") ed.dom.setAttrib(e, "dir", "rtl"); else ed.dom.setAttrib(e, "dir", ""); } ed.nodeChanged(); }); ed.addButton('ltr', {title : 'directionality.ltr_desc', cmd : 'mceDirectionLTR'}); ed.addButton('rtl', {title : 'directionality.rtl_desc', cmd : 'mceDirectionRTL'}); ed.onNodeChange.add(t._nodeChange, t); }, getInfo : function() { return { longname : 'Directionality', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/directionality', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, // Private methods _nodeChange : function(ed, cm, n) { var dom = ed.dom, dir; n = dom.getParent(n, dom.isBlock); if (!n) { cm.setDisabled('ltr', 1); cm.setDisabled('rtl', 1); return; } dir = dom.getAttrib(n, 'dir'); cm.setActive('ltr', dir == "ltr"); cm.setDisabled('ltr', 0); cm.setActive('rtl', dir == "rtl"); cm.setDisabled('rtl', 0); } }); // Register plugin tinymce.PluginManager.add('directionality', tinymce.plugins.Directionality); })();
JavaScript
tinyMCEPopup.requireLangPack(); var EmotionsDialog = { init : function(ed) { tinyMCEPopup.resizeToInnerSize(); }, insert : function(file, title) { var ed = tinyMCEPopup.editor, dom = ed.dom; tinyMCEPopup.execCommand('mceInsertContent', false, dom.createHTML('img', { src : tinyMCEPopup.getWindowArg('plugin_url') + '/img/' + file, alt : ed.getLang(title), title : ed.getLang(title), border : 0 })); tinyMCEPopup.close(); } }; tinyMCEPopup.onInit.add(EmotionsDialog.init, EmotionsDialog);
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function(tinymce) { tinymce.create('tinymce.plugins.EmotionsPlugin', { init : function(ed, url) { // Register commands ed.addCommand('mceEmotion', function() { ed.windowManager.open({ file : url + '/emotions.htm', width : 250 + parseInt(ed.getLang('emotions.delta_width', 0)), height : 160 + parseInt(ed.getLang('emotions.delta_height', 0)), inline : 1 }, { plugin_url : url }); }); // Register buttons ed.addButton('emotions', {title : 'emotions.emotions_desc', cmd : 'mceEmotion'}); }, getInfo : function() { return { longname : 'Emotions', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/emotions', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('emotions', tinymce.plugins.EmotionsPlugin); })(tinymce);
JavaScript
tinyMCE.addI18n('en.emotions_dlg',{ title:"Insert emotion", desc:"Emotions", cool:"Cool", cry:"Cry", embarassed:"Embarassed", foot_in_mouth:"Foot in mouth", frown:"Frown", innocent:"Innocent", kiss:"Kiss", laughing:"Laughing", money_mouth:"Money mouth", sealed:"Sealed", smile:"Smile", surprised:"Surprised", tongue_out:"Tongue out", undecided:"Undecided", wink:"Wink", yell:"Yell" });
JavaScript
var AdvHRDialog = { init : function(ed) { var dom = ed.dom, f = document.forms[0], n = ed.selection.getNode(), w; w = dom.getAttrib(n, 'width'); f.width.value = w ? parseInt(w) : (dom.getStyle('width') || ''); f.size.value = dom.getAttrib(n, 'size') || parseInt(dom.getStyle('height')) || ''; f.noshade.checked = !!dom.getAttrib(n, 'noshade') || !!dom.getStyle('border-width'); selectByValue(f, 'width2', w.indexOf('%') != -1 ? '%' : 'px'); }, update : function() { var ed = tinyMCEPopup.editor, h, f = document.forms[0], st = ''; h = '<hr'; if (f.size.value) { h += ' size="' + f.size.value + '"'; st += ' height:' + f.size.value + 'px;'; } if (f.width.value) { h += ' width="' + f.width.value + (f.width2.value == '%' ? '%' : '') + '"'; st += ' width:' + f.width.value + (f.width2.value == '%' ? '%' : 'px') + ';'; } if (f.noshade.checked) { h += ' noshade="noshade"'; st += ' border-width: 1px; border-style: solid; border-color: #CCCCCC; color: #ffffff;'; } if (ed.settings.inline_styles) h += ' style="' + tinymce.trim(st) + '"'; h += ' />'; ed.execCommand("mceInsertContent", false, h); tinyMCEPopup.close(); } }; tinyMCEPopup.requireLangPack(); tinyMCEPopup.onInit.add(AdvHRDialog.init, AdvHRDialog);
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.AdvancedHRPlugin', { init : function(ed, url) { // Register commands ed.addCommand('mceAdvancedHr', function() { ed.windowManager.open({ file : url + '/rule.htm', width : 250 + parseInt(ed.getLang('advhr.delta_width', 0)), height : 160 + parseInt(ed.getLang('advhr.delta_height', 0)), inline : 1 }, { plugin_url : url }); }); // Register buttons ed.addButton('advhr', { title : 'advhr.advhr_desc', cmd : 'mceAdvancedHr' }); ed.onNodeChange.add(function(ed, cm, n) { cm.setActive('advhr', n.nodeName == 'HR'); }); ed.onClick.add(function(ed, e) { e = e.target; if (e.nodeName === 'HR') ed.selection.select(e); }); }, getInfo : function() { return { longname : 'Advanced HR', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/advhr', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('advhr', tinymce.plugins.AdvancedHRPlugin); })();
JavaScript
tinyMCE.addI18n('en.advhr_dlg',{ width:"Width", size:"Height", noshade:"No shadow" });
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.PageBreakPlugin', { init : function(ed, url) { var pb = '<img src="' + url + '/img/trans.gif" class="mcePageBreak mceItemNoResize" />', cls = 'mcePageBreak', sep = ed.getParam('pagebreak_separator', '<!-- pagebreak -->'), pbRE; pbRE = new RegExp(sep.replace(/[\?\.\*\[\]\(\)\{\}\+\^\$\:]/g, function(a) {return '\\' + a;}), 'g'); // Register commands ed.addCommand('mcePageBreak', function() { ed.execCommand('mceInsertContent', 0, pb); }); // Register buttons ed.addButton('pagebreak', {title : 'pagebreak.desc', cmd : cls}); ed.onInit.add(function() { if (ed.settings.content_css !== false) ed.dom.loadCSS(url + "/css/content.css"); if (ed.theme.onResolveName) { ed.theme.onResolveName.add(function(th, o) { if (o.node.nodeName == 'IMG' && ed.dom.hasClass(o.node, cls)) o.name = 'pagebreak'; }); } }); ed.onClick.add(function(ed, e) { e = e.target; if (e.nodeName === 'IMG' && ed.dom.hasClass(e, cls)) ed.selection.select(e); }); ed.onNodeChange.add(function(ed, cm, n) { cm.setActive('pagebreak', n.nodeName === 'IMG' && ed.dom.hasClass(n, cls)); }); ed.onBeforeSetContent.add(function(ed, o) { o.content = o.content.replace(pbRE, pb); }); ed.onPostProcess.add(function(ed, o) { if (o.get) o.content = o.content.replace(/<img[^>]+>/g, function(im) { if (im.indexOf('class="mcePageBreak') !== -1) im = sep; return im; }); }); }, getInfo : function() { return { longname : 'PageBreak', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/pagebreak', version : tinymce.majorVersion + "." + tinymce.minorVersion }; } }); // Register plugin tinymce.PluginManager.add('pagebreak', tinymce.plugins.PageBreakPlugin); })();
JavaScript
tinyMCEPopup.requireLangPack(); var PasteWordDialog = { init : function() { var ed = tinyMCEPopup.editor, el = document.getElementById('iframecontainer'), ifr, doc, css, cssHTML = ''; // Create iframe el.innerHTML = '<iframe id="iframe" src="javascript:\'\';" frameBorder="0" style="border: 1px solid gray"></iframe>'; ifr = document.getElementById('iframe'); doc = ifr.contentWindow.document; // Force absolute CSS urls css = [ed.baseURI.toAbsolute("themes/" + ed.settings.theme + "/skins/" + ed.settings.skin + "/content.css")]; css = css.concat(tinymce.explode(ed.settings.content_css) || []); tinymce.each(css, function(u) { cssHTML += '<link href="' + ed.documentBaseURI.toAbsolute('' + u) + '" rel="stylesheet" type="text/css" />'; }); // Write content into iframe doc.open(); doc.write('<html><head>' + cssHTML + '</head><body class="mceContentBody" spellcheck="false"></body></html>'); doc.close(); doc.designMode = 'on'; this.resize(); window.setTimeout(function() { ifr.contentWindow.focus(); }, 10); }, insert : function() { var h = document.getElementById('iframe').contentWindow.document.body.innerHTML; tinyMCEPopup.editor.execCommand('mceInsertClipboardContent', false, {content : h, wordContent : true}); tinyMCEPopup.close(); }, resize : function() { var vp = tinyMCEPopup.dom.getViewPort(window), el; el = document.getElementById('iframe'); if (el) { el.style.width = (vp.w - 20) + 'px'; el.style.height = (vp.h - 90) + 'px'; } } }; tinyMCEPopup.onInit.add(PasteWordDialog.init, PasteWordDialog);
JavaScript
tinyMCEPopup.requireLangPack(); var PasteTextDialog = { init : function() { this.resize(); }, insert : function() { var h = tinyMCEPopup.dom.encode(document.getElementById('content').value), lines; // Convert linebreaks into paragraphs if (document.getElementById('linebreaks').checked) { lines = h.split(/\r?\n/); if (lines.length > 1) { h = ''; tinymce.each(lines, function(row) { h += '<p>' + row + '</p>'; }); } } tinyMCEPopup.editor.execCommand('mceInsertClipboardContent', false, {content : h}); tinyMCEPopup.close(); }, resize : function() { var vp = tinyMCEPopup.dom.getViewPort(window), el; el = document.getElementById('content'); el.style.width = (vp.w - 20) + 'px'; el.style.height = (vp.h - 90) + 'px'; } }; tinyMCEPopup.onInit.add(PasteTextDialog.init, PasteTextDialog);
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { var each = tinymce.each, entities = null, defs = { paste_auto_cleanup_on_paste : true, paste_block_drop : false, paste_retain_style_properties : "none", paste_strip_class_attributes : "mso", paste_remove_spans : false, paste_remove_styles : false, paste_remove_styles_if_webkit : true, paste_convert_middot_lists : true, paste_convert_headers_to_strong : false, paste_dialog_width : "450", paste_dialog_height : "400", paste_text_use_dialog : false, paste_text_sticky : false, paste_text_notifyalways : false, paste_text_linebreaktype : "p", paste_text_replacements : [ [/\u2026/g, "..."], [/[\x93\x94\u201c\u201d]/g, '"'], [/[\x60\x91\x92\u2018\u2019]/g, "'"] ] }; function getParam(ed, name) { return ed.getParam(name, defs[name]); } tinymce.create('tinymce.plugins.PastePlugin', { init : function(ed, url) { var t = this; t.editor = ed; t.url = url; // Setup plugin events t.onPreProcess = new tinymce.util.Dispatcher(t); t.onPostProcess = new tinymce.util.Dispatcher(t); // Register default handlers t.onPreProcess.add(t._preProcess); t.onPostProcess.add(t._postProcess); // Register optional preprocess handler t.onPreProcess.add(function(pl, o) { ed.execCallback('paste_preprocess', pl, o); }); // Register optional postprocess t.onPostProcess.add(function(pl, o) { ed.execCallback('paste_postprocess', pl, o); }); // Initialize plain text flag ed.pasteAsPlainText = false; // This function executes the process handlers and inserts the contents // force_rich overrides plain text mode set by user, important for pasting with execCommand function process(o, force_rich) { var dom = ed.dom; // Execute pre process handlers t.onPreProcess.dispatch(t, o); // Create DOM structure o.node = dom.create('div', 0, o.content); // Execute post process handlers t.onPostProcess.dispatch(t, o); // Serialize content o.content = ed.serializer.serialize(o.node, {getInner : 1}); // Plain text option active? if ((!force_rich) && (ed.pasteAsPlainText)) { t._insertPlainText(ed, dom, o.content); if (!getParam(ed, "paste_text_sticky")) { ed.pasteAsPlainText = false; ed.controlManager.setActive("pastetext", false); } } else if (/<(p|h[1-6]|ul|ol)/.test(o.content)) { // Handle insertion of contents containing block elements separately t._insertBlockContent(ed, dom, o.content); } else { t._insert(o.content); } } // Add command for external usage ed.addCommand('mceInsertClipboardContent', function(u, o) { process(o, true); }); if (!getParam(ed, "paste_text_use_dialog")) { ed.addCommand('mcePasteText', function(u, v) { var cookie = tinymce.util.Cookie; ed.pasteAsPlainText = !ed.pasteAsPlainText; ed.controlManager.setActive('pastetext', ed.pasteAsPlainText); if ((ed.pasteAsPlainText) && (!cookie.get("tinymcePasteText"))) { if (getParam(ed, "paste_text_sticky")) { ed.windowManager.alert(ed.translate('paste.plaintext_mode_sticky')); } else { ed.windowManager.alert(ed.translate('paste.plaintext_mode_sticky')); } if (!getParam(ed, "paste_text_notifyalways")) { cookie.set("tinymcePasteText", "1", new Date(new Date().getFullYear() + 1, 12, 31)) } } }); } ed.addButton('pastetext', {title: 'paste.paste_text_desc', cmd: 'mcePasteText'}); ed.addButton('selectall', {title: 'paste.selectall_desc', cmd: 'selectall'}); // This function grabs the contents from the clipboard by adding a // hidden div and placing the caret inside it and after the browser paste // is done it grabs that contents and processes that function grabContent(e) { var n, or, rng, sel = ed.selection, dom = ed.dom, body = ed.getBody(), posY; // Check if browser supports direct plaintext access if (ed.pasteAsPlainText && (e.clipboardData || dom.doc.dataTransfer)) { e.preventDefault(); process({content : (e.clipboardData || dom.doc.dataTransfer).getData('Text')}, true); return; } if (dom.get('_mcePaste')) return; // Create container to paste into n = dom.add(body, 'div', {id : '_mcePaste', 'class' : 'mcePaste'}, '\uFEFF<br _mce_bogus="1">'); // If contentEditable mode we need to find out the position of the closest element if (body != ed.getDoc().body) posY = dom.getPos(ed.selection.getStart(), body).y; else posY = body.scrollTop; // Styles needs to be applied after the element is added to the document since WebKit will otherwise remove all styles dom.setStyles(n, { position : 'absolute', left : -10000, top : posY, width : 1, height : 1, overflow : 'hidden' }); if (tinymce.isIE) { // Select the container rng = dom.doc.body.createTextRange(); rng.moveToElementText(n); rng.execCommand('Paste'); // Remove container dom.remove(n); // Check if the contents was changed, if it wasn't then clipboard extraction failed probably due // to IE security settings so we pass the junk though better than nothing right if (n.innerHTML === '\uFEFF') { ed.execCommand('mcePasteWord'); e.preventDefault(); return; } // Process contents process({content : n.innerHTML}); // Block the real paste event return tinymce.dom.Event.cancel(e); } else { function block(e) { e.preventDefault(); }; // Block mousedown and click to prevent selection change dom.bind(ed.getDoc(), 'mousedown', block); dom.bind(ed.getDoc(), 'keydown', block); or = ed.selection.getRng(); // Move caret into hidden div n = n.firstChild; rng = ed.getDoc().createRange(); rng.setStart(n, 0); rng.setEnd(n, 1); sel.setRng(rng); // Wait a while and grab the pasted contents window.setTimeout(function() { var h = '', nl = dom.select('div.mcePaste'); // WebKit will split the div into multiple ones so this will loop through then all and join them to get the whole HTML string each(nl, function(n) { var child = n.firstChild; // WebKit inserts a DIV container with lots of odd styles if (child && child.nodeName == 'DIV' && child.style.marginTop && child.style.backgroundColor) { dom.remove(child, 1); } // WebKit duplicates the divs so we need to remove them each(dom.select('div.mcePaste', n), function(n) { dom.remove(n, 1); }); // Remove apply style spans each(dom.select('span.Apple-style-span', n), function(n) { dom.remove(n, 1); }); // Remove bogus br elements each(dom.select('br[_mce_bogus]', n), function(n) { dom.remove(n); }); h += n.innerHTML; }); // Remove the nodes each(nl, function(n) { dom.remove(n); }); // Restore the old selection if (or) sel.setRng(or); process({content : h}); // Unblock events ones we got the contents dom.unbind(ed.getDoc(), 'mousedown', block); dom.unbind(ed.getDoc(), 'keydown', block); }, 0); } } // Check if we should use the new auto process method if (getParam(ed, "paste_auto_cleanup_on_paste")) { // Is it's Opera or older FF use key handler if (tinymce.isOpera || /Firefox\/2/.test(navigator.userAgent)) { ed.onKeyDown.add(function(ed, e) { if (((tinymce.isMac ? e.metaKey : e.ctrlKey) && e.keyCode == 86) || (e.shiftKey && e.keyCode == 45)) grabContent(e); }); } else { // Grab contents on paste event on Gecko and WebKit ed.onPaste.addToTop(function(ed, e) { return grabContent(e); }); } } // Block all drag/drop events if (getParam(ed, "paste_block_drop")) { ed.onInit.add(function() { ed.dom.bind(ed.getBody(), ['dragend', 'dragover', 'draggesture', 'dragdrop', 'drop', 'drag'], function(e) { e.preventDefault(); e.stopPropagation(); return false; }); }); } // Add legacy support t._legacySupport(); }, getInfo : function() { return { longname : 'Paste text/word', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/paste', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, _preProcess : function(pl, o) { //console.log('Before preprocess:' + o.content); var ed = this.editor, h = o.content, grep = tinymce.grep, explode = tinymce.explode, trim = tinymce.trim, len, stripClass; function process(items) { each(items, function(v) { // Remove or replace if (v.constructor == RegExp) h = h.replace(v, ''); else h = h.replace(v[0], v[1]); }); } // Detect Word content and process it more aggressive if (/class="?Mso|style="[^"]*\bmso-|w:WordDocument/i.test(h) || o.wordContent) { o.wordContent = true; // Mark the pasted contents as word specific content //console.log('Word contents detected.'); // Process away some basic content process([ /^\s*(&nbsp;)+/gi, // &nbsp; entities at the start of contents /(&nbsp;|<br[^>]*>)+\s*$/gi // &nbsp; entities at the end of contents ]); if (getParam(ed, "paste_convert_headers_to_strong")) { h = h.replace(/<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>"); } if (getParam(ed, "paste_convert_middot_lists")) { process([ [/<!--\[if !supportLists\]-->/gi, '$&__MCE_ITEM__'], // Convert supportLists to a list item marker [/(<span[^>]+(?:mso-list:|:\s*symbol)[^>]+>)/gi, '$1__MCE_ITEM__'] // Convert mso-list and symbol spans to item markers ]); } process([ // Word comments like conditional comments etc /<!--[\s\S]+?-->/gi, // Remove comments, scripts (e.g., msoShowComment), XML tag, VML content, MS Office namespaced tags, and a few other tags /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|img|meta|link|style|\w:\w+)(?=[\s\/>]))[^>]*>/gi, // Convert <s> into <strike> for line-though [/<(\/?)s>/gi, "<$1strike>"], // Replace nsbp entites to char since it's easier to handle [/&nbsp;/gi, "\u00a0"] ]); // Remove bad attributes, with or without quotes, ensuring that attribute text is really inside a tag. // If JavaScript had a RegExp look-behind, we could have integrated this with the last process() array and got rid of the loop. But alas, it does not, so we cannot. do { len = h.length; h = h.replace(/(<[a-z][^>]*\s)(?:id|name|language|type|on\w+|\w+:\w+)=(?:"[^"]*"|\w+)\s?/gi, "$1"); } while (len != h.length); // Remove all spans if no styles is to be retained if (getParam(ed, "paste_retain_style_properties").replace(/^none$/i, "").length == 0) { h = h.replace(/<\/?span[^>]*>/gi, ""); } else { // We're keeping styles, so at least clean them up. // CSS Reference: http://msdn.microsoft.com/en-us/library/aa155477.aspx process([ // Convert <span style="mso-spacerun:yes">___</span> to string of alternating breaking/non-breaking spaces of same length [/<span\s+style\s*=\s*"\s*mso-spacerun\s*:\s*yes\s*;?\s*"\s*>([\s\u00a0]*)<\/span>/gi, function(str, spaces) { return (spaces.length > 0)? spaces.replace(/./, " ").slice(Math.floor(spaces.length/2)).split("").join("\u00a0") : ""; } ], // Examine all styles: delete junk, transform some, and keep the rest [/(<[a-z][^>]*)\sstyle="([^"]*)"/gi, function(str, tag, style) { var n = [], i = 0, s = explode(trim(style).replace(/&quot;/gi, "'"), ";"); // Examine each style definition within the tag's style attribute each(s, function(v) { var name, value, parts = explode(v, ":"); function ensureUnits(v) { return v + ((v !== "0") && (/\d$/.test(v)))? "px" : ""; } if (parts.length == 2) { name = parts[0].toLowerCase(); value = parts[1].toLowerCase(); // Translate certain MS Office styles into their CSS equivalents switch (name) { case "mso-padding-alt": case "mso-padding-top-alt": case "mso-padding-right-alt": case "mso-padding-bottom-alt": case "mso-padding-left-alt": case "mso-margin-alt": case "mso-margin-top-alt": case "mso-margin-right-alt": case "mso-margin-bottom-alt": case "mso-margin-left-alt": case "mso-table-layout-alt": case "mso-height": case "mso-width": case "mso-vertical-align-alt": n[i++] = name.replace(/^mso-|-alt$/g, "") + ":" + ensureUnits(value); return; case "horiz-align": n[i++] = "text-align:" + value; return; case "vert-align": n[i++] = "vertical-align:" + value; return; case "font-color": case "mso-foreground": n[i++] = "color:" + value; return; case "mso-background": case "mso-highlight": n[i++] = "background:" + value; return; case "mso-default-height": n[i++] = "min-height:" + ensureUnits(value); return; case "mso-default-width": n[i++] = "min-width:" + ensureUnits(value); return; case "mso-padding-between-alt": n[i++] = "border-collapse:separate;border-spacing:" + ensureUnits(value); return; case "text-line-through": if ((value == "single") || (value == "double")) { n[i++] = "text-decoration:line-through"; } return; case "mso-zero-height": if (value == "yes") { n[i++] = "display:none"; } return; } // Eliminate all MS Office style definitions that have no CSS equivalent by examining the first characters in the name if (/^(mso|column|font-emph|lang|layout|line-break|list-image|nav|panose|punct|row|ruby|sep|size|src|tab-|table-border|text-(?!align|decor|indent|trans)|top-bar|version|vnd|word-break)/.test(name)) { return; } // If it reached this point, it must be a valid CSS style n[i++] = name + ":" + parts[1]; // Lower-case name, but keep value case } }); // If style attribute contained any valid styles the re-write it; otherwise delete style attribute. if (i > 0) { return tag + ' style="' + n.join(';') + '"'; } else { return tag; } } ] ]); } } // Replace headers with <strong> if (getParam(ed, "paste_convert_headers_to_strong")) { process([ [/<h[1-6][^>]*>/gi, "<p><strong>"], [/<\/h[1-6][^>]*>/gi, "</strong></p>"] ]); } // Class attribute options are: leave all as-is ("none"), remove all ("all"), or remove only those starting with mso ("mso"). // Note:- paste_strip_class_attributes: "none", verify_css_classes: true is also a good variation. stripClass = getParam(ed, "paste_strip_class_attributes"); if (stripClass !== "none") { function removeClasses(match, g1) { if (stripClass === "all") return ''; var cls = grep(explode(g1.replace(/^(["'])(.*)\1$/, "$2"), " "), function(v) { return (/^(?!mso)/i.test(v)); } ); return cls.length ? ' class="' + cls.join(" ") + '"' : ''; }; h = h.replace(/ class="([^"]+)"/gi, removeClasses); h = h.replace(/ class=(\w+)/gi, removeClasses); } // Remove spans option if (getParam(ed, "paste_remove_spans")) { h = h.replace(/<\/?span[^>]*>/gi, ""); } //console.log('After preprocess:' + h); o.content = h; }, /** * Various post process items. */ _postProcess : function(pl, o) { var t = this, ed = t.editor, dom = ed.dom, styleProps; if (o.wordContent) { // Remove named anchors or TOC links each(dom.select('a', o.node), function(a) { if (!a.href || a.href.indexOf('#_Toc') != -1) dom.remove(a, 1); }); if (getParam(ed, "paste_convert_middot_lists")) { t._convertLists(pl, o); } // Process styles styleProps = getParam(ed, "paste_retain_style_properties"); // retained properties // Process only if a string was specified and not equal to "all" or "*" if ((tinymce.is(styleProps, "string")) && (styleProps !== "all") && (styleProps !== "*")) { styleProps = tinymce.explode(styleProps.replace(/^none$/i, "")); // Retains some style properties each(dom.select('*', o.node), function(el) { var newStyle = {}, npc = 0, i, sp, sv; // Store a subset of the existing styles if (styleProps) { for (i = 0; i < styleProps.length; i++) { sp = styleProps[i]; sv = dom.getStyle(el, sp); if (sv) { newStyle[sp] = sv; npc++; } } } // Remove all of the existing styles dom.setAttrib(el, 'style', ''); if (styleProps && npc > 0) dom.setStyles(el, newStyle); // Add back the stored subset of styles else // Remove empty span tags that do not have class attributes if (el.nodeName == 'SPAN' && !el.className) dom.remove(el, true); }); } } // Remove all style information or only specifically on WebKit to avoid the style bug on that browser if (getParam(ed, "paste_remove_styles") || (getParam(ed, "paste_remove_styles_if_webkit") && tinymce.isWebKit)) { each(dom.select('*[style]', o.node), function(el) { el.removeAttribute('style'); el.removeAttribute('_mce_style'); }); } else { if (tinymce.isWebKit) { // We need to compress the styles on WebKit since if you paste <img border="0" /> it will become <img border="0" style="... lots of junk ..." /> // Removing the mce_style that contains the real value will force the Serializer engine to compress the styles each(dom.select('*', o.node), function(el) { el.removeAttribute('_mce_style'); }); } } }, /** * Converts the most common bullet and number formats in Office into a real semantic UL/LI list. */ _convertLists : function(pl, o) { var dom = pl.editor.dom, listElm, li, lastMargin = -1, margin, levels = [], lastType, html; // Convert middot lists into real semantic lists each(dom.select('p', o.node), function(p) { var sib, val = '', type, html, idx, parents; // Get text node value at beginning of paragraph for (sib = p.firstChild; sib && sib.nodeType == 3; sib = sib.nextSibling) val += sib.nodeValue; val = p.innerHTML.replace(/<\/?\w+[^>]*>/gi, '').replace(/&nbsp;/g, '\u00a0'); // Detect unordered lists look for bullets if (/^(__MCE_ITEM__)+[\u2022\u00b7\u00a7\u00d8o]\s*\u00a0*/.test(val)) type = 'ul'; // Detect ordered lists 1., a. or ixv. if (/^__MCE_ITEM__\s*\w+\.\s*\u00a0{2,}/.test(val)) type = 'ol'; // Check if node value matches the list pattern: o&nbsp;&nbsp; if (type) { margin = parseFloat(p.style.marginLeft || 0); if (margin > lastMargin) levels.push(margin); if (!listElm || type != lastType) { listElm = dom.create(type); dom.insertAfter(listElm, p); } else { // Nested list element if (margin > lastMargin) { listElm = li.appendChild(dom.create(type)); } else if (margin < lastMargin) { // Find parent level based on margin value idx = tinymce.inArray(levels, margin); parents = dom.getParents(listElm.parentNode, type); listElm = parents[parents.length - 1 - idx] || listElm; } } // Remove middot or number spans if they exists each(dom.select('span', p), function(span) { var html = span.innerHTML.replace(/<\/?\w+[^>]*>/gi, ''); // Remove span with the middot or the number if (type == 'ul' && /^[\u2022\u00b7\u00a7\u00d8o]/.test(html)) dom.remove(span); else if (/^[\s\S]*\w+\.(&nbsp;|\u00a0)*\s*/.test(html)) dom.remove(span); }); html = p.innerHTML; // Remove middot/list items if (type == 'ul') html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^[\u2022\u00b7\u00a7\u00d8o]\s*(&nbsp;|\u00a0)+\s*/, ''); else html = p.innerHTML.replace(/__MCE_ITEM__/g, '').replace(/^\s*\w+\.(&nbsp;|\u00a0)+\s*/, ''); // Create li and add paragraph data into the new li li = listElm.appendChild(dom.create('li', 0, html)); dom.remove(p); lastMargin = margin; lastType = type; } else listElm = lastMargin = 0; // End list element }); // Remove any left over makers html = o.node.innerHTML; if (html.indexOf('__MCE_ITEM__') != -1) o.node.innerHTML = html.replace(/__MCE_ITEM__/g, ''); }, /** * This method will split the current block parent and insert the contents inside the split position. * This logic can be improved so text nodes at the start/end remain in the start/end block elements */ _insertBlockContent : function(ed, dom, content) { var parentBlock, marker, sel = ed.selection, last, elm, vp, y, elmHeight, markerId = 'mce_marker'; function select(n) { var r; if (tinymce.isIE) { r = ed.getDoc().body.createTextRange(); r.moveToElementText(n); r.collapse(false); r.select(); } else { sel.select(n, 1); sel.collapse(false); } } // Insert a marker for the caret position this._insert('<span id="' + markerId + '"></span>', 1); marker = dom.get(markerId); parentBlock = dom.getParent(marker, 'p,h1,h2,h3,h4,h5,h6,ul,ol,th,td'); // If it's a parent block but not a table cell if (parentBlock && !/TD|TH/.test(parentBlock.nodeName)) { // Split parent block marker = dom.split(parentBlock, marker); // Insert nodes before the marker each(dom.create('div', 0, content).childNodes, function(n) { last = marker.parentNode.insertBefore(n.cloneNode(true), marker); }); // Move caret after marker select(last); } else { dom.setOuterHTML(marker, content); sel.select(ed.getBody(), 1); sel.collapse(0); } // Remove marker if it's left while (elm = dom.get(markerId)) dom.remove(elm); // Get element, position and height elm = sel.getStart(); vp = dom.getViewPort(ed.getWin()); y = ed.dom.getPos(elm).y; elmHeight = elm.clientHeight; // Is element within viewport if not then scroll it into view if (y < vp.y || y + elmHeight > vp.y + vp.h) ed.getDoc().body.scrollTop = y < vp.y ? y : y - vp.h + 25; }, /** * Inserts the specified contents at the caret position. */ _insert : function(h, skip_undo) { var ed = this.editor, r = ed.selection.getRng(); // First delete the contents seems to work better on WebKit when the selection spans multiple list items or multiple table cells. if (!ed.selection.isCollapsed() && r.startContainer != r.endContainer) ed.getDoc().execCommand('Delete', false, null); // It's better to use the insertHTML method on Gecko since it will combine paragraphs correctly before inserting the contents ed.execCommand(tinymce.isGecko ? 'insertHTML' : 'mceInsertContent', false, h, {skip_undo : skip_undo}); }, /** * Instead of the old plain text method which tried to re-create a paste operation, the * new approach adds a plain text mode toggle switch that changes the behavior of paste. * This function is passed the same input that the regular paste plugin produces. * It performs additional scrubbing and produces (and inserts) the plain text. * This approach leverages all of the great existing functionality in the paste * plugin, and requires minimal changes to add the new functionality. * Speednet - June 2009 */ _insertPlainText : function(ed, dom, h) { var i, len, pos, rpos, node, breakElms, before, after, w = ed.getWin(), d = ed.getDoc(), sel = ed.selection, is = tinymce.is, inArray = tinymce.inArray, linebr = getParam(ed, "paste_text_linebreaktype"), rl = getParam(ed, "paste_text_replacements"); function process(items) { each(items, function(v) { if (v.constructor == RegExp) h = h.replace(v, ""); else h = h.replace(v[0], v[1]); }); }; if ((typeof(h) === "string") && (h.length > 0)) { if (!entities) entities = ("34,quot,38,amp,39,apos,60,lt,62,gt," + ed.serializer.settings.entities).split(","); // If HTML content with line-breaking tags, then remove all cr/lf chars because only tags will break a line if (/<(?:p|br|h[1-6]|ul|ol|dl|table|t[rdh]|div|blockquote|fieldset|pre|address|center)[^>]*>/i.test(h)) { process([ /[\n\r]+/g ]); } else { // Otherwise just get rid of carriage returns (only need linefeeds) process([ /\r+/g ]); } process([ [/<\/(?:p|h[1-6]|ul|ol|dl|table|div|blockquote|fieldset|pre|address|center)>/gi, "\n\n"], // Block tags get a blank line after them [/<br[^>]*>|<\/tr>/gi, "\n"], // Single linebreak for <br /> tags and table rows [/<\/t[dh]>\s*<t[dh][^>]*>/gi, "\t"], // Table cells get tabs betweem them /<[a-z!\/?][^>]*>/gi, // Delete all remaining tags [/&nbsp;/gi, " "], // Convert non-break spaces to regular spaces (remember, *plain text*) [ // HTML entity /&(#\d+|[a-z0-9]{1,10});/gi, // Replace with actual character function(e, s) { if (s.charAt(0) === "#") { return String.fromCharCode(s.slice(1)); } else { return ((e = inArray(entities, s)) > 0)? String.fromCharCode(entities[e-1]) : " "; } } ], [/(?:(?!\n)\s)*(\n+)(?:(?!\n)\s)*/gi, "$1"], // Cool little RegExp deletes whitespace around linebreak chars. [/\n{3,}/g, "\n\n"], // Max. 2 consecutive linebreaks /^\s+|\s+$/g // Trim the front & back ]); h = dom.encode(h); // Delete any highlighted text before pasting if (!sel.isCollapsed()) { d.execCommand("Delete", false, null); } // Perform default or custom replacements if (is(rl, "array") || (is(rl, "array"))) { process(rl); } else if (is(rl, "string")) { process(new RegExp(rl, "gi")); } // Treat paragraphs as specified in the config if (linebr == "none") { process([ [/\n+/g, " "] ]); } else if (linebr == "br") { process([ [/\n/g, "<br />"] ]); } else { process([ /^\s+|\s+$/g, [/\n\n/g, "</p><p>"], [/\n/g, "<br />"] ]); } // This next piece of code handles the situation where we're pasting more than one paragraph of plain // text, and we are pasting the content into the middle of a block node in the editor. The block // node gets split at the selection point into "Para A" and "Para B" (for the purposes of explaining). // The first paragraph of the pasted text is appended to "Para A", and the last paragraph of the // pasted text is prepended to "Para B". Any other paragraphs of pasted text are placed between // "Para A" and "Para B". This code solves a host of problems with the original plain text plugin and // now handles styles correctly. (Pasting plain text into a styled paragraph is supposed to make the // plain text take the same style as the existing paragraph.) if ((pos = h.indexOf("</p><p>")) != -1) { rpos = h.lastIndexOf("</p><p>"); node = sel.getNode(); breakElms = []; // Get list of elements to break do { if (node.nodeType == 1) { // Don't break tables and break at body if (node.nodeName == "TD" || node.nodeName == "BODY") { break; } breakElms[breakElms.length] = node; } } while (node = node.parentNode); // Are we in the middle of a block node? if (breakElms.length > 0) { before = h.substring(0, pos); after = ""; for (i=0, len=breakElms.length; i<len; i++) { before += "</" + breakElms[i].nodeName.toLowerCase() + ">"; after += "<" + breakElms[breakElms.length-i-1].nodeName.toLowerCase() + ">"; } if (pos == rpos) { h = before + after + h.substring(pos+7); } else { h = before + h.substring(pos+4, rpos+4) + after + h.substring(rpos+7); } } } // Insert content at the caret, plus add a marker for repositioning the caret ed.execCommand("mceInsertRawHTML", false, h + '<span id="_plain_text_marker">&nbsp;</span>'); // Reposition the caret to the marker, which was placed immediately after the inserted content. // Needs to be done asynchronously (in window.setTimeout) or else it doesn't work in all browsers. // The second part of the code scrolls the content up if the caret is positioned off-screen. // This is only necessary for WebKit browsers, but it doesn't hurt to use for all. window.setTimeout(function() { var marker = dom.get('_plain_text_marker'), elm, vp, y, elmHeight; sel.select(marker, false); d.execCommand("Delete", false, null); marker = null; // Get element, position and height elm = sel.getStart(); vp = dom.getViewPort(w); y = dom.getPos(elm).y; elmHeight = elm.clientHeight; // Is element within viewport if not then scroll it into view if ((y < vp.y) || (y + elmHeight > vp.y + vp.h)) { d.body.scrollTop = y < vp.y ? y : y - vp.h + 25; } }, 0); } }, /** * This method will open the old style paste dialogs. Some users might want the old behavior but still use the new cleanup engine. */ _legacySupport : function() { var t = this, ed = t.editor; // Register command(s) for backwards compatibility ed.addCommand("mcePasteWord", function() { ed.windowManager.open({ file: t.url + "/pasteword.htm", width: parseInt(getParam(ed, "paste_dialog_width")), height: parseInt(getParam(ed, "paste_dialog_height")), inline: 1 }); }); if (getParam(ed, "paste_text_use_dialog")) { ed.addCommand("mcePasteText", function() { ed.windowManager.open({ file : t.url + "/pastetext.htm", width: parseInt(getParam(ed, "paste_dialog_width")), height: parseInt(getParam(ed, "paste_dialog_height")), inline : 1 }); }); } // Register button for backwards compatibility ed.addButton("pasteword", {title : "paste.paste_word_desc", cmd : "mcePasteWord"}); } }); // Register plugin tinymce.PluginManager.add("paste", tinymce.plugins.PastePlugin); })();
JavaScript
tinyMCE.addI18n('en.paste_dlg',{ text_title:"Use CTRL+V on your keyboard to paste the text into the window.", text_linebreaks:"Keep linebreaks", word_title:"Use CTRL+V on your keyboard to paste the text into the window." });
JavaScript
/** * fullpage.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ tinyMCEPopup.requireLangPack(); var doc; var defaultDocTypes = 'XHTML 1.0 Transitional=<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">,' + 'XHTML 1.0 Frameset=<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">,' + 'XHTML 1.0 Strict=<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">,' + 'XHTML 1.1=<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">,' + 'HTML 4.01 Transitional=<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">,' + 'HTML 4.01 Strict=<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">,' + 'HTML 4.01 Frameset=<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'; var defaultEncodings = 'Western european (iso-8859-1)=iso-8859-1,' + 'Central European (iso-8859-2)=iso-8859-2,' + 'Unicode (UTF-8)=utf-8,' + 'Chinese traditional (Big5)=big5,' + 'Cyrillic (iso-8859-5)=iso-8859-5,' + 'Japanese (iso-2022-jp)=iso-2022-jp,' + 'Greek (iso-8859-7)=iso-8859-7,' + 'Korean (iso-2022-kr)=iso-2022-kr,' + 'ASCII (us-ascii)=us-ascii'; var defaultMediaTypes = 'all=all,' + 'screen=screen,' + 'print=print,' + 'tty=tty,' + 'tv=tv,' + 'projection=projection,' + 'handheld=handheld,' + 'braille=braille,' + 'aural=aural'; var defaultFontNames = 'Arial=arial,helvetica,sans-serif;Courier New=courier new,courier,monospace;Georgia=georgia,times new roman,times,serif;Tahoma=tahoma,arial,helvetica,sans-serif;Times New Roman=times new roman,times,serif;Verdana=verdana,arial,helvetica,sans-serif;Impact=impact;WingDings=wingdings'; var defaultFontSizes = '10px,11px,12px,13px,14px,15px,16px'; function init() { var f = document.forms['fullpage'], el = f.elements, e, i, p, doctypes, encodings, mediaTypes, fonts, ed = tinyMCEPopup.editor, dom = tinyMCEPopup.dom, style; // Setup doctype select box doctypes = ed.getParam("fullpage_doctypes", defaultDocTypes).split(','); for (i=0; i<doctypes.length; i++) { p = doctypes[i].split('='); if (p.length > 1) addSelectValue(f, 'doctypes', p[0], p[1]); } // Setup fonts select box fonts = ed.getParam("fullpage_fonts", defaultFontNames).split(';'); for (i=0; i<fonts.length; i++) { p = fonts[i].split('='); if (p.length > 1) addSelectValue(f, 'fontface', p[0], p[1]); } // Setup fontsize select box fonts = ed.getParam("fullpage_fontsizes", defaultFontSizes).split(','); for (i=0; i<fonts.length; i++) addSelectValue(f, 'fontsize', fonts[i], fonts[i]); // Setup mediatype select boxs mediaTypes = ed.getParam("fullpage_media_types", defaultMediaTypes).split(','); for (i=0; i<mediaTypes.length; i++) { p = mediaTypes[i].split('='); if (p.length > 1) { addSelectValue(f, 'element_style_media', p[0], p[1]); addSelectValue(f, 'element_link_media', p[0], p[1]); } } // Setup encodings select box encodings = ed.getParam("fullpage_encodings", defaultEncodings).split(','); for (i=0; i<encodings.length; i++) { p = encodings[i].split('='); if (p.length > 1) { addSelectValue(f, 'docencoding', p[0], p[1]); addSelectValue(f, 'element_script_charset', p[0], p[1]); addSelectValue(f, 'element_link_charset', p[0], p[1]); } } document.getElementById('bgcolor_pickcontainer').innerHTML = getColorPickerHTML('bgcolor_pick','bgcolor'); document.getElementById('link_color_pickcontainer').innerHTML = getColorPickerHTML('link_color_pick','link_color'); //document.getElementById('hover_color_pickcontainer').innerHTML = getColorPickerHTML('hover_color_pick','hover_color'); document.getElementById('visited_color_pickcontainer').innerHTML = getColorPickerHTML('visited_color_pick','visited_color'); document.getElementById('active_color_pickcontainer').innerHTML = getColorPickerHTML('active_color_pick','active_color'); document.getElementById('textcolor_pickcontainer').innerHTML = getColorPickerHTML('textcolor_pick','textcolor'); document.getElementById('stylesheet_browsercontainer').innerHTML = getBrowserHTML('stylesheetbrowser','stylesheet','file','fullpage'); document.getElementById('link_href_pickcontainer').innerHTML = getBrowserHTML('link_href_browser','element_link_href','file','fullpage'); document.getElementById('script_src_pickcontainer').innerHTML = getBrowserHTML('script_src_browser','element_script_src','file','fullpage'); document.getElementById('bgimage_pickcontainer').innerHTML = getBrowserHTML('bgimage_browser','bgimage','image','fullpage'); // Resize some elements if (isVisible('stylesheetbrowser')) document.getElementById('stylesheet').style.width = '220px'; if (isVisible('link_href_browser')) document.getElementById('element_link_href').style.width = '230px'; if (isVisible('bgimage_browser')) document.getElementById('bgimage').style.width = '210px'; // Add iframe dom.add(document.body, 'iframe', {id : 'documentIframe', src : 'javascript:""', style : {display : 'none'}}); doc = dom.get('documentIframe').contentWindow.document; h = tinyMCEPopup.getWindowArg('head_html'); // Preprocess the HTML disable scripts and urls h = h.replace(/<script>/gi, '<script type="text/javascript">'); h = h.replace(/type=([\"\'])?/gi, 'type=$1-mce-'); h = h.replace(/(src=|href=)/g, '_mce_$1'); // Write in the content in the iframe doc.write(h + '</body></html>'); doc.close(); // Parse xml and doctype xmlVer = getReItem(/<\?\s*?xml.*?version\s*?=\s*?"(.*?)".*?\?>/gi, h, 1); xmlEnc = getReItem(/<\?\s*?xml.*?encoding\s*?=\s*?"(.*?)".*?\?>/gi, h, 1); docType = getReItem(/<\!DOCTYPE.*?>/gi, h.replace(/\n/g, ''), 0).replace(/ +/g, ' '); f.langcode.value = getReItem(/lang="(.*?)"/gi, h, 1); // Parse title if (e = doc.getElementsByTagName('title')[0]) el.metatitle.value = e.textContent || e.text; // Parse meta tinymce.each(doc.getElementsByTagName('meta'), function(n) { var na = (n.getAttribute('name', 2) || '').toLowerCase(), va = n.getAttribute('content', 2), eq = n.getAttribute('httpEquiv', 2) || ''; e = el['meta' + na]; if (na == 'robots') { selectByValue(f, 'metarobots', tinymce.trim(va), true, true); return; } switch (eq.toLowerCase()) { case "content-type": tmp = getReItem(/charset\s*=\s*(.*)\s*/gi, va, 1); // Override XML encoding if (tmp != "") xmlEnc = tmp; return; } if (e) e.value = va; }); selectByValue(f, 'doctypes', docType, true, true); selectByValue(f, 'docencoding', xmlEnc, true, true); selectByValue(f, 'langdir', doc.body.getAttribute('dir', 2) || '', true, true); if (xmlVer != '') el.xml_pi.checked = true; // Parse appearance // Parse primary stylesheet tinymce.each(doc.getElementsByTagName("link"), function(l) { var m = l.getAttribute('media', 2) || '', t = l.getAttribute('type', 2) || ''; if (t == "-mce-text/css" && (m == "" || m == "screen" || m == "all") && (l.getAttribute('rel', 2) || '') == "stylesheet") { f.stylesheet.value = l.getAttribute('_mce_href', 2) || ''; return false; } }); // Get from style elements tinymce.each(doc.getElementsByTagName("style"), function(st) { var tmp = parseStyleElement(st); for (x=0; x<tmp.length; x++) { if (tmp[x].rule.indexOf('a:visited') != -1 && tmp[x].data['color']) f.visited_color.value = tmp[x].data['color']; if (tmp[x].rule.indexOf('a:link') != -1 && tmp[x].data['color']) f.link_color.value = tmp[x].data['color']; if (tmp[x].rule.indexOf('a:active') != -1 && tmp[x].data['color']) f.active_color.value = tmp[x].data['color']; } }); f.textcolor.value = tinyMCEPopup.dom.getAttrib(doc.body, "text"); f.active_color.value = tinyMCEPopup.dom.getAttrib(doc.body, "alink"); f.link_color.value = tinyMCEPopup.dom.getAttrib(doc.body, "link"); f.visited_color.value = tinyMCEPopup.dom.getAttrib(doc.body, "vlink"); f.bgcolor.value = tinyMCEPopup.dom.getAttrib(doc.body, "bgcolor"); f.bgimage.value = tinyMCEPopup.dom.getAttrib(doc.body, "background"); // Get from style info style = tinyMCEPopup.dom.parseStyle(tinyMCEPopup.dom.getAttrib(doc.body, 'style')); if (style['font-family']) selectByValue(f, 'fontface', style['font-family'], true, true); else selectByValue(f, 'fontface', ed.getParam("fullpage_default_fontface", ""), true, true); if (style['font-size']) selectByValue(f, 'fontsize', style['font-size'], true, true); else selectByValue(f, 'fontsize', ed.getParam("fullpage_default_fontsize", ""), true, true); if (style['color']) f.textcolor.value = convertRGBToHex(style['color']); if (style['background-image']) f.bgimage.value = style['background-image'].replace(new RegExp("url\\('?([^']*)'?\\)", 'gi'), "$1"); if (style['background-color']) f.bgcolor.value = style['background-color']; if (style['margin']) { tmp = style['margin'].replace(/[^0-9 ]/g, ''); tmp = tmp.split(/ +/); f.topmargin.value = tmp.length > 0 ? tmp[0] : ''; f.rightmargin.value = tmp.length > 1 ? tmp[1] : tmp[0]; f.bottommargin.value = tmp.length > 2 ? tmp[2] : tmp[0]; f.leftmargin.value = tmp.length > 3 ? tmp[3] : tmp[0]; } if (style['margin-left']) f.leftmargin.value = style['margin-left'].replace(/[^0-9]/g, ''); if (style['margin-right']) f.rightmargin.value = style['margin-right'].replace(/[^0-9]/g, ''); if (style['margin-top']) f.topmargin.value = style['margin-top'].replace(/[^0-9]/g, ''); if (style['margin-bottom']) f.bottommargin.value = style['margin-bottom'].replace(/[^0-9]/g, ''); f.style.value = tinyMCEPopup.dom.serializeStyle(style); // Update colors updateColor('textcolor_pick', 'textcolor'); updateColor('bgcolor_pick', 'bgcolor'); updateColor('visited_color_pick', 'visited_color'); updateColor('active_color_pick', 'active_color'); updateColor('link_color_pick', 'link_color'); } function getReItem(r, s, i) { var c = r.exec(s); if (c && c.length > i) return c[i]; return ''; } function updateAction() { var f = document.forms[0], nl, i, h, v, s, head, html, l, tmp, addlink = true, ser; head = doc.getElementsByTagName('head')[0]; // Fix scripts without a type nl = doc.getElementsByTagName('script'); for (i=0; i<nl.length; i++) { if (tinyMCEPopup.dom.getAttrib(nl[i], '_mce_type') == '') nl[i].setAttribute('_mce_type', 'text/javascript'); } // Get primary stylesheet nl = doc.getElementsByTagName("link"); for (i=0; i<nl.length; i++) { l = nl[i]; tmp = tinyMCEPopup.dom.getAttrib(l, 'media'); if (tinyMCEPopup.dom.getAttrib(l, '_mce_type') == "text/css" && (tmp == "" || tmp == "screen" || tmp == "all") && tinyMCEPopup.dom.getAttrib(l, 'rel') == "stylesheet") { addlink = false; if (f.stylesheet.value == '') l.parentNode.removeChild(l); else l.setAttribute('_mce_href', f.stylesheet.value); break; } } // Add new link if (f.stylesheet.value != '') { l = doc.createElement('link'); l.setAttribute('type', 'text/css'); l.setAttribute('_mce_href', f.stylesheet.value); l.setAttribute('rel', 'stylesheet'); head.appendChild(l); } setMeta(head, 'keywords', f.metakeywords.value); setMeta(head, 'description', f.metadescription.value); setMeta(head, 'author', f.metaauthor.value); setMeta(head, 'copyright', f.metacopyright.value); setMeta(head, 'robots', getSelectValue(f, 'metarobots')); setMeta(head, 'Content-Type', getSelectValue(f, 'docencoding')); doc.body.dir = getSelectValue(f, 'langdir'); doc.body.style.cssText = f.style.value; doc.body.setAttribute('vLink', f.visited_color.value); doc.body.setAttribute('link', f.link_color.value); doc.body.setAttribute('text', f.textcolor.value); doc.body.setAttribute('aLink', f.active_color.value); doc.body.style.fontFamily = getSelectValue(f, 'fontface'); doc.body.style.fontSize = getSelectValue(f, 'fontsize'); doc.body.style.backgroundColor = f.bgcolor.value; if (f.leftmargin.value != '') doc.body.style.marginLeft = f.leftmargin.value + 'px'; if (f.rightmargin.value != '') doc.body.style.marginRight = f.rightmargin.value + 'px'; if (f.bottommargin.value != '') doc.body.style.marginBottom = f.bottommargin.value + 'px'; if (f.topmargin.value != '') doc.body.style.marginTop = f.topmargin.value + 'px'; html = doc.getElementsByTagName('html')[0]; html.setAttribute('lang', f.langcode.value); html.setAttribute('xml:lang', f.langcode.value); if (f.bgimage.value != '') doc.body.style.backgroundImage = "url('" + f.bgimage.value + "')"; else doc.body.style.backgroundImage = ''; ser = tinyMCEPopup.editor.plugins.fullpage._createSerializer(); ser.setRules('-title,meta[http-equiv|name|content],base[href|target],link[href|rel|type|title|media],style[type],script[type|language|src],html[lang|xml::lang|xmlns],body[style|dir|vlink|link|text|alink],head'); h = ser.serialize(doc.documentElement); h = h.substring(0, h.lastIndexOf('</body>')); if (h.indexOf('<title>') == -1) h = h.replace(/<head.*?>/, '$&\n' + '<title>' + tinyMCEPopup.dom.encode(f.metatitle.value) + '</title>'); else h = h.replace(/<title>(.*?)<\/title>/, '<title>' + tinyMCEPopup.dom.encode(f.metatitle.value) + '</title>'); if ((v = getSelectValue(f, 'doctypes')) != '') h = v + '\n' + h; if (f.xml_pi.checked) { s = '<?xml version="1.0"'; if ((v = getSelectValue(f, 'docencoding')) != '') s += ' encoding="' + v + '"'; s += '?>\n'; h = s + h; } h = h.replace(/type=\"\-mce\-/gi, 'type="'); tinyMCEPopup.editor.plugins.fullpage.head = h; tinyMCEPopup.editor.plugins.fullpage._setBodyAttribs(tinyMCEPopup.editor, {}); tinyMCEPopup.close(); } function changedStyleField(field) { } function setMeta(he, k, v) { var nl, i, m; nl = he.getElementsByTagName('meta'); for (i=0; i<nl.length; i++) { if (k == 'Content-Type' && tinyMCEPopup.dom.getAttrib(nl[i], 'http-equiv') == k) { if (v == '') nl[i].parentNode.removeChild(nl[i]); else nl[i].setAttribute('content', "text/html; charset=" + v); return; } if (tinyMCEPopup.dom.getAttrib(nl[i], 'name') == k) { if (v == '') nl[i].parentNode.removeChild(nl[i]); else nl[i].setAttribute('content', v); return; } } if (v == '') return; m = doc.createElement('meta'); if (k == 'Content-Type') m.httpEquiv = k; else m.setAttribute('name', k); m.setAttribute('content', v); he.appendChild(m); } function parseStyleElement(e) { var v = e.innerHTML; var p, i, r; v = v.replace(/<!--/gi, ''); v = v.replace(/-->/gi, ''); v = v.replace(/[\n\r]/gi, ''); v = v.replace(/\s+/gi, ' '); r = []; p = v.split(/{|}/); for (i=0; i<p.length; i+=2) { if (p[i] != "") r[r.length] = {rule : tinymce.trim(p[i]), data : tinyMCEPopup.dom.parseStyle(p[i+1])}; } return r; } function serializeStyleElement(d) { var i, s, st; s = '<!--\n'; for (i=0; i<d.length; i++) { s += d[i].rule + ' {\n'; st = tinyMCE.serializeStyle(d[i].data); if (st != '') st += ';'; s += st.replace(/;/g, ';\n'); s += '}\n'; if (i != d.length - 1) s += '\n'; } s += '\n-->'; return s; } tinyMCEPopup.onInit.add(init);
JavaScript
/** * editor_plugin_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function() { tinymce.create('tinymce.plugins.FullPagePlugin', { init : function(ed, url) { var t = this; t.editor = ed; // Register commands ed.addCommand('mceFullPageProperties', function() { ed.windowManager.open({ file : url + '/fullpage.htm', width : 430 + parseInt(ed.getLang('fullpage.delta_width', 0)), height : 495 + parseInt(ed.getLang('fullpage.delta_height', 0)), inline : 1 }, { plugin_url : url, head_html : t.head }); }); // Register buttons ed.addButton('fullpage', {title : 'fullpage.desc', cmd : 'mceFullPageProperties'}); ed.onBeforeSetContent.add(t._setContent, t); ed.onSetContent.add(t._setBodyAttribs, t); ed.onGetContent.add(t._getContent, t); }, getInfo : function() { return { longname : 'Fullpage', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/fullpage', version : tinymce.majorVersion + "." + tinymce.minorVersion }; }, // Private plugin internal methods _setBodyAttribs : function(ed, o) { var bdattr, i, len, kv, k, v, t, attr = this.head.match(/body(.*?)>/i); if (attr && attr[1]) { bdattr = attr[1].match(/\s*(\w+\s*=\s*".*?"|\w+\s*=\s*'.*?'|\w+\s*=\s*\w+|\w+)\s*/g); if (bdattr) { for(i = 0, len = bdattr.length; i < len; i++) { kv = bdattr[i].split('='); k = kv[0].replace(/\s/,''); v = kv[1]; if (v) { v = v.replace(/^\s+/,'').replace(/\s+$/,''); t = v.match(/^["'](.*)["']$/); if (t) v = t[1]; } else v = k; ed.dom.setAttrib(ed.getBody(), 'style', v); } } } }, _createSerializer : function() { return new tinymce.dom.Serializer({ dom : this.editor.dom, apply_source_formatting : true }); }, _setContent : function(ed, o) { var t = this, sp, ep, c = o.content, v, st = ''; // Ignore raw updated if we already have a head, this will fix issues with undo/redo keeping the head/foot separate if (o.format == 'raw' && t.head) return; if (o.source_view && ed.getParam('fullpage_hide_in_source_view')) return; // Parse out head, body and footer c = c.replace(/<(\/?)BODY/gi, '<$1body'); sp = c.indexOf('<body'); if (sp != -1) { sp = c.indexOf('>', sp); t.head = c.substring(0, sp + 1); ep = c.indexOf('</body', sp); if (ep == -1) ep = c.indexOf('</body', ep); o.content = c.substring(sp + 1, ep); t.foot = c.substring(ep); function low(s) { return s.replace(/<\/?[A-Z]+/g, function(a) { return a.toLowerCase(); }) }; t.head = low(t.head); t.foot = low(t.foot); } else { t.head = ''; if (ed.getParam('fullpage_default_xml_pi')) t.head += '<?xml version="1.0" encoding="' + ed.getParam('fullpage_default_encoding', 'ISO-8859-1') + '" ?>\n'; t.head += ed.getParam('fullpage_default_doctype', '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'); t.head += '\n<html>\n<head>\n<title>' + ed.getParam('fullpage_default_title', 'Untitled document') + '</title>\n'; if (v = ed.getParam('fullpage_default_encoding')) t.head += '<meta http-equiv="Content-Type" content="' + v + '" />\n'; if (v = ed.getParam('fullpage_default_font_family')) st += 'font-family: ' + v + ';'; if (v = ed.getParam('fullpage_default_font_size')) st += 'font-size: ' + v + ';'; if (v = ed.getParam('fullpage_default_text_color')) st += 'color: ' + v + ';'; t.head += '</head>\n<body' + (st ? ' style="' + st + '"' : '') + '>\n'; t.foot = '\n</body>\n</html>'; } }, _getContent : function(ed, o) { var t = this; if (!o.source_view || !ed.getParam('fullpage_hide_in_source_view')) o.content = tinymce.trim(t.head) + '\n' + tinymce.trim(o.content) + '\n' + tinymce.trim(t.foot); } }); // Register plugin tinymce.PluginManager.add('fullpage', tinymce.plugins.FullPagePlugin); })();
JavaScript
tinyMCE.addI18n('en.fullpage_dlg',{ title:"Document properties", meta_tab:"General", appearance_tab:"Appearance", advanced_tab:"Advanced", meta_props:"Meta information", langprops:"Language and encoding", meta_title:"Title", meta_keywords:"Keywords", meta_description:"Description", meta_robots:"Robots", doctypes:"Doctype", langcode:"Language code", langdir:"Language direction", ltr:"Left to right", rtl:"Right to left", xml_pi:"XML declaration", encoding:"Character encoding", appearance_bgprops:"Background properties", appearance_marginprops:"Body margins", appearance_linkprops:"Link colors", appearance_textprops:"Text properties", bgcolor:"Background color", bgimage:"Background image", left_margin:"Left margin", right_margin:"Right margin", top_margin:"Top margin", bottom_margin:"Bottom margin", text_color:"Text color", font_size:"Font size", font_face:"Font face", link_color:"Link color", hover_color:"Hover color", visited_color:"Visited color", active_color:"Active color", textcolor:"Color", fontsize:"Font size", fontface:"Font family", meta_index_follow:"Index and follow the links", meta_index_nofollow:"Index and don't follow the links", meta_noindex_follow:"Do not index but follow the links", meta_noindex_nofollow:"Do not index and don\'t follow the links", appearance_style:"Stylesheet and style properties", stylesheet:"Stylesheet", style:"Style", author:"Author", copyright:"Copyright", add:"Add new element", remove:"Remove selected element", moveup:"Move selected element up", movedown:"Move selected element down", head_elements:"Head elements", info:"Information", add_title:"Title element", add_meta:"Meta element", add_script:"Script element", add_style:"Style element", add_link:"Link element", add_base:"Base element", add_comment:"Comment node", title_element:"Title element", script_element:"Script element", style_element:"Style element", base_element:"Base element", link_element:"Link element", meta_element:"Meta element", comment_element:"Comment", src:"Src", language:"Language", href:"Href", target:"Target", type:"Type", charset:"Charset", defer:"Defer", media:"Media", properties:"Properties", name:"Name", value:"Value", content:"Content", rel:"Rel", rev:"Rev", hreflang:"Href lang", general_props:"General", advanced_props:"Advanced" });
JavaScript