code
stringlengths
1
2.08M
language
stringclasses
1 value
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
// js here
JavaScript
/* __ .__ |__|____ __________ _|__| ______ | \__ \\_ __ \ \/ / |/ ___/ | |/ __ \| | \/\ /| |\___ \ /\__| (____ /__| \_/ |__/____ > \______| \/ \/ Copyright 2013 - SmartAdmin Template * This script is part of an item on wrapbootstrap.com * https://wrapbootstrap.com/user/myorange * * Date : Jan 2014 * Updated : 12/12/2013 * Dependency: jQuery UI core, json2(ie7) * * ************************************************************* * * * Jarvis Widgets (AKA Power Widgets), is originally created by * Mark (www.creativemilk.net) and Sunny (bootstraphunter.com). * This script may NOT be RESOLD or REDISTRUBUTED under any * circumstances, and is only to be used with this purchased * copy of SmartAdmin Template. * * ************************************************************* */ ; (function ($, window, document, undefined) { //"use strict"; // jshint ;_; var pluginName = 'jarvisWidgets'; function Plugin(element, options) { /** * Variables. **/ this.obj = $(element); this.o = $.extend({}, $.fn[pluginName].defaults, options); this.objId = this.obj.attr('id'); this.pwCtrls = '.jarviswidget-ctrls' this.widget = this.obj.find(this.o.widgets); this.toggleClass = this.o.toggleClass.split('|'); this.editClass = this.o.editClass.split('|'); this.fullscreenClass = this.o.fullscreenClass.split('|'); this.customClass = this.o.customClass.split('|'); this.init(); }; Plugin.prototype = { /** * Important settings like storage and touch support. * * @param: **/ _settings: function () { var self = this; //*****************************************************************// //////////////////////// LOCALSTORAGE CHECK ///////////////////////// //*****************************************************************// storage = !! function () { var result, uid = +new Date; try { localStorage.setItem(uid, uid); result = localStorage.getItem(uid) == uid; localStorage.removeItem(uid); return result; } catch (e) {} }() && localStorage; //*****************************************************************// /////////////////////////// SET/GET KEYS //////////////////////////// //*****************************************************************// // TODO : Push state does not work on IE9, try to find a way to detect IE and use a seperate filter if (storage && self.o.localStorage) { if (self.o.ajaxnav === true) { widget_url = location.hash.replace(/^#/, '') keySettings = 'Plugin_settings_' + widget_url + '_' + self.objId; getKeySettings = localStorage.getItem(keySettings); keyPosition = 'Plugin_position_' + widget_url + '_' + self.objId; getKeyPosition = localStorage.getItem(keyPosition); //console.log("from jarvis widget " + widget_url); //console.log(self.o.ajaxnav + " if") } else { keySettings = 'jarvisWidgets_settings_' + location.pathname + '_' + self.objId; getKeySettings = localStorage.getItem(keySettings); keyPosition = 'jarvisWidgets_position_' + location.pathname + '_' + self.objId; getKeyPosition = localStorage.getItem(keyPosition); //console.log(self.o.ajaxnav + " else") } // end else } // end if //*****************************************************************// ////////////////////////// TOUCH SUPPORT //////////////////////////// //*****************************************************************// /** * Check for touch support and set right click events. **/ if (('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) { clickEvent = 'touchstart'; //click tap } else { clickEvent = 'click'; } }, /** * Function for the indicator image. * * @param: **/ _runLoaderWidget: function (elm) { var self = this; if (self.o.indicator === true) { elm.parents(self.o.widgets) .find('.jarviswidget-loader') .stop(true, true) .fadeIn(100) .delay(self.o.indicatorTime) .fadeOut(100); } }, /** * Create a fixed timestamp. * * @param: t | date | Current date. **/ _getPastTimestamp: function (t) { var self = this; var da = new Date(t); /** * Get and set the date and time. **/ tsMonth = da.getMonth() + 1; // index based tsDay = da.getDate(); tsYear = da.getFullYear(); tsHours = da.getHours(); tsMinutes = da.getMinutes(); tsSeconds = da.getUTCSeconds(); /** * Checking for one digit values, if so add an zero. **/ if (tsMonth < 10) { var tsMonth = '0' + tsMonth } if (tsDay < 10) { var tsDay = '0' + tsDay } if (tsHours < 10) { var tsHours = '0' + tsHours } if (tsMinutes < 10) { var tsMinutes = '0' + tsMinutes } if (tsSeconds < 10) { var tsSeconds = '0' + tsSeconds } /** * The output, how you want it. **/ var format = self.o.timestampFormat.replace(/%d%/g, tsDay) .replace(/%m%/g, tsMonth) .replace(/%y%/g, tsYear) .replace(/%h%/g, tsHours) .replace(/%i%/g, tsMinutes) .replace(/%s%/g, tsSeconds); return format; }, /** * AJAX load File, which get and shows the . * * @param: awidget | object | The widget. * @param: file | file | The file thats beeing loaded. * @param: loader | object | The widget. **/ _loadAjaxFile: function (awidget, file, loader) { var self = this awidget.find('.widget-body') .load(file, function (response, status, xhr) { var $this = $(this); /** * If action runs into an error display an error msg. **/ if (status == "error") { $this.html('<h4 class="alert alert-danger">' + self.o.labelError + '<b> ' + xhr.status + " " + xhr.statusText + '</b></h4>'); } /** * Run if there are no errors. **/ if (status == "success") { /** * Show a timestamp. **/ var aPalceholder = awidget.find(self.o.timestampPlaceholder); if (aPalceholder.length) { aPalceholder.html(self._getPastTimestamp(new Date())); } /** * Run the callback function. **/ if (typeof self.o.afterLoad == 'function') { self.o.afterLoad.call(this, awidget); } } }); /** * Run function for the indicator image. **/ self._runLoaderWidget(loader); }, /** * Save all settings to the localStorage. * * @param: **/ _saveSettingsWidget: function () { var self = this; self._settings(); if (storage && self.o.localStorage) { var storeSettings = []; self.obj.find(self.o.widgets) .each(function () { var storeSettingsStr = {}; storeSettingsStr['id'] = $(this) .attr('id'); storeSettingsStr['style'] = $(this) .attr('data-widget-attstyle'); storeSettingsStr['title'] = $(this) .children('header') .children('h2') .text(); storeSettingsStr['hidden'] = ($(this) .is(':hidden') ? 1 : 0); storeSettingsStr['collapsed'] = ($(this) .hasClass('jarviswidget-collapsed') ? 1 : 0); storeSettings.push(storeSettingsStr); }); var storeSettingsObj = JSON.stringify({ 'widget': storeSettings }); /* Place it in the storage(only if needed) */ if (getKeySettings != storeSettingsObj) { localStorage.setItem(keySettings, storeSettingsObj); } } /** * Run the callback function. **/ if (typeof self.o.onSave == 'function') { self.o.onSave.call(this, null, storeSettingsObj); } }, /** * Save positions to the localStorage. * * @param: **/ _savePositionWidget: function () { var self = this; self._settings(); if (storage && self.o.localStorage) { var mainArr = []; self.obj.find(self.o.grid + '.sortable-grid') .each(function () { var subArr = []; $(this) .children(self.o.widgets) .each(function () { var subObj = {}; subObj['id'] = $(this) .attr('id'); subArr.push(subObj); }); var out = { 'section': subArr } mainArr.push(out); }); var storePositionObj = JSON.stringify({ 'grid': mainArr }); /* Place it in the storage(only if needed) */ if (getKeyPosition != storePositionObj) { localStorage.setItem(keyPosition, storePositionObj, null); } } /** * Run the callback function. **/ if (typeof self.o.onSave == 'function') { self.o.onSave.call(this, storePositionObj); } }, /** * Code that we run at the start. * * @param: **/ init: function () { var self = this; self._settings(); /** * Force users to use an id(it's needed for the local storage). **/ if (!$('#' + self.objId) .length) { alert('It looks like your using a class instead of an ID, dont do that!') } /** * Add RTL support. **/ if (self.o.rtl === true) { $('body') .addClass('rtl'); } /** * This will add an extra class that we use to store the * widgets in the right order.(savety) **/ $(self.o.grid) .each(function () { if ($(this) .find(self.o.widgets) .length) { $(this) .addClass('sortable-grid'); } }); //*****************************************************************// //////////////////////// SET POSITION WIDGET //////////////////////// //*****************************************************************// /** * Run if data is present. **/ if (storage && self.o.localStorage && getKeyPosition) { var jsonPosition = JSON.parse(getKeyPosition); /** * Loop the data, and put every widget on the right place. **/ for (var key in jsonPosition.grid) { var changeOrder = self.obj.find(self.o.grid + '.sortable-grid') .eq(key); for (var key2 in jsonPosition.grid[key].section) { changeOrder.append($('#' + jsonPosition.grid[key].section[key2].id)); } } } //*****************************************************************// /////////////////////// SET SETTINGS WIDGET ///////////////////////// //*****************************************************************// /** * Run if data is present. **/ if (storage && self.o.localStorage && getKeySettings) { var jsonSettings = JSON.parse(getKeySettings); /** * Loop the data and hide/show the widgets and set the inputs in * panel to checked(if hidden) and add an indicator class to the div. * Loop all labels and update the widget titles. **/ for (var key in jsonSettings.widget) { var widgetId = $('#' + jsonSettings.widget[key].id); /** * Set a style(if present). **/ if (jsonSettings.widget[key].style) { //console.log("test"); widgetId.removeClassPrefix('jarviswidget-color-') .addClass(jsonSettings.widget[key].style) .attr('data-widget-attstyle', '' + jsonSettings.widget[key].style + ''); } /** * Hide/show widget. **/ if (jsonSettings.widget[key].hidden == 1) { widgetId.hide(1); } else { widgetId.show(1) .removeAttr('data-widget-hidden'); } /** * Toggle content widget. **/ if (jsonSettings.widget[key].collapsed == 1) { widgetId.addClass('jarviswidget-collapsed') .children('div') .hide(1); } /** * Update title widget (if needed). **/ if (widgetId.children('header') .children('h2') .text() != jsonSettings.widget[key].title) { widgetId.children('header') .children('h2') .text(jsonSettings.widget[key].title); } } } //*****************************************************************// ////////////////////////// LOOP AL WIDGETS ////////////////////////// //*****************************************************************// /** * This will add/edit/remove the settings to all widgets **/ self.widget.each(function () { var tWidget = $(this); var thisHeader = $(this) .children('header'); /** * Dont double wrap(check). **/ if (!thisHeader.parent() .attr('role')) { /** * Hide the widget if the dataset 'widget-hidden' is set to true. **/ if (tWidget.data('widget-hidden') === true) { tWidget.hide(); } /** * Hide the content of the widget if the dataset * 'widget-collapsed' is set to true. **/ if (tWidget.data('widget-collapsed') === true) { tWidget.addClass('jarviswidget-collapsed') .children('div') .hide(); } /** * Check for the dataset 'widget-icon' if so get the icon * and attach it to the widget header. * NOTE: MOVED THIS TO PHYSICAL for more control **/ //if(tWidget.data('widget-icon')){ // thisHeader.prepend('<i class="jarviswidget-icon '+tWidget.data('widget-icon')+'"></i>'); //} /** * Add a delete button to the widget header (if set to true). **/ if (self.o.customButton === true && tWidget.data('widget-custombutton') === undefined && self.customClass[0].length != 0) { var customBtn = '<a href="javascript:void(0);" class="button-icon jarviswidget-custom-btn"><i class="' + self.customClass[0] + '"></i></a>'; } else { customBtn = ''; } /** * Add a delete button to the widget header (if set to true). **/ if (self.o.deleteButton === true && tWidget.data('widget-deletebutton') === undefined) { var deleteBtn = '<a href="javascript:void(0);" class="button-icon jarviswidget-delete-btn" rel="tooltip" title="Delete" data-placement="bottom"><i class="' + self.o.deleteClass + '"></i></a>'; } else { deleteBtn = ''; } /** * Add a delete button to the widget header (if set to true). **/ if (self.o.editButton === true && tWidget.data('widget-editbutton') === undefined) { var editBtn = '<a href="javascript:void(0);" class="button-icon jarviswidget-edit-btn" rel="tooltip" title="Edit Title" data-placement="bottom"><i class="' + self.editClass[0] + '"></i></a>'; } else { editBtn = ''; } /** * Add a delete button to the widget header (if set to true). **/ if (self.o.fullscreenButton === true && tWidget.data('widget-fullscreenbutton') === undefined) { var fullscreenBtn = '<a href="javascript:void(0);" class="button-icon jarviswidget-fullscreen-btn" rel="tooltip" title="Fullscreen" data-placement="bottom"><i class="' + self.fullscreenClass[0] + '"></i></a>'; } else { fullscreenBtn = ''; } /** * Add a delete button to the widget header (if set to true). **/ if (self.o.colorButton === true && tWidget.data('widget-colorbutton') === undefined) { var widgetcolorBtn = '<a data-toggle="dropdown" class="dropdown-toggle color-box selector" href="javascript:void(0);"></a><ul class="dropdown-menu arrow-box-up-right color-select pull-right"><li><span class="bg-color-green" data-widget-setstyle="jarviswidget-color-green" rel="tooltip" data-placement="left" data-original-title="Green Grass"></span></li><li><span class="bg-color-greenDark" data-widget-setstyle="jarviswidget-color-greenDark" rel="tooltip" data-placement="top" data-original-title="Dark Green"></span></li><li><span class="bg-color-greenLight" data-widget-setstyle="jarviswidget-color-greenLight" rel="tooltip" data-placement="top" data-original-title="Light Green"></span></li><li><span class="bg-color-purple" data-widget-setstyle="jarviswidget-color-purple" rel="tooltip" data-placement="top" data-original-title="Purple"></span></li><li><span class="bg-color-magenta" data-widget-setstyle="jarviswidget-color-magenta" rel="tooltip" data-placement="top" data-original-title="Magenta"></span></li><li><span class="bg-color-pink" data-widget-setstyle="jarviswidget-color-pink" rel="tooltip" data-placement="right" data-original-title="Pink"></span></li><li><span class="bg-color-pinkDark" data-widget-setstyle="jarviswidget-color-pinkDark" rel="tooltip" data-placement="left" data-original-title="Fade Pink"></span></li><li><span class="bg-color-blueLight" data-widget-setstyle="jarviswidget-color-blueLight" rel="tooltip" data-placement="top" data-original-title="Light Blue"></span></li><li><span class="bg-color-teal" data-widget-setstyle="jarviswidget-color-teal" rel="tooltip" data-placement="top" data-original-title="Teal"></span></li><li><span class="bg-color-blue" data-widget-setstyle="jarviswidget-color-blue" rel="tooltip" data-placement="top" data-original-title="Ocean Blue"></span></li><li><span class="bg-color-blueDark" data-widget-setstyle="jarviswidget-color-blueDark" rel="tooltip" data-placement="top" data-original-title="Night Sky"></span></li><li><span class="bg-color-darken" data-widget-setstyle="jarviswidget-color-darken" rel="tooltip" data-placement="right" data-original-title="Night"></span></li><li><span class="bg-color-yellow" data-widget-setstyle="jarviswidget-color-yellow" rel="tooltip" data-placement="left" data-original-title="Day Light"></span></li><li><span class="bg-color-orange" data-widget-setstyle="jarviswidget-color-orange" rel="tooltip" data-placement="bottom" data-original-title="Orange"></span></li><li><span class="bg-color-orangeDark" data-widget-setstyle="jarviswidget-color-orangeDark" rel="tooltip" data-placement="bottom" data-original-title="Dark Orange"></span></li><li><span class="bg-color-red" data-widget-setstyle="jarviswidget-color-red" rel="tooltip" data-placement="bottom" data-original-title="Red Rose"></span></li><li><span class="bg-color-redLight" data-widget-setstyle="jarviswidget-color-redLight" rel="tooltip" data-placement="bottom" data-original-title="Light Red"></span></li><li><span class="bg-color-white" data-widget-setstyle="jarviswidget-color-white" rel="tooltip" data-placement="right" data-original-title="Purity"></span></li><li><a href="javascript:void(0);" class="jarviswidget-remove-colors" data-widget-setstyle="" rel="tooltip" data-placement="bottom" data-original-title="Reset widget color to default">Remove</a></li></ul>'; thisHeader.prepend('<div class="widget-toolbar">' + widgetcolorBtn + '</div>'); } else { widgetcolorBtn = ''; } /** * Add a toggle button to the widget header (if set to true). **/ if (self.o.toggleButton === true && tWidget.data('widget-togglebutton') === undefined) { if (tWidget.data('widget-collapsed') === true || tWidget.hasClass( 'jarviswidget-collapsed')) { var toggleSettings = self.toggleClass[1]; } else { toggleSettings = self.toggleClass[0]; } var toggleBtn = '<a href="#" class="button-icon jarviswidget-toggle-btn" rel="tooltip" title="Collapse" data-placement="bottom"><i class="' + toggleSettings + '"></i></a>'; } else { toggleBtn = ''; } /** * Add a refresh button to the widget header (if set to true). **/ if (self.o.refreshButton === true && tWidget.data('widget-refreshbutton') != false && tWidget.data('widget-load')) { var refreshBtn = '<a href="#" class="button-icon jarviswidget-refresh-btn" data-loading-text="&nbsp;&nbsp;Loading...&nbsp;" rel="tooltip" title="Refresh" data-placement="bottom"><i class="' + self.o.refreshButtonClass + '"></i></a>'; } else { refreshBtn = ''; } /** * Set the buttons order. **/ var formatButtons = self.o.buttonOrder.replace(/%refresh%/g, refreshBtn) .replace(/%delete%/g, deleteBtn) .replace(/%custom%/g, customBtn) .replace(/%fullscreen%/g, fullscreenBtn) .replace(/%edit%/g, editBtn) .replace(/%toggle%/g, toggleBtn); /** * Add a button wrapper to the header. **/ if (refreshBtn != '' || deleteBtn != '' || customBtn != '' || fullscreenBtn != '' || editBtn != '' || toggleBtn != '') { thisHeader.prepend('<div class="jarviswidget-ctrls">' + formatButtons + '</div>'); } /** * Adding a helper class to all sortable widgets, this will be * used to find the widgets that are sortable, it will skip the widgets * that have the dataset 'widget-sortable="false"' set to false. **/ if (self.o.sortable === true && tWidget.data('widget-sortable') === undefined) { tWidget.addClass('jarviswidget-sortable'); } /** * If the edit box is present copy the title to the input. **/ if (tWidget.find(self.o.editPlaceholder) .length) { tWidget.find(self.o.editPlaceholder) .find('input') .val($.trim(thisHeader.children('h2') .text())); } /** * Prepend the image to the widget header. **/ thisHeader.append( '<span class="jarviswidget-loader"><i class="fa fa-refresh fa-spin"></i></span>' ); /** * Adding roles to some parts. **/ tWidget.attr('role', 'widget') .children('div') .attr('role', 'content') .prev('header') .attr('role', 'heading') .children('div') .attr('role', 'menu'); } }); /** * Hide all buttons if option is set to true. **/ if (self.o.buttonsHidden === true) { $(self.o.pwCtrls) .hide(); } /* activate all tooltips */ $(".jarviswidget header [rel=tooltip]") .tooltip(); //******************************************************************// //////////////////////////////// AJAX //////////////////////////////// //******************************************************************// /** * Loop all ajax widgets. **/ self.obj.find('[data-widget-load]') .each(function () { /** * Variables. **/ var thisItem = $(this), thisItemHeader = thisItem.children(), pathToFile = thisItem.data('widget-load'), reloadTime = thisItem.data('widget-refresh') * 1000, ajaxLoader = thisItem.children(); if (!thisItem.find('.jarviswidget-ajax-placeholder') .length) { /** * Append a AJAX placeholder. **/ thisItem.children('widget-body') .append('<div class="jarviswidget-ajax-placeholder">' + self.o.loadingLabel + '</div>'); /** * If widget has a reload time refresh the widget, if the value * has been set to 0 dont reload. **/ if (thisItem.data('widget-refresh') > 0) { /** * Load file on start. **/ self._loadAjaxFile(thisItem, pathToFile, thisItemHeader); /** * Set an interval to reload the content every XXX seconds. **/ setInterval(function () { self._loadAjaxFile(thisItem, pathToFile, thisItemHeader); }, reloadTime); } else { /** * Load the content just once. **/ self._loadAjaxFile(thisItem, pathToFile, thisItemHeader); } } }); //******************************************************************// ////////////////////////////// SORTABLE ////////////////////////////// //******************************************************************// /** * jQuery UI soratble, this allows users to sort the widgets. * Notice that this part needs the jquery-ui core to work. **/ if (self.o.sortable === true && jQuery.ui) { var sortItem = self.obj.find('.sortable-grid') .not('[data-widget-excludegrid]'); sortItem.sortable({ items: sortItem.find('.jarviswidget-sortable'), connectWith: sortItem, placeholder: self.o.placeholderClass, cursor: 'move', revert: true, opacity: self.o.opacity, delay: 200, cancel: '.button-icon, #jarviswidget-fullscreen-mode > div', zIndex: 10000, handle: self.o.dragHandle, forcePlaceholderSize: true, forceHelperSize: true, update: function (event, ui) { /* run pre-loader in the widget */ self._runLoaderWidget(ui.item.children()); /* store the positions of the plugins */ self._savePositionWidget(); /** * Run the callback function. **/ if (typeof self.o.onChange == 'function') { self.o.onChange.call(this, ui.item); } } }); } //*****************************************************************// ////////////////////////// BUTTONS VISIBLE ////////////////////////// //*****************************************************************// /** * Show and hide the widget control buttons, the buttons will be * visible if the users hover over the widgets header. At default the * buttons are always visible. **/ if (self.o.buttonsHidden === true) { /** * Show and hide the buttons. **/ self.widget.children('header') .hover(function () { $(this) .children(self.o.pwCtrls) .stop(true, true) .fadeTo(100, 1.0); }, function () { $(this) .children(self.o.pwCtrls) .stop(true, true) .fadeTo(100, 0.0); }); } //*****************************************************************// ///////////////////////// CLICKEVENTS ////////////////////////// //*****************************************************************// self._clickEvents(); //*****************************************************************// ///////////////////// DELETE LOCAL STORAGE KEYS ///////////////////// //*****************************************************************// /** * Delete the settings key. **/ $(self.o.deleteSettingsKey) .on(clickEvent, this, function (e) { if (storage && self.o.localStorage) { var cleared = confirm(self.o.settingsKeyLabel); if (cleared) { localStorage.removeItem(keySettings); } } e.preventDefault(); }); /** * Delete the position key. **/ $(self.o.deletePositionKey) .on(clickEvent, this, function (e) { if (storage && self.o.localStorage) { var cleared = confirm(self.o.positionKeyLabel); if (cleared) { localStorage.removeItem(keyPosition); } } e.preventDefault(); }); //*****************************************************************// ///////////////////////// CREATE NEW KEYS ////////////////////////// //*****************************************************************// /** * Create new keys if non are present. **/ if (storage && self.o.localStorage) { /** * If the local storage key (keySettings) is empty or * does not excite, create one and fill it. **/ if (getKeySettings === null || getKeySettings.length < 1) { self._saveSettingsWidget(); } /** * If the local storage key (keyPosition) is empty or * does not excite, create one and fill it. **/ if (getKeyPosition === null || getKeyPosition.length < 1) { self._savePositionWidget(); } } }, /** * All of the click events. * * @param: **/ _clickEvents: function () { var self = this; self._settings(); //*****************************************************************// /////////////////////////// TOGGLE WIDGETS ////////////////////////// //*****************************************************************// /** * Allow users to toggle the content of the widgets. **/ self.widget.on(clickEvent, '.jarviswidget-toggle-btn', function (e) { var tWidget = $(this); var pWidget = tWidget.parents(self.o.widgets); /** * Run function for the indicator image. **/ self._runLoaderWidget(tWidget); /** * Change the class and hide/show the widgets content. **/ if (pWidget.hasClass('jarviswidget-collapsed')) { tWidget.children() .removeClass(self.toggleClass[1]) .addClass(self.toggleClass[0]) .parents(self.o.widgets) .removeClass('jarviswidget-collapsed') .children('[role=content]') .slideDown(self.o.toggleSpeed, function () { self._saveSettingsWidget(); }); } else { tWidget.children() .removeClass(self.toggleClass[0]) .addClass(self.toggleClass[1]) .parents(self.o.widgets) .addClass('jarviswidget-collapsed') .children('[role=content]') .slideUp(self.o.toggleSpeed, function () { self._saveSettingsWidget(); }); } /** * Run the callback function. **/ if (typeof self.o.onToggle == 'function') { self.o.onToggle.call(this, pWidget); } e.preventDefault(); }); //*****************************************************************// ///////////////////////// FULLSCREEN WIDGETS //////////////////////// //*****************************************************************// /** * Set fullscreen height function. **/ function heightFullscreen() { if ($('#jarviswidget-fullscreen-mode') .length) { /** * Setting height variables. **/ var heightWindow = $(window) .height(); var heightHeader = $('#jarviswidget-fullscreen-mode') .find(self.o.widgets) .children('header') .height(); /** * Setting the height to the right widget. **/ $('#jarviswidget-fullscreen-mode') .find(self.o.widgets) .children('div') .height(heightWindow - heightHeader - 15); } } /** * On click go to fullscreen mode. **/ self.widget.on(clickEvent, '.jarviswidget-fullscreen-btn', function (e) { var thisWidget = $(this) .parents(self.o.widgets); var thisWidgetContent = thisWidget.children('div'); /** * Run function for the indicator image. **/ self._runLoaderWidget($(this)); /** * Wrap the widget and go fullsize. **/ if ($('#jarviswidget-fullscreen-mode') .length) { /** * Remove class from the body. **/ $('.nooverflow') .removeClass('nooverflow'); /** * Unwrap the widget, remove the height, set the right * fulscreen button back, and show all other buttons. **/ thisWidget.unwrap('<div>') .children('div') .removeAttr('style') .end() .find('.jarviswidget-fullscreen-btn') .children() .removeClass(self.fullscreenClass[1]) .addClass(self.fullscreenClass[0]) .parents(self.pwCtrls) .children('a') .show(); /** * Reset collapsed widgets. **/ if (thisWidgetContent.hasClass('jarviswidget-visible')) { thisWidgetContent.hide() .removeClass('jarviswidget-visible'); } } else { /** * Prevent the body from scrolling. **/ $('body') .addClass('nooverflow'); /** * Wrap, append it to the body, show the right button * and hide all other buttons. **/ thisWidget.wrap('<div id="jarviswidget-fullscreen-mode"/>') .parent() .find('.jarviswidget-fullscreen-btn') .children() .removeClass(self.fullscreenClass[0]) .addClass(self.fullscreenClass[1]) .parents(self.pwCtrls) .children('a:not(.jarviswidget-fullscreen-btn)') .hide(); /** * Show collapsed widgets. **/ if (thisWidgetContent.is(':hidden')) { thisWidgetContent.show() .addClass('jarviswidget-visible'); } } /** * Run the set height function. **/ heightFullscreen(); /** * Run the callback function. **/ if (typeof self.o.onFullscreen == 'function') { self.o.onFullscreen.call(this, thisWidget); } e.preventDefault(); }); /** * Run the set fullscreen height function when the screen resizes. **/ $(window) .resize(function () { /** * Run the set height function. **/ heightFullscreen(); }); //*****************************************************************// //////////////////////////// EDIT WIDGETS /////////////////////////// //*****************************************************************// /** * Allow users to show/hide a edit box. **/ self.widget.on(clickEvent, '.jarviswidget-edit-btn', function (e) { var tWidget = $(this) .parents(self.o.widgets); /** * Run function for the indicator image. **/ self._runLoaderWidget($(this)); /** * Show/hide the edit box. **/ if (tWidget.find(self.o.editPlaceholder) .is(':visible')) { $(this) .children() .removeClass(self.editClass[1]) .addClass(self.editClass[0]) .parents(self.o.widgets) .find(self.o.editPlaceholder) .slideUp(self.o.editSpeed, function () { self._saveSettingsWidget(); }); } else { $(this) .children() .removeClass(self.editClass[0]) .addClass(self.editClass[1]) .parents(self.o.widgets) .find(self.o.editPlaceholder) .slideDown(self.o.editSpeed); } /** * Run the callback function. **/ if (typeof self.o.onEdit == 'function') { self.o.onEdit.call(this, tWidget); } e.preventDefault(); }); /** * Update the widgets title by using the edit input. **/ $(self.o.editPlaceholder) .find('input') .keyup(function () { $(this) .parents(self.o.widgets) .children('header') .children('h2') .text($(this) .val()); }); /** * Set a custom style. **/ self.widget.on(clickEvent, '[data-widget-setstyle]', function (e) { var val = $(this) .data('widget-setstyle'); var styles = ''; /** * Get all other styles, in order to remove it. **/ $(this) .parents(self.o.editPlaceholder) .find('[data-widget-setstyle]') .each(function () { styles += $(this) .data('widget-setstyle') + ' '; }); /** * Set the new style. **/ $(this) .parents(self.o.widgets) .attr('data-widget-attstyle', '' + val + '') .removeClassPrefix('jarviswidget-color-') .addClass(val); /** * Run function for the indicator image. **/ self._runLoaderWidget($(this)); /** * Lets save the setings. **/ self._saveSettingsWidget(); e.preventDefault(); }); //*****************************************************************// /////////////////////////// CUSTOM ACTION /////////////////////////// //*****************************************************************// /** * Allow users to show/hide a edit box. **/ self.widget.on(clickEvent, '.jarviswidget-custom-btn', function (e) { var w = $(this) .parents(self.o.widgets); /** * Run function for the indicator image. **/ self._runLoaderWidget($(this)); /** * Start and end custom action. **/ if ($(this) .children('.' + self.customClass[0]) .length) { $(this) .children() .removeClass(self.customClass[0]) .addClass(self.customClass[1]); /** * Run the callback function. **/ if (typeof self.o.customStart == 'function') { self.o.customStart.call(this, w); } } else { $(this) .children() .removeClass(self.customClass[1]) .addClass(self.customClass[0]); /** * Run the callback function. **/ if (typeof self.o.customEnd == 'function') { self.o.customEnd.call(this, w); } } /** * Lets save the setings. **/ self._saveSettingsWidget(); e.preventDefault(); }); //*****************************************************************// /////////////////////////// DELETE WIDGETS ////////////////////////// //*****************************************************************// /** * Allow users to delete the widgets. **/ self.widget.on(clickEvent, '.jarviswidget-delete-btn', function (e) { var tWidget = $(this) .parents(self.o.widgets); var removeId = tWidget.attr('id'); var widTitle = tWidget.children('header') .children('h2') .text(); /** * Delete the widgets with a confirm popup. **/ $.SmartMessageBox({ title: "<i class='fa fa-times' style='color:#ed1c24'></i> " + self.o.labelDelete + ' "' + widTitle + '"', content: "Warning: This action cannot be undone", buttons: '[No][Yes]' }, function (ButtonPressed) { //console.log(ButtonPressed); if (ButtonPressed == "Yes") { /** * Run function for the indicator image. **/ self._runLoaderWidget($(this)); /** * Delete the right widget. **/ $('#' + removeId) .fadeOut(self.o.deleteSpeed, function () { $(this) .remove(); /** * Run the callback function. **/ if (typeof self.o.onDelete == 'function') { self.o.onDelete.call(this, tWidget); } }); } }); e.preventDefault(); }); //******************************************************************// /////////////////////////// REFRESH BUTTON /////////////////////////// //******************************************************************// /** * Refresh ajax upon clicking refresh link. **/ self.widget.on(clickEvent, '.jarviswidget-refresh-btn', function (e) { /** * Variables. **/ var rItem = $(this) .parents(self.o.widgets), pathToFile = rItem.data('widget-load'), ajaxLoader = rItem.children(), btn = $(this); /** * Run the ajax function. **/ btn.button('loading'); ajaxLoader.addClass("widget-body-ajax-loading"); setTimeout(function () { btn.button('reset'); ajaxLoader.removeClass("widget-body-ajax-loading"); self._loadAjaxFile(rItem, pathToFile, ajaxLoader); }, 1000) e.preventDefault(); }); }, /** * Destroy. * * @param: **/ destroy: function () { var self = this; self.widget.off('click', self._clickEvents()); self.obj.removeData(pluginName); } }; $.fn[pluginName] = function (option) { return this.each(function () { var $this = $(this); var data = $this.data(pluginName); var options = typeof option == 'object' && option; if (!data) { $this.data(pluginName, (data = new Plugin(this, options))) } if (typeof option == 'string') { data[option](); } }); }; /** * Default settings(dont change). * You can globally override these options * by using $.fn.pluginName.key = 'value'; **/ $.fn[pluginName].defaults = { grid: 'section', widgets: '.jarviswidget', localStorage: true, deleteSettingsKey: '', settingsKeyLabel: 'Reset settings?', deletePositionKey: '', positionKeyLabel: 'Reset position?', sortable: true, buttonsHidden: false, toggleButton: true, toggleClass: 'min-10 | plus-10', toggleSpeed: 200, onToggle: function () {}, deleteButton: true, deleteClass: 'trashcan-10', deleteSpeed: 200, onDelete: function () {}, editButton: true, editPlaceholder: '.jarviswidget-editbox', editClass: 'pencil-10 | delete-10', editSpeed: 200, onEdit: function () {}, colorButton: true, fullscreenButton: true, fullscreenClass: 'fullscreen-10 | normalscreen-10', fullscreenDiff: 3, onFullscreen: function () {}, customButton: true, customClass: '', customStart: function () {}, customEnd: function () {}, buttonOrder: '%refresh% %delete% %custom% %edit% %fullscreen% %toggle%', opacity: 1.0, dragHandle: '> header', placeholderClass: 'jarviswidget-placeholder', indicator: true, indicatorTime: 600, ajax: true, loadingLabel: 'loading...', timestampPlaceholder: '.jarviswidget-timestamp', timestampFormat: 'Last update: %m%/%d%/%y% %h%:%i%:%s%', refreshButton: true, refreshButtonClass: 'refresh-10', labelError: 'Sorry but there was a error:', labelUpdated: 'Last Update:', labelRefresh: 'Refresh', labelDelete: 'Delete widget:', afterLoad: function () {}, rtl: false, onChange: function () {}, onSave: function () {}, ajaxnav: true }; /* * REMOVE CSS CLASS WITH PREFIX * Description: Remove classes that have given prefix. You have an element with classes * "widget widget-color-red" * Usage: $elem.removeClassPrefix('widget-color-'); */ $.fn.removeClassPrefix = function (prefix) { this.each(function (i, it) { var classes = it.className.split(" ") .map(function (item) { return item.indexOf(prefix) === 0 ? "" : item; }); //it.className = classes.join(" "); it.className = $.trim(classes.join(" ")); }); return this; } })(jQuery, window, document);
JavaScript
// Smart Notification (bootstraphunter.com) $.sound_path = "sound/"; $(document).ready(function () { // Plugins placing $("body").append("<div id='divSmallBoxes'></div>"); $("body").append("<div id='divMiniIcons'></div><div id='divbigBoxes'></div>"); }); //Closing Rutine for Loadings function SmartUnLoading() { $(".divMessageBox").fadeOut(300, function () { $(this).remove(); }); $(".LoadingBoxContainer").fadeOut(300, function () { $(this).remove(); }); } // Messagebox var ExistMsg = 0, SmartMSGboxCount = 0, PrevTop = 0; (function ($) { $.SmartMessageBox = function (settings, callback) { var SmartMSG, Content; settings = $.extend({ title: "", content: "", NormalButton: undefined, ActiveButton: undefined, buttons: undefined, input: undefined, inputValue: undefined, placeholder: "", options: undefined }, settings); var PlaySound = 0; PlaySound = 1; //Messagebox Sound // SmallBox Sound if (isIE8orlower() == 0) { var audioElement = document.createElement('audio'); audioElement.setAttribute('src', $.sound_path + 'messagebox.mp3'); $.get(); audioElement.addEventListener("load", function () { audioElement.play(); }, true); audioElement.pause(); audioElement.play(); } SmartMSGboxCount = SmartMSGboxCount + 1; if (ExistMsg == 0) { ExistMsg = 1; SmartMSG = "<div class='divMessageBox animated fadeIn fast' id='MsgBoxBack'></div>"; $("body").append(SmartMSG); if (isIE8orlower() == 1) { $("#MsgBoxBack").addClass("MessageIE"); } } var InputType = ""; var HasInput = 0; if (settings.input != undefined) { HasInput = 1; settings.input = settings.input.toLowerCase(); switch (settings.input) { case "text": settings.inputValue = $.type(settings.inputValue) === 'string' ? settings.inputValue.replace(/'/g, "&#x27;") : settings.inputValue; InputType = "<input class='form-control' type='" + settings.input + "' id='txt" + SmartMSGboxCount + "' placeholder='" + settings.placeholder + "' value='" + settings.inputValue + "'/><br/><br/>"; break; case "password": InputType = "<input class='form-control' type='" + settings.input + "' id='txt" + SmartMSGboxCount + "' placeholder='" + settings.placeholder + "'/><br/><br/>"; break; case "select": if (settings.options == undefined) { alert("For this type of input, the options parameter is required."); } else { InputType = "<select class='form-control' id='txt" + SmartMSGboxCount + "'>"; for (var i = 0; i <= settings.options.length - 1; i++) { if (settings.options[i] == "[") { Name = ""; } else { if (settings.options[i] == "]") { NumBottons = NumBottons + 1; Name = "<option>" + Name + "</option>"; InputType += Name; } else { Name += settings.options[i]; } } }; InputType += "</select>" } break; default: alert("That type of input is not handled yet"); } } Content = "<div class='MessageBoxContainer animated fadeIn fast' id='Msg" + SmartMSGboxCount + "'>"; Content += "<div class='MessageBoxMiddle'>"; Content += "<span class='MsgTitle'>" + settings.title + "</span class='MsgTitle'>"; Content += "<p class='pText'>" + settings.content + "</p>"; Content += InputType; Content += "<div class='MessageBoxButtonSection'>"; if (settings.buttons == undefined) { settings.buttons = "[Accept]"; } settings.buttons = $.trim(settings.buttons); settings.buttons = settings.buttons.split(''); var Name = ""; var NumBottons = 0; if (settings.NormalButton == undefined) { settings.NormalButton = "#232323"; } if (settings.ActiveButton == undefined) { settings.ActiveButton = "#ed145b"; } for (var i = 0; i <= settings.buttons.length - 1; i++) { if (settings.buttons[i] == "[") { Name = ""; } else { if (settings.buttons[i] == "]") { NumBottons = NumBottons + 1; Name = "<button id='bot" + NumBottons + "-Msg" + SmartMSGboxCount + "' class='btn btn-default btn-sm botTempo'> " + Name + "</button>"; Content += Name; } else { Name += settings.buttons[i]; } } }; Content += "</div>"; //MessageBoxButtonSection Content += "</div>"; //MessageBoxMiddle Content += "</div>"; //MessageBoxContainer // alert(SmartMSGboxCount); if (SmartMSGboxCount > 1) { $(".MessageBoxContainer").hide(); $(".MessageBoxContainer").css("z-index", 99999); } $(".divMessageBox").append(Content); // Focus if (HasInput == 1) { $("#txt" + SmartMSGboxCount).focus(); } $('.botTempo').hover(function () { var ThisID = $(this).attr('id'); // alert(ThisID); // $("#"+ThisID).css("background-color", settings.ActiveButton); }, function () { var ThisID = $(this).attr('id'); //$("#"+ThisID).css("background-color", settings.NormalButton); }); // Callback and button Pressed $(".botTempo").click(function () { // Closing Method var ThisID = $(this).attr('id'); var MsgBoxID = ThisID.substr(ThisID.indexOf("-") + 1); var Press = $.trim($(this).text()); if (HasInput == 1) { if (typeof callback == "function") { var IDNumber = MsgBoxID.replace("Msg", ""); var Value = $("#txt" + IDNumber).val(); if (callback) callback(Press, Value); } } else { if (typeof callback == "function") { if (callback) callback(Press); } } $("#" + MsgBoxID).addClass("animated fadeOut fast"); SmartMSGboxCount = SmartMSGboxCount - 1; if (SmartMSGboxCount == 0) { $("#MsgBoxBack").removeClass("fadeIn").addClass("fadeOut").delay(300).queue(function () { ExistMsg = 0; $(this).remove(); }); } }); } })(jQuery); // BigBox var BigBoxes = 0; (function ($) { $.bigBox = function (settings, callback) { var boxBig, content; settings = $.extend({ title: "", content: "", icon: undefined, number: undefined, color: undefined, sound: true, timeout: undefined, colortime: 1500, colors: undefined }, settings); // bigbox Sound if (settings.sound === true) { if (isIE8orlower() == 0) { var audioElement = document.createElement('audio'); if (navigator.userAgent.match('Firefox/')) audioElement.setAttribute('src', $.sound_path + 'bigbox.ogg'); else audioElement.setAttribute('src', $.sound_path + 'bigbox.mp3'); $.get(); audioElement.addEventListener("load", function () { audioElement.play(); }, true); audioElement.pause(); audioElement.play(); } } BigBoxes = BigBoxes + 1; boxBig = "<div id='bigBox" + BigBoxes + "' class='bigBox animated fadeIn fast'><div id='bigBoxColor" + BigBoxes + "'><i class='botClose fa fa-times' id='botClose" + BigBoxes + "'></i>"; boxBig += "<span>" + settings.title + "</span>"; boxBig += "<p>" + settings.content + "</p>"; boxBig += "<div class='bigboxicon'>"; if (settings.icon == undefined) { settings.icon = "fa fa-cloud"; } boxBig += "<i class='" + settings.icon + "'></i>"; boxBig += "</div>"; boxBig += "<div class='bigboxnumber'>"; if (settings.number != undefined) { boxBig += settings.number; } boxBig += "</div></div>"; boxBig += "</div>"; // stacking method $("#divbigBoxes").append(boxBig); if (settings.color == undefined) { settings.color = "#004d60"; } $("#bigBox" + BigBoxes).css("background-color", settings.color); $("#divMiniIcons").append("<div id='miniIcon" + BigBoxes + "' class='cajita animated fadeIn' style='background-color: " + settings.color + ";'><i class='" + settings.icon + "'/></i></div>"); //Click Mini Icon $("#miniIcon" + BigBoxes).bind('click', function () { var FrontBox = $(this).attr('id'); var FrontBigBox = FrontBox.replace("miniIcon", "bigBox"); var FronBigBoxColor = FrontBox.replace("miniIcon", "bigBoxColor"); $(".cajita").each(function (index) { var BackBox = $(this).attr('id'); var BigBoxID = BackBox.replace("miniIcon", "bigBox"); $("#" + BigBoxID).css("z-index", 9998); }); $("#" + FrontBigBox).css("z-index", 9999); $("#" + FronBigBoxColor).removeClass("animated fadeIn").delay(1).queue(function () { $(this).show(); $(this).addClass("animated fadeIn"); $(this).clearQueue(); }); }); var ThisBigBoxCloseCross = $("#botClose" + BigBoxes); var ThisBigBox = $("#bigBox" + BigBoxes); var ThisMiniIcon = $("#miniIcon" + BigBoxes); // Color Functionality var ColorTimeInterval; if (settings.colors != undefined && settings.colors.length > 0) { ThisBigBoxCloseCross.attr("colorcount", "0"); ColorTimeInterval = setInterval(function () { var ColorIndex = ThisBigBoxCloseCross.attr("colorcount"); ThisBigBoxCloseCross.animate({ backgroundColor: settings.colors[ColorIndex].color, }); ThisBigBox.animate({ backgroundColor: settings.colors[ColorIndex].color, }); ThisMiniIcon.animate({ backgroundColor: settings.colors[ColorIndex].color, }); if (ColorIndex < settings.colors.length - 1) { ThisBigBoxCloseCross.attr("colorcount", ((ColorIndex * 1) + 1)); } else { ThisBigBoxCloseCross.attr("colorcount", 0); } }, settings.colortime); } //Close Cross ThisBigBoxCloseCross.bind('click', function () { clearInterval(ColorTimeInterval); if (typeof callback == "function") { if (callback) callback(); } var FrontBox = $(this).attr('id'); var FrontBigBox = FrontBox.replace("botClose", "bigBox"); var miniIcon = FrontBox.replace("botClose", "miniIcon"); $("#" + FrontBigBox).removeClass("fadeIn fast"); $("#" + FrontBigBox).addClass("fadeOut fast").delay(300).queue(function () { $(this).clearQueue(); $(this).remove(); }); $("#" + miniIcon).removeClass("fadeIn fast"); $("#" + miniIcon).addClass("fadeOut fast").delay(300).queue(function () { $(this).clearQueue(); $(this).remove(); }); }); if (settings.timeout != undefined) { var TimedID = BigBoxes; setTimeout(function () { clearInterval(ColorTimeInterval); $("#bigBox" + TimedID).removeClass("fadeIn fast"); $("#bigBox" + TimedID).addClass("fadeOut fast").delay(300).queue(function () { $(this).clearQueue(); $(this).remove(); }); $("#miniIcon" + TimedID).removeClass("fadeIn fast"); $("#miniIcon" + TimedID).addClass("fadeOut fast").delay(300).queue(function () { $(this).clearQueue(); $(this).remove(); }); }, settings.timeout); } } })(jQuery); // .BigBox // Small Notification var SmallBoxes = 0, SmallCount = 0, SmallBoxesAnchos = 0; (function ($) { $.smallBox = function (settings, callback) { var BoxSmall, content; settings = $.extend({ title: "", content: "", icon: undefined, iconSmall: undefined, sound: true, color: undefined, timeout: undefined, colortime: 1500, colors: undefined }, settings); // SmallBox Sound if (settings.sound === true) { if (isIE8orlower() == 0) { var audioElement = document.createElement('audio'); if (navigator.userAgent.match('Firefox/')) audioElement.setAttribute('src', $.sound_path + 'smallbox.ogg'); else audioElement.setAttribute('src', $.sound_path + 'smallbox.mp3'); $.get(); audioElement.addEventListener("load", function () { audioElement.play(); }, true); audioElement.pause(); audioElement.play(); } } SmallBoxes = SmallBoxes + 1; BoxSmall = "" var IconSection = "", CurrentIDSmallbox = "smallbox" + SmallBoxes; if (settings.iconSmall == undefined) { IconSection = "<div class='miniIcono'></div>"; } else { IconSection = "<div class='miniIcono'><i class='miniPic " + settings.iconSmall + "'></i></div>"; } if (settings.icon == undefined) { BoxSmall = "<div id='smallbox" + SmallBoxes + "' class='SmallBox animated fadeInRight fast'><div class='textoFull'><span>" + settings.title + "</span><p>" + settings.content + "</p></div>" + IconSection + "</div>"; } else { BoxSmall = "<div id='smallbox" + SmallBoxes + "' class='SmallBox animated fadeInRight fast'><div class='foto'><i class='" + settings.icon + "'></i></div><div class='textoFoto'><span>" + settings.title + "</span><p>" + settings.content + "</p></div>" + IconSection + "</div>"; } if (SmallBoxes == 1) { $("#divSmallBoxes").append(BoxSmall); SmallBoxesAnchos = $("#smallbox" + SmallBoxes).height() + 40; } else { var SmartExist = $(".SmallBox").size(); if (SmartExist == 0) { $("#divSmallBoxes").append(BoxSmall); SmallBoxesAnchos = $("#smallbox" + SmallBoxes).height() + 40; } else { $("#divSmallBoxes").append(BoxSmall); $("#smallbox" + SmallBoxes).css("top", SmallBoxesAnchos); SmallBoxesAnchos = SmallBoxesAnchos + $("#smallbox" + SmallBoxes).height() + 20; $(".SmallBox").each(function (index) { if (index == 0) { $(this).css("top", 20); heightPrev = $(this).height() + 40; SmallBoxesAnchos = $(this).height() + 40; } else { $(this).css("top", heightPrev); heightPrev = heightPrev + $(this).height() + 20; SmallBoxesAnchos = SmallBoxesAnchos + $(this).height() + 20; } }); } } var ThisSmallBox = $("#smallbox" + SmallBoxes); // IE fix // if($.browser.msie) { // // alert($("#"+CurrentIDSmallbox).css("height")); // } if (settings.color == undefined) { ThisSmallBox.css("background-color", "#004d60"); } else { ThisSmallBox.css("background-color", settings.color); } var ColorTimeInterval; if (settings.colors != undefined && settings.colors.length > 0) { ThisSmallBox.attr("colorcount", "0"); ColorTimeInterval = setInterval(function () { var ColorIndex = ThisSmallBox.attr("colorcount"); ThisSmallBox.animate({ backgroundColor: settings.colors[ColorIndex].color, }); if (ColorIndex < settings.colors.length - 1) { ThisSmallBox.attr("colorcount", ((ColorIndex * 1) + 1)); } else { ThisSmallBox.attr("colorcount", 0); } }, settings.colortime); } if (settings.timeout != undefined) { setTimeout(function () { clearInterval(ColorTimeInterval); var ThisHeight = $(this).height() + 20; var ID = CurrentIDSmallbox; var ThisTop = $("#" + CurrentIDSmallbox).css('top'); // SmallBoxesAnchos = SmallBoxesAnchos - ThisHeight; // $("#"+CurrentIDSmallbox).remove(); if ($("#" + CurrentIDSmallbox + ":hover").length != 0) { //Mouse Over the element $("#" + CurrentIDSmallbox).on("mouseleave", function () { SmallBoxesAnchos = SmallBoxesAnchos - ThisHeight; $("#" + CurrentIDSmallbox).remove(); if (typeof callback == "function") { if (callback) callback(); } var Primero = 1; var heightPrev = 0; $(".SmallBox").each(function (index) { if (index == 0) { $(this).animate({ top: 20 }, 300); heightPrev = $(this).height() + 40; SmallBoxesAnchos = $(this).height() + 40; } else { $(this).animate({ top: heightPrev }, 350); heightPrev = heightPrev + $(this).height() + 20; SmallBoxesAnchos = SmallBoxesAnchos + $(this).height() + 20; } }); }); } else { clearInterval(ColorTimeInterval); SmallBoxesAnchos = SmallBoxesAnchos - ThisHeight; if (typeof callback == "function") { if (callback) callback(); } $("#" + CurrentIDSmallbox).removeClass().addClass("SmallBox").animate({ opacity: 0 }, 300, function () { $(this).remove(); var Primero = 1; var heightPrev = 0; $(".SmallBox").each(function (index) { if (index == 0) { $(this).animate({ top: 20 }, 300); heightPrev = $(this).height() + 40; SmallBoxesAnchos = $(this).height() + 40; } else { $(this).animate({ top: heightPrev }); heightPrev = heightPrev + $(this).height() + 20; SmallBoxesAnchos = SmallBoxesAnchos + $(this).height() + 20; } }); }) } }, settings.timeout); } // Click Closing $("#smallbox" + SmallBoxes).bind('click', function () { clearInterval(ColorTimeInterval); if (typeof callback == "function") { if (callback) callback(); } var ThisHeight = $(this).height() + 20; var ID = $(this).attr('id'); var ThisTop = $(this).css('top'); SmallBoxesAnchos = SmallBoxesAnchos - ThisHeight; $(this).removeClass().addClass("SmallBox").animate({ opacity: 0 }, 300, function () { $(this).remove(); var Primero = 1; var heightPrev = 0; $(".SmallBox").each(function (index) { if (index == 0) { $(this).animate({ top: 20, }, 300); heightPrev = $(this).height() + 40; SmallBoxesAnchos = $(this).height() + 40; } else { $(this).animate({ top: heightPrev }, 350); heightPrev = heightPrev + $(this).height() + 20; SmallBoxesAnchos = SmallBoxesAnchos + $(this).height() + 20; } }); }) }); } })(jQuery); // .Small Notification // Sounds function getInternetExplorerVersion() { var rv = -1; // Return value assumes failure. if (navigator.appName == 'Microsoft Internet Explorer') { var ua = navigator.userAgent; var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})"); if (re.exec(ua) != null) rv = parseFloat(RegExp.$1); } return rv; } function checkVersion() { var msg = "You're not using Windows Internet Explorer."; var ver = getInternetExplorerVersion(); if (ver > -1) { if (ver >= 8.0) msg = "You're using a recent copy of Windows Internet Explorer." else msg = "You should upgrade your copy of Windows Internet Explorer."; } alert(msg); } function isIE8orlower() { var msg = "0"; var ver = getInternetExplorerVersion(); if (ver > -1) { if (ver >= 9.0) msg = 0 else msg = 1; } return msg; // alert(msg); }
JavaScript
/* json2.js 2014-02-04 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, regexp: true */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. if (typeof JSON !== 'object') { JSON = {}; } (function () { 'use strict'; function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function () { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function () { return this.valueOf(); }; } var cx, escapable, gap, indent, meta, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === 'string') { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }; JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } }());
JavaScript
/** * summernote.js * (c) 2013~ Alan Hong * summernote may be freely distributed under the MIT license./ */ (function($) { "use strict"; //Check Platform/Agent var bMac = navigator.appVersion.indexOf('Mac') > -1; var bMSIE = navigator.userAgent.indexOf('MSIE') > -1; /** * func utils (for high-order func's arg) */ var func = function() { var eq = function(elA) { return function(elB) { return elA === elB; }; }; var eq2 = function(elA, elB) { return elA === elB; }; var fail = function() { return false; }; var not = function(f) { return function() { return !f.apply(f, arguments); }}; var self = function(a) { return a; } return { eq: eq, eq2: eq2, fail: fail, not: not, self: self }; }(); /** * list utils */ var list = function() { var head = function(array) { return array[0]; }; var last = function(array) { return array[array.length - 1]; }; var initial = function(array) { return array.slice(0, array.length - 1); }; var tail = function(array) { return array.slice(1); }; var sum = function(array, fn) { fn = fn || func.self; return array.reduce(function(memo, v) { return memo + fn(v); }, 0); }; var from = function(collection) { var result = [], idx = -1, length = collection.length; while (++idx < length) { result[idx] = collection[idx]; } return result; }; var clusterBy = function(array, fn) { if (array.length === 0) { return []; } var aTail = tail(array); return aTail.reduce(function (memo, v) { var aLast = last(memo); if (fn(last(aLast), v)) { aLast[aLast.length] = v; } else { memo[memo.length] = [v]; } return memo; }, [[head(array)]]); }; var compact = function(array) { var aResult = []; for (var idx = 0, sz = array.length; idx < sz; idx ++) { if (array[idx]) { aResult.push(array[idx]); }; }; return aResult; }; return { head: head, last: last, initial: initial, tail: tail, sum: sum, from: from, compact: compact, clusterBy: clusterBy }; }(); /** * dom utils */ var dom = function() { var makePredByNodeName = function(sNodeName) { // nodeName of element is always uppercase. return function(node) { return node && node.nodeName === sNodeName; }; }; var isPara = function(node) { return node && /^P|^LI|^H[1-7]/.test(node.nodeName); }; var isList = function(node) { return node && /^UL|^OL/.test(node.nodeName); }; var isEditable = function(node) { return node && $(node).hasClass('note-editable'); }; var isControlSizing = function(node) { return node && $(node).hasClass('note-control-sizing'); }; // ancestor: find nearest ancestor predicate hit var ancestor = function(node, pred) { while (node) { if (pred(node)) { return node; } node = node.parentNode; } return null; }; // listAncestor: listing ancestor nodes (until predicate hit: optional) var listAncestor = function(node, pred) { pred = pred || func.fail; var aAncestor = []; ancestor(node, function(el) { aAncestor.push(el); return pred(el); }); return aAncestor; }; // commonAncestor: find commonAncestor var commonAncestor = function(nodeA, nodeB) { var aAncestor = listAncestor(nodeA); for (var n = nodeB; n; n = n.parentNode) { if ($.inArray(n, aAncestor) > -1) { return n; } } return null; // difference document area }; // listBetween: listing all Nodes between nodeA and nodeB // FIXME: nodeA and nodeB must be sorted, use comparePoints later. var listBetween = function(nodeA, nodeB) { var aNode = []; var bStart = false, bEnd = false; var fnWalk = function(node) { if (!node) { return; } // traverse fisnish if (node === nodeA) { bStart = true; } // start point if (bStart && !bEnd) { aNode.push(node) } // between if (node === nodeB) { bEnd = true; return; } // end point for (var idx = 0, sz = node.childNodes.length; idx < sz; idx++) { fnWalk(node.childNodes[idx]); } } fnWalk(commonAncestor(nodeA, nodeB)); // DFS with commonAcestor. return aNode; }; // listPrev: listing prevSiblings (until predicate hit: optional) var listPrev = function(node, pred) { pred = pred || func.fail; var aNext = []; while (node) { aNext.push(node); if (pred(node)) { break; } node = node.previousSibling; }; return aNext; }; // listNext: listing nextSiblings (until predicate hit: optional) var listNext = function(node, pred) { pred = pred || func.fail; var aNext = []; while (node) { aNext.push(node); if (pred(node)) { break; } node = node.nextSibling; }; return aNext; }; // insertAfter: insert node after preceding var insertAfter = function(node, preceding) { var next = preceding.nextSibling, parent = preceding.parentNode; if (next) { parent.insertBefore(node, next); } else { parent.appendChild(node); } return node; }; // appends: append children var appends = function(node, aChild) { $.each(aChild, function(idx, child) { node.appendChild(child); }); return node; }; var isText = makePredByNodeName('#text'); // length: size of element. var length = function(node) { if (isText(node)) { return node.nodeValue.length; } return node.childNodes.length; }; // position: offset from parent. var position = function(node) { var offset = 0; while (node = node.previousSibling) { offset += 1; } return offset; }; // makeOffsetPath: return offsetPath(offset list) from ancestor var makeOffsetPath = function(ancestor, node) { var aAncestor = list.initial(listAncestor(node, func.eq(ancestor))); return $.map(aAncestor, position).reverse(); }; // fromtOffsetPath: return element from offsetPath(offset list) var fromOffsetPath = function(ancestor, aOffset) { var current = ancestor; for (var i = 0, sz = aOffset.length; i < sz; i++) { current = current.childNodes[aOffset[i]]; } return current; }; // splitData: split element or #text var splitData = function(node, offset) { if (offset === 0) { return node; } if (offset >= length(node)) { return node.nextSibling; } // splitText if (isText(node)) { return node.splitText(offset); } // splitElement var child = node.childNodes[offset]; node = insertAfter(node.cloneNode(false), node); return appends(node, listNext(child)); }; // split: split dom tree by boundaryPoint(pivot and offset) var split = function(root, pivot, offset) { var aAncestor = listAncestor(pivot, func.eq(root)); if (aAncestor.length === 1) { return splitData(pivot, offset); } return aAncestor.reduce(function(node, parent) { var clone = parent.cloneNode(false); insertAfter(clone, parent); if (node === pivot) { node = splitData(node, offset); } appends(clone, listNext(node)); return clone; }); }; // remove: remove node, (bRemoveChild: remove child or not) var remove = function(node, bRemoveChild) { if (!node || !node.parentNode) { return; } if (node.removeNode) { return node.removeNode(bRemoveChild); } var elParent = node.parentNode; if (!bRemoveChild) { var aNode = []; for (var i = 0, sz = node.childNodes.length; i < sz; i++) { aNode.push(node.childNodes[i]); } for (var i = 0, sz = aNode.length; i < sz; i++) { elParent.insertBefore(aNode[i], node); } } elParent.removeChild(node); }; var unescape = function(str) { return $("<div/>").html(str).text(); }; var html = function($node) { return dom.isTextarea($node[0]) ? unescape($node.val()) : $node.html(); }; return { isText: isText, isPara: isPara, isList: isList, isEditable: isEditable, isControlSizing: isControlSizing, isAnchor: makePredByNodeName('A'), isDiv: makePredByNodeName('DIV'), isSpan: makePredByNodeName('SPAN'), isB: makePredByNodeName('B'), isU: makePredByNodeName('U'), isS: makePredByNodeName('S'), isI: makePredByNodeName('I'), isImg: makePredByNodeName('IMG'), isTextarea: makePredByNodeName('TEXTAREA'), ancestor: ancestor, listAncestor: listAncestor, listNext: listNext, listPrev: listPrev, commonAncestor: commonAncestor, listBetween: listBetween, insertAfter: insertAfter, position: position, makeOffsetPath: makeOffsetPath, fromOffsetPath: fromOffsetPath, split: split, remove: remove, html: html }; }(); /** * range module */ var range = function() { var bW3CRangeSupport = !!document.createRange; // return boundaryPoint from TextRange, inspired by Andy Na's HuskyRange.js var textRange2bp = function(textRange, bStart) { var elCont = textRange.parentElement(), nOffset; var tester = document.body.createTextRange(), elPrevCont; var aChild = list.from(elCont.childNodes); for (nOffset = 0; nOffset < aChild.length; nOffset++) { if (dom.isText(aChild[nOffset])) { continue; } tester.moveToElementText(aChild[nOffset]); if (tester.compareEndPoints('StartToStart', textRange) >= 0) { break; } elPrevCont = aChild[nOffset]; } if (nOffset != 0 && dom.isText(aChild[nOffset - 1])) { var textRangeStart = document.body.createTextRange(), elCurText = null; textRangeStart.moveToElementText(elPrevCont || elCont); textRangeStart.collapse(!elPrevCont); elCurText = elPrevCont ? elPrevCont.nextSibling : elCont.firstChild; var pointTester = textRange.duplicate(); pointTester.setEndPoint('StartToStart', textRangeStart); var nTextCount = pointTester.text.replace(/[\r\n]/g, '').length; while (nTextCount > elCurText.nodeValue.length && elCurText.nextSibling) { nTextCount -= elCurText.nodeValue.length; elCurText = elCurText.nextSibling; } var sDummy = elCurText.nodeValue; //enforce IE to re-reference elCurText if (bStart && elCurText.nextSibling && dom.isText(elCurText.nextSibling) && nTextCount == elCurText.nodeValue.length) { nTextCount -= elCurText.nodeValue.length; elCurText = elCurText.nextSibling; } elCont = elCurText; nOffset = nTextCount; } return {cont: elCont, offset: nOffset}; }; // return TextRange from boundary point (inspired by google closure-library) var bp2textRange = function(bp) { var textRangeInfo = function(elCont, nOffset) { var elNode, bCollapseToStart; if (dom.isText(elCont)) { var aPrevText = dom.listPrev(elCont, func.not(dom.isText)); var elPrevCont = list.last(aPrevText).previousSibling; elNode = elPrevCont || elCont.parentNode; nOffset += list.sum(list.tail(aPrevText), dom.length); bCollapseToStart = !elPrevCont; } else { elNode = elCont.childNodes[nOffset] || elCont; if (dom.isText(elNode)) { return textRangeInfo(elNode, nOffset); } nOffset = 0; bCollapseToStart = false; } return {cont: elNode, collapseToStart: bCollapseToStart, offset: nOffset}; } var textRange = document.body.createTextRange(); var info = textRangeInfo(bp.cont, bp.offset); textRange.moveToElementText(info.cont); textRange.collapse(info.collapseToStart); textRange.moveStart('character', info.offset); return textRange; }; // {startContainer, startOffset, endContainer, endOffset} var WrappedRange = function(sc, so, ec, eo) { this.sc = sc; this.so = so; this.ec = ec; this.eo = eo; // nativeRange: get nativeRange from sc, so, ec, eo var nativeRange = function() { if (bW3CRangeSupport) { var w3cRange = document.createRange(); w3cRange.setStart(sc, so); w3cRange.setEnd(ec, eo); return w3cRange; } else { var textRange = bp2textRange({cont:sc, offset:so}); textRange.setEndPoint('EndToEnd', bp2textRange({cont:ec, offset:eo})); return textRange; } }; // select: update visible range this.select = function() { var nativeRng = nativeRange(); if (bW3CRangeSupport) { var selection = document.getSelection(); if (selection.rangeCount > 0) { selection.removeAllRanges(); } selection.addRange(nativeRng); } else { nativeRng.select(); } }; // listPara: listing paragraphs on range this.listPara = function() { var aNode = dom.listBetween(sc, ec); var aPara = list.compact($.map(aNode, function(node) { return dom.ancestor(node, dom.isPara); })); return $.map(list.clusterBy(aPara, func.eq2), list.head); }; // makeIsOn: return isOn(pred) function var makeIsOn = function(pred) { return function() { var elAncestor = dom.ancestor(sc, pred); return elAncestor && (elAncestor === dom.ancestor(ec, pred)); }; }; // isOnEditable: judge whether range is on editable or not this.isOnEditable = makeIsOn(dom.isEditable); // isOnList: judge whether range is on list node or not this.isOnList = makeIsOn(dom.isList); // isOnAnchor: judge whether range is on anchor node or not this.isOnAnchor = makeIsOn(dom.isAnchor); // isCollapsed: judge whether range was collapsed this.isCollapsed = function() { return sc === ec && so === eo; }; // insertNode this.insertNode = function(node) { var nativeRng = nativeRange(); if (bW3CRangeSupport) { nativeRng.insertNode(node); } else { nativeRng.pasteHTML(node.outerHTML); // NOTE: missing node reference. } }; this.toString = function() { var nativeRng = nativeRange(); if (bW3CRangeSupport) { return nativeRng.toString(); } else { return nativeRng.text; } }; //bookmark: offsetPath bookmark this.bookmark = function(elEditable) { return { s: { path: dom.makeOffsetPath(elEditable, sc), offset: so }, e: { path: dom.makeOffsetPath(elEditable, ec), offset: eo } }; }; }; return { // Range Object // create Range Object From arguments or Browser Selection create : function(sc, so, ec, eo) { if (arguments.length === 0) { // from Browser Selection if (bW3CRangeSupport) { // webkit, firefox var nativeRng = document.getSelection().getRangeAt(0); sc = nativeRng.startContainer, so = nativeRng.startOffset, ec = nativeRng.endContainer, eo = nativeRng.endOffset; } else { // IE8: TextRange var textRange = document.selection.createRange(); var textRangeEnd = textRange.duplicate(); textRangeEnd.collapse(false); var textRangeStart = textRange; textRangeStart.collapse(true); var bpStart = textRange2bp(textRangeStart, true), bpEnd = textRange2bp(textRangeEnd, false); sc = bpStart.cont, so = bpStart.offset; ec = bpEnd.cont, eo = bpEnd.offset; } } else if (arguments.length === 2) { //collapsed ec = sc; eo = so; } return new WrappedRange(sc, so, ec, eo); }, // createFromBookmark createFromBookmark : function(elEditable, bookmark) { var sc = dom.fromOffsetPath(elEditable, bookmark.s.path); var so = bookmark.s.offset; var ec = dom.fromOffsetPath(elEditable, bookmark.e.path); var eo = bookmark.e.offset; return new WrappedRange(sc, so, ec, eo); } }; }(); /** * Style */ var Style = function() { // para level style this.stylePara = function(rng, oStyle) { var aPara = rng.listPara(); $.each(aPara, function(idx, elPara) { $.each(oStyle, function(sKey, sValue) { elPara.style[sKey] = sValue; }); }); }; // get current style, elTarget: target element on event. this.current = function(rng, elTarget) { var welCont = $(dom.isText(rng.sc) ? rng.sc.parentNode : rng.sc); var oStyle = welCont.css(['font-size', 'text-align', 'list-style-type', 'line-height']) || {}; oStyle['font-size'] = parseInt(oStyle['font-size']); // document.queryCommandState for toggle state oStyle['font-bold'] = document.queryCommandState('bold') ? 'bold' : 'normal'; oStyle['font-italic'] = document.queryCommandState('italic') ? 'italic' : 'normal'; oStyle['font-underline'] = document.queryCommandState('underline') ? 'underline' : 'normal'; // list-style-type to list-style(unordered, ordered) if (!rng.isOnList()) { oStyle['list-style'] = 'none'; } else { var aOrderedType = ['circle', 'disc', 'disc-leading-zero', 'square']; var bUnordered = $.inArray(oStyle['list-style-type'], aOrderedType) > -1; oStyle['list-style'] = bUnordered ? 'unordered' : 'ordered'; } var elPara = dom.ancestor(rng.sc, dom.isPara); if (elPara && elPara.style['line-height']) { oStyle['line-height'] = elPara.style.lineHeight; } else { var lineHeight = parseInt(oStyle['line-height']) / parseInt(oStyle['font-size']); oStyle['line-height'] = lineHeight.toFixed(1); } oStyle.image = dom.isImg(elTarget) && elTarget; oStyle.anchor = rng.isOnAnchor() && dom.ancestor(rng.sc, dom.isAnchor); oStyle.aAncestor = dom.listAncestor(rng.sc, dom.isEditable); return oStyle; } }; /** * History */ var History = function() { var aUndo = [], aRedo = []; var makeSnap = function(welEditable) { var elEditable = welEditable[0], rng = range.create(); return { contents: welEditable.html(), bookmark: rng.bookmark(elEditable), scrollTop: welEditable.scrollTop() }; }; var applySnap = function(welEditable, oSnap) { welEditable.html(oSnap.contents).scrollTop(oSnap.scrollTop); range.createFromBookmark(welEditable[0], oSnap.bookmark).select(); }; this.undo = function(welEditable) { var oSnap = makeSnap(welEditable); if (aUndo.length === 0) { return; } applySnap(welEditable, aUndo.pop()), aRedo.push(oSnap); }; this.redo = function(welEditable) { var oSnap = makeSnap(welEditable); if (aRedo.length === 0) { return; } applySnap(welEditable, aRedo.pop()), aUndo.push(oSnap); }; this.recordUndo = function(welEditable) { aRedo = [], aUndo.push(makeSnap(welEditable)); }; }; /** * Editor */ var Editor = function() { //currentStyle var style = new Style(); this.currentStyle = function(elTarget) { var rng = range.create(); return rng.isOnEditable() && style.current(rng, elTarget); }; this.tab = function(welEditable) { recordUndo(welEditable); var rng = range.create(); var sNbsp = new Array(welEditable.data('tabsize') + 1).join('&nbsp;') rng.insertNode($('<span id="noteTab">' + sNbsp + '</span>')[0]); var welTab = $('#noteTab').removeAttr('id'); rng = range.create(welTab[0], 1); rng.select(); dom.remove(welTab[0]); }; // undo this.undo = function(welEditable) { welEditable.data('NoteHistory').undo(welEditable); }; // redo this.redo = function(welEditable) { welEditable.data('NoteHistory').redo(welEditable); }; // recordUndo var recordUndo = this.recordUndo = function(welEditable) { welEditable.data('NoteHistory').recordUndo(welEditable); }; // native commands(with execCommand) var aCmd = ['bold', 'italic', 'underline', 'strikethrough', 'justifyLeft', 'justifyCenter', 'justifyRight', 'justifyFull', 'insertOrderedList', 'insertUnorderedList', 'indent', 'outdent', 'formatBlock', 'removeFormat', 'backColor', 'foreColor', 'insertImage', 'insertHorizontalRule']; for (var idx = 0, len=aCmd.length; idx < len; idx ++) { this[aCmd[idx]] = function(sCmd) { return function(welEditable, sValue) { recordUndo(welEditable); document.execCommand(sCmd, false, sValue); }; }(aCmd[idx]); } this.formatBlock = function(welEditable, sValue) { sValue = bMSIE ? '<' + sValue + '>' : sValue; document.execCommand('FormatBlock', false, sValue); }; this.fontSize = function(welEditable, sValue) { recordUndo(welEditable); document.execCommand('fontSize', false, 3); // <font size='3'> to <font style='font-size={sValue}px;'> var welFont = welEditable.find('font[size=3]'); welFont.removeAttr('size').css('font-size', sValue + 'px'); }; this.lineHeight = function(welEditable, sValue) { recordUndo(welEditable); style.stylePara(range.create(), {lineHeight: sValue}); }; this.unlink = function(welEditable) { var rng = range.create(); if (rng.isOnAnchor()) { recordUndo(welEditable); var elAnchor = dom.ancestor(rng.sc, dom.isAnchor); rng = range.create(elAnchor, 0, elAnchor, 1); rng.select(); document.execCommand('unlink'); } }; this.setLinkDialog = function(welEditable, fnShowDialog) { var rng = range.create(); if (rng.isOnAnchor()) { var elAnchor = dom.ancestor(rng.sc, dom.isAnchor); rng = range.create(elAnchor, 0, elAnchor, 1); } fnShowDialog({ range: rng, text: rng.toString(), url: rng.isOnAnchor() ? dom.ancestor(rng.sc, dom.isAnchor).href : '' }, function(sLinkUrl) { rng.select(); recordUndo(welEditable); var bProtocol = sLinkUrl.toLowerCase().indexOf('://') !== -1; var sLinkUrlWithProtocol = bProtocol ? sLinkUrl : 'http://' + sLinkUrl; //IE: createLink when range collapsed. if (bMSIE && rng.isCollapsed()) { rng.insertNode($('<A id="linkAnchor">' + sLinkUrl + '</A>')[0]); var welAnchor = $('#linkAnchor').removeAttr('id') .attr('href', sLinkUrlWithProtocol); rng = range.create(welAnchor[0], 0, welAnchor[0], 1); rng.select(); } else { document.execCommand('createlink', false, sLinkUrlWithProtocol); } }); }; this.color = function(welEditable, sObjColor) { var oColor = JSON.parse(sObjColor); var foreColor = oColor.foreColor, backColor = oColor.backColor; recordUndo(welEditable); if (foreColor) { document.execCommand('foreColor', false, foreColor); } if (backColor) { document.execCommand('backColor', false, backColor); } }; this.insertTable = function(welEditable, sDim) { recordUndo(welEditable); var aDim = sDim.split('x'); var nCol = aDim[0], nRow = aDim[1]; var aTD = [], sTD; var sWhitespace = bMSIE ? '&nbsp;' : '<br/>'; for (var idxCol = 0; idxCol < nCol; idxCol++) { aTD.push('<td>' + sWhitespace + '</td>'); } sTD = aTD.join(''); var aTR = [], sTR; for (var idxRow = 0; idxRow < nRow; idxRow++) { aTR.push('<tr>' + sTD + '</tr>'); } sTR = aTR.join(''); var sTable = '<table class="table table-bordered">' + sTR + '</table>'; range.create().insertNode($(sTable)[0]); }; this.float = function(welEditable, sValue, elTarget) { recordUndo(welEditable); elTarget.style.cssFloat = sValue; }; this.resize = function(welEditable, sValue, elTarget) { recordUndo(welEditable); elTarget.style.width = welEditable.width() * sValue + 'px'; elTarget.style.height = ''; }; this.resizeTo = function(pos, welTarget) { var newRatio = pos.y / pos.x; var ratio = welTarget.data('ratio'); welTarget.css({ width: ratio > newRatio ? pos.x : pos.y / ratio, height: ratio > newRatio ? pos.x * ratio : pos.y }); }; }; /** * Toolbar */ var Toolbar = function() { this.update = function(welToolbar, oStyle) { //handle selectbox for fontsize, lineHeight var checkDropdownMenu = function(welBtn, nValue) { welBtn.find('.dropdown-menu li a').each(function() { var bChecked = $(this).attr('data-value') == nValue; this.className = bChecked ? 'checked' : ''; }); }; var welFontsize = welToolbar.find('.note-fontsize'); welFontsize.find('.note-current-fontsize').html(oStyle['font-size']); checkDropdownMenu(welFontsize, parseFloat(oStyle['font-size'])); var welLineHeight = welToolbar.find('.note-height'); checkDropdownMenu(welLineHeight, parseFloat(oStyle['line-height'])); //check button state var btnState = function(sSelector, pred) { var welBtn = welToolbar.find(sSelector); welBtn[pred() ? 'addClass' : 'removeClass']('active'); }; btnState('button[data-event="bold"]', function() { return oStyle['font-bold'] === 'bold'; }); btnState('button[data-event="italic"]', function() { return oStyle['font-italic'] === 'italic'; }); btnState('button[data-event="underline"]', function() { return oStyle['font-underline'] === 'underline'; }); btnState('button[data-event="justifyLeft"]', function() { return oStyle['text-align'] === 'left' || oStyle['text-align'] === 'start'; }); btnState('button[data-event="justifyCenter"]', function() { return oStyle['text-align'] === 'center'; }); btnState('button[data-event="justifyRight"]', function() { return oStyle['text-align'] === 'right'; }); btnState('button[data-event="justifyFull"]', function() { return oStyle['text-align'] === 'justify'; }); btnState('button[data-event="insertUnorderedList"]', function() { return oStyle['list-style'] === 'unordered'; }); btnState('button[data-event="insertOrderedList"]', function() { return oStyle['list-style'] === 'ordered'; }); }; this.updateRecentColor = function(elBtn, sEvent, sValue) { var welColor = $(elBtn).closest('.note-color'); var welRecentColor = welColor.find('.note-recent-color'); var oColor = JSON.parse(welRecentColor.attr('data-value')); oColor[sEvent] = sValue; welRecentColor.attr('data-value', JSON.stringify(oColor)); var sKey = sEvent === 'backColor' ? 'background-color' : 'color'; welRecentColor.find('i').css(sKey, sValue); }; this.updateFullscreen = function(welToolbar, bFullscreen) { var welBtn = welToolbar.find('button[data-event="fullscreen"]'); welBtn[bFullscreen ? 'addClass' : 'removeClass']('active'); }; this.updateCodeview = function(welToolbar, bCodeview) { var welBtn = welToolbar.find('button[data-event="codeview"]'); welBtn[bCodeview ? 'addClass' : 'removeClass']('active'); }; this.enable = function(welToolbar) { welToolbar.find('button').not('button[data-event="codeview"]').removeClass('disabled'); }; this.disable = function(welToolbar) { welToolbar.find('button').not('button[data-event="codeview"]').addClass('disabled'); }; }; /** * Popover */ var Popover = function() { var showPopover = function(welPopover, elPlaceholder) { var welPlaceHolder = $(elPlaceholder); var pos = welPlaceHolder.position(), height = welPlaceHolder.height(); welPopover.css({ display: 'block', left: pos.left, top: pos.top + height }); }; this.update = function(welPopover, oStyle) { var welLinkPopover = welPopover.find('.note-link-popover'), welImagePopover = welPopover.find('.note-image-popover'); if (oStyle.anchor) { var welAnchor = welLinkPopover.find('a'); welAnchor.attr('href', oStyle.anchor.href).html(oStyle.anchor.href); showPopover(welLinkPopover, oStyle.anchor); } else { welLinkPopover.hide(); } if (oStyle.image) { showPopover(welImagePopover, oStyle.image); } else { welImagePopover.hide(); } }; this.hide = function(welPopover) { welPopover.children().hide(); }; }; /** * Handle */ var Handle = function() { this.update = function(welHandle, oStyle) { var welSelection = welHandle.find('.note-control-selection'); if (oStyle.image) { var welImage = $(oStyle.image); var pos = welImage.position(); var szImage = {w: welImage.width(), h: welImage.height()}; welSelection.css({ display: 'block', left: pos.left, top: pos.top, width: szImage.w, height: szImage.h }).data('target', oStyle.image); // save current image element. var sSizing = szImage.w + 'x' + szImage.h; welSelection.find('.note-control-selection-info').text(sSizing); } else { welSelection.hide(); } }; this.hide = function(welHandle) { welHandle.children().hide(); }; }; /** * Dialog */ var Dialog = function() { this.showImageDialog = function(welDialog, hDropImage, fnInsertImages) { var welImageDialog = welDialog.find('.note-image-dialog'); var welDropzone = welDialog.find('.note-dropzone'), welImageInput = welDialog.find('.note-image-input'); welImageDialog.on('shown.bs.modal', function(e) { welDropzone.on('dragenter dragover dragleave', false); welDropzone.on('drop', function(e) { hDropImage(e); welImageDialog.modal('hide'); }); welImageInput.on('change', function(event) { fnInsertImages(this.files); $(this).val(''); welImageDialog.modal('hide'); }); }).on('hidden.bs.modal', function(e) { welDropzone.off('dragenter dragover dragleave drop'); welImageInput.off('change'); welImageDialog.off('shown.bs.modal hidden.bs.modal'); }).modal('show'); }; this.showLinkDialog = function(welDialog, linkInfo, callback) { var welLinkDialog = welDialog.find('.note-link-dialog'); var welLinkText = welLinkDialog.find('.note-link-text'), welLinkUrl = welLinkDialog.find('.note-link-url'), welLinkBtn = welLinkDialog.find('.note-link-btn'); welLinkDialog.on('shown.bs.modal', function(e) { welLinkText.html(linkInfo.text); welLinkUrl.val(linkInfo.url).keyup(function(event) { if (welLinkUrl.val()) { welLinkBtn.removeClass('disabled').attr('disabled', false); } else { welLinkBtn.addClass('disabled').attr('disabled', true); } if (!linkInfo.text) { welLinkText.html(welLinkUrl.val()); }; }).trigger('focus'); welLinkBtn.click(function(event) { welLinkDialog.modal('hide'); //hide and createLink (ie9+) callback(welLinkUrl.val()); event.preventDefault(); }); }).on('hidden.bs.modal', function(e) { welLinkUrl.off('keyup'); welLinkBtn.off('click'); welLinkDialog.off('shown.bs.modal hidden.bs.modal'); }).modal('show'); }; this.showHelpDialog = function(welDialog) { welDialog.find('.note-help-dialog').modal('show'); }; }; /** * EventHandler * * handle mouse & key event on note */ var EventHandler = function() { var editor = new Editor(); var toolbar = new Toolbar(), popover = new Popover(); var handle = new Handle(), dialog = new Dialog(); var key = { BACKSPACE: 8, TAB: 9, ENTER: 13, SPACE: 32, NUM0: 48, NUM1: 49, NUM6: 54, NUM7: 55, NUM8: 56, B: 66, E: 69, I: 73, J: 74, K: 75, L: 76, R: 82, S: 83, U: 85, Y: 89, Z: 90, SLASH: 191, LEFTBRACKET: 219, BACKSLACH: 220, RIGHTBRACKET: 221 }; // makeLayoutInfo from editor's descendant node. var makeLayoutInfo = function(descendant) { var welEditor = $(descendant).closest('.note-editor'); return { editor: function() { return welEditor; }, toolbar: function() { return welEditor.find('.note-toolbar'); }, editable: function() { return welEditor.find('.note-editable'); }, codeable: function() { return welEditor.find('.note-codeable'); }, statusbar: function() { return welEditor.find('.note-statusbar'); }, popover: function() { return welEditor.find('.note-popover'); }, handle: function() { return welEditor.find('.note-handle'); }, dialog: function() { return welEditor.find('.note-dialog'); } }; }; var hKeydown = function(event) { var bCmd = bMac ? event.metaKey : event.ctrlKey, bShift = event.shiftKey, keyCode = event.keyCode; // optimize var bExecCmd = (bCmd || bShift || keyCode === key.TAB); var oLayoutInfo = (bExecCmd) ? makeLayoutInfo(event.target) : null; if (keyCode === key.TAB && oLayoutInfo.editable().data('tabsize')) { editor.tab(oLayoutInfo.editable()); } else if (bCmd && ((bShift && keyCode === key.Z) || keyCode === key.Y)) { editor.redo(oLayoutInfo.editable()); } else if (bCmd && keyCode === key.Z) { editor.undo(oLayoutInfo.editable()); } else if (bCmd && keyCode === key.B) { editor.bold(oLayoutInfo.editable()); } else if (bCmd && keyCode === key.I) { editor.italic(oLayoutInfo.editable()); } else if (bCmd && keyCode === key.U) { editor.underline(oLayoutInfo.editable()); } else if (bCmd && bShift && keyCode === key.S) { editor.strikethrough(oLayoutInfo.editable()); } else if (bCmd && keyCode === key.BACKSLACH) { editor.removeFormat(oLayoutInfo.editable()); } else if (bCmd && keyCode === key.K) { editor.setLinkDialog(oLayoutInfo.editable(), function(linkInfo, cb) { dialog.showLinkDialog(oLayoutInfo.dialog(), linkInfo, cb); }); } else if (bCmd && keyCode === key.SLASH) { dialog.showHelpDialog(oLayoutInfo.dialog()); } else if (bCmd && bShift && keyCode === key.L) { editor.justifyLeft(oLayoutInfo.editable()); } else if (bCmd && bShift && keyCode === key.E) { editor.justifyCenter(oLayoutInfo.editable()); } else if (bCmd && bShift && keyCode === key.R) { editor.justifyRight(oLayoutInfo.editable()); } else if (bCmd && bShift && keyCode === key.J) { editor.justifyFull(oLayoutInfo.editable()); } else if (bCmd && bShift && keyCode === key.NUM7) { editor.insertUnorderedList(oLayoutInfo.editable()); } else if (bCmd && bShift && keyCode === key.NUM8) { editor.insertOrderedList(oLayoutInfo.editable()); } else if (bCmd && keyCode === key.LEFTBRACKET) { editor.outdent(oLayoutInfo.editable()); } else if (bCmd && keyCode === key.RIGHTBRACKET) { editor.indent(oLayoutInfo.editable()); } else if (bCmd && keyCode === key.NUM0) { // formatBlock Paragraph editor.formatBlock(oLayoutInfo.editable(), 'P'); } else if (bCmd && (key.NUM1 <= keyCode && keyCode <= key.NUM6)) { var sHeading = 'H' + String.fromCharCode(keyCode); // H1~H6 editor.formatBlock(oLayoutInfo.editable(), sHeading); } else if (bCmd && keyCode === key.ENTER) { editor.insertHorizontalRule(oLayoutInfo.editable()); } else { if (keyCode === key.BACKSPACE || keyCode === key.ENTER || keyCode === key.SPACE) { editor.recordUndo(makeLayoutInfo(event.target).editable()); } return; // not matched } event.preventDefault(); //prevent default event for FF }; var insertImages = function(welEditable, files) { welEditable.trigger('focus'); $.each(files, function(idx, file) { var fileReader = new FileReader; fileReader.onload = function(event) { editor.insertImage(welEditable, event.target.result); // sURL }; fileReader.readAsDataURL(file); }); }; var hDropImage = function(event) { var dataTransfer = event.originalEvent.dataTransfer; if (dataTransfer && dataTransfer.files) { var oLayoutInfo = makeLayoutInfo(event.currentTarget || event.target); insertImages(oLayoutInfo.editable(), dataTransfer.files); } event.stopPropagation(); event.preventDefault(); }; var hMousedown = function(event) { //preventDefault Selection for FF, IE8+ if (dom.isImg(event.target)) { event.preventDefault(); }; }; var hToolbarAndPopoverUpdate = function(event) { var oLayoutInfo = makeLayoutInfo(event.currentTarget || event.target); var oStyle = editor.currentStyle(event.target); if (!oStyle) { return; } toolbar.update(oLayoutInfo.toolbar(), oStyle); popover.update(oLayoutInfo.popover(), oStyle); handle.update(oLayoutInfo.handle(), oStyle); }; var hScroll = function(event) { var oLayoutInfo = makeLayoutInfo(event.currentTarget || event.target); //hide popover and handle when scrolled popover.hide(oLayoutInfo.popover()); handle.hide(oLayoutInfo.handle()); }; var hHandleMousedown = function(event) { if (dom.isControlSizing(event.target)) { var oLayoutInfo = makeLayoutInfo(event.target), welHandle = oLayoutInfo.handle(), welPopover = oLayoutInfo.popover(), welEditable = oLayoutInfo.editable(), welEditor = oLayoutInfo.editor(); var elTarget = welHandle.find('.note-control-selection').data('target'), welTarget = $(elTarget); var posStart = welTarget.offset(), scrollTop = $(document).scrollTop(), posDistance; welEditor.on('mousemove', function(event) { posDistance = {x: event.clientX - posStart.left, y: event.clientY - (posStart.top - scrollTop)}; editor.resizeTo(posDistance, welTarget); handle.update(welHandle, {image: elTarget}); popover.update(welPopover, {image: elTarget}); }).on('mouseup', function() { welEditor.off('mousemove').off('mouseup'); }); if (!welTarget.data('ratio')) { // original ratio. welTarget.data('ratio', welTarget.height() / welTarget.width()); } editor.recordUndo(welEditable); event.stopPropagation(); event.preventDefault(); } }; var hToolbarAndPopoverMousedown = function(event) { // prevent default event when insertTable (FF, Webkit) var welBtn = $(event.target).closest('[data-event]'); if (welBtn.length > 0) { event.preventDefault(); } }; var hToolbarAndPopoverClick = function(event) { var welBtn = $(event.target).closest('[data-event]'); if (welBtn.length > 0) { var sEvent = welBtn.attr('data-event'), sValue = welBtn.attr('data-value'); var oLayoutInfo = makeLayoutInfo(event.target); var welDialog = oLayoutInfo.dialog(), welEditable = oLayoutInfo.editable(), welCodeable = oLayoutInfo.codeable(); // before command var elTarget; if ($.inArray(sEvent, ['resize', 'float']) !== -1) { var welHandle = oLayoutInfo.handle(); var welSelection = welHandle.find('.note-control-selection'); elTarget = welSelection.data('target'); } if (editor[sEvent]) { // on command welEditable.trigger('focus'); editor[sEvent](welEditable, sValue, elTarget); } // after command if ($.inArray(sEvent, ['backColor', 'foreColor']) !== -1) { toolbar.updateRecentColor(welBtn[0], sEvent, sValue); } else if (sEvent === 'showLinkDialog') { // popover to dialog editor.setLinkDialog(welEditable, function(linkInfo, cb) { dialog.showLinkDialog(welDialog, linkInfo, cb); }); } else if (sEvent === 'showImageDialog') { dialog.showImageDialog(welDialog, hDropImage, function(files) { insertImages(welEditable, files); }); } else if (sEvent === 'showHelpDialog') { dialog.showHelpDialog(welDialog); } else if (sEvent === 'fullscreen') { var welEditor = oLayoutInfo.editor(); welEditor.toggleClass('fullscreen'); var welToolbar = oLayoutInfo.toolbar(); var hResizeFullscreen = function() { var nHeight = $(window).height() - welToolbar.outerHeight(); welEditable.css('height', nHeight); } var bFullscreen = welEditor.hasClass('fullscreen'); if (bFullscreen) { welEditable.data('orgHeight', welEditable.css('height')); $(window).resize(hResizeFullscreen).trigger('resize'); } else { welEditable.css('height', welEditable.data('orgHeight')); $(window).off('resize'); } toolbar.updateFullscreen(welToolbar, bFullscreen); } else if (sEvent === 'codeview') { var welEditor = oLayoutInfo.editor(), welToolbar = oLayoutInfo.toolbar(); welEditor.toggleClass('codeview'); var bCodeview = welEditor.hasClass('codeview') if (bCodeview) { welCodeable.val(welEditable.html()); welCodeable.height(welEditable.height()); toolbar.disable(welToolbar); welCodeable.focus(); } else { welEditable.html(welCodeable.val()); welEditable.height(welCodeable.height()); toolbar.enable(welToolbar); welEditable.focus(); } toolbar.updateCodeview(oLayoutInfo.toolbar(), bCodeview); } hToolbarAndPopoverUpdate(event); } }; var EDITABLE_PADDING = 24; var hStatusbarMousedown = function(event) { var welDocument = $(document); var oLayoutInfo = makeLayoutInfo(event.target); var welEditable = oLayoutInfo.editable(), welCodeable = oLayoutInfo.codeable(); var nEditableTop = welEditable.offset().top - welDocument.scrollTop(); var hMousemove = function(event) { welEditable.height(event.clientY - (nEditableTop + EDITABLE_PADDING)); }; var hMouseup = function() { welDocument.unbind('mousemove', hMousemove) .unbind('mouseup', hMouseup); } welDocument.mousemove(hMousemove).mouseup(hMouseup); event.stopPropagation(); event.preventDefault(); }; var PX_PER_EM = 18; var hDimensionPickerMove = function(event) { var welPicker = $(event.target.parentNode); // target is mousecatcher var welDimensionDisplay = welPicker.next(); var welCatcher = welPicker.find('.note-dimension-picker-mousecatcher'); var welHighlighted = welPicker.find('.note-dimension-picker-highlighted'); var welUnhighlighted = welPicker.find('.note-dimension-picker-unhighlighted'); var posOffset; if (event.offsetX === undefined) { // HTML5 with jQuery - e.offsetX is undefined in Firefox var posCatcher = $(event.target).offset(); posOffset = {x: event.pageX - posCatcher.left, y: event.pageY - posCatcher.top}; } else { posOffset = {x: event.offsetX, y: event.offsetY}; } var dim = {c: Math.ceil(posOffset.x / PX_PER_EM) || 1, r: Math.ceil(posOffset.y / PX_PER_EM) || 1}; welHighlighted.css({ width: dim.c +'em', height: dim.r + 'em' }); welCatcher.attr('data-value', dim.c + 'x' + dim.r); if (3 < dim.c && dim.c < 10) { // 5~10 welUnhighlighted.css({ width: dim.c + 1 + 'em'}); } if (3 < dim.r && dim.r < 10) { // 5~10 welUnhighlighted.css({ height: dim.r + 1 + 'em'}); } welDimensionDisplay.html(dim.c + ' x ' + dim.r); }; this.attach = function(oLayoutInfo, options) { oLayoutInfo.editable.on('keydown', hKeydown); oLayoutInfo.editable.on('mousedown', hMousedown); oLayoutInfo.editable.on('keyup mouseup', hToolbarAndPopoverUpdate); oLayoutInfo.editable.on('scroll', hScroll); //TODO: handle Drag point oLayoutInfo.editable.on('dragenter dragover dragleave', false); oLayoutInfo.editable.on('drop', hDropImage); oLayoutInfo.handle.on('mousedown', hHandleMousedown); oLayoutInfo.toolbar.on('click', hToolbarAndPopoverClick); oLayoutInfo.popover.on('click', hToolbarAndPopoverClick); oLayoutInfo.toolbar.on('mousedown', hToolbarAndPopoverMousedown); oLayoutInfo.popover.on('mousedown', hToolbarAndPopoverMousedown); oLayoutInfo.statusbar.on('mousedown', hStatusbarMousedown); //toolbar table dimension var welToolbar = oLayoutInfo.toolbar; var welCatcher = welToolbar.find('.note-dimension-picker-mousecatcher'); welCatcher.on('mousemove', hDimensionPickerMove); // callback // init, enter, !change, !pasteBefore, !pasteAfter, focus, blur, keyup, keydown if (options.onenter) { oLayoutInfo.editable.keypress(function(event) { if (event.keyCode === key.ENTER) { options.onenter(event);} }); } if (options.onfocus) { oLayoutInfo.editable.focus(options.onfocus); } if (options.onblur) { oLayoutInfo.editable.blur(options.onblur); } if (options.onkeyup) { oLayoutInfo.editable.keyup(options.onkeyup); } if (options.onkeydown) { oLayoutInfo.editable.keydown(options.onkeydown); } // TODO: callback for advanced features // autosave, impageUpload, imageUploadError, fileUpload, fileUploadError }; this.dettach = function(oLayoutInfo) { oLayoutInfo.editable.off(); oLayoutInfo.toolbar.off(); oLayoutInfo.handle.off(); oLayoutInfo.popover.off(); }; }; /** * Renderer * * rendering toolbar and editable */ var Renderer = function() { var aToolbarItem = { picture: '<button type="button" class="btn btn-default" title="Picture" data-event="showImageDialog" tabindex="-1"><i class="fa fa-picture-o"></i></button>', link: '<button type="button" class="btn btn-default" title="Link" data-event="showLinkDialog" data-shortcut="Ctrl+K" data-mac-shortcut="⌘+K" tabindex="-1"><i class="fa fa-link"></i></button>', table: '<button type="button" class="btn btn-default dropdown-toggle" title="Table" data-toggle="dropdown" tabindex="-1"><i class="fa fa-table"></i> <span class="caret"></span></button>' + '<ul class="dropdown-menu">' + '<div class="note-dimension-picker">' + '<div class="note-dimension-picker-mousecatcher" data-event="insertTable" data-value="1x1"></div>' + '<div class="note-dimension-picker-highlighted"></div>' + '<div class="note-dimension-picker-unhighlighted"></div>' + '</div>' + '<div class="note-dimension-display"> 1 x 1 </div>' + '</ul>', style: '<button type="button" class="btn btn-default dropdown-toggle" title="Style" data-toggle="dropdown" tabindex="-1"><i class="fa fa-magic"></i> <span class="caret"></span></button>' + '<ul class="dropdown-menu">' + '<li><a data-event="formatBlock" data-value="p">Normal</a></li>' + '<li><a data-event="formatBlock" data-value="blockquote"><blockquote>Quote</blockquote></a></li>' + '<li><a data-event="formatBlock" data-value="pre">Code</a></li>' + '<li><a data-event="formatBlock" data-value="h1"><h1>Header 1</h1></a></li>' + '<li><a data-event="formatBlock" data-value="h2"><h2>Header 2</h2></a></li>' + '<li><a data-event="formatBlock" data-value="h3"><h3>Header 3</h3></a></li>' + '<li><a data-event="formatBlock" data-value="h4"><h4>Header 4</h4></a></li>' + '<li><a data-event="formatBlock" data-value="h5"><h5>Header 5</h5></a></li>' + '<li><a data-event="formatBlock" data-value="h6"><h6>Header 6</h6></a></li>' + '</ul>', fontsize: '<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" title="Font Size" tabindex="-1"><span class="note-current-fontsize">11</span> <b class="caret"></b></button>' + '<ul class="dropdown-menu">' + '<li><a data-event="fontSize" data-value="8"><i class="fa fa-check"></i> 8</a></li>' + '<li><a data-event="fontSize" data-value="9"><i class="fa fa-check"></i> 9</a></li>' + '<li><a data-event="fontSize" data-value="10"><i class="fa fa-check"></i> 10</a></li>' + '<li><a data-event="fontSize" data-value="11"><i class="fa fa-check"></i> 11</a></li>' + '<li><a data-event="fontSize" data-value="12"><i class="fa fa-check"></i> 12</a></li>' + '<li><a data-event="fontSize" data-value="14"><i class="fa fa-check"></i> 14</a></li>' + '<li><a data-event="fontSize" data-value="18"><i class="fa fa-check"></i> 18</a></li>' + '<li><a data-event="fontSize" data-value="24"><i class="fa fa-check"></i> 24</a></li>' + '<li><a data-event="fontSize" data-value="36"><i class="fa fa-check"></i> 36</a></li>' + '</ul>', color: '<button type="button" class="btn btn-default note-recent-color" title="Recent Color" data-event="color" data-value=\'{"backColor":"yellow"}\' tabindex="-1"><i class="fa fa-font" style="color:black;background-color:yellow;"></i></button>' + '<button type="button" class="btn btn-default dropdown-toggle" title="More Color" data-toggle="dropdown" tabindex="-1">' + '<span class="caret"></span>' + '</button>' + '<ul class="dropdown-menu">' + '<li>' + '<div class="btn-group">' + '<div class="note-palette-title">BackColor</div>' + '<div class="note-color-reset" data-event="backColor" data-value="inherit" title="Transparent">Set transparent</div>' + '<div class="note-color-palette" data-target-event="backColor"></div>' + '</div>' + '<div class="btn-group">' + '<div class="note-palette-title">FontColor</div>' + '<div class="note-color-reset" data-event="foreColor" data-value="inherit" title="Reset">Reset to default</div>' + '<div class="note-color-palette" data-target-event="foreColor"></div>' + '</div>' + '</li>' + '</ul>', bold: '<button type="button" class="btn btn-default" title="Bold" data-shortcut="Ctrl+B" data-mac-shortcut="⌘+B" data-event="bold" tabindex="-1"><i class="fa fa-bold"></i></button>', italic: '<button type="button" class="btn btn-default" title="Italic" data-shortcut="Ctrl+I" data-mac-shortcut="⌘+I" data-event="italic" tabindex="-1"><i class="fa fa-italic"></i></button>', underline: '<button type="button" class="btn btn-default" title="Underline" data-shortcut="Ctrl+U" data-mac-shortcut="⌘+U" data-event="underline" tabindex="-1"><i class="fa fa-underline"></i></button>', clear: '<button type="button" class="btn btn-default" title="Remove Font Style" data-shortcut="Ctrl+\\" data-mac-shortcut="⌘+\\" data-event="removeFormat" tabindex="-1"><i class="fa fa-eraser"></i></button>', ul: '<button type="button" class="btn btn-default" title="Unordered list" data-shortcut="Ctrl+Shift+8" data-mac-shortcut="⌘+⇧+7" data-event="insertUnorderedList" tabindex="-1"><i class="fa fa-list-ul"></i></button>', ol: '<button type="button" class="btn btn-default" title="Ordered list" data-shortcut="Ctrl+Shift+7" data-mac-shortcut="⌘+⇧+8" data-event="insertOrderedList" tabindex="-1"><i class="fa fa-list-ol"></i></button>', paragraph: '<button type="button" class="btn btn-default dropdown-toggle" title="Paragraph" data-toggle="dropdown" tabindex="-1"><i class="fa fa-align-left"></i> <span class="caret"></span></button>' + '<ul class="dropdown-menu">' + '<li>' + '<div class="note-align btn-group">' + '<button type="button" class="btn btn-default" title="Align left" data-shortcut="Ctrl+Shift+L" data-mac-shortcut="⌘+⇧+L" data-event="justifyLeft" tabindex="-1"><i class="fa fa-align-left"></i></button>' + '<button type="button" class="btn btn-default" title="Align center" data-shortcut="Ctrl+Shift+E" data-mac-shortcut="⌘+⇧+E" data-event="justifyCenter" tabindex="-1"><i class="fa fa-align-center"></i></button>' + '<button type="button" class="btn btn-default" title="Align right" data-shortcut="Ctrl+Shift+R" data-mac-shortcut="⌘+⇧+R" data-event="justifyRight" tabindex="-1"><i class="fa fa-align-right"></i></button>' + '<button type="button" class="btn btn-default" title="Justify full" data-shortcut="Ctrl+Shift+J" data-mac-shortcut="⌘+⇧+J" data-event="justifyFull" tabindex="-1"><i class="fa fa-align-justify"></i></button>' + '</div>' + '</li>' + '<li>' + '<div class="note-list btn-group">' + '<button type="button" class="btn btn-default" title="Outdent" data-shortcut="Ctrl+[" data-mac-shortcut="⌘+[" data-event="outdent" tabindex="-1"><i class="fa fa-indent-left"></i></button>' + '<button type="button" class="btn btn-default" title="Indent" data-shortcut="Ctrl+]" data-mac-shortcut="⌘+]" data-event="indent" tabindex="-1"><i class="fa fa-indent-right"></i></button>' + '</li>' + '</ul>', height: '<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" title="Line Height" tabindex="-1"><i class="fa fa-text-height"></i>&nbsp; <b class="caret"></b></button>' + '<ul class="dropdown-menu">' + '<li><a data-event="lineHeight" data-value="1.0"><i class="fa fa-check"></i> 1.0</a></li>' + '<li><a data-event="lineHeight" data-value="1.2"><i class="fa fa-check"></i> 1.2</a></li>' + '<li><a data-event="lineHeight" data-value="1.4"><i class="fa fa-check"></i> 1.4</a></li>' + '<li><a data-event="lineHeight" data-value="1.5"><i class="fa fa-check"></i> 1.5</a></li>' + '<li><a data-event="lineHeight" data-value="1.6"><i class="fa fa-check"></i> 1.6</a></li>' + '<li><a data-event="lineHeight" data-value="1.8"><i class="fa fa-check"></i> 1.8</a></li>' + '<li><a data-event="lineHeight" data-value="2.0"><i class="fa fa-check"></i> 2.0</a></li>' + '<li><a data-event="lineHeight" data-value="3.0"><i class="fa fa-check"></i> 3.0</a></li>' + '</ul>', help: '<button type="button" class="btn btn-default" title="Help" data-shortcut="Ctrl+/" data-mac-shortcut="⌘+/" data-event="showHelpDialog" tabindex="-1"><i class="fa fa-question"></i></button>', fullscreen: '<button type="button" class="btn btn-default" title="Full Screen" data-event="fullscreen" tabindex="-1"><i class="fa fa-fullscreen"></i></button>', codeview: '<button type="button" class="btn btn-default" title="Code View" data-event="codeview" tabindex="-1"><i class="fa fa-code"></i></button>' }; var sPopover = '<div class="note-popover">' + '<div class="note-link-popover popover bottom in" style="display: none;">' + '<div class="arrow"></div>' + '<div class="popover-content note-link-content">' + '<a href="http://www.google.com" target="_blank">www.google.com</a>&nbsp;&nbsp;' + '<div class="note-insert btn-group">' + '<button type="button" class="btn btn-default" title="Edit" data-event="showLinkDialog" tabindex="-1"><i class="fa fa-edit"></i></button>' + '<button type="button" class="btn btn-default" title="Unlink" data-event="unlink" tabindex="-1"><i class="fa fa-unlink"></i></button>' + '</div>' + '</div>' + '</div>' + '<div class="note-image-popover popover bottom in" style="display: none;">' + '<div class="arrow"></div>' + '<div class="popover-content note-image-content">' + '<div class="btn-group">' + '<button type="button" class="btn btn-default" title="Resize Full" data-event="resize" data-value="1" tabindex="-1"><i class="fa fa-resize-full"></i></button>' + '<button type="button" class="btn btn-default" title="Resize Half" data-event="resize" data-value="0.5" tabindex="-1">½</button>' + '<button type="button" class="btn btn-default" title="Resize Thrid" data-event="resize" data-value="0.33" tabindex="-1">⅓</button>' + '<button type="button" class="btn btn-default" title="Resize Quarter" data-event="resize" data-value="0.25" tabindex="-1">¼</button>' + '</div>' + '<div class="btn-group">' + '<button type="button" class="btn btn-default" title="Float Left" data-event="float" data-value="left" tabindex="-1"><i class="fa fa-align-left"></i></button>' + '<button type="button" class="btn btn-default" title="Float Right" data-event="float" data-value="right" tabindex="-1"><i class="fa fa-align-right"></i></button>' + '<button type="button" class="btn btn-default" title="Float None" data-event="float" data-value="none" tabindex="-1"><i class="fa fa-reorder"></i></button>' + '</div>' + '</div>' + '</div>' + '</div>'; var sHandle = '<div class="note-handle">' + '<div class="note-control-selection">' + '<div class="note-control-selection-bg"></div>' + '<div class="note-control-holder note-control-nw"></div>' + '<div class="note-control-holder note-control-ne"></div>' + '<div class="note-control-holder note-control-sw"></div>' + '<div class="note-control-sizing note-control-se"></div>' + '<div class="note-control-selection-info"></div>' + '</div>' + '</div>'; var sShortcutText = '<table class="note-shortcut">' + '<thead>' + '<tr><th></th><th>Text formatting</th></tr>' + '</thead>' + '<tbody>' + '<tr><td>⌘ + B</td><td>Toggle Bold</td></tr>' + '<tr><td>⌘ + I</td><td>Toggle Italic</td></tr>' + '<tr><td>⌘ + U</td><td>Toggle Underline</td></tr>' + '<tr><td>⌘ + ⇧ + S</td><td>Toggle Strike</td></tr>' + '<tr><td>⌘ + \\</td><td>Remove Font Style</td></tr>' + '</tr>' + '</tbody>' + '</table>'; var sShortcutAction = '<table class="note-shortcut">' + '<thead>' + '<tr><th></th><th>Action</th></tr>' + '</thead>' + '<tbody>' + '<tr><td>⌘ + Z</td><td>Undo</td></tr>' + '<tr><td>⌘ + ⇧ + Z</td><td>Redo</td></tr>' + '<tr><td>⌘ + ]</td><td>Indent</td></tr>' + '<tr><td>⌘ + [</td><td>Outdent</td></tr>' + '<tr><td>⌘ + K</td><td>Insert Link</td></tr>' + '<tr><td>⌘ + ENTER</td><td>Insert Horizontal Rule</td></tr>' + '</tbody>' + '</table>'; var sShortcutPara = '<table class="note-shortcut">' + '<thead>' + '<tr><th></th><th>Paragraph formatting</th></tr>' + '</thead>' + '<tbody>' + '<tr><td>⌘ + ⇧ + L</td><td>Align Left</td></tr>' + '<tr><td>⌘ + ⇧ + E</td><td>Align Center</td></tr>' + '<tr><td>⌘ + ⇧ + R</td><td>Align Right</td></tr>' + '<tr><td>⌘ + ⇧ + J</td><td>Justify Full</td></tr>' + '<tr><td>⌘ + ⇧ + NUM7</td><td>Ordered List</td></tr>' + '<tr><td>⌘ + ⇧ + NUM8</td><td>Unordered List</td></tr>' + '</tbody>' + '</table>'; var sShortcutStyle = '<table class="note-shortcut">' + '<thead>' + '<tr><th></th><th>Document Style</th></tr>' + '</thead>' + '<tbody>' + '<tr><td>⌘ + NUM0</td><td>Normal Text</td></tr>' + '<tr><td>⌘ + NUM1</td><td>Heading 1</td></tr>' + '<tr><td>⌘ + NUM2</td><td>Heading 2</td></tr>' + '<tr><td>⌘ + NUM3</td><td>Heading 3</td></tr>' + '<tr><td>⌘ + NUM4</td><td>Heading 4</td></tr>' + '<tr><td>⌘ + NUM5</td><td>Heading 5</td></tr>' + '<tr><td>⌘ + NUM6</td><td>Heading 6</td></tr>' + '</tbody>' + '</table>'; var sShortcutTable = '<table class="note-shortcut-layout">' + '<tbody>' + '<tr><td>' + sShortcutAction +'</td><td>' + sShortcutText +'</td></tr>' + '<tr><td>' + sShortcutStyle +'</td><td>' + sShortcutPara +'</td></tr>' + '</tbody>' + '</table>'; var sDialog = '<div class="note-dialog">' + '<div class="note-image-dialog modal" aria-hidden="false">' + '<div class="modal-dialog">' + '<div class="modal-content">' + '<div class="modal-header">' + '<button type="button" class="close" aria-hidden="true" tabindex="-1">×</button>' + '<h4>Insert Image</h4>' + '</div>' + '<div class="modal-body">' + '<div class="row-fluid">' + '<div class="note-dropzone span12">Drag an image here</div>' + '<div>or if you prefer...</div>' + '<input class="note-image-input" type="file" class="note-link-url" type="text" />' + '</div>' + '</div>' + '</div>' + '</div>' + '</div>' + '<div class="note-link-dialog modal" aria-hidden="false">' + '<div class="modal-dialog">' + '<div class="modal-content">' + '<div class="modal-header">' + '<button type="button" class="close" aria-hidden="true" tabindex="-1">×</button>' + '<h4>Edit Link</h4>' + '</div>' + '<div class="modal-body">' + '<div class="row-fluid">' + '<div class="form-group">' + '<label>Text to display</label>' + '<span class="note-link-text form-control input-xlarge uneditable-input" />' + '</div>' + '<div class="form-group">' + '<label>To what URL should this link go?</label>' + '<input class="note-link-url form-control span12" type="text" />' + '</div>' + '</div>' + '</div>' + '<div class="modal-footer">' + '<button href="#" class="btn btn-primary note-link-btn disabled" disabled="disabled">Link</button>' + '</div>' + '</div>' + '</div>' + '</div>' + '<div class="note-help-dialog modal" aria-hidden="false">' + '<div class="modal-dialog">' + '<div class="modal-content">' + '<div class="modal-body">' + '<div class="modal-background">' + '<a class="modal-close pull-right" aria-hidden="true" tabindex="-1">Close</a>' + '<div class="title">Smart shortcuts</div>' + sShortcutTable + '</div>' + '</div>' + '</div>' + '</div>' + '</div>'; // createTooltip var createTooltip = function(welContainer, sPlacement) { welContainer.find('button').each(function(i, elBtn) { var welBtn = $(elBtn); var sShortcut = welBtn.attr(bMac ? 'data-mac-shortcut':'data-shortcut'); if (sShortcut) { welBtn.attr('title', function(i, v) { return v + ' (' + sShortcut + ')'}); } //bootstrap tooltip on btn-group bug: https://github.com/twitter/bootstrap/issues/5687 }).tooltip({container: 'body', placement: sPlacement || 'top'}); }; // pallete colors var aaColor = [ ['#000000', '#424242', '#636363', '#9C9C94', '#CEC6CE', '#EFEFEF', '#EFF7F7', '#FFFFFF'], ['#FF0000', '#FF9C00', '#FFFF00', '#00FF00', '#00FFFF', '#0000FF', '#9C00FF', '#FF00FF'], ['#F7C6CE', '#FFE7CE', '#FFEFC6', '#D6EFD6', '#CEDEE7', '#CEE7F7', '#D6D6E7', '#E7D6DE'], ['#E79C9C', '#FFC69C', '#FFE79C', '#B5D6A5', '#A5C6CE', '#9CC6EF', '#B5A5D6', '#D6A5BD'], ['#E76363', '#F7AD6B', '#FFD663', '#94BD7B', '#73A5AD', '#6BADDE', '#8C7BC6', '#C67BA5'], ['#CE0000', '#E79439', '#EFC631', '#6BA54A', '#4A7B8C', '#3984C6', '#634AA5', '#A54A7B'], ['#9C0000', '#B56308', '#BD9400', '#397B21', '#104A5A', '#085294', '#311873', '#731842'], ['#630000', '#7B3900', '#846300', '#295218', '#083139', '#003163', '#21104A', '#4A1031'] ]; // createPalette var createPalette = function(welContainer) { welContainer.find('.note-color-palette').each(function() { var welPalette = $(this), sEvent = welPalette.attr('data-target-event'); var sPaletteContents = ''; for (var row = 0, szRow = aaColor.length; row < szRow; row++) { var aColor = aaColor[row]; var sLine = '<div>'; for (var col = 0, szCol = aColor.length; col < szCol; col++) { var sColor = aColor[col]; var sButton = ['<button type="button" class="note-color-btn" style="background-color:', sColor, ';" data-event="', sEvent, '" data-value="', sColor, '" title="', sColor, '" data-toggle="button" tabindex="-1"></button>'].join(''); sLine += sButton; } sLine += '</div>'; sPaletteContents += sLine; } welPalette.html(sPaletteContents); }); }; // createLayout var createLayout = this.createLayout = function(welHolder, nHeight, nTabsize, aToolbarSetting) { //already created if (welHolder.next().hasClass('note-editor')) { return; } //01. create Editor var welEditor = $('<div class="note-editor"></div>'); //02. statusbar if (nHeight > 0) { var welStatusbar = $('<div class="note-statusbar"><div class="note-resizebar"><div class="note-icon-bar"></div><div class="note-icon-bar"></div><div class="note-icon-bar"></div></div></div>').prependTo(welEditor); } //03. create Editable var welEditable = $('<div class="note-editable custom-scroll" contentEditable="true"></div>').prependTo(welEditor); if (nHeight) { welEditable.height(nHeight); } if (nTabsize) { welEditable.data('tabsize', nTabsize); } welEditable.html(dom.html(welHolder)); welEditable.data('NoteHistory', new History()); //031. create Codeable var welCodeable = $('<textarea class="note-codeable"></textarea>').prependTo(welEditor); //032. set styleWithCSS for backColor / foreColor clearing with 'inherit'. setTimeout(function() { // protect FF Error: NS_ERROR_FAILURE: Failure //document.execCommand('styleWithCSS', 0, true); try { document.execCommand("styleWithCSS", 0, false); } catch (e) { try { document.execCommand("useCSS", 0, true); } catch (e) { try { document.execCommand('styleWithCSS', false, false); } catch (e) { } } } }); //04. create Toolbar var sToolbar = ''; for (var idx = 0, sz = aToolbarSetting.length; idx < sz; idx ++) { var group = aToolbarSetting[idx]; sToolbar += '<div class="note-' + group[0] + ' btn-group">'; for (var i = 0, szGroup = group[1].length; i < szGroup; i++) { sToolbar += aToolbarItem[group[1][i]]; } sToolbar += '</div>'; }; sToolbar = '<div class="note-toolbar btn-toolbar">' + sToolbar + '</div>'; var welToolbar = $(sToolbar).prependTo(welEditor); createPalette(welToolbar); createTooltip(welToolbar, 'bottom'); //05. create Popover var welPopover = $(sPopover).prependTo(welEditor); createTooltip(welPopover); //06. handle(control selection, ...) $(sHandle).prependTo(welEditor); //07. create Dialog var welDialog = $(sDialog).prependTo(welEditor); welDialog.find('button.close, a.modal-close').click(function(event) { $(this).closest('.modal').modal('hide'); }); //08. Editor/Holder switch welEditor.insertAfter(welHolder); welHolder.hide(); }; // layoutInfoFromHolder var layoutInfoFromHolder = this.layoutInfoFromHolder = function(welHolder) { var welEditor = welHolder.next(); if (!welEditor.hasClass('note-editor')) { return; } return { editor: welEditor, toolbar: welEditor.find('.note-toolbar'), editable: welEditor.find('.note-editable'), statusbar: welEditor.find('.note-statusbar'), popover: welEditor.find('.note-popover'), handle: welEditor.find('.note-handle'), dialog: welEditor.find('.note-dialog') }; }; // removeLayout var removeLayout = this.removeLayout = function(welHolder) { var info = layoutInfoFromHolder(welHolder); if (!info) { return; } welHolder.html(info.editable.html()); info.editor.remove(); welHolder.show(); }; }; var renderer = new Renderer(); var eventHandler = new EventHandler(); /** * extend jquery fn */ $.fn.extend({ // create Editor Layout and attach Key and Mouse Event summernote: function(options) { options = $.extend({ toolbar: [ ['style', ['style']], ['font', ['bold', 'italic', 'underline', 'clear']], ['fontsize', ['fontsize']], ['color', ['color']], ['para', ['ul', 'ol', 'paragraph']], ['height', ['height']], ['table', ['table']], ['insert', ['link', 'picture']], ['view', ['fullscreen', 'codeview']], ['help', ['help']] ] }, options ); this.each(function(idx, elHolder) { var welHolder = $(elHolder); // createLayout with options renderer.createLayout(welHolder, options.height, options.tabsize, options.toolbar); var info = renderer.layoutInfoFromHolder(welHolder); eventHandler.attach(info, options); }); if (this.first() && options.focus) { // focus on first editable element var info = renderer.layoutInfoFromHolder(this.first()); info.editable.focus(); } if (this.length > 0 && options.oninit) { // callback on init options.oninit(); }; }, // get the HTML contents of note or set the HTML contents of note. code: function(sHTML) { //get the HTML contents if (sHTML === undefined) { var welHolder = this.first(); if (welHolder.length == 0) { return; } var info = renderer.layoutInfoFromHolder(welHolder); var bEditable = !!(info && info.editable); return bEditable ? info.editable.html() : welHolder.html(); } // set the HTML contents this.each(function(i, elHolder) { var info = renderer.layoutInfoFromHolder($(elHolder)); if (info && info.editable) { info.editable.html(sHTML); } }); }, // destroy Editor Layout and dettach Key and Mouse Event destroy: function() { this.each(function(idx, elHolder) { var welHolder = $(elHolder); var info = renderer.layoutInfoFromHolder(welHolder); if (!info || !info.editable) { return; } eventHandler.dettach(info); renderer.removeLayout(welHolder); }); }, // inner object for test summernoteInner: function() { return { dom: dom, list: list, func: func, range: range }; } }); })(window.jQuery); // jQuery // Array.prototype.reduce fallback // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce if ('function' !== typeof Array.prototype.reduce) { Array.prototype.reduce = function(callback, opt_initialValue) { 'use strict'; var idx, value, length = this.length >>> 0, isValueSet = false; if (1 < arguments.length) { value = opt_initialValue, isValueSet = true; } for (idx = 0; length > idx; ++idx) { if (this.hasOwnProperty(idx)) { if (isValueSet) { value = callback(value, this[idx], idx, this); } else { value = this[idx], isValueSet = true; } } } if (!isValueSet) { throw new TypeError('Reduce of empty array with no initial value'); } return value; }; }
JavaScript
// Uses AMD or browser globals to create a jQuery plugin. (function (factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else { // Browser globals factory(jQuery); } } (function (jQuery) { var module = { exports: { } }; // Fake component /** * Expose `Emitter`. */ module.exports = Emitter; /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks[event] = this._callbacks[event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ var self = this; this._callbacks = this._callbacks || {}; function on() { self.off(event, on); fn.apply(this, arguments); } fn._off = on; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = function(event, fn){ this._callbacks = this._callbacks || {}; var callbacks = this._callbacks[event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks[event]; return this; } // remove specific handler var i = callbacks.indexOf(fn._off || fn); if (~i) callbacks.splice(i, 1); return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks[event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks[event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; /* # # More info at [www.dropzonejs.com](http://www.dropzonejs.com) # # Copyright (c) 2012, Matias Meno # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # */ (function() { var Dropzone, Em, camelize, contentLoaded, noop, without, __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; }, __slice = [].slice; Em = typeof Emitter !== "undefined" && Emitter !== null ? Emitter : require("emitter"); noop = function() {}; Dropzone = (function(_super) { var extend; __extends(Dropzone, _super); /* This is a list of all available events you can register on a dropzone object. You can register an event handler like this: dropzone.on("dragEnter", function() { }); */ Dropzone.prototype.events = ["drop", "dragstart", "dragend", "dragenter", "dragover", "dragleave", "selectedfiles", "addedfile", "removedfile", "thumbnail", "error", "errormultiple", "processing", "processingmultiple", "uploadprogress", "totaluploadprogress", "sending", "sendingmultiple", "success", "successmultiple", "canceled", "canceledmultiple", "complete", "completemultiple", "reset", "maxfilesexceeded"]; Dropzone.prototype.defaultOptions = { url: null, method: "post", withCredentials: false, parallelUploads: 2, uploadMultiple: false, maxFilesize: 256, paramName: "file", createImageThumbnails: true, maxThumbnailFilesize: 10, thumbnailWidth: 100, thumbnailHeight: 100, maxFiles: null, params: {}, clickable: true, ignoreHiddenFiles: true, acceptedFiles: null, acceptedMimeTypes: null, autoProcessQueue: true, addRemoveLinks: false, previewsContainer: null, dictDefaultMessage: "Drop files here to upload", dictFallbackMessage: "Your browser does not support drag'n'drop file uploads.", dictFallbackText: "Please use the fallback form below to upload your files like in the olden days.", dictFileTooBig: "File is too big ({{filesize}}MB). Max filesize: {{maxFilesize}}MB.", dictInvalidFileType: "You can't upload files of this type.", dictResponseError: "Server responded with {{statusCode}} code.", dictCancelUpload: "Cancel upload", dictCancelUploadConfirmation: "Are you sure you want to cancel this upload?", dictRemoveFile: "Remove file", dictRemoveFileConfirmation: null, dictMaxFilesExceeded: "You can only upload {{maxFiles}} files.", accept: function(file, done) { return done(); }, init: function() { return noop; }, forceFallback: false, fallback: function() { var child, messageElement, span, _i, _len, _ref; this.element.className = "" + this.element.className + " dz-browser-not-supported"; _ref = this.element.getElementsByTagName("div"); for (_i = 0, _len = _ref.length; _i < _len; _i++) { child = _ref[_i]; if (/(^| )dz-message($| )/.test(child.className)) { messageElement = child; child.className = "dz-message"; continue; } } if (!messageElement) { messageElement = Dropzone.createElement("<div class=\"dz-message\"><span></span></div>"); this.element.appendChild(messageElement); } span = messageElement.getElementsByTagName("span")[0]; if (span) { span.textContent = this.options.dictFallbackMessage; } return this.element.appendChild(this.getFallbackForm()); }, resize: function(file) { var info, srcRatio, trgRatio; info = { srcX: 0, srcY: 0, srcWidth: file.width, srcHeight: file.height }; srcRatio = file.width / file.height; trgRatio = this.options.thumbnailWidth / this.options.thumbnailHeight; if (file.height < this.options.thumbnailHeight || file.width < this.options.thumbnailWidth) { info.trgHeight = info.srcHeight; info.trgWidth = info.srcWidth; } else { if (srcRatio > trgRatio) { info.srcHeight = file.height; info.srcWidth = info.srcHeight * trgRatio; } else { info.srcWidth = file.width; info.srcHeight = info.srcWidth / trgRatio; } } info.srcX = (file.width - info.srcWidth) / 2; info.srcY = (file.height - info.srcHeight) / 2; return info; }, /* Those functions register themselves to the events on init and handle all the user interface specific stuff. Overwriting them won't break the upload but can break the way it's displayed. You can overwrite them if you don't like the default behavior. If you just want to add an additional event handler, register it on the dropzone object and don't overwrite those options. */ drop: function(e) { return this.element.classList.remove("dz-drag-hover"); }, dragstart: noop, dragend: function(e) { return this.element.classList.remove("dz-drag-hover"); }, dragenter: function(e) { return this.element.classList.add("dz-drag-hover"); }, dragover: function(e) { return this.element.classList.add("dz-drag-hover"); }, dragleave: function(e) { return this.element.classList.remove("dz-drag-hover"); }, selectedfiles: function(files) { if (this.element === this.previewsContainer) { return this.element.classList.add("dz-started"); } }, reset: function() { return this.element.classList.remove("dz-started"); }, addedfile: function(file) { var _this = this; file.previewElement = Dropzone.createElement(this.options.previewTemplate); file.previewTemplate = file.previewElement; this.previewsContainer.appendChild(file.previewElement); file.previewElement.querySelector("[data-dz-name]").textContent = file.name; file.previewElement.querySelector("[data-dz-size]").innerHTML = this.filesize(file.size); if (this.options.addRemoveLinks) { file._removeLink = Dropzone.createElement("<a class=\"dz-remove\" href=\"javascript:undefined;\">" + this.options.dictRemoveFile + "</a>"); file._removeLink.addEventListener("click", function(e) { e.preventDefault(); e.stopPropagation(); if (file.status === Dropzone.UPLOADING) { return Dropzone.confirm(_this.options.dictCancelUploadConfirmation, function() { return _this.removeFile(file); }); } else { if (_this.options.dictRemoveFileConfirmation) { return Dropzone.confirm(_this.options.dictRemoveFileConfirmation, function() { return _this.removeFile(file); }); } else { return _this.removeFile(file); } } }); file.previewElement.appendChild(file._removeLink); } return this._updateMaxFilesReachedClass(); }, removedfile: function(file) { var _ref; if ((_ref = file.previewElement) != null) { _ref.parentNode.removeChild(file.previewElement); } return this._updateMaxFilesReachedClass(); }, thumbnail: function(file, dataUrl) { var thumbnailElement; file.previewElement.classList.remove("dz-file-preview"); file.previewElement.classList.add("dz-image-preview"); thumbnailElement = file.previewElement.querySelector("[data-dz-thumbnail]"); thumbnailElement.alt = file.name; return thumbnailElement.src = dataUrl; }, error: function(file, message) { file.previewElement.classList.add("dz-error"); return file.previewElement.querySelector("[data-dz-errormessage]").textContent = message; }, errormultiple: noop, processing: function(file) { file.previewElement.classList.add("dz-processing"); if (file._removeLink) { return file._removeLink.textContent = this.options.dictCancelUpload; } }, processingmultiple: noop, uploadprogress: function(file, progress, bytesSent) { return file.previewElement.querySelector("[data-dz-uploadprogress]").style.width = "" + progress + "%"; }, totaluploadprogress: noop, sending: noop, sendingmultiple: noop, success: function(file) { return file.previewElement.classList.add("dz-success"); }, successmultiple: noop, canceled: function(file) { return this.emit("error", file, "Upload canceled."); }, canceledmultiple: noop, complete: function(file) { if (file._removeLink) { return file._removeLink.textContent = this.options.dictRemoveFile; } }, completemultiple: noop, maxfilesexceeded: noop, previewTemplate: "<div class=\"dz-preview dz-file-preview\">\n <div class=\"dz-details\">\n <div class=\"dz-filename\"><span data-dz-name></span></div>\n <div class=\"dz-size\" data-dz-size></div>\n <img data-dz-thumbnail />\n </div>\n <div class=\"dz-progress\"><span class=\"dz-upload\" data-dz-uploadprogress></span></div>\n <div class=\"dz-success-mark\"><span>✔</span></div>\n <div class=\"dz-error-mark\"><span>✘</span></div>\n <div class=\"dz-error-message\"><span data-dz-errormessage></span></div>\n</div>" }; extend = function() { var key, object, objects, target, val, _i, _len; target = arguments[0], objects = 2 <= arguments.length ? __slice.call(arguments, 1) : []; for (_i = 0, _len = objects.length; _i < _len; _i++) { object = objects[_i]; for (key in object) { val = object[key]; target[key] = val; } } return target; }; function Dropzone(element, options) { var elementOptions, fallback, _ref; this.element = element; this.version = Dropzone.version; this.defaultOptions.previewTemplate = this.defaultOptions.previewTemplate.replace(/\n*/g, ""); this.clickableElements = []; this.listeners = []; this.files = []; if (typeof this.element === "string") { this.element = document.querySelector(this.element); } if (!(this.element && (this.element.nodeType != null))) { throw new Error("Invalid dropzone element."); } if (this.element.dropzone) { throw new Error("Dropzone already attached."); } Dropzone.instances.push(this); element.dropzone = this; elementOptions = (_ref = Dropzone.optionsForElement(this.element)) != null ? _ref : {}; this.options = extend({}, this.defaultOptions, elementOptions, options != null ? options : {}); if (this.options.forceFallback || !Dropzone.isBrowserSupported()) { return this.options.fallback.call(this); } if (this.options.url == null) { this.options.url = this.element.getAttribute("action"); } if (!this.options.url) { throw new Error("No URL provided."); } if (this.options.acceptedFiles && this.options.acceptedMimeTypes) { throw new Error("You can't provide both 'acceptedFiles' and 'acceptedMimeTypes'. 'acceptedMimeTypes' is deprecated."); } if (this.options.acceptedMimeTypes) { this.options.acceptedFiles = this.options.acceptedMimeTypes; delete this.options.acceptedMimeTypes; } this.options.method = this.options.method.toUpperCase(); if ((fallback = this.getExistingFallback()) && fallback.parentNode) { fallback.parentNode.removeChild(fallback); } if (this.options.previewsContainer) { this.previewsContainer = Dropzone.getElement(this.options.previewsContainer, "previewsContainer"); } else { this.previewsContainer = this.element; } if (this.options.clickable) { if (this.options.clickable === true) { this.clickableElements = [this.element]; } else { this.clickableElements = Dropzone.getElements(this.options.clickable, "clickable"); } } this.init(); } Dropzone.prototype.getAcceptedFiles = function() { var file, _i, _len, _ref, _results; _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (file.accepted) { _results.push(file); } } return _results; }; Dropzone.prototype.getRejectedFiles = function() { var file, _i, _len, _ref, _results; _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (!file.accepted) { _results.push(file); } } return _results; }; Dropzone.prototype.getQueuedFiles = function() { var file, _i, _len, _ref, _results; _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (file.status === Dropzone.QUEUED) { _results.push(file); } } return _results; }; Dropzone.prototype.getUploadingFiles = function() { var file, _i, _len, _ref, _results; _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (file.status === Dropzone.UPLOADING) { _results.push(file); } } return _results; }; Dropzone.prototype.init = function() { var eventName, noPropagation, setupHiddenFileInput, _i, _len, _ref, _ref1, _this = this; if (this.element.tagName === "form") { this.element.setAttribute("enctype", "multipart/form-data"); } if (this.element.classList.contains("dropzone") && !this.element.querySelector(".dz-message")) { this.element.appendChild(Dropzone.createElement("<div class=\"dz-default dz-message\"><span>" + this.options.dictDefaultMessage + "</span></div>")); } if (this.clickableElements.length) { setupHiddenFileInput = function() { if (_this.hiddenFileInput) { document.body.removeChild(_this.hiddenFileInput); } _this.hiddenFileInput = document.createElement("input"); _this.hiddenFileInput.setAttribute("type", "file"); _this.hiddenFileInput.setAttribute("multiple", "multiple"); if (_this.options.acceptedFiles != null) { _this.hiddenFileInput.setAttribute("accept", _this.options.acceptedFiles); } _this.hiddenFileInput.style.visibility = "hidden"; _this.hiddenFileInput.style.position = "absolute"; _this.hiddenFileInput.style.top = "0"; _this.hiddenFileInput.style.left = "0"; _this.hiddenFileInput.style.height = "0"; _this.hiddenFileInput.style.width = "0"; document.body.appendChild(_this.hiddenFileInput); return _this.hiddenFileInput.addEventListener("change", function() { var files; files = _this.hiddenFileInput.files; if (files.length) { _this.emit("selectedfiles", files); _this.handleFiles(files); } return setupHiddenFileInput(); }); }; setupHiddenFileInput(); } this.URL = (_ref = window.URL) != null ? _ref : window.webkitURL; _ref1 = this.events; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { eventName = _ref1[_i]; this.on(eventName, this.options[eventName]); } this.on("uploadprogress", function() { return _this.updateTotalUploadProgress(); }); this.on("removedfile", function() { return _this.updateTotalUploadProgress(); }); this.on("canceled", function(file) { return _this.emit("complete", file); }); noPropagation = function(e) { e.stopPropagation(); if (e.preventDefault) { return e.preventDefault(); } else { return e.returnValue = false; } }; this.listeners = [ { element: this.element, events: { "dragstart": function(e) { return _this.emit("dragstart", e); }, "dragenter": function(e) { noPropagation(e); return _this.emit("dragenter", e); }, "dragover": function(e) { noPropagation(e); return _this.emit("dragover", e); }, "dragleave": function(e) { return _this.emit("dragleave", e); }, "drop": function(e) { noPropagation(e); return _this.drop(e); }, "dragend": function(e) { return _this.emit("dragend", e); } } } ]; this.clickableElements.forEach(function(clickableElement) { return _this.listeners.push({ element: clickableElement, events: { "click": function(evt) { if ((clickableElement !== _this.element) || (evt.target === _this.element || Dropzone.elementInside(evt.target, _this.element.querySelector(".dz-message")))) { return _this.hiddenFileInput.click(); } } } }); }); this.enable(); return this.options.init.call(this); }; Dropzone.prototype.destroy = function() { var _ref; this.disable(); this.removeAllFiles(true); if ((_ref = this.hiddenFileInput) != null ? _ref.parentNode : void 0) { this.hiddenFileInput.parentNode.removeChild(this.hiddenFileInput); this.hiddenFileInput = null; } return delete this.element.dropzone; }; Dropzone.prototype.updateTotalUploadProgress = function() { var acceptedFiles, file, totalBytes, totalBytesSent, totalUploadProgress, _i, _len, _ref; totalBytesSent = 0; totalBytes = 0; acceptedFiles = this.getAcceptedFiles(); if (acceptedFiles.length) { _ref = this.getAcceptedFiles(); for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; totalBytesSent += file.upload.bytesSent; totalBytes += file.upload.total; } totalUploadProgress = 100 * totalBytesSent / totalBytes; } else { totalUploadProgress = 100; } return this.emit("totaluploadprogress", totalUploadProgress, totalBytes, totalBytesSent); }; Dropzone.prototype.getFallbackForm = function() { var existingFallback, fields, fieldsString, form; if (existingFallback = this.getExistingFallback()) { return existingFallback; } fieldsString = "<div class=\"dz-fallback\">"; if (this.options.dictFallbackText) { fieldsString += "<p>" + this.options.dictFallbackText + "</p>"; } fieldsString += "<input type=\"file\" name=\"" + this.options.paramName + (this.options.uploadMultiple ? "[]" : "") + "\" " + (this.options.uploadMultiple ? 'multiple="multiple"' : void 0) + " /><button type=\"submit\">Upload!</button></div>"; fields = Dropzone.createElement(fieldsString); if (this.element.tagName !== "FORM") { form = Dropzone.createElement("<form action=\"" + this.options.url + "\" enctype=\"multipart/form-data\" method=\"" + this.options.method + "\"></form>"); form.appendChild(fields); } else { this.element.setAttribute("enctype", "multipart/form-data"); this.element.setAttribute("method", this.options.method); } return form != null ? form : fields; }; Dropzone.prototype.getExistingFallback = function() { var fallback, getFallback, tagName, _i, _len, _ref; getFallback = function(elements) { var el, _i, _len; for (_i = 0, _len = elements.length; _i < _len; _i++) { el = elements[_i]; if (/(^| )fallback($| )/.test(el.className)) { return el; } } }; _ref = ["div", "form"]; for (_i = 0, _len = _ref.length; _i < _len; _i++) { tagName = _ref[_i]; if (fallback = getFallback(this.element.getElementsByTagName(tagName))) { return fallback; } } }; Dropzone.prototype.setupEventListeners = function() { var elementListeners, event, listener, _i, _len, _ref, _results; _ref = this.listeners; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { elementListeners = _ref[_i]; _results.push((function() { var _ref1, _results1; _ref1 = elementListeners.events; _results1 = []; for (event in _ref1) { listener = _ref1[event]; _results1.push(elementListeners.element.addEventListener(event, listener, false)); } return _results1; })()); } return _results; }; Dropzone.prototype.removeEventListeners = function() { var elementListeners, event, listener, _i, _len, _ref, _results; _ref = this.listeners; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { elementListeners = _ref[_i]; _results.push((function() { var _ref1, _results1; _ref1 = elementListeners.events; _results1 = []; for (event in _ref1) { listener = _ref1[event]; _results1.push(elementListeners.element.removeEventListener(event, listener, false)); } return _results1; })()); } return _results; }; Dropzone.prototype.disable = function() { var file, _i, _len, _ref, _results; this.clickableElements.forEach(function(element) { return element.classList.remove("dz-clickable"); }); this.removeEventListeners(); _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; _results.push(this.cancelUpload(file)); } return _results; }; Dropzone.prototype.enable = function() { this.clickableElements.forEach(function(element) { return element.classList.add("dz-clickable"); }); return this.setupEventListeners(); }; Dropzone.prototype.filesize = function(size) { var string; if (size >= 100000000000) { size = size / 100000000000; string = "TB"; } else if (size >= 100000000) { size = size / 100000000; string = "GB"; } else if (size >= 100000) { size = size / 100000; string = "MB"; } else if (size >= 100) { size = size / 100; string = "KB"; } else { size = size * 10; string = "b"; } return "<strong>" + (Math.round(size) / 10) + "</strong> " + string; }; Dropzone.prototype._updateMaxFilesReachedClass = function() { if (this.options.maxFiles && this.getAcceptedFiles().length >= this.options.maxFiles) { return this.element.classList.add("dz-max-files-reached"); } else { return this.element.classList.remove("dz-max-files-reached"); } }; Dropzone.prototype.drop = function(e) { var files, items; if (!e.dataTransfer) { return; } this.emit("drop", e); files = e.dataTransfer.files; this.emit("selectedfiles", files); if (files.length) { items = e.dataTransfer.items; if (items && items.length && ((items[0].webkitGetAsEntry != null) || (items[0].getAsEntry != null))) { this.handleItems(items); } else { this.handleFiles(files); } } }; Dropzone.prototype.handleFiles = function(files) { var file, _i, _len, _results; _results = []; for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; _results.push(this.addFile(file)); } return _results; }; Dropzone.prototype.handleItems = function(items) { var entry, item, _i, _len; for (_i = 0, _len = items.length; _i < _len; _i++) { item = items[_i]; if (item.webkitGetAsEntry != null) { entry = item.webkitGetAsEntry(); if (entry.isFile) { this.addFile(item.getAsFile()); } else if (entry.isDirectory) { this.addDirectory(entry, entry.name); } } else { this.addFile(item.getAsFile()); } } }; Dropzone.prototype.accept = function(file, done) { if (file.size > this.options.maxFilesize * 1024 * 1024) { return done(this.options.dictFileTooBig.replace("{{filesize}}", Math.round(file.size / 1024 / 10.24) / 100).replace("{{maxFilesize}}", this.options.maxFilesize)); } else if (!Dropzone.isValidFile(file, this.options.acceptedFiles)) { return done(this.options.dictInvalidFileType); } else if (this.options.maxFiles && this.getAcceptedFiles().length >= this.options.maxFiles) { done(this.options.dictMaxFilesExceeded.replace("{{maxFiles}}", this.options.maxFiles)); return this.emit("maxfilesexceeded", file); } else { return this.options.accept.call(this, file, done); } }; Dropzone.prototype.addFile = function(file) { var _this = this; file.upload = { progress: 0, total: file.size, bytesSent: 0 }; this.files.push(file); file.status = Dropzone.ADDED; this.emit("addedfile", file); if (this.options.createImageThumbnails && file.type.match(/image.*/) && file.size <= this.options.maxThumbnailFilesize * 1024 * 1024) { this.createThumbnail(file); } return this.accept(file, function(error) { if (error) { file.accepted = false; return _this._errorProcessing([file], error); } else { return _this.enqueueFile(file); } }); }; Dropzone.prototype.enqueueFiles = function(files) { var file, _i, _len; for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; this.enqueueFile(file); } return null; }; Dropzone.prototype.enqueueFile = function(file) { var _this = this; file.accepted = true; if (file.status === Dropzone.ADDED) { file.status = Dropzone.QUEUED; if (this.options.autoProcessQueue) { return setTimeout((function() { return _this.processQueue(); }), 1); } } else { throw new Error("This file can't be queued because it has already been processed or was rejected."); } }; Dropzone.prototype.addDirectory = function(entry, path) { var dirReader, entriesReader, _this = this; dirReader = entry.createReader(); entriesReader = function(entries) { var _i, _len; for (_i = 0, _len = entries.length; _i < _len; _i++) { entry = entries[_i]; if (entry.isFile) { entry.file(function(file) { if (_this.options.ignoreHiddenFiles && file.name.substring(0, 1) === '.') { return; } file.fullPath = "" + path + "/" + file.name; return _this.addFile(file); }); } else if (entry.isDirectory) { _this.addDirectory(entry, "" + path + "/" + entry.name); } } }; return dirReader.readEntries(entriesReader, function(error) { return typeof console !== "undefined" && console !== null ? typeof console.log === "function" ? console.log(error) : void 0 : void 0; }); }; Dropzone.prototype.removeFile = function(file) { if (file.status === Dropzone.UPLOADING) { this.cancelUpload(file); } this.files = without(this.files, file); this.emit("removedfile", file); if (this.files.length === 0) { return this.emit("reset"); } }; Dropzone.prototype.removeAllFiles = function(cancelIfNecessary) { var file, _i, _len, _ref; if (cancelIfNecessary == null) { cancelIfNecessary = false; } _ref = this.files.slice(); for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (file.status !== Dropzone.UPLOADING || cancelIfNecessary) { this.removeFile(file); } } return null; }; Dropzone.prototype.createThumbnail = function(file) { var fileReader, _this = this; fileReader = new FileReader; fileReader.onload = function() { var img; img = new Image; img.onload = function() { var canvas, ctx, resizeInfo, thumbnail, _ref, _ref1, _ref2, _ref3; file.width = img.width; file.height = img.height; resizeInfo = _this.options.resize.call(_this, file); if (resizeInfo.trgWidth == null) { resizeInfo.trgWidth = _this.options.thumbnailWidth; } if (resizeInfo.trgHeight == null) { resizeInfo.trgHeight = _this.options.thumbnailHeight; } canvas = document.createElement("canvas"); ctx = canvas.getContext("2d"); canvas.width = resizeInfo.trgWidth; canvas.height = resizeInfo.trgHeight; ctx.drawImage(img, (_ref = resizeInfo.srcX) != null ? _ref : 0, (_ref1 = resizeInfo.srcY) != null ? _ref1 : 0, resizeInfo.srcWidth, resizeInfo.srcHeight, (_ref2 = resizeInfo.trgX) != null ? _ref2 : 0, (_ref3 = resizeInfo.trgY) != null ? _ref3 : 0, resizeInfo.trgWidth, resizeInfo.trgHeight); thumbnail = canvas.toDataURL("image/png"); return _this.emit("thumbnail", file, thumbnail); }; return img.src = fileReader.result; }; return fileReader.readAsDataURL(file); }; Dropzone.prototype.processQueue = function() { var i, parallelUploads, processingLength, queuedFiles; parallelUploads = this.options.parallelUploads; processingLength = this.getUploadingFiles().length; i = processingLength; if (processingLength >= parallelUploads) { return; } queuedFiles = this.getQueuedFiles(); if (!(queuedFiles.length > 0)) { return; } if (this.options.uploadMultiple) { return this.processFiles(queuedFiles.slice(0, parallelUploads - processingLength)); } else { while (i < parallelUploads) { if (!queuedFiles.length) { return; } this.processFile(queuedFiles.shift()); i++; } } }; Dropzone.prototype.processFile = function(file) { return this.processFiles([file]); }; Dropzone.prototype.processFiles = function(files) { var file, _i, _len; for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; file.processing = true; file.status = Dropzone.UPLOADING; this.emit("processing", file); } if (this.options.uploadMultiple) { this.emit("processingmultiple", files); } return this.uploadFiles(files); }; Dropzone.prototype._getFilesWithXhr = function(xhr) { var file, files; return files = (function() { var _i, _len, _ref, _results; _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (file.xhr === xhr) { _results.push(file); } } return _results; }).call(this); }; Dropzone.prototype.cancelUpload = function(file) { var groupedFile, groupedFiles, _i, _j, _len, _len1, _ref; if (file.status === Dropzone.UPLOADING) { groupedFiles = this._getFilesWithXhr(file.xhr); for (_i = 0, _len = groupedFiles.length; _i < _len; _i++) { groupedFile = groupedFiles[_i]; groupedFile.status = Dropzone.CANCELED; } file.xhr.abort(); for (_j = 0, _len1 = groupedFiles.length; _j < _len1; _j++) { groupedFile = groupedFiles[_j]; this.emit("canceled", groupedFile); } if (this.options.uploadMultiple) { this.emit("canceledmultiple", groupedFiles); } } else if ((_ref = file.status) === Dropzone.ADDED || _ref === Dropzone.QUEUED) { file.status = Dropzone.CANCELED; this.emit("canceled", file); if (this.options.uploadMultiple) { this.emit("canceledmultiple", [file]); } } if (this.options.autoProcessQueue) { return this.processQueue(); } }; Dropzone.prototype.uploadFile = function(file) { return this.uploadFiles([file]); }; Dropzone.prototype.uploadFiles = function(files) { var file, formData, handleError, headerName, headerValue, headers, input, inputName, inputType, key, progressObj, response, updateProgress, value, xhr, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref, _ref1, _ref2, _ref3, _this = this; xhr = new XMLHttpRequest(); for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; file.xhr = xhr; } xhr.open(this.options.method, this.options.url, true); xhr.withCredentials = !!this.options.withCredentials; response = null; handleError = function() { var _j, _len1, _results; _results = []; for (_j = 0, _len1 = files.length; _j < _len1; _j++) { file = files[_j]; _results.push(_this._errorProcessing(files, response || _this.options.dictResponseError.replace("{{statusCode}}", xhr.status), xhr)); } return _results; }; updateProgress = function(e) { var allFilesFinished, progress, _j, _k, _l, _len1, _len2, _len3, _results; if (e != null) { progress = 100 * e.loaded / e.total; for (_j = 0, _len1 = files.length; _j < _len1; _j++) { file = files[_j]; file.upload = { progress: progress, total: e.total, bytesSent: e.loaded }; } } else { allFilesFinished = true; progress = 100; for (_k = 0, _len2 = files.length; _k < _len2; _k++) { file = files[_k]; if (!(file.upload.progress === 100 && file.upload.bytesSent === file.upload.total)) { allFilesFinished = false; } file.upload.progress = progress; file.upload.bytesSent = file.upload.total; } if (allFilesFinished) { return; } } _results = []; for (_l = 0, _len3 = files.length; _l < _len3; _l++) { file = files[_l]; _results.push(_this.emit("uploadprogress", file, progress, file.upload.bytesSent)); } return _results; }; xhr.onload = function(e) { var _ref; if (files[0].status === Dropzone.CANCELED) { return; } if (xhr.readyState !== 4) { return; } response = xhr.responseText; if (xhr.getResponseHeader("content-type") && ~xhr.getResponseHeader("content-type").indexOf("application/json")) { try { response = JSON.parse(response); } catch (_error) { e = _error; response = "Invalid JSON response from server."; } } updateProgress(); if (!((200 <= (_ref = xhr.status) && _ref < 300))) { return handleError(); } else { return _this._finished(files, response, e); } }; xhr.onerror = function() { if (files[0].status === Dropzone.CANCELED) { return; } return handleError(); }; progressObj = (_ref = xhr.upload) != null ? _ref : xhr; progressObj.onprogress = updateProgress; headers = { "Accept": "application/json", "Cache-Control": "no-cache", "X-Requested-With": "XMLHttpRequest" }; if (this.options.headers) { extend(headers, this.options.headers); } for (headerName in headers) { headerValue = headers[headerName]; xhr.setRequestHeader(headerName, headerValue); } formData = new FormData(); if (this.options.params) { _ref1 = this.options.params; for (key in _ref1) { value = _ref1[key]; formData.append(key, value); } } for (_j = 0, _len1 = files.length; _j < _len1; _j++) { file = files[_j]; this.emit("sending", file, xhr, formData); } if (this.options.uploadMultiple) { this.emit("sendingmultiple", files, xhr, formData); } if (this.element.tagName === "FORM") { _ref2 = this.element.querySelectorAll("input, textarea, select, button"); for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { input = _ref2[_k]; inputName = input.getAttribute("name"); inputType = input.getAttribute("type"); if (!inputType || ((_ref3 = inputType.toLowerCase()) !== "checkbox" && _ref3 !== "radio") || input.checked) { formData.append(inputName, input.value); } } } for (_l = 0, _len3 = files.length; _l < _len3; _l++) { file = files[_l]; formData.append("" + this.options.paramName + (this.options.uploadMultiple ? "[]" : ""), file, file.name); } return xhr.send(formData); }; Dropzone.prototype._finished = function(files, responseText, e) { var file, _i, _len; for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; file.status = Dropzone.SUCCESS; this.emit("success", file, responseText, e); this.emit("complete", file); } if (this.options.uploadMultiple) { this.emit("successmultiple", files, responseText, e); this.emit("completemultiple", files); } if (this.options.autoProcessQueue) { return this.processQueue(); } }; Dropzone.prototype._errorProcessing = function(files, message, xhr) { var file, _i, _len; for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; file.status = Dropzone.ERROR; this.emit("error", file, message, xhr); this.emit("complete", file); } if (this.options.uploadMultiple) { this.emit("errormultiple", files, message, xhr); this.emit("completemultiple", files); } if (this.options.autoProcessQueue) { return this.processQueue(); } }; return Dropzone; })(Em); Dropzone.version = "3.7.1"; Dropzone.options = {}; Dropzone.optionsForElement = function(element) { if (element.id) { return Dropzone.options[camelize(element.id)]; } else { return void 0; } }; Dropzone.instances = []; Dropzone.forElement = function(element) { if (typeof element === "string") { element = document.querySelector(element); } if ((element != null ? element.dropzone : void 0) == null) { throw new Error("No Dropzone found for given element. This is probably because you're trying to access it before Dropzone had the time to initialize. Use the `init` option to setup any additional observers on your Dropzone."); } return element.dropzone; }; Dropzone.autoDiscover = true; Dropzone.discover = function() { var checkElements, dropzone, dropzones, _i, _len, _results; if (document.querySelectorAll) { dropzones = document.querySelectorAll(".dropzone"); } else { dropzones = []; checkElements = function(elements) { var el, _i, _len, _results; _results = []; for (_i = 0, _len = elements.length; _i < _len; _i++) { el = elements[_i]; if (/(^| )dropzone($| )/.test(el.className)) { _results.push(dropzones.push(el)); } else { _results.push(void 0); } } return _results; }; checkElements(document.getElementsByTagName("div")); checkElements(document.getElementsByTagName("form")); } _results = []; for (_i = 0, _len = dropzones.length; _i < _len; _i++) { dropzone = dropzones[_i]; if (Dropzone.optionsForElement(dropzone) !== false) { _results.push(new Dropzone(dropzone)); } else { _results.push(void 0); } } return _results; }; Dropzone.blacklistedBrowsers = [/opera.*Macintosh.*version\/12/i]; Dropzone.isBrowserSupported = function() { var capableBrowser, regex, _i, _len, _ref; capableBrowser = true; if (window.File && window.FileReader && window.FileList && window.Blob && window.FormData && document.querySelector) { if (!("classList" in document.createElement("a"))) { capableBrowser = false; } else { _ref = Dropzone.blacklistedBrowsers; for (_i = 0, _len = _ref.length; _i < _len; _i++) { regex = _ref[_i]; if (regex.test(navigator.userAgent)) { capableBrowser = false; continue; } } } } else { capableBrowser = false; } return capableBrowser; }; without = function(list, rejectedItem) { var item, _i, _len, _results; _results = []; for (_i = 0, _len = list.length; _i < _len; _i++) { item = list[_i]; if (item !== rejectedItem) { _results.push(item); } } return _results; }; camelize = function(str) { return str.replace(/[\-_](\w)/g, function(match) { return match[1].toUpperCase(); }); }; Dropzone.createElement = function(string) { var div; div = document.createElement("div"); div.innerHTML = string; return div.childNodes[0]; }; Dropzone.elementInside = function(element, container) { if (element === container) { return true; } while (element = element.parentNode) { if (element === container) { return true; } } return false; }; Dropzone.getElement = function(el, name) { var element; if (typeof el === "string") { element = document.querySelector(el); } else if (el.nodeType != null) { element = el; } if (element == null) { throw new Error("Invalid `" + name + "` option provided. Please provide a CSS selector or a plain HTML element."); } return element; }; Dropzone.getElements = function(els, name) { var e, el, elements, _i, _j, _len, _len1, _ref; if (els instanceof Array) { elements = []; try { for (_i = 0, _len = els.length; _i < _len; _i++) { el = els[_i]; elements.push(this.getElement(el, name)); } } catch (_error) { e = _error; elements = null; } } else if (typeof els === "string") { elements = []; _ref = document.querySelectorAll(els); for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) { el = _ref[_j]; elements.push(el); } } else if (els.nodeType != null) { elements = [els]; } if (!((elements != null) && elements.length)) { throw new Error("Invalid `" + name + "` option provided. Please provide a CSS selector, a plain HTML element or a list of those."); } return elements; }; Dropzone.confirm = function(question, accepted, rejected) { if (window.confirm(question)) { return accepted(); } else if (rejected != null) { return rejected(); } }; Dropzone.isValidFile = function(file, acceptedFiles) { var baseMimeType, mimeType, validType, _i, _len; if (!acceptedFiles) { return true; } acceptedFiles = acceptedFiles.split(","); mimeType = file.type; baseMimeType = mimeType.replace(/\/.*$/, ""); for (_i = 0, _len = acceptedFiles.length; _i < _len; _i++) { validType = acceptedFiles[_i]; validType = validType.trim(); if (validType.charAt(0) === ".") { if (file.name.indexOf(validType, file.name.length - validType.length) !== -1) { return true; } } else if (/\/\*$/.test(validType)) { if (baseMimeType === validType.replace(/\/.*$/, "")) { return true; } } else { if (mimeType === validType) { return true; } } } return false; }; if (typeof jQuery !== "undefined" && jQuery !== null) { jQuery.fn.dropzone = function(options) { return this.each(function() { return new Dropzone(this, options); }); }; } if (typeof module !== "undefined" && module !== null) { module.exports = Dropzone; } else { window.Dropzone = Dropzone; } Dropzone.ADDED = "added"; Dropzone.QUEUED = "queued"; Dropzone.ACCEPTED = Dropzone.QUEUED; Dropzone.UPLOADING = "uploading"; Dropzone.PROCESSING = Dropzone.UPLOADING; Dropzone.CANCELED = "canceled"; Dropzone.ERROR = "error"; Dropzone.SUCCESS = "success"; /* # contentloaded.js # # Author: Diego Perini (diego.perini at gmail.com) # Summary: cross-browser wrapper for DOMContentLoaded # Updated: 20101020 # License: MIT # Version: 1.2 # # URL: # http://javascript.nwbox.com/ContentLoaded/ # http://javascript.nwbox.com/ContentLoaded/MIT-LICENSE */ contentLoaded = function(win, fn) { var add, doc, done, init, poll, pre, rem, root, top; done = false; top = true; doc = win.document; root = doc.documentElement; add = (doc.addEventListener ? "addEventListener" : "attachEvent"); rem = (doc.addEventListener ? "removeEventListener" : "detachEvent"); pre = (doc.addEventListener ? "" : "on"); init = function(e) { if (e.type === "readystatechange" && doc.readyState !== "complete") { return; } (e.type === "load" ? win : doc)[rem](pre + e.type, init, false); if (!done && (done = true)) { return fn.call(win, e.type || e); } }; poll = function() { var e; try { root.doScroll("left"); } catch (_error) { e = _error; setTimeout(poll, 50); return; } return init("poll"); }; if (doc.readyState !== "complete") { if (doc.createEventObject && root.doScroll) { try { top = !win.frameElement; } catch (_error) {} if (top) { poll(); } } doc[add](pre + "DOMContentLoaded", init, false); doc[add](pre + "readystatechange", init, false); return win[add](pre + "load", init, false); } }; Dropzone._autoDiscoverFunction = function() { if (Dropzone.autoDiscover) { return Dropzone.discover(); } }; contentLoaded(window, Dropzone._autoDiscoverFunction); }).call(this); return module.exports; }));
JavaScript
;(function(){ /** * Require the given path. * * @param {String} path * @return {Object} exports * @api public */ function require(path, parent, orig) { var resolved = require.resolve(path); // lookup failed if (null == resolved) { orig = orig || path; parent = parent || 'root'; var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); err.path = orig; err.parent = parent; err.require = true; throw err; } var module = require.modules[resolved]; // perform real require() // by invoking the module's // registered function if (!module.exports) { module.exports = {}; module.client = module.component = true; module.call(this, module.exports, require.relative(resolved), module); } return module.exports; } /** * Registered modules. */ require.modules = {}; /** * Registered aliases. */ require.aliases = {}; /** * Resolve `path`. * * Lookup: * * - PATH/index.js * - PATH.js * - PATH * * @param {String} path * @return {String} path or null * @api private */ require.resolve = function(path) { if (path.charAt(0) === '/') path = path.slice(1); var paths = [ path, path + '.js', path + '.json', path + '/index.js', path + '/index.json' ]; for (var i = 0; i < paths.length; i++) { var path = paths[i]; if (require.modules.hasOwnProperty(path)) return path; if (require.aliases.hasOwnProperty(path)) return require.aliases[path]; } }; /** * Normalize `path` relative to the current path. * * @param {String} curr * @param {String} path * @return {String} * @api private */ require.normalize = function(curr, path) { var segs = []; if ('.' != path.charAt(0)) return path; curr = curr.split('/'); path = path.split('/'); for (var i = 0; i < path.length; ++i) { if ('..' == path[i]) { curr.pop(); } else if ('.' != path[i] && '' != path[i]) { segs.push(path[i]); } } return curr.concat(segs).join('/'); }; /** * Register module at `path` with callback `definition`. * * @param {String} path * @param {Function} definition * @api private */ require.register = function(path, definition) { require.modules[path] = definition; }; /** * Alias a module definition. * * @param {String} from * @param {String} to * @api private */ require.alias = function(from, to) { if (!require.modules.hasOwnProperty(from)) { throw new Error('Failed to alias "' + from + '", it does not exist'); } require.aliases[to] = from; }; /** * Return a require function relative to the `parent` path. * * @param {String} parent * @return {Function} * @api private */ require.relative = function(parent) { var p = require.normalize(parent, '..'); /** * lastIndexOf helper. */ function lastIndexOf(arr, obj) { var i = arr.length; while (i--) { if (arr[i] === obj) return i; } return -1; } /** * The relative require() itself. */ function localRequire(path) { var resolved = localRequire.resolve(path); return require(resolved, parent, path); } /** * Resolve relative to the parent. */ localRequire.resolve = function(path) { var c = path.charAt(0); if ('/' == c) return path.slice(1); if ('.' == c) return require.normalize(p, path); // resolve deps by returning // the dep in the nearest "deps" // directory var segs = parent.split('/'); var i = lastIndexOf(segs, 'deps') + 1; if (!i) i = 0; path = segs.slice(0, i + 1).join('/') + '/deps/' + path; return path; }; /** * Check if module is defined at `path`. */ localRequire.exists = function(path) { return require.modules.hasOwnProperty(localRequire.resolve(path)); }; return localRequire; }; require.register("component-emitter/index.js", function(exports, require, module){ /** * Expose `Emitter`. */ module.exports = Emitter; /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks[event] = this._callbacks[event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ var self = this; this._callbacks = this._callbacks || {}; function on() { self.off(event, on); fn.apply(this, arguments); } fn._off = on; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = function(event, fn){ this._callbacks = this._callbacks || {}; var callbacks = this._callbacks[event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks[event]; return this; } // remove specific handler var i = callbacks.indexOf(fn._off || fn); if (~i) callbacks.splice(i, 1); return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks[event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks[event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; }); require.register("dropzone/index.js", function(exports, require, module){ /** * Exposing dropzone */ module.exports = require("./lib/dropzone.js"); }); require.register("dropzone/lib/dropzone.js", function(exports, require, module){ /* # # More info at [www.dropzonejs.com](http://www.dropzonejs.com) # # Copyright (c) 2012, Matias Meno # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # */ (function() { var Dropzone, Em, camelize, contentLoaded, noop, without, __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; }, __slice = [].slice; Em = typeof Emitter !== "undefined" && Emitter !== null ? Emitter : require("emitter"); noop = function() {}; Dropzone = (function(_super) { var extend; __extends(Dropzone, _super); /* This is a list of all available events you can register on a dropzone object. You can register an event handler like this: dropzone.on("dragEnter", function() { }); */ Dropzone.prototype.events = ["drop", "dragstart", "dragend", "dragenter", "dragover", "dragleave", "selectedfiles", "addedfile", "removedfile", "thumbnail", "error", "errormultiple", "processing", "processingmultiple", "uploadprogress", "totaluploadprogress", "sending", "sendingmultiple", "success", "successmultiple", "canceled", "canceledmultiple", "complete", "completemultiple", "reset", "maxfilesexceeded"]; Dropzone.prototype.defaultOptions = { url: null, method: "post", withCredentials: false, parallelUploads: 2, uploadMultiple: false, maxFilesize: 256, paramName: "file", createImageThumbnails: true, maxThumbnailFilesize: 10, thumbnailWidth: 100, thumbnailHeight: 100, maxFiles: null, params: {}, clickable: true, ignoreHiddenFiles: true, acceptedFiles: null, acceptedMimeTypes: null, autoProcessQueue: true, addRemoveLinks: false, previewsContainer: null, dictDefaultMessage: "Drop files here to upload", dictFallbackMessage: "Your browser does not support drag'n'drop file uploads.", dictFallbackText: "Please use the fallback form below to upload your files like in the olden days.", dictFileTooBig: "File is too big ({{filesize}}MB). Max filesize: {{maxFilesize}}MB.", dictInvalidFileType: "You can't upload files of this type.", dictResponseError: "Server responded with {{statusCode}} code.", dictCancelUpload: "Cancel upload", dictCancelUploadConfirmation: "Are you sure you want to cancel this upload?", dictRemoveFile: "Remove file", dictRemoveFileConfirmation: null, dictMaxFilesExceeded: "You can only upload {{maxFiles}} files.", accept: function(file, done) { return done(); }, init: function() { return noop; }, forceFallback: false, fallback: function() { var child, messageElement, span, _i, _len, _ref; this.element.className = "" + this.element.className + " dz-browser-not-supported"; _ref = this.element.getElementsByTagName("div"); for (_i = 0, _len = _ref.length; _i < _len; _i++) { child = _ref[_i]; if (/(^| )dz-message($| )/.test(child.className)) { messageElement = child; child.className = "dz-message"; continue; } } if (!messageElement) { messageElement = Dropzone.createElement("<div class=\"dz-message\"><span></span></div>"); this.element.appendChild(messageElement); } span = messageElement.getElementsByTagName("span")[0]; if (span) { span.textContent = this.options.dictFallbackMessage; } return this.element.appendChild(this.getFallbackForm()); }, resize: function(file) { var info, srcRatio, trgRatio; info = { srcX: 0, srcY: 0, srcWidth: file.width, srcHeight: file.height }; srcRatio = file.width / file.height; trgRatio = this.options.thumbnailWidth / this.options.thumbnailHeight; if (file.height < this.options.thumbnailHeight || file.width < this.options.thumbnailWidth) { info.trgHeight = info.srcHeight; info.trgWidth = info.srcWidth; } else { if (srcRatio > trgRatio) { info.srcHeight = file.height; info.srcWidth = info.srcHeight * trgRatio; } else { info.srcWidth = file.width; info.srcHeight = info.srcWidth / trgRatio; } } info.srcX = (file.width - info.srcWidth) / 2; info.srcY = (file.height - info.srcHeight) / 2; return info; }, /* Those functions register themselves to the events on init and handle all the user interface specific stuff. Overwriting them won't break the upload but can break the way it's displayed. You can overwrite them if you don't like the default behavior. If you just want to add an additional event handler, register it on the dropzone object and don't overwrite those options. */ drop: function(e) { return this.element.classList.remove("dz-drag-hover"); }, dragstart: noop, dragend: function(e) { return this.element.classList.remove("dz-drag-hover"); }, dragenter: function(e) { return this.element.classList.add("dz-drag-hover"); }, dragover: function(e) { return this.element.classList.add("dz-drag-hover"); }, dragleave: function(e) { return this.element.classList.remove("dz-drag-hover"); }, selectedfiles: function(files) { if (this.element === this.previewsContainer) { return this.element.classList.add("dz-started"); } }, reset: function() { return this.element.classList.remove("dz-started"); }, addedfile: function(file) { var _this = this; file.previewElement = Dropzone.createElement(this.options.previewTemplate); file.previewTemplate = file.previewElement; this.previewsContainer.appendChild(file.previewElement); file.previewElement.querySelector("[data-dz-name]").textContent = file.name; file.previewElement.querySelector("[data-dz-size]").innerHTML = this.filesize(file.size); if (this.options.addRemoveLinks) { file._removeLink = Dropzone.createElement("<a class=\"btn btn-sm btn-danger btn-block\" href=\"javascript:undefined;\">" + this.options.dictRemoveFile + "</a>"); file._removeLink.addEventListener("click", function(e) { e.preventDefault(); e.stopPropagation(); if (file.status === Dropzone.UPLOADING) { return Dropzone.confirm(_this.options.dictCancelUploadConfirmation, function() { return _this.removeFile(file); }); } else { if (_this.options.dictRemoveFileConfirmation) { return Dropzone.confirm(_this.options.dictRemoveFileConfirmation, function() { return _this.removeFile(file); }); } else { return _this.removeFile(file); } } }); file.previewElement.appendChild(file._removeLink); } return this._updateMaxFilesReachedClass(); }, removedfile: function(file) { var _ref; if ((_ref = file.previewElement) != null) { _ref.parentNode.removeChild(file.previewElement); } return this._updateMaxFilesReachedClass(); }, thumbnail: function(file, dataUrl) { var thumbnailElement; file.previewElement.classList.remove("dz-file-preview"); file.previewElement.classList.add("dz-image-preview"); thumbnailElement = file.previewElement.querySelector("[data-dz-thumbnail]"); thumbnailElement.alt = file.name; return thumbnailElement.src = dataUrl; }, error: function(file, message) { file.previewElement.classList.add("dz-error"); return file.previewElement.querySelector("[data-dz-errormessage]").textContent = message; }, errormultiple: noop, processing: function(file) { file.previewElement.classList.add("dz-processing"); if (file._removeLink) { return file._removeLink.textContent = this.options.dictCancelUpload; } }, processingmultiple: noop, uploadprogress: function(file, progress, bytesSent) { return file.previewElement.querySelector("[data-dz-uploadprogress]").style.width = "" + progress + "%"; }, totaluploadprogress: noop, sending: noop, sendingmultiple: noop, success: function(file) { return file.previewElement.classList.add("dz-success"); }, successmultiple: noop, canceled: function(file) { return this.emit("error", file, "Upload canceled."); }, canceledmultiple: noop, complete: function(file) { if (file._removeLink) { return file._removeLink.textContent = this.options.dictRemoveFile; } }, completemultiple: noop, maxfilesexceeded: noop, previewTemplate: "<div class=\"dz-preview dz-file-preview\">\n <div class=\"dz-details\">\n <div class=\"dz-filename\"><span data-dz-name></span></div>\n <div class=\"dz-size\" data-dz-size></div>\n <img data-dz-thumbnail />\n </div>\n <div class=\"dz-progress\"><span class=\"dz-upload\" data-dz-uploadprogress></span></div>\n <div class=\"dz-success-mark\"><span>✔</span></div>\n <div class=\"dz-error-mark\"><span><i class=\"fa fa-times\"></i></span></div>\n <div class=\"dz-error-message\"><span data-dz-errormessage></span></div>\n</div>" }; extend = function() { var key, object, objects, target, val, _i, _len; target = arguments[0], objects = 2 <= arguments.length ? __slice.call(arguments, 1) : []; for (_i = 0, _len = objects.length; _i < _len; _i++) { object = objects[_i]; for (key in object) { val = object[key]; target[key] = val; } } return target; }; function Dropzone(element, options) { var elementOptions, fallback, _ref; this.element = element; this.version = Dropzone.version; this.defaultOptions.previewTemplate = this.defaultOptions.previewTemplate.replace(/\n*/g, ""); this.clickableElements = []; this.listeners = []; this.files = []; if (typeof this.element === "string") { this.element = document.querySelector(this.element); } if (!(this.element && (this.element.nodeType != null))) { throw new Error("Invalid dropzone element."); } if (this.element.dropzone) { throw new Error("Dropzone already attached."); } Dropzone.instances.push(this); element.dropzone = this; elementOptions = (_ref = Dropzone.optionsForElement(this.element)) != null ? _ref : {}; this.options = extend({}, this.defaultOptions, elementOptions, options != null ? options : {}); if (this.options.forceFallback || !Dropzone.isBrowserSupported()) { return this.options.fallback.call(this); } if (this.options.url == null) { this.options.url = this.element.getAttribute("action"); } if (!this.options.url) { throw new Error("No URL provided."); } if (this.options.acceptedFiles && this.options.acceptedMimeTypes) { throw new Error("You can't provide both 'acceptedFiles' and 'acceptedMimeTypes'. 'acceptedMimeTypes' is deprecated."); } if (this.options.acceptedMimeTypes) { this.options.acceptedFiles = this.options.acceptedMimeTypes; delete this.options.acceptedMimeTypes; } this.options.method = this.options.method.toUpperCase(); if ((fallback = this.getExistingFallback()) && fallback.parentNode) { fallback.parentNode.removeChild(fallback); } if (this.options.previewsContainer) { this.previewsContainer = Dropzone.getElement(this.options.previewsContainer, "previewsContainer"); } else { this.previewsContainer = this.element; } if (this.options.clickable) { if (this.options.clickable === true) { this.clickableElements = [this.element]; } else { this.clickableElements = Dropzone.getElements(this.options.clickable, "clickable"); } } this.init(); } Dropzone.prototype.getAcceptedFiles = function() { var file, _i, _len, _ref, _results; _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (file.accepted) { _results.push(file); } } return _results; }; Dropzone.prototype.getRejectedFiles = function() { var file, _i, _len, _ref, _results; _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (!file.accepted) { _results.push(file); } } return _results; }; Dropzone.prototype.getQueuedFiles = function() { var file, _i, _len, _ref, _results; _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (file.status === Dropzone.QUEUED) { _results.push(file); } } return _results; }; Dropzone.prototype.getUploadingFiles = function() { var file, _i, _len, _ref, _results; _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (file.status === Dropzone.UPLOADING) { _results.push(file); } } return _results; }; Dropzone.prototype.init = function() { var eventName, noPropagation, setupHiddenFileInput, _i, _len, _ref, _ref1, _this = this; if (this.element.tagName === "form") { this.element.setAttribute("enctype", "multipart/form-data"); } if (this.element.classList.contains("dropzone") && !this.element.querySelector(".dz-message")) { this.element.appendChild(Dropzone.createElement("<div class=\"dz-default dz-message\"><span>" + this.options.dictDefaultMessage + "</span></div>")); } if (this.clickableElements.length) { setupHiddenFileInput = function() { if (_this.hiddenFileInput) { document.body.removeChild(_this.hiddenFileInput); } _this.hiddenFileInput = document.createElement("input"); _this.hiddenFileInput.setAttribute("type", "file"); _this.hiddenFileInput.setAttribute("multiple", "multiple"); if (_this.options.acceptedFiles != null) { _this.hiddenFileInput.setAttribute("accept", _this.options.acceptedFiles); } _this.hiddenFileInput.style.visibility = "hidden"; _this.hiddenFileInput.style.position = "absolute"; _this.hiddenFileInput.style.top = "0"; _this.hiddenFileInput.style.left = "0"; _this.hiddenFileInput.style.height = "0"; _this.hiddenFileInput.style.width = "0"; document.body.appendChild(_this.hiddenFileInput); return _this.hiddenFileInput.addEventListener("change", function() { var files; files = _this.hiddenFileInput.files; if (files.length) { _this.emit("selectedfiles", files); _this.handleFiles(files); } return setupHiddenFileInput(); }); }; setupHiddenFileInput(); } this.URL = (_ref = window.URL) != null ? _ref : window.webkitURL; _ref1 = this.events; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { eventName = _ref1[_i]; this.on(eventName, this.options[eventName]); } this.on("uploadprogress", function() { return _this.updateTotalUploadProgress(); }); this.on("removedfile", function() { return _this.updateTotalUploadProgress(); }); this.on("canceled", function(file) { return _this.emit("complete", file); }); noPropagation = function(e) { e.stopPropagation(); if (e.preventDefault) { return e.preventDefault(); } else { return e.returnValue = false; } }; this.listeners = [ { element: this.element, events: { "dragstart": function(e) { return _this.emit("dragstart", e); }, "dragenter": function(e) { noPropagation(e); return _this.emit("dragenter", e); }, "dragover": function(e) { noPropagation(e); return _this.emit("dragover", e); }, "dragleave": function(e) { return _this.emit("dragleave", e); }, "drop": function(e) { noPropagation(e); return _this.drop(e); }, "dragend": function(e) { return _this.emit("dragend", e); } } } ]; this.clickableElements.forEach(function(clickableElement) { return _this.listeners.push({ element: clickableElement, events: { "click": function(evt) { if ((clickableElement !== _this.element) || (evt.target === _this.element || Dropzone.elementInside(evt.target, _this.element.querySelector(".dz-message")))) { return _this.hiddenFileInput.click(); } } } }); }); this.enable(); return this.options.init.call(this); }; Dropzone.prototype.destroy = function() { var _ref; this.disable(); this.removeAllFiles(true); if ((_ref = this.hiddenFileInput) != null ? _ref.parentNode : void 0) { this.hiddenFileInput.parentNode.removeChild(this.hiddenFileInput); this.hiddenFileInput = null; } return delete this.element.dropzone; }; Dropzone.prototype.updateTotalUploadProgress = function() { var acceptedFiles, file, totalBytes, totalBytesSent, totalUploadProgress, _i, _len, _ref; totalBytesSent = 0; totalBytes = 0; acceptedFiles = this.getAcceptedFiles(); if (acceptedFiles.length) { _ref = this.getAcceptedFiles(); for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; totalBytesSent += file.upload.bytesSent; totalBytes += file.upload.total; } totalUploadProgress = 100 * totalBytesSent / totalBytes; } else { totalUploadProgress = 100; } return this.emit("totaluploadprogress", totalUploadProgress, totalBytes, totalBytesSent); }; Dropzone.prototype.getFallbackForm = function() { var existingFallback, fields, fieldsString, form; if (existingFallback = this.getExistingFallback()) { return existingFallback; } fieldsString = "<div class=\"dz-fallback\">"; if (this.options.dictFallbackText) { fieldsString += "<p>" + this.options.dictFallbackText + "</p>"; } fieldsString += "<input type=\"file\" name=\"" + this.options.paramName + (this.options.uploadMultiple ? "[]" : "") + "\" " + (this.options.uploadMultiple ? 'multiple="multiple"' : void 0) + " /><button type=\"submit\">Upload!</button></div>"; fields = Dropzone.createElement(fieldsString); if (this.element.tagName !== "FORM") { form = Dropzone.createElement("<form action=\"" + this.options.url + "\" enctype=\"multipart/form-data\" method=\"" + this.options.method + "\"></form>"); form.appendChild(fields); } else { this.element.setAttribute("enctype", "multipart/form-data"); this.element.setAttribute("method", this.options.method); } return form != null ? form : fields; }; Dropzone.prototype.getExistingFallback = function() { var fallback, getFallback, tagName, _i, _len, _ref; getFallback = function(elements) { var el, _i, _len; for (_i = 0, _len = elements.length; _i < _len; _i++) { el = elements[_i]; if (/(^| )fallback($| )/.test(el.className)) { return el; } } }; _ref = ["div", "form"]; for (_i = 0, _len = _ref.length; _i < _len; _i++) { tagName = _ref[_i]; if (fallback = getFallback(this.element.getElementsByTagName(tagName))) { return fallback; } } }; Dropzone.prototype.setupEventListeners = function() { var elementListeners, event, listener, _i, _len, _ref, _results; _ref = this.listeners; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { elementListeners = _ref[_i]; _results.push((function() { var _ref1, _results1; _ref1 = elementListeners.events; _results1 = []; for (event in _ref1) { listener = _ref1[event]; _results1.push(elementListeners.element.addEventListener(event, listener, false)); } return _results1; })()); } return _results; }; Dropzone.prototype.removeEventListeners = function() { var elementListeners, event, listener, _i, _len, _ref, _results; _ref = this.listeners; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { elementListeners = _ref[_i]; _results.push((function() { var _ref1, _results1; _ref1 = elementListeners.events; _results1 = []; for (event in _ref1) { listener = _ref1[event]; _results1.push(elementListeners.element.removeEventListener(event, listener, false)); } return _results1; })()); } return _results; }; Dropzone.prototype.disable = function() { var file, _i, _len, _ref, _results; this.clickableElements.forEach(function(element) { return element.classList.remove("dz-clickable"); }); this.removeEventListeners(); _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; _results.push(this.cancelUpload(file)); } return _results; }; Dropzone.prototype.enable = function() { this.clickableElements.forEach(function(element) { return element.classList.add("dz-clickable"); }); return this.setupEventListeners(); }; Dropzone.prototype.filesize = function(size) { var string; if (size >= 100000000000) { size = size / 100000000000; string = "TB"; } else if (size >= 100000000) { size = size / 100000000; string = "GB"; } else if (size >= 100000) { size = size / 100000; string = "MB"; } else if (size >= 100) { size = size / 100; string = "KB"; } else { size = size * 10; string = "b"; } return "<strong>" + (Math.round(size) / 10) + "</strong> " + string; }; Dropzone.prototype._updateMaxFilesReachedClass = function() { if (this.options.maxFiles && this.getAcceptedFiles().length >= this.options.maxFiles) { return this.element.classList.add("dz-max-files-reached"); } else { return this.element.classList.remove("dz-max-files-reached"); } }; Dropzone.prototype.drop = function(e) { var files, items; if (!e.dataTransfer) { return; } this.emit("drop", e); files = e.dataTransfer.files; this.emit("selectedfiles", files); if (files.length) { items = e.dataTransfer.items; if (items && items.length && ((items[0].webkitGetAsEntry != null) || (items[0].getAsEntry != null))) { this.handleItems(items); } else { this.handleFiles(files); } } }; Dropzone.prototype.handleFiles = function(files) { var file, _i, _len, _results; _results = []; for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; _results.push(this.addFile(file)); } return _results; }; Dropzone.prototype.handleItems = function(items) { var entry, item, _i, _len; for (_i = 0, _len = items.length; _i < _len; _i++) { item = items[_i]; if (item.webkitGetAsEntry != null) { entry = item.webkitGetAsEntry(); if (entry.isFile) { this.addFile(item.getAsFile()); } else if (entry.isDirectory) { this.addDirectory(entry, entry.name); } } else { this.addFile(item.getAsFile()); } } }; Dropzone.prototype.accept = function(file, done) { if (file.size > this.options.maxFilesize * 1024 * 1024) { return done(this.options.dictFileTooBig.replace("{{filesize}}", Math.round(file.size / 1024 / 10.24) / 100).replace("{{maxFilesize}}", this.options.maxFilesize)); } else if (!Dropzone.isValidFile(file, this.options.acceptedFiles)) { return done(this.options.dictInvalidFileType); } else if (this.options.maxFiles && this.getAcceptedFiles().length >= this.options.maxFiles) { done(this.options.dictMaxFilesExceeded.replace("{{maxFiles}}", this.options.maxFiles)); return this.emit("maxfilesexceeded", file); } else { return this.options.accept.call(this, file, done); } }; Dropzone.prototype.addFile = function(file) { var _this = this; file.upload = { progress: 0, total: file.size, bytesSent: 0 }; this.files.push(file); file.status = Dropzone.ADDED; this.emit("addedfile", file); if (this.options.createImageThumbnails && file.type.match(/image.*/) && file.size <= this.options.maxThumbnailFilesize * 1024 * 1024) { this.createThumbnail(file); } return this.accept(file, function(error) { if (error) { file.accepted = false; return _this._errorProcessing([file], error); } else { return _this.enqueueFile(file); } }); }; Dropzone.prototype.enqueueFiles = function(files) { var file, _i, _len; for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; this.enqueueFile(file); } return null; }; Dropzone.prototype.enqueueFile = function(file) { var _this = this; file.accepted = true; if (file.status === Dropzone.ADDED) { file.status = Dropzone.QUEUED; if (this.options.autoProcessQueue) { return setTimeout((function() { return _this.processQueue(); }), 1); } } else { throw new Error("This file can't be queued because it has already been processed or was rejected."); } }; Dropzone.prototype.addDirectory = function(entry, path) { var dirReader, entriesReader, _this = this; dirReader = entry.createReader(); entriesReader = function(entries) { var _i, _len; for (_i = 0, _len = entries.length; _i < _len; _i++) { entry = entries[_i]; if (entry.isFile) { entry.file(function(file) { if (_this.options.ignoreHiddenFiles && file.name.substring(0, 1) === '.') { return; } file.fullPath = "" + path + "/" + file.name; return _this.addFile(file); }); } else if (entry.isDirectory) { _this.addDirectory(entry, "" + path + "/" + entry.name); } } }; return dirReader.readEntries(entriesReader, function(error) { return typeof console !== "undefined" && console !== null ? typeof console.log === "function" ? console.log(error) : void 0 : void 0; }); }; Dropzone.prototype.removeFile = function(file) { if (file.status === Dropzone.UPLOADING) { this.cancelUpload(file); } this.files = without(this.files, file); this.emit("removedfile", file); if (this.files.length === 0) { return this.emit("reset"); } }; Dropzone.prototype.removeAllFiles = function(cancelIfNecessary) { var file, _i, _len, _ref; if (cancelIfNecessary == null) { cancelIfNecessary = false; } _ref = this.files.slice(); for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (file.status !== Dropzone.UPLOADING || cancelIfNecessary) { this.removeFile(file); } } return null; }; Dropzone.prototype.createThumbnail = function(file) { var fileReader, _this = this; fileReader = new FileReader; fileReader.onload = function() { var img; img = new Image; img.onload = function() { var canvas, ctx, resizeInfo, thumbnail, _ref, _ref1, _ref2, _ref3; file.width = img.width; file.height = img.height; resizeInfo = _this.options.resize.call(_this, file); if (resizeInfo.trgWidth == null) { resizeInfo.trgWidth = _this.options.thumbnailWidth; } if (resizeInfo.trgHeight == null) { resizeInfo.trgHeight = _this.options.thumbnailHeight; } canvas = document.createElement("canvas"); ctx = canvas.getContext("2d"); canvas.width = resizeInfo.trgWidth; canvas.height = resizeInfo.trgHeight; ctx.drawImage(img, (_ref = resizeInfo.srcX) != null ? _ref : 0, (_ref1 = resizeInfo.srcY) != null ? _ref1 : 0, resizeInfo.srcWidth, resizeInfo.srcHeight, (_ref2 = resizeInfo.trgX) != null ? _ref2 : 0, (_ref3 = resizeInfo.trgY) != null ? _ref3 : 0, resizeInfo.trgWidth, resizeInfo.trgHeight); thumbnail = canvas.toDataURL("image/png"); return _this.emit("thumbnail", file, thumbnail); }; return img.src = fileReader.result; }; return fileReader.readAsDataURL(file); }; Dropzone.prototype.processQueue = function() { var i, parallelUploads, processingLength, queuedFiles; parallelUploads = this.options.parallelUploads; processingLength = this.getUploadingFiles().length; i = processingLength; if (processingLength >= parallelUploads) { return; } queuedFiles = this.getQueuedFiles(); if (!(queuedFiles.length > 0)) { return; } if (this.options.uploadMultiple) { return this.processFiles(queuedFiles.slice(0, parallelUploads - processingLength)); } else { while (i < parallelUploads) { if (!queuedFiles.length) { return; } this.processFile(queuedFiles.shift()); i++; } } }; Dropzone.prototype.processFile = function(file) { return this.processFiles([file]); }; Dropzone.prototype.processFiles = function(files) { var file, _i, _len; for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; file.processing = true; file.status = Dropzone.UPLOADING; this.emit("processing", file); } if (this.options.uploadMultiple) { this.emit("processingmultiple", files); } return this.uploadFiles(files); }; Dropzone.prototype._getFilesWithXhr = function(xhr) { var file, files; return files = (function() { var _i, _len, _ref, _results; _ref = this.files; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { file = _ref[_i]; if (file.xhr === xhr) { _results.push(file); } } return _results; }).call(this); }; Dropzone.prototype.cancelUpload = function(file) { var groupedFile, groupedFiles, _i, _j, _len, _len1, _ref; if (file.status === Dropzone.UPLOADING) { groupedFiles = this._getFilesWithXhr(file.xhr); for (_i = 0, _len = groupedFiles.length; _i < _len; _i++) { groupedFile = groupedFiles[_i]; groupedFile.status = Dropzone.CANCELED; } file.xhr.abort(); for (_j = 0, _len1 = groupedFiles.length; _j < _len1; _j++) { groupedFile = groupedFiles[_j]; this.emit("canceled", groupedFile); } if (this.options.uploadMultiple) { this.emit("canceledmultiple", groupedFiles); } } else if ((_ref = file.status) === Dropzone.ADDED || _ref === Dropzone.QUEUED) { file.status = Dropzone.CANCELED; this.emit("canceled", file); if (this.options.uploadMultiple) { this.emit("canceledmultiple", [file]); } } if (this.options.autoProcessQueue) { return this.processQueue(); } }; Dropzone.prototype.uploadFile = function(file) { return this.uploadFiles([file]); }; Dropzone.prototype.uploadFiles = function(files) { var file, formData, handleError, headerName, headerValue, headers, input, inputName, inputType, key, progressObj, response, updateProgress, value, xhr, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref, _ref1, _ref2, _ref3, _this = this; xhr = new XMLHttpRequest(); for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; file.xhr = xhr; } xhr.open(this.options.method, this.options.url, true); xhr.withCredentials = !!this.options.withCredentials; response = null; handleError = function() { var _j, _len1, _results; _results = []; for (_j = 0, _len1 = files.length; _j < _len1; _j++) { file = files[_j]; _results.push(_this._errorProcessing(files, response || _this.options.dictResponseError.replace("{{statusCode}}", xhr.status), xhr)); } return _results; }; updateProgress = function(e) { var allFilesFinished, progress, _j, _k, _l, _len1, _len2, _len3, _results; if (e != null) { progress = 100 * e.loaded / e.total; for (_j = 0, _len1 = files.length; _j < _len1; _j++) { file = files[_j]; file.upload = { progress: progress, total: e.total, bytesSent: e.loaded }; } } else { allFilesFinished = true; progress = 100; for (_k = 0, _len2 = files.length; _k < _len2; _k++) { file = files[_k]; if (!(file.upload.progress === 100 && file.upload.bytesSent === file.upload.total)) { allFilesFinished = false; } file.upload.progress = progress; file.upload.bytesSent = file.upload.total; } if (allFilesFinished) { return; } } _results = []; for (_l = 0, _len3 = files.length; _l < _len3; _l++) { file = files[_l]; _results.push(_this.emit("uploadprogress", file, progress, file.upload.bytesSent)); } return _results; }; xhr.onload = function(e) { var _ref; if (files[0].status === Dropzone.CANCELED) { return; } if (xhr.readyState !== 4) { return; } response = xhr.responseText; if (xhr.getResponseHeader("content-type") && ~xhr.getResponseHeader("content-type").indexOf("application/json")) { try { response = JSON.parse(response); } catch (_error) { e = _error; response = "Invalid JSON response from server."; } } updateProgress(); if (!((200 <= (_ref = xhr.status) && _ref < 300))) { return handleError(); } else { return _this._finished(files, response, e); } }; xhr.onerror = function() { if (files[0].status === Dropzone.CANCELED) { return; } return handleError(); }; progressObj = (_ref = xhr.upload) != null ? _ref : xhr; progressObj.onprogress = updateProgress; headers = { "Accept": "application/json", "Cache-Control": "no-cache", "X-Requested-With": "XMLHttpRequest" }; if (this.options.headers) { extend(headers, this.options.headers); } for (headerName in headers) { headerValue = headers[headerName]; xhr.setRequestHeader(headerName, headerValue); } formData = new FormData(); if (this.options.params) { _ref1 = this.options.params; for (key in _ref1) { value = _ref1[key]; formData.append(key, value); } } for (_j = 0, _len1 = files.length; _j < _len1; _j++) { file = files[_j]; this.emit("sending", file, xhr, formData); } if (this.options.uploadMultiple) { this.emit("sendingmultiple", files, xhr, formData); } if (this.element.tagName === "FORM") { _ref2 = this.element.querySelectorAll("input, textarea, select, button"); for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { input = _ref2[_k]; inputName = input.getAttribute("name"); inputType = input.getAttribute("type"); if (!inputType || ((_ref3 = inputType.toLowerCase()) !== "checkbox" && _ref3 !== "radio") || input.checked) { formData.append(inputName, input.value); } } } for (_l = 0, _len3 = files.length; _l < _len3; _l++) { file = files[_l]; formData.append("" + this.options.paramName + (this.options.uploadMultiple ? "[]" : ""), file, file.name); } return xhr.send(formData); }; Dropzone.prototype._finished = function(files, responseText, e) { var file, _i, _len; for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; file.status = Dropzone.SUCCESS; this.emit("success", file, responseText, e); this.emit("complete", file); } if (this.options.uploadMultiple) { this.emit("successmultiple", files, responseText, e); this.emit("completemultiple", files); } if (this.options.autoProcessQueue) { return this.processQueue(); } }; Dropzone.prototype._errorProcessing = function(files, message, xhr) { var file, _i, _len; for (_i = 0, _len = files.length; _i < _len; _i++) { file = files[_i]; file.status = Dropzone.ERROR; this.emit("error", file, message, xhr); this.emit("complete", file); } if (this.options.uploadMultiple) { this.emit("errormultiple", files, message, xhr); this.emit("completemultiple", files); } if (this.options.autoProcessQueue) { return this.processQueue(); } }; return Dropzone; })(Em); Dropzone.version = "3.7.1"; Dropzone.options = {}; Dropzone.optionsForElement = function(element) { if (element.id) { return Dropzone.options[camelize(element.id)]; } else { return void 0; } }; Dropzone.instances = []; Dropzone.forElement = function(element) { if (typeof element === "string") { element = document.querySelector(element); } if ((element != null ? element.dropzone : void 0) == null) { throw new Error("No Dropzone found for given element. This is probably because you're trying to access it before Dropzone had the time to initialize. Use the `init` option to setup any additional observers on your Dropzone."); } return element.dropzone; }; Dropzone.autoDiscover = true; Dropzone.discover = function() { var checkElements, dropzone, dropzones, _i, _len, _results; if (document.querySelectorAll) { dropzones = document.querySelectorAll(".dropzone"); } else { dropzones = []; checkElements = function(elements) { var el, _i, _len, _results; _results = []; for (_i = 0, _len = elements.length; _i < _len; _i++) { el = elements[_i]; if (/(^| )dropzone($| )/.test(el.className)) { _results.push(dropzones.push(el)); } else { _results.push(void 0); } } return _results; }; checkElements(document.getElementsByTagName("div")); checkElements(document.getElementsByTagName("form")); } _results = []; for (_i = 0, _len = dropzones.length; _i < _len; _i++) { dropzone = dropzones[_i]; if (Dropzone.optionsForElement(dropzone) !== false) { _results.push(new Dropzone(dropzone)); } else { _results.push(void 0); } } return _results; }; Dropzone.blacklistedBrowsers = [/opera.*Macintosh.*version\/12/i]; Dropzone.isBrowserSupported = function() { var capableBrowser, regex, _i, _len, _ref; capableBrowser = true; if (window.File && window.FileReader && window.FileList && window.Blob && window.FormData && document.querySelector) { if (!("classList" in document.createElement("a"))) { capableBrowser = false; } else { _ref = Dropzone.blacklistedBrowsers; for (_i = 0, _len = _ref.length; _i < _len; _i++) { regex = _ref[_i]; if (regex.test(navigator.userAgent)) { capableBrowser = false; continue; } } } } else { capableBrowser = false; } return capableBrowser; }; without = function(list, rejectedItem) { var item, _i, _len, _results; _results = []; for (_i = 0, _len = list.length; _i < _len; _i++) { item = list[_i]; if (item !== rejectedItem) { _results.push(item); } } return _results; }; camelize = function(str) { return str.replace(/[\-_](\w)/g, function(match) { return match[1].toUpperCase(); }); }; Dropzone.createElement = function(string) { var div; div = document.createElement("div"); div.innerHTML = string; return div.childNodes[0]; }; Dropzone.elementInside = function(element, container) { if (element === container) { return true; } while (element = element.parentNode) { if (element === container) { return true; } } return false; }; Dropzone.getElement = function(el, name) { var element; if (typeof el === "string") { element = document.querySelector(el); } else if (el.nodeType != null) { element = el; } if (element == null) { throw new Error("Invalid `" + name + "` option provided. Please provide a CSS selector or a plain HTML element."); } return element; }; Dropzone.getElements = function(els, name) { var e, el, elements, _i, _j, _len, _len1, _ref; if (els instanceof Array) { elements = []; try { for (_i = 0, _len = els.length; _i < _len; _i++) { el = els[_i]; elements.push(this.getElement(el, name)); } } catch (_error) { e = _error; elements = null; } } else if (typeof els === "string") { elements = []; _ref = document.querySelectorAll(els); for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) { el = _ref[_j]; elements.push(el); } } else if (els.nodeType != null) { elements = [els]; } if (!((elements != null) && elements.length)) { throw new Error("Invalid `" + name + "` option provided. Please provide a CSS selector, a plain HTML element or a list of those."); } return elements; }; Dropzone.confirm = function(question, accepted, rejected) { if (window.confirm(question)) { return accepted(); } else if (rejected != null) { return rejected(); } }; Dropzone.isValidFile = function(file, acceptedFiles) { var baseMimeType, mimeType, validType, _i, _len; if (!acceptedFiles) { return true; } acceptedFiles = acceptedFiles.split(","); mimeType = file.type; baseMimeType = mimeType.replace(/\/.*$/, ""); for (_i = 0, _len = acceptedFiles.length; _i < _len; _i++) { validType = acceptedFiles[_i]; validType = validType.trim(); if (validType.charAt(0) === ".") { if (file.name.indexOf(validType, file.name.length - validType.length) !== -1) { return true; } } else if (/\/\*$/.test(validType)) { if (baseMimeType === validType.replace(/\/.*$/, "")) { return true; } } else { if (mimeType === validType) { return true; } } } return false; }; if (typeof jQuery !== "undefined" && jQuery !== null) { jQuery.fn.dropzone = function(options) { return this.each(function() { return new Dropzone(this, options); }); }; } if (typeof module !== "undefined" && module !== null) { module.exports = Dropzone; } else { window.Dropzone = Dropzone; } Dropzone.ADDED = "added"; Dropzone.QUEUED = "queued"; Dropzone.ACCEPTED = Dropzone.QUEUED; Dropzone.UPLOADING = "uploading"; Dropzone.PROCESSING = Dropzone.UPLOADING; Dropzone.CANCELED = "canceled"; Dropzone.ERROR = "error"; Dropzone.SUCCESS = "success"; /* # contentloaded.js # # Author: Diego Perini (diego.perini at gmail.com) # Summary: cross-browser wrapper for DOMContentLoaded # Updated: 20101020 # License: MIT # Version: 1.2 # # URL: # http://javascript.nwbox.com/ContentLoaded/ # http://javascript.nwbox.com/ContentLoaded/MIT-LICENSE */ contentLoaded = function(win, fn) { var add, doc, done, init, poll, pre, rem, root, top; done = false; top = true; doc = win.document; root = doc.documentElement; add = (doc.addEventListener ? "addEventListener" : "attachEvent"); rem = (doc.addEventListener ? "removeEventListener" : "detachEvent"); pre = (doc.addEventListener ? "" : "on"); init = function(e) { if (e.type === "readystatechange" && doc.readyState !== "complete") { return; } (e.type === "load" ? win : doc)[rem](pre + e.type, init, false); if (!done && (done = true)) { return fn.call(win, e.type || e); } }; poll = function() { var e; try { root.doScroll("left"); } catch (_error) { e = _error; setTimeout(poll, 50); return; } return init("poll"); }; if (doc.readyState !== "complete") { if (doc.createEventObject && root.doScroll) { try { top = !win.frameElement; } catch (_error) {} if (top) { poll(); } } doc[add](pre + "DOMContentLoaded", init, false); doc[add](pre + "readystatechange", init, false); return win[add](pre + "load", init, false); } }; Dropzone._autoDiscoverFunction = function() { if (Dropzone.autoDiscover) { return Dropzone.discover(); } }; contentLoaded(window, Dropzone._autoDiscoverFunction); }).call(this); }); require.alias("component-emitter/index.js", "dropzone/deps/emitter/index.js"); require.alias("component-emitter/index.js", "emitter/index.js"); if (typeof exports == "object") { module.exports = require("dropzone"); } else if (typeof define == "function" && define.amd) { define(function(){ return require("dropzone"); }); } else { this["Dropzone"] = require("dropzone"); }})();
JavaScript
/*! X-editable - v1.5.0 * In-place editing with Twitter Bootstrap, jQuery UI or pure jQuery * http://github.com/vitalets/x-editable * Copyright (c) 2013 Vitaliy Potapov; Licensed MIT */ /** Form with single input element, two buttons and two states: normal/loading. Applied as jQuery method to DIV tag (not to form tag!). This is because form can be in loading state when spinner shown. Editableform is linked with one of input types, e.g. 'text', 'select' etc. @class editableform @uses text @uses textarea **/ (function ($) { "use strict"; var EditableForm = function (div, options) { this.options = $.extend({}, $.fn.editableform.defaults, options); this.$div = $(div); //div, containing form. Not form tag. Not editable-element. if(!this.options.scope) { this.options.scope = this; } //nothing shown after init }; EditableForm.prototype = { constructor: EditableForm, initInput: function() { //called once //take input from options (as it is created in editable-element) this.input = this.options.input; //set initial value //todo: may be add check: typeof str === 'string' ? this.value = this.input.str2value(this.options.value); //prerender: get input.$input this.input.prerender(); }, initTemplate: function() { this.$form = $($.fn.editableform.template); }, initButtons: function() { var $btn = this.$form.find('.editable-buttons'); $btn.append($.fn.editableform.buttons); if(this.options.showbuttons === 'bottom') { $btn.addClass('editable-buttons-bottom'); } }, /** Renders editableform @method render **/ render: function() { //init loader this.$loading = $($.fn.editableform.loading); this.$div.empty().append(this.$loading); //init form template and buttons this.initTemplate(); if(this.options.showbuttons) { this.initButtons(); } else { this.$form.find('.editable-buttons').remove(); } //show loading state this.showLoading(); //flag showing is form now saving value to server. //It is needed to wait when closing form. this.isSaving = false; /** Fired when rendering starts @event rendering @param {Object} event event object **/ this.$div.triggerHandler('rendering'); //init input this.initInput(); //append input to form this.$form.find('div.editable-input').append(this.input.$tpl); //append form to container this.$div.append(this.$form); //render input $.when(this.input.render()) .then($.proxy(function () { //setup input to submit automatically when no buttons shown if(!this.options.showbuttons) { this.input.autosubmit(); } //attach 'cancel' handler this.$form.find('.editable-cancel').click($.proxy(this.cancel, this)); if(this.input.error) { this.error(this.input.error); this.$form.find('.editable-submit').attr('disabled', true); this.input.$input.attr('disabled', true); //prevent form from submitting this.$form.submit(function(e){ e.preventDefault(); }); } else { this.error(false); this.input.$input.removeAttr('disabled'); this.$form.find('.editable-submit').removeAttr('disabled'); var value = (this.value === null || this.value === undefined || this.value === '') ? this.options.defaultValue : this.value; this.input.value2input(value); //attach submit handler this.$form.submit($.proxy(this.submit, this)); } /** Fired when form is rendered @event rendered @param {Object} event event object **/ this.$div.triggerHandler('rendered'); this.showForm(); //call postrender method to perform actions required visibility of form if(this.input.postrender) { this.input.postrender(); } }, this)); }, cancel: function() { /** Fired when form was cancelled by user @event cancel @param {Object} event event object **/ this.$div.triggerHandler('cancel'); }, showLoading: function() { var w, h; if(this.$form) { //set loading size equal to form w = this.$form.outerWidth(); h = this.$form.outerHeight(); if(w) { this.$loading.width(w); } if(h) { this.$loading.height(h); } this.$form.hide(); } else { //stretch loading to fill container width w = this.$loading.parent().width(); if(w) { this.$loading.width(w); } } this.$loading.show(); }, showForm: function(activate) { this.$loading.hide(); this.$form.show(); if(activate !== false) { this.input.activate(); } /** Fired when form is shown @event show @param {Object} event event object **/ this.$div.triggerHandler('show'); }, error: function(msg) { var $group = this.$form.find('.control-group'), $block = this.$form.find('.editable-error-block'), lines; if(msg === false) { $group.removeClass($.fn.editableform.errorGroupClass); $block.removeClass($.fn.editableform.errorBlockClass).empty().hide(); } else { //convert newline to <br> for more pretty error display if(msg) { lines = msg.split("\n"); for (var i = 0; i < lines.length; i++) { lines[i] = $('<div>').text(lines[i]).html(); } msg = lines.join('<br>'); } $group.addClass($.fn.editableform.errorGroupClass); $block.addClass($.fn.editableform.errorBlockClass).html(msg).show(); } }, submit: function(e) { e.stopPropagation(); e.preventDefault(); var error, newValue = this.input.input2value(); //get new value from input //validation if (error = this.validate(newValue)) { this.error(error); this.showForm(); return; } //if value not changed --> trigger 'nochange' event and return /*jslint eqeq: true*/ if (!this.options.savenochange && this.input.value2str(newValue) == this.input.value2str(this.value)) { /*jslint eqeq: false*/ /** Fired when value not changed but form is submitted. Requires savenochange = false. @event nochange @param {Object} event event object **/ this.$div.triggerHandler('nochange'); return; } //convert value for submitting to server var submitValue = this.input.value2submit(newValue); this.isSaving = true; //sending data to server $.when(this.save(submitValue)) .done($.proxy(function(response) { this.isSaving = false; //run success callback var res = typeof this.options.success === 'function' ? this.options.success.call(this.options.scope, response, newValue) : null; //if success callback returns false --> keep form open and do not activate input if(res === false) { this.error(false); this.showForm(false); return; } //if success callback returns string --> keep form open, show error and activate input if(typeof res === 'string') { this.error(res); this.showForm(); return; } //if success callback returns object like {newValue: <something>} --> use that value instead of submitted //it is usefull if you want to chnage value in url-function if(res && typeof res === 'object' && res.hasOwnProperty('newValue')) { newValue = res.newValue; } //clear error message this.error(false); this.value = newValue; /** Fired when form is submitted @event save @param {Object} event event object @param {Object} params additional params @param {mixed} params.newValue raw new value @param {mixed} params.submitValue submitted value as string @param {Object} params.response ajax response @example $('#form-div').on('save'), function(e, params){ if(params.newValue === 'username') {...} }); **/ this.$div.triggerHandler('save', {newValue: newValue, submitValue: submitValue, response: response}); }, this)) .fail($.proxy(function(xhr) { this.isSaving = false; var msg; if(typeof this.options.error === 'function') { msg = this.options.error.call(this.options.scope, xhr, newValue); } else { msg = typeof xhr === 'string' ? xhr : xhr.responseText || xhr.statusText || 'Unknown error!'; } this.error(msg); this.showForm(); }, this)); }, save: function(submitValue) { //try parse composite pk defined as json string in data-pk this.options.pk = $.fn.editableutils.tryParseJson(this.options.pk, true); var pk = (typeof this.options.pk === 'function') ? this.options.pk.call(this.options.scope) : this.options.pk, /* send on server in following cases: 1. url is function 2. url is string AND (pk defined OR send option = always) */ send = !!(typeof this.options.url === 'function' || (this.options.url && ((this.options.send === 'always') || (this.options.send === 'auto' && pk !== null && pk !== undefined)))), params; if (send) { //send to server this.showLoading(); //standard params params = { name: this.options.name || '', value: submitValue, pk: pk }; //additional params if(typeof this.options.params === 'function') { params = this.options.params.call(this.options.scope, params); } else { //try parse json in single quotes (from data-params attribute) this.options.params = $.fn.editableutils.tryParseJson(this.options.params, true); $.extend(params, this.options.params); } if(typeof this.options.url === 'function') { //user's function return this.options.url.call(this.options.scope, params); } else { //send ajax to server and return deferred object return $.ajax($.extend({ url : this.options.url, data : params, type : 'POST' }, this.options.ajaxOptions)); } } }, validate: function (value) { if (value === undefined) { value = this.value; } if (typeof this.options.validate === 'function') { return this.options.validate.call(this.options.scope, value); } }, option: function(key, value) { if(key in this.options) { this.options[key] = value; } if(key === 'value') { this.setValue(value); } //do not pass option to input as it is passed in editable-element }, setValue: function(value, convertStr) { if(convertStr) { this.value = this.input.str2value(value); } else { this.value = value; } //if form is visible, update input if(this.$form && this.$form.is(':visible')) { this.input.value2input(this.value); } } }; /* Initialize editableform. Applied to jQuery object. @method $().editableform(options) @params {Object} options @example var $form = $('&lt;div&gt;').editableform({ type: 'text', name: 'username', url: '/post', value: 'vitaliy' }); //to display form you should call 'render' method $form.editableform('render'); */ $.fn.editableform = function (option) { var args = arguments; return this.each(function () { var $this = $(this), data = $this.data('editableform'), options = typeof option === 'object' && option; if (!data) { $this.data('editableform', (data = new EditableForm(this, options))); } if (typeof option === 'string') { //call method data[option].apply(data, Array.prototype.slice.call(args, 1)); } }); }; //keep link to constructor to allow inheritance $.fn.editableform.Constructor = EditableForm; //defaults $.fn.editableform.defaults = { /* see also defaults for input */ /** Type of input. Can be <code>text|textarea|select|date|checklist</code> @property type @type string @default 'text' **/ type: 'text', /** Url for submit, e.g. <code>'/post'</code> If function - it will be called instead of ajax. Function should return deferred object to run fail/done callbacks. @property url @type string|function @default null @example url: function(params) { var d = new $.Deferred; if(params.value === 'abc') { return d.reject('error message'); //returning error via deferred object } else { //async saving data in js model someModel.asyncSaveMethod({ ..., success: function(){ d.resolve(); } }); return d.promise(); } } **/ url:null, /** Additional params for submit. If defined as <code>object</code> - it is **appended** to original ajax data (pk, name and value). If defined as <code>function</code> - returned object **overwrites** original ajax data. @example params: function(params) { //originally params contain pk, name and value params.a = 1; return params; } @property params @type object|function @default null **/ params:null, /** Name of field. Will be submitted on server. Can be taken from <code>id</code> attribute @property name @type string @default null **/ name: null, /** Primary key of editable object (e.g. record id in database). For composite keys use object, e.g. <code>{id: 1, lang: 'en'}</code>. Can be calculated dynamically via function. @property pk @type string|object|function @default null **/ pk: null, /** Initial value. If not defined - will be taken from element's content. For __select__ type should be defined (as it is ID of shown text). @property value @type string|object @default null **/ value: null, /** Value that will be displayed in input if original field value is empty (`null|undefined|''`). @property defaultValue @type string|object @default null @since 1.4.6 **/ defaultValue: null, /** Strategy for sending data on server. Can be `auto|always|never`. When 'auto' data will be sent on server **only if pk and url defined**, otherwise new value will be stored locally. @property send @type string @default 'auto' **/ send: 'auto', /** Function for client-side validation. If returns string - means validation not passed and string showed as error. @property validate @type function @default null @example validate: function(value) { if($.trim(value) == '') { return 'This field is required'; } } **/ validate: null, /** Success callback. Called when value successfully sent on server and **response status = 200**. Usefull to work with json response. For example, if your backend response can be <code>{success: true}</code> or <code>{success: false, msg: "server error"}</code> you can check it inside this callback. If it returns **string** - means error occured and string is shown as error message. If it returns **object like** <code>{newValue: &lt;something&gt;}</code> - it overwrites value, submitted by user. Otherwise newValue simply rendered into element. @property success @type function @default null @example success: function(response, newValue) { if(!response.success) return response.msg; } **/ success: null, /** Error callback. Called when request failed (response status != 200). Usefull when you want to parse error response and display a custom message. Must return **string** - the message to be displayed in the error block. @property error @type function @default null @since 1.4.4 @example error: function(response, newValue) { if(response.status === 500) { return 'Service unavailable. Please try later.'; } else { return response.responseText; } } **/ error: null, /** Additional options for submit ajax request. List of values: http://api.jquery.com/jQuery.ajax @property ajaxOptions @type object @default null @since 1.1.1 @example ajaxOptions: { type: 'put', dataType: 'json' } **/ ajaxOptions: null, /** Where to show buttons: left(true)|bottom|false Form without buttons is auto-submitted. @property showbuttons @type boolean|string @default true @since 1.1.1 **/ showbuttons: true, /** Scope for callback methods (success, validate). If <code>null</code> means editableform instance itself. @property scope @type DOMElement|object @default null @since 1.2.0 @private **/ scope: null, /** Whether to save or cancel value when it was not changed but form was submitted @property savenochange @type boolean @default false @since 1.2.0 **/ savenochange: false }; /* Note: following params could redefined in engine: bootstrap or jqueryui: Classes 'control-group' and 'editable-error-block' must always present! */ $.fn.editableform.template = '<form class="form-inline editableform">'+ '<div class="control-group">' + '<div><div class="editable-input"></div><div class="editable-buttons"></div></div>'+ '<div class="editable-error-block"></div>' + '</div>' + '</form>'; //loading div $.fn.editableform.loading = '<div class="editableform-loading"></div>'; //buttons $.fn.editableform.buttons = '<button type="submit" class="editable-submit">ok</button>'+ '<button type="button" class="editable-cancel">cancel</button>'; //error class attached to control-group $.fn.editableform.errorGroupClass = null; //error class attached to editable-error-block $.fn.editableform.errorBlockClass = 'editable-error'; //engine $.fn.editableform.engine = 'jquery'; }(window.jQuery)); /** * EditableForm utilites */ (function ($) { "use strict"; //utils $.fn.editableutils = { /** * classic JS inheritance function */ inherit: function (Child, Parent) { var F = function() { }; F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child; Child.superclass = Parent.prototype; }, /** * set caret position in input * see http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area */ setCursorPosition: function(elem, pos) { if (elem.setSelectionRange) { elem.setSelectionRange(pos, pos); } else if (elem.createTextRange) { var range = elem.createTextRange(); range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } }, /** * function to parse JSON in *single* quotes. (jquery automatically parse only double quotes) * That allows such code as: <a data-source="{'a': 'b', 'c': 'd'}"> * safe = true --> means no exception will be thrown * for details see http://stackoverflow.com/questions/7410348/how-to-set-json-format-to-html5-data-attributes-in-the-jquery */ tryParseJson: function(s, safe) { if (typeof s === 'string' && s.length && s.match(/^[\{\[].*[\}\]]$/)) { if (safe) { try { /*jslint evil: true*/ s = (new Function('return ' + s))(); /*jslint evil: false*/ } catch (e) {} finally { return s; } } else { /*jslint evil: true*/ s = (new Function('return ' + s))(); /*jslint evil: false*/ } } return s; }, /** * slice object by specified keys */ sliceObj: function(obj, keys, caseSensitive /* default: false */) { var key, keyLower, newObj = {}; if (!$.isArray(keys) || !keys.length) { return newObj; } for (var i = 0; i < keys.length; i++) { key = keys[i]; if (obj.hasOwnProperty(key)) { newObj[key] = obj[key]; } if(caseSensitive === true) { continue; } //when getting data-* attributes via $.data() it's converted to lowercase. //details: http://stackoverflow.com/questions/7602565/using-data-attributes-with-jquery //workaround is code below. keyLower = key.toLowerCase(); if (obj.hasOwnProperty(keyLower)) { newObj[key] = obj[keyLower]; } } return newObj; }, /* exclude complex objects from $.data() before pass to config */ getConfigData: function($element) { var data = {}; $.each($element.data(), function(k, v) { if(typeof v !== 'object' || (v && typeof v === 'object' && (v.constructor === Object || v.constructor === Array))) { data[k] = v; } }); return data; }, /* returns keys of object */ objectKeys: function(o) { if (Object.keys) { return Object.keys(o); } else { if (o !== Object(o)) { throw new TypeError('Object.keys called on a non-object'); } var k=[], p; for (p in o) { if (Object.prototype.hasOwnProperty.call(o,p)) { k.push(p); } } return k; } }, /** method to escape html. **/ escape: function(str) { return $('<div>').text(str).html(); }, /* returns array items from sourceData having value property equal or inArray of 'value' */ itemsByValue: function(value, sourceData, valueProp) { if(!sourceData || value === null) { return []; } if (typeof(valueProp) !== "function") { var idKey = valueProp || 'value'; valueProp = function (e) { return e[idKey]; }; } var isValArray = $.isArray(value), result = [], that = this; $.each(sourceData, function(i, o) { if(o.children) { result = result.concat(that.itemsByValue(value, o.children, valueProp)); } else { /*jslint eqeq: true*/ if(isValArray) { if($.grep(value, function(v){ return v == (o && typeof o === 'object' ? valueProp(o) : o); }).length) { result.push(o); } } else { var itemValue = (o && (typeof o === 'object')) ? valueProp(o) : o; if(value == itemValue) { result.push(o); } } /*jslint eqeq: false*/ } }); return result; }, /* Returns input by options: type, mode. */ createInput: function(options) { var TypeConstructor, typeOptions, input, type = options.type; //`date` is some kind of virtual type that is transformed to one of exact types //depending on mode and core lib if(type === 'date') { //inline if(options.mode === 'inline') { if($.fn.editabletypes.datefield) { type = 'datefield'; } else if($.fn.editabletypes.dateuifield) { type = 'dateuifield'; } //popup } else { if($.fn.editabletypes.date) { type = 'date'; } else if($.fn.editabletypes.dateui) { type = 'dateui'; } } //if type still `date` and not exist in types, replace with `combodate` that is base input if(type === 'date' && !$.fn.editabletypes.date) { type = 'combodate'; } } //`datetime` should be datetimefield in 'inline' mode if(type === 'datetime' && options.mode === 'inline') { type = 'datetimefield'; } //change wysihtml5 to textarea for jquery UI and plain versions if(type === 'wysihtml5' && !$.fn.editabletypes[type]) { type = 'textarea'; } //create input of specified type. Input will be used for converting value, not in form if(typeof $.fn.editabletypes[type] === 'function') { TypeConstructor = $.fn.editabletypes[type]; typeOptions = this.sliceObj(options, this.objectKeys(TypeConstructor.defaults)); input = new TypeConstructor(typeOptions); return input; } else { $.error('Unknown type: '+ type); return false; } }, //see http://stackoverflow.com/questions/7264899/detect-css-transitions-using-javascript-and-without-modernizr supportsTransitions: function () { var b = document.body || document.documentElement, s = b.style, p = 'transition', v = ['Moz', 'Webkit', 'Khtml', 'O', 'ms']; if(typeof s[p] === 'string') { return true; } // Tests for vendor specific prop p = p.charAt(0).toUpperCase() + p.substr(1); for(var i=0; i<v.length; i++) { if(typeof s[v[i] + p] === 'string') { return true; } } return false; } }; }(window.jQuery)); /** Attaches stand-alone container with editable-form to HTML element. Element is used only for positioning, value is not stored anywhere.<br> This method applied internally in <code>$().editable()</code>. You should subscribe on it's events (save / cancel) to get profit of it.<br> Final realization can be different: bootstrap-popover, jqueryui-tooltip, poshytip, inline-div. It depends on which js file you include.<br> Applied as jQuery method. @class editableContainer @uses editableform **/ (function ($) { "use strict"; var Popup = function (element, options) { this.init(element, options); }; var Inline = function (element, options) { this.init(element, options); }; //methods Popup.prototype = { containerName: null, //method to call container on element containerDataName: null, //object name in element's .data() innerCss: null, //tbd in child class containerClass: 'editable-container editable-popup', //css class applied to container element defaults: {}, //container itself defaults init: function(element, options) { this.$element = $(element); //since 1.4.1 container do not use data-* directly as they already merged into options. this.options = $.extend({}, $.fn.editableContainer.defaults, options); this.splitOptions(); //set scope of form callbacks to element this.formOptions.scope = this.$element[0]; this.initContainer(); //flag to hide container, when saving value will finish this.delayedHide = false; //bind 'destroyed' listener to destroy container when element is removed from dom this.$element.on('destroyed', $.proxy(function(){ this.destroy(); }, this)); //attach document handler to close containers on click / escape if(!$(document).data('editable-handlers-attached')) { //close all on escape $(document).on('keyup.editable', function (e) { if (e.which === 27) { $('.editable-open').editableContainer('hide'); //todo: return focus on element } }); //close containers when click outside //(mousedown could be better than click, it closes everything also on drag drop) $(document).on('click.editable', function(e) { var $target = $(e.target), i, exclude_classes = ['.editable-container', '.ui-datepicker-header', '.datepicker', //in inline mode datepicker is rendered into body '.modal-backdrop', '.bootstrap-wysihtml5-insert-image-modal', '.bootstrap-wysihtml5-insert-link-modal' ]; //check if element is detached. It occurs when clicking in bootstrap datepicker if (!$.contains(document.documentElement, e.target)) { return; } //for some reason FF 20 generates extra event (click) in select2 widget with e.target = document //we need to filter it via construction below. See https://github.com/vitalets/x-editable/issues/199 //Possibly related to http://stackoverflow.com/questions/10119793/why-does-firefox-react-differently-from-webkit-and-ie-to-click-event-on-selec if($target.is(document)) { return; } //if click inside one of exclude classes --> no nothing for(i=0; i<exclude_classes.length; i++) { if($target.is(exclude_classes[i]) || $target.parents(exclude_classes[i]).length) { return; } } //close all open containers (except one - target) Popup.prototype.closeOthers(e.target); }); $(document).data('editable-handlers-attached', true); } }, //split options on containerOptions and formOptions splitOptions: function() { this.containerOptions = {}; this.formOptions = {}; if(!$.fn[this.containerName]) { throw new Error(this.containerName + ' not found. Have you included corresponding js file?'); } //keys defined in container defaults go to container, others go to form for(var k in this.options) { if(k in this.defaults) { this.containerOptions[k] = this.options[k]; } else { this.formOptions[k] = this.options[k]; } } }, /* Returns jquery object of container @method tip() */ tip: function() { return this.container() ? this.container().$tip : null; }, /* returns container object */ container: function() { var container; //first, try get it by `containerDataName` if(this.containerDataName) { if(container = this.$element.data(this.containerDataName)) { return container; } } //second, try `containerName` container = this.$element.data(this.containerName); return container; }, /* call native method of underlying container, e.g. this.$element.popover('method') */ call: function() { this.$element[this.containerName].apply(this.$element, arguments); }, initContainer: function(){ this.call(this.containerOptions); }, renderForm: function() { this.$form .editableform(this.formOptions) .on({ save: $.proxy(this.save, this), //click on submit button (value changed) nochange: $.proxy(function(){ this.hide('nochange'); }, this), //click on submit button (value NOT changed) cancel: $.proxy(function(){ this.hide('cancel'); }, this), //click on calcel button show: $.proxy(function() { if(this.delayedHide) { this.hide(this.delayedHide.reason); this.delayedHide = false; } else { this.setPosition(); } }, this), //re-position container every time form is shown (occurs each time after loading state) rendering: $.proxy(this.setPosition, this), //this allows to place container correctly when loading shown resize: $.proxy(this.setPosition, this), //this allows to re-position container when form size is changed rendered: $.proxy(function(){ /** Fired when container is shown and form is rendered (for select will wait for loading dropdown options). **Note:** Bootstrap popover has own `shown` event that now cannot be separated from x-editable's one. The workaround is to check `arguments.length` that is always `2` for x-editable. @event shown @param {Object} event event object @example $('#username').on('shown', function(e, editable) { editable.input.$input.val('overwriting value of input..'); }); **/ /* TODO: added second param mainly to distinguish from bootstrap's shown event. It's a hotfix that will be solved in future versions via namespaced events. */ this.$element.triggerHandler('shown', $(this.options.scope).data('editable')); }, this) }) .editableform('render'); }, /** Shows container with form @method show() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ /* Note: poshytip owerwrites this method totally! */ show: function (closeAll) { this.$element.addClass('editable-open'); if(closeAll !== false) { //close all open containers (except this) this.closeOthers(this.$element[0]); } //show container itself this.innerShow(); this.tip().addClass(this.containerClass); /* Currently, form is re-rendered on every show. The main reason is that we dont know, what will container do with content when closed: remove(), detach() or just hide() - it depends on container. Detaching form itself before hide and re-insert before show is good solution, but visually it looks ugly --> container changes size before hide. */ //if form already exist - delete previous data if(this.$form) { //todo: destroy prev data! //this.$form.destroy(); } this.$form = $('<div>'); //insert form into container body if(this.tip().is(this.innerCss)) { //for inline container this.tip().append(this.$form); } else { this.tip().find(this.innerCss).append(this.$form); } //render form this.renderForm(); }, /** Hides container with form @method hide() @param {string} reason Reason caused hiding. Can be <code>save|cancel|onblur|nochange|undefined (=manual)</code> **/ hide: function(reason) { if(!this.tip() || !this.tip().is(':visible') || !this.$element.hasClass('editable-open')) { return; } //if form is saving value, schedule hide if(this.$form.data('editableform').isSaving) { this.delayedHide = {reason: reason}; return; } else { this.delayedHide = false; } this.$element.removeClass('editable-open'); this.innerHide(); /** Fired when container was hidden. It occurs on both save or cancel. **Note:** Bootstrap popover has own `hidden` event that now cannot be separated from x-editable's one. The workaround is to check `arguments.length` that is always `2` for x-editable. @event hidden @param {object} event event object @param {string} reason Reason caused hiding. Can be <code>save|cancel|onblur|nochange|manual</code> @example $('#username').on('hidden', function(e, reason) { if(reason === 'save' || reason === 'cancel') { //auto-open next editable $(this).closest('tr').next().find('.editable').editable('show'); } }); **/ this.$element.triggerHandler('hidden', reason || 'manual'); }, /* internal show method. To be overwritten in child classes */ innerShow: function () { }, /* internal hide method. To be overwritten in child classes */ innerHide: function () { }, /** Toggles container visibility (show / hide) @method toggle() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ toggle: function(closeAll) { if(this.container() && this.tip() && this.tip().is(':visible')) { this.hide(); } else { this.show(closeAll); } }, /* Updates the position of container when content changed. @method setPosition() */ setPosition: function() { //tbd in child class }, save: function(e, params) { /** Fired when new value was submitted. You can use <code>$(this).data('editableContainer')</code> inside handler to access to editableContainer instance @event save @param {Object} event event object @param {Object} params additional params @param {mixed} params.newValue submitted value @param {Object} params.response ajax response @example $('#username').on('save', function(e, params) { //assuming server response: '{success: true}' var pk = $(this).data('editableContainer').options.pk; if(params.response && params.response.success) { alert('value: ' + params.newValue + ' with pk: ' + pk + ' saved!'); } else { alert('error!'); } }); **/ this.$element.triggerHandler('save', params); //hide must be after trigger, as saving value may require methods of plugin, applied to input this.hide('save'); }, /** Sets new option @method option(key, value) @param {string} key @param {mixed} value **/ option: function(key, value) { this.options[key] = value; if(key in this.containerOptions) { this.containerOptions[key] = value; this.setContainerOption(key, value); } else { this.formOptions[key] = value; if(this.$form) { this.$form.editableform('option', key, value); } } }, setContainerOption: function(key, value) { this.call('option', key, value); }, /** Destroys the container instance @method destroy() **/ destroy: function() { this.hide(); this.innerDestroy(); this.$element.off('destroyed'); this.$element.removeData('editableContainer'); }, /* to be overwritten in child classes */ innerDestroy: function() { }, /* Closes other containers except one related to passed element. Other containers can be cancelled or submitted (depends on onblur option) */ closeOthers: function(element) { $('.editable-open').each(function(i, el){ //do nothing with passed element and it's children if(el === element || $(el).find(element).length) { return; } //otherwise cancel or submit all open containers var $el = $(el), ec = $el.data('editableContainer'); if(!ec) { return; } if(ec.options.onblur === 'cancel') { $el.data('editableContainer').hide('onblur'); } else if(ec.options.onblur === 'submit') { $el.data('editableContainer').tip().find('form').submit(); } }); }, /** Activates input of visible container (e.g. set focus) @method activate() **/ activate: function() { if(this.tip && this.tip().is(':visible') && this.$form) { this.$form.data('editableform').input.activate(); } } }; /** jQuery method to initialize editableContainer. @method $().editableContainer(options) @params {Object} options @example $('#edit').editableContainer({ type: 'text', url: '/post', pk: 1, value: 'hello' }); **/ $.fn.editableContainer = function (option) { var args = arguments; return this.each(function () { var $this = $(this), dataKey = 'editableContainer', data = $this.data(dataKey), options = typeof option === 'object' && option, Constructor = (options.mode === 'inline') ? Inline : Popup; if (!data) { $this.data(dataKey, (data = new Constructor(this, options))); } if (typeof option === 'string') { //call method data[option].apply(data, Array.prototype.slice.call(args, 1)); } }); }; //store constructors $.fn.editableContainer.Popup = Popup; $.fn.editableContainer.Inline = Inline; //defaults $.fn.editableContainer.defaults = { /** Initial value of form input @property value @type mixed @default null @private **/ value: null, /** Placement of container relative to element. Can be <code>top|right|bottom|left</code>. Not used for inline container. @property placement @type string @default 'top' **/ placement: 'top', /** Whether to hide container on save/cancel. @property autohide @type boolean @default true @private **/ autohide: true, /** Action when user clicks outside the container. Can be <code>cancel|submit|ignore</code>. Setting <code>ignore</code> allows to have several containers open. @property onblur @type string @default 'cancel' @since 1.1.1 **/ onblur: 'cancel', /** Animation speed (inline mode only) @property anim @type string @default false **/ anim: false, /** Mode of editable, can be `popup` or `inline` @property mode @type string @default 'popup' @since 1.4.0 **/ mode: 'popup' }; /* * workaround to have 'destroyed' event to destroy popover when element is destroyed * see http://stackoverflow.com/questions/2200494/jquery-trigger-event-when-an-element-is-removed-from-the-dom */ jQuery.event.special.destroyed = { remove: function(o) { if (o.handler) { o.handler(); } } }; }(window.jQuery)); /** * Editable Inline * --------------------- */ (function ($) { "use strict"; //copy prototype from EditableContainer //extend methods $.extend($.fn.editableContainer.Inline.prototype, $.fn.editableContainer.Popup.prototype, { containerName: 'editableform', innerCss: '.editable-inline', containerClass: 'editable-container editable-inline', //css class applied to container element initContainer: function(){ //container is <span> element this.$tip = $('<span></span>'); //convert anim to miliseconds (int) if(!this.options.anim) { this.options.anim = 0; } }, splitOptions: function() { //all options are passed to form this.containerOptions = {}; this.formOptions = this.options; }, tip: function() { return this.$tip; }, innerShow: function () { this.$element.hide(); this.tip().insertAfter(this.$element).show(); }, innerHide: function () { this.$tip.hide(this.options.anim, $.proxy(function() { this.$element.show(); this.innerDestroy(); }, this)); }, innerDestroy: function() { if(this.tip()) { this.tip().empty().remove(); } } }); }(window.jQuery)); /** Makes editable any HTML element on the page. Applied as jQuery method. @class editable @uses editableContainer **/ (function ($) { "use strict"; var Editable = function (element, options) { this.$element = $(element); //data-* has more priority over js options: because dynamically created elements may change data-* this.options = $.extend({}, $.fn.editable.defaults, options, $.fn.editableutils.getConfigData(this.$element)); if(this.options.selector) { this.initLive(); } else { this.init(); } //check for transition support if(this.options.highlight && !$.fn.editableutils.supportsTransitions()) { this.options.highlight = false; } }; Editable.prototype = { constructor: Editable, init: function () { var isValueByText = false, doAutotext, finalize; //name this.options.name = this.options.name || this.$element.attr('id'); //create input of specified type. Input needed already here to convert value for initial display (e.g. show text by id for select) //also we set scope option to have access to element inside input specific callbacks (e. g. source as function) this.options.scope = this.$element[0]; this.input = $.fn.editableutils.createInput(this.options); if(!this.input) { return; } //set value from settings or by element's text if (this.options.value === undefined || this.options.value === null) { this.value = this.input.html2value($.trim(this.$element.html())); isValueByText = true; } else { /* value can be string when received from 'data-value' attribute for complext objects value can be set as json string in data-value attribute, e.g. data-value="{city: 'Moscow', street: 'Lenina'}" */ this.options.value = $.fn.editableutils.tryParseJson(this.options.value, true); if(typeof this.options.value === 'string') { this.value = this.input.str2value(this.options.value); } else { this.value = this.options.value; } } //add 'editable' class to every editable element this.$element.addClass('editable'); //specifically for "textarea" add class .editable-pre-wrapped to keep linebreaks if(this.input.type === 'textarea') { this.$element.addClass('editable-pre-wrapped'); } //attach handler activating editable. In disabled mode it just prevent default action (useful for links) if(this.options.toggle !== 'manual') { this.$element.addClass('editable-click'); this.$element.on(this.options.toggle + '.editable', $.proxy(function(e){ //prevent following link if editable enabled if(!this.options.disabled) { e.preventDefault(); } //stop propagation not required because in document click handler it checks event target //e.stopPropagation(); if(this.options.toggle === 'mouseenter') { //for hover only show container this.show(); } else { //when toggle='click' we should not close all other containers as they will be closed automatically in document click listener var closeAll = (this.options.toggle !== 'click'); this.toggle(closeAll); } }, this)); } else { this.$element.attr('tabindex', -1); //do not stop focus on element when toggled manually } //if display is function it's far more convinient to have autotext = always to render correctly on init //see https://github.com/vitalets/x-editable-yii/issues/34 if(typeof this.options.display === 'function') { this.options.autotext = 'always'; } //check conditions for autotext: switch(this.options.autotext) { case 'always': doAutotext = true; break; case 'auto': //if element text is empty and value is defined and value not generated by text --> run autotext doAutotext = !$.trim(this.$element.text()).length && this.value !== null && this.value !== undefined && !isValueByText; break; default: doAutotext = false; } //depending on autotext run render() or just finilize init $.when(doAutotext ? this.render() : true).then($.proxy(function() { if(this.options.disabled) { this.disable(); } else { this.enable(); } /** Fired when element was initialized by `$().editable()` method. Please note that you should setup `init` handler **before** applying `editable`. @event init @param {Object} event event object @param {Object} editable editable instance (as here it cannot accessed via data('editable')) @since 1.2.0 @example $('#username').on('init', function(e, editable) { alert('initialized ' + editable.options.name); }); $('#username').editable(); **/ this.$element.triggerHandler('init', this); }, this)); }, /* Initializes parent element for live editables */ initLive: function() { //store selector var selector = this.options.selector; //modify options for child elements this.options.selector = false; this.options.autotext = 'never'; //listen toggle events this.$element.on(this.options.toggle + '.editable', selector, $.proxy(function(e){ var $target = $(e.target); if(!$target.data('editable')) { //if delegated element initially empty, we need to clear it's text (that was manually set to `empty` by user) //see https://github.com/vitalets/x-editable/issues/137 if($target.hasClass(this.options.emptyclass)) { $target.empty(); } $target.editable(this.options).trigger(e); } }, this)); }, /* Renders value into element's text. Can call custom display method from options. Can return deferred object. @method render() @param {mixed} response server response (if exist) to pass into display function */ render: function(response) { //do not display anything if(this.options.display === false) { return; } //if input has `value2htmlFinal` method, we pass callback in third param to be called when source is loaded if(this.input.value2htmlFinal) { return this.input.value2html(this.value, this.$element[0], this.options.display, response); //if display method defined --> use it } else if(typeof this.options.display === 'function') { return this.options.display.call(this.$element[0], this.value, response); //else use input's original value2html() method } else { return this.input.value2html(this.value, this.$element[0]); } }, /** Enables editable @method enable() **/ enable: function() { this.options.disabled = false; this.$element.removeClass('editable-disabled'); this.handleEmpty(this.isEmpty); if(this.options.toggle !== 'manual') { if(this.$element.attr('tabindex') === '-1') { this.$element.removeAttr('tabindex'); } } }, /** Disables editable @method disable() **/ disable: function() { this.options.disabled = true; this.hide(); this.$element.addClass('editable-disabled'); this.handleEmpty(this.isEmpty); //do not stop focus on this element this.$element.attr('tabindex', -1); }, /** Toggles enabled / disabled state of editable element @method toggleDisabled() **/ toggleDisabled: function() { if(this.options.disabled) { this.enable(); } else { this.disable(); } }, /** Sets new option @method option(key, value) @param {string|object} key option name or object with several options @param {mixed} value option new value @example $('.editable').editable('option', 'pk', 2); **/ option: function(key, value) { //set option(s) by object if(key && typeof key === 'object') { $.each(key, $.proxy(function(k, v){ this.option($.trim(k), v); }, this)); return; } //set option by string this.options[key] = value; //disabled if(key === 'disabled') { return value ? this.disable() : this.enable(); } //value if(key === 'value') { this.setValue(value); } //transfer new option to container! if(this.container) { this.container.option(key, value); } //pass option to input directly (as it points to the same in form) if(this.input.option) { this.input.option(key, value); } }, /* * set emptytext if element is empty */ handleEmpty: function (isEmpty) { //do not handle empty if we do not display anything if(this.options.display === false) { return; } /* isEmpty may be set directly as param of method. It is required when we enable/disable field and can't rely on content as node content is text: "Empty" that is not empty %) */ if(isEmpty !== undefined) { this.isEmpty = isEmpty; } else { //detect empty //for some inputs we need more smart check //e.g. wysihtml5 may have <br>, <p></p>, <img> if(typeof(this.input.isEmpty) === 'function') { this.isEmpty = this.input.isEmpty(this.$element); } else { this.isEmpty = $.trim(this.$element.html()) === ''; } } //emptytext shown only for enabled if(!this.options.disabled) { if (this.isEmpty) { this.$element.html(this.options.emptytext); if(this.options.emptyclass) { this.$element.addClass(this.options.emptyclass); } } else if(this.options.emptyclass) { this.$element.removeClass(this.options.emptyclass); } } else { //below required if element disable property was changed if(this.isEmpty) { this.$element.empty(); if(this.options.emptyclass) { this.$element.removeClass(this.options.emptyclass); } } } }, /** Shows container with form @method show() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ show: function (closeAll) { if(this.options.disabled) { return; } //init editableContainer: popover, tooltip, inline, etc.. if(!this.container) { var containerOptions = $.extend({}, this.options, { value: this.value, input: this.input //pass input to form (as it is already created) }); this.$element.editableContainer(containerOptions); //listen `save` event this.$element.on("save.internal", $.proxy(this.save, this)); this.container = this.$element.data('editableContainer'); } else if(this.container.tip().is(':visible')) { return; } //show container this.container.show(closeAll); }, /** Hides container with form @method hide() **/ hide: function () { if(this.container) { this.container.hide(); } }, /** Toggles container visibility (show / hide) @method toggle() @param {boolean} closeAll Whether to close all other editable containers when showing this one. Default true. **/ toggle: function(closeAll) { if(this.container && this.container.tip().is(':visible')) { this.hide(); } else { this.show(closeAll); } }, /* * called when form was submitted */ save: function(e, params) { //mark element with unsaved class if needed if(this.options.unsavedclass) { /* Add unsaved css to element if: - url is not user's function - value was not sent to server - params.response === undefined, that means data was not sent - value changed */ var sent = false; sent = sent || typeof this.options.url === 'function'; sent = sent || this.options.display === false; sent = sent || params.response !== undefined; sent = sent || (this.options.savenochange && this.input.value2str(this.value) !== this.input.value2str(params.newValue)); if(sent) { this.$element.removeClass(this.options.unsavedclass); } else { this.$element.addClass(this.options.unsavedclass); } } //highlight when saving if(this.options.highlight) { var $e = this.$element, bgColor = $e.css('background-color'); $e.css('background-color', this.options.highlight); setTimeout(function(){ if(bgColor === 'transparent') { bgColor = ''; } $e.css('background-color', bgColor); $e.addClass('editable-bg-transition'); setTimeout(function(){ $e.removeClass('editable-bg-transition'); }, 1700); }, 10); } //set new value this.setValue(params.newValue, false, params.response); /** Fired when new value was submitted. You can use <code>$(this).data('editable')</code> to access to editable instance @event save @param {Object} event event object @param {Object} params additional params @param {mixed} params.newValue submitted value @param {Object} params.response ajax response @example $('#username').on('save', function(e, params) { alert('Saved value: ' + params.newValue); }); **/ //event itself is triggered by editableContainer. Description here is only for documentation }, validate: function () { if (typeof this.options.validate === 'function') { return this.options.validate.call(this, this.value); } }, /** Sets new value of editable @method setValue(value, convertStr) @param {mixed} value new value @param {boolean} convertStr whether to convert value from string to internal format **/ setValue: function(value, convertStr, response) { if(convertStr) { this.value = this.input.str2value(value); } else { this.value = value; } if(this.container) { this.container.option('value', this.value); } $.when(this.render(response)) .then($.proxy(function() { this.handleEmpty(); }, this)); }, /** Activates input of visible container (e.g. set focus) @method activate() **/ activate: function() { if(this.container) { this.container.activate(); } }, /** Removes editable feature from element @method destroy() **/ destroy: function() { this.disable(); if(this.container) { this.container.destroy(); } this.input.destroy(); if(this.options.toggle !== 'manual') { this.$element.removeClass('editable-click'); this.$element.off(this.options.toggle + '.editable'); } this.$element.off("save.internal"); this.$element.removeClass('editable editable-open editable-disabled'); this.$element.removeData('editable'); } }; /* EDITABLE PLUGIN DEFINITION * ======================= */ /** jQuery method to initialize editable element. @method $().editable(options) @params {Object} options @example $('#username').editable({ type: 'text', url: '/post', pk: 1 }); **/ $.fn.editable = function (option) { //special API methods returning non-jquery object var result = {}, args = arguments, datakey = 'editable'; switch (option) { /** Runs client-side validation for all matched editables @method validate() @returns {Object} validation errors map @example $('#username, #fullname').editable('validate'); // possible result: { username: "username is required", fullname: "fullname should be minimum 3 letters length" } **/ case 'validate': this.each(function () { var $this = $(this), data = $this.data(datakey), error; if (data && (error = data.validate())) { result[data.options.name] = error; } }); return result; /** Returns current values of editable elements. Note that it returns an **object** with name-value pairs, not a value itself. It allows to get data from several elements. If value of some editable is `null` or `undefined` it is excluded from result object. When param `isSingle` is set to **true** - it is supposed you have single element and will return value of editable instead of object. @method getValue() @param {bool} isSingle whether to return just value of single element @returns {Object} object of element names and values @example $('#username, #fullname').editable('getValue'); //result: { username: "superuser", fullname: "John" } //isSingle = true $('#username').editable('getValue', true); //result "superuser" **/ case 'getValue': if(arguments.length === 2 && arguments[1] === true) { //isSingle = true result = this.eq(0).data(datakey).value; } else { this.each(function () { var $this = $(this), data = $this.data(datakey); if (data && data.value !== undefined && data.value !== null) { result[data.options.name] = data.input.value2submit(data.value); } }); } return result; /** This method collects values from several editable elements and submit them all to server. Internally it runs client-side validation for all fields and submits only in case of success. See <a href="#newrecord">creating new records</a> for details. @method submit(options) @param {object} options @param {object} options.url url to submit data @param {object} options.data additional data to submit @param {object} options.ajaxOptions additional ajax options @param {function} options.error(obj) error handler @param {function} options.success(obj,config) success handler @returns {Object} jQuery object **/ case 'submit': //collects value, validate and submit to server for creating new record var config = arguments[1] || {}, $elems = this, errors = this.editable('validate'), values; if($.isEmptyObject(errors)) { values = this.editable('getValue'); if(config.data) { $.extend(values, config.data); } $.ajax($.extend({ url: config.url, data: values, type: 'POST' }, config.ajaxOptions)) .success(function(response) { //successful response 200 OK if(typeof config.success === 'function') { config.success.call($elems, response, config); } }) .error(function(){ //ajax error if(typeof config.error === 'function') { config.error.apply($elems, arguments); } }); } else { //client-side validation error if(typeof config.error === 'function') { config.error.call($elems, errors); } } return this; } //return jquery object return this.each(function () { var $this = $(this), data = $this.data(datakey), options = typeof option === 'object' && option; //for delegated targets do not store `editable` object for element //it's allows several different selectors. //see: https://github.com/vitalets/x-editable/issues/312 if(options && options.selector) { data = new Editable(this, options); return; } if (!data) { $this.data(datakey, (data = new Editable(this, options))); } if (typeof option === 'string') { //call method data[option].apply(data, Array.prototype.slice.call(args, 1)); } }); }; $.fn.editable.defaults = { /** Type of input. Can be <code>text|textarea|select|date|checklist</code> and more @property type @type string @default 'text' **/ type: 'text', /** Sets disabled state of editable @property disabled @type boolean @default false **/ disabled: false, /** How to toggle editable. Can be <code>click|dblclick|mouseenter|manual</code>. When set to <code>manual</code> you should manually call <code>show/hide</code> methods of editable. **Note**: if you call <code>show</code> or <code>toggle</code> inside **click** handler of some DOM element, you need to apply <code>e.stopPropagation()</code> because containers are being closed on any click on document. @example $('#edit-button').click(function(e) { e.stopPropagation(); $('#username').editable('toggle'); }); @property toggle @type string @default 'click' **/ toggle: 'click', /** Text shown when element is empty. @property emptytext @type string @default 'Empty' **/ emptytext: 'Empty', /** Allows to automatically set element's text based on it's value. Can be <code>auto|always|never</code>. Useful for select and date. For example, if dropdown list is <code>{1: 'a', 2: 'b'}</code> and element's value set to <code>1</code>, it's html will be automatically set to <code>'a'</code>. <code>auto</code> - text will be automatically set only if element is empty. <code>always|never</code> - always(never) try to set element's text. @property autotext @type string @default 'auto' **/ autotext: 'auto', /** Initial value of input. If not set, taken from element's text. Note, that if element's text is empty - text is automatically generated from value and can be customized (see `autotext` option). For example, to display currency sign: @example <a id="price" data-type="text" data-value="100"></a> <script> $('#price').editable({ ... display: function(value) { $(this).text(value + '$'); } }) </script> @property value @type mixed @default element's text **/ value: null, /** Callback to perform custom displaying of value in element's text. If `null`, default input's display used. If `false`, no displaying methods will be called, element's text will never change. Runs under element's scope. _**Parameters:**_ * `value` current value to be displayed * `response` server response (if display called after ajax submit), since 1.4.0 For _inputs with source_ (select, checklist) parameters are different: * `value` current value to be displayed * `sourceData` array of items for current input (e.g. dropdown items) * `response` server response (if display called after ajax submit), since 1.4.0 To get currently selected items use `$.fn.editableutils.itemsByValue(value, sourceData)`. @property display @type function|boolean @default null @since 1.2.0 @example display: function(value, sourceData) { //display checklist as comma-separated values var html = [], checked = $.fn.editableutils.itemsByValue(value, sourceData); if(checked.length) { $.each(checked, function(i, v) { html.push($.fn.editableutils.escape(v.text)); }); $(this).html(html.join(', ')); } else { $(this).empty(); } } **/ display: null, /** Css class applied when editable text is empty. @property emptyclass @type string @since 1.4.1 @default editable-empty **/ emptyclass: 'editable-empty', /** Css class applied when value was stored but not sent to server (`pk` is empty or `send = 'never'`). You may set it to `null` if you work with editables locally and submit them together. @property unsavedclass @type string @since 1.4.1 @default editable-unsaved **/ unsavedclass: 'editable-unsaved', /** If selector is provided, editable will be delegated to the specified targets. Usefull for dynamically generated DOM elements. **Please note**, that delegated targets can't be initialized with `emptytext` and `autotext` options, as they actually become editable only after first click. You should manually set class `editable-click` to these elements. Also, if element originally empty you should add class `editable-empty`, set `data-value=""` and write emptytext into element: @property selector @type string @since 1.4.1 @default null @example <div id="user"> <!-- empty --> <a href="#" data-name="username" data-type="text" class="editable-click editable-empty" data-value="" title="Username">Empty</a> <!-- non-empty --> <a href="#" data-name="group" data-type="select" data-source="/groups" data-value="1" class="editable-click" title="Group">Operator</a> </div> <script> $('#user').editable({ selector: 'a', url: '/post', pk: 1 }); </script> **/ selector: null, /** Color used to highlight element after update. Implemented via CSS3 transition, works in modern browsers. @property highlight @type string|boolean @since 1.4.5 @default #FFFF80 **/ highlight: '#FFFF80' }; }(window.jQuery)); /** AbstractInput - base class for all editable inputs. It defines interface to be implemented by any input type. To create your own input you can inherit from this class. @class abstractinput **/ (function ($) { "use strict"; //types $.fn.editabletypes = {}; var AbstractInput = function () { }; AbstractInput.prototype = { /** Initializes input @method init() **/ init: function(type, options, defaults) { this.type = type; this.options = $.extend({}, defaults, options); }, /* this method called before render to init $tpl that is inserted in DOM */ prerender: function() { this.$tpl = $(this.options.tpl); //whole tpl as jquery object this.$input = this.$tpl; //control itself, can be changed in render method this.$clear = null; //clear button this.error = null; //error message, if input cannot be rendered }, /** Renders input from tpl. Can return jQuery deferred object. Can be overwritten in child objects @method render() **/ render: function() { }, /** Sets element's html by value. @method value2html(value, element) @param {mixed} value @param {DOMElement} element **/ value2html: function(value, element) { $(element)[this.options.escape ? 'text' : 'html']($.trim(value)); }, /** Converts element's html to value @method html2value(html) @param {string} html @returns {mixed} **/ html2value: function(html) { return $('<div>').html(html).text(); }, /** Converts value to string (for internal compare). For submitting to server used value2submit(). @method value2str(value) @param {mixed} value @returns {string} **/ value2str: function(value) { return value; }, /** Converts string received from server into value. Usually from `data-value` attribute. @method str2value(str) @param {string} str @returns {mixed} **/ str2value: function(str) { return str; }, /** Converts value for submitting to server. Result can be string or object. @method value2submit(value) @param {mixed} value @returns {mixed} **/ value2submit: function(value) { return value; }, /** Sets value of input. @method value2input(value) @param {mixed} value **/ value2input: function(value) { this.$input.val(value); }, /** Returns value of input. Value can be object (e.g. datepicker) @method input2value() **/ input2value: function() { return this.$input.val(); }, /** Activates input. For text it sets focus. @method activate() **/ activate: function() { if(this.$input.is(':visible')) { this.$input.focus(); } }, /** Creates input. @method clear() **/ clear: function() { this.$input.val(null); }, /** method to escape html. **/ escape: function(str) { return $('<div>').text(str).html(); }, /** attach handler to automatically submit form when value changed (useful when buttons not shown) **/ autosubmit: function() { }, /** Additional actions when destroying element **/ destroy: function() { }, // -------- helper functions -------- setClass: function() { if(this.options.inputclass) { this.$input.addClass(this.options.inputclass); } }, setAttr: function(attr) { if (this.options[attr] !== undefined && this.options[attr] !== null) { this.$input.attr(attr, this.options[attr]); } }, option: function(key, value) { this.options[key] = value; } }; AbstractInput.defaults = { /** HTML template of input. Normally you should not change it. @property tpl @type string @default '' **/ tpl: '', /** CSS class automatically applied to input @property inputclass @type string @default null **/ inputclass: null, /** If `true` - html will be escaped in content of element via $.text() method. If `false` - html will not be escaped, $.html() used. When you use own `display` function, this option obviosly has no effect. @property escape @type boolean @since 1.5.0 @default true **/ escape: true, //scope for external methods (e.g. source defined as function) //for internal use only scope: null, //need to re-declare showbuttons here to get it's value from common config (passed only options existing in defaults) showbuttons: true }; $.extend($.fn.editabletypes, {abstractinput: AbstractInput}); }(window.jQuery)); /** List - abstract class for inputs that have source option loaded from js array or via ajax @class list @extends abstractinput **/ (function ($) { "use strict"; var List = function (options) { }; $.fn.editableutils.inherit(List, $.fn.editabletypes.abstractinput); $.extend(List.prototype, { render: function () { var deferred = $.Deferred(); this.error = null; this.onSourceReady(function () { this.renderList(); deferred.resolve(); }, function () { this.error = this.options.sourceError; deferred.resolve(); }); return deferred.promise(); }, html2value: function (html) { return null; //can't set value by text }, value2html: function (value, element, display, response) { var deferred = $.Deferred(), success = function () { if(typeof display === 'function') { //custom display method display.call(element, value, this.sourceData, response); } else { this.value2htmlFinal(value, element); } deferred.resolve(); }; //for null value just call success without loading source if(value === null) { success.call(this); } else { this.onSourceReady(success, function () { deferred.resolve(); }); } return deferred.promise(); }, // ------------- additional functions ------------ onSourceReady: function (success, error) { //run source if it function var source; if ($.isFunction(this.options.source)) { source = this.options.source.call(this.options.scope); this.sourceData = null; //note: if function returns the same source as URL - sourceData will be taken from cahce and no extra request performed } else { source = this.options.source; } //if allready loaded just call success if(this.options.sourceCache && $.isArray(this.sourceData)) { success.call(this); return; } //try parse json in single quotes (for double quotes jquery does automatically) try { source = $.fn.editableutils.tryParseJson(source, false); } catch (e) { error.call(this); return; } //loading from url if (typeof source === 'string') { //try to get sourceData from cache if(this.options.sourceCache) { var cacheID = source, cache; if (!$(document).data(cacheID)) { $(document).data(cacheID, {}); } cache = $(document).data(cacheID); //check for cached data if (cache.loading === false && cache.sourceData) { //take source from cache this.sourceData = cache.sourceData; this.doPrepend(); success.call(this); return; } else if (cache.loading === true) { //cache is loading, put callback in stack to be called later cache.callbacks.push($.proxy(function () { this.sourceData = cache.sourceData; this.doPrepend(); success.call(this); }, this)); //also collecting error callbacks cache.err_callbacks.push($.proxy(error, this)); return; } else { //no cache yet, activate it cache.loading = true; cache.callbacks = []; cache.err_callbacks = []; } } //ajaxOptions for source. Can be overwritten bt options.sourceOptions var ajaxOptions = $.extend({ url: source, type: 'get', cache: false, dataType: 'json', success: $.proxy(function (data) { if(cache) { cache.loading = false; } this.sourceData = this.makeArray(data); if($.isArray(this.sourceData)) { if(cache) { //store result in cache cache.sourceData = this.sourceData; //run success callbacks for other fields waiting for this source $.each(cache.callbacks, function () { this.call(); }); } this.doPrepend(); success.call(this); } else { error.call(this); if(cache) { //run error callbacks for other fields waiting for this source $.each(cache.err_callbacks, function () { this.call(); }); } } }, this), error: $.proxy(function () { error.call(this); if(cache) { cache.loading = false; //run error callbacks for other fields $.each(cache.err_callbacks, function () { this.call(); }); } }, this) }, this.options.sourceOptions); //loading sourceData from server $.ajax(ajaxOptions); } else { //options as json/array this.sourceData = this.makeArray(source); if($.isArray(this.sourceData)) { this.doPrepend(); success.call(this); } else { error.call(this); } } }, doPrepend: function () { if(this.options.prepend === null || this.options.prepend === undefined) { return; } if(!$.isArray(this.prependData)) { //run prepend if it is function (once) if ($.isFunction(this.options.prepend)) { this.options.prepend = this.options.prepend.call(this.options.scope); } //try parse json in single quotes this.options.prepend = $.fn.editableutils.tryParseJson(this.options.prepend, true); //convert prepend from string to object if (typeof this.options.prepend === 'string') { this.options.prepend = {'': this.options.prepend}; } this.prependData = this.makeArray(this.options.prepend); } if($.isArray(this.prependData) && $.isArray(this.sourceData)) { this.sourceData = this.prependData.concat(this.sourceData); } }, /* renders input list */ renderList: function() { // this method should be overwritten in child class }, /* set element's html by value */ value2htmlFinal: function(value, element) { // this method should be overwritten in child class }, /** * convert data to array suitable for sourceData, e.g. [{value: 1, text: 'abc'}, {...}] */ makeArray: function(data) { var count, obj, result = [], item, iterateItem; if(!data || typeof data === 'string') { return null; } if($.isArray(data)) { //array /* function to iterate inside item of array if item is object. Caclulates count of keys in item and store in obj. */ iterateItem = function (k, v) { obj = {value: k, text: v}; if(count++ >= 2) { return false;// exit from `each` if item has more than one key. } }; for(var i = 0; i < data.length; i++) { item = data[i]; if(typeof item === 'object') { count = 0; //count of keys inside item $.each(item, iterateItem); //case: [{val1: 'text1'}, {val2: 'text2} ...] if(count === 1) { result.push(obj); //case: [{value: 1, text: 'text1'}, {value: 2, text: 'text2'}, ...] } else if(count > 1) { //removed check of existance: item.hasOwnProperty('value') && item.hasOwnProperty('text') if(item.children) { item.children = this.makeArray(item.children); } result.push(item); } } else { //case: ['text1', 'text2' ...] result.push({value: item, text: item}); } } } else { //case: {val1: 'text1', val2: 'text2, ...} $.each(data, function (k, v) { result.push({value: k, text: v}); }); } return result; }, option: function(key, value) { this.options[key] = value; if(key === 'source') { this.sourceData = null; } if(key === 'prepend') { this.prependData = null; } } }); List.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** Source data for list. If **array** - it should be in format: `[{value: 1, text: "text1"}, {value: 2, text: "text2"}, ...]` For compability, object format is also supported: `{"1": "text1", "2": "text2" ...}` but it does not guarantee elements order. If **string** - considered ajax url to load items. In that case results will be cached for fields with the same source and name. See also `sourceCache` option. If **function**, it should return data in format above (since 1.4.0). Since 1.4.1 key `children` supported to render OPTGROUP (for **select** input only). `[{text: "group1", children: [{value: 1, text: "text1"}, {value: 2, text: "text2"}]}, ...]` @property source @type string | array | object | function @default null **/ source: null, /** Data automatically prepended to the beginning of dropdown list. @property prepend @type string | array | object | function @default false **/ prepend: false, /** Error message when list cannot be loaded (e.g. ajax error) @property sourceError @type string @default Error when loading list **/ sourceError: 'Error when loading list', /** if <code>true</code> and source is **string url** - results will be cached for fields with the same source. Usefull for editable column in grid to prevent extra requests. @property sourceCache @type boolean @default true @since 1.2.0 **/ sourceCache: true, /** Additional ajax options to be used in $.ajax() when loading list from server. Useful to send extra parameters (`data` key) or change request method (`type` key). @property sourceOptions @type object|function @default null @since 1.5.0 **/ sourceOptions: null }); $.fn.editabletypes.list = List; }(window.jQuery)); /** Text input @class text @extends abstractinput @final @example <a href="#" id="username" data-type="text" data-pk="1">awesome</a> <script> $(function(){ $('#username').editable({ url: '/post', title: 'Enter username' }); }); </script> **/ (function ($) { "use strict"; var Text = function (options) { this.init('text', options, Text.defaults); }; $.fn.editableutils.inherit(Text, $.fn.editabletypes.abstractinput); $.extend(Text.prototype, { render: function() { this.renderClear(); this.setClass(); this.setAttr('placeholder'); }, activate: function() { if(this.$input.is(':visible')) { this.$input.focus(); $.fn.editableutils.setCursorPosition(this.$input.get(0), this.$input.val().length); if(this.toggleClear) { this.toggleClear(); } } }, //render clear button renderClear: function() { if (this.options.clear) { this.$clear = $('<span class="editable-clear-x"></span>'); this.$input.after(this.$clear) .css('padding-right', 24) .keyup($.proxy(function(e) { //arrows, enter, tab, etc if(~$.inArray(e.keyCode, [40,38,9,13,27])) { return; } clearTimeout(this.t); var that = this; this.t = setTimeout(function() { that.toggleClear(e); }, 100); }, this)) .parent().css('position', 'relative'); this.$clear.click($.proxy(this.clear, this)); } }, postrender: function() { /* //now `clear` is positioned via css if(this.$clear) { //can position clear button only here, when form is shown and height can be calculated // var h = this.$input.outerHeight(true) || 20, var h = this.$clear.parent().height(), delta = (h - this.$clear.height()) / 2; //this.$clear.css({bottom: delta, right: delta}); } */ }, //show / hide clear button toggleClear: function(e) { if(!this.$clear) { return; } var len = this.$input.val().length, visible = this.$clear.is(':visible'); if(len && !visible) { this.$clear.show(); } if(!len && visible) { this.$clear.hide(); } }, clear: function() { this.$clear.hide(); this.$input.val('').focus(); } }); Text.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <input type="text"> **/ tpl: '<input type="text">', /** Placeholder attribute of input. Shown when input is empty. @property placeholder @type string @default null **/ placeholder: null, /** Whether to show `clear` button @property clear @type boolean @default true **/ clear: true }); $.fn.editabletypes.text = Text; }(window.jQuery)); /** Textarea input @class textarea @extends abstractinput @final @example <a href="#" id="comments" data-type="textarea" data-pk="1">awesome comment!</a> <script> $(function(){ $('#comments').editable({ url: '/post', title: 'Enter comments', rows: 10 }); }); </script> **/ (function ($) { "use strict"; var Textarea = function (options) { this.init('textarea', options, Textarea.defaults); }; $.fn.editableutils.inherit(Textarea, $.fn.editabletypes.abstractinput); $.extend(Textarea.prototype, { render: function () { this.setClass(); this.setAttr('placeholder'); this.setAttr('rows'); //ctrl + enter this.$input.keydown(function (e) { if (e.ctrlKey && e.which === 13) { $(this).closest('form').submit(); } }); }, //using `white-space: pre-wrap` solves \n <--> BR conversion very elegant! /* value2html: function(value, element) { var html = '', lines; if(value) { lines = value.split("\n"); for (var i = 0; i < lines.length; i++) { lines[i] = $('<div>').text(lines[i]).html(); } html = lines.join('<br>'); } $(element).html(html); }, html2value: function(html) { if(!html) { return ''; } var regex = new RegExp(String.fromCharCode(10), 'g'); var lines = html.split(/<br\s*\/?>/i); for (var i = 0; i < lines.length; i++) { var text = $('<div>').html(lines[i]).text(); // Remove newline characters (\n) to avoid them being converted by value2html() method // thus adding extra <br> tags text = text.replace(regex, ''); lines[i] = text; } return lines.join("\n"); }, */ activate: function() { $.fn.editabletypes.text.prototype.activate.call(this); } }); Textarea.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <textarea></textarea> **/ tpl:'<textarea></textarea>', /** @property inputclass @default input-large **/ inputclass: 'input-large', /** Placeholder attribute of input. Shown when input is empty. @property placeholder @type string @default null **/ placeholder: null, /** Number of rows in textarea @property rows @type integer @default 7 **/ rows: 7 }); $.fn.editabletypes.textarea = Textarea; }(window.jQuery)); /** Select (dropdown) @class select @extends list @final @example <a href="#" id="status" data-type="select" data-pk="1" data-url="/post" data-title="Select status"></a> <script> $(function(){ $('#status').editable({ value: 2, source: [ {value: 1, text: 'Active'}, {value: 2, text: 'Blocked'}, {value: 3, text: 'Deleted'} ] }); }); </script> **/ (function ($) { "use strict"; var Select = function (options) { this.init('select', options, Select.defaults); }; $.fn.editableutils.inherit(Select, $.fn.editabletypes.list); $.extend(Select.prototype, { renderList: function() { this.$input.empty(); var fillItems = function($el, data) { var attr; if($.isArray(data)) { for(var i=0; i<data.length; i++) { attr = {}; if(data[i].children) { attr.label = data[i].text; $el.append(fillItems($('<optgroup>', attr), data[i].children)); } else { attr.value = data[i].value; if(data[i].disabled) { attr.disabled = true; } $el.append($('<option>', attr).text(data[i].text)); } } } return $el; }; fillItems(this.$input, this.sourceData); this.setClass(); //enter submit this.$input.on('keydown.editable', function (e) { if (e.which === 13) { $(this).closest('form').submit(); } }); }, value2htmlFinal: function(value, element) { var text = '', items = $.fn.editableutils.itemsByValue(value, this.sourceData); if(items.length) { text = items[0].text; } //$(element).text(text); $.fn.editabletypes.abstractinput.prototype.value2html.call(this, text, element); }, autosubmit: function() { this.$input.off('keydown.editable').on('change.editable', function(){ $(this).closest('form').submit(); }); } }); Select.defaults = $.extend({}, $.fn.editabletypes.list.defaults, { /** @property tpl @default <select></select> **/ tpl:'<select></select>' }); $.fn.editabletypes.select = Select; }(window.jQuery)); /** List of checkboxes. Internally value stored as javascript array of values. @class checklist @extends list @final @example <a href="#" id="options" data-type="checklist" data-pk="1" data-url="/post" data-title="Select options"></a> <script> $(function(){ $('#options').editable({ value: [2, 3], source: [ {value: 1, text: 'option1'}, {value: 2, text: 'option2'}, {value: 3, text: 'option3'} ] }); }); </script> **/ (function ($) { "use strict"; var Checklist = function (options) { this.init('checklist', options, Checklist.defaults); }; $.fn.editableutils.inherit(Checklist, $.fn.editabletypes.list); $.extend(Checklist.prototype, { renderList: function() { var $label, $div; this.$tpl.empty(); if(!$.isArray(this.sourceData)) { return; } for(var i=0; i<this.sourceData.length; i++) { $label = $('<label>').append($('<input>', { type: 'checkbox', value: this.sourceData[i].value })) .append($('<span>').text(' '+this.sourceData[i].text)); $('<div>').append($label).appendTo(this.$tpl); } this.$input = this.$tpl.find('input[type="checkbox"]'); this.setClass(); }, value2str: function(value) { return $.isArray(value) ? value.sort().join($.trim(this.options.separator)) : ''; }, //parse separated string str2value: function(str) { var reg, value = null; if(typeof str === 'string' && str.length) { reg = new RegExp('\\s*'+$.trim(this.options.separator)+'\\s*'); value = str.split(reg); } else if($.isArray(str)) { value = str; } else { value = [str]; } return value; }, //set checked on required checkboxes value2input: function(value) { this.$input.prop('checked', false); if($.isArray(value) && value.length) { this.$input.each(function(i, el) { var $el = $(el); // cannot use $.inArray as it performs strict comparison $.each(value, function(j, val){ /*jslint eqeq: true*/ if($el.val() == val) { /*jslint eqeq: false*/ $el.prop('checked', true); } }); }); } }, input2value: function() { var checked = []; this.$input.filter(':checked').each(function(i, el) { checked.push($(el).val()); }); return checked; }, //collect text of checked boxes value2htmlFinal: function(value, element) { var html = [], checked = $.fn.editableutils.itemsByValue(value, this.sourceData), escape = this.options.escape; if(checked.length) { $.each(checked, function(i, v) { var text = escape ? $.fn.editableutils.escape(v.text) : v.text; html.push(text); }); $(element).html(html.join('<br>')); } else { $(element).empty(); } }, activate: function() { this.$input.first().focus(); }, autosubmit: function() { this.$input.on('keydown', function(e){ if (e.which === 13) { $(this).closest('form').submit(); } }); } }); Checklist.defaults = $.extend({}, $.fn.editabletypes.list.defaults, { /** @property tpl @default <div></div> **/ tpl:'<div class="editable-checklist"></div>', /** @property inputclass @type string @default null **/ inputclass: null, /** Separator of values when reading from `data-value` attribute @property separator @type string @default ',' **/ separator: ',' }); $.fn.editabletypes.checklist = Checklist; }(window.jQuery)); /** HTML5 input types. Following types are supported: * password * email * url * tel * number * range * time Learn more about html5 inputs: http://www.w3.org/wiki/HTML5_form_additions To check browser compatibility please see: https://developer.mozilla.org/en-US/docs/HTML/Element/Input @class html5types @extends text @final @since 1.3.0 @example <a href="#" id="email" data-type="email" data-pk="1">admin@example.com</a> <script> $(function(){ $('#email').editable({ url: '/post', title: 'Enter email' }); }); </script> **/ /** @property tpl @default depends on type **/ /* Password */ (function ($) { "use strict"; var Password = function (options) { this.init('password', options, Password.defaults); }; $.fn.editableutils.inherit(Password, $.fn.editabletypes.text); $.extend(Password.prototype, { //do not display password, show '[hidden]' instead value2html: function(value, element) { if(value) { $(element).text('[hidden]'); } else { $(element).empty(); } }, //as password not displayed, should not set value by html html2value: function(html) { return null; } }); Password.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="password">' }); $.fn.editabletypes.password = Password; }(window.jQuery)); /* Email */ (function ($) { "use strict"; var Email = function (options) { this.init('email', options, Email.defaults); }; $.fn.editableutils.inherit(Email, $.fn.editabletypes.text); Email.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="email">' }); $.fn.editabletypes.email = Email; }(window.jQuery)); /* Url */ (function ($) { "use strict"; var Url = function (options) { this.init('url', options, Url.defaults); }; $.fn.editableutils.inherit(Url, $.fn.editabletypes.text); Url.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="url">' }); $.fn.editabletypes.url = Url; }(window.jQuery)); /* Tel */ (function ($) { "use strict"; var Tel = function (options) { this.init('tel', options, Tel.defaults); }; $.fn.editableutils.inherit(Tel, $.fn.editabletypes.text); Tel.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="tel">' }); $.fn.editabletypes.tel = Tel; }(window.jQuery)); /* Number */ (function ($) { "use strict"; var NumberInput = function (options) { this.init('number', options, NumberInput.defaults); }; $.fn.editableutils.inherit(NumberInput, $.fn.editabletypes.text); $.extend(NumberInput.prototype, { render: function () { NumberInput.superclass.render.call(this); this.setAttr('min'); this.setAttr('max'); this.setAttr('step'); }, postrender: function() { if(this.$clear) { //increase right ffset for up/down arrows this.$clear.css({right: 24}); /* //can position clear button only here, when form is shown and height can be calculated var h = this.$input.outerHeight(true) || 20, delta = (h - this.$clear.height()) / 2; //add 12px to offset right for up/down arrows this.$clear.css({top: delta, right: delta + 16}); */ } } }); NumberInput.defaults = $.extend({}, $.fn.editabletypes.text.defaults, { tpl: '<input type="number">', inputclass: 'input-mini', min: null, max: null, step: null }); $.fn.editabletypes.number = NumberInput; }(window.jQuery)); /* Range (inherit from number) */ (function ($) { "use strict"; var Range = function (options) { this.init('range', options, Range.defaults); }; $.fn.editableutils.inherit(Range, $.fn.editabletypes.number); $.extend(Range.prototype, { render: function () { this.$input = this.$tpl.filter('input'); this.setClass(); this.setAttr('min'); this.setAttr('max'); this.setAttr('step'); this.$input.on('input', function(){ $(this).siblings('output').text($(this).val()); }); }, activate: function() { this.$input.focus(); } }); Range.defaults = $.extend({}, $.fn.editabletypes.number.defaults, { tpl: '<input type="range"><output style="width: 30px; display: inline-block"></output>', inputclass: 'input-medium' }); $.fn.editabletypes.range = Range; }(window.jQuery)); /* Time */ (function ($) { "use strict"; var Time = function (options) { this.init('time', options, Time.defaults); }; //inherit from abstract, as inheritance from text gives selection error. $.fn.editableutils.inherit(Time, $.fn.editabletypes.abstractinput); $.extend(Time.prototype, { render: function() { this.setClass(); } }); Time.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { tpl: '<input type="time">' }); $.fn.editabletypes.time = Time; }(window.jQuery)); /** Select2 input. Based on amazing work of Igor Vaynberg https://github.com/ivaynberg/select2. Please see [original select2 docs](http://ivaynberg.github.com/select2) for detailed description and options. You should manually download and include select2 distributive: <link href="select2/select2.css" rel="stylesheet" type="text/css"></link> <script src="select2/select2.js"></script> To make it **bootstrap-styled** you can use css from [here](https://github.com/t0m/select2-bootstrap-css): <link href="select2-bootstrap.css" rel="stylesheet" type="text/css"></link> **Note:** currently `autotext` feature does not work for select2 with `ajax` remote source. You need initially put both `data-value` and element's text youself: <a href="#" data-type="select2" data-value="1">Text1</a> @class select2 @extends abstractinput @since 1.4.1 @final @example <a href="#" id="country" data-type="select2" data-pk="1" data-value="ru" data-url="/post" data-title="Select country"></a> <script> $(function(){ //local source $('#country').editable({ source: [ {id: 'gb', text: 'Great Britain'}, {id: 'us', text: 'United States'}, {id: 'ru', text: 'Russia'} ], select2: { multiple: true } }); //remote source (simple) $('#country').editable({ source: '/getCountries' }); //remote source (advanced) $('#country').editable({ select2: { placeholder: 'Select Country', allowClear: true, minimumInputLength: 3, id: function (item) { return item.CountryId; }, ajax: { url: '/getCountries', dataType: 'json', data: function (term, page) { return { query: term }; }, results: function (data, page) { return { results: data }; } }, formatResult: function (item) { return item.CountryName; }, formatSelection: function (item) { return item.CountryName; }, initSelection: function (element, callback) { return $.get('/getCountryById', { query: element.val() }, function (data) { callback(data); }); } } }); }); </script> **/ (function ($) { "use strict"; var Constructor = function (options) { this.init('select2', options, Constructor.defaults); options.select2 = options.select2 || {}; this.sourceData = null; //placeholder if(options.placeholder) { options.select2.placeholder = options.placeholder; } //if not `tags` mode, use source if(!options.select2.tags && options.source) { var source = options.source; //if source is function, call it (once!) if ($.isFunction(options.source)) { source = options.source.call(options.scope); } if (typeof source === 'string') { options.select2.ajax = options.select2.ajax || {}; //some default ajax params if(!options.select2.ajax.data) { options.select2.ajax.data = function(term) {return { query:term };}; } if(!options.select2.ajax.results) { options.select2.ajax.results = function(data) { return {results:data };}; } options.select2.ajax.url = source; } else { //check format and convert x-editable format to select2 format (if needed) this.sourceData = this.convertSource(source); options.select2.data = this.sourceData; } } //overriding objects in config (as by default jQuery extend() is not recursive) this.options.select2 = $.extend({}, Constructor.defaults.select2, options.select2); //detect whether it is multi-valued this.isMultiple = this.options.select2.tags || this.options.select2.multiple; this.isRemote = ('ajax' in this.options.select2); //store function returning ID of item //should be here as used inautotext for local source this.idFunc = this.options.select2.id; if (typeof(this.idFunc) !== "function") { var idKey = this.idFunc || 'id'; this.idFunc = function (e) { return e[idKey]; }; } //store function that renders text in select2 this.formatSelection = this.options.select2.formatSelection; if (typeof(this.formatSelection) !== "function") { this.formatSelection = function (e) { return e.text; }; } }; $.fn.editableutils.inherit(Constructor, $.fn.editabletypes.abstractinput); $.extend(Constructor.prototype, { render: function() { this.setClass(); //can not apply select2 here as it calls initSelection //over input that does not have correct value yet. //apply select2 only in value2input //this.$input.select2(this.options.select2); //when data is loaded via ajax, we need to know when it's done to populate listData if(this.isRemote) { //listen to loaded event to populate data this.$input.on('select2-loaded', $.proxy(function(e) { this.sourceData = e.items.results; }, this)); } //trigger resize of editableform to re-position container in multi-valued mode if(this.isMultiple) { this.$input.on('change', function() { $(this).closest('form').parent().triggerHandler('resize'); }); } }, value2html: function(value, element) { var text = '', data, that = this; if(this.options.select2.tags) { //in tags mode just assign value data = value; //data = $.fn.editableutils.itemsByValue(value, this.options.select2.tags, this.idFunc); } else if(this.sourceData) { data = $.fn.editableutils.itemsByValue(value, this.sourceData, this.idFunc); } else { //can not get list of possible values //(e.g. autotext for select2 with ajax source) } //data may be array (when multiple values allowed) if($.isArray(data)) { //collect selected data and show with separator text = []; $.each(data, function(k, v){ text.push(v && typeof v === 'object' ? that.formatSelection(v) : v); }); } else if(data) { text = that.formatSelection(data); } text = $.isArray(text) ? text.join(this.options.viewseparator) : text; //$(element).text(text); Constructor.superclass.value2html.call(this, text, element); }, html2value: function(html) { return this.options.select2.tags ? this.str2value(html, this.options.viewseparator) : null; }, value2input: function(value) { //for local source use data directly from source (to allow autotext) /* if(!this.isRemote && !this.isMultiple) { var items = $.fn.editableutils.itemsByValue(value, this.sourceData, this.idFunc); if(items.length) { this.$input.select2('data', items[0]); return; } } */ //for remote source just set value, text is updated by initSelection if(!this.$input.data('select2')) { this.$input.val(value); this.$input.select2(this.options.select2); } else { //second argument needed to separate initial change from user's click (for autosubmit) this.$input.val(value).trigger('change', true); } //if remote source AND no user's initSelection provided --> try to use element's text if(this.isRemote && !this.isMultiple && !this.options.select2.initSelection) { var customId = this.options.select2.id, customText = this.options.select2.formatSelection; if(!customId && !customText) { var data = {id: value, text: $(this.options.scope).text()}; this.$input.select2('data', data); } } }, input2value: function() { return this.$input.select2('val'); }, str2value: function(str, separator) { if(typeof str !== 'string' || !this.isMultiple) { return str; } separator = separator || this.options.select2.separator || $.fn.select2.defaults.separator; var val, i, l; if (str === null || str.length < 1) { return null; } val = str.split(separator); for (i = 0, l = val.length; i < l; i = i + 1) { val[i] = $.trim(val[i]); } return val; }, autosubmit: function() { this.$input.on('change', function(e, isInitial){ if(!isInitial) { $(this).closest('form').submit(); } }); }, /* Converts source from x-editable format: {value: 1, text: "1"} to select2 format: {id: 1, text: "1"} */ convertSource: function(source) { if($.isArray(source) && source.length && source[0].value !== undefined) { for(var i = 0; i<source.length; i++) { if(source[i].value !== undefined) { source[i].id = source[i].value; delete source[i].value; } } } return source; }, destroy: function() { if(this.$input.data('select2')) { this.$input.select2('destroy'); } } }); Constructor.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <input type="hidden"> **/ tpl:'<input type="hidden">', /** Configuration of select2. [Full list of options](http://ivaynberg.github.com/select2). @property select2 @type object @default null **/ select2: null, /** Placeholder attribute of select @property placeholder @type string @default null **/ placeholder: null, /** Source data for select. It will be assigned to select2 `data` property and kept here just for convenience. Please note, that format is different from simple `select` input: use 'id' instead of 'value'. E.g. `[{id: 1, text: "text1"}, {id: 2, text: "text2"}, ...]`. @property source @type array|string|function @default null **/ source: null, /** Separator used to display tags. @property viewseparator @type string @default ', ' **/ viewseparator: ', ' }); $.fn.editabletypes.select2 = Constructor; }(window.jQuery)); /** * Combodate - 1.0.4 * Dropdown date and time picker. * Converts text input into dropdowns to pick day, month, year, hour, minute and second. * Uses momentjs as datetime library http://momentjs.com. * For internalization include corresponding file from https://github.com/timrwood/moment/tree/master/lang * * Confusion at noon and midnight - see http://en.wikipedia.org/wiki/12-hour_clock#Confusion_at_noon_and_midnight * In combodate: * 12:00 pm --> 12:00 (24-h format, midday) * 12:00 am --> 00:00 (24-h format, midnight, start of day) * * Differs from momentjs parse rules: * 00:00 pm, 12:00 pm --> 12:00 (24-h format, day not change) * 00:00 am, 12:00 am --> 00:00 (24-h format, day not change) * * * Author: Vitaliy Potapov * Project page: http://github.com/vitalets/combodate * Copyright (c) 2012 Vitaliy Potapov. Released under MIT License. **/ (function ($) { var Combodate = function (element, options) { this.$element = $(element); if(!this.$element.is('input')) { $.error('Combodate should be applied to INPUT element'); return; } this.options = $.extend({}, $.fn.combodate.defaults, options, this.$element.data()); this.init(); }; Combodate.prototype = { constructor: Combodate, init: function () { this.map = { //key regexp moment.method day: ['D', 'date'], month: ['M', 'month'], year: ['Y', 'year'], hour: ['[Hh]', 'hours'], minute: ['m', 'minutes'], second: ['s', 'seconds'], ampm: ['[Aa]', ''] }; this.$widget = $('<span class="combodate"></span>').html(this.getTemplate()); this.initCombos(); //update original input on change this.$widget.on('change', 'select', $.proxy(function(){ this.$element.val(this.getValue()); }, this)); this.$widget.find('select').css('width', 'auto'); //hide original input and insert widget this.$element.hide().after(this.$widget); //set initial value this.setValue(this.$element.val() || this.options.value); }, /* Replace tokens in template with <select> elements */ getTemplate: function() { var tpl = this.options.template; //first pass $.each(this.map, function(k, v) { v = v[0]; var r = new RegExp(v+'+'), token = v.length > 1 ? v.substring(1, 2) : v; tpl = tpl.replace(r, '{'+token+'}'); }); //replace spaces with &nbsp; tpl = tpl.replace(/ /g, '&nbsp;'); //second pass $.each(this.map, function(k, v) { v = v[0]; var token = v.length > 1 ? v.substring(1, 2) : v; tpl = tpl.replace('{'+token+'}', '<select class="'+k+'"></select>'); }); return tpl; }, /* Initialize combos that presents in template */ initCombos: function() { var that = this; $.each(this.map, function(k, v) { var $c = that.$widget.find('.'+k), f, items; if($c.length) { that['$'+k] = $c; //set properties like this.$day, this.$month etc. f = 'fill' + k.charAt(0).toUpperCase() + k.slice(1); //define method name to fill items, e.g `fillDays` items = that[f](); that['$'+k].html(that.renderItems(items)); } }); }, /* Initialize items of combos. Handles `firstItem` option */ initItems: function(key) { var values = [], relTime; if(this.options.firstItem === 'name') { //need both to support moment ver < 2 and >= 2 relTime = moment.relativeTime || moment.langData()._relativeTime; var header = typeof relTime[key] === 'function' ? relTime[key](1, true, key, false) : relTime[key]; //take last entry (see momentjs lang files structure) header = header.split(' ').reverse()[0]; values.push(['', header]); } else if(this.options.firstItem === 'empty') { values.push(['', '']); } return values; }, /* render items to string of <option> tags */ renderItems: function(items) { var str = []; for(var i=0; i<items.length; i++) { str.push('<option value="'+items[i][0]+'">'+items[i][1]+'</option>'); } return str.join("\n"); }, /* fill day */ fillDay: function() { var items = this.initItems('d'), name, i, twoDigit = this.options.template.indexOf('DD') !== -1; for(i=1; i<=31; i++) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill month */ fillMonth: function() { var items = this.initItems('M'), name, i, longNames = this.options.template.indexOf('MMMM') !== -1, shortNames = this.options.template.indexOf('MMM') !== -1, twoDigit = this.options.template.indexOf('MM') !== -1; for(i=0; i<=11; i++) { if(longNames) { //see https://github.com/timrwood/momentjs.com/pull/36 name = moment().date(1).month(i).format('MMMM'); } else if(shortNames) { name = moment().date(1).month(i).format('MMM'); } else if(twoDigit) { name = this.leadZero(i+1); } else { name = i+1; } items.push([i, name]); } return items; }, /* fill year */ fillYear: function() { var items = [], name, i, longNames = this.options.template.indexOf('YYYY') !== -1; for(i=this.options.maxYear; i>=this.options.minYear; i--) { name = longNames ? i : (i+'').substring(2); items[this.options.yearDescending ? 'push' : 'unshift']([i, name]); } items = this.initItems('y').concat(items); return items; }, /* fill hour */ fillHour: function() { var items = this.initItems('h'), name, i, h12 = this.options.template.indexOf('h') !== -1, h24 = this.options.template.indexOf('H') !== -1, twoDigit = this.options.template.toLowerCase().indexOf('hh') !== -1, min = h12 ? 1 : 0, max = h12 ? 12 : 23; for(i=min; i<=max; i++) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill minute */ fillMinute: function() { var items = this.initItems('m'), name, i, twoDigit = this.options.template.indexOf('mm') !== -1; for(i=0; i<=59; i+= this.options.minuteStep) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill second */ fillSecond: function() { var items = this.initItems('s'), name, i, twoDigit = this.options.template.indexOf('ss') !== -1; for(i=0; i<=59; i+= this.options.secondStep) { name = twoDigit ? this.leadZero(i) : i; items.push([i, name]); } return items; }, /* fill ampm */ fillAmpm: function() { var ampmL = this.options.template.indexOf('a') !== -1, ampmU = this.options.template.indexOf('A') !== -1, items = [ ['am', ampmL ? 'am' : 'AM'], ['pm', ampmL ? 'pm' : 'PM'] ]; return items; }, /* Returns current date value from combos. If format not specified - `options.format` used. If format = `null` - Moment object returned. */ getValue: function(format) { var dt, values = {}, that = this, notSelected = false; //getting selected values $.each(this.map, function(k, v) { if(k === 'ampm') { return; } var def = k === 'day' ? 1 : 0; values[k] = that['$'+k] ? parseInt(that['$'+k].val(), 10) : def; if(isNaN(values[k])) { notSelected = true; return false; } }); //if at least one visible combo not selected - return empty string if(notSelected) { return ''; } //convert hours 12h --> 24h if(this.$ampm) { //12:00 pm --> 12:00 (24-h format, midday), 12:00 am --> 00:00 (24-h format, midnight, start of day) if(values.hour === 12) { values.hour = this.$ampm.val() === 'am' ? 0 : 12; } else { values.hour = this.$ampm.val() === 'am' ? values.hour : values.hour+12; } } dt = moment([values.year, values.month, values.day, values.hour, values.minute, values.second]); //highlight invalid date this.highlight(dt); format = format === undefined ? this.options.format : format; if(format === null) { return dt.isValid() ? dt : null; } else { return dt.isValid() ? dt.format(format) : ''; } }, setValue: function(value) { if(!value) { return; } var dt = typeof value === 'string' ? moment(value, this.options.format) : moment(value), that = this, values = {}; //function to find nearest value in select options function getNearest($select, value) { var delta = {}; $select.children('option').each(function(i, opt){ var optValue = $(opt).attr('value'), distance; if(optValue === '') return; distance = Math.abs(optValue - value); if(typeof delta.distance === 'undefined' || distance < delta.distance) { delta = {value: optValue, distance: distance}; } }); return delta.value; } if(dt.isValid()) { //read values from date object $.each(this.map, function(k, v) { if(k === 'ampm') { return; } values[k] = dt[v[1]](); }); if(this.$ampm) { //12:00 pm --> 12:00 (24-h format, midday), 12:00 am --> 00:00 (24-h format, midnight, start of day) if(values.hour >= 12) { values.ampm = 'pm'; if(values.hour > 12) { values.hour -= 12; } } else { values.ampm = 'am'; if(values.hour === 0) { values.hour = 12; } } } $.each(values, function(k, v) { //call val() for each existing combo, e.g. this.$hour.val() if(that['$'+k]) { if(k === 'minute' && that.options.minuteStep > 1 && that.options.roundTime) { v = getNearest(that['$'+k], v); } if(k === 'second' && that.options.secondStep > 1 && that.options.roundTime) { v = getNearest(that['$'+k], v); } that['$'+k].val(v); } }); this.$element.val(dt.format(this.options.format)); } }, /* highlight combos if date is invalid */ highlight: function(dt) { if(!dt.isValid()) { if(this.options.errorClass) { this.$widget.addClass(this.options.errorClass); } else { //store original border color if(!this.borderColor) { this.borderColor = this.$widget.find('select').css('border-color'); } this.$widget.find('select').css('border-color', 'red'); } } else { if(this.options.errorClass) { this.$widget.removeClass(this.options.errorClass); } else { this.$widget.find('select').css('border-color', this.borderColor); } } }, leadZero: function(v) { return v <= 9 ? '0' + v : v; }, destroy: function() { this.$widget.remove(); this.$element.removeData('combodate').show(); } //todo: clear method }; $.fn.combodate = function ( option ) { var d, args = Array.apply(null, arguments); args.shift(); //getValue returns date as string / object (not jQuery object) if(option === 'getValue' && this.length && (d = this.eq(0).data('combodate'))) { return d.getValue.apply(d, args); } return this.each(function () { var $this = $(this), data = $this.data('combodate'), options = typeof option == 'object' && option; if (!data) { $this.data('combodate', (data = new Combodate(this, options))); } if (typeof option == 'string' && typeof data[option] == 'function') { data[option].apply(data, args); } }); }; $.fn.combodate.defaults = { //in this format value stored in original input format: 'DD-MM-YYYY HH:mm', //in this format items in dropdowns are displayed template: 'D / MMM / YYYY H : mm', //initial value, can be `new Date()` value: null, minYear: 1970, maxYear: 2015, yearDescending: true, minuteStep: 5, secondStep: 1, firstItem: 'empty', //'name', 'empty', 'none' errorClass: null, roundTime: true //whether to round minutes and seconds if step > 1 }; }(window.jQuery)); /** Combodate input - dropdown date and time picker. Based on [combodate](http://vitalets.github.com/combodate) plugin (included). To use it you should manually include [momentjs](http://momentjs.com). <script src="js/moment.min.js"></script> Allows to input: * only date * only time * both date and time Please note, that format is taken from momentjs and **not compatible** with bootstrap-datepicker / jquery UI datepicker. Internally value stored as `momentjs` object. @class combodate @extends abstractinput @final @since 1.4.0 @example <a href="#" id="dob" data-type="combodate" data-pk="1" data-url="/post" data-value="1984-05-15" data-title="Select date"></a> <script> $(function(){ $('#dob').editable({ format: 'YYYY-MM-DD', viewformat: 'DD.MM.YYYY', template: 'D / MMMM / YYYY', combodate: { minYear: 2000, maxYear: 2015, minuteStep: 1 } } }); }); </script> **/ /*global moment*/ (function ($) { "use strict"; var Constructor = function (options) { this.init('combodate', options, Constructor.defaults); //by default viewformat equals to format if(!this.options.viewformat) { this.options.viewformat = this.options.format; } //try parse combodate config defined as json string in data-combodate options.combodate = $.fn.editableutils.tryParseJson(options.combodate, true); //overriding combodate config (as by default jQuery extend() is not recursive) this.options.combodate = $.extend({}, Constructor.defaults.combodate, options.combodate, { format: this.options.format, template: this.options.template }); }; $.fn.editableutils.inherit(Constructor, $.fn.editabletypes.abstractinput); $.extend(Constructor.prototype, { render: function () { this.$input.combodate(this.options.combodate); if($.fn.editableform.engine === 'bs3') { this.$input.siblings().find('select').addClass('form-control'); } if(this.options.inputclass) { this.$input.siblings().find('select').addClass(this.options.inputclass); } //"clear" link /* if(this.options.clear) { this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){ e.preventDefault(); e.stopPropagation(); this.clear(); }, this)); this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear)); } */ }, value2html: function(value, element) { var text = value ? value.format(this.options.viewformat) : ''; //$(element).text(text); Constructor.superclass.value2html.call(this, text, element); }, html2value: function(html) { return html ? moment(html, this.options.viewformat) : null; }, value2str: function(value) { return value ? value.format(this.options.format) : ''; }, str2value: function(str) { return str ? moment(str, this.options.format) : null; }, value2submit: function(value) { return this.value2str(value); }, value2input: function(value) { this.$input.combodate('setValue', value); }, input2value: function() { return this.$input.combodate('getValue', null); }, activate: function() { this.$input.siblings('.combodate').find('select').eq(0).focus(); }, /* clear: function() { this.$input.data('datepicker').date = null; this.$input.find('.active').removeClass('active'); }, */ autosubmit: function() { } }); Constructor.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <input type="text"> **/ tpl:'<input type="text">', /** @property inputclass @default null **/ inputclass: null, /** Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br> See list of tokens in [momentjs docs](http://momentjs.com/docs/#/parsing/string-format) @property format @type string @default YYYY-MM-DD **/ format:'YYYY-MM-DD', /** Format used for displaying date. Also applied when converting date from element's text on init. If not specified equals to `format`. @property viewformat @type string @default null **/ viewformat: null, /** Template used for displaying dropdowns. @property template @type string @default D / MMM / YYYY **/ template: 'D / MMM / YYYY', /** Configuration of combodate. Full list of options: http://vitalets.github.com/combodate/#docs @property combodate @type object @default null **/ combodate: null /* (not implemented yet) Text shown as clear date button. If <code>false</code> clear button will not be rendered. @property clear @type boolean|string @default 'x clear' */ //clear: '&times; clear' }); $.fn.editabletypes.combodate = Constructor; }(window.jQuery)); /* Editableform based on Twitter Bootstrap 3 */ (function ($) { "use strict"; //store parent methods var pInitInput = $.fn.editableform.Constructor.prototype.initInput; $.extend($.fn.editableform.Constructor.prototype, { initTemplate: function() { this.$form = $($.fn.editableform.template); this.$form.find('.control-group').addClass('form-group'); this.$form.find('.editable-error-block').addClass('help-block'); }, initInput: function() { pInitInput.apply(this); //for bs3 set default class `input-sm` to standard inputs var emptyInputClass = this.input.options.inputclass === null || this.input.options.inputclass === false; var defaultClass = 'input-sm'; //bs3 add `form-control` class to standard inputs var stdtypes = 'text,select,textarea,password,email,url,tel,number,range,time,typeaheadjs'.split(','); if(~$.inArray(this.input.type, stdtypes)) { this.input.$input.addClass('form-control'); if(emptyInputClass) { this.input.options.inputclass = defaultClass; this.input.$input.addClass(defaultClass); } } //apply bs3 size class also to buttons (to fit size of control) var $btn = this.$form.find('.editable-buttons'); var classes = emptyInputClass ? [defaultClass] : this.input.options.inputclass.split(' '); for(var i=0; i<classes.length; i++) { // `btn-sm` is default now /* if(classes[i].toLowerCase() === 'input-sm') { $btn.find('button').addClass('btn-sm'); } */ if(classes[i].toLowerCase() === 'input-lg') { $btn.find('button').removeClass('btn-sm').addClass('btn-lg'); } } } }); //buttons $.fn.editableform.buttons = '<button type="submit" class="btn btn-primary btn-sm editable-submit">'+ '<i class="glyphicon glyphicon-ok"></i>'+ '</button>'+ '<button type="button" class="btn btn-default btn-sm editable-cancel">'+ '<i class="glyphicon glyphicon-remove"></i>'+ '</button>'; //error classes $.fn.editableform.errorGroupClass = 'has-error'; $.fn.editableform.errorBlockClass = null; //engine $.fn.editableform.engine = 'bs3'; }(window.jQuery)); /** * Editable Popover3 (for Bootstrap 3) * --------------------- * requires bootstrap-popover.js */ (function ($) { "use strict"; //extend methods $.extend($.fn.editableContainer.Popup.prototype, { containerName: 'popover', containerDataName: 'bs.popover', innerCss: '.popover-content', defaults: $.fn.popover.Constructor.DEFAULTS, initContainer: function(){ $.extend(this.containerOptions, { trigger: 'manual', selector: false, content: ' ', template: this.defaults.template }); //as template property is used in inputs, hide it from popover var t; if(this.$element.data('template')) { t = this.$element.data('template'); this.$element.removeData('template'); } this.call(this.containerOptions); if(t) { //restore data('template') this.$element.data('template', t); } }, /* show */ innerShow: function () { this.call('show'); }, /* hide */ innerHide: function () { this.call('hide'); }, /* destroy */ innerDestroy: function() { this.call('destroy'); }, setContainerOption: function(key, value) { this.container().options[key] = value; }, /** * move popover to new position. This function mainly copied from bootstrap-popover. */ /*jshint laxcomma: true, eqeqeq: false*/ setPosition: function () { (function() { /* var $tip = this.tip() , inside , pos , actualWidth , actualHeight , placement , tp , tpt , tpb , tpl , tpr; placement = typeof this.options.placement === 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement; inside = /in/.test(placement); $tip // .detach() //vitalets: remove any placement class because otherwise they dont influence on re-positioning of visible popover .removeClass('top right bottom left') .css({ top: 0, left: 0, display: 'block' }); // .insertAfter(this.$element); pos = this.getPosition(inside); actualWidth = $tip[0].offsetWidth; actualHeight = $tip[0].offsetHeight; placement = inside ? placement.split(' ')[1] : placement; tpb = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2}; tpt = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2}; tpl = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth}; tpr = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width}; switch (placement) { case 'bottom': if ((tpb.top + actualHeight) > ($(window).scrollTop() + $(window).height())) { if (tpt.top > $(window).scrollTop()) { placement = 'top'; } else if ((tpr.left + actualWidth) < ($(window).scrollLeft() + $(window).width())) { placement = 'right'; } else if (tpl.left > $(window).scrollLeft()) { placement = 'left'; } else { placement = 'right'; } } break; case 'top': if (tpt.top < $(window).scrollTop()) { if ((tpb.top + actualHeight) < ($(window).scrollTop() + $(window).height())) { placement = 'bottom'; } else if ((tpr.left + actualWidth) < ($(window).scrollLeft() + $(window).width())) { placement = 'right'; } else if (tpl.left > $(window).scrollLeft()) { placement = 'left'; } else { placement = 'right'; } } break; case 'left': if (tpl.left < $(window).scrollLeft()) { if ((tpr.left + actualWidth) < ($(window).scrollLeft() + $(window).width())) { placement = 'right'; } else if (tpt.top > $(window).scrollTop()) { placement = 'top'; } else if (tpt.top > $(window).scrollTop()) { placement = 'bottom'; } else { placement = 'right'; } } break; case 'right': if ((tpr.left + actualWidth) > ($(window).scrollLeft() + $(window).width())) { if (tpl.left > $(window).scrollLeft()) { placement = 'left'; } else if (tpt.top > $(window).scrollTop()) { placement = 'top'; } else if (tpt.top > $(window).scrollTop()) { placement = 'bottom'; } } break; } switch (placement) { case 'bottom': tp = tpb; break; case 'top': tp = tpt; break; case 'left': tp = tpl; break; case 'right': tp = tpr; break; } $tip .offset(tp) .addClass(placement) .addClass('in'); */ var $tip = this.tip(); var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement; var pos = this.getPosition(); var actualWidth = $tip[0].offsetWidth; var actualHeight = $tip[0].offsetHeight; var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight); this.applyPlacement(calculatedOffset, placement); }).call(this.container()); /*jshint laxcomma: false, eqeqeq: true*/ } }); }(window.jQuery)); /* ========================================================= * bootstrap-datepicker.js * http://www.eyecon.ro/bootstrap-datepicker * ========================================================= * Copyright 2012 Stefan Petre * Improvements by Andrew Rowls * * 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. * ========================================================= */ (function( $ ) { function UTCDate(){ return new Date(Date.UTC.apply(Date, arguments)); } function UTCToday(){ var today = new Date(); return UTCDate(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate()); } // Picker object var Datepicker = function(element, options) { var that = this; this._process_options(options); this.element = $(element); this.isInline = false; this.isInput = this.element.is('input'); this.component = this.element.is('.date') ? this.element.find('.add-on, .btn') : false; this.hasInput = this.component && this.element.find('input').length; if(this.component && this.component.length === 0) this.component = false; this.picker = $(DPGlobal.template); this._buildEvents(); this._attachEvents(); if(this.isInline) { this.picker.addClass('datepicker-inline').appendTo(this.element); } else { this.picker.addClass('datepicker-dropdown dropdown-menu'); } if (this.o.rtl){ this.picker.addClass('datepicker-rtl'); this.picker.find('.prev i, .next i') .toggleClass('icon-arrow-left icon-arrow-right'); } this.viewMode = this.o.startView; if (this.o.calendarWeeks) this.picker.find('tfoot th.today') .attr('colspan', function(i, val){ return parseInt(val) + 1; }); this._allow_update = false; this.setStartDate(this.o.startDate); this.setEndDate(this.o.endDate); this.setDaysOfWeekDisabled(this.o.daysOfWeekDisabled); this.fillDow(); this.fillMonths(); this._allow_update = true; this.update(); this.showMode(); if(this.isInline) { this.show(); } }; Datepicker.prototype = { constructor: Datepicker, _process_options: function(opts){ // Store raw options for reference this._o = $.extend({}, this._o, opts); // Processed options var o = this.o = $.extend({}, this._o); // Check if "de-DE" style date is available, if not language should // fallback to 2 letter code eg "de" var lang = o.language; if (!dates[lang]) { lang = lang.split('-')[0]; if (!dates[lang]) lang = defaults.language; } o.language = lang; switch(o.startView){ case 2: case 'decade': o.startView = 2; break; case 1: case 'year': o.startView = 1; break; default: o.startView = 0; } switch (o.minViewMode) { case 1: case 'months': o.minViewMode = 1; break; case 2: case 'years': o.minViewMode = 2; break; default: o.minViewMode = 0; } o.startView = Math.max(o.startView, o.minViewMode); o.weekStart %= 7; o.weekEnd = ((o.weekStart + 6) % 7); var format = DPGlobal.parseFormat(o.format) if (o.startDate !== -Infinity) { o.startDate = DPGlobal.parseDate(o.startDate, format, o.language); } if (o.endDate !== Infinity) { o.endDate = DPGlobal.parseDate(o.endDate, format, o.language); } o.daysOfWeekDisabled = o.daysOfWeekDisabled||[]; if (!$.isArray(o.daysOfWeekDisabled)) o.daysOfWeekDisabled = o.daysOfWeekDisabled.split(/[,\s]*/); o.daysOfWeekDisabled = $.map(o.daysOfWeekDisabled, function (d) { return parseInt(d, 10); }); }, _events: [], _secondaryEvents: [], _applyEvents: function(evs){ for (var i=0, el, ev; i<evs.length; i++){ el = evs[i][0]; ev = evs[i][1]; el.on(ev); } }, _unapplyEvents: function(evs){ for (var i=0, el, ev; i<evs.length; i++){ el = evs[i][0]; ev = evs[i][1]; el.off(ev); } }, _buildEvents: function(){ if (this.isInput) { // single input this._events = [ [this.element, { focus: $.proxy(this.show, this), keyup: $.proxy(this.update, this), keydown: $.proxy(this.keydown, this) }] ]; } else if (this.component && this.hasInput){ // component: input + button this._events = [ // For components that are not readonly, allow keyboard nav [this.element.find('input'), { focus: $.proxy(this.show, this), keyup: $.proxy(this.update, this), keydown: $.proxy(this.keydown, this) }], [this.component, { click: $.proxy(this.show, this) }] ]; } else if (this.element.is('div')) { // inline datepicker this.isInline = true; } else { this._events = [ [this.element, { click: $.proxy(this.show, this) }] ]; } this._secondaryEvents = [ [this.picker, { click: $.proxy(this.click, this) }], [$(window), { resize: $.proxy(this.place, this) }], [$(document), { mousedown: $.proxy(function (e) { // Clicked outside the datepicker, hide it if (!( this.element.is(e.target) || this.element.find(e.target).size() || this.picker.is(e.target) || this.picker.find(e.target).size() )) { this.hide(); } }, this) }] ]; }, _attachEvents: function(){ this._detachEvents(); this._applyEvents(this._events); }, _detachEvents: function(){ this._unapplyEvents(this._events); }, _attachSecondaryEvents: function(){ this._detachSecondaryEvents(); this._applyEvents(this._secondaryEvents); }, _detachSecondaryEvents: function(){ this._unapplyEvents(this._secondaryEvents); }, _trigger: function(event, altdate){ var date = altdate || this.date, local_date = new Date(date.getTime() + (date.getTimezoneOffset()*60000)); this.element.trigger({ type: event, date: local_date, format: $.proxy(function(altformat){ var format = altformat || this.o.format; return DPGlobal.formatDate(date, format, this.o.language); }, this) }); }, show: function(e) { if (!this.isInline) this.picker.appendTo('body'); this.picker.show(); this.height = this.component ? this.component.outerHeight() : this.element.outerHeight(); this.place(); this._attachSecondaryEvents(); if (e) { e.preventDefault(); } this._trigger('show'); }, hide: function(e){ if(this.isInline) return; if (!this.picker.is(':visible')) return; this.picker.hide().detach(); this._detachSecondaryEvents(); this.viewMode = this.o.startView; this.showMode(); if ( this.o.forceParse && ( this.isInput && this.element.val() || this.hasInput && this.element.find('input').val() ) ) this.setValue(); this._trigger('hide'); }, remove: function() { this.hide(); this._detachEvents(); this._detachSecondaryEvents(); this.picker.remove(); delete this.element.data().datepicker; if (!this.isInput) { delete this.element.data().date; } }, getDate: function() { var d = this.getUTCDate(); return new Date(d.getTime() + (d.getTimezoneOffset()*60000)); }, getUTCDate: function() { return this.date; }, setDate: function(d) { this.setUTCDate(new Date(d.getTime() - (d.getTimezoneOffset()*60000))); }, setUTCDate: function(d) { this.date = d; this.setValue(); }, setValue: function() { var formatted = this.getFormattedDate(); if (!this.isInput) { if (this.component){ this.element.find('input').val(formatted); } } else { this.element.val(formatted); } }, getFormattedDate: function(format) { if (format === undefined) format = this.o.format; return DPGlobal.formatDate(this.date, format, this.o.language); }, setStartDate: function(startDate){ this._process_options({startDate: startDate}); this.update(); this.updateNavArrows(); }, setEndDate: function(endDate){ this._process_options({endDate: endDate}); this.update(); this.updateNavArrows(); }, setDaysOfWeekDisabled: function(daysOfWeekDisabled){ this._process_options({daysOfWeekDisabled: daysOfWeekDisabled}); this.update(); this.updateNavArrows(); }, place: function(){ if(this.isInline) return; var zIndex = parseInt(this.element.parents().filter(function() { return $(this).css('z-index') != 'auto'; }).first().css('z-index'))+10; var offset = this.component ? this.component.parent().offset() : this.element.offset(); var height = this.component ? this.component.outerHeight(true) : this.element.outerHeight(true); this.picker.css({ top: offset.top + height, left: offset.left, zIndex: zIndex }); }, _allow_update: true, update: function(){ if (!this._allow_update) return; var date, fromArgs = false; if(arguments && arguments.length && (typeof arguments[0] === 'string' || arguments[0] instanceof Date)) { date = arguments[0]; fromArgs = true; } else { date = this.isInput ? this.element.val() : this.element.data('date') || this.element.find('input').val(); delete this.element.data().date; } this.date = DPGlobal.parseDate(date, this.o.format, this.o.language); if(fromArgs) this.setValue(); if (this.date < this.o.startDate) { this.viewDate = new Date(this.o.startDate); } else if (this.date > this.o.endDate) { this.viewDate = new Date(this.o.endDate); } else { this.viewDate = new Date(this.date); } this.fill(); }, fillDow: function(){ var dowCnt = this.o.weekStart, html = '<tr>'; if(this.o.calendarWeeks){ var cell = '<th class="cw">&nbsp;</th>'; html += cell; this.picker.find('.datepicker-days thead tr:first-child').prepend(cell); } while (dowCnt < this.o.weekStart + 7) { html += '<th class="dow">'+dates[this.o.language].daysMin[(dowCnt++)%7]+'</th>'; } html += '</tr>'; this.picker.find('.datepicker-days thead').append(html); }, fillMonths: function(){ var html = '', i = 0; while (i < 12) { html += '<span class="month">'+dates[this.o.language].monthsShort[i++]+'</span>'; } this.picker.find('.datepicker-months td').html(html); }, setRange: function(range){ if (!range || !range.length) delete this.range; else this.range = $.map(range, function(d){ return d.valueOf(); }); this.fill(); }, getClassNames: function(date){ var cls = [], year = this.viewDate.getUTCFullYear(), month = this.viewDate.getUTCMonth(), currentDate = this.date.valueOf(), today = new Date(); if (date.getUTCFullYear() < year || (date.getUTCFullYear() == year && date.getUTCMonth() < month)) { cls.push('old'); } else if (date.getUTCFullYear() > year || (date.getUTCFullYear() == year && date.getUTCMonth() > month)) { cls.push('new'); } // Compare internal UTC date with local today, not UTC today if (this.o.todayHighlight && date.getUTCFullYear() == today.getFullYear() && date.getUTCMonth() == today.getMonth() && date.getUTCDate() == today.getDate()) { cls.push('today'); } if (currentDate && date.valueOf() == currentDate) { cls.push('active'); } if (date.valueOf() < this.o.startDate || date.valueOf() > this.o.endDate || $.inArray(date.getUTCDay(), this.o.daysOfWeekDisabled) !== -1) { cls.push('disabled'); } if (this.range){ if (date > this.range[0] && date < this.range[this.range.length-1]){ cls.push('range'); } if ($.inArray(date.valueOf(), this.range) != -1){ cls.push('selected'); } } return cls; }, fill: function() { var d = new Date(this.viewDate), year = d.getUTCFullYear(), month = d.getUTCMonth(), startYear = this.o.startDate !== -Infinity ? this.o.startDate.getUTCFullYear() : -Infinity, startMonth = this.o.startDate !== -Infinity ? this.o.startDate.getUTCMonth() : -Infinity, endYear = this.o.endDate !== Infinity ? this.o.endDate.getUTCFullYear() : Infinity, endMonth = this.o.endDate !== Infinity ? this.o.endDate.getUTCMonth() : Infinity, currentDate = this.date && this.date.valueOf(), tooltip; this.picker.find('.datepicker-days thead th.datepicker-switch') .text(dates[this.o.language].months[month]+' '+year); this.picker.find('tfoot th.today') .text(dates[this.o.language].today) .toggle(this.o.todayBtn !== false); this.picker.find('tfoot th.clear') .text(dates[this.o.language].clear) .toggle(this.o.clearBtn !== false); this.updateNavArrows(); this.fillMonths(); var prevMonth = UTCDate(year, month-1, 28,0,0,0,0), day = DPGlobal.getDaysInMonth(prevMonth.getUTCFullYear(), prevMonth.getUTCMonth()); prevMonth.setUTCDate(day); prevMonth.setUTCDate(day - (prevMonth.getUTCDay() - this.o.weekStart + 7)%7); var nextMonth = new Date(prevMonth); nextMonth.setUTCDate(nextMonth.getUTCDate() + 42); nextMonth = nextMonth.valueOf(); var html = []; var clsName; while(prevMonth.valueOf() < nextMonth) { if (prevMonth.getUTCDay() == this.o.weekStart) { html.push('<tr>'); if(this.o.calendarWeeks){ // ISO 8601: First week contains first thursday. // ISO also states week starts on Monday, but we can be more abstract here. var // Start of current week: based on weekstart/current date ws = new Date(+prevMonth + (this.o.weekStart - prevMonth.getUTCDay() - 7) % 7 * 864e5), // Thursday of this week th = new Date(+ws + (7 + 4 - ws.getUTCDay()) % 7 * 864e5), // First Thursday of year, year from thursday yth = new Date(+(yth = UTCDate(th.getUTCFullYear(), 0, 1)) + (7 + 4 - yth.getUTCDay())%7*864e5), // Calendar week: ms between thursdays, div ms per day, div 7 days calWeek = (th - yth) / 864e5 / 7 + 1; html.push('<td class="cw">'+ calWeek +'</td>'); } } clsName = this.getClassNames(prevMonth); clsName.push('day'); var before = this.o.beforeShowDay(prevMonth); if (before === undefined) before = {}; else if (typeof(before) === 'boolean') before = {enabled: before}; else if (typeof(before) === 'string') before = {classes: before}; if (before.enabled === false) clsName.push('disabled'); if (before.classes) clsName = clsName.concat(before.classes.split(/\s+/)); if (before.tooltip) tooltip = before.tooltip; clsName = $.unique(clsName); html.push('<td class="'+clsName.join(' ')+'"' + (tooltip ? ' title="'+tooltip+'"' : '') + '>'+prevMonth.getUTCDate() + '</td>'); if (prevMonth.getUTCDay() == this.o.weekEnd) { html.push('</tr>'); } prevMonth.setUTCDate(prevMonth.getUTCDate()+1); } this.picker.find('.datepicker-days tbody').empty().append(html.join('')); var currentYear = this.date && this.date.getUTCFullYear(); var months = this.picker.find('.datepicker-months') .find('th:eq(1)') .text(year) .end() .find('span').removeClass('active'); if (currentYear && currentYear == year) { months.eq(this.date.getUTCMonth()).addClass('active'); } if (year < startYear || year > endYear) { months.addClass('disabled'); } if (year == startYear) { months.slice(0, startMonth).addClass('disabled'); } if (year == endYear) { months.slice(endMonth+1).addClass('disabled'); } html = ''; year = parseInt(year/10, 10) * 10; var yearCont = this.picker.find('.datepicker-years') .find('th:eq(1)') .text(year + '-' + (year + 9)) .end() .find('td'); year -= 1; for (var i = -1; i < 11; i++) { html += '<span class="year'+(i == -1 ? ' old' : i == 10 ? ' new' : '')+(currentYear == year ? ' active' : '')+(year < startYear || year > endYear ? ' disabled' : '')+'">'+year+'</span>'; year += 1; } yearCont.html(html); }, updateNavArrows: function() { if (!this._allow_update) return; var d = new Date(this.viewDate), year = d.getUTCFullYear(), month = d.getUTCMonth(); switch (this.viewMode) { case 0: if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear() && month <= this.o.startDate.getUTCMonth()) { this.picker.find('.prev').css({visibility: 'hidden'}); } else { this.picker.find('.prev').css({visibility: 'visible'}); } if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear() && month >= this.o.endDate.getUTCMonth()) { this.picker.find('.next').css({visibility: 'hidden'}); } else { this.picker.find('.next').css({visibility: 'visible'}); } break; case 1: case 2: if (this.o.startDate !== -Infinity && year <= this.o.startDate.getUTCFullYear()) { this.picker.find('.prev').css({visibility: 'hidden'}); } else { this.picker.find('.prev').css({visibility: 'visible'}); } if (this.o.endDate !== Infinity && year >= this.o.endDate.getUTCFullYear()) { this.picker.find('.next').css({visibility: 'hidden'}); } else { this.picker.find('.next').css({visibility: 'visible'}); } break; } }, click: function(e) { e.preventDefault(); var target = $(e.target).closest('span, td, th'); if (target.length == 1) { switch(target[0].nodeName.toLowerCase()) { case 'th': switch(target[0].className) { case 'datepicker-switch': this.showMode(1); break; case 'prev': case 'next': var dir = DPGlobal.modes[this.viewMode].navStep * (target[0].className == 'prev' ? -1 : 1); switch(this.viewMode){ case 0: this.viewDate = this.moveMonth(this.viewDate, dir); break; case 1: case 2: this.viewDate = this.moveYear(this.viewDate, dir); break; } this.fill(); break; case 'today': var date = new Date(); date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); this.showMode(-2); var which = this.o.todayBtn == 'linked' ? null : 'view'; this._setDate(date, which); break; case 'clear': var element; if (this.isInput) element = this.element; else if (this.component) element = this.element.find('input'); if (element) element.val("").change(); this._trigger('changeDate'); this.update(); if (this.o.autoclose) this.hide(); break; } break; case 'span': if (!target.is('.disabled')) { this.viewDate.setUTCDate(1); if (target.is('.month')) { var day = 1; var month = target.parent().find('span').index(target); var year = this.viewDate.getUTCFullYear(); this.viewDate.setUTCMonth(month); this._trigger('changeMonth', this.viewDate); if (this.o.minViewMode === 1) { this._setDate(UTCDate(year, month, day,0,0,0,0)); } } else { var year = parseInt(target.text(), 10)||0; var day = 1; var month = 0; this.viewDate.setUTCFullYear(year); this._trigger('changeYear', this.viewDate); if (this.o.minViewMode === 2) { this._setDate(UTCDate(year, month, day,0,0,0,0)); } } this.showMode(-1); this.fill(); } break; case 'td': if (target.is('.day') && !target.is('.disabled')){ var day = parseInt(target.text(), 10)||1; var year = this.viewDate.getUTCFullYear(), month = this.viewDate.getUTCMonth(); if (target.is('.old')) { if (month === 0) { month = 11; year -= 1; } else { month -= 1; } } else if (target.is('.new')) { if (month == 11) { month = 0; year += 1; } else { month += 1; } } this._setDate(UTCDate(year, month, day,0,0,0,0)); } break; } } }, _setDate: function(date, which){ if (!which || which == 'date') this.date = new Date(date); if (!which || which == 'view') this.viewDate = new Date(date); this.fill(); this.setValue(); this._trigger('changeDate'); var element; if (this.isInput) { element = this.element; } else if (this.component){ element = this.element.find('input'); } if (element) { element.change(); if (this.o.autoclose && (!which || which == 'date')) { this.hide(); } } }, moveMonth: function(date, dir){ if (!dir) return date; var new_date = new Date(date.valueOf()), day = new_date.getUTCDate(), month = new_date.getUTCMonth(), mag = Math.abs(dir), new_month, test; dir = dir > 0 ? 1 : -1; if (mag == 1){ test = dir == -1 // If going back one month, make sure month is not current month // (eg, Mar 31 -> Feb 31 == Feb 28, not Mar 02) ? function(){ return new_date.getUTCMonth() == month; } // If going forward one month, make sure month is as expected // (eg, Jan 31 -> Feb 31 == Feb 28, not Mar 02) : function(){ return new_date.getUTCMonth() != new_month; }; new_month = month + dir; new_date.setUTCMonth(new_month); // Dec -> Jan (12) or Jan -> Dec (-1) -- limit expected date to 0-11 if (new_month < 0 || new_month > 11) new_month = (new_month + 12) % 12; } else { // For magnitudes >1, move one month at a time... for (var i=0; i<mag; i++) // ...which might decrease the day (eg, Jan 31 to Feb 28, etc)... new_date = this.moveMonth(new_date, dir); // ...then reset the day, keeping it in the new month new_month = new_date.getUTCMonth(); new_date.setUTCDate(day); test = function(){ return new_month != new_date.getUTCMonth(); }; } // Common date-resetting loop -- if date is beyond end of month, make it // end of month while (test()){ new_date.setUTCDate(--day); new_date.setUTCMonth(new_month); } return new_date; }, moveYear: function(date, dir){ return this.moveMonth(date, dir*12); }, dateWithinRange: function(date){ return date >= this.o.startDate && date <= this.o.endDate; }, keydown: function(e){ if (this.picker.is(':not(:visible)')){ if (e.keyCode == 27) // allow escape to hide and re-show picker this.show(); return; } var dateChanged = false, dir, day, month, newDate, newViewDate; switch(e.keyCode){ case 27: // escape this.hide(); e.preventDefault(); break; case 37: // left case 39: // right if (!this.o.keyboardNavigation) break; dir = e.keyCode == 37 ? -1 : 1; if (e.ctrlKey){ newDate = this.moveYear(this.date, dir); newViewDate = this.moveYear(this.viewDate, dir); } else if (e.shiftKey){ newDate = this.moveMonth(this.date, dir); newViewDate = this.moveMonth(this.viewDate, dir); } else { newDate = new Date(this.date); newDate.setUTCDate(this.date.getUTCDate() + dir); newViewDate = new Date(this.viewDate); newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir); } if (this.dateWithinRange(newDate)){ this.date = newDate; this.viewDate = newViewDate; this.setValue(); this.update(); e.preventDefault(); dateChanged = true; } break; case 38: // up case 40: // down if (!this.o.keyboardNavigation) break; dir = e.keyCode == 38 ? -1 : 1; if (e.ctrlKey){ newDate = this.moveYear(this.date, dir); newViewDate = this.moveYear(this.viewDate, dir); } else if (e.shiftKey){ newDate = this.moveMonth(this.date, dir); newViewDate = this.moveMonth(this.viewDate, dir); } else { newDate = new Date(this.date); newDate.setUTCDate(this.date.getUTCDate() + dir * 7); newViewDate = new Date(this.viewDate); newViewDate.setUTCDate(this.viewDate.getUTCDate() + dir * 7); } if (this.dateWithinRange(newDate)){ this.date = newDate; this.viewDate = newViewDate; this.setValue(); this.update(); e.preventDefault(); dateChanged = true; } break; case 13: // enter this.hide(); e.preventDefault(); break; case 9: // tab this.hide(); break; } if (dateChanged){ this._trigger('changeDate'); var element; if (this.isInput) { element = this.element; } else if (this.component){ element = this.element.find('input'); } if (element) { element.change(); } } }, showMode: function(dir) { if (dir) { this.viewMode = Math.max(this.o.minViewMode, Math.min(2, this.viewMode + dir)); } /* vitalets: fixing bug of very special conditions: jquery 1.7.1 + webkit + show inline datepicker in bootstrap popover. Method show() does not set display css correctly and datepicker is not shown. Changed to .css('display', 'block') solve the problem. See https://github.com/vitalets/x-editable/issues/37 In jquery 1.7.2+ everything works fine. */ //this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show(); this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).css('display', 'block'); this.updateNavArrows(); } }; var DateRangePicker = function(element, options){ this.element = $(element); this.inputs = $.map(options.inputs, function(i){ return i.jquery ? i[0] : i; }); delete options.inputs; $(this.inputs) .datepicker(options) .bind('changeDate', $.proxy(this.dateUpdated, this)); this.pickers = $.map(this.inputs, function(i){ return $(i).data('datepicker'); }); this.updateDates(); }; DateRangePicker.prototype = { updateDates: function(){ this.dates = $.map(this.pickers, function(i){ return i.date; }); this.updateRanges(); }, updateRanges: function(){ var range = $.map(this.dates, function(d){ return d.valueOf(); }); $.each(this.pickers, function(i, p){ p.setRange(range); }); }, dateUpdated: function(e){ var dp = $(e.target).data('datepicker'), new_date = dp.getUTCDate(), i = $.inArray(e.target, this.inputs), l = this.inputs.length; if (i == -1) return; if (new_date < this.dates[i]){ // Date being moved earlier/left while (i>=0 && new_date < this.dates[i]){ this.pickers[i--].setUTCDate(new_date); } } else if (new_date > this.dates[i]){ // Date being moved later/right while (i<l && new_date > this.dates[i]){ this.pickers[i++].setUTCDate(new_date); } } this.updateDates(); }, remove: function(){ $.map(this.pickers, function(p){ p.remove(); }); delete this.element.data().datepicker; } }; function opts_from_el(el, prefix){ // Derive options from element data-attrs var data = $(el).data(), out = {}, inkey, replace = new RegExp('^' + prefix.toLowerCase() + '([A-Z])'), prefix = new RegExp('^' + prefix.toLowerCase()); for (var key in data) if (prefix.test(key)){ inkey = key.replace(replace, function(_,a){ return a.toLowerCase(); }); out[inkey] = data[key]; } return out; } function opts_from_locale(lang){ // Derive options from locale plugins var out = {}; // Check if "de-DE" style date is available, if not language should // fallback to 2 letter code eg "de" if (!dates[lang]) { lang = lang.split('-')[0] if (!dates[lang]) return; } var d = dates[lang]; $.each(locale_opts, function(i,k){ if (k in d) out[k] = d[k]; }); return out; } var old = $.fn.datepicker; var datepicker = $.fn.datepicker = function ( option ) { var args = Array.apply(null, arguments); args.shift(); var internal_return, this_return; this.each(function () { var $this = $(this), data = $this.data('datepicker'), options = typeof option == 'object' && option; if (!data) { var elopts = opts_from_el(this, 'date'), // Preliminary otions xopts = $.extend({}, defaults, elopts, options), locopts = opts_from_locale(xopts.language), // Options priority: js args, data-attrs, locales, defaults opts = $.extend({}, defaults, locopts, elopts, options); if ($this.is('.input-daterange') || opts.inputs){ var ropts = { inputs: opts.inputs || $this.find('input').toArray() }; $this.data('datepicker', (data = new DateRangePicker(this, $.extend(opts, ropts)))); } else{ $this.data('datepicker', (data = new Datepicker(this, opts))); } } if (typeof option == 'string' && typeof data[option] == 'function') { internal_return = data[option].apply(data, args); if (internal_return !== undefined) return false; } }); if (internal_return !== undefined) return internal_return; else return this; }; var defaults = $.fn.datepicker.defaults = { autoclose: false, beforeShowDay: $.noop, calendarWeeks: false, clearBtn: false, daysOfWeekDisabled: [], endDate: Infinity, forceParse: true, format: 'mm/dd/yyyy', keyboardNavigation: true, language: 'en', minViewMode: 0, rtl: false, startDate: -Infinity, startView: 0, todayBtn: false, todayHighlight: false, weekStart: 0 }; var locale_opts = $.fn.datepicker.locale_opts = [ 'format', 'rtl', 'weekStart' ]; $.fn.datepicker.Constructor = Datepicker; var dates = $.fn.datepicker.dates = { en: { days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"], daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"], months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], today: "Today", clear: "Clear" } }; var DPGlobal = { modes: [ { clsName: 'days', navFnc: 'Month', navStep: 1 }, { clsName: 'months', navFnc: 'FullYear', navStep: 1 }, { clsName: 'years', navFnc: 'FullYear', navStep: 10 }], isLeapYear: function (year) { return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)); }, getDaysInMonth: function (year, month) { return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]; }, validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g, nonpunctuation: /[^ -\/:-@\[\u3400-\u9fff-`{-~\t\n\r]+/g, parseFormat: function(format){ // IE treats \0 as a string end in inputs (truncating the value), // so it's a bad format delimiter, anyway var separators = format.replace(this.validParts, '\0').split('\0'), parts = format.match(this.validParts); if (!separators || !separators.length || !parts || parts.length === 0){ throw new Error("Invalid date format."); } return {separators: separators, parts: parts}; }, parseDate: function(date, format, language) { if (date instanceof Date) return date; if (typeof format === 'string') format = DPGlobal.parseFormat(format); if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(date)) { var part_re = /([\-+]\d+)([dmwy])/, parts = date.match(/([\-+]\d+)([dmwy])/g), part, dir; date = new Date(); for (var i=0; i<parts.length; i++) { part = part_re.exec(parts[i]); dir = parseInt(part[1]); switch(part[2]){ case 'd': date.setUTCDate(date.getUTCDate() + dir); break; case 'm': date = Datepicker.prototype.moveMonth.call(Datepicker.prototype, date, dir); break; case 'w': date.setUTCDate(date.getUTCDate() + dir * 7); break; case 'y': date = Datepicker.prototype.moveYear.call(Datepicker.prototype, date, dir); break; } } return UTCDate(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), 0, 0, 0); } var parts = date && date.match(this.nonpunctuation) || [], date = new Date(), parsed = {}, setters_order = ['yyyy', 'yy', 'M', 'MM', 'm', 'mm', 'd', 'dd'], setters_map = { yyyy: function(d,v){ return d.setUTCFullYear(v); }, yy: function(d,v){ return d.setUTCFullYear(2000+v); }, m: function(d,v){ v -= 1; while (v<0) v += 12; v %= 12; d.setUTCMonth(v); while (d.getUTCMonth() != v) d.setUTCDate(d.getUTCDate()-1); return d; }, d: function(d,v){ return d.setUTCDate(v); } }, val, filtered, part; setters_map['M'] = setters_map['MM'] = setters_map['mm'] = setters_map['m']; setters_map['dd'] = setters_map['d']; date = UTCDate(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); var fparts = format.parts.slice(); // Remove noop parts if (parts.length != fparts.length) { fparts = $(fparts).filter(function(i,p){ return $.inArray(p, setters_order) !== -1; }).toArray(); } // Process remainder if (parts.length == fparts.length) { for (var i=0, cnt = fparts.length; i < cnt; i++) { val = parseInt(parts[i], 10); part = fparts[i]; if (isNaN(val)) { switch(part) { case 'MM': filtered = $(dates[language].months).filter(function(){ var m = this.slice(0, parts[i].length), p = parts[i].slice(0, m.length); return m == p; }); val = $.inArray(filtered[0], dates[language].months) + 1; break; case 'M': filtered = $(dates[language].monthsShort).filter(function(){ var m = this.slice(0, parts[i].length), p = parts[i].slice(0, m.length); return m == p; }); val = $.inArray(filtered[0], dates[language].monthsShort) + 1; break; } } parsed[part] = val; } for (var i=0, s; i<setters_order.length; i++){ s = setters_order[i]; if (s in parsed && !isNaN(parsed[s])) setters_map[s](date, parsed[s]); } } return date; }, formatDate: function(date, format, language){ if (typeof format === 'string') format = DPGlobal.parseFormat(format); var val = { d: date.getUTCDate(), D: dates[language].daysShort[date.getUTCDay()], DD: dates[language].days[date.getUTCDay()], m: date.getUTCMonth() + 1, M: dates[language].monthsShort[date.getUTCMonth()], MM: dates[language].months[date.getUTCMonth()], yy: date.getUTCFullYear().toString().substring(2), yyyy: date.getUTCFullYear() }; val.dd = (val.d < 10 ? '0' : '') + val.d; val.mm = (val.m < 10 ? '0' : '') + val.m; var date = [], seps = $.extend([], format.separators); for (var i=0, cnt = format.parts.length; i <= cnt; i++) { if (seps.length) date.push(seps.shift()); date.push(val[format.parts[i]]); } return date.join(''); }, headTemplate: '<thead>'+ '<tr>'+ '<th class="prev"><i class="icon-arrow-left"/></th>'+ '<th colspan="5" class="datepicker-switch"></th>'+ '<th class="next"><i class="icon-arrow-right"/></th>'+ '</tr>'+ '</thead>', contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>', footTemplate: '<tfoot><tr><th colspan="7" class="today"></th></tr><tr><th colspan="7" class="clear"></th></tr></tfoot>' }; DPGlobal.template = '<div class="datepicker">'+ '<div class="datepicker-days">'+ '<table class=" table-condensed">'+ DPGlobal.headTemplate+ '<tbody></tbody>'+ DPGlobal.footTemplate+ '</table>'+ '</div>'+ '<div class="datepicker-months">'+ '<table class="table-condensed">'+ DPGlobal.headTemplate+ DPGlobal.contTemplate+ DPGlobal.footTemplate+ '</table>'+ '</div>'+ '<div class="datepicker-years">'+ '<table class="table-condensed">'+ DPGlobal.headTemplate+ DPGlobal.contTemplate+ DPGlobal.footTemplate+ '</table>'+ '</div>'+ '</div>'; $.fn.datepicker.DPGlobal = DPGlobal; /* DATEPICKER NO CONFLICT * =================== */ $.fn.datepicker.noConflict = function(){ $.fn.datepicker = old; return this; }; /* DATEPICKER DATA-API * ================== */ $(document).on( 'focus.datepicker.data-api click.datepicker.data-api', '[data-provide="datepicker"]', function(e){ var $this = $(this); if ($this.data('datepicker')) return; e.preventDefault(); // component click requires us to explicitly show it datepicker.call($this, 'show'); } ); $(function(){ //$('[data-provide="datepicker-inline"]').datepicker(); //vit: changed to support noConflict() datepicker.call($('[data-provide="datepicker-inline"]')); }); }( window.jQuery )); /** Bootstrap-datepicker. Description and examples: https://github.com/eternicode/bootstrap-datepicker. For **i18n** you should include js file from here: https://github.com/eternicode/bootstrap-datepicker/tree/master/js/locales and set `language` option. Since 1.4.0 date has different appearance in **popup** and **inline** modes. @class date @extends abstractinput @final @example <a href="#" id="dob" data-type="date" data-pk="1" data-url="/post" data-title="Select date">15/05/1984</a> <script> $(function(){ $('#dob').editable({ format: 'yyyy-mm-dd', viewformat: 'dd/mm/yyyy', datepicker: { weekStart: 1 } } }); }); </script> **/ (function ($) { "use strict"; //store bootstrap-datepicker as bdateicker to exclude conflict with jQuery UI one $.fn.bdatepicker = $.fn.datepicker.noConflict(); if(!$.fn.datepicker) { //if there were no other datepickers, keep also original name $.fn.datepicker = $.fn.bdatepicker; } var Date = function (options) { this.init('date', options, Date.defaults); this.initPicker(options, Date.defaults); }; $.fn.editableutils.inherit(Date, $.fn.editabletypes.abstractinput); $.extend(Date.prototype, { initPicker: function(options, defaults) { //'format' is set directly from settings or data-* attributes //by default viewformat equals to format if(!this.options.viewformat) { this.options.viewformat = this.options.format; } //try parse datepicker config defined as json string in data-datepicker options.datepicker = $.fn.editableutils.tryParseJson(options.datepicker, true); //overriding datepicker config (as by default jQuery extend() is not recursive) //since 1.4 datepicker internally uses viewformat instead of format. Format is for submit only this.options.datepicker = $.extend({}, defaults.datepicker, options.datepicker, { format: this.options.viewformat }); //language this.options.datepicker.language = this.options.datepicker.language || 'en'; //store DPglobal this.dpg = $.fn.bdatepicker.DPGlobal; //store parsed formats this.parsedFormat = this.dpg.parseFormat(this.options.format); this.parsedViewFormat = this.dpg.parseFormat(this.options.viewformat); }, render: function () { this.$input.bdatepicker(this.options.datepicker); //"clear" link if(this.options.clear) { this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){ e.preventDefault(); e.stopPropagation(); this.clear(); }, this)); this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear)); } }, value2html: function(value, element) { var text = value ? this.dpg.formatDate(value, this.parsedViewFormat, this.options.datepicker.language) : ''; Date.superclass.value2html.call(this, text, element); }, html2value: function(html) { return this.parseDate(html, this.parsedViewFormat); }, value2str: function(value) { return value ? this.dpg.formatDate(value, this.parsedFormat, this.options.datepicker.language) : ''; }, str2value: function(str) { return this.parseDate(str, this.parsedFormat); }, value2submit: function(value) { return this.value2str(value); }, value2input: function(value) { this.$input.bdatepicker('update', value); }, input2value: function() { return this.$input.data('datepicker').date; }, activate: function() { }, clear: function() { this.$input.data('datepicker').date = null; this.$input.find('.active').removeClass('active'); if(!this.options.showbuttons) { this.$input.closest('form').submit(); } }, autosubmit: function() { this.$input.on('mouseup', '.day', function(e){ if($(e.currentTarget).is('.old') || $(e.currentTarget).is('.new')) { return; } var $form = $(this).closest('form'); setTimeout(function() { $form.submit(); }, 200); }); //changedate is not suitable as it triggered when showing datepicker. see #149 /* this.$input.on('changeDate', function(e){ var $form = $(this).closest('form'); setTimeout(function() { $form.submit(); }, 200); }); */ }, /* For incorrect date bootstrap-datepicker returns current date that is not suitable for datefield. This function returns null for incorrect date. */ parseDate: function(str, format) { var date = null, formattedBack; if(str) { date = this.dpg.parseDate(str, format, this.options.datepicker.language); if(typeof str === 'string') { formattedBack = this.dpg.formatDate(date, format, this.options.datepicker.language); if(str !== formattedBack) { date = null; } } } return date; } }); Date.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <div></div> **/ tpl:'<div class="editable-date well"></div>', /** @property inputclass @default null **/ inputclass: null, /** Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br> Possible tokens are: <code>d, dd, m, mm, yy, yyyy</code> @property format @type string @default yyyy-mm-dd **/ format:'yyyy-mm-dd', /** Format used for displaying date. Also applied when converting date from element's text on init. If not specified equals to <code>format</code> @property viewformat @type string @default null **/ viewformat: null, /** Configuration of datepicker. Full list of options: http://vitalets.github.com/bootstrap-datepicker @property datepicker @type object @default { weekStart: 0, startView: 0, minViewMode: 0, autoclose: false } **/ datepicker:{ weekStart: 0, startView: 0, minViewMode: 0, autoclose: false }, /** Text shown as clear date button. If <code>false</code> clear button will not be rendered. @property clear @type boolean|string @default 'x clear' **/ clear: '&times; clear' }); $.fn.editabletypes.date = Date; }(window.jQuery)); /** Bootstrap datefield input - modification for inline mode. Shows normal <input type="text"> and binds popup datepicker. Automatically shown in inline mode. @class datefield @extends date @since 1.4.0 **/ (function ($) { "use strict"; var DateField = function (options) { this.init('datefield', options, DateField.defaults); this.initPicker(options, DateField.defaults); }; $.fn.editableutils.inherit(DateField, $.fn.editabletypes.date); $.extend(DateField.prototype, { render: function () { this.$input = this.$tpl.find('input'); this.setClass(); this.setAttr('placeholder'); //bootstrap-datepicker is set `bdateicker` to exclude conflict with jQuery UI one. (in date.js) this.$tpl.bdatepicker(this.options.datepicker); //need to disable original event handlers this.$input.off('focus keydown'); //update value of datepicker this.$input.keyup($.proxy(function(){ this.$tpl.removeData('date'); this.$tpl.bdatepicker('update'); }, this)); }, value2input: function(value) { this.$input.val(value ? this.dpg.formatDate(value, this.parsedViewFormat, this.options.datepicker.language) : ''); this.$tpl.bdatepicker('update'); }, input2value: function() { return this.html2value(this.$input.val()); }, activate: function() { $.fn.editabletypes.text.prototype.activate.call(this); }, autosubmit: function() { //reset autosubmit to empty } }); DateField.defaults = $.extend({}, $.fn.editabletypes.date.defaults, { /** @property tpl **/ tpl:'<div class="input-append date"><input type="text"/><span class="add-on"><i class="icon-th"></i></span></div>', /** @property inputclass @default 'input-small' **/ inputclass: 'input-small', /* datepicker config */ datepicker: { weekStart: 0, startView: 0, minViewMode: 0, autoclose: true } }); $.fn.editabletypes.datefield = DateField; }(window.jQuery)); /** Bootstrap-datetimepicker. Based on [smalot bootstrap-datetimepicker plugin](https://github.com/smalot/bootstrap-datetimepicker). Before usage you should manually include dependent js and css: <link href="css/datetimepicker.css" rel="stylesheet" type="text/css"></link> <script src="js/bootstrap-datetimepicker.js"></script> For **i18n** you should include js file from here: https://github.com/smalot/bootstrap-datetimepicker/tree/master/js/locales and set `language` option. @class datetime @extends abstractinput @final @since 1.4.4 @example <a href="#" id="last_seen" data-type="datetime" data-pk="1" data-url="/post" title="Select date & time">15/03/2013 12:45</a> <script> $(function(){ $('#last_seen').editable({ format: 'yyyy-mm-dd hh:ii', viewformat: 'dd/mm/yyyy hh:ii', datetimepicker: { weekStart: 1 } } }); }); </script> **/ (function ($) { "use strict"; var DateTime = function (options) { this.init('datetime', options, DateTime.defaults); this.initPicker(options, DateTime.defaults); }; $.fn.editableutils.inherit(DateTime, $.fn.editabletypes.abstractinput); $.extend(DateTime.prototype, { initPicker: function(options, defaults) { //'format' is set directly from settings or data-* attributes //by default viewformat equals to format if(!this.options.viewformat) { this.options.viewformat = this.options.format; } //try parse datetimepicker config defined as json string in data-datetimepicker options.datetimepicker = $.fn.editableutils.tryParseJson(options.datetimepicker, true); //overriding datetimepicker config (as by default jQuery extend() is not recursive) //since 1.4 datetimepicker internally uses viewformat instead of format. Format is for submit only this.options.datetimepicker = $.extend({}, defaults.datetimepicker, options.datetimepicker, { format: this.options.viewformat }); //language this.options.datetimepicker.language = this.options.datetimepicker.language || 'en'; //store DPglobal this.dpg = $.fn.datetimepicker.DPGlobal; //store parsed formats this.parsedFormat = this.dpg.parseFormat(this.options.format, this.options.formatType); this.parsedViewFormat = this.dpg.parseFormat(this.options.viewformat, this.options.formatType); }, render: function () { this.$input.datetimepicker(this.options.datetimepicker); //adjust container position when viewMode changes //see https://github.com/smalot/bootstrap-datetimepicker/pull/80 this.$input.on('changeMode', function(e) { var f = $(this).closest('form').parent(); //timeout here, otherwise container changes position before form has new size setTimeout(function(){ f.triggerHandler('resize'); }, 0); }); //"clear" link if(this.options.clear) { this.$clear = $('<a href="#"></a>').html(this.options.clear).click($.proxy(function(e){ e.preventDefault(); e.stopPropagation(); this.clear(); }, this)); this.$tpl.parent().append($('<div class="editable-clear">').append(this.$clear)); } }, value2html: function(value, element) { //formatDate works with UTCDate! var text = value ? this.dpg.formatDate(this.toUTC(value), this.parsedViewFormat, this.options.datetimepicker.language, this.options.formatType) : ''; if(element) { DateTime.superclass.value2html.call(this, text, element); } else { return text; } }, html2value: function(html) { //parseDate return utc date! var value = this.parseDate(html, this.parsedViewFormat); return value ? this.fromUTC(value) : null; }, value2str: function(value) { //formatDate works with UTCDate! return value ? this.dpg.formatDate(this.toUTC(value), this.parsedFormat, this.options.datetimepicker.language, this.options.formatType) : ''; }, str2value: function(str) { //parseDate return utc date! var value = this.parseDate(str, this.parsedFormat); return value ? this.fromUTC(value) : null; }, value2submit: function(value) { return this.value2str(value); }, value2input: function(value) { if(value) { this.$input.data('datetimepicker').setDate(value); } }, input2value: function() { //date may be cleared, in that case getDate() triggers error var dt = this.$input.data('datetimepicker'); return dt.date ? dt.getDate() : null; }, activate: function() { }, clear: function() { this.$input.data('datetimepicker').date = null; this.$input.find('.active').removeClass('active'); if(!this.options.showbuttons) { this.$input.closest('form').submit(); } }, autosubmit: function() { this.$input.on('mouseup', '.minute', function(e){ var $form = $(this).closest('form'); setTimeout(function() { $form.submit(); }, 200); }); }, //convert date from local to utc toUTC: function(value) { return value ? new Date(value.valueOf() - value.getTimezoneOffset() * 60000) : value; }, //convert date from utc to local fromUTC: function(value) { return value ? new Date(value.valueOf() + value.getTimezoneOffset() * 60000) : value; }, /* For incorrect date bootstrap-datetimepicker returns current date that is not suitable for datetimefield. This function returns null for incorrect date. */ parseDate: function(str, format) { var date = null, formattedBack; if(str) { date = this.dpg.parseDate(str, format, this.options.datetimepicker.language, this.options.formatType); if(typeof str === 'string') { formattedBack = this.dpg.formatDate(date, format, this.options.datetimepicker.language, this.options.formatType); if(str !== formattedBack) { date = null; } } } return date; } }); DateTime.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, { /** @property tpl @default <div></div> **/ tpl:'<div class="editable-date well"></div>', /** @property inputclass @default null **/ inputclass: null, /** Format used for sending value to server. Also applied when converting date from <code>data-value</code> attribute.<br> Possible tokens are: <code>d, dd, m, mm, yy, yyyy, h, i</code> @property format @type string @default yyyy-mm-dd hh:ii **/ format:'yyyy-mm-dd hh:ii', formatType:'standard', /** Format used for displaying date. Also applied when converting date from element's text on init. If not specified equals to <code>format</code> @property viewformat @type string @default null **/ viewformat: null, /** Configuration of datetimepicker. Full list of options: https://github.com/smalot/bootstrap-datetimepicker @property datetimepicker @type object @default { } **/ datetimepicker:{ todayHighlight: false, autoclose: false }, /** Text shown as clear date button. If <code>false</code> clear button will not be rendered. @property clear @type boolean|string @default 'x clear' **/ clear: '&times; clear' }); $.fn.editabletypes.datetime = DateTime; }(window.jQuery)); /** Bootstrap datetimefield input - datetime input for inline mode. Shows normal <input type="text"> and binds popup datetimepicker. Automatically shown in inline mode. @class datetimefield @extends datetime **/ (function ($) { "use strict"; var DateTimeField = function (options) { this.init('datetimefield', options, DateTimeField.defaults); this.initPicker(options, DateTimeField.defaults); }; $.fn.editableutils.inherit(DateTimeField, $.fn.editabletypes.datetime); $.extend(DateTimeField.prototype, { render: function () { this.$input = this.$tpl.find('input'); this.setClass(); this.setAttr('placeholder'); this.$tpl.datetimepicker(this.options.datetimepicker); //need to disable original event handlers this.$input.off('focus keydown'); //update value of datepicker this.$input.keyup($.proxy(function(){ this.$tpl.removeData('date'); this.$tpl.datetimepicker('update'); }, this)); }, value2input: function(value) { this.$input.val(this.value2html(value)); this.$tpl.datetimepicker('update'); }, input2value: function() { return this.html2value(this.$input.val()); }, activate: function() { $.fn.editabletypes.text.prototype.activate.call(this); }, autosubmit: function() { //reset autosubmit to empty } }); DateTimeField.defaults = $.extend({}, $.fn.editabletypes.datetime.defaults, { /** @property tpl **/ tpl:'<div class="input-append date"><input type="text"/><span class="add-on"><i class="icon-th"></i></span></div>', /** @property inputclass @default 'input-medium' **/ inputclass: 'input-medium', /* datetimepicker config */ datetimepicker:{ todayHighlight: false, autoclose: true } }); $.fn.editabletypes.datetimefield = DateTimeField; }(window.jQuery));
JavaScript
/* * Fuel UX Wizard * https://github.com/ExactTarget/fuelux * * Copyright (c) 2012 ExactTarget * Licensed under the MIT license. */ //var $ = require('jquery'); var old = $.fn.wizard; // WIZARD CONSTRUCTOR AND PROTOTYPE var Wizard = function (element, options) { var kids; this.$element = $(element); this.options = $.extend({}, $.fn.wizard.defaults, options); this.options.disablePreviousStep = ( this.$element.data().restrict === "previous" ) ? true : false; this.currentStep = this.options.selectedItem.step; this.numSteps = this.$element.find('.steps li').length; this.$prevBtn = this.$element.find('button.btn-prev'); this.$nextBtn = this.$element.find('button.btn-next'); kids = this.$nextBtn.children().detach(); this.nextText = $.trim(this.$nextBtn.text()); this.$nextBtn.append(kids); // handle events this.$prevBtn.on('click', $.proxy(this.previous, this)); this.$nextBtn.on('click', $.proxy(this.next, this)); this.$element.on('click', 'li.complete', $.proxy(this.stepclicked, this)); if(this.currentStep > 1) { this.selectedItem(this.options.selectedItem); } if( this.options.disablePreviousStep ) { this.$prevBtn.attr( 'disabled', true ); this.$element.find( '.steps' ).addClass( 'previous-disabled' ); } }; Wizard.prototype = { constructor: Wizard, setState: function () { var canMovePrev = (this.currentStep > 1); var firstStep = (this.currentStep === 1); var lastStep = (this.currentStep === this.numSteps); // disable buttons based on current step if( !this.options.disablePreviousStep ) { this.$prevBtn.attr('disabled', (firstStep === true || canMovePrev === false)); } // change button text of last step, if specified var data = this.$nextBtn.data(); if (data && data.last) { this.lastText = data.last; if (typeof this.lastText !== 'undefined') { // replace text var text = (lastStep !== true) ? this.nextText : this.lastText; var kids = this.$nextBtn.children().detach(); this.$nextBtn.text(text).append(kids); } } // reset classes for all steps var $steps = this.$element.find('.steps li'); $steps.removeClass('active').removeClass('complete'); $steps.find('span.badge').removeClass('badge-info').removeClass('badge-success'); // set class for all previous steps var prevSelector = '.steps li:lt(' + (this.currentStep - 1) + ')'; var $prevSteps = this.$element.find(prevSelector); $prevSteps.addClass('complete'); $prevSteps.find('span.badge').addClass('badge-success'); // set class for current step var currentSelector = '.steps li:eq(' + (this.currentStep - 1) + ')'; var $currentStep = this.$element.find(currentSelector); $currentStep.addClass('active'); $currentStep.find('span.badge').addClass('badge-info'); // set display of target element var target = $currentStep.data().target; this.$element.next('.step-content').find('.step-pane').removeClass('active'); $(target).addClass('active'); // reset the wizard position to the left this.$element.find('.steps').first().attr('style','margin-left: 0'); // check if the steps are wider than the container div var totalWidth = 0; this.$element.find('.steps > li').each(function () { totalWidth += $(this).outerWidth(); }); var containerWidth = 0; if (this.$element.find('.actions').length) { containerWidth = this.$element.width() - this.$element.find('.actions').first().outerWidth(); } else { containerWidth = this.$element.width(); } if (totalWidth > containerWidth) { // set the position so that the last step is on the right var newMargin = totalWidth - containerWidth; this.$element.find('.steps').first().attr('style','margin-left: -' + newMargin + 'px'); // set the position so that the active step is in a good // position if it has been moved out of view if (this.$element.find('li.active').first().position().left < 200) { newMargin += this.$element.find('li.active').first().position().left - 200; if (newMargin < 1) { this.$element.find('.steps').first().attr('style','margin-left: 0'); } else { this.$element.find('.steps').first().attr('style','margin-left: -' + newMargin + 'px'); } } } this.$element.trigger('changed'); }, stepclicked: function (e) { var li = $(e.currentTarget); var index = this.$element.find('.steps li').index(li); var canMovePrev = true; if( this.options.disablePreviousStep ) { if( index < this.currentStep ) { canMovePrev = false; } } if( canMovePrev ) { var evt = $.Event('stepclick'); this.$element.trigger(evt, {step: index + 1}); if (evt.isDefaultPrevented()) return; this.currentStep = (index + 1); this.setState(); } }, previous: function () { var canMovePrev = (this.currentStep > 1); if( this.options.disablePreviousStep ) { canMovePrev = false; } if (canMovePrev) { var e = $.Event('change'); this.$element.trigger(e, {step: this.currentStep, direction: 'previous'}); if (e.isDefaultPrevented()) return; this.currentStep -= 1; this.setState(); } }, next: function () { var canMoveNext = (this.currentStep + 1 <= this.numSteps); var lastStep = (this.currentStep === this.numSteps); if (canMoveNext) { var e = $.Event('change'); this.$element.trigger(e, {step: this.currentStep, direction: 'next'}); if (e.isDefaultPrevented()) return; this.currentStep += 1; this.setState(); } else if (lastStep) { this.$element.trigger('finished'); } }, selectedItem: function (selectedItem) { var retVal, step; if(selectedItem) { step = selectedItem.step || -1; if(step >= 1 && step <= this.numSteps) { this.currentStep = step; this.setState(); } retVal = this; } else { retVal = { step: this.currentStep }; } return retVal; } }; // WIZARD PLUGIN DEFINITION $.fn.wizard = function (option) { var args = Array.prototype.slice.call( arguments, 1 ); var methodReturn; var $set = this.each(function () { var $this = $( this ); var data = $this.data( 'wizard' ); var options = typeof option === 'object' && option; if( !data ) $this.data('wizard', (data = new Wizard( this, options ) ) ); if( typeof option === 'string' ) methodReturn = data[ option ].apply( data, args ); }); return ( methodReturn === undefined ) ? $set : methodReturn; }; $.fn.wizard.defaults = { selectedItem: {step:1} }; $.fn.wizard.Constructor = Wizard; $.fn.wizard.noConflict = function () { $.fn.wizard = old; return this; }; // WIZARD DATA-API $(function () { $('body').on('mouseover.wizard.data-api', '.wizard', function () { var $this = $(this); if ($this.data('wizard')) return; $this.wizard($this.data()); }); });
JavaScript
/*! * jQuery Migrate - v1.2.1 - 2013-05-08 * https://github.com/jquery/jquery-migrate * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors; Licensed MIT */ (function( jQuery, window, undefined ) { // See http://bugs.jquery.com/ticket/13335 // "use strict"; var warnedAbout = {}; // List of warnings already given; public read only jQuery.migrateWarnings = []; // Set to true to prevent console output; migrateWarnings still maintained // jQuery.migrateMute = false; // Show a message on the console so devs know we're active if ( !jQuery.migrateMute && window.console && window.console.log ) { window.console.log("JQMIGRATE: Logging is active"); } // Set to false to disable traces that appear with warnings if ( jQuery.migrateTrace === undefined ) { jQuery.migrateTrace = true; } // Forget any warnings we've already given; public jQuery.migrateReset = function() { warnedAbout = {}; jQuery.migrateWarnings.length = 0; }; function migrateWarn( msg) { var console = window.console; if ( !warnedAbout[ msg ] ) { warnedAbout[ msg ] = true; jQuery.migrateWarnings.push( msg ); if ( console && console.warn && !jQuery.migrateMute ) { console.warn( "JQMIGRATE: " + msg ); if ( jQuery.migrateTrace && console.trace ) { console.trace(); } } } } function migrateWarnProp( obj, prop, value, msg ) { if ( Object.defineProperty ) { // On ES5 browsers (non-oldIE), warn if the code tries to get prop; // allow property to be overwritten in case some other plugin wants it try { Object.defineProperty( obj, prop, { configurable: true, enumerable: true, get: function() { migrateWarn( msg ); return value; }, set: function( newValue ) { migrateWarn( msg ); value = newValue; } }); return; } catch( err ) { // IE8 is a dope about Object.defineProperty, can't warn there } } // Non-ES5 (or broken) browser; just set the property jQuery._definePropertyBroken = true; obj[ prop ] = value; } if ( document.compatMode === "BackCompat" ) { // jQuery has never supported or tested Quirks Mode migrateWarn( "jQuery is not compatible with Quirks Mode" ); } var attrFn = jQuery( "<input/>", { size: 1 } ).attr("size") && jQuery.attrFn, oldAttr = jQuery.attr, valueAttrGet = jQuery.attrHooks.value && jQuery.attrHooks.value.get || function() { return null; }, valueAttrSet = jQuery.attrHooks.value && jQuery.attrHooks.value.set || function() { return undefined; }, rnoType = /^(?:input|button)$/i, rnoAttrNodeType = /^[238]$/, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, ruseDefault = /^(?:checked|selected)$/i; // jQuery.attrFn migrateWarnProp( jQuery, "attrFn", attrFn || {}, "jQuery.attrFn is deprecated" ); jQuery.attr = function( elem, name, value, pass ) { var lowerName = name.toLowerCase(), nType = elem && elem.nodeType; if ( pass ) { // Since pass is used internally, we only warn for new jQuery // versions where there isn't a pass arg in the formal params if ( oldAttr.length < 4 ) { migrateWarn("jQuery.fn.attr( props, pass ) is deprecated"); } if ( elem && !rnoAttrNodeType.test( nType ) && (attrFn ? name in attrFn : jQuery.isFunction(jQuery.fn[name])) ) { return jQuery( elem )[ name ]( value ); } } // Warn if user tries to set `type`, since it breaks on IE 6/7/8; by checking // for disconnected elements we don't warn on $( "<button>", { type: "button" } ). if ( name === "type" && value !== undefined && rnoType.test( elem.nodeName ) && elem.parentNode ) { migrateWarn("Can't change the 'type' of an input or button in IE 6/7/8"); } // Restore boolHook for boolean property/attribute synchronization if ( !jQuery.attrHooks[ lowerName ] && rboolean.test( lowerName ) ) { jQuery.attrHooks[ lowerName ] = { get: function( elem, name ) { // Align boolean attributes with corresponding properties // Fall back to attribute presence where some booleans are not supported var attrNode, property = jQuery.prop( elem, name ); return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { var propName; if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { // value is true since we know at this point it's type boolean and not false // Set boolean attributes to the same name and set the DOM property propName = jQuery.propFix[ name ] || name; if ( propName in elem ) { // Only set the IDL specifically if it already exists on the element elem[ propName ] = true; } elem.setAttribute( name, name.toLowerCase() ); } return name; } }; // Warn only for attributes that can remain distinct from their properties post-1.9 if ( ruseDefault.test( lowerName ) ) { migrateWarn( "jQuery.fn.attr('" + lowerName + "') may use property instead of attribute" ); } } return oldAttr.call( jQuery, elem, name, value ); }; // attrHooks: value jQuery.attrHooks.value = { get: function( elem, name ) { var nodeName = ( elem.nodeName || "" ).toLowerCase(); if ( nodeName === "button" ) { return valueAttrGet.apply( this, arguments ); } if ( nodeName !== "input" && nodeName !== "option" ) { migrateWarn("jQuery.fn.attr('value') no longer gets properties"); } return name in elem ? elem.value : null; }, set: function( elem, value ) { var nodeName = ( elem.nodeName || "" ).toLowerCase(); if ( nodeName === "button" ) { return valueAttrSet.apply( this, arguments ); } if ( nodeName !== "input" && nodeName !== "option" ) { migrateWarn("jQuery.fn.attr('value', val) no longer sets properties"); } // Does not return so that setAttribute is also used elem.value = value; } }; var matched, browser, oldInit = jQuery.fn.init, oldParseJSON = jQuery.parseJSON, // Note: XSS check is done below after string is trimmed rquickExpr = /^([^<]*)(<[\w\W]+>)([^>]*)$/; // $(html) "looks like html" rule change jQuery.fn.init = function( selector, context, rootjQuery ) { var match; if ( selector && typeof selector === "string" && !jQuery.isPlainObject( context ) && (match = rquickExpr.exec( jQuery.trim( selector ) )) && match[ 0 ] ) { // This is an HTML string according to the "old" rules; is it still? if ( selector.charAt( 0 ) !== "<" ) { migrateWarn("$(html) HTML strings must start with '<' character"); } if ( match[ 3 ] ) { migrateWarn("$(html) HTML text after last tag is ignored"); } // Consistently reject any HTML-like string starting with a hash (#9521) // Note that this may break jQuery 1.6.x code that otherwise would work. if ( match[ 0 ].charAt( 0 ) === "#" ) { migrateWarn("HTML string cannot start with a '#' character"); jQuery.error("JQMIGRATE: Invalid selector string (XSS)"); } // Now process using loose rules; let pre-1.8 play too if ( context && context.context ) { // jQuery object as context; parseHTML expects a DOM object context = context.context; } if ( jQuery.parseHTML ) { return oldInit.call( this, jQuery.parseHTML( match[ 2 ], context, true ), context, rootjQuery ); } } return oldInit.apply( this, arguments ); }; jQuery.fn.init.prototype = jQuery.fn; // Let $.parseJSON(falsy_value) return null jQuery.parseJSON = function( json ) { if ( !json && json !== null ) { migrateWarn("jQuery.parseJSON requires a valid JSON string"); return null; } return oldParseJSON.apply( this, arguments ); }; jQuery.uaMatch = function( ua ) { ua = ua.toLowerCase(); var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) || /(webkit)[ \/]([\w.]+)/.exec( ua ) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) || /(msie) ([\w.]+)/.exec( ua ) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) || []; return { browser: match[ 1 ] || "", version: match[ 2 ] || "0" }; }; // Don't clobber any existing jQuery.browser in case it's different if ( !jQuery.browser ) { matched = jQuery.uaMatch( navigator.userAgent ); browser = {}; if ( matched.browser ) { browser[ matched.browser ] = true; browser.version = matched.version; } // Chrome is Webkit, but Webkit is also Safari. if ( browser.chrome ) { browser.webkit = true; } else if ( browser.webkit ) { browser.safari = true; } jQuery.browser = browser; } // Warn if the code tries to get jQuery.browser migrateWarnProp( jQuery, "browser", jQuery.browser, "jQuery.browser is deprecated" ); jQuery.sub = function() { function jQuerySub( selector, context ) { return new jQuerySub.fn.init( selector, context ); } jQuery.extend( true, jQuerySub, this ); jQuerySub.superclass = this; jQuerySub.fn = jQuerySub.prototype = this(); jQuerySub.fn.constructor = jQuerySub; jQuerySub.sub = this.sub; jQuerySub.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { context = jQuerySub( context ); } return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); }; jQuerySub.fn.init.prototype = jQuerySub.fn; var rootjQuerySub = jQuerySub(document); migrateWarn( "jQuery.sub() is deprecated" ); return jQuerySub; }; // Ensure that $.ajax gets the new parseJSON defined in core.js jQuery.ajaxSetup({ converters: { "text json": jQuery.parseJSON } }); var oldFnData = jQuery.fn.data; jQuery.fn.data = function( name ) { var ret, evt, elem = this[0]; // Handles 1.7 which has this behavior and 1.8 which doesn't if ( elem && name === "events" && arguments.length === 1 ) { ret = jQuery.data( elem, name ); evt = jQuery._data( elem, name ); if ( ( ret === undefined || ret === evt ) && evt !== undefined ) { migrateWarn("Use of jQuery.fn.data('events') is deprecated"); return evt; } } return oldFnData.apply( this, arguments ); }; var rscriptType = /\/(java|ecma)script/i, oldSelf = jQuery.fn.andSelf || jQuery.fn.addBack; jQuery.fn.andSelf = function() { migrateWarn("jQuery.fn.andSelf() replaced by jQuery.fn.addBack()"); return oldSelf.apply( this, arguments ); }; // Since jQuery.clean is used internally on older versions, we only shim if it's missing if ( !jQuery.clean ) { jQuery.clean = function( elems, context, fragment, scripts ) { // Set context per 1.8 logic context = context || document; context = !context.nodeType && context[0] || context; context = context.ownerDocument || context; migrateWarn("jQuery.clean() is deprecated"); var i, elem, handleScript, jsTags, ret = []; jQuery.merge( ret, jQuery.buildFragment( elems, context ).childNodes ); // Complex logic lifted directly from jQuery 1.8 if ( fragment ) { // Special handling of each script element handleScript = function( elem ) { // Check if we consider it executable if ( !elem.type || rscriptType.test( elem.type ) ) { // Detach the script and store it in the scripts array (if provided) or the fragment // Return truthy to indicate that it has been handled return scripts ? scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) : fragment.appendChild( elem ); } }; for ( i = 0; (elem = ret[i]) != null; i++ ) { // Check if we're done after handling an executable script if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) { // Append to fragment and handle embedded scripts fragment.appendChild( elem ); if ( typeof elem.getElementsByTagName !== "undefined" ) { // handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript ); // Splice the scripts into ret after their former ancestor and advance our index beyond them ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); i += jsTags.length; } } } } return ret; }; } var eventAdd = jQuery.event.add, eventRemove = jQuery.event.remove, eventTrigger = jQuery.event.trigger, oldToggle = jQuery.fn.toggle, oldLive = jQuery.fn.live, oldDie = jQuery.fn.die, ajaxEvents = "ajaxStart|ajaxStop|ajaxSend|ajaxComplete|ajaxError|ajaxSuccess", rajaxEvent = new RegExp( "\\b(?:" + ajaxEvents + ")\\b" ), rhoverHack = /(?:^|\s)hover(\.\S+|)\b/, hoverHack = function( events ) { if ( typeof( events ) !== "string" || jQuery.event.special.hover ) { return events; } if ( rhoverHack.test( events ) ) { migrateWarn("'hover' pseudo-event is deprecated, use 'mouseenter mouseleave'"); } return events && events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); }; // Event props removed in 1.9, put them back if needed; no practical way to warn them if ( jQuery.event.props && jQuery.event.props[ 0 ] !== "attrChange" ) { jQuery.event.props.unshift( "attrChange", "attrName", "relatedNode", "srcElement" ); } // Undocumented jQuery.event.handle was "deprecated" in jQuery 1.7 if ( jQuery.event.dispatch ) { migrateWarnProp( jQuery.event, "handle", jQuery.event.dispatch, "jQuery.event.handle is undocumented and deprecated" ); } // Support for 'hover' pseudo-event and ajax event warnings jQuery.event.add = function( elem, types, handler, data, selector ){ if ( elem !== document && rajaxEvent.test( types ) ) { migrateWarn( "AJAX events should be attached to document: " + types ); } eventAdd.call( this, elem, hoverHack( types || "" ), handler, data, selector ); }; jQuery.event.remove = function( elem, types, handler, selector, mappedTypes ){ eventRemove.call( this, elem, hoverHack( types ) || "", handler, selector, mappedTypes ); }; jQuery.fn.error = function() { var args = Array.prototype.slice.call( arguments, 0); migrateWarn("jQuery.fn.error() is deprecated"); args.splice( 0, 0, "error" ); if ( arguments.length ) { return this.bind.apply( this, args ); } // error event should not bubble to window, although it does pre-1.7 this.triggerHandler.apply( this, args ); return this; }; jQuery.fn.toggle = function( fn, fn2 ) { // Don't mess with animation or css toggles if ( !jQuery.isFunction( fn ) || !jQuery.isFunction( fn2 ) ) { return oldToggle.apply( this, arguments ); } migrateWarn("jQuery.fn.toggle(handler, handler...) is deprecated"); // 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 ); }; jQuery.fn.live = function( types, data, fn ) { migrateWarn("jQuery.fn.live() is deprecated"); if ( oldLive ) { return oldLive.apply( this, arguments ); } jQuery( this.context ).on( types, this.selector, data, fn ); return this; }; jQuery.fn.die = function( types, fn ) { migrateWarn("jQuery.fn.die() is deprecated"); if ( oldDie ) { return oldDie.apply( this, arguments ); } jQuery( this.context ).off( types, this.selector || "**", fn ); return this; }; // Turn global events into document-triggered events jQuery.event.trigger = function( event, data, elem, onlyHandlers ){ if ( !elem && !rajaxEvent.test( event ) ) { migrateWarn( "Global events are undocumented and deprecated" ); } return eventTrigger.call( this, event, data, elem || document, onlyHandlers ); }; jQuery.each( ajaxEvents.split("|"), function( _, name ) { jQuery.event.special[ name ] = { setup: function() { var elem = this; // The document needs no shimming; must be !== for oldIE if ( elem !== document ) { jQuery.event.add( document, name + "." + jQuery.guid, function() { jQuery.event.trigger( name, null, elem, true ); }); jQuery._data( this, name, jQuery.guid++ ); } return false; }, teardown: function() { if ( this !== document ) { jQuery.event.remove( document, name + "." + jQuery._data( this, name ) ); } return false; } }; } ); })( jQuery, window );
JavaScript
/* SuperBox v1.0.0 (modified by bootstraphunter.com) by Todd Motto: http://www.toddmotto.com Latest version: https://github.com/toddmotto/superbox Copyright 2013 Todd Motto Licensed under the MIT license http://www.opensource.org/licenses/mit-license.php SuperBox, the lightbox reimagined. Fully responsive HTML5 image galleries. */ ;(function($) { $.fn.SuperBox = function(options) { var superbox = $('<div class="superbox-show"></div>'), superboximg = $('<img src="" class="superbox-current-img"><div id="imgInfoBox" class="superbox-imageinfo inline-block"> <h1>Image Title</h1><span><p><em>http://imagelink.com/thisimage.jpg</em></p><p class="superbox-img-description">Image description</p><p><a href="javascript:void(0);" class="btn btn-primary btn-sm">Edit Image</a> <a href="javascript:void(0);" class="btn btn-danger btn-sm">Delete</a></p></span> </div>'), superboxclose = $('<div class="superbox-close txt-color-white"><i class="fa fa-times fa-lg"></i></div>'); superbox.append(superboximg).append(superboxclose); var imgInfoBox = $('.superbox-imageinfo'); return this.each(function() { $('.superbox-list').click(function() { $this = $(this); var currentimg = $this.find('.superbox-img'), imgData = currentimg.data('img'), imgDescription = currentimg.attr('alt') || "No description", imgLink = imgData, imgTitle = currentimg.attr('title') || "No Title"; //console.log(imgData, imgDescription, imgLink, imgTitle) superboximg.attr('src', imgData); $('.superbox-list').removeClass('active'); $this.addClass('active'); //$('#imgInfoBox em').text(imgLink); //$('#imgInfoBox >:first-child').text(imgTitle); //$('#imgInfoBox .superbox-img-description').text(imgDescription); superboximg.find('em').text(imgLink); superboximg.find('>:first-child').text(imgTitle); superboximg.find('.superbox-img-description').text(imgDescription); //console.log("fierd") if($('.superbox-current-img').css('opacity') == 0) { $('.superbox-current-img').animate({opacity: 1}); } if ($(this).next().hasClass('superbox-show')) { $('.superbox-list').removeClass('active'); superbox.toggle(); } else { superbox.insertAfter(this).css('display', 'block'); $this.addClass('active'); } $('html, body').animate({ scrollTop:superbox.position().top - currentimg.width() }, 'medium'); }); $('.superbox').on('click', '.superbox-close', function() { $('.superbox-list').removeClass('active'); $('.superbox-current-img').animate({opacity: 0}, 200, function() { $('.superbox-show').slideUp(); }); }); }); }; })(jQuery);
JavaScript
/* Masked Input plugin for jQuery Copyright (c) 2007-2013 Josh Bush (digitalbush.com) Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license) Version: 1.3.1 */ (function($) { function getPasteEvent() { var el = document.createElement('input'), name = 'onpaste'; el.setAttribute(name, ''); return (typeof el[name] === 'function')?'paste':'input'; } var pasteEventName = getPasteEvent() + ".mask", ua = navigator.userAgent, iPhone = /iphone/i.test(ua), android=/android/i.test(ua), caretTimeoutId; $.mask = { //Predefined character definitions definitions: { '9': "[0-9]", 'a': "[A-Za-z]", '*': "[A-Za-z0-9]" }, dataName: "rawMaskFn", placeholder: '_', }; $.fn.extend({ //Helper Function for Caret positioning caret: function(begin, end) { var range; if (this.length === 0 || this.is(":hidden")) { return; } if (typeof begin == 'number') { end = (typeof end === 'number') ? end : begin; return this.each(function() { if (this.setSelectionRange) { this.setSelectionRange(begin, end); } else if (this.createTextRange) { range = this.createTextRange(); range.collapse(true); range.moveEnd('character', end); range.moveStart('character', begin); range.select(); } }); } else { if (this[0].setSelectionRange) { begin = this[0].selectionStart; end = this[0].selectionEnd; } else if (document.selection && document.selection.createRange) { range = document.selection.createRange(); begin = 0 - range.duplicate().moveStart('character', -100000); end = begin + range.text.length; } return { begin: begin, end: end }; } }, unmask: function() { return this.trigger("unmask"); }, mask: function(mask, settings) { var input, defs, tests, partialPosition, firstNonMaskPos, len; if (!mask && this.length > 0) { input = $(this[0]); return input.data($.mask.dataName)(); } settings = $.extend({ placeholder: $.mask.placeholder, // Load default placeholder completed: null }, settings); defs = $.mask.definitions; tests = []; partialPosition = len = mask.length; firstNonMaskPos = null; $.each(mask.split(""), function(i, c) { if (c == '?') { len--; partialPosition = i; } else if (defs[c]) { tests.push(new RegExp(defs[c])); if (firstNonMaskPos === null) { firstNonMaskPos = tests.length - 1; } } else { tests.push(null); } }); return this.trigger("unmask").each(function() { var input = $(this), buffer = $.map( mask.split(""), function(c, i) { if (c != '?') { return defs[c] ? settings.placeholder : c; } }), focusText = input.val(); function seekNext(pos) { while (++pos < len && !tests[pos]); return pos; } function seekPrev(pos) { while (--pos >= 0 && !tests[pos]); return pos; } function shiftL(begin,end) { var i, j; if (begin<0) { return; } for (i = begin, j = seekNext(end); i < len; i++) { if (tests[i]) { if (j < len && tests[i].test(buffer[j])) { buffer[i] = buffer[j]; buffer[j] = settings.placeholder; } else { break; } j = seekNext(j); } } writeBuffer(); input.caret(Math.max(firstNonMaskPos, begin)); } function shiftR(pos) { var i, c, j, t; for (i = pos, c = settings.placeholder; i < len; i++) { if (tests[i]) { j = seekNext(i); t = buffer[i]; buffer[i] = c; if (j < len && tests[j].test(t)) { c = t; } else { break; } } } } function keydownEvent(e) { var k = e.which, pos, begin, end; //backspace, delete, and escape get special treatment if (k === 8 || k === 46 || (iPhone && k === 127)) { pos = input.caret(); begin = pos.begin; end = pos.end; if (end - begin === 0) { begin=k!==46?seekPrev(begin):(end=seekNext(begin-1)); end=k===46?seekNext(end):end; } clearBuffer(begin, end); shiftL(begin, end - 1); e.preventDefault(); } else if (k == 27) {//escape input.val(focusText); input.caret(0, checkVal()); e.preventDefault(); } } function keypressEvent(e) { var k = e.which, pos = input.caret(), p, c, next; if (e.ctrlKey || e.altKey || e.metaKey || k < 32) {//Ignore return; } else if (k) { if (pos.end - pos.begin !== 0){ clearBuffer(pos.begin, pos.end); shiftL(pos.begin, pos.end-1); } p = seekNext(pos.begin - 1); if (p < len) { c = String.fromCharCode(k); if (tests[p].test(c)) { shiftR(p); buffer[p] = c; writeBuffer(); next = seekNext(p); if(android){ setTimeout($.proxy($.fn.caret,input,next),0); }else{ input.caret(next); } if (settings.completed && next >= len) { settings.completed.call(input); } } } e.preventDefault(); } } function clearBuffer(start, end) { var i; for (i = start; i < end && i < len; i++) { if (tests[i]) { buffer[i] = settings.placeholder; } } } function writeBuffer() { input.val(buffer.join('')); } function checkVal(allow) { //try to place characters where they belong var test = input.val(), lastMatch = -1, i, c; for (i = 0, pos = 0; i < len; i++) { if (tests[i]) { buffer[i] = settings.placeholder; while (pos++ < test.length) { c = test.charAt(pos - 1); if (tests[i].test(c)) { buffer[i] = c; lastMatch = i; break; } } if (pos > test.length) { break; } } else if (buffer[i] === test.charAt(pos) && i !== partialPosition) { pos++; lastMatch = i; } } if (allow) { writeBuffer(); } else if (lastMatch + 1 < partialPosition) { input.val(""); clearBuffer(0, len); } else { writeBuffer(); input.val(input.val().substring(0, lastMatch + 1)); } return (partialPosition ? i : firstNonMaskPos); } input.data($.mask.dataName,function(){ return $.map(buffer, function(c, i) { return tests[i]&&c!=settings.placeholder ? c : null; }).join(''); }); if (!input.attr("readonly")) input .one("unmask", function() { input .unbind(".mask") .removeData($.mask.dataName); }) .bind("focus.mask", function() { clearTimeout(caretTimeoutId); var pos, moveCaret; focusText = input.val(); pos = checkVal(); caretTimeoutId = setTimeout(function(){ writeBuffer(); if (pos == mask.length) { input.caret(0, pos); } else { input.caret(pos); } }, 10); }) .bind("blur.mask", function() { checkVal(); if (input.val() != focusText) input.change(); }) .bind("keydown.mask", keydownEvent) .bind("keypress.mask", keypressEvent) .bind(pasteEventName, function() { setTimeout(function() { var pos=checkVal(true); input.caret(pos); if (settings.completed && pos == input.val().length) settings.completed.call(input); }, 0); }); checkVal(); //Perform initial check for existing values }); } }); })(jQuery);
JavaScript
// Copyright 2006 Google Inc. // // 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. // Known Issues: // // * Patterns are not implemented. // * Radial gradient are not implemented. The VML version of these look very // different from the canvas one. // * Clipping paths are not implemented. // * Coordsize. The width and height attribute have higher priority than the // width and height style values which isn't correct. // * Painting mode isn't implemented. // * Canvas width/height should is using content-box by default. IE in // Quirks mode will draw the canvas using border-box. Either change your // doctype to HTML5 // (http://www.whatwg.org/specs/web-apps/current-work/#the-doctype) // or use Box Sizing Behavior from WebFX // (http://webfx.eae.net/dhtml/boxsizing/boxsizing.html) // * Non uniform scaling does not correctly scale strokes. // * Optimize. There is always room for speed improvements. // Only add this code if we do not already have a canvas implementation if (!document.createElement('canvas').getContext) { (function() { // alias some functions to make (compiled) code shorter var m = Math; var mr = m.round; var ms = m.sin; var mc = m.cos; var abs = m.abs; var sqrt = m.sqrt; // this is used for sub pixel precision var Z = 10; var Z2 = Z / 2; /** * This funtion is assigned to the <canvas> elements as element.getContext(). * @this {HTMLElement} * @return {CanvasRenderingContext2D_} */ function getContext() { return this.context_ || (this.context_ = new CanvasRenderingContext2D_(this)); } var slice = Array.prototype.slice; /** * Binds a function to an object. The returned function will always use the * passed in {@code obj} as {@code this}. * * Example: * * g = bind(f, obj, a, b) * g(c, d) // will do f.call(obj, a, b, c, d) * * @param {Function} f The function to bind the object to * @param {Object} obj The object that should act as this when the function * is called * @param {*} var_args Rest arguments that will be used as the initial * arguments when the function is called * @return {Function} A new function that has bound this */ function bind(f, obj, var_args) { var a = slice.call(arguments, 2); return function() { return f.apply(obj, a.concat(slice.call(arguments))); }; } var G_vmlCanvasManager_ = { init: function(opt_doc) { if (/MSIE/.test(navigator.userAgent) && !window.opera) { var doc = opt_doc || document; // Create a dummy element so that IE will allow canvas elements to be // recognized. doc.createElement('canvas'); doc.attachEvent('onreadystatechange', bind(this.init_, this, doc)); } }, init_: function(doc) { // create xmlns if (!doc.namespaces['g_vml_']) { doc.namespaces.add('g_vml_', 'urn:schemas-microsoft-com:vml', '#default#VML'); } if (!doc.namespaces['g_o_']) { doc.namespaces.add('g_o_', 'urn:schemas-microsoft-com:office:office', '#default#VML'); } // Setup default CSS. Only add one style sheet per document if (!doc.styleSheets['ex_canvas_']) { var ss = doc.createStyleSheet(); ss.owningElement.id = 'ex_canvas_'; ss.cssText = 'canvas{display:inline-block;overflow:hidden;' + // default size is 300x150 in Gecko and Opera 'text-align:left;width:300px;height:150px}' + 'g_vml_\\:*{behavior:url(#default#VML)}' + 'g_o_\\:*{behavior:url(#default#VML)}'; } // find all canvas elements var els = doc.getElementsByTagName('canvas'); for (var i = 0; i < els.length; i++) { this.initElement(els[i]); } }, /** * Public initializes a canvas element so that it can be used as canvas * element from now on. This is called automatically before the page is * loaded but if you are creating elements using createElement you need to * make sure this is called on the element. * @param {HTMLElement} el The canvas element to initialize. * @return {HTMLElement} the element that was created. */ initElement: function(el) { if (!el.getContext) { el.getContext = getContext; // Remove fallback content. There is no way to hide text nodes so we // just remove all childNodes. We could hide all elements and remove // text nodes but who really cares about the fallback content. el.innerHTML = ''; // do not use inline function because that will leak memory el.attachEvent('onpropertychange', onPropertyChange); el.attachEvent('onresize', onResize); var attrs = el.attributes; if (attrs.width && attrs.width.specified) { // TODO: use runtimeStyle and coordsize // el.getContext().setWidth_(attrs.width.nodeValue); el.style.width = attrs.width.nodeValue + 'px'; } else { el.width = el.clientWidth; } if (attrs.height && attrs.height.specified) { // TODO: use runtimeStyle and coordsize // el.getContext().setHeight_(attrs.height.nodeValue); el.style.height = attrs.height.nodeValue + 'px'; } else { el.height = el.clientHeight; } //el.getContext().setCoordsize_() } return el; } }; function onPropertyChange(e) { var el = e.srcElement; switch (e.propertyName) { case 'width': el.style.width = el.attributes.width.nodeValue + 'px'; el.getContext().clearRect(); break; case 'height': el.style.height = el.attributes.height.nodeValue + 'px'; el.getContext().clearRect(); break; } } function onResize(e) { var el = e.srcElement; if (el.firstChild) { el.firstChild.style.width = el.clientWidth + 'px'; el.firstChild.style.height = el.clientHeight + 'px'; } } G_vmlCanvasManager_.init(); // precompute "00" to "FF" var dec2hex = []; for (var i = 0; i < 16; i++) { for (var j = 0; j < 16; j++) { dec2hex[i * 16 + j] = i.toString(16) + j.toString(16); } } function createMatrixIdentity() { return [ [1, 0, 0], [0, 1, 0], [0, 0, 1] ]; } function matrixMultiply(m1, m2) { var result = createMatrixIdentity(); for (var x = 0; x < 3; x++) { for (var y = 0; y < 3; y++) { var sum = 0; for (var z = 0; z < 3; z++) { sum += m1[x][z] * m2[z][y]; } result[x][y] = sum; } } return result; } function copyState(o1, o2) { o2.fillStyle = o1.fillStyle; o2.lineCap = o1.lineCap; o2.lineJoin = o1.lineJoin; o2.lineWidth = o1.lineWidth; o2.miterLimit = o1.miterLimit; o2.shadowBlur = o1.shadowBlur; o2.shadowColor = o1.shadowColor; o2.shadowOffsetX = o1.shadowOffsetX; o2.shadowOffsetY = o1.shadowOffsetY; o2.strokeStyle = o1.strokeStyle; o2.globalAlpha = o1.globalAlpha; o2.arcScaleX_ = o1.arcScaleX_; o2.arcScaleY_ = o1.arcScaleY_; o2.lineScale_ = o1.lineScale_; } function processStyle(styleString) { var str, alpha = 1; styleString = String(styleString); if (styleString.substring(0, 3) == 'rgb') { var start = styleString.indexOf('(', 3); var end = styleString.indexOf(')', start + 1); var guts = styleString.substring(start + 1, end).split(','); str = '#'; for (var i = 0; i < 3; i++) { str += dec2hex[Number(guts[i])]; } if (guts.length == 4 && styleString.substr(3, 1) == 'a') { alpha = guts[3]; } } else { str = styleString; } return {color: str, alpha: alpha}; } function processLineCap(lineCap) { switch (lineCap) { case 'butt': return 'flat'; case 'round': return 'round'; case 'square': default: return 'square'; } } /** * This class implements CanvasRenderingContext2D interface as described by * the WHATWG. * @param {HTMLElement} surfaceElement The element that the 2D context should * be associated with */ function CanvasRenderingContext2D_(surfaceElement) { this.m_ = createMatrixIdentity(); this.mStack_ = []; this.aStack_ = []; this.currentPath_ = []; // Canvas context properties this.strokeStyle = '#000'; this.fillStyle = '#000'; this.lineWidth = 1; this.lineJoin = 'miter'; this.lineCap = 'butt'; this.miterLimit = Z * 1; this.globalAlpha = 1; this.canvas = surfaceElement; var el = surfaceElement.ownerDocument.createElement('div'); el.style.width = surfaceElement.clientWidth + 'px'; el.style.height = surfaceElement.clientHeight + 'px'; el.style.overflow = 'hidden'; el.style.position = 'absolute'; surfaceElement.appendChild(el); this.element_ = el; this.arcScaleX_ = 1; this.arcScaleY_ = 1; this.lineScale_ = 1; } var contextPrototype = CanvasRenderingContext2D_.prototype; contextPrototype.clearRect = function() { this.element_.innerHTML = ''; }; contextPrototype.beginPath = function() { // TODO: Branch current matrix so that save/restore has no effect // as per safari docs. this.currentPath_ = []; }; contextPrototype.moveTo = function(aX, aY) { var p = this.getCoords_(aX, aY); this.currentPath_.push({type: 'moveTo', x: p.x, y: p.y}); this.currentX_ = p.x; this.currentY_ = p.y; }; contextPrototype.lineTo = function(aX, aY) { var p = this.getCoords_(aX, aY); this.currentPath_.push({type: 'lineTo', x: p.x, y: p.y}); this.currentX_ = p.x; this.currentY_ = p.y; }; contextPrototype.bezierCurveTo = function(aCP1x, aCP1y, aCP2x, aCP2y, aX, aY) { var p = this.getCoords_(aX, aY); var cp1 = this.getCoords_(aCP1x, aCP1y); var cp2 = this.getCoords_(aCP2x, aCP2y); bezierCurveTo(this, cp1, cp2, p); }; // Helper function that takes the already fixed cordinates. function bezierCurveTo(self, cp1, cp2, p) { self.currentPath_.push({ type: 'bezierCurveTo', cp1x: cp1.x, cp1y: cp1.y, cp2x: cp2.x, cp2y: cp2.y, x: p.x, y: p.y }); self.currentX_ = p.x; self.currentY_ = p.y; } contextPrototype.quadraticCurveTo = function(aCPx, aCPy, aX, aY) { // the following is lifted almost directly from // http://developer.mozilla.org/en/docs/Canvas_tutorial:Drawing_shapes var cp = this.getCoords_(aCPx, aCPy); var p = this.getCoords_(aX, aY); var cp1 = { x: this.currentX_ + 2.0 / 3.0 * (cp.x - this.currentX_), y: this.currentY_ + 2.0 / 3.0 * (cp.y - this.currentY_) }; var cp2 = { x: cp1.x + (p.x - this.currentX_) / 3.0, y: cp1.y + (p.y - this.currentY_) / 3.0 }; bezierCurveTo(this, cp1, cp2, p); }; contextPrototype.arc = function(aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise) { aRadius *= Z; var arcType = aClockwise ? 'at' : 'wa'; var xStart = aX + mc(aStartAngle) * aRadius - Z2; var yStart = aY + ms(aStartAngle) * aRadius - Z2; var xEnd = aX + mc(aEndAngle) * aRadius - Z2; var yEnd = aY + ms(aEndAngle) * aRadius - Z2; // IE won't render arches drawn counter clockwise if xStart == xEnd. if (xStart == xEnd && !aClockwise) { xStart += 0.125; // Offset xStart by 1/80 of a pixel. Use something // that can be represented in binary } var p = this.getCoords_(aX, aY); var pStart = this.getCoords_(xStart, yStart); var pEnd = this.getCoords_(xEnd, yEnd); this.currentPath_.push({type: arcType, x: p.x, y: p.y, radius: aRadius, xStart: pStart.x, yStart: pStart.y, xEnd: pEnd.x, yEnd: pEnd.y}); }; contextPrototype.rect = function(aX, aY, aWidth, aHeight) { this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); }; contextPrototype.strokeRect = function(aX, aY, aWidth, aHeight) { var oldPath = this.currentPath_; this.beginPath(); this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); this.stroke(); this.currentPath_ = oldPath; }; contextPrototype.fillRect = function(aX, aY, aWidth, aHeight) { var oldPath = this.currentPath_; this.beginPath(); this.moveTo(aX, aY); this.lineTo(aX + aWidth, aY); this.lineTo(aX + aWidth, aY + aHeight); this.lineTo(aX, aY + aHeight); this.closePath(); this.fill(); this.currentPath_ = oldPath; }; contextPrototype.createLinearGradient = function(aX0, aY0, aX1, aY1) { var gradient = new CanvasGradient_('gradient'); gradient.x0_ = aX0; gradient.y0_ = aY0; gradient.x1_ = aX1; gradient.y1_ = aY1; return gradient; }; contextPrototype.createRadialGradient = function(aX0, aY0, aR0, aX1, aY1, aR1) { var gradient = new CanvasGradient_('gradientradial'); gradient.x0_ = aX0; gradient.y0_ = aY0; gradient.r0_ = aR0; gradient.x1_ = aX1; gradient.y1_ = aY1; gradient.r1_ = aR1; return gradient; }; contextPrototype.drawImage = function(image, var_args) { var dx, dy, dw, dh, sx, sy, sw, sh; // to find the original width we overide the width and height var oldRuntimeWidth = image.runtimeStyle.width; var oldRuntimeHeight = image.runtimeStyle.height; image.runtimeStyle.width = 'auto'; image.runtimeStyle.height = 'auto'; // get the original size var w = image.width; var h = image.height; // and remove overides image.runtimeStyle.width = oldRuntimeWidth; image.runtimeStyle.height = oldRuntimeHeight; if (arguments.length == 3) { dx = arguments[1]; dy = arguments[2]; sx = sy = 0; sw = dw = w; sh = dh = h; } else if (arguments.length == 5) { dx = arguments[1]; dy = arguments[2]; dw = arguments[3]; dh = arguments[4]; sx = sy = 0; sw = w; sh = h; } else if (arguments.length == 9) { sx = arguments[1]; sy = arguments[2]; sw = arguments[3]; sh = arguments[4]; dx = arguments[5]; dy = arguments[6]; dw = arguments[7]; dh = arguments[8]; } else { throw Error('Invalid number of arguments'); } var d = this.getCoords_(dx, dy); var w2 = sw / 2; var h2 = sh / 2; var vmlStr = []; var W = 10; var H = 10; // For some reason that I've now forgotten, using divs didn't work vmlStr.push(' <g_vml_:group', ' coordsize="', Z * W, ',', Z * H, '"', ' coordorigin="0,0"' , ' style="width:', W, 'px;height:', H, 'px;position:absolute;'); // If filters are necessary (rotation exists), create them // filters are bog-slow, so only create them if abbsolutely necessary // The following check doesn't account for skews (which don't exist // in the canvas spec (yet) anyway. if (this.m_[0][0] != 1 || this.m_[0][1]) { var filter = []; // Note the 12/21 reversal filter.push('M11=', this.m_[0][0], ',', 'M12=', this.m_[1][0], ',', 'M21=', this.m_[0][1], ',', 'M22=', this.m_[1][1], ',', 'Dx=', mr(d.x / Z), ',', 'Dy=', mr(d.y / Z), ''); // Bounding box calculation (need to minimize displayed area so that // filters don't waste time on unused pixels. var max = d; var c2 = this.getCoords_(dx + dw, dy); var c3 = this.getCoords_(dx, dy + dh); var c4 = this.getCoords_(dx + dw, dy + dh); max.x = m.max(max.x, c2.x, c3.x, c4.x); max.y = m.max(max.y, c2.y, c3.y, c4.y); vmlStr.push('padding:0 ', mr(max.x / Z), 'px ', mr(max.y / Z), 'px 0;filter:progid:DXImageTransform.Microsoft.Matrix(', filter.join(''), ", sizingmethod='clip');") } else { vmlStr.push('top:', mr(d.y / Z), 'px;left:', mr(d.x / Z), 'px;'); } vmlStr.push(' ">' , '<g_vml_:image src="', image.src, '"', ' style="width:', Z * dw, 'px;', ' height:', Z * dh, 'px;"', ' cropleft="', sx / w, '"', ' croptop="', sy / h, '"', ' cropright="', (w - sx - sw) / w, '"', ' cropbottom="', (h - sy - sh) / h, '"', ' />', '</g_vml_:group>'); this.element_.insertAdjacentHTML('BeforeEnd', vmlStr.join('')); }; contextPrototype.stroke = function(aFill) { var lineStr = []; var lineOpen = false; var a = processStyle(aFill ? this.fillStyle : this.strokeStyle); var color = a.color; var opacity = a.alpha * this.globalAlpha; var W = 10; var H = 10; lineStr.push('<g_vml_:shape', ' filled="', !!aFill, '"', ' style="position:absolute;width:', W, 'px;height:', H, 'px;"', ' coordorigin="0 0" coordsize="', Z * W, ' ', Z * H, '"', ' stroked="', !aFill, '"', ' path="'); var newSeq = false; var min = {x: null, y: null}; var max = {x: null, y: null}; for (var i = 0; i < this.currentPath_.length; i++) { var p = this.currentPath_[i]; var c; switch (p.type) { case 'moveTo': c = p; lineStr.push(' m ', mr(p.x), ',', mr(p.y)); break; case 'lineTo': lineStr.push(' l ', mr(p.x), ',', mr(p.y)); break; case 'close': lineStr.push(' x '); p = null; break; case 'bezierCurveTo': lineStr.push(' c ', mr(p.cp1x), ',', mr(p.cp1y), ',', mr(p.cp2x), ',', mr(p.cp2y), ',', mr(p.x), ',', mr(p.y)); break; case 'at': case 'wa': lineStr.push(' ', p.type, ' ', mr(p.x - this.arcScaleX_ * p.radius), ',', mr(p.y - this.arcScaleY_ * p.radius), ' ', mr(p.x + this.arcScaleX_ * p.radius), ',', mr(p.y + this.arcScaleY_ * p.radius), ' ', mr(p.xStart), ',', mr(p.yStart), ' ', mr(p.xEnd), ',', mr(p.yEnd)); break; } // TODO: Following is broken for curves due to // move to proper paths. // Figure out dimensions so we can do gradient fills // properly if (p) { if (min.x == null || p.x < min.x) { min.x = p.x; } if (max.x == null || p.x > max.x) { max.x = p.x; } if (min.y == null || p.y < min.y) { min.y = p.y; } if (max.y == null || p.y > max.y) { max.y = p.y; } } } lineStr.push(' ">'); if (!aFill) { var lineWidth = this.lineScale_ * this.lineWidth; // VML cannot correctly render a line if the width is less than 1px. // In that case, we dilute the color to make the line look thinner. if (lineWidth < 1) { opacity *= lineWidth; } lineStr.push( '<g_vml_:stroke', ' opacity="', opacity, '"', ' joinstyle="', this.lineJoin, '"', ' miterlimit="', this.miterLimit, '"', ' endcap="', processLineCap(this.lineCap), '"', ' weight="', lineWidth, 'px"', ' color="', color, '" />' ); } else if (typeof this.fillStyle == 'object') { var fillStyle = this.fillStyle; var angle = 0; var focus = {x: 0, y: 0}; // additional offset var shift = 0; // scale factor for offset var expansion = 1; if (fillStyle.type_ == 'gradient') { var x0 = fillStyle.x0_ / this.arcScaleX_; var y0 = fillStyle.y0_ / this.arcScaleY_; var x1 = fillStyle.x1_ / this.arcScaleX_; var y1 = fillStyle.y1_ / this.arcScaleY_; var p0 = this.getCoords_(x0, y0); var p1 = this.getCoords_(x1, y1); var dx = p1.x - p0.x; var dy = p1.y - p0.y; angle = Math.atan2(dx, dy) * 180 / Math.PI; // The angle should be a non-negative number. if (angle < 0) { angle += 360; } // Very small angles produce an unexpected result because they are // converted to a scientific notation string. if (angle < 1e-6) { angle = 0; } } else { var p0 = this.getCoords_(fillStyle.x0_, fillStyle.y0_); var width = max.x - min.x; var height = max.y - min.y; focus = { x: (p0.x - min.x) / width, y: (p0.y - min.y) / height }; width /= this.arcScaleX_ * Z; height /= this.arcScaleY_ * Z; var dimension = m.max(width, height); shift = 2 * fillStyle.r0_ / dimension; expansion = 2 * fillStyle.r1_ / dimension - shift; } // We need to sort the color stops in ascending order by offset, // otherwise IE won't interpret it correctly. var stops = fillStyle.colors_; stops.sort(function(cs1, cs2) { return cs1.offset - cs2.offset; }); var length = stops.length; var color1 = stops[0].color; var color2 = stops[length - 1].color; var opacity1 = stops[0].alpha * this.globalAlpha; var opacity2 = stops[length - 1].alpha * this.globalAlpha; var colors = []; for (var i = 0; i < length; i++) { var stop = stops[i]; colors.push(stop.offset * expansion + shift + ' ' + stop.color); } // When colors attribute is used, the meanings of opacity and o:opacity2 // are reversed. lineStr.push('<g_vml_:fill type="', fillStyle.type_, '"', ' method="none" focus="100%"', ' color="', color1, '"', ' color2="', color2, '"', ' colors="', colors.join(','), '"', ' opacity="', opacity2, '"', ' g_o_:opacity2="', opacity1, '"', ' angle="', angle, '"', ' focusposition="', focus.x, ',', focus.y, '" />'); } else { lineStr.push('<g_vml_:fill color="', color, '" opacity="', opacity, '" />'); } lineStr.push('</g_vml_:shape>'); this.element_.insertAdjacentHTML('beforeEnd', lineStr.join('')); }; contextPrototype.fill = function() { this.stroke(true); } contextPrototype.closePath = function() { this.currentPath_.push({type: 'close'}); }; /** * @private */ contextPrototype.getCoords_ = function(aX, aY) { var m = this.m_; return { x: Z * (aX * m[0][0] + aY * m[1][0] + m[2][0]) - Z2, y: Z * (aX * m[0][1] + aY * m[1][1] + m[2][1]) - Z2 } }; contextPrototype.save = function() { var o = {}; copyState(this, o); this.aStack_.push(o); this.mStack_.push(this.m_); this.m_ = matrixMultiply(createMatrixIdentity(), this.m_); }; contextPrototype.restore = function() { copyState(this.aStack_.pop(), this); this.m_ = this.mStack_.pop(); }; function matrixIsFinite(m) { for (var j = 0; j < 3; j++) { for (var k = 0; k < 2; k++) { if (!isFinite(m[j][k]) || isNaN(m[j][k])) { return false; } } } return true; } function setM(ctx, m, updateLineScale) { if (!matrixIsFinite(m)) { return; } ctx.m_ = m; if (updateLineScale) { // Get the line scale. // Determinant of this.m_ means how much the area is enlarged by the // transformation. So its square root can be used as a scale factor // for width. var det = m[0][0] * m[1][1] - m[0][1] * m[1][0]; ctx.lineScale_ = sqrt(abs(det)); } } contextPrototype.translate = function(aX, aY) { var m1 = [ [1, 0, 0], [0, 1, 0], [aX, aY, 1] ]; setM(this, matrixMultiply(m1, this.m_), false); }; contextPrototype.rotate = function(aRot) { var c = mc(aRot); var s = ms(aRot); var m1 = [ [c, s, 0], [-s, c, 0], [0, 0, 1] ]; setM(this, matrixMultiply(m1, this.m_), false); }; contextPrototype.scale = function(aX, aY) { this.arcScaleX_ *= aX; this.arcScaleY_ *= aY; var m1 = [ [aX, 0, 0], [0, aY, 0], [0, 0, 1] ]; setM(this, matrixMultiply(m1, this.m_), true); }; contextPrototype.transform = function(m11, m12, m21, m22, dx, dy) { var m1 = [ [m11, m12, 0], [m21, m22, 0], [dx, dy, 1] ]; setM(this, matrixMultiply(m1, this.m_), true); }; contextPrototype.setTransform = function(m11, m12, m21, m22, dx, dy) { var m = [ [m11, m12, 0], [m21, m22, 0], [dx, dy, 1] ]; setM(this, m, true); }; /******** STUBS ********/ contextPrototype.clip = function() { // TODO: Implement }; contextPrototype.arcTo = function() { // TODO: Implement }; contextPrototype.createPattern = function() { return new CanvasPattern_; }; // Gradient / Pattern Stubs function CanvasGradient_(aType) { this.type_ = aType; this.x0_ = 0; this.y0_ = 0; this.r0_ = 0; this.x1_ = 0; this.y1_ = 0; this.r1_ = 0; this.colors_ = []; } CanvasGradient_.prototype.addColorStop = function(aOffset, aColor) { aColor = processStyle(aColor); this.colors_.push({offset: aOffset, color: aColor.color, alpha: aColor.alpha}); }; function CanvasPattern_() {} // set up externs G_vmlCanvasManager = G_vmlCanvasManager_; CanvasRenderingContext2D = CanvasRenderingContext2D_; CanvasGradient = CanvasGradient_; CanvasPattern = CanvasPattern_; })(); } // if
JavaScript
// Ion.RangeSlider // version 1.7.2 Build: 134 // © 2013 Denis Ineshin | IonDen.com // // Project page: http://ionden.com/a/plugins/ion.rangeSlider/ // GitHub page: https://github.com/IonDen/ion.rangeSlider // // Released under MIT licence: // http://ionden.com/a/plugins/licence-en.html // ===================================================================================================================== (function($){ var pluginCount = 0; var oldie = (function(){ var n = navigator.userAgent, r = /msie\s\d+/i, v; if(n.search(r) > 0){ v = r.exec(n).toString(); v = v.split(" ")[1]; if(v < 9) { return true; } else { return false; } } else { return false; } }()); var isTouch = (function() { try { document.createEvent("TouchEvent"); return true; } catch (e) { return false; } }()); var methods = { init: function(options){ var settings = $.extend({ min: 10, max: 100, from: null, to: null, type: "single", step: 1, prefix: "", postfix: "", hasGrid: false, hideText: false, prettify: true, onChange: null, onFinish: null }, options); var baseHTML = '<span class="irs">'; // irs = ion range slider css prefix baseHTML += '<span class="irs-line"><span class="irs-line-left"></span><span class="irs-line-mid"></span><span class="irs-line-right"></span></span>'; baseHTML += '<span class="irs-min">0</span><span class="irs-max">1</span>'; baseHTML += '<span class="irs-from">0</span><span class="irs-to">0</span><span class="irs-single">0</span>'; baseHTML += '</span>'; baseHTML += '<span class="irs-grid"></span>'; var singleHTML = '<span class="irs-slider single"></span>'; var doubleHTML = '<span class="irs-diapason"></span>'; doubleHTML += '<span class="irs-slider from"></span>'; doubleHTML += '<span class="irs-slider to"></span>'; return this.each(function(){ var slider = $(this); if(slider.data("isActive")) { return; } slider.data("isActive", true); pluginCount++; this.pluginCount = pluginCount; // check default values if (typeof settings.from !== "number") { settings.from = settings.min; } if (typeof settings.to !== "number") { settings.to = settings.max; } if (slider.attr("value")) { settings.min = parseInt(slider.attr("value").split(";")[0], 10); settings.max = parseInt(slider.attr("value").split(";")[1], 10); } // extend from data-* if (typeof slider.data("from") === "number") { settings.from = parseInt(slider.data("from"), 10); } if (typeof slider.data("to") === "number") { settings.to = parseInt(slider.data("to"), 10); } if (slider.data("step")) { settings.step = parseFloat(slider.data("step")); } if (slider.data("type")) { settings.type = slider.data("type"); } if (slider.data("prefix")) { settings.prefix = slider.data("prefix"); } if (slider.data("postfix")) { settings.postfix = slider.data("postfix"); } if (slider.data("hasgrid")) { settings.hasGrid = slider.data("hasgrid"); } if (slider.data("hidetext")) { settings.hideText = slider.data("hidetext"); } if (slider.data("prettify")) { settings.prettify = slider.data("prettify"); } // fix diapason if(settings.from < settings.min) { settings.from = settings.min; } if(settings.to > settings.max) { settings.to = settings.max; } if(settings.type === "double") { if(settings.from > settings.to) { settings.from = settings.to; } if(settings.to < settings.from) { settings.to = settings.from; } } var prettify = function(num){ var n = num.toString(); if(settings.prettify) { n = n.replace(/(\d{1,3}(?=(?:\d\d\d)+(?!\d)))/g,"$1 "); } return n; }; var containerHTML = '<span class="irs" id="irs-' + this.pluginCount + '"></span>'; slider[0].style.display = "none"; slider.before(containerHTML); var $container = $("#irs-" + this.pluginCount), $body = $(document.body), $window = $(window), $rangeSlider, $fieldMin, $fieldMax, $fieldFrom, $fieldTo, $fieldSingle, $singleSlider, $fromSlider, $toSlider, $activeSlider, $diapason, $grid; var allowDrag = false, sliderIsActive = false, firstStart = true, numbers = {}; var mouseX = 0, fieldMinWidth = 0, fieldMaxWidth = 0, normalWidth = 0, fullWidth = 0, sliderWidth = 0, width = 0, left = 0, right = 0, minusX = 0, stepFloat = 0; if(parseInt(settings.step, 10) !== parseFloat(settings.step)) { stepFloat = settings.step.toString().split(".")[1]; stepFloat = Math.pow(10, stepFloat.length); } // public methods this.updateData = function(options){ settings = $.extend(settings, options); removeHTML(); }; this.removeSlider = function(){ $container.find("*").off(); $container.html("").remove(); slider.data("isActive", false); slider.show(); }; // private methods var removeHTML = function(){ $container.find("*").off(); $container.html(""); placeHTML(); }; var placeHTML = function(){ $container.html(baseHTML); $rangeSlider = $container.find(".irs"); $fieldMin = $rangeSlider.find(".irs-min"); $fieldMax = $rangeSlider.find(".irs-max"); $fieldFrom = $rangeSlider.find(".irs-from"); $fieldTo = $rangeSlider.find(".irs-to"); $fieldSingle = $rangeSlider.find(".irs-single"); $grid = $container.find(".irs-grid"); if(settings.hideText) { $fieldMin[0].style.display = "none"; $fieldMax[0].style.display = "none"; $fieldFrom[0].style.display = "none"; $fieldTo[0].style.display = "none"; $fieldSingle[0].style.display = "none"; } else { $fieldMin.html(settings.prefix + prettify(settings.min) + settings.postfix); $fieldMax.html(settings.prefix + prettify(settings.max) + settings.postfix); } fieldMinWidth = $fieldMin.outerWidth(); fieldMaxWidth = $fieldMax.outerWidth(); if(settings.type === "single") { $rangeSlider.append(singleHTML); $singleSlider = $rangeSlider.find(".single"); $singleSlider.on("mousedown", function(e){ e.preventDefault(); e.stopPropagation(); calcDimensions(e, $(this), null); allowDrag = true; sliderIsActive = true; if(oldie) { $("*").prop("unselectable",true); } }); if(isTouch) { $singleSlider.on("touchstart", function(e){ e.preventDefault(); e.stopPropagation(); calcDimensions(e.originalEvent.touches[0], $(this), null); allowDrag = true; sliderIsActive = true; }); } } else if(settings.type === "double") { $rangeSlider.append(doubleHTML); $fromSlider = $rangeSlider.find(".from"); $toSlider = $rangeSlider.find(".to"); $diapason = $rangeSlider.find(".irs-diapason"); setDiapason(); $fromSlider.on("mousedown", function(e){ e.preventDefault(); e.stopPropagation(); $(this).addClass("last"); $toSlider.removeClass("last"); calcDimensions(e, $(this), "from"); allowDrag = true; sliderIsActive = true; if(oldie) { $("*").prop("unselectable",true); } }); $toSlider.on("mousedown", function(e){ e.preventDefault(); e.stopPropagation(); $(this).addClass("last"); $fromSlider.removeClass("last"); calcDimensions(e, $(this), "to"); allowDrag = true; sliderIsActive = true; if(oldie) { $("*").prop("unselectable",true); } }); if(isTouch) { $fromSlider.on("touchstart", function(e){ e.preventDefault(); e.stopPropagation(); $(this).addClass("last"); $toSlider.removeClass("last"); calcDimensions(e.originalEvent.touches[0], $(this), "from"); allowDrag = true; sliderIsActive = true; }); $toSlider.on("touchstart", function(e){ e.preventDefault(); e.stopPropagation(); $(this).addClass("last"); $fromSlider.removeClass("last"); calcDimensions(e.originalEvent.touches[0], $(this), "to"); allowDrag = true; sliderIsActive = true; }); } if(settings.to === settings.max) { $fromSlider.addClass("last"); } } $body.on("mouseup", function(){ if(!allowDrag) return; sliderIsActive = false; allowDrag = false; $activeSlider.removeAttr("id"); $activeSlider = null; if(settings.type === "double") { setDiapason(); } getNumbers(); if(oldie) { $("*").prop("unselectable",false); } }); $body.on("mousemove", function(e){ if(allowDrag) { mouseX = e.pageX; dragSlider(); } }); if(isTouch) { $window.on("touchend", function(){ if(!allowDrag) return; sliderIsActive = false; allowDrag = false; $activeSlider.removeAttr("id"); $activeSlider = null; if(settings.type === "double") { setDiapason(); } getNumbers(); }); $window.on("touchmove", function(e){ if(allowDrag) { mouseX = e.originalEvent.touches[0].pageX; dragSlider(); } }); } getSize(); setNumbers(); if(settings.hasGrid) { setGrid(); } }; var getSize = function(){ normalWidth = $rangeSlider.width(); if($singleSlider) { sliderWidth = $singleSlider.width(); } else { sliderWidth = $fromSlider.width(); } fullWidth = normalWidth - sliderWidth; }; var calcDimensions = function(e, currentSlider, whichSlider){ getSize(); firstStart = false; $activeSlider = currentSlider; $activeSlider.attr("id", "irs-active-slider"); var _x1 = $activeSlider.offset().left, _x2 = e.pageX - _x1; minusX = _x1 + _x2 - $activeSlider.position().left; if(settings.type === "single") { width = $rangeSlider.width() - sliderWidth; } else if(settings.type === "double") { if(whichSlider === "from") { left = 0; right = parseInt($toSlider.css("left"), 10); } else { left = parseInt($fromSlider.css("left"), 10); right = $rangeSlider.width() - sliderWidth; } } }; var setDiapason = function(){ var _w = $fromSlider.width(), _x = parseInt($fromSlider[0].style.left, 10) || $fromSlider.position().left, _width = parseInt($toSlider[0].style.left, 10) || $toSlider.position().left, x = _x + (_w / 2), w = _width - _x; $diapason[0].style.left = x + "px"; $diapason[0].style.width = w + "px"; }; var dragSlider = function(){ var x = Math.round(mouseX - minusX); if(settings.type === "single") { if(x < 0) { x = 0; } if(x > width) { x = width; } getNumbers(); } else if(settings.type === "double") { if(x < left) { x = left; } if(x > right) { x = right; } getNumbers(); setDiapason(); } $activeSlider[0].style.left = x + "px"; }; var getNumbers = function(){ var nums = { fromNumber: 0, toNumber: 0, fromPers: 0, toPers: 0, fromX: 0, toX: 0 }; var diapason = settings.max - settings.min, _from, _to; if(settings.type === "single") { nums.fromX = parseInt($singleSlider[0].style.left, 10) || $singleSlider.position().left; nums.fromPers = nums.fromX / fullWidth * 100; _from = (diapason / 100 * nums.fromPers) + parseInt(settings.min, 10); nums.fromNumber = Math.round(_from / settings.step) * settings.step; if(stepFloat) { nums.fromNumber = parseInt(nums.fromNumber * stepFloat, 10) / stepFloat; } } else if(settings.type === "double") { nums.fromX = parseInt($fromSlider[0].style.left, 10) || $fromSlider.position().left; nums.fromPers = nums.fromX / fullWidth * 100; _from = (diapason / 100 * nums.fromPers) + parseInt(settings.min, 10); nums.fromNumber = Math.round(_from / settings.step) * settings.step; nums.toX = parseInt($toSlider[0].style.left, 10) || $toSlider.position().left; nums.toPers = nums.toX / fullWidth * 100; _to = (diapason / 100 * nums.toPers) + parseInt(settings.min, 10); nums.toNumber = Math.round(_to / settings.step) * settings.step; if(stepFloat) { nums.fromNumber = parseInt(nums.fromNumber * stepFloat, 10) / stepFloat; nums.toNumber = parseInt(nums.toNumber * stepFloat, 10) / stepFloat; } } numbers = nums; setFields(); }; var setNumbers = function(){ var nums = { fromNumber: settings.from, toNumber: settings.to, fromPers: 0, toPers: 0, fromX: 0, toX: 0 }; var diapason = settings.max - settings.min; if(settings.type === "single") { nums.fromPers = (nums.fromNumber - settings.min) / diapason * 100; nums.fromX = Math.round(fullWidth / 100 * nums.fromPers); $singleSlider[0].style.left = nums.fromX + "px"; } else if(settings.type === "double") { nums.fromPers = (nums.fromNumber - settings.min) / diapason * 100; nums.fromX = Math.round(fullWidth / 100 * nums.fromPers); $fromSlider[0].style.left = nums.fromX + "px"; nums.toPers = (nums.toNumber - settings.min) / diapason * 100; nums.toX = Math.round(fullWidth / 100 * nums.toPers); $toSlider[0].style.left = nums.toX + "px"; setDiapason(); } numbers = nums; setFields(); }; var setFields = function(){ var _from, _fromW, _fromX, _to, _toW, _toX, _single, _singleW, _singleX, _slW = (sliderWidth / 2); if(settings.type === "single") { if(!settings.hideText) { $fieldFrom[0].style.display = "none"; $fieldTo[0].style.display = "none"; _single = settings.prefix + prettify(numbers.fromNumber) + settings.postfix; $fieldSingle.html(_single); _singleW = $fieldSingle.outerWidth(); _singleX = numbers.fromX - (_singleW / 2) + _slW; if(_singleX < 0) { _singleX = 0; } if(_singleX > normalWidth - _singleW) { _singleX = normalWidth - _singleW; } $fieldSingle[0].style.left = _singleX + "px"; if(_singleX < fieldMinWidth) { $fieldMin[0].style.display = "none"; } else { $fieldMin[0].style.display = "block"; } if(_singleX + _singleW > normalWidth - fieldMaxWidth) { $fieldMax[0].style.display = "none"; } else { $fieldMax[0].style.display = "block"; } } slider.attr("value", parseInt(numbers.fromNumber, 10)); } else if(settings.type === "double") { if(!settings.hideText) { _from = settings.prefix + prettify(numbers.fromNumber) + settings.postfix; _to = settings.prefix + prettify(numbers.toNumber) + settings.postfix; if(numbers.fromNumber != numbers.toNumber) { _single = settings.prefix + prettify(numbers.fromNumber) + " — " + settings.prefix + prettify(numbers.toNumber) + settings.postfix; } else { _single = settings.prefix + prettify(numbers.fromNumber) + settings.postfix; } $fieldFrom.html(_from); $fieldTo.html(_to); $fieldSingle.html(_single); _fromW = $fieldFrom.outerWidth(); _fromX = numbers.fromX - (_fromW / 2) + _slW; if(_fromX < 0) { _fromX = 0; } if(_fromX > normalWidth - _fromW) { _fromX = normalWidth - _fromW; } $fieldFrom[0].style.left = _fromX + "px"; _toW = $fieldTo.outerWidth(); _toX = numbers.toX - (_toW / 2) + _slW; if(_toX < 0) { _toX = 0; } if(_toX > normalWidth - _toW) { _toX = normalWidth - _toW; } $fieldTo[0].style.left = _toX + "px"; _singleW = $fieldSingle.outerWidth(); _singleX = numbers.fromX + ((numbers.toX - numbers.fromX) / 2) - (_singleW / 2) + _slW; if(_singleX < 0) { _singleX = 0; } if(_singleX > normalWidth - _singleW) { _singleX = normalWidth - _singleW; } $fieldSingle[0].style.left = _singleX + "px"; if(_fromX + _fromW < _toX) { $fieldSingle[0].style.display = "none"; $fieldFrom[0].style.display = "block"; $fieldTo[0].style.display = "block"; } else { $fieldSingle[0].style.display = "block"; $fieldFrom[0].style.display = "none"; $fieldTo[0].style.display = "none"; } if(_singleX < fieldMinWidth || _fromX < fieldMinWidth) { $fieldMin[0].style.display = "none"; } else { $fieldMin[0].style.display = "block"; } if(_singleX + _singleW > normalWidth - fieldMaxWidth || _toX + _toW > normalWidth - fieldMaxWidth) { $fieldMax[0].style.display = "none"; } else { $fieldMax[0].style.display = "block"; } } slider.attr("value", parseInt(numbers.fromNumber, 10) + ";" + parseInt(numbers.toNumber, 10)); } // trigger callback function if(typeof settings.onChange === "function") { settings.onChange.call(this, numbers); } // trigger finish function if(typeof settings.onFinish === "function" && !sliderIsActive && !firstStart) { settings.onFinish.call(this, numbers); } }; var setGrid = function(){ $container.addClass("irs-with-grid"); var i, text = '', step = 0, tStep = 0, gridHTML = '', smNum = 20, bigNum = 4; for(i = 0; i <= smNum; i++){ step = Math.floor(normalWidth / smNum * i); if(step >= normalWidth) { step = normalWidth - 1; } gridHTML += '<span class="irs-grid-pol small" style="left: ' + step + 'px;"></span>'; } for(i = 0; i <= bigNum; i++){ step = Math.floor(normalWidth / bigNum * i); if(step >= normalWidth) { step = normalWidth - 1; } gridHTML += '<span class="irs-grid-pol" style="left: ' + step + 'px;"></span>'; if(stepFloat) { text = (settings.min + ((settings.max -settings.min) / bigNum * i)); text = (text / settings.step) * settings.step; text = parseInt(text * stepFloat, 10) / stepFloat; } else { text = Math.round(settings.min + ((settings.max -settings.min) / bigNum * i)); text = Math.round(text / settings.step) * settings.step; text = prettify(text); } if(i === 0) { tStep = step; gridHTML += '<span class="irs-grid-text" style="left: ' + tStep + 'px; text-align: left;">' + text + '</span>'; } else if(i === bigNum) { tStep = step - 100; gridHTML += '<span class="irs-grid-text" style="left: ' + tStep + 'px; text-align: right;">' + text + '</span>'; } else { tStep = step - 50; gridHTML += '<span class="irs-grid-text" style="left: ' + tStep + 'px;">' + text + '</span>'; } } $grid.html(gridHTML); }; placeHTML(); }); }, update: function(options){ return this.each(function(){ this.updateData(options); }); }, remove: function(){ return this.each(function(){ this.removeSlider(); }); } }; $.fn.ionRangeSlider = function(method){ if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist for jQuery.ionRangeSlider'); } }; })(jQuery);
JavaScript
/* * to-markdown - an HTML to Markdown converter * * Copyright 2011, Dom Christie * Licenced under the MIT licence * */ var toMarkdown = function(string) { var ELEMENTS = [ { patterns: 'p', replacement: function(str, attrs, innerHTML) { return innerHTML ? '\n\n' + innerHTML + '\n' : ''; } }, { patterns: 'br', type: 'void', replacement: '\n' }, { patterns: 'h([1-6])', replacement: function(str, hLevel, attrs, innerHTML) { var hPrefix = ''; for(var i = 0; i < hLevel; i++) { hPrefix += '#'; } return '\n\n' + hPrefix + ' ' + innerHTML + '\n'; } }, { patterns: 'hr', type: 'void', replacement: '\n\n* * *\n' }, { patterns: 'a', replacement: function(str, attrs, innerHTML) { var href = attrs.match(attrRegExp('href')), title = attrs.match(attrRegExp('title')); return href ? '[' + innerHTML + ']' + '(' + href[1] + (title && title[1] ? ' "' + title[1] + '"' : '') + ')' : str; } }, { patterns: ['b', 'strong'], replacement: function(str, attrs, innerHTML) { return innerHTML ? '**' + innerHTML + '**' : ''; } }, { patterns: ['i', 'em'], replacement: function(str, attrs, innerHTML) { return innerHTML ? '_' + innerHTML + '_' : ''; } }, { patterns: 'code', replacement: function(str, attrs, innerHTML) { return innerHTML ? '`' + innerHTML + '`' : ''; } }, { patterns: 'img', type: 'void', replacement: function(str, attrs, innerHTML) { var src = attrs.match(attrRegExp('src')), alt = attrs.match(attrRegExp('alt')), title = attrs.match(attrRegExp('title')); return '![' + (alt && alt[1] ? alt[1] : '') + ']' + '(' + src[1] + (title && title[1] ? ' "' + title[1] + '"' : '') + ')'; } } ]; for(var i = 0, len = ELEMENTS.length; i < len; i++) { if(typeof ELEMENTS[i].patterns === 'string') { string = replaceEls(string, { tag: ELEMENTS[i].patterns, replacement: ELEMENTS[i].replacement, type: ELEMENTS[i].type }); } else { for(var j = 0, pLen = ELEMENTS[i].patterns.length; j < pLen; j++) { string = replaceEls(string, { tag: ELEMENTS[i].patterns[j], replacement: ELEMENTS[i].replacement, type: ELEMENTS[i].type }); } } } function replaceEls(html, elProperties) { var pattern = elProperties.type === 'void' ? '<' + elProperties.tag + '\\b([^>]*)\\/?>' : '<' + elProperties.tag + '\\b([^>]*)>([\\s\\S]*?)<\\/' + elProperties.tag + '>', regex = new RegExp(pattern, 'gi'), markdown = ''; if(typeof elProperties.replacement === 'string') { markdown = html.replace(regex, elProperties.replacement); } else { markdown = html.replace(regex, function(str, p1, p2, p3) { return elProperties.replacement.call(this, str, p1, p2, p3); }); } return markdown; } function attrRegExp(attr) { return new RegExp(attr + '\\s*=\\s*["\']?([^"\']*)["\']?', 'i'); } // Pre code blocks string = string.replace(/<pre\b[^>]*>`([\s\S]*)`<\/pre>/gi, function(str, innerHTML) { innerHTML = innerHTML.replace(/^\t+/g, ' '); // convert tabs to spaces (you know it makes sense) innerHTML = innerHTML.replace(/\n/g, '\n '); return '\n\n ' + innerHTML + '\n'; }); // Lists // Escape numbers that could trigger an ol // If there are more than three spaces before the code, it would be in a pre tag // Make sure we are escaping the period not matching any character string = string.replace(/^(\s{0,3}\d+)\. /g, '$1\\. '); // Converts lists that have no child lists (of same type) first, then works it's way up var noChildrenRegex = /<(ul|ol)\b[^>]*>(?:(?!<ul|<ol)[\s\S])*?<\/\1>/gi; while(string.match(noChildrenRegex)) { string = string.replace(noChildrenRegex, function(str) { return replaceLists(str); }); } function replaceLists(html) { html = html.replace(/<(ul|ol)\b[^>]*>([\s\S]*?)<\/\1>/gi, function(str, listType, innerHTML) { var lis = innerHTML.split('</li>'); lis.splice(lis.length - 1, 1); for(i = 0, len = lis.length; i < len; i++) { if(lis[i]) { var prefix = (listType === 'ol') ? (i + 1) + ". " : "* "; lis[i] = lis[i].replace(/\s*<li[^>]*>([\s\S]*)/i, function(str, innerHTML) { innerHTML = innerHTML.replace(/^\s+/, ''); innerHTML = innerHTML.replace(/\n\n/g, '\n\n '); // indent nested lists innerHTML = innerHTML.replace(/\n([ ]*)+(\*|\d+\.) /g, '\n$1 $2 '); return prefix + innerHTML; }); } } return lis.join('\n'); }); return '\n\n' + html.replace(/[ \t]+\n|\s+$/g, ''); } // Blockquotes var deepest = /<blockquote\b[^>]*>((?:(?!<blockquote)[\s\S])*?)<\/blockquote>/gi; while(string.match(deepest)) { string = string.replace(deepest, function(str) { return replaceBlockquotes(str); }); } function replaceBlockquotes(html) { html = html.replace(/<blockquote\b[^>]*>([\s\S]*?)<\/blockquote>/gi, function(str, inner) { inner = inner.replace(/^\s+|\s+$/g, ''); inner = cleanUp(inner); inner = inner.replace(/^/gm, '> '); inner = inner.replace(/^(>([ \t]{2,}>)+)/gm, '> >'); return inner; }); return html; } function cleanUp(string) { string = string.replace(/^[\t\r\n]+|[\t\r\n]+$/g, ''); // trim leading/trailing whitespace string = string.replace(/\n\s+\n/g, '\n\n'); string = string.replace(/\n{3,}/g, '\n\n'); // limit consecutive linebreaks to 2 return string; } return cleanUp(string); }; if (typeof exports === 'object') { exports.toMarkdown = toMarkdown; }
JavaScript
// Released under MIT license // Copyright (c) 2009-2010 Dominic Baggott // Copyright (c) 2009-2010 Ash Berlin // Copyright (c) 2011 Christoph Dorn <christoph@christophdorn.com> (http://www.christophdorn.com) (function( expose ) { /** * class Markdown * * Markdown processing in Javascript done right. We have very particular views * on what constitutes 'right' which include: * * - produces well-formed HTML (this means that em and strong nesting is * important) * * - has an intermediate representation to allow processing of parsed data (We * in fact have two, both as [JsonML]: a markdown tree and an HTML tree). * * - is easily extensible to add new dialects without having to rewrite the * entire parsing mechanics * * - has a good test suite * * This implementation fulfills all of these (except that the test suite could * do with expanding to automatically run all the fixtures from other Markdown * implementations.) * * ##### Intermediate Representation * * *TODO* Talk about this :) Its JsonML, but document the node names we use. * * [JsonML]: http://jsonml.org/ "JSON Markup Language" **/ var Markdown = expose.Markdown = function Markdown(dialect) { switch (typeof dialect) { case "undefined": this.dialect = Markdown.dialects.Gruber; break; case "object": this.dialect = dialect; break; default: if (dialect in Markdown.dialects) { this.dialect = Markdown.dialects[dialect]; } else { throw new Error("Unknown Markdown dialect '" + String(dialect) + "'"); } break; } this.em_state = []; this.strong_state = []; this.debug_indent = ""; }; /** * parse( markdown, [dialect] ) -> JsonML * - markdown (String): markdown string to parse * - dialect (String | Dialect): the dialect to use, defaults to gruber * * Parse `markdown` and return a markdown document as a Markdown.JsonML tree. **/ expose.parse = function( source, dialect ) { // dialect will default if undefined var md = new Markdown( dialect ); return md.toTree( source ); }; /** * toHTML( markdown, [dialect] ) -> String * toHTML( md_tree ) -> String * - markdown (String): markdown string to parse * - md_tree (Markdown.JsonML): parsed markdown tree * * Take markdown (either as a string or as a JsonML tree) and run it through * [[toHTMLTree]] then turn it into a well-formated HTML fragment. **/ expose.toHTML = function toHTML( source , dialect , options ) { var input = expose.toHTMLTree( source , dialect , options ); return expose.renderJsonML( input ); }; /** * toHTMLTree( markdown, [dialect] ) -> JsonML * toHTMLTree( md_tree ) -> JsonML * - markdown (String): markdown string to parse * - dialect (String | Dialect): the dialect to use, defaults to gruber * - md_tree (Markdown.JsonML): parsed markdown tree * * Turn markdown into HTML, represented as a JsonML tree. If a string is given * to this function, it is first parsed into a markdown tree by calling * [[parse]]. **/ expose.toHTMLTree = function toHTMLTree( input, dialect , options ) { // convert string input to an MD tree if ( typeof input ==="string" ) input = this.parse( input, dialect ); // Now convert the MD tree to an HTML tree // remove references from the tree var attrs = extract_attr( input ), refs = {}; if ( attrs && attrs.references ) { refs = attrs.references; } var html = convert_tree_to_html( input, refs , options ); merge_text_nodes( html ); return html; }; // For Spidermonkey based engines function mk_block_toSource() { return "Markdown.mk_block( " + uneval(this.toString()) + ", " + uneval(this.trailing) + ", " + uneval(this.lineNumber) + " )"; } // node function mk_block_inspect() { var util = require('util'); return "Markdown.mk_block( " + util.inspect(this.toString()) + ", " + util.inspect(this.trailing) + ", " + util.inspect(this.lineNumber) + " )"; } var mk_block = Markdown.mk_block = function(block, trail, line) { // Be helpful for default case in tests. if ( arguments.length == 1 ) trail = "\n\n"; var s = new String(block); s.trailing = trail; // To make it clear its not just a string s.inspect = mk_block_inspect; s.toSource = mk_block_toSource; if (line != undefined) s.lineNumber = line; return s; }; function count_lines( str ) { var n = 0, i = -1; while ( ( i = str.indexOf('\n', i+1) ) !== -1) n++; return n; } // Internal - split source into rough blocks Markdown.prototype.split_blocks = function splitBlocks( input, startLine ) { // [\s\S] matches _anything_ (newline or space) var re = /([\s\S]+?)($|\n(?:\s*\n|$)+)/g, blocks = [], m; var line_no = 1; if ( ( m = /^(\s*\n)/.exec(input) ) != null ) { // skip (but count) leading blank lines line_no += count_lines( m[0] ); re.lastIndex = m[0].length; } while ( ( m = re.exec(input) ) !== null ) { blocks.push( mk_block( m[1], m[2], line_no ) ); line_no += count_lines( m[0] ); } return blocks; }; /** * Markdown#processBlock( block, next ) -> undefined | [ JsonML, ... ] * - block (String): the block to process * - next (Array): the following blocks * * Process `block` and return an array of JsonML nodes representing `block`. * * It does this by asking each block level function in the dialect to process * the block until one can. Succesful handling is indicated by returning an * array (with zero or more JsonML nodes), failure by a false value. * * Blocks handlers are responsible for calling [[Markdown#processInline]] * themselves as appropriate. * * If the blocks were split incorrectly or adjacent blocks need collapsing you * can adjust `next` in place using shift/splice etc. * * If any of this default behaviour is not right for the dialect, you can * define a `__call__` method on the dialect that will get invoked to handle * the block processing. */ Markdown.prototype.processBlock = function processBlock( block, next ) { var cbs = this.dialect.block, ord = cbs.__order__; if ( "__call__" in cbs ) { return cbs.__call__.call(this, block, next); } for ( var i = 0; i < ord.length; i++ ) { //D:this.debug( "Testing", ord[i] ); var res = cbs[ ord[i] ].call( this, block, next ); if ( res ) { //D:this.debug(" matched"); if ( !isArray(res) || ( res.length > 0 && !( isArray(res[0]) ) ) ) this.debug(ord[i], "didn't return a proper array"); //D:this.debug( "" ); return res; } } // Uhoh! no match! Should we throw an error? return []; }; Markdown.prototype.processInline = function processInline( block ) { return this.dialect.inline.__call__.call( this, String( block ) ); }; /** * Markdown#toTree( source ) -> JsonML * - source (String): markdown source to parse * * Parse `source` into a JsonML tree representing the markdown document. **/ // custom_tree means set this.tree to `custom_tree` and restore old value on return Markdown.prototype.toTree = function toTree( source, custom_root ) { var blocks = source instanceof Array ? source : this.split_blocks( source ); // Make tree a member variable so its easier to mess with in extensions var old_tree = this.tree; try { this.tree = custom_root || this.tree || [ "markdown" ]; blocks: while ( blocks.length ) { var b = this.processBlock( blocks.shift(), blocks ); // Reference blocks and the like won't return any content if ( !b.length ) continue blocks; this.tree.push.apply( this.tree, b ); } return this.tree; } finally { if ( custom_root ) { this.tree = old_tree; } } }; // Noop by default Markdown.prototype.debug = function () { var args = Array.prototype.slice.call( arguments); args.unshift(this.debug_indent); if (typeof print !== "undefined") print.apply( print, args ); if (typeof console !== "undefined" && typeof console.log !== "undefined") console.log.apply( null, args ); } Markdown.prototype.loop_re_over_block = function( re, block, cb ) { // Dont use /g regexps with this var m, b = block.valueOf(); while ( b.length && (m = re.exec(b) ) != null) { b = b.substr( m[0].length ); cb.call(this, m); } return b; }; /** * Markdown.dialects * * Namespace of built-in dialects. **/ Markdown.dialects = {}; /** * Markdown.dialects.Gruber * * The default dialect that follows the rules set out by John Gruber's * markdown.pl as closely as possible. Well actually we follow the behaviour of * that script which in some places is not exactly what the syntax web page * says. **/ Markdown.dialects.Gruber = { block: { atxHeader: function atxHeader( block, next ) { var m = block.match( /^(#{1,6})\s*(.*?)\s*#*\s*(?:\n|$)/ ); if ( !m ) return undefined; var header = [ "header", { level: m[ 1 ].length } ]; Array.prototype.push.apply(header, this.processInline(m[ 2 ])); if ( m[0].length < block.length ) next.unshift( mk_block( block.substr( m[0].length ), block.trailing, block.lineNumber + 2 ) ); return [ header ]; }, setextHeader: function setextHeader( block, next ) { var m = block.match( /^(.*)\n([-=])\2\2+(?:\n|$)/ ); if ( !m ) return undefined; var level = ( m[ 2 ] === "=" ) ? 1 : 2; var header = [ "header", { level : level }, m[ 1 ] ]; if ( m[0].length < block.length ) next.unshift( mk_block( block.substr( m[0].length ), block.trailing, block.lineNumber + 2 ) ); return [ header ]; }, code: function code( block, next ) { // | Foo // |bar // should be a code block followed by a paragraph. Fun // // There might also be adjacent code block to merge. var ret = [], re = /^(?: {0,3}\t| {4})(.*)\n?/, lines; // 4 spaces + content if ( !block.match( re ) ) return undefined; block_search: do { // Now pull out the rest of the lines var b = this.loop_re_over_block( re, block.valueOf(), function( m ) { ret.push( m[1] ); } ); if (b.length) { // Case alluded to in first comment. push it back on as a new block next.unshift( mk_block(b, block.trailing) ); break block_search; } else if (next.length) { // Check the next block - it might be code too if ( !next[0].match( re ) ) break block_search; // Pull how how many blanks lines follow - minus two to account for .join ret.push ( block.trailing.replace(/[^\n]/g, '').substring(2) ); block = next.shift(); } else { break block_search; } } while (true); return [ [ "code_block", ret.join("\n") ] ]; }, horizRule: function horizRule( block, next ) { // this needs to find any hr in the block to handle abutting blocks var m = block.match( /^(?:([\s\S]*?)\n)?[ \t]*([-_*])(?:[ \t]*\2){2,}[ \t]*(?:\n([\s\S]*))?$/ ); if ( !m ) { return undefined; } var jsonml = [ [ "hr" ] ]; // if there's a leading abutting block, process it if ( m[ 1 ] ) { jsonml.unshift.apply( jsonml, this.processBlock( m[ 1 ], [] ) ); } // if there's a trailing abutting block, stick it into next if ( m[ 3 ] ) { next.unshift( mk_block( m[ 3 ] ) ); } return jsonml; }, // There are two types of lists. Tight and loose. Tight lists have no whitespace // between the items (and result in text just in the <li>) and loose lists, // which have an empty line between list items, resulting in (one or more) // paragraphs inside the <li>. // // There are all sorts weird edge cases about the original markdown.pl's // handling of lists: // // * Nested lists are supposed to be indented by four chars per level. But // if they aren't, you can get a nested list by indenting by less than // four so long as the indent doesn't match an indent of an existing list // item in the 'nest stack'. // // * The type of the list (bullet or number) is controlled just by the // first item at the indent. Subsequent changes are ignored unless they // are for nested lists // lists: (function( ) { // Use a closure to hide a few variables. var any_list = "[*+-]|\\d+\\.", bullet_list = /[*+-]/, number_list = /\d+\./, // Capture leading indent as it matters for determining nested lists. is_list_re = new RegExp( "^( {0,3})(" + any_list + ")[ \t]+" ), indent_re = "(?: {0,3}\\t| {4})"; // TODO: Cache this regexp for certain depths. // Create a regexp suitable for matching an li for a given stack depth function regex_for_depth( depth ) { return new RegExp( // m[1] = indent, m[2] = list_type "(?:^(" + indent_re + "{0," + depth + "} {0,3})(" + any_list + ")\\s+)|" + // m[3] = cont "(^" + indent_re + "{0," + (depth-1) + "}[ ]{0,4})" ); } function expand_tab( input ) { return input.replace( / {0,3}\t/g, " " ); } // Add inline content `inline` to `li`. inline comes from processInline // so is an array of content function add(li, loose, inline, nl) { if (loose) { li.push( [ "para" ].concat(inline) ); return; } // Hmmm, should this be any block level element or just paras? var add_to = li[li.length -1] instanceof Array && li[li.length - 1][0] == "para" ? li[li.length -1] : li; // If there is already some content in this list, add the new line in if (nl && li.length > 1) inline.unshift(nl); for (var i=0; i < inline.length; i++) { var what = inline[i], is_str = typeof what == "string"; if (is_str && add_to.length > 1 && typeof add_to[add_to.length-1] == "string" ) { add_to[ add_to.length-1 ] += what; } else { add_to.push( what ); } } } // contained means have an indent greater than the current one. On // *every* line in the block function get_contained_blocks( depth, blocks ) { var re = new RegExp( "^(" + indent_re + "{" + depth + "}.*?\\n?)*$" ), replace = new RegExp("^" + indent_re + "{" + depth + "}", "gm"), ret = []; while ( blocks.length > 0 ) { if ( re.exec( blocks[0] ) ) { var b = blocks.shift(), // Now remove that indent x = b.replace( replace, ""); ret.push( mk_block( x, b.trailing, b.lineNumber ) ); } break; } return ret; } // passed to stack.forEach to turn list items up the stack into paras function paragraphify(s, i, stack) { var list = s.list; var last_li = list[list.length-1]; if (last_li[1] instanceof Array && last_li[1][0] == "para") { return; } if (i+1 == stack.length) { // Last stack frame // Keep the same array, but replace the contents last_li.push( ["para"].concat( last_li.splice(1) ) ); } else { var sublist = last_li.pop(); last_li.push( ["para"].concat( last_li.splice(1) ), sublist ); } } // The matcher function return function( block, next ) { var m = block.match( is_list_re ); if ( !m ) return undefined; function make_list( m ) { var list = bullet_list.exec( m[2] ) ? ["bulletlist"] : ["numberlist"]; stack.push( { list: list, indent: m[1] } ); return list; } var stack = [], // Stack of lists for nesting. list = make_list( m ), last_li, loose = false, ret = [ stack[0].list ], i; // Loop to search over block looking for inner block elements and loose lists loose_search: while( true ) { // Split into lines preserving new lines at end of line var lines = block.split( /(?=\n)/ ); // We have to grab all lines for a li and call processInline on them // once as there are some inline things that can span lines. var li_accumulate = ""; // Loop over the lines in this block looking for tight lists. tight_search: for (var line_no=0; line_no < lines.length; line_no++) { var nl = "", l = lines[line_no].replace(/^\n/, function(n) { nl = n; return ""; }); // TODO: really should cache this var line_re = regex_for_depth( stack.length ); m = l.match( line_re ); //print( "line:", uneval(l), "\nline match:", uneval(m) ); // We have a list item if ( m[1] !== undefined ) { // Process the previous list item, if any if ( li_accumulate.length ) { add( last_li, loose, this.processInline( li_accumulate ), nl ); // Loose mode will have been dealt with. Reset it loose = false; li_accumulate = ""; } m[1] = expand_tab( m[1] ); var wanted_depth = Math.floor(m[1].length/4)+1; //print( "want:", wanted_depth, "stack:", stack.length); if ( wanted_depth > stack.length ) { // Deep enough for a nested list outright //print ( "new nested list" ); list = make_list( m ); last_li.push( list ); last_li = list[1] = [ "listitem" ]; } else { // We aren't deep enough to be strictly a new level. This is // where Md.pl goes nuts. If the indent matches a level in the // stack, put it there, else put it one deeper then the // wanted_depth deserves. var found = false; for (i = 0; i < stack.length; i++) { if ( stack[ i ].indent != m[1] ) continue; list = stack[ i ].list; stack.splice( i+1 ); found = true; break; } if (!found) { //print("not found. l:", uneval(l)); wanted_depth++; if (wanted_depth <= stack.length) { stack.splice(wanted_depth); //print("Desired depth now", wanted_depth, "stack:", stack.length); list = stack[wanted_depth-1].list; //print("list:", uneval(list) ); } else { //print ("made new stack for messy indent"); list = make_list(m); last_li.push(list); } } //print( uneval(list), "last", list === stack[stack.length-1].list ); last_li = [ "listitem" ]; list.push(last_li); } // end depth of shenegains nl = ""; } // Add content if (l.length > m[0].length) { li_accumulate += nl + l.substr( m[0].length ); } } // tight_search if ( li_accumulate.length ) { add( last_li, loose, this.processInline( li_accumulate ), nl ); // Loose mode will have been dealt with. Reset it loose = false; li_accumulate = ""; } // Look at the next block - we might have a loose list. Or an extra // paragraph for the current li var contained = get_contained_blocks( stack.length, next ); // Deal with code blocks or properly nested lists if (contained.length > 0) { // Make sure all listitems up the stack are paragraphs forEach( stack, paragraphify, this); last_li.push.apply( last_li, this.toTree( contained, [] ) ); } var next_block = next[0] && next[0].valueOf() || ""; if ( next_block.match(is_list_re) || next_block.match( /^ / ) ) { block = next.shift(); // Check for an HR following a list: features/lists/hr_abutting var hr = this.dialect.block.horizRule( block, next ); if (hr) { ret.push.apply(ret, hr); break; } // Make sure all listitems up the stack are paragraphs forEach( stack, paragraphify, this); loose = true; continue loose_search; } break; } // loose_search return ret; }; })(), blockquote: function blockquote( block, next ) { if ( !block.match( /^>/m ) ) return undefined; var jsonml = []; // separate out the leading abutting block, if any if ( block[ 0 ] != ">" ) { var lines = block.split( /\n/ ), prev = []; // keep shifting lines until you find a crotchet while ( lines.length && lines[ 0 ][ 0 ] != ">" ) { prev.push( lines.shift() ); } // reassemble! block = lines.join( "\n" ); jsonml.push.apply( jsonml, this.processBlock( prev.join( "\n" ), [] ) ); } // if the next block is also a blockquote merge it in while ( next.length && next[ 0 ][ 0 ] == ">" ) { var b = next.shift(); block = new String(block + block.trailing + b); block.trailing = b.trailing; } // Strip off the leading "> " and re-process as a block. var input = block.replace( /^> ?/gm, '' ), old_tree = this.tree; jsonml.push( this.toTree( input, [ "blockquote" ] ) ); return jsonml; }, referenceDefn: function referenceDefn( block, next) { var re = /^\s*\[(.*?)\]:\s*(\S+)(?:\s+(?:(['"])(.*?)\3|\((.*?)\)))?\n?/; // interesting matches are [ , ref_id, url, , title, title ] if ( !block.match(re) ) return undefined; // make an attribute node if it doesn't exist if ( !extract_attr( this.tree ) ) { this.tree.splice( 1, 0, {} ); } var attrs = extract_attr( this.tree ); // make a references hash if it doesn't exist if ( attrs.references === undefined ) { attrs.references = {}; } var b = this.loop_re_over_block(re, block, function( m ) { if ( m[2] && m[2][0] == '<' && m[2][m[2].length-1] == '>' ) m[2] = m[2].substring( 1, m[2].length - 1 ); var ref = attrs.references[ m[1].toLowerCase() ] = { href: m[2] }; if (m[4] !== undefined) ref.title = m[4]; else if (m[5] !== undefined) ref.title = m[5]; } ); if (b.length) next.unshift( mk_block( b, block.trailing ) ); return []; }, para: function para( block, next ) { // everything's a para! return [ ["para"].concat( this.processInline( block ) ) ]; } } }; Markdown.dialects.Gruber.inline = { __oneElement__: function oneElement( text, patterns_or_re, previous_nodes ) { var m, res, lastIndex = 0; patterns_or_re = patterns_or_re || this.dialect.inline.__patterns__; var re = new RegExp( "([\\s\\S]*?)(" + (patterns_or_re.source || patterns_or_re) + ")" ); m = re.exec( text ); if (!m) { // Just boring text return [ text.length, text ]; } else if ( m[1] ) { // Some un-interesting text matched. Return that first return [ m[1].length, m[1] ]; } var res; if ( m[2] in this.dialect.inline ) { res = this.dialect.inline[ m[2] ].call( this, text.substr( m.index ), m, previous_nodes || [] ); } // Default for now to make dev easier. just slurp special and output it. res = res || [ m[2].length, m[2] ]; return res; }, __call__: function inline( text, patterns ) { var out = [], res; function add(x) { //D:self.debug(" adding output", uneval(x)); if (typeof x == "string" && typeof out[out.length-1] == "string") out[ out.length-1 ] += x; else out.push(x); } while ( text.length > 0 ) { res = this.dialect.inline.__oneElement__.call(this, text, patterns, out ); text = text.substr( res.shift() ); forEach(res, add ) } return out; }, // These characters are intersting elsewhere, so have rules for them so that // chunks of plain text blocks don't include them "]": function () {}, "}": function () {}, "\\": function escaped( text ) { // [ length of input processed, node/children to add... ] // Only esacape: \ ` * _ { } [ ] ( ) # * + - . ! if ( text.match( /^\\[\\`\*_{}\[\]()#\+.!\-]/ ) ) return [ 2, text[1] ]; else // Not an esacpe return [ 1, "\\" ]; }, "![": function image( text ) { // Unlike images, alt text is plain text only. no other elements are // allowed in there // ![Alt text](/path/to/img.jpg "Optional title") // 1 2 3 4 <--- captures var m = text.match( /^!\[(.*?)\][ \t]*\([ \t]*(\S*)(?:[ \t]+(["'])(.*?)\3)?[ \t]*\)/ ); if ( m ) { if ( m[2] && m[2][0] == '<' && m[2][m[2].length-1] == '>' ) m[2] = m[2].substring( 1, m[2].length - 1 ); m[2] = this.dialect.inline.__call__.call( this, m[2], /\\/ )[0]; var attrs = { alt: m[1], href: m[2] || "" }; if ( m[4] !== undefined) attrs.title = m[4]; return [ m[0].length, [ "img", attrs ] ]; } // ![Alt text][id] m = text.match( /^!\[(.*?)\][ \t]*\[(.*?)\]/ ); if ( m ) { // We can't check if the reference is known here as it likely wont be // found till after. Check it in md tree->hmtl tree conversion return [ m[0].length, [ "img_ref", { alt: m[1], ref: m[2].toLowerCase(), original: m[0] } ] ]; } // Just consume the '![' return [ 2, "![" ]; }, "[": function link( text ) { var orig = String(text); // Inline content is possible inside `link text` var res = Markdown.DialectHelpers.inline_until_char.call( this, text.substr(1), ']' ); // No closing ']' found. Just consume the [ if ( !res ) return [ 1, '[' ]; var consumed = 1 + res[ 0 ], children = res[ 1 ], link, attrs; // At this point the first [...] has been parsed. See what follows to find // out which kind of link we are (reference or direct url) text = text.substr( consumed ); // [link text](/path/to/img.jpg "Optional title") // 1 2 3 <--- captures // This will capture up to the last paren in the block. We then pull // back based on if there a matching ones in the url // ([here](/url/(test)) // The parens have to be balanced var m = text.match( /^\s*\([ \t]*(\S+)(?:[ \t]+(["'])(.*?)\2)?[ \t]*\)/ ); if ( m ) { var url = m[1]; consumed += m[0].length; if ( url && url[0] == '<' && url[url.length-1] == '>' ) url = url.substring( 1, url.length - 1 ); // If there is a title we don't have to worry about parens in the url if ( !m[3] ) { var open_parens = 1; // One open that isn't in the capture for (var len = 0; len < url.length; len++) { switch ( url[len] ) { case '(': open_parens++; break; case ')': if ( --open_parens == 0) { consumed -= url.length - len; url = url.substring(0, len); } break; } } } // Process escapes only url = this.dialect.inline.__call__.call( this, url, /\\/ )[0]; attrs = { href: url || "" }; if ( m[3] !== undefined) attrs.title = m[3]; link = [ "link", attrs ].concat( children ); return [ consumed, link ]; } // [Alt text][id] // [Alt text] [id] m = text.match( /^\s*\[(.*?)\]/ ); if ( m ) { consumed += m[ 0 ].length; // [links][] uses links as its reference attrs = { ref: ( m[ 1 ] || String(children) ).toLowerCase(), original: orig.substr( 0, consumed ) }; link = [ "link_ref", attrs ].concat( children ); // We can't check if the reference is known here as it likely wont be // found till after. Check it in md tree->hmtl tree conversion. // Store the original so that conversion can revert if the ref isn't found. return [ consumed, link ]; } // [id] // Only if id is plain (no formatting.) if ( children.length == 1 && typeof children[0] == "string" ) { attrs = { ref: children[0].toLowerCase(), original: orig.substr( 0, consumed ) }; link = [ "link_ref", attrs, children[0] ]; return [ consumed, link ]; } // Just consume the '[' return [ 1, "[" ]; }, "<": function autoLink( text ) { var m; if ( ( m = text.match( /^<(?:((https?|ftp|mailto):[^>]+)|(.*?@.*?\.[a-zA-Z]+))>/ ) ) != null ) { if ( m[3] ) { return [ m[0].length, [ "link", { href: "mailto:" + m[3] }, m[3] ] ]; } else if ( m[2] == "mailto" ) { return [ m[0].length, [ "link", { href: m[1] }, m[1].substr("mailto:".length ) ] ]; } else return [ m[0].length, [ "link", { href: m[1] }, m[1] ] ]; } return [ 1, "<" ]; }, "`": function inlineCode( text ) { // Inline code block. as many backticks as you like to start it // Always skip over the opening ticks. var m = text.match( /(`+)(([\s\S]*?)\1)/ ); if ( m && m[2] ) return [ m[1].length + m[2].length, [ "inlinecode", m[3] ] ]; else { // TODO: No matching end code found - warn! return [ 1, "`" ]; } }, " \n": function lineBreak( text ) { return [ 3, [ "linebreak" ] ]; } }; // Meta Helper/generator method for em and strong handling function strong_em( tag, md ) { var state_slot = tag + "_state", other_slot = tag == "strong" ? "em_state" : "strong_state"; function CloseTag(len) { this.len_after = len; this.name = "close_" + md; } return function ( text, orig_match ) { if (this[state_slot][0] == md) { // Most recent em is of this type //D:this.debug("closing", md); this[state_slot].shift(); // "Consume" everything to go back to the recrusion in the else-block below return[ text.length, new CloseTag(text.length-md.length) ]; } else { // Store a clone of the em/strong states var other = this[other_slot].slice(), state = this[state_slot].slice(); this[state_slot].unshift(md); //D:this.debug_indent += " "; // Recurse var res = this.processInline( text.substr( md.length ) ); //D:this.debug_indent = this.debug_indent.substr(2); var last = res[res.length - 1]; //D:this.debug("processInline from", tag + ": ", uneval( res ) ); var check = this[state_slot].shift(); if (last instanceof CloseTag) { res.pop(); // We matched! Huzzah. var consumed = text.length - last.len_after; return [ consumed, [ tag ].concat(res) ]; } else { // Restore the state of the other kind. We might have mistakenly closed it. this[other_slot] = other; this[state_slot] = state; // We can't reuse the processed result as it could have wrong parsing contexts in it. return [ md.length, md ]; } } }; // End returned function } Markdown.dialects.Gruber.inline["**"] = strong_em("strong", "**"); Markdown.dialects.Gruber.inline["__"] = strong_em("strong", "__"); Markdown.dialects.Gruber.inline["*"] = strong_em("em", "*"); Markdown.dialects.Gruber.inline["_"] = strong_em("em", "_"); // Build default order from insertion order. Markdown.buildBlockOrder = function(d) { var ord = []; for ( var i in d ) { if ( i == "__order__" || i == "__call__" ) continue; ord.push( i ); } d.__order__ = ord; }; // Build patterns for inline matcher Markdown.buildInlinePatterns = function(d) { var patterns = []; for ( var i in d ) { // __foo__ is reserved and not a pattern if ( i.match( /^__.*__$/) ) continue; var l = i.replace( /([\\.*+?|()\[\]{}])/g, "\\$1" ) .replace( /\n/, "\\n" ); patterns.push( i.length == 1 ? l : "(?:" + l + ")" ); } patterns = patterns.join("|"); d.__patterns__ = patterns; //print("patterns:", uneval( patterns ) ); var fn = d.__call__; d.__call__ = function(text, pattern) { if (pattern != undefined) { return fn.call(this, text, pattern); } else { return fn.call(this, text, patterns); } }; }; Markdown.DialectHelpers = {}; Markdown.DialectHelpers.inline_until_char = function( text, want ) { var consumed = 0, nodes = []; while ( true ) { if ( text[ consumed ] == want ) { // Found the character we were looking for consumed++; return [ consumed, nodes ]; } if ( consumed >= text.length ) { // No closing char found. Abort. return null; } var res = this.dialect.inline.__oneElement__.call(this, text.substr( consumed ) ); consumed += res[ 0 ]; // Add any returned nodes. nodes.push.apply( nodes, res.slice( 1 ) ); } } // Helper function to make sub-classing a dialect easier Markdown.subclassDialect = function( d ) { function Block() {} Block.prototype = d.block; function Inline() {} Inline.prototype = d.inline; return { block: new Block(), inline: new Inline() }; }; Markdown.buildBlockOrder ( Markdown.dialects.Gruber.block ); Markdown.buildInlinePatterns( Markdown.dialects.Gruber.inline ); Markdown.dialects.Maruku = Markdown.subclassDialect( Markdown.dialects.Gruber ); Markdown.dialects.Maruku.processMetaHash = function processMetaHash( meta_string ) { var meta = split_meta_hash( meta_string ), attr = {}; for ( var i = 0; i < meta.length; ++i ) { // id: #foo if ( /^#/.test( meta[ i ] ) ) { attr.id = meta[ i ].substring( 1 ); } // class: .foo else if ( /^\./.test( meta[ i ] ) ) { // if class already exists, append the new one if ( attr['class'] ) { attr['class'] = attr['class'] + meta[ i ].replace( /./, " " ); } else { attr['class'] = meta[ i ].substring( 1 ); } } // attribute: foo=bar else if ( /\=/.test( meta[ i ] ) ) { var s = meta[ i ].split( /\=/ ); attr[ s[ 0 ] ] = s[ 1 ]; } } return attr; } function split_meta_hash( meta_string ) { var meta = meta_string.split( "" ), parts = [ "" ], in_quotes = false; while ( meta.length ) { var letter = meta.shift(); switch ( letter ) { case " " : // if we're in a quoted section, keep it if ( in_quotes ) { parts[ parts.length - 1 ] += letter; } // otherwise make a new part else { parts.push( "" ); } break; case "'" : case '"' : // reverse the quotes and move straight on in_quotes = !in_quotes; break; case "\\" : // shift off the next letter to be used straight away. // it was escaped so we'll keep it whatever it is letter = meta.shift(); default : parts[ parts.length - 1 ] += letter; break; } } return parts; } Markdown.dialects.Maruku.block.document_meta = function document_meta( block, next ) { // we're only interested in the first block if ( block.lineNumber > 1 ) return undefined; // document_meta blocks consist of one or more lines of `Key: Value\n` if ( ! block.match( /^(?:\w+:.*\n)*\w+:.*$/ ) ) return undefined; // make an attribute node if it doesn't exist if ( !extract_attr( this.tree ) ) { this.tree.splice( 1, 0, {} ); } var pairs = block.split( /\n/ ); for ( p in pairs ) { var m = pairs[ p ].match( /(\w+):\s*(.*)$/ ), key = m[ 1 ].toLowerCase(), value = m[ 2 ]; this.tree[ 1 ][ key ] = value; } // document_meta produces no content! return []; }; Markdown.dialects.Maruku.block.block_meta = function block_meta( block, next ) { // check if the last line of the block is an meta hash var m = block.match( /(^|\n) {0,3}\{:\s*((?:\\\}|[^\}])*)\s*\}$/ ); if ( !m ) return undefined; // process the meta hash var attr = this.dialect.processMetaHash( m[ 2 ] ); var hash; // if we matched ^ then we need to apply meta to the previous block if ( m[ 1 ] === "" ) { var node = this.tree[ this.tree.length - 1 ]; hash = extract_attr( node ); // if the node is a string (rather than JsonML), bail if ( typeof node === "string" ) return undefined; // create the attribute hash if it doesn't exist if ( !hash ) { hash = {}; node.splice( 1, 0, hash ); } // add the attributes in for ( a in attr ) { hash[ a ] = attr[ a ]; } // return nothing so the meta hash is removed return []; } // pull the meta hash off the block and process what's left var b = block.replace( /\n.*$/, "" ), result = this.processBlock( b, [] ); // get or make the attributes hash hash = extract_attr( result[ 0 ] ); if ( !hash ) { hash = {}; result[ 0 ].splice( 1, 0, hash ); } // attach the attributes to the block for ( a in attr ) { hash[ a ] = attr[ a ]; } return result; }; Markdown.dialects.Maruku.block.definition_list = function definition_list( block, next ) { // one or more terms followed by one or more definitions, in a single block var tight = /^((?:[^\s:].*\n)+):\s+([\s\S]+)$/, list = [ "dl" ], i; // see if we're dealing with a tight or loose block if ( ( m = block.match( tight ) ) ) { // pull subsequent tight DL blocks out of `next` var blocks = [ block ]; while ( next.length && tight.exec( next[ 0 ] ) ) { blocks.push( next.shift() ); } for ( var b = 0; b < blocks.length; ++b ) { var m = blocks[ b ].match( tight ), terms = m[ 1 ].replace( /\n$/, "" ).split( /\n/ ), defns = m[ 2 ].split( /\n:\s+/ ); // print( uneval( m ) ); for ( i = 0; i < terms.length; ++i ) { list.push( [ "dt", terms[ i ] ] ); } for ( i = 0; i < defns.length; ++i ) { // run inline processing over the definition list.push( [ "dd" ].concat( this.processInline( defns[ i ].replace( /(\n)\s+/, "$1" ) ) ) ); } } } else { return undefined; } return [ list ]; }; Markdown.dialects.Maruku.inline[ "{:" ] = function inline_meta( text, matches, out ) { if ( !out.length ) { return [ 2, "{:" ]; } // get the preceeding element var before = out[ out.length - 1 ]; if ( typeof before === "string" ) { return [ 2, "{:" ]; } // match a meta hash var m = text.match( /^\{:\s*((?:\\\}|[^\}])*)\s*\}/ ); // no match, false alarm if ( !m ) { return [ 2, "{:" ]; } // attach the attributes to the preceeding element var meta = this.dialect.processMetaHash( m[ 1 ] ), attr = extract_attr( before ); if ( !attr ) { attr = {}; before.splice( 1, 0, attr ); } for ( var k in meta ) { attr[ k ] = meta[ k ]; } // cut out the string and replace it with nothing return [ m[ 0 ].length, "" ]; }; Markdown.buildBlockOrder ( Markdown.dialects.Maruku.block ); Markdown.buildInlinePatterns( Markdown.dialects.Maruku.inline ); var isArray = Array.isArray || function(obj) { return Object.prototype.toString.call(obj) == '[object Array]'; }; var forEach; // Don't mess with Array.prototype. Its not friendly if ( Array.prototype.forEach ) { forEach = function( arr, cb, thisp ) { return arr.forEach( cb, thisp ); }; } else { forEach = function(arr, cb, thisp) { for (var i = 0; i < arr.length; i++) { cb.call(thisp || arr, arr[i], i, arr); } } } function extract_attr( jsonml ) { return isArray(jsonml) && jsonml.length > 1 && typeof jsonml[ 1 ] === "object" && !( isArray(jsonml[ 1 ]) ) ? jsonml[ 1 ] : undefined; } /** * renderJsonML( jsonml[, options] ) -> String * - jsonml (Array): JsonML array to render to XML * - options (Object): options * * Converts the given JsonML into well-formed XML. * * The options currently understood are: * * - root (Boolean): wether or not the root node should be included in the * output, or just its children. The default `false` is to not include the * root itself. */ expose.renderJsonML = function( jsonml, options ) { options = options || {}; // include the root element in the rendered output? options.root = options.root || false; var content = []; if ( options.root ) { content.push( render_tree( jsonml ) ); } else { jsonml.shift(); // get rid of the tag if ( jsonml.length && typeof jsonml[ 0 ] === "object" && !( jsonml[ 0 ] instanceof Array ) ) { jsonml.shift(); // get rid of the attributes } while ( jsonml.length ) { content.push( render_tree( jsonml.shift() ) ); } } return content.join( "\n\n" ); }; function escapeHTML( text ) { return text.replace( /&/g, "&amp;" ) .replace( /</g, "&lt;" ) .replace( />/g, "&gt;" ) .replace( /"/g, "&quot;" ) .replace( /'/g, "&#39;" ); } function render_tree( jsonml ) { // basic case if ( typeof jsonml === "string" ) { return escapeHTML( jsonml ); } var tag = jsonml.shift(), attributes = {}, content = []; if ( jsonml.length && typeof jsonml[ 0 ] === "object" && !( jsonml[ 0 ] instanceof Array ) ) { attributes = jsonml.shift(); } while ( jsonml.length ) { content.push( arguments.callee( jsonml.shift() ) ); } var tag_attrs = ""; for ( var a in attributes ) { tag_attrs += " " + a + '="' + escapeHTML( attributes[ a ] ) + '"'; } // be careful about adding whitespace here for inline elements if ( tag == "img" || tag == "br" || tag == "hr" ) { return "<"+ tag + tag_attrs + "/>"; } else { return "<"+ tag + tag_attrs + ">" + content.join( "" ) + "</" + tag + ">"; } } function convert_tree_to_html( tree, references, options ) { var i; options = options || {}; // shallow clone var jsonml = tree.slice( 0 ); if (typeof options.preprocessTreeNode === "function") { jsonml = options.preprocessTreeNode(jsonml, references); } // Clone attributes if they exist var attrs = extract_attr( jsonml ); if ( attrs ) { jsonml[ 1 ] = {}; for ( i in attrs ) { jsonml[ 1 ][ i ] = attrs[ i ]; } attrs = jsonml[ 1 ]; } // basic case if ( typeof jsonml === "string" ) { return jsonml; } // convert this node switch ( jsonml[ 0 ] ) { case "header": jsonml[ 0 ] = "h" + jsonml[ 1 ].level; delete jsonml[ 1 ].level; break; case "bulletlist": jsonml[ 0 ] = "ul"; break; case "numberlist": jsonml[ 0 ] = "ol"; break; case "listitem": jsonml[ 0 ] = "li"; break; case "para": jsonml[ 0 ] = "p"; break; case "markdown": jsonml[ 0 ] = "html"; if ( attrs ) delete attrs.references; break; case "code_block": jsonml[ 0 ] = "pre"; i = attrs ? 2 : 1; var code = [ "code" ]; code.push.apply( code, jsonml.splice( i ) ); jsonml[ i ] = code; break; case "inlinecode": jsonml[ 0 ] = "code"; break; case "img": jsonml[ 1 ].src = jsonml[ 1 ].href; delete jsonml[ 1 ].href; break; case "linebreak": jsonml[ 0 ] = "br"; break; case "link": jsonml[ 0 ] = "a"; break; case "link_ref": jsonml[ 0 ] = "a"; // grab this ref and clean up the attribute node var ref = references[ attrs.ref ]; // if the reference exists, make the link if ( ref ) { delete attrs.ref; // add in the href and title, if present attrs.href = ref.href; if ( ref.title ) { attrs.title = ref.title; } // get rid of the unneeded original text delete attrs.original; } // the reference doesn't exist, so revert to plain text else { return attrs.original; } break; case "img_ref": jsonml[ 0 ] = "img"; // grab this ref and clean up the attribute node var ref = references[ attrs.ref ]; // if the reference exists, make the link if ( ref ) { delete attrs.ref; // add in the href and title, if present attrs.src = ref.href; if ( ref.title ) { attrs.title = ref.title; } // get rid of the unneeded original text delete attrs.original; } // the reference doesn't exist, so revert to plain text else { return attrs.original; } break; } // convert all the children i = 1; // deal with the attribute node, if it exists if ( attrs ) { // if there are keys, skip over it for ( var key in jsonml[ 1 ] ) { i = 2; } // if there aren't, remove it if ( i === 1 ) { jsonml.splice( i, 1 ); } } for ( ; i < jsonml.length; ++i ) { jsonml[ i ] = arguments.callee( jsonml[ i ], references, options ); } return jsonml; } // merges adjacent text nodes into a single node function merge_text_nodes( jsonml ) { // skip the tag name and attribute hash var i = extract_attr( jsonml ) ? 2 : 1; while ( i < jsonml.length ) { // if it's a string check the next item too if ( typeof jsonml[ i ] === "string" ) { if ( i + 1 < jsonml.length && typeof jsonml[ i + 1 ] === "string" ) { // merge the second string into the first and remove it jsonml[ i ] += jsonml.splice( i + 1, 1 )[ 0 ]; } else { ++i; } } // if it's not a string recurse else { arguments.callee( jsonml[ i ] ); ++i; } } } } )( (function() { if ( typeof exports === "undefined" ) { window.markdown = {}; return window.markdown; } else { return exports; } } )() );
JavaScript
/*! * Nestable jQuery Plugin - Copyright (c) 2012 David Bushell - http://dbushell.com/ * Dual-licensed under the BSD or MIT licenses */ ;(function($, window, document, undefined) { var hasTouch = 'ontouchstart' in window; /** * Detect CSS pointer-events property * events are normally disabled on the dragging element to avoid conflicts * https://github.com/ausi/Feature-detection-technique-for-pointer-events/blob/master/modernizr-pointerevents.js */ var hasPointerEvents = (function() { var el = document.createElement('div'), docEl = document.documentElement; if (!('pointerEvents' in el.style)) { return false; } el.style.pointerEvents = 'auto'; el.style.pointerEvents = 'x'; docEl.appendChild(el); var supports = window.getComputedStyle && window.getComputedStyle(el, '').pointerEvents === 'auto'; docEl.removeChild(el); return !!supports; })(); var eStart = hasTouch ? 'touchstart' : 'mousedown', eMove = hasTouch ? 'touchmove' : 'mousemove', eEnd = hasTouch ? 'touchend' : 'mouseup'; eCancel = hasTouch ? 'touchcancel' : 'mouseup'; var defaults = { listNodeName : 'ol', itemNodeName : 'li', rootClass : 'dd', listClass : 'dd-list', itemClass : 'dd-item', dragClass : 'dd-dragel', handleClass : 'dd-handle', collapsedClass : 'dd-collapsed', placeClass : 'dd-placeholder', noDragClass : 'dd-nodrag', emptyClass : 'dd-empty', expandBtnHTML : '<button data-action="expand" type="button">Expand</button>', collapseBtnHTML : '<button data-action="collapse" type="button">Collapse</button>', group : 0, maxDepth : 5, threshold : 20 }; function Plugin(element, options) { this.w = $(window); this.el = $(element); this.options = $.extend({}, defaults, options); this.init(); } Plugin.prototype = { init: function() { var list = this; list.reset(); list.el.data('nestable-group', this.options.group); list.placeEl = $('<div class="' + list.options.placeClass + '"/>'); $.each(this.el.find(list.options.itemNodeName), function(k, el) { list.setParent($(el)); }); list.el.on('click', 'button', function(e) { if (list.dragEl || (!hasTouch && e.button !== 0)) { return; } var target = $(e.currentTarget), action = target.data('action'), item = target.parent(list.options.itemNodeName); if (action === 'collapse') { list.collapseItem(item); } if (action === 'expand') { list.expandItem(item); } }); var onStartEvent = function(e) { var handle = $(e.target); if (!handle.hasClass(list.options.handleClass)) { if (handle.closest('.' + list.options.noDragClass).length) { return; } handle = handle.closest('.' + list.options.handleClass); } if (!handle.length || list.dragEl || (!hasTouch && e.button !== 0) || (hasTouch && e.touches.length !== 1)) { return; } e.preventDefault(); list.dragStart(hasTouch ? e.touches[0] : e); }; var onMoveEvent = function(e) { if (list.dragEl) { e.preventDefault(); list.dragMove(hasTouch ? e.touches[0] : e); } }; var onEndEvent = function(e) { if (list.dragEl) { e.preventDefault(); list.dragStop(hasTouch ? e.touches[0] : e); } }; if (hasTouch) { list.el[0].addEventListener(eStart, onStartEvent, false); window.addEventListener(eMove, onMoveEvent, false); window.addEventListener(eEnd, onEndEvent, false); window.addEventListener(eCancel, onEndEvent, false); } else { list.el.on(eStart, onStartEvent); list.w.on(eMove, onMoveEvent); list.w.on(eEnd, onEndEvent); } }, serialize: function() { var data, depth = 0, list = this; step = function(level, depth) { var array = [ ], items = level.children(list.options.itemNodeName); items.each(function() { var li = $(this), item = $.extend({}, li.data()), sub = li.children(list.options.listNodeName); if (sub.length) { item.children = step(sub, depth + 1); } array.push(item); }); return array; }; data = step(list.el.find(list.options.listNodeName).first(), depth); return data; }, serialise: function() { return this.serialize(); }, reset: function() { this.mouse = { offsetX : 0, offsetY : 0, startX : 0, startY : 0, lastX : 0, lastY : 0, nowX : 0, nowY : 0, distX : 0, distY : 0, dirAx : 0, dirX : 0, dirY : 0, lastDirX : 0, lastDirY : 0, distAxX : 0, distAxY : 0 }; this.moving = false; this.dragEl = null; this.dragRootEl = null; this.dragDepth = 0; this.hasNewRoot = false; this.pointEl = null; }, expandItem: function(li) { li.removeClass(this.options.collapsedClass); li.children('[data-action="expand"]').hide(); li.children('[data-action="collapse"]').show(); li.children(this.options.listNodeName).show(); }, collapseItem: function(li) { var lists = li.children(this.options.listNodeName); if (lists.length) { li.addClass(this.options.collapsedClass); li.children('[data-action="collapse"]').hide(); li.children('[data-action="expand"]').show(); li.children(this.options.listNodeName).hide(); } }, expandAll: function() { var list = this; list.el.find(list.options.itemNodeName).each(function() { list.expandItem($(this)); }); }, collapseAll: function() { var list = this; list.el.find(list.options.itemNodeName).each(function() { list.collapseItem($(this)); }); }, setParent: function(li) { if (li.children(this.options.listNodeName).length) { li.prepend($(this.options.expandBtnHTML)); li.prepend($(this.options.collapseBtnHTML)); } li.children('[data-action="expand"]').hide(); }, unsetParent: function(li) { li.removeClass(this.options.collapsedClass); li.children('[data-action]').remove(); li.children(this.options.listNodeName).remove(); }, dragStart: function(e) { var mouse = this.mouse, target = $(e.target), dragItem = target.closest(this.options.itemNodeName); this.placeEl.css('height', dragItem.height()); mouse.offsetX = e.offsetX !== undefined ? e.offsetX : e.pageX - target.offset().left; mouse.offsetY = e.offsetY !== undefined ? e.offsetY : e.pageY - target.offset().top; mouse.startX = mouse.lastX = e.pageX; mouse.startY = mouse.lastY = e.pageY; this.dragRootEl = this.el; this.dragEl = $(document.createElement(this.options.listNodeName)).addClass(this.options.listClass + ' ' + this.options.dragClass); this.dragEl.css('width', dragItem.width()); // fix for zepto.js //dragItem.after(this.placeEl).detach().appendTo(this.dragEl); dragItem.after(this.placeEl); dragItem[0].parentNode.removeChild(dragItem[0]); dragItem.appendTo(this.dragEl); $(document.body).append(this.dragEl); this.dragEl.css({ 'left' : e.pageX - mouse.offsetX, 'top' : e.pageY - mouse.offsetY }); // total depth of dragging item var i, depth, items = this.dragEl.find(this.options.itemNodeName); for (i = 0; i < items.length; i++) { depth = $(items[i]).parents(this.options.listNodeName).length; if (depth > this.dragDepth) { this.dragDepth = depth; } } }, dragStop: function(e) { // fix for zepto.js //this.placeEl.replaceWith(this.dragEl.children(this.options.itemNodeName + ':first').detach()); var el = this.dragEl.children(this.options.itemNodeName).first(); el[0].parentNode.removeChild(el[0]); this.placeEl.replaceWith(el); this.dragEl.remove(); this.el.trigger('change'); if (this.hasNewRoot) { this.dragRootEl.trigger('change'); } this.reset(); }, dragMove: function(e) { var list, parent, prev, next, depth, opt = this.options, mouse = this.mouse; this.dragEl.css({ 'left' : e.pageX - mouse.offsetX, 'top' : e.pageY - mouse.offsetY }); // mouse position last events mouse.lastX = mouse.nowX; mouse.lastY = mouse.nowY; // mouse position this events mouse.nowX = e.pageX; mouse.nowY = e.pageY; // distance mouse moved between events mouse.distX = mouse.nowX - mouse.lastX; mouse.distY = mouse.nowY - mouse.lastY; // direction mouse was moving mouse.lastDirX = mouse.dirX; mouse.lastDirY = mouse.dirY; // direction mouse is now moving (on both axis) mouse.dirX = mouse.distX === 0 ? 0 : mouse.distX > 0 ? 1 : -1; mouse.dirY = mouse.distY === 0 ? 0 : mouse.distY > 0 ? 1 : -1; // axis mouse is now moving on var newAx = Math.abs(mouse.distX) > Math.abs(mouse.distY) ? 1 : 0; // do nothing on first move if (!mouse.moving) { mouse.dirAx = newAx; mouse.moving = true; return; } // calc distance moved on this axis (and direction) if (mouse.dirAx !== newAx) { mouse.distAxX = 0; mouse.distAxY = 0; } else { mouse.distAxX += Math.abs(mouse.distX); if (mouse.dirX !== 0 && mouse.dirX !== mouse.lastDirX) { mouse.distAxX = 0; } mouse.distAxY += Math.abs(mouse.distY); if (mouse.dirY !== 0 && mouse.dirY !== mouse.lastDirY) { mouse.distAxY = 0; } } mouse.dirAx = newAx; /** * move horizontal */ if (mouse.dirAx && mouse.distAxX >= opt.threshold) { // reset move distance on x-axis for new phase mouse.distAxX = 0; prev = this.placeEl.prev(opt.itemNodeName); // increase horizontal level if previous sibling exists and is not collapsed if (mouse.distX > 0 && prev.length && !prev.hasClass(opt.collapsedClass)) { // cannot increase level when item above is collapsed list = prev.find(opt.listNodeName).last(); // check if depth limit has reached depth = this.placeEl.parents(opt.listNodeName).length; if (depth + this.dragDepth <= opt.maxDepth) { // create new sub-level if one doesn't exist if (!list.length) { list = $('<' + opt.listNodeName + '/>').addClass(opt.listClass); list.append(this.placeEl); prev.append(list); this.setParent(prev); } else { // else append to next level up list = prev.children(opt.listNodeName).last(); list.append(this.placeEl); } } } // decrease horizontal level if (mouse.distX < 0) { // we can't decrease a level if an item preceeds the current one next = this.placeEl.next(opt.itemNodeName); if (!next.length) { parent = this.placeEl.parent(); this.placeEl.closest(opt.itemNodeName).after(this.placeEl); if (!parent.children().length) { this.unsetParent(parent.parent()); } } } } var isEmpty = false; // find list item under cursor if (!hasPointerEvents) { this.dragEl[0].style.visibility = 'hidden'; } this.pointEl = $(document.elementFromPoint(e.pageX - document.body.scrollLeft, e.pageY - (window.pageYOffset || document.documentElement.scrollTop))); if (!hasPointerEvents) { this.dragEl[0].style.visibility = 'visible'; } if (this.pointEl.hasClass(opt.handleClass)) { this.pointEl = this.pointEl.parent(opt.itemNodeName); } if (this.pointEl.hasClass(opt.emptyClass)) { isEmpty = true; } else if (!this.pointEl.length || !this.pointEl.hasClass(opt.itemClass)) { return; } // find parent list of item under cursor var pointElRoot = this.pointEl.closest('.' + opt.rootClass), isNewRoot = this.dragRootEl.data('nestable-id') !== pointElRoot.data('nestable-id'); /** * move vertical */ if (!mouse.dirAx || isNewRoot || isEmpty) { // check if groups match if dragging over new root if (isNewRoot && opt.group !== pointElRoot.data('nestable-group')) { return; } // check depth limit depth = this.dragDepth - 1 + this.pointEl.parents(opt.listNodeName).length; if (depth > opt.maxDepth) { return; } var before = e.pageY < (this.pointEl.offset().top + this.pointEl.height() / 2); parent = this.placeEl.parent(); // if empty create new list to replace empty placeholder if (isEmpty) { list = $(document.createElement(opt.listNodeName)).addClass(opt.listClass); list.append(this.placeEl); this.pointEl.replaceWith(list); } else if (before) { this.pointEl.before(this.placeEl); } else { this.pointEl.after(this.placeEl); } if (!parent.children().length) { this.unsetParent(parent.parent()); } if (!this.dragRootEl.find(opt.itemNodeName).length) { this.dragRootEl.append('<div class="' + opt.emptyClass + '"/>'); } // parent root list has changed if (isNewRoot) { this.dragRootEl = pointElRoot; this.hasNewRoot = this.el[0] !== this.dragRootEl[0]; } } } }; $.fn.nestable = function(params) { var lists = this, retval = this; lists.each(function() { var plugin = $(this).data("nestable"); if (!plugin) { $(this).data("nestable", new Plugin(this, params)); $(this).data("nestable-id", new Date().getTime()); } else { if (typeof params === 'string' && typeof plugin[params] === 'function') { retval = plugin[params](); } } }); return retval || lists; }; })(window.jQuery || window.Zepto, window, document);
JavaScript
/** * @preserve * FullCalendar v1.5.4 * http://arshaw.com/fullcalendar/ * * Use fullcalendar.css for basic styling. * For event drag & drop, requires jQuery UI draggable. * For event resizing, requires jQuery UI resizable. * * Copyright (c) 2011 Adam Shaw * Dual licensed under the MIT and GPL licenses, located in * MIT-LICENSE.txt and GPL-LICENSE.txt respectively. * * Date: Tue Sep 4 23:38:33 2012 -0700 * */ (function($, undefined) { var defaults = { // display defaultView: 'month', aspectRatio: 1.35, header: { left: 'title', center: '', right: 'today prev,next' }, weekends: true, // editing //editable: false, //disableDragging: false, //disableResizing: false, allDayDefault: true, ignoreTimezone: true, // event ajax lazyFetching: true, startParam: 'start', endParam: 'end', // time formats titleFormat: { month: 'MMMM yyyy', week: "MMM d[ yyyy]{ '&#8212;'[ MMM] d yyyy}", day: 'dddd, MMM d, yyyy' }, columnFormat: { month: 'ddd', week: 'ddd M/d', day: 'dddd M/d' }, timeFormat: { // for event elements '': 'h(:mm)t' // default }, // locale isRTL: false, firstDay: 0, monthNames: ['January','February','March','April','May','June','July','August','September','October','November','December'], monthNamesShort: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'], dayNames: ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'], dayNamesShort: ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'], buttonText: { prev: '&nbsp;&#9668;&nbsp;', next: '&nbsp;&#9658;&nbsp;', prevYear: '&nbsp;&lt;&lt;&nbsp;', nextYear: '&nbsp;&gt;&gt;&nbsp;', today: 'today', month: 'month', week: 'week', day: 'day' }, // jquery-ui theming theme: false, buttonIcons: { prev: 'circle-triangle-w', next: 'circle-triangle-e' }, //selectable: false, unselectAuto: true, dropAccept: '*' }; // right-to-left defaults var rtlDefaults = { header: { left: 'next,prev today', center: '', right: 'title' }, buttonText: { prev: '&nbsp;&#9658;&nbsp;', next: '&nbsp;&#9668;&nbsp;', prevYear: '&nbsp;&gt;&gt;&nbsp;', nextYear: '&nbsp;&lt;&lt;&nbsp;' }, buttonIcons: { prev: 'circle-triangle-e', next: 'circle-triangle-w' } }; var fc = $.fullCalendar = { version: "1.5.4" }; var fcViews = fc.views = {}; $.fn.fullCalendar = function(options) { // method calling if (typeof options == 'string') { var args = Array.prototype.slice.call(arguments, 1); var res; this.each(function() { var calendar = $.data(this, 'fullCalendar'); if (calendar && $.isFunction(calendar[options])) { var r = calendar[options].apply(calendar, args); if (res === undefined) { res = r; } if (options == 'destroy') { $.removeData(this, 'fullCalendar'); } } }); if (res !== undefined) { return res; } return this; } // would like to have this logic in EventManager, but needs to happen before options are recursively extended var eventSources = options.eventSources || []; delete options.eventSources; if (options.events) { eventSources.push(options.events); delete options.events; } options = $.extend(true, {}, defaults, (options.isRTL || options.isRTL===undefined && defaults.isRTL) ? rtlDefaults : {}, options ); this.each(function(i, _element) { var element = $(_element); var calendar = new Calendar(element, options, eventSources); element.data('fullCalendar', calendar); // TODO: look into memory leak implications calendar.render(); }); return this; }; // function for adding/overriding defaults function setDefaults(d) { $.extend(true, defaults, d); } function Calendar(element, options, eventSources) { var t = this; // 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.formatDate = function(format, date) { return formatDate(format, date, options) }; t.formatDates = function(format, date1, date2) { return formatDates(format, date1, date2, options) }; t.getDate = getDate; t.getView = getView; t.option = option; t.trigger = trigger; // imports EventManager.call(t, options, eventSources); 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 viewInstances = {}; var elementOuterWidth; var suggestedViewHeight; var absoluteViewElement; var resizeUID = 0; var ignoreWindowResize = 0; var date = new Date(); var events = []; var _dragElement; /* Main Rendering -----------------------------------------------------------------------------*/ setYMD(date, options.year, options.month, options.date); function render(inc) { if (!content) { initialRender(); }else{ calcSize(); markSizesDirty(); markEventsDirty(); renderView(inc); } } function initialRender() { tm = options.theme ? 'ui' : 'fc'; element.addClass('fc'); if (options.isRTL) { element.addClass('fc-rtl'); } if (options.theme) { element.addClass('ui-widget'); } content = $("<div class='fc-content' style='position:relative'/>") .prependTo(element); header = new Header(t, options); headerElement = header.render(); if (headerElement) { element.prepend(headerElement); } changeView(options.defaultView); $(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() { $(window).unbind('resize', windowResize); header.destroy(); content.remove(); element.removeClass('fc fc-rtl ui-widget'); } function elementVisible() { return _element.offsetWidth !== 0; } function bodyVisible() { return $('body')[0].offsetWidth !== 0; } /* View Rendering -----------------------------------------------------------------------------*/ // TODO: improve view switching (still weird transition in IE, and FF has whiteout problem) function changeView(newViewName) { if (!currentView || newViewName != currentView.name) { ignoreWindowResize++; // because setMinHeight might change the height before render (and subsequently setSize) is reached unselect(); var oldView = currentView; var newViewElement; if (oldView) { (oldView.beforeHide || noop)(); // called before changing min-height. if called after, scroll state is reset (in Opera) setMinHeight(content, content.height()); oldView.element.hide(); }else{ setMinHeight(content, 1); // needs to be 1 (not 0) for IE7, or else view dimensions miscalculated } content.css('overflow', 'hidden'); currentView = viewInstances[newViewName]; if (currentView) { currentView.element.show(); }else{ currentView = viewInstances[newViewName] = new fcViews[newViewName]( newViewElement = absoluteViewElement = $("<div class='fc-view fc-view-" + newViewName + "' style='position:absolute'/>") .appendTo(content), t // the calendar object ); } if (oldView) { header.deactivateButton(oldView.name); } header.activateButton(newViewName); renderView(); // after height has been set, will make absoluteViewElement's position=relative, then set to null content.css('overflow', ''); if (oldView) { setMinHeight(content, 1); } if (!newViewElement) { (currentView.afterShow || noop)(); // called after setting min-height/overflow, so in final scroll state (for Opera) } ignoreWindowResize--; } } function renderView(inc) { if (elementVisible()) { ignoreWindowResize++; // because renderEvents might temporarily change the height before setSize is reached unselect(); if (suggestedViewHeight === undefined) { calcSize(); } var forceEventRender = false; if (!currentView.start || inc || date < currentView.start || date >= currentView.end) { // view must render an entire new date range (and refetch/render events) currentView.render(date, inc || 0); // responsible for clearing events setSize(true); forceEventRender = true; } else if (currentView.sizeDirty) { // view must resize (and rerender events) currentView.clearEvents(); setSize(); forceEventRender = true; } else if (currentView.eventsDirty) { currentView.clearEvents(); forceEventRender = true; } currentView.sizeDirty = false; currentView.eventsDirty = false; updateEvents(forceEventRender); elementOuterWidth = element.outerWidth(); header.updateTitle(currentView.title); var today = new Date(); if (today >= currentView.start && today < currentView.end) { header.disableButton('today'); }else{ header.enableButton('today'); } ignoreWindowResize--; currentView.trigger('viewDisplay', _element); } } /* Resizing -----------------------------------------------------------------------------*/ function updateSize() { markSizesDirty(); if (elementVisible()) { calcSize(); setSize(); unselect(); currentView.clearEvents(); currentView.renderEvents(events); currentView.sizeDirty = false; } } function markSizesDirty() { $.each(viewInstances, function(i, inst) { inst.sizeDirty = true; }); } function calcSize() { 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(dateChanged) { // todo: dateChanged? ignoreWindowResize++; currentView.setHeight(suggestedViewHeight, dateChanged); if (absoluteViewElement) { absoluteViewElement.css('position', 'relative'); absoluteViewElement = null; } currentView.setWidth(content.width(), dateChanged); ignoreWindowResize--; } 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 -----------------------------------------------------------------------------*/ // fetches events if necessary, rerenders events if necessary (or if forced) function updateEvents(forceRender) { if (!options.lazyFetching || isFetchNeeded(currentView.visStart, currentView.visEnd)) { refetchEvents(); } else if (forceRender) { rerenderEvents(); } } function refetchEvents() { fetchEvents(currentView.visStart, currentView.visEnd); // will call reportEvents } // called when event data arrives function reportEvents(_events) { events = _events; rerenderEvents(); } // called when a single event's data has been changed function reportEventChange(eventID) { rerenderEvents(eventID); } // attempts to rerenderEvents function rerenderEvents(modifiedEventID) { markEventsDirty(); if (elementVisible()) { currentView.clearEvents(); currentView.renderEvents(events, modifiedEventID); currentView.eventsDirty = false; } } function markEventsDirty() { $.each(viewInstances, function(i, inst) { inst.eventsDirty = true; }); } /* Selection -----------------------------------------------------------------------------*/ function select(start, end, allDay) { currentView.select(start, end, allDay===undefined ? true : allDay); } function unselect() { // safe to be called before renderView if (currentView) { currentView.unselect(); } } /* Date -----------------------------------------------------------------------------*/ function prev() { renderView(-1); } function next() { renderView(1); } function prevYear() { addYears(date, -1); renderView(); } function nextYear() { addYears(date, 1); renderView(); } function today() { date = new Date(); renderView(); } function gotoDate(year, month, dateOfMonth) { if (year instanceof Date) { date = cloneDate(year); // provided 1 argument, a Date }else{ setYMD(date, year, month, dateOfMonth); } renderView(); } function incrementDate(years, months, days) { if (years !== undefined) { addYears(date, years); } if (months !== undefined) { addMonths(date, months); } if (days !== undefined) { addDays(date, days); } renderView(); } function getDate() { return cloneDate(date); } /* Misc -----------------------------------------------------------------------------*/ 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) { $(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) { var icon = options.theme ? smartProperty(options.buttonIcons, buttonName) : null; // why are we using smartProperty here? var text = smartProperty(options.buttonText, buttonName); // why are we using smartProperty here? var button = $( "<span class='fc-button fc-button-" + buttonName + " " + tm + "-state-default'>" + "<span class='fc-button-inner'>" + "<span class='fc-button-content'>" + (icon ? "<span class='fc-icon-wrap'>" + "<span class='ui-icon ui-icon-" + icon + "'/>" + "</span>" : text ) + "</span>" + "<span class='fc-button-effect'><span></span></span>" + "</span>" + "</span>" ); if (button) { button .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); 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, _sources) { 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.normalizeEvent = normalizeEvent; // imports var trigger = t.trigger; var getView = t.getView; var reportEvents = t.reportEvents; // locals var stickySource = { events: [] }; var sources = [ stickySource ]; var rangeStart, rangeEnd; var currentFetchID = 0; var pendingSourceCnt = 0; var loadingLevel = 0; var cache = []; for (var i=0; i<_sources.length; i++) { _addEventSource(_sources[i]); } /* Fetching -----------------------------------------------------------------------------*/ function isFetchNeeded(start, end) { return !rangeStart || start < rangeStart || end > rangeEnd; } 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++) { events[i].source = source; normalizeEvent(events[i]); } cache = cache.concat(events); } 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](source, rangeStart, rangeEnd, 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(cloneDate(rangeStart), cloneDate(rangeEnd), 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; var data = $.extend({}, source.data || {}); var startParam = firstDefined(source.startParam, options.startParam); var endParam = firstDefined(source.endParam, options.endParam); if (startParam) { data[startParam] = Math.round(+rangeStart / 1000); } if (endParam) { data[endParam] = Math.round(+rangeEnd / 1000); } 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) { // update an existing event var i, len = cache.length, e, defaultEventEnd = getView().defaultEventEnd, // getView??? startDelta = event.start - event._start, endDelta = event.end ? (event.end - (event._end || defaultEventEnd(event))) // event._end would be null if event.end : 0; // was null and event was just resized for (i=0; i<len; i++) { e = cache[i]; if (e._id == event._id && e != event) { e.start = new Date(+e.start + startDelta); if (event.end) { if (e.end) { e.end = new Date(+e.end + endDelta); }else{ e.end = new Date(+defaultEventEnd(e) + endDelta); } }else{ e.end = null; } e.title = event.title; e.url = event.url; e.allDay = event.allDay; e.className = event.className; e.editable = event.editable; e.color = event.color; e.backgroudColor = event.backgroudColor; e.borderColor = event.borderColor; e.textColor = event.textColor; normalizeEvent(e); } } normalizeEvent(event); reportEvents(cache); } function renderEvent(event, stick) { normalizeEvent(event); if (!event.source) { if (stick) { stickySource.events.push(event); event.source = stickySource; } cache.push(event); } reportEvents(cache); } function removeEvents(filter) { if (!filter) { // remove all cache = []; // clear all array sources for (var 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 (var 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); } } function popLoading() { if (!--loadingLevel) { trigger('loading', null, false); } } /* Event Normalization -----------------------------------------------------------------------------*/ function normalizeEvent(event) { var source = event.source || {}; var ignoreTimezone = firstDefined(source.ignoreTimezone, options.ignoreTimezone); event._id = event._id || (event.id === undefined ? '_fc' + eventGUID++ : event.id + ''); if (event.date) { if (!event.start) { event.start = event.date; } delete event.date; } event._start = cloneDate(event.start = parseDate(event.start, ignoreTimezone)); event.end = parseDate(event.end, ignoreTimezone); if (event.end && event.end <= event.start) { event.end = null; } event._end = event.end ? cloneDate(event.end) : null; if (event.allDay === undefined) { event.allDay = firstDefined(source.allDayDefault, options.allDayDefault); } if (event.className) { if (typeof event.className == 'string') { event.className = event.className.split(/\s+/); } }else{ event.className = []; } // TODO: if there is no start date, return false to indicate an invalid event } /* 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](source); } } function isSourcesEqual(source1, source2) { return source1 && source2 && getSourcePrimitive(source1) == getSourcePrimitive(source2); } function getSourcePrimitive(source) { return ((typeof source == 'object') ? (source.events || source.url) : '') || source; } } fc.addDays = addDays; fc.cloneDate = cloneDate; fc.parseDate = parseDate; fc.parseISO8601 = parseISO8601; fc.parseTime = parseTime; fc.formatDate = formatDate; fc.formatDates = formatDates; /* Date Math -----------------------------------------------------------------------------*/ var dayIDs = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'], DAY_MS = 86400000, HOUR_MS = 3600000, MINUTE_MS = 60000; function addYears(d, n, keepTime) { d.setFullYear(d.getFullYear() + n); if (!keepTime) { clearTime(d); } return d; } function addMonths(d, n, keepTime) { // prevents day overflow/underflow if (+d) { // prevent infinite looping on invalid dates var m = d.getMonth() + n, check = cloneDate(d); check.setDate(1); check.setMonth(m); d.setMonth(m); if (!keepTime) { clearTime(d); } while (d.getMonth() != check.getMonth()) { d.setDate(d.getDate() + (d < check ? 1 : -1)); } } return d; } function addDays(d, n, keepTime) { // deals with daylight savings if (+d) { var dd = d.getDate() + n, check = cloneDate(d); check.setHours(9); // set to middle of day check.setDate(dd); d.setDate(dd); if (!keepTime) { clearTime(d); } fixDate(d, check); } return d; } function fixDate(d, check) { // force d to be on check's YMD, for daylight savings purposes if (+d) { // prevent infinite looping on invalid dates while (d.getDate() != check.getDate()) { d.setTime(+d + (d < check ? 1 : -1) * HOUR_MS); } } } function addMinutes(d, n) { d.setMinutes(d.getMinutes() + n); return d; } function clearTime(d) { d.setHours(0); d.setMinutes(0); d.setSeconds(0); d.setMilliseconds(0); return d; } function cloneDate(d, dontKeepTime) { if (dontKeepTime) { return clearTime(new Date(+d)); } return new Date(+d); } function zeroDate() { // returns a Date with time 00:00:00 and dateOfMonth=1 var i=0, d; do { d = new Date(1970, i++, 1); } while (d.getHours()); // != 0 return d; } function skipWeekend(date, inc, excl) { inc = inc || 1; while (!date.getDay() || (excl && date.getDay()==1 || !excl && date.getDay()==6)) { addDays(date, inc); } return date; } function dayDiff(d1, d2) { // d1 - d2 return Math.round((cloneDate(d1, true) - cloneDate(d2, true)) / DAY_MS); } function setYMD(date, y, m, d) { if (y !== undefined && y != date.getFullYear()) { date.setDate(1); date.setMonth(0); date.setFullYear(y); } if (m !== undefined && m != date.getMonth()) { date.setDate(1); date.setMonth(m); } if (d !== undefined) { date.setDate(d); } } /* Date Parsing -----------------------------------------------------------------------------*/ function parseDate(s, ignoreTimezone) { // ignoreTimezone defaults to true if (typeof s == 'object') { // already a Date object return s; } if (typeof s == 'number') { // a UNIX timestamp return new Date(s * 1000); } if (typeof s == 'string') { if (s.match(/^\d+(\.\d+)?$/)) { // a UNIX timestamp return new Date(parseFloat(s) * 1000); } if (ignoreTimezone === undefined) { ignoreTimezone = true; } return parseISO8601(s, ignoreTimezone) || (s ? new Date(s) : null); } // TODO: never return invalid dates (like from new Date(<string>)), return null instead return null; } function parseISO8601(s, ignoreTimezone) { // ignoreTimezone defaults to false // derived from http://delete.me.uk/2005/03/iso8601.html // TODO: for a know glitch/feature, read tests/issue_206_parseDate_dst.html var m = s.match(/^([0-9]{4})(-([0-9]{2})(-([0-9]{2})([T ]([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?(Z|(([-+])([0-9]{2})(:?([0-9]{2}))?))?)?)?)?$/); if (!m) { return null; } var date = new Date(m[1], 0, 1); if (ignoreTimezone || !m[13]) { var check = new Date(m[1], 0, 1, 9, 0); if (m[3]) { date.setMonth(m[3] - 1); check.setMonth(m[3] - 1); } if (m[5]) { date.setDate(m[5]); check.setDate(m[5]); } fixDate(date, check); if (m[7]) { date.setHours(m[7]); } if (m[8]) { date.setMinutes(m[8]); } if (m[10]) { date.setSeconds(m[10]); } if (m[12]) { date.setMilliseconds(Number("0." + m[12]) * 1000); } fixDate(date, check); }else{ date.setUTCFullYear( m[1], m[3] ? m[3] - 1 : 0, m[5] || 1 ); date.setUTCHours( m[7] || 0, m[8] || 0, m[10] || 0, m[12] ? Number("0." + m[12]) * 1000 : 0 ); if (m[14]) { var offset = Number(m[16]) * 60 + (m[18] ? Number(m[18]) : 0); offset *= m[15] == '-' ? 1 : -1; date = new Date(+date + (offset * 60 * 1000)); } } return date; } function parseTime(s) { // returns minutes since start of day if (typeof s == 'number') { // an hour return s * 60; } if (typeof s == 'object') { // a Date object return s.getHours() * 60 + s.getMinutes(); } var m = s.match(/(\d+)(?::(\d+))?\s*(\w+)?/); if (m) { var h = parseInt(m[1], 10); if (m[3]) { h %= 12; if (m[3].toLowerCase().charAt(0) == 'p') { h += 12; } } return h * 60 + (m[2] ? parseInt(m[2], 10) : 0); } } /* Date Formatting -----------------------------------------------------------------------------*/ // TODO: use same function formatDate(date, [date2], format, [options]) function formatDate(date, format, options) { return formatDates(date, null, format, options); } function formatDates(date1, date2, format, options) { options = options || defaults; var date = date1, otherDate = date2, i, len = format.length, c, i2, formatter, res = ''; for (i=0; i<len; i++) { c = format.charAt(i); if (c == "'") { for (i2=i+1; i2<len; i2++) { if (format.charAt(i2) == "'") { if (date) { if (i2 == i+1) { res += "'"; }else{ res += format.substring(i+1, i2); } i = i2; } break; } } } else if (c == '(') { for (i2=i+1; i2<len; i2++) { if (format.charAt(i2) == ')') { var subres = formatDate(date, format.substring(i+1, i2), options); if (parseInt(subres.replace(/\D/, ''), 10)) { res += subres; } i = i2; break; } } } else if (c == '[') { for (i2=i+1; i2<len; i2++) { if (format.charAt(i2) == ']') { var subformat = format.substring(i+1, i2); var subres = formatDate(date, subformat, options); if (subres != formatDate(otherDate, subformat, options)) { res += subres; } i = i2; break; } } } else if (c == '{') { date = date2; otherDate = date1; } else if (c == '}') { date = date1; otherDate = date2; } else { for (i2=len; i2>i; i2--) { if (formatter = dateFormatters[format.substring(i, i2)]) { if (date) { res += formatter(date, options); } i = i2 - 1; break; } } if (i2 == i) { if (date) { res += c; } } } } return res; }; var dateFormatters = { s : function(d) { return d.getSeconds() }, ss : function(d) { return zeroPad(d.getSeconds()) }, m : function(d) { return d.getMinutes() }, mm : function(d) { return zeroPad(d.getMinutes()) }, h : function(d) { return d.getHours() % 12 || 12 }, hh : function(d) { return zeroPad(d.getHours() % 12 || 12) }, H : function(d) { return d.getHours() }, HH : function(d) { return zeroPad(d.getHours()) }, d : function(d) { return d.getDate() }, dd : function(d) { return zeroPad(d.getDate()) }, ddd : function(d,o) { return o.dayNamesShort[d.getDay()] }, dddd: function(d,o) { return o.dayNames[d.getDay()] }, M : function(d) { return d.getMonth() + 1 }, MM : function(d) { return zeroPad(d.getMonth() + 1) }, MMM : function(d,o) { return o.monthNamesShort[d.getMonth()] }, MMMM: function(d,o) { return o.monthNames[d.getMonth()] }, yy : function(d) { return (d.getFullYear()+'').substring(2) }, yyyy: function(d) { return d.getFullYear() }, t : function(d) { return d.getHours() < 12 ? 'a' : 'p' }, tt : function(d) { return d.getHours() < 12 ? 'am' : 'pm' }, T : function(d) { return d.getHours() < 12 ? 'A' : 'P' }, TT : function(d) { return d.getHours() < 12 ? 'AM' : 'PM' }, u : function(d) { return formatDate(d, "yyyy-MM-dd'T'HH:mm:ss'Z'") }, S : function(d) { var date = d.getDate(); if (date > 10 && date < 20) { return 'th'; } return ['st', 'nd', 'rd'][date%10-1] || 'th'; } }; fc.applyAll = applyAll; /* Event Date Math -----------------------------------------------------------------------------*/ function exclEndDay(event) { if (event.end) { return _exclEndDay(event.end, event.allDay); }else{ return addDays(cloneDate(event.start), 1); } } function _exclEndDay(end, allDay) { end = cloneDate(end); return allDay || end.getHours() || end.getMinutes() ? addDays(end, 1) : clearTime(end); } function segCmp(a, b) { return (b.msLength - a.msLength) * 100 + (a.event.start - b.event.start); } function segsCollide(seg1, seg2) { return seg1.end > seg2.start && seg1.start < seg2.end; } /* Event Sorting -----------------------------------------------------------------------------*/ // event rendering utilities function sliceSegs(events, visEventEnds, start, end) { var segs = [], i, len=events.length, event, eventStart, eventEnd, segStart, segEnd, isStart, isEnd; for (i=0; i<len; i++) { event = events[i]; eventStart = event.start; eventEnd = visEventEnds[i]; if (eventEnd > start && eventStart < end) { if (eventStart < start) { segStart = cloneDate(start); isStart = false; }else{ segStart = eventStart; isStart = true; } if (eventEnd > end) { segEnd = cloneDate(end); isEnd = false; }else{ segEnd = eventEnd; isEnd = true; } segs.push({ event: event, start: segStart, end: segEnd, isStart: isStart, isEnd: isEnd, msLength: segEnd - segStart }); } } return segs.sort(segCmp); } // event rendering calculation utilities function stackSegs(segs) { var levels = [], i, len = segs.length, seg, j, collide, k; for (i=0; i<len; i++) { seg = segs[i]; j = 0; // the level index where seg should belong while (true) { collide = false; if (levels[j]) { for (k=0; k<levels[j].length; k++) { if (segsCollide(levels[j][k], seg)) { collide = true; break; } } } if (collide) { j++; }else{ break; } } if (levels[j]) { levels[j].push(seg); }else{ levels[j] = [seg]; } } return levels; } /* 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); } function setMinHeight(element, height) { height = (typeof height == 'number' ? height + 'px' : height); element.each(function(i, _element) { _element.style.cssText += ';min-height:' + height + ';_height:' + height; // why can't we just use .css() ? i forget }); } /* Misc Utils -----------------------------------------------------------------------------*/ //TODO: arraySlice //TODO: isFunction, grep ? function noop() { } function cmp(a, b) { return a - b; } function arrayMax(a) { return Math.max.apply(Math, a); } function zeroPad(n) { return (n < 10 ? '0' : '') + n; } 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['']; } 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 cssKey(_element) { return _element.id + '/' + _element.className + '/' + _element.style.cssText.replace(/(^|;)\s*(top|left|width|height)\s*:[^;]*/ig, ''); } 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) { e.children() .removeClass('fc-first fc-last') .filter(':first-child') .addClass('fc-first') .end() .filter(':last-child') .addClass('fc-last'); } function setDayID(cell, date) { cell.each(function(i, _cell) { _cell.className = _cell.className.replace(/^fc-\w*/, 'fc-' + dayIDs[date.getDay()]); // TODO: make a way that doesn't rely on order of classes }); } 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]; } } } fcViews.month = MonthView; function MonthView(element, calendar) { var t = this; // exports t.render = render; // imports BasicView.call(t, element, calendar, 'month'); var opt = t.opt; var renderBasic = t.renderBasic; var formatDate = calendar.formatDate; function render(date, delta) { if (delta) { addMonths(date, delta); date.setDate(1); } var start = cloneDate(date, true); start.setDate(1); var end = addMonths(cloneDate(start), 1); var visStart = cloneDate(start); var visEnd = cloneDate(end); var firstDay = opt('firstDay'); var nwe = opt('weekends') ? 0 : 1; if (nwe) { skipWeekend(visStart); skipWeekend(visEnd, -1, true); } addDays(visStart, -((visStart.getDay() - Math.max(firstDay, nwe) + 7) % 7)); addDays(visEnd, (7 - visEnd.getDay() + Math.max(firstDay, nwe)) % 7); var rowCnt = Math.round((visEnd - visStart) / (DAY_MS * 7)); if (opt('weekMode') == 'fixed') { addDays(visEnd, (6 - rowCnt) * 7); rowCnt = 6; } t.title = formatDate(start, opt('titleFormat')); t.start = start; t.end = end; t.visStart = visStart; t.visEnd = visEnd; renderBasic(6, rowCnt, nwe ? 5 : 7, true); } } fcViews.basicWeek = BasicWeekView; function BasicWeekView(element, calendar) { var t = this; // exports t.render = render; // imports BasicView.call(t, element, calendar, 'basicWeek'); var opt = t.opt; var renderBasic = t.renderBasic; var formatDates = calendar.formatDates; function render(date, delta) { if (delta) { addDays(date, delta * 7); } var start = addDays(cloneDate(date), -((date.getDay() - opt('firstDay') + 7) % 7)); var end = addDays(cloneDate(start), 7); var visStart = cloneDate(start); var visEnd = cloneDate(end); var weekends = opt('weekends'); if (!weekends) { skipWeekend(visStart); skipWeekend(visEnd, -1, true); } t.title = formatDates( visStart, addDays(cloneDate(visEnd), -1), opt('titleFormat') ); t.start = start; t.end = end; t.visStart = visStart; t.visEnd = visEnd; renderBasic(1, 1, weekends ? 7 : 5, false); } } fcViews.basicDay = BasicDayView; //TODO: when calendar's date starts out on a weekend, shouldn't happen function BasicDayView(element, calendar) { var t = this; // exports t.render = render; // imports BasicView.call(t, element, calendar, 'basicDay'); var opt = t.opt; var renderBasic = t.renderBasic; var formatDate = calendar.formatDate; function render(date, delta) { if (delta) { addDays(date, delta); if (!opt('weekends')) { skipWeekend(date, delta < 0 ? -1 : 1); } } t.title = formatDate(date, opt('titleFormat')); t.start = t.visStart = cloneDate(date, true); t.end = t.visEnd = addDays(cloneDate(t.start), 1); renderBasic(1, 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.defaultEventEnd = defaultEventEnd; t.getHoverListener = function() { return hoverListener }; t.colContentLeft = colContentLeft; t.colContentRight = colContentRight; t.dayOfWeekCol = dayOfWeekCol; t.dateCell = dateCell; t.cellDate = cellDate; t.cellIsAllDay = function() { return true }; t.allDayRow = allDayRow; t.allDayBounds = allDayBounds; 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 clearEvents = t.clearEvents; var renderOverlay = t.renderOverlay; var clearOverlays = t.clearOverlays; var daySelectionMousedown = t.daySelectionMousedown; var formatDate = calendar.formatDate; // locals var head; var headCells; var body; var bodyRows; var bodyCells; var bodyFirstCells; var bodyCellTopInners; var daySegmentContainer; var viewWidth; var viewHeight; var colWidth; var rowCnt, colCnt; var coordinateGrid; var hoverListener; var colContentPositions; var rtl, dis, dit; var firstDay; var nwe; var tm; var colFormat; /* Rendering ------------------------------------------------------------*/ disableTextSelection(element.addClass('fc-grid')); function renderBasic(maxr, r, c, showNumbers) { rowCnt = r; colCnt = c; updateOptions(); var firstTime = !body; if (firstTime) { buildSkeleton(maxr, showNumbers); }else{ clearEvents(); } updateCells(firstTime); } function updateOptions() { rtl = opt('isRTL'); if (rtl) { dis = -1; dit = colCnt - 1; }else{ dis = 1; dit = 0; } firstDay = opt('firstDay'); nwe = opt('weekends') ? 0 : 1; tm = opt('theme') ? 'ui' : 'fc'; colFormat = opt('columnFormat'); } function buildSkeleton(maxRowCnt, showNumbers) { var s; var headerClass = tm + "-widget-header"; var contentClass = tm + "-widget-content"; var i, j; var table; s = "<table class='fc-border-separate' style='width:100%' cellspacing='0'>" + "<thead>" + "<tr>"; for (i=0; i<colCnt; i++) { s += "<th class='fc- " + headerClass + "'/>"; // need fc- for setDayID } s += "</tr>" + "</thead>" + "<tbody>"; for (i=0; i<maxRowCnt; i++) { s += "<tr class='fc-week" + i + "'>"; for (j=0; j<colCnt; j++) { s += "<td class='fc- " + contentClass + " fc-day" + (i*colCnt+j) + "'>" + // need fc- for setDayID "<div>" + (showNumbers ? "<div class='fc-day-number'/>" : '' ) + "<div class='fc-day-content'>" + "<div style='position:relative'>&nbsp;</div>" + "</div>" + "</div>" + "</td>"; } s += "</tr>"; } s += "</tbody>" + "</table>"; table = $(s).appendTo(element); head = table.find('thead'); headCells = head.find('th'); body = table.find('tbody'); bodyRows = body.find('tr'); bodyCells = body.find('td'); bodyFirstCells = bodyCells.filter(':first-child'); bodyCellTopInners = bodyRows.eq(0).find('div.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'); // fc-last is done in updateCells dayBind(bodyCells); daySegmentContainer = $("<div style='position:absolute;z-index:8;top:0;left:0'/>") .appendTo(element); } function updateCells(firstTime) { var dowDirty = firstTime || rowCnt == 1; // could the cells' day-of-weeks need updating? var month = t.start.getMonth(); var today = clearTime(new Date()); var cell; var date; var row; if (dowDirty) { headCells.each(function(i, _cell) { cell = $(_cell); date = indexDate(i); cell.html(formatDate(date, colFormat)); setDayID(cell, date); }); } bodyCells.each(function(i, _cell) { cell = $(_cell); date = indexDate(i); if (date.getMonth() == month) { cell.removeClass('fc-other-month'); }else{ cell.addClass('fc-other-month'); } if (+date == +today) { cell.addClass(tm + '-state-highlight fc-today'); }else{ cell.removeClass(tm + '-state-highlight fc-today'); } cell.find('div.fc-day-number').text(date.getDate()); if (dowDirty) { setDayID(cell, date); } }); bodyRows.each(function(i, _row) { row = $(_row); if (i < rowCnt) { row.show(); if (i == rowCnt-1) { row.addClass('fc-last'); }else{ row.removeClass('fc-last'); } }else{ row.hide(); } }); } function setHeight(height) { viewHeight = height; var bodyHeight = viewHeight - head.height(); 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); setMinHeight( cell.find('> div'), (i==rowCnt-1 ? rowHeightLast : rowHeight) - vsides(cell) ); } }); } function setWidth(width) { viewWidth = width; colContentPositions.clear(); colWidth = Math.floor(viewWidth / 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 index = parseInt(this.className.match(/fc\-day(\d+)/)[1]); // TODO: maybe use .data var date = indexDate(index); trigger('dayClick', this, date, true, ev); } } /* Semi-transparent Overlay Helpers ------------------------------------------------------*/ function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive if (refreshCoordinateGrid) { coordinateGrid.build(); } var rowStart = cloneDate(t.visStart); var rowEnd = addDays(cloneDate(rowStart), colCnt); for (var i=0; i<rowCnt; i++) { var stretchStart = new Date(Math.max(rowStart, overlayStart)); var stretchEnd = new Date(Math.min(rowEnd, overlayEnd)); if (stretchStart < stretchEnd) { var colStart, colEnd; if (rtl) { colStart = dayDiff(stretchEnd, rowStart)*dis+dit+1; colEnd = dayDiff(stretchStart, rowStart)*dis+dit+1; }else{ colStart = dayDiff(stretchStart, rowStart); colEnd = dayDiff(stretchEnd, rowStart); } dayBind( renderCellOverlay(i, colStart, i, colEnd-1) ); } addDays(rowStart, 7); addDays(rowEnd, 7); } } 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(startDate, allDay) { return cloneDate(startDate); } function renderSelection(startDate, endDate, allDay) { renderDayOverlay(startDate, addDays(cloneDate(endDate), 1), true); // rebuild every time??? } function clearSelection() { clearOverlays(); } function reportDayClick(date, allDay, ev) { var cell = dateCell(date); var _element = bodyCells[cell.row*colCnt + cell.col]; trigger('dayClick', _element, date, allDay, ev); } /* External Dragging -----------------------------------------------------------------------*/ function dragStart(_dragElement, ev, ui) { hoverListener.start(function(cell) { clearOverlays(); if (cell) { renderCellOverlay(cell.row, cell.col, cell.row, cell.col); } }, ev); } function dragStop(_dragElement, ev, ui) { var cell = hoverListener.stop(); clearOverlays(); if (cell) { var d = cellDate(cell); trigger('drop', _dragElement, d, true, ev, ui); } } /* Utilities --------------------------------------------------------*/ function defaultEventEnd(event) { return cloneDate(event.start); } 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); colContentPositions = new HorizontalPositionCache(function(col) { return bodyCellTopInners.eq(col); }); function colContentLeft(col) { return colContentPositions.left(col); } function colContentRight(col) { return colContentPositions.right(col); } function dateCell(date) { return { row: Math.floor(dayDiff(date, t.visStart) / 7), col: dayOfWeekCol(date.getDay()) }; } function cellDate(cell) { return _cellDate(cell.row, cell.col); } function _cellDate(row, col) { return addDays(cloneDate(t.visStart), row*7 + col*dis+dit); // what about weekends in middle of week? } function indexDate(index) { return _cellDate(Math.floor(index/colCnt), index%colCnt); } function dayOfWeekCol(dayOfWeek) { return ((dayOfWeek - Math.max(firstDay, nwe) + colCnt) % colCnt) * dis + dit; } function allDayRow(i) { return bodyRows.eq(i); } function allDayBounds(i) { return { left: 0, right: viewWidth }; } } function BasicEventRenderer() { var t = this; // exports t.renderEvents = renderEvents; t.compileDaySegs = compileSegs; // for DayEventRenderer t.clearEvents = clearEvents; t.bindDaySeg = bindDaySeg; // imports DayEventRenderer.call(t); var opt = t.opt; var trigger = t.trigger; //var setOverflowHidden = t.setOverflowHidden; var isEventDraggable = t.isEventDraggable; var isEventResizable = t.isEventResizable; var reportEvents = t.reportEvents; var reportEventClear = t.reportEventClear; var eventElementHandlers = t.eventElementHandlers; var showEvents = t.showEvents; var hideEvents = t.hideEvents; var eventDrop = t.eventDrop; var getDaySegmentContainer = t.getDaySegmentContainer; var getHoverListener = t.getHoverListener; var renderDayOverlay = t.renderDayOverlay; var clearOverlays = t.clearOverlays; var getRowCnt = t.getRowCnt; var getColCnt = t.getColCnt; var renderDaySegs = t.renderDaySegs; var resizableDayEvent = t.resizableDayEvent; /* Rendering --------------------------------------------------------------------*/ function renderEvents(events, modifiedEventId) { reportEvents(events); renderDaySegs(compileSegs(events), modifiedEventId); } function clearEvents() { reportEventClear(); getDaySegmentContainer().empty(); } function compileSegs(events) { var rowCnt = getRowCnt(), colCnt = getColCnt(), d1 = cloneDate(t.visStart), d2 = addDays(cloneDate(d1), colCnt), visEventsEnds = $.map(events, exclEndDay), i, row, j, level, k, seg, segs=[]; for (i=0; i<rowCnt; i++) { row = stackSegs(sliceSegs(events, visEventsEnds, d1, d2)); for (j=0; j<row.length; j++) { level = row[j]; for (k=0; k<level.length; k++) { seg = level[k]; seg.row = i; seg.level = j; // not needed anymore segs.push(seg); } } addDays(d1, 7); addDays(d2, 7); } return segs; } function bindDaySeg(event, eventElement, seg) { if (isEventDraggable(event)) { draggableDayEvent(event, eventElement); } if (seg.isEnd && isEventResizable(event)) { resizableDayEvent(event, eventElement, seg); } eventElementHandlers(event, eventElement); // needs to be after, because resizableDayEvent might stopImmediatePropagation on click } /* Dragging ----------------------------------------------------------------------------*/ function draggableDayEvent(event, eventElement) { var hoverListener = getHoverListener(); var dayDelta; eventElement.draggable({ zIndex: 9, 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) { //setOverflowHidden(true); dayDelta = rowDelta*7 + colDelta * (opt('isRTL') ? -1 : 1); renderDayOverlay( addDays(cloneDate(event.start), dayDelta), addDays(exclEndDay(event), dayDelta) ); }else{ //setOverflowHidden(false); dayDelta = 0; } }, ev, 'drag'); }, stop: function(ev, ui) { hoverListener.stop(); clearOverlays(); trigger('eventDragStop', eventElement, event, ev, ui); if (dayDelta) { eventDrop(this, event, dayDelta, 0, event.allDay, ev, ui); }else{ eventElement.css('filter', ''); // clear IE opacity side-effects showEvents(event, eventElement); } //setOverflowHidden(false); } }); } } fcViews.agendaWeek = AgendaWeekView; function AgendaWeekView(element, calendar) { var t = this; // exports t.render = render; // imports AgendaView.call(t, element, calendar, 'agendaWeek'); var opt = t.opt; var renderAgenda = t.renderAgenda; var formatDates = calendar.formatDates; function render(date, delta) { if (delta) { addDays(date, delta * 7); } var start = addDays(cloneDate(date), -((date.getDay() - opt('firstDay') + 7) % 7)); var end = addDays(cloneDate(start), 7); var visStart = cloneDate(start); var visEnd = cloneDate(end); var weekends = opt('weekends'); if (!weekends) { skipWeekend(visStart); skipWeekend(visEnd, -1, true); } t.title = formatDates( visStart, addDays(cloneDate(visEnd), -1), opt('titleFormat') ); t.start = start; t.end = end; t.visStart = visStart; t.visEnd = visEnd; renderAgenda(weekends ? 7 : 5); } } fcViews.agendaDay = AgendaDayView; function AgendaDayView(element, calendar) { var t = this; // exports t.render = render; // imports AgendaView.call(t, element, calendar, 'agendaDay'); var opt = t.opt; var renderAgenda = t.renderAgenda; var formatDate = calendar.formatDate; function render(date, delta) { if (delta) { addDays(date, delta); if (!opt('weekends')) { skipWeekend(date, delta < 0 ? -1 : 1); } } var start = cloneDate(date, true); var end = addDays(cloneDate(start), 1); t.title = formatDate(date, opt('titleFormat')); t.start = t.visStart = start; t.end = t.visEnd = end; renderAgenda(1); } } setDefaults({ allDaySlot: true, allDayText: 'all-day', firstHour: 6, slotMinutes: 30, defaultEventMinutes: 120, axisFormat: 'h(:mm)tt', timeFormat: { agenda: 'h:mm{ - h:mm}' }, dragOpacity: { agenda: .5 }, minTime: 0, maxTime: 24 }); // 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.beforeHide = beforeHide; t.afterShow = afterShow; t.defaultEventEnd = defaultEventEnd; t.timePosition = timePosition; t.dayOfWeekCol = dayOfWeekCol; t.dateCell = dateCell; t.cellDate = cellDate; t.cellIsAllDay = cellIsAllDay; t.allDayRow = getAllDayRow; t.allDayBounds = allDayBounds; t.getHoverListener = function() { return hoverListener }; t.colContentLeft = colContentLeft; t.colContentRight = colContentRight; t.getDaySegmentContainer = function() { return daySegmentContainer }; t.getSlotSegmentContainer = function() { return slotSegmentContainer }; t.getMinMinute = function() { return minMinute }; t.getMaxMinute = function() { return maxMinute }; t.getBodyContent = function() { return slotContent }; // !!?? t.getRowCnt = function() { return 1 }; t.getColCnt = function() { return colCnt }; t.getColWidth = function() { return colWidth }; t.getSlotHeight = function() { return slotHeight }; 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 clearEvents = t.clearEvents; 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 formatDate = calendar.formatDate; // locals var dayTable; var dayHead; var dayHeadCells; var dayBody; var dayBodyCells; var dayBodyCellInners; var dayBodyFirstCell; var dayBodyFirstCellStretcher; var slotLayer; var daySegmentContainer; var allDayTable; var allDayRow; var slotScroller; var slotContent; var slotSegmentContainer; var slotTable; var slotTableFirstInner; var axisFirstCells; var gutterCells; var selectionHelper; var viewWidth; var viewHeight; var axisWidth; var colWidth; var gutterWidth; var slotHeight; // TODO: what if slotHeight changes? (see issue 650) var savedScrollTop; var colCnt; var slotCnt; var coordinateGrid; var hoverListener; var colContentPositions; var slotTopCache = {}; var tm; var firstDay; var nwe; // no weekends (int) var rtl, dis, dit; // day index sign / translate var minMinute, maxMinute; var colFormat; /* Rendering -----------------------------------------------------------------------------*/ disableTextSelection(element.addClass('fc-agenda')); function renderAgenda(c) { colCnt = c; updateOptions(); if (!dayTable) { buildSkeleton(); }else{ clearEvents(); } updateCells(); } function updateOptions() { tm = opt('theme') ? 'ui' : 'fc'; nwe = opt('weekends') ? 0 : 1; firstDay = opt('firstDay'); if (rtl = opt('isRTL')) { dis = -1; dit = colCnt - 1; }else{ dis = 1; dit = 0; } minMinute = parseTime(opt('minTime')); maxMinute = parseTime(opt('maxTime')); colFormat = opt('columnFormat'); } function buildSkeleton() { var headerClass = tm + "-widget-header"; var contentClass = tm + "-widget-content"; var s; var i; var d; var maxd; var minutes; var slotNormal = opt('slotMinutes') % 15 == 0; s = "<table style='width:100%' class='fc-agenda-days fc-border-separate' cellspacing='0'>" + "<thead>" + "<tr>" + "<th class='fc-agenda-axis " + headerClass + "'>&nbsp;</th>"; for (i=0; i<colCnt; i++) { s += "<th class='fc- fc-col" + i + ' ' + headerClass + "'/>"; // fc- needed for setDayID } s += "<th class='fc-agenda-gutter " + headerClass + "'>&nbsp;</th>" + "</tr>" + "</thead>" + "<tbody>" + "<tr>" + "<th class='fc-agenda-axis " + headerClass + "'>&nbsp;</th>"; for (i=0; i<colCnt; i++) { s += "<td class='fc- fc-col" + i + ' ' + contentClass + "'>" + // fc- needed for setDayID "<div>" + "<div class='fc-day-content'>" + "<div style='position:relative'>&nbsp;</div>" + "</div>" + "</div>" + "</td>"; } s += "<td class='fc-agenda-gutter " + contentClass + "'>&nbsp;</td>" + "</tr>" + "</tbody>" + "</table>"; dayTable = $(s).appendTo(element); dayHead = dayTable.find('thead'); dayHeadCells = dayHead.find('th').slice(1, -1); dayBody = dayTable.find('tbody'); dayBodyCells = dayBody.find('td').slice(0, -1); dayBodyCellInners = dayBodyCells.find('div.fc-day-content div'); dayBodyFirstCell = dayBodyCells.eq(0); dayBodyFirstCellStretcher = dayBodyFirstCell.find('> div'); markFirstLast(dayHead.add(dayHead.find('tr'))); markFirstLast(dayBody.add(dayBody.find('tr'))); axisFirstCells = dayHead.find('th:first'); gutterCells = dayTable.find('.fc-agenda-gutter'); slotLayer = $("<div style='position:absolute;z-index:2;left:0;width:100%'/>") .appendTo(element); if (opt('allDaySlot')) { daySegmentContainer = $("<div 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('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')); axisFirstCells = axisFirstCells.add(allDayTable.find('th:first')); gutterCells = gutterCells.add(allDayTable.find('th.fc-agenda-gutter')); 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); slotContent = $("<div style='position:relative;width:100%;overflow:hidden'/>") .appendTo(slotScroller); slotSegmentContainer = $("<div style='position:absolute;z-index:8;top:0;left:0'/>") .appendTo(slotContent); s = "<table class='fc-agenda-slots' style='width:100%' cellspacing='0'>" + "<tbody>"; d = zeroDate(); maxd = addMinutes(cloneDate(d), maxMinute); addMinutes(d, minMinute); slotCnt = 0; for (i=0; d < maxd; i++) { minutes = d.getMinutes(); s += "<tr class='fc-slot" + i + ' ' + (!minutes ? '' : 'fc-minor') + "'>" + "<th class='fc-agenda-axis " + headerClass + "'>" + ((!slotNormal || !minutes) ? formatDate(d, opt('axisFormat')) : '&nbsp;') + "</th>" + "<td class='" + contentClass + "'>" + "<div style='position:relative'>&nbsp;</div>" + "</td>" + "</tr>"; addMinutes(d, opt('slotMinutes')); slotCnt++; } s += "</tbody>" + "</table>"; slotTable = $(s).appendTo(slotContent); slotTableFirstInner = slotTable.find('div:first'); slotBind(slotTable.find('td')); axisFirstCells = axisFirstCells.add(slotTable.find('th:first')); } function updateCells() { var i; var headCell; var bodyCell; var date; var today = clearTime(new Date()); for (i=0; i<colCnt; i++) { date = colDate(i); headCell = dayHeadCells.eq(i); headCell.html(formatDate(date, colFormat)); bodyCell = dayBodyCells.eq(i); if (+date == +today) { bodyCell.addClass(tm + '-state-highlight fc-today'); }else{ bodyCell.removeClass(tm + '-state-highlight fc-today'); } setDayID(headCell.add(bodyCell), date); } } function setHeight(height, dateChanged) { 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); slotHeight = slotTableFirstInner.height() + 1; // +1 for border if (dateChanged) { resetScroll(); } } function setWidth(width) { viewWidth = width; colContentPositions.clear(); axisWidth = 0; setOuterWidth( axisFirstCells .width('') .each(function(i, _cell) { axisWidth = Math.max(axisWidth, $(_cell).outerWidth()); }), axisWidth ); var slotTableWidth = slotScroller[0].clientWidth; // needs to be done after axisWidth (for IE7) //slotTable.width(slotTableWidth); 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); } function resetScroll() { var d0 = zeroDate(); var scrollDate = cloneDate(d0); scrollDate.setHours(opt('firstHour')); var top = timePosition(d0, scrollDate) + 1; // +1 for the border function scroll() { slotScroller.scrollTop(top); } scroll(); setTimeout(scroll, 0); // overrides any previous scroll state made by the browser } function beforeHide() { savedScrollTop = slotScroller.scrollTop(); } function afterShow() { slotScroller.scrollTop(savedScrollTop); } /* 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 = colDate(col); var rowMatch = this.parentNode.className.match(/fc-slot(\d+)/); // TODO: maybe use data if (rowMatch) { var mins = parseInt(rowMatch[1]) * opt('slotMinutes'); var hours = Math.floor(mins/60); date.setHours(hours); date.setMinutes(mins%60 + minMinute); trigger('dayClick', dayBodyCells[col], date, false, ev); }else{ trigger('dayClick', dayBodyCells[col], date, true, ev); } } } /* Semi-transparent Overlay Helpers -----------------------------------------------------*/ function renderDayOverlay(startDate, endDate, refreshCoordinateGrid) { // endDate is exclusive if (refreshCoordinateGrid) { coordinateGrid.build(); } var visStart = cloneDate(t.visStart); var startCol, endCol; if (rtl) { startCol = dayDiff(endDate, visStart)*dis+dit+1; endCol = dayDiff(startDate, visStart)*dis+dit+1; }else{ startCol = dayDiff(startDate, visStart); endCol = dayDiff(endDate, visStart); } startCol = Math.max(0, startCol); endCol = Math.min(colCnt, endCol); if (startCol < endCol) { dayBind( renderCellOverlay(0, startCol, 0, endCol-1) ); } } 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) { var dayStart = cloneDate(t.visStart); var dayEnd = addDays(cloneDate(dayStart), 1); for (var i=0; i<colCnt; i++) { var stretchStart = new Date(Math.max(dayStart, overlayStart)); var stretchEnd = new Date(Math.min(dayEnd, overlayEnd)); if (stretchStart < stretchEnd) { var col = i*dis+dit; var rect = coordinateGrid.rect(0, col, 0, col, slotContent); // only use it for horizontal coords var top = timePosition(dayStart, stretchStart); var bottom = timePosition(dayStart, stretchEnd); rect.top = top; rect.height = bottom - top; slotBind( renderOverlay(rect, slotContent) ); } addDays(dayStart, 1); addDays(dayEnd, 1); } } /* 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 = slotContent.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; i++) { rows.push([ constrain(slotTableTop + slotHeight*i), constrain(slotTableTop + slotHeight*(i+1)) ]); } }); hoverListener = new HoverListener(coordinateGrid); colContentPositions = new HorizontalPositionCache(function(col) { return dayBodyCellInners.eq(col); }); function colContentLeft(col) { return colContentPositions.left(col); } function colContentRight(col) { return colContentPositions.right(col); } function dateCell(date) { // "cell" terminology is now confusing return { row: Math.floor(dayDiff(date, t.visStart) / 7), col: dayOfWeekCol(date.getDay()) }; } function cellDate(cell) { var d = colDate(cell.col); var slotIndex = cell.row; if (opt('allDaySlot')) { slotIndex--; } if (slotIndex >= 0) { addMinutes(d, minMinute + slotIndex * opt('slotMinutes')); } return d; } function colDate(col) { // returns dates with 00:00:00 return addDays(cloneDate(t.visStart), col*dis+dit); } function cellIsAllDay(cell) { return opt('allDaySlot') && !cell.row; } function dayOfWeekCol(dayOfWeek) { return ((dayOfWeek - Math.max(firstDay, nwe) + colCnt) % colCnt)*dis+dit; } // get the Y coordinate of the given time on the given day (both Date objects) function timePosition(day, time) { // both date objects. day holds 00:00 of current day day = cloneDate(day, true); if (time < addMinutes(cloneDate(day), minMinute)) { return 0; } if (time >= addMinutes(cloneDate(day), maxMinute)) { return slotTable.height(); } var slotMinutes = opt('slotMinutes'), minutes = time.getHours()*60 + time.getMinutes() - minMinute, slotI = Math.floor(minutes / slotMinutes), slotTop = slotTopCache[slotI]; if (slotTop === undefined) { slotTop = slotTopCache[slotI] = slotTable.find('tr:eq(' + slotI + ') td div')[0].offsetTop; //.position().top; // need this optimization??? } return Math.max(0, Math.round( slotTop - 1 + slotHeight * ((minutes % slotMinutes) / slotMinutes) )); } function allDayBounds() { return { left: axisWidth, right: viewWidth - gutterWidth } } function getAllDayRow(index) { return allDayRow; } function defaultEventEnd(event) { var start = cloneDate(event.start); if (event.allDay) { return start; } return addMinutes(start, opt('defaultEventMinutes')); } /* Selection ---------------------------------------------------------------------------------*/ function defaultSelectionEnd(startDate, allDay) { if (allDay) { return cloneDate(startDate); } return addMinutes(cloneDate(startDate), opt('slotMinutes')); } function renderSelection(startDate, endDate, allDay) { // only for all-day if (allDay) { if (opt('allDaySlot')) { renderDayOverlay(startDate, addDays(cloneDate(endDate), 1), true); } }else{ renderSlotSelection(startDate, endDate); } } function renderSlotSelection(startDate, endDate) { var helperOption = opt('selectHelper'); coordinateGrid.build(); if (helperOption) { var col = dayDiff(startDate, t.visStart) * dis + dit; if (col >= 0 && col < colCnt) { // only works when times are on same day var rect = coordinateGrid.rect(0, col, 0, col, slotContent); // only for horizontal coords var top = timePosition(startDate, startDate); var bottom = timePosition(startDate, endDate); 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'; rect.zIndex = 8; selectionHelper = $(helperRes) .css(rect) .appendTo(slotContent); } }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); slotContent.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 && !cellIsAllDay(cell)) { var d1 = cellDate(origCell); var d2 = cellDate(cell); dates = [ d1, addMinutes(cloneDate(d1), opt('slotMinutes')), d2, addMinutes(cloneDate(d2), opt('slotMinutes')) ].sort(cmp); 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], false, ev); } reportSelection(dates[0], dates[3], false, ev); } }); } } function reportDayClick(date, allDay, ev) { trigger('dayClick', dayBodyCells[dayOfWeekCol(date.getDay())], date, allDay, ev); } /* External Dragging --------------------------------------------------------------------------------*/ function dragStart(_dragElement, ev, ui) { hoverListener.start(function(cell) { clearOverlays(); if (cell) { if (cellIsAllDay(cell)) { renderCellOverlay(cell.row, cell.col, cell.row, cell.col); }else{ var d1 = cellDate(cell); var d2 = addMinutes(cloneDate(d1), opt('defaultEventMinutes')); renderSlotOverlay(d1, d2); } } }, ev); } function dragStop(_dragElement, ev, ui) { var cell = hoverListener.stop(); clearOverlays(); if (cell) { trigger('drop', _dragElement, cellDate(cell), cellIsAllDay(cell), ev, ui); } } } function AgendaEventRenderer() { var t = this; // exports t.renderEvents = renderEvents; t.compileDaySegs = compileDaySegs; // for DayEventRenderer t.clearEvents = clearEvents; t.slotSegHtml = slotSegHtml; t.bindDaySeg = bindDaySeg; // imports DayEventRenderer.call(t); var opt = t.opt; var trigger = t.trigger; //var setOverflowHidden = t.setOverflowHidden; var isEventDraggable = t.isEventDraggable; var isEventResizable = t.isEventResizable; var eventEnd = t.eventEnd; var reportEvents = t.reportEvents; var reportEventClear = t.reportEventClear; var eventElementHandlers = t.eventElementHandlers; var setHeight = t.setHeight; var getDaySegmentContainer = t.getDaySegmentContainer; var getSlotSegmentContainer = t.getSlotSegmentContainer; var getHoverListener = t.getHoverListener; var getMaxMinute = t.getMaxMinute; var getMinMinute = t.getMinMinute; var timePosition = t.timePosition; var colContentLeft = t.colContentLeft; var colContentRight = t.colContentRight; var renderDaySegs = t.renderDaySegs; var resizableDayEvent = t.resizableDayEvent; // TODO: streamline binding architecture var getColCnt = t.getColCnt; var getColWidth = t.getColWidth; var getSlotHeight = t.getSlotHeight; var getBodyContent = t.getBodyContent; 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 calendar = t.calendar; var formatDate = calendar.formatDate; var formatDates = calendar.formatDates; /* Rendering ----------------------------------------------------------------------------*/ function renderEvents(events, modifiedEventId) { reportEvents(events); 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')) { renderDaySegs(compileDaySegs(dayEvents), modifiedEventId); setHeight(); // no params means set to viewHeight } renderSlotSegs(compileSlotSegs(slotEvents), modifiedEventId); } function clearEvents() { reportEventClear(); getDaySegmentContainer().empty(); getSlotSegmentContainer().empty(); } function compileDaySegs(events) { var levels = stackSegs(sliceSegs(events, $.map(events, exclEndDay), t.visStart, t.visEnd)), i, levelCnt=levels.length, level, j, seg, segs=[]; for (i=0; i<levelCnt; i++) { level = levels[i]; for (j=0; j<level.length; j++) { seg = level[j]; seg.row = 0; seg.level = i; // not needed anymore segs.push(seg); } } return segs; } function compileSlotSegs(events) { var colCnt = getColCnt(), minMinute = getMinMinute(), maxMinute = getMaxMinute(), d = addMinutes(cloneDate(t.visStart), minMinute), visEventEnds = $.map(events, slotEventEnd), i, col, j, level, k, seg, segs=[]; for (i=0; i<colCnt; i++) { col = stackSegs(sliceSegs(events, visEventEnds, d, addMinutes(cloneDate(d), maxMinute-minMinute))); countForwardSegs(col); for (j=0; j<col.length; j++) { level = col[j]; for (k=0; k<level.length; k++) { seg = level[k]; seg.col = i; seg.level = j; segs.push(seg); } } addDays(d, 1, true); } return segs; } function slotEventEnd(event) { if (event.end) { return cloneDate(event.end); }else{ return addMinutes(cloneDate(event.start), opt('defaultEventMinutes')); } } // renders events in the 'time slots' at the bottom function renderSlotSegs(segs, modifiedEventId) { var i, segCnt=segs.length, seg, event, classes, top, bottom, colI, levelI, forward, leftmost, availWidth, outerWidth, left, html='', eventElements, eventElement, triggerRes, vsideCache={}, hsideCache={}, key, val, contentElement, height, slotSegmentContainer = getSlotSegmentContainer(), rtl, dis, dit, colCnt = getColCnt(); if (rtl = opt('isRTL')) { dis = -1; dit = colCnt - 1; }else{ dis = 1; dit = 0; } // calculate position/dimensions, create html for (i=0; i<segCnt; i++) { seg = segs[i]; event = seg.event; top = timePosition(seg.start, seg.start); bottom = timePosition(seg.start, seg.end); colI = seg.col; levelI = seg.level; forward = seg.forward || 0; leftmost = colContentLeft(colI*dis + dit); availWidth = colContentRight(colI*dis + dit) - leftmost; availWidth = Math.min(availWidth-6, availWidth*.95); // TODO: move this to CSS if (levelI) { // indented and thin outerWidth = availWidth / (levelI + forward + 1); }else{ if (forward) { // moderately wide, aligned left still outerWidth = ((availWidth / (forward + 1)) - (12/2)) * 2; // 12 is the predicted width of resizer = }else{ // can be entire width, aligned left outerWidth = availWidth; } } left = leftmost + // leftmost possible (availWidth / (levelI + forward + 1) * levelI) // indentation * dis + (rtl ? availWidth - outerWidth : 0); // rtl seg.top = top; seg.left = left; seg.outerWidth = outerWidth; 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) { val = vsideCache[key = seg.key = cssKey(eventElement[0])]; seg.vsides = val === undefined ? (vsideCache[key] = vsides(eventElement, true)) : val; val = hsideCache[key]; seg.hsides = val === undefined ? (hsideCache[key] = hsides(eventElement, true)) : val; contentElement = eventElement.find('div.fc-event-content'); if (contentElement.length) { seg.contentTop = contentElement[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 header 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 skinCssAttr = (skinCss ? " style='" + skinCss + "'" : ''); var classes = ['fc-event', 'fc-event-skin', 'fc-event-vert']; if (isEventDraggable(event)) { classes.push('fc-event-draggable'); } if (seg.isStart) { classes.push('fc-corner-top'); } if (seg.isEnd) { classes.push('fc-corner-bottom'); } 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;z-index:8;top:" + seg.top + "px;left:" + seg.left + "px;" + skinCss + "'" + ">" + "<div class='fc-event-inner fc-event-skin'" + skinCssAttr + ">" + "<div class='fc-event-head fc-event-skin'" + skinCssAttr + ">" + "<div class='fc-event-time'>" + htmlEscape(formatDates(event.start, event.end, opt('timeFormat'))) + "</div>" + "</div>" + "<div class='fc-event-content'>" + "<div class='fc-event-title'>" + htmlEscape(event.title) + "</div>" + "</div>" + "<div class='fc-event-bg'></div>" + "</div>"; // close inner if (seg.isEnd && isEventResizable(event)) { html += "<div class='ui-resizable-handle ui-resizable-s'>=</div>"; } html += "</" + (url ? "a" : "div") + ">"; return html; } function bindDaySeg(event, eventElement, seg) { if (isEventDraggable(event)) { draggableDayEvent(event, eventElement, seg.isStart); } if (seg.isEnd && isEventResizable(event)) { resizableDayEvent(event, eventElement, seg); } eventElementHandlers(event, eventElement); // needs to be after, because resizableDayEvent might stopImmediatePropagation on click } 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 function draggableDayEvent(event, eventElement, isStart) { var origWidth; var revert; var allDay=true; var dayDelta; var dis = opt('isRTL') ? -1 : 1; var hoverListener = getHoverListener(); var colWidth = getColWidth(); var slotHeight = getSlotHeight(); var minMinute = getMinMinute(); eventElement.draggable({ zIndex: 9, 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, rowDelta, colDelta) { clearOverlays(); if (cell) { //setOverflowHidden(true); revert = false; dayDelta = colDelta * dis; if (!cell.row) { // on full-days renderDayOverlay( addDays(cloneDate(event.start), dayDelta), addDays(exclEndDay(event), 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, slotHeight * Math.round( (event.end ? ((event.end - event.start) / MINUTE_MS) : opt('defaultEventMinutes')) / opt('slotMinutes') ) ); eventElement.draggable('option', 'grid', [colWidth, 1]); allDay = false; } }else{ revert = true; } } revert = revert || (allDay && !dayDelta); }else{ resetElement(); //setOverflowHidden(false); 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 minuteDelta = 0; if (!allDay) { minuteDelta = Math.round((eventElement.offset().top - getBodyContent().offset().top) / slotHeight) * opt('slotMinutes') + minMinute - (event.start.getHours() * 60 + event.start.getMinutes()); } eventDrop(this, event, dayDelta, minuteDelta, allDay, ev, ui); } //setOverflowHidden(false); } }); 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 origPosition; var allDay=false; var dayDelta; var minuteDelta; var prevMinuteDelta; var dis = opt('isRTL') ? -1 : 1; var hoverListener = getHoverListener(); var colCnt = getColCnt(); var colWidth = getColWidth(); var slotHeight = getSlotHeight(); eventElement.draggable({ zIndex: 9, scroll: false, grid: [colWidth, slotHeight], axis: colCnt==1 ? 'y' : false, opacity: opt('dragOpacity'), revertDuration: opt('dragRevertDuration'), start: function(ev, ui) { trigger('eventDragStart', eventElement, event, ev, ui); hideEvents(event, eventElement); origPosition = eventElement.position(); minuteDelta = prevMinuteDelta = 0; hoverListener.start(function(cell, origCell, rowDelta, colDelta) { eventElement.draggable('option', 'revert', !cell); clearOverlays(); if (cell) { dayDelta = colDelta * dis; if (opt('allDaySlot') && !cell.row) { // over full days if (!allDay) { // convert to temporary all-day event allDay = true; timeElement.hide(); eventElement.draggable('option', 'grid', null); } renderDayOverlay( addDays(cloneDate(event.start), dayDelta), addDays(exclEndDay(event), dayDelta) ); }else{ // on slots resetElement(); } } }, ev, 'drag'); }, drag: function(ev, ui) { minuteDelta = Math.round((ui.position.top - origPosition.top) / slotHeight) * opt('slotMinutes'); if (minuteDelta != prevMinuteDelta) { if (!allDay) { updateTimeText(minuteDelta); } prevMinuteDelta = minuteDelta; } }, stop: function(ev, ui) { var cell = hoverListener.stop(); clearOverlays(); trigger('eventDragStop', eventElement, event, ev, ui); if (cell && (dayDelta || minuteDelta || allDay)) { // changed! eventDrop(this, event, dayDelta, allDay ? 0 : minuteDelta, allDay, ev, ui); }else{ // either no change or out-of-bounds (draggable has already reverted) resetElement(); eventElement.css('filter', ''); // clear IE opacity side-effects eventElement.css(origPosition); // sometimes fast drags make event revert to wrong position updateTimeText(0); showEvents(event, eventElement); } } }); function updateTimeText(minuteDelta) { var newStart = addMinutes(cloneDate(event.start), minuteDelta); var newEnd; if (event.end) { newEnd = addMinutes(cloneDate(event.end), minuteDelta); } timeElement.text(formatDates(newStart, newEnd, opt('timeFormat'))); } function resetElement() { // convert back to original slot-event if (allDay) { timeElement.css('display', ''); // show() was causing display=inline eventElement.draggable('option', 'grid', [colWidth, slotHeight]); allDay = false; } } } /* Resizing --------------------------------------------------------------------------------------*/ function resizableSlotEvent(event, eventElement, timeElement) { var slotDelta, prevSlotDelta; var slotHeight = getSlotHeight(); eventElement.resizable({ handles: { s: 'div.ui-resizable-s' }, grid: slotHeight, start: function(ev, ui) { slotDelta = prevSlotDelta = 0; hideEvents(event, eventElement); eventElement.css('z-index', 9); trigger('eventResizeStart', this, event, ev, ui); }, resize: function(ev, ui) { // don't rely on ui.size.height, doesn't take grid into account slotDelta = Math.round((Math.max(slotHeight, eventElement.height()) - ui.originalSize.height) / slotHeight); if (slotDelta != prevSlotDelta) { timeElement.text( formatDates( event.start, (!slotDelta && !event.end) ? null : // no change, so don't display time range addMinutes(eventEnd(event), opt('slotMinutes')*slotDelta), opt('timeFormat') ) ); prevSlotDelta = slotDelta; } }, stop: function(ev, ui) { trigger('eventResizeStop', this, event, ev, ui); if (slotDelta) { eventResize(this, event, 0, opt('slotMinutes')*slotDelta, ev, ui); }else{ eventElement.css('z-index', 8); showEvents(event, eventElement); // BUG: if event was really short, need to put title back in span } } }); } } function countForwardSegs(levels) { var i, j, k, level, segForward, segBack; for (i=levels.length-1; i>0; i--) { level = levels[i]; for (j=0; j<level.length; j++) { segForward = level[j]; for (k=0; k<levels[i-1].length; k++) { segBack = levels[i-1][k]; if (segsCollide(segForward, segBack)) { segBack.forward = Math.max(segBack.forward||0, (segForward.forward||0)+1); } } } } } 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.setOverflowHidden = setOverflowHidden; t.isEventDraggable = isEventDraggable; t.isEventResizable = isEventResizable; t.reportEvents = reportEvents; t.eventEnd = eventEnd; t.reportEventElement = reportEventElement; t.reportEventClear = reportEventClear; t.eventElementHandlers = eventElementHandlers; t.showEvents = showEvents; t.hideEvents = hideEvents; t.eventDrop = eventDrop; t.eventResize = eventResize; // t.title // t.start, t.end // t.visStart, t.visEnd // imports var defaultEventEnd = t.defaultEventEnd; var normalizeEvent = calendar.normalizeEvent; // in EventManager var reportEventChange = calendar.reportEventChange; // locals var eventsByID = {}; var eventElements = []; var eventElementsByID = {}; var options = calendar.options; function opt(name, viewNameOverride) { var v = options[name]; if (typeof v == 'object') { 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]) ); } /* function setOverflowHidden(bool) { element.css('overflow', bool ? 'hidden' : ''); } */ function isEventDraggable(event) { return isEventEditable(event) && !opt('disableDragging'); } function isEventResizable(event) { // but also need to make sure the seg.isEnd == true return isEventEditable(event) && !opt('disableResizing'); } function isEventEditable(event) { return firstDefined(event.editable, (event.source || {}).editable, opt('editable')); } /* Event Data ------------------------------------------------------------------------------*/ // report when view receives new events function reportEvents(events) { // events are already normalized at this point eventsByID = {}; var i, len=events.length, event; for (i=0; i<len; i++) { event = events[i]; if (eventsByID[event._id]) { eventsByID[event._id].push(event); }else{ eventsByID[event._id] = [event]; } } } // returns a Date object for an event's end function eventEnd(event) { return event.end ? cloneDate(event.end) : defaultEventEnd(event); } /* Event Elements ------------------------------------------------------------------------------*/ // report when view creates an element for an event function reportEventElement(event, element) { eventElements.push(element); if (eventElementsByID[event._id]) { eventElementsByID[event._id].push(element); }else{ eventElementsByID[event._id] = [element]; } } function reportEventClear() { eventElements = []; eventElementsByID = {}; } // 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) { 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(e, event, dayDelta, minuteDelta, allDay, ev, ui) { var oldAllDay = event.allDay; var eventId = event._id; moveEvents(eventsByID[eventId], dayDelta, minuteDelta, allDay); trigger( 'eventDrop', e, event, dayDelta, minuteDelta, allDay, function() { // TODO: investigate cases where this inverse technique might not work moveEvents(eventsByID[eventId], -dayDelta, -minuteDelta, oldAllDay); reportEventChange(eventId); }, ev, ui ); reportEventChange(eventId); } function eventResize(e, event, dayDelta, minuteDelta, ev, ui) { var eventId = event._id; elongateEvents(eventsByID[eventId], dayDelta, minuteDelta); trigger( 'eventResize', e, event, dayDelta, minuteDelta, function() { // TODO: investigate cases where this inverse technique might not work elongateEvents(eventsByID[eventId], -dayDelta, -minuteDelta); reportEventChange(eventId); }, ev, ui ); reportEventChange(eventId); } /* Event Modification Math ---------------------------------------------------------------------------------*/ function moveEvents(events, dayDelta, minuteDelta, allDay) { minuteDelta = minuteDelta || 0; for (var e, len=events.length, i=0; i<len; i++) { e = events[i]; if (allDay !== undefined) { e.allDay = allDay; } addMinutes(addDays(e.start, dayDelta, true), minuteDelta); if (e.end) { e.end = addMinutes(addDays(e.end, dayDelta, true), minuteDelta); } normalizeEvent(e, options); } } function elongateEvents(events, dayDelta, minuteDelta) { minuteDelta = minuteDelta || 0; for (var e, len=events.length, i=0; i<len; i++) { e = events[i]; e.end = addMinutes(addDays(eventEnd(e), dayDelta, true), minuteDelta); normalizeEvent(e, options); } } } function DayEventRenderer() { var t = this; // exports t.renderDaySegs = renderDaySegs; t.resizableDayEvent = resizableDayEvent; // imports var opt = t.opt; var trigger = t.trigger; var isEventDraggable = t.isEventDraggable; var isEventResizable = t.isEventResizable; var eventEnd = t.eventEnd; var reportEventElement = t.reportEventElement; var showEvents = t.showEvents; var hideEvents = t.hideEvents; var eventResize = t.eventResize; var getRowCnt = t.getRowCnt; var getColCnt = t.getColCnt; var getColWidth = t.getColWidth; var allDayRow = t.allDayRow; var allDayBounds = t.allDayBounds; var colContentLeft = t.colContentLeft; var colContentRight = t.colContentRight; var dayOfWeekCol = t.dayOfWeekCol; var dateCell = t.dateCell; var compileDaySegs = t.compileDaySegs; var getDaySegmentContainer = t.getDaySegmentContainer; var bindDaySeg = t.bindDaySeg; //TODO: streamline this var formatDates = t.calendar.formatDates; var renderDayOverlay = t.renderDayOverlay; var clearOverlays = t.clearOverlays; var clearSelection = t.clearSelection; /* Rendering -----------------------------------------------------------------------------*/ function renderDaySegs(segs, modifiedEventId) { var segmentContainer = getDaySegmentContainer(); var rowDivs; var rowCnt = getRowCnt(); var colCnt = getColCnt(); var i = 0; var rowI; var levelI; var colHeights; var j; var segCnt = segs.length; var seg; var top; var k; segmentContainer[0].innerHTML = daySegHTML(segs); // faster than .html() daySegElementResolve(segs, segmentContainer.children()); daySegElementReport(segs); daySegHandlers(segs, segmentContainer, modifiedEventId); daySegCalcHSides(segs); daySegSetWidths(segs); daySegCalcHeights(segs); rowDivs = getRowDivs(); // set row heights, calculate event tops (in relation to row top) for (rowI=0; rowI<rowCnt; rowI++) { levelI = 0; colHeights = []; for (j=0; j<colCnt; j++) { colHeights[j] = 0; } while (i<segCnt && (seg = segs[i]).row == rowI) { // loop through segs in a row top = arrayMax(colHeights.slice(seg.startCol, seg.endCol)); seg.top = top; top += seg.outerHeight; for (k=seg.startCol; k<seg.endCol; k++) { colHeights[k] = top; } i++; } rowDivs[rowI].height(arrayMax(colHeights)); } daySegSetTops(segs, getRowTops(rowDivs)); } function renderTempDaySegs(segs, adjustRow, adjustTop) { var tempContainer = $("<div/>"); var elements; var segmentContainer = getDaySegmentContainer(); var i; var segCnt = segs.length; var element; tempContainer[0].innerHTML = daySegHTML(segs); // faster than .html() elements = tempContainer.children(); segmentContainer.append(elements); daySegElementResolve(segs, elements); daySegCalcHSides(segs); daySegSetWidths(segs); daySegCalcHeights(segs); daySegSetTops(segs, getRowTops(getRowDivs())); elements = []; for (i=0; i<segCnt; i++) { element = segs[i].element; if (element) { if (segs[i].row === adjustRow) { element.css('top', adjustTop); } elements.push(element[0]); } } return $(elements); } function daySegHTML(segs) { // also sets seg.left and seg.outerWidth var rtl = opt('isRTL'); var i; var segCnt=segs.length; var seg; var event; var url; var classes; var bounds = allDayBounds(); var minLeft = bounds.left; var maxLeft = bounds.right; var leftCol; var rightCol; var left; var right; var skinCss; var html = ''; // calculate desired position/dimensions, create html for (i=0; i<segCnt; i++) { seg = segs[i]; event = seg.event; classes = ['fc-event', 'fc-event-skin', 'fc-event-hori']; if (isEventDraggable(event)) { classes.push('fc-event-draggable'); } if (rtl) { if (seg.isStart) { classes.push('fc-corner-right'); } if (seg.isEnd) { classes.push('fc-corner-left'); } leftCol = dayOfWeekCol(seg.end.getDay()-1); rightCol = dayOfWeekCol(seg.start.getDay()); left = seg.isEnd ? colContentLeft(leftCol) : minLeft; right = seg.isStart ? colContentRight(rightCol) : maxLeft; }else{ if (seg.isStart) { classes.push('fc-corner-left'); } if (seg.isEnd) { classes.push('fc-corner-right'); } leftCol = dayOfWeekCol(seg.start.getDay()); rightCol = dayOfWeekCol(seg.end.getDay()-1); left = seg.isStart ? colContentLeft(leftCol) : minLeft; right = seg.isEnd ? colContentRight(rightCol) : maxLeft; } classes = classes.concat(event.className); if (event.source) { classes = classes.concat(event.source.className || []); } url = event.url; skinCss = getSkinCss(event, opt); if (url) { html += "<a href='" + htmlEscape(url) + "'"; }else{ html += "<div"; } html += " class='" + classes.join(' ') + "'" + " style='position:absolute;z-index:8;left:"+left+"px;" + skinCss + "'" + ">" + "<div" + " class='fc-event-inner fc-event-skin'" + (skinCss ? " style='" + skinCss + "'" : '') + ">"; if (!event.allDay && seg.isStart) { html += "<span class='fc-event-time'>" + htmlEscape(formatDates(event.start, event.end, opt('timeFormat'))) + "</span>"; } html += "<span class='fc-event-title'>" + htmlEscape(event.title) + "</span>" + "</div>"; if (seg.isEnd && isEventResizable(event)) { html += "<div class='ui-resizable-handle ui-resizable-" + (rtl ? 'w' : 'e') + "'>" + "&nbsp;&nbsp;&nbsp;" + // makes hit area a lot better for IE6/7 "</div>"; } html += "</" + (url ? "a" : "div" ) + ">"; seg.left = left; seg.outerWidth = right - left; seg.startCol = leftCol; seg.endCol = rightCol + 1; // needs to be exclusive } return html; } function daySegElementResolve(segs, elements) { // sets seg.element var i; var segCnt = segs.length; var seg; var event; var element; var triggerRes; for (i=0; i<segCnt; i++) { seg = segs[i]; event = seg.event; element = $(elements[i]); // faster than .eq() triggerRes = trigger('eventRender', event, event, element); if (triggerRes === false) { element.remove(); }else{ if (triggerRes && triggerRes !== true) { triggerRes = $(triggerRes) .css({ position: 'absolute', left: seg.left }); element.replaceWith(triggerRes); element = triggerRes; } seg.element = element; } } } function daySegElementReport(segs) { var i; var segCnt = segs.length; var seg; var element; for (i=0; i<segCnt; i++) { seg = segs[i]; element = seg.element; if (element) { reportEventElement(seg.event, element); } } } function daySegHandlers(segs, segmentContainer, modifiedEventId) { var i; var segCnt = segs.length; var seg; var element; var event; // retrieve elements, run through eventRender callback, bind handlers for (i=0; i<segCnt; i++) { seg = segs[i]; element = seg.element; if (element) { event = seg.event; if (event._id === modifiedEventId) { bindDaySeg(event, element, seg); }else{ element[0]._fci = i; // for lazySegBind } } } lazySegBind(segmentContainer, segs, bindDaySeg); } function daySegCalcHSides(segs) { // also sets seg.key var i; var segCnt = segs.length; var seg; var element; var key, val; var hsideCache = {}; // record event horizontal sides for (i=0; i<segCnt; i++) { seg = segs[i]; element = seg.element; if (element) { key = seg.key = cssKey(element[0]); val = hsideCache[key]; if (val === undefined) { val = hsideCache[key] = hsides(element, true); } seg.hsides = val; } } } function daySegSetWidths(segs) { var i; var segCnt = segs.length; var seg; var element; for (i=0; i<segCnt; i++) { seg = segs[i]; element = seg.element; if (element) { element[0].style.width = Math.max(0, seg.outerWidth - seg.hsides) + 'px'; } } } function daySegCalcHeights(segs) { var i; var segCnt = segs.length; var seg; var element; var key, val; var vmarginCache = {}; // record event heights for (i=0; i<segCnt; i++) { seg = segs[i]; element = seg.element; if (element) { key = seg.key; // created in daySegCalcHSides val = vmarginCache[key]; if (val === undefined) { val = vmarginCache[key] = vmargins(element); } seg.outerHeight = element[0].offsetHeight + val; } } } function getRowDivs() { var i; var rowCnt = getRowCnt(); var rowDivs = []; for (i=0; i<rowCnt; i++) { rowDivs[i] = allDayRow(i) .find('td:first div.fc-day-content > div'); // optimal selector? } return rowDivs; } function getRowTops(rowDivs) { var i; var rowCnt = rowDivs.length; var tops = []; for (i=0; i<rowCnt; i++) { tops[i] = rowDivs[i][0].offsetTop; // !!?? but this means the element needs position:relative if in a table cell!!!! } return tops; } function daySegSetTops(segs, rowTops) { // also triggers eventAfterRender var i; var segCnt = segs.length; var seg; var element; var event; for (i=0; i<segCnt; i++) { seg = segs[i]; element = seg.element; if (element) { element[0].style.top = rowTops[seg.row] + (seg.top||0) + 'px'; event = seg.event; trigger('eventAfterRender', event, event, element); } } } /* Resizing -----------------------------------------------------------------------------------*/ function resizableDayEvent(event, element, seg) { var rtl = opt('isRTL'); var direction = rtl ? 'w' : 'e'; var handle = element.find('div.ui-resizable-' + direction); 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 = t.getHoverListener(); var rowCnt = getRowCnt(); var colCnt = getColCnt(); var dis = rtl ? -1 : 1; var dit = rtl ? colCnt-1 : 0; var elementTop = element.css('top'); var dayDelta; var helpers; var eventCopy = $.extend({}, event); var minCell = dateCell(event.start); clearSelection(); $('body') .css('cursor', direction + '-resize') .one('mouseup', mouseup); trigger('eventResizeStart', this, event, ev); hoverListener.start(function(cell, origCell) { if (cell) { var r = Math.max(minCell.row, cell.row); var c = cell.col; if (rowCnt == 1) { r = 0; // hack for all-day area in agenda views } if (r == minCell.row) { if (rtl) { c = Math.min(minCell.col, c); }else{ c = Math.max(minCell.col, c); } } dayDelta = (r*7 + c*dis+dit) - (origCell.row*7 + origCell.col*dis+dit); var newEnd = addDays(eventEnd(event), dayDelta, true); if (dayDelta) { eventCopy.end = newEnd; var oldHelpers = helpers; helpers = renderTempDaySegs(compileDaySegs([eventCopy]), seg.row, elementTop); helpers.find('*').css('cursor', direction + '-resize'); if (oldHelpers) { oldHelpers.remove(); } hideEvents(event); }else{ if (helpers) { showEvents(event); helpers.remove(); helpers = null; } } clearOverlays(); renderDayOverlay(event.start, addDays(cloneDate(newEnd), 1)); // coordinate grid already rebuild at hoverListener.start } }, ev); function mouseup(ev) { trigger('eventResizeStop', this, event, ev); $('body').css('cursor', ''); hoverListener.stop(); clearOverlays(); if (dayDelta) { eventResize(this, event, dayDelta, 0, 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); } }); } } //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 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')) { $(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(startDate, endDate, allDay) { unselect(); if (!endDate) { endDate = defaultSelectionEnd(startDate, allDay); } renderSelection(startDate, endDate, allDay); reportSelection(startDate, endDate, allDay); } function unselect(ev) { if (selected) { selected = false; clearSelection(); trigger('unselect', null, ev); } } function reportSelection(startDate, endDate, allDay, ev) { selected = true; trigger('select', null, startDate, endDate, allDay, ev); } function daySelectionMousedown(ev) { // not really a generic manager method, oh well var cellDate = t.cellDate; var cellIsAllDay = t.cellIsAllDay; 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 _mousedownElement = this; var dates; hoverListener.start(function(cell, origCell) { // TODO: maybe put cellDate/cellIsAllDay info in cell clearSelection(); if (cell && cellIsAllDay(cell)) { dates = [ cellDate(origCell), cellDate(cell) ].sort(cmp); renderSelection(dates[0], dates[1], true); }else{ dates = null; } }, ev); $(document).one('mouseup', function(ev) { hoverListener.stop(); if (dates) { if (+dates[0] == +dates[1]) { reportDayClick(dates[0], true, ev); } reportSelection(dates[0], dates[1], true, 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 (!newCell != !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 = {}; }; } })(jQuery);
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: 'full', ignore: [ 'dev', '.gitignore', '.gitattributes', 'README.md', '.mailmap' ], plugins : { 'about' : 1, 'a11yhelp' : 1, 'dialogadvtab' : 1, 'basicstyles' : 1, 'bidi' : 1, 'blockquote' : 1, 'clipboard' : 1, 'colorbutton' : 1, 'colordialog' : 1, 'templates' : 1, 'contextmenu' : 1, 'div' : 1, 'resize' : 1, 'toolbar' : 1, 'elementspath' : 1, 'enterkey' : 1, 'entities' : 1, 'filebrowser' : 1, 'find' : 1, 'flash' : 1, 'floatingspace' : 1, 'font' : 1, 'forms' : 1, 'format' : 1, 'horizontalrule' : 1, 'htmlwriter' : 1, 'iframe' : 1, 'wysiwygarea' : 1, 'image' : 1, 'indentblock' : 1, 'indentlist' : 1, 'smiley' : 1, 'justify' : 1, 'link' : 1, 'list' : 1, 'liststyle' : 1, 'magicline' : 1, 'maximize' : 1, 'newpage' : 1, 'pagebreak' : 1, 'pastetext' : 1, 'pastefromword' : 1, 'preview' : 1, 'print' : 1, 'removeformat' : 1, 'save' : 1, 'selectall' : 1, 'showblocks' : 1, 'showborders' : 1, 'sourcearea' : 1, 'specialchar' : 1, 'scayt' : 1, 'stylescombo' : 1, 'tab' : 1, 'table' : 1, 'tabletools' : 1, 'undo' : 1, 'wsc' : 1, 'dialog' : 1, 'dialogui' : 1, 'panelbutton' : 1, 'button' : 1, 'floatpanel' : 1, 'panel' : 1, 'menu' : 1, 'popup' : 1, 'fakeobjects' : 1, 'richcombo' : 1, 'listblock' : 1, 'indent' : 1, 'menubutton' : 1 }, languages : { 'af' : 1, 'sq' : 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, 'id' : 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, 'si' : 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.html or http://ckeditor.com/license */ CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; };
JavaScript
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */
JavaScript
/** * Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md 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', element: 'span', attributes: { 'class': 'marker' } }, { 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
/** * Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.dialog.add( 'myDialog', function( editor ) { return { title: 'My Dialog', minWidth: 400, minHeight: 200, contents: [ { id: 'tab1', label: 'First Tab', title: 'First Tab', elements: [ { id: 'input1', type: 'text', label: 'Text Field' }, { id: 'select1', type: 'select', label: 'Select Field', items: [ [ 'option1', 'value1' ], [ 'option2', 'value2' ] ] } ] }, { id: 'tab2', label: 'Second Tab', title: 'Second Tab', elements: [ { id: 'button1', type: 'button', label: 'Button Field' } ] } ] }; });
JavaScript
/** * Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ // Tool scripts for the sample pages. // This file can be ignored and is not required to make use of CKEditor. (function() { // Check for sample compliance. CKEDITOR.on( 'instanceReady', function( ev ) { var editor = ev.editor, meta = CKEDITOR.document.$.getElementsByName( 'ckeditor-sample-required-plugins' ), requires = meta.length ? CKEDITOR.dom.element.get( meta[ 0 ] ).getAttribute( 'content' ).split( ',' ) : [], missing = []; if ( requires.length ) { for ( var i = 0; i < requires.length; i++ ) { if ( !editor.plugins[ requires[ i ] ] ) missing.push( '<code>' + requires[ i ] + '</code>' ); } if ( missing.length ) { var warn = CKEDITOR.dom.element.createFromHtml( '<div class="warning">' + '<span>To fully experience this demo, the ' + missing.join( ', ' ) + ' plugin' + ( missing.length > 1 ? 's are' : ' is' ) + ' required.</span>' + '</div>' ); warn.insertBefore( editor.container ); } } }); })();
JavaScript