{I" class:ETI"BundledAsset;FI"logical_path;TI" type_station/application.js;TI" pathname;TI"_/Users/richardadams/github/type_station/app/assets/javascripts/type_station/application.js;FI"content_type;TI"application/javascript;TI" mtime;Tl+TI" length;TiZLI" digest;TI"%3a0d5a839c47dbd7c229a12fa40d6b03;FI" source;TI"ZL/*! jQuery UI - v1.11.1+CommonJS - 2014-09-17 * http://jqueryui.com * Includes: widget.js * Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */ (function( factory ) { if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery" ], factory ); } else if (typeof exports === "object") { // Node/CommonJS: factory(require("jquery")); } else { // Browser globals factory( jQuery ); } }(function( $ ) { /*! * jQuery UI Widget 1.11.1 * http://jqueryui.com * * Copyright 2014 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * http://api.jqueryui.com/jQuery.widget/ */ var widget_uuid = 0, widget_slice = Array.prototype.slice; $.cleanData = (function( orig ) { return function( elems ) { var events, elem, i; for ( i = 0; (elem = elems[i]) != null; i++ ) { try { // Only trigger remove when necessary to save time events = $._data( elem, "events" ); if ( events && events.remove ) { $( elem ).triggerHandler( "remove" ); } // http://bugs.jquery.com/ticket/8235 } catch( e ) {} } orig( elems ); }; })( $.cleanData ); $.widget = function( name, base, prototype ) { var fullName, existingConstructor, constructor, basePrototype, // proxiedPrototype allows the provided prototype to remain unmodified // so that it can be used as a mixin for multiple widgets (#8876) proxiedPrototype = {}, namespace = name.split( "." )[ 0 ]; name = name.split( "." )[ 1 ]; fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } // create selector for plugin $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) { return !!$.data( elem, fullName ); }; $[ namespace ] = $[ namespace ] || {}; existingConstructor = $[ namespace ][ name ]; constructor = $[ namespace ][ name ] = function( options, element ) { // allow instantiation without "new" keyword if ( !this._createWidget ) { return new constructor( options, element ); } // allow instantiation without initializing for simple inheritance // must use "new" keyword (the code above always passes args) if ( arguments.length ) { this._createWidget( options, element ); } }; // extend with the existing constructor to carry over any static properties $.extend( constructor, existingConstructor, { version: prototype.version, // copy the object used to create the prototype in case we need to // redefine the widget later _proto: $.extend( {}, prototype ), // track widgets that inherit from this widget in case this widget is // redefined after a widget inherits from it _childConstructors: [] }); basePrototype = new base(); // we need to make the options hash a property directly on the new instance // otherwise we'll modify the options hash on the prototype that we're // inheriting from basePrototype.options = $.widget.extend( {}, basePrototype.options ); $.each( prototype, function( prop, value ) { if ( !$.isFunction( value ) ) { proxiedPrototype[ prop ] = value; return; } proxiedPrototype[ prop ] = (function() { var _super = function() { return base.prototype[ prop ].apply( this, arguments ); }, _superApply = function( args ) { return base.prototype[ prop ].apply( this, args ); }; return function() { var __super = this._super, __superApply = this._superApply, returnValue; this._super = _super; this._superApply = _superApply; returnValue = value.apply( this, arguments ); this._super = __super; this._superApply = __superApply; return returnValue; }; })(); }); constructor.prototype = $.widget.extend( basePrototype, { // TODO: remove support for widgetEventPrefix // always use the name + a colon as the prefix, e.g., draggable:start // don't prefix for widgets that aren't DOM-based widgetEventPrefix: existingConstructor ? (basePrototype.widgetEventPrefix || name) : name }, proxiedPrototype, { constructor: constructor, namespace: namespace, widgetName: name, widgetFullName: fullName }); // If this widget is being redefined then we need to find all widgets that // are inheriting from it and redefine all of them so that they inherit from // the new version of this widget. We're essentially trying to replace one // level in the prototype chain. if ( existingConstructor ) { $.each( existingConstructor._childConstructors, function( i, child ) { var childPrototype = child.prototype; // redefine the child widget using the same prototype that was // originally used, but inherit from the new version of the base $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto ); }); // remove the list of existing child constructors from the old constructor // so the old child constructors can be garbage collected delete existingConstructor._childConstructors; } else { base._childConstructors.push( constructor ); } $.widget.bridge( name, constructor ); return constructor; }; $.widget.extend = function( target ) { var input = widget_slice.call( arguments, 1 ), inputIndex = 0, inputLength = input.length, key, value; for ( ; inputIndex < inputLength; inputIndex++ ) { for ( key in input[ inputIndex ] ) { value = input[ inputIndex ][ key ]; if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) { // Clone objects if ( $.isPlainObject( value ) ) { target[ key ] = $.isPlainObject( target[ key ] ) ? $.widget.extend( {}, target[ key ], value ) : // Don't extend strings, arrays, etc. with objects $.widget.extend( {}, value ); // Copy everything else by reference } else { target[ key ] = value; } } } } return target; }; $.widget.bridge = function( name, object ) { var fullName = object.prototype.widgetFullName || name; $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string", args = widget_slice.call( arguments, 1 ), returnValue = this; // allow multiple hashes to be passed on init options = !isMethodCall && args.length ? $.widget.extend.apply( null, [ options ].concat(args) ) : options; if ( isMethodCall ) { this.each(function() { var methodValue, instance = $.data( this, fullName ); if ( options === "instance" ) { returnValue = instance; return false; } if ( !instance ) { return $.error( "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'" ); } if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) { return $.error( "no such method '" + options + "' for " + name + " widget instance" ); } methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue && methodValue.jquery ? returnValue.pushStack( methodValue.get() ) : methodValue; return false; } }); } else { this.each(function() { var instance = $.data( this, fullName ); if ( instance ) { instance.option( options || {} ); if ( instance._init ) { instance._init(); } } else { $.data( this, fullName, new object( options, this ) ); } }); } return returnValue; }; }; $.Widget = function( /* options, element */ ) {}; $.Widget._childConstructors = []; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", defaultElement: "
", options: { disabled: false, // callbacks create: null }, _createWidget: function( options, element ) { element = $( element || this.defaultElement || this )[ 0 ]; this.element = $( element ); this.uuid = widget_uuid++; this.eventNamespace = "." + this.widgetName + this.uuid; this.options = $.widget.extend( {}, this.options, this._getCreateOptions(), options ); this.bindings = $(); this.hoverable = $(); this.focusable = $(); if ( element !== this ) { $.data( element, this.widgetFullName, this ); this._on( true, this.element, { remove: function( event ) { if ( event.target === element ) { this.destroy(); } } }); this.document = $( element.style ? // element within the document element.ownerDocument : // element is window or document element.document || element ); this.window = $( this.document[0].defaultView || this.document[0].parentWindow ); } this._create(); this._trigger( "create", null, this._getCreateEventData() ); this._init(); }, _getCreateOptions: $.noop, _getCreateEventData: $.noop, _create: $.noop, _init: $.noop, destroy: function() { this._destroy(); // we can probably remove the unbind calls in 2.0 // all event bindings should go through this._on() this.element .unbind( this.eventNamespace ) .removeData( this.widgetFullName ) // support: jquery <1.6.3 // http://bugs.jquery.com/ticket/9413 .removeData( $.camelCase( this.widgetFullName ) ); this.widget() .unbind( this.eventNamespace ) .removeAttr( "aria-disabled" ) .removeClass( this.widgetFullName + "-disabled " + "ui-state-disabled" ); // clean up events and states this.bindings.unbind( this.eventNamespace ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); }, _destroy: $.noop, widget: function() { return this.element; }, option: function( key, value ) { var options = key, parts, curOption, i; if ( arguments.length === 0 ) { // don't return a reference to the internal hash return $.widget.extend( {}, this.options ); } if ( typeof key === "string" ) { // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } } options = {}; parts = key.split( "." ); key = parts.shift(); if ( parts.length ) { curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] ); for ( i = 0; i < parts.length - 1; i++ ) { curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {}; curOption = curOption[ parts[ i ] ]; } key = parts.pop(); if ( arguments.length === 1 ) { return curOption[ key ] === undefined ? null : curOption[ key ]; } curOption[ key ] = value; } else { if ( arguments.length === 1 ) { return this.options[ key ] === undefined ? null : this.options[ key ]; } options[ key ] = value; } } this._setOptions( options ); return this; }, _setOptions: function( options ) { var key; for ( key in options ) { this._setOption( key, options[ key ] ); } return this; }, _setOption: function( key, value ) { this.options[ key ] = value; if ( key === "disabled" ) { this.widget() .toggleClass( this.widgetFullName + "-disabled", !!value ); // If the widget is becoming disabled, then nothing is interactive if ( value ) { this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); } } return this; }, enable: function() { return this._setOptions({ disabled: false }); }, disable: function() { return this._setOptions({ disabled: true }); }, _on: function( suppressDisabledCheck, element, handlers ) { var delegateElement, instance = this; // no suppressDisabledCheck flag, shuffle arguments if ( typeof suppressDisabledCheck !== "boolean" ) { handlers = element; element = suppressDisabledCheck; suppressDisabledCheck = false; } // no element argument, shuffle and use this.element if ( !handlers ) { handlers = element; element = this.element; delegateElement = this.widget(); } else { element = delegateElement = $( element ); this.bindings = this.bindings.add( element ); } $.each( handlers, function( event, handler ) { function handlerProxy() { // allow widgets to customize the disabled handling // - disabled as an array instead of boolean // - disabled class as method for disabling individual parts if ( !suppressDisabledCheck && ( instance.options.disabled === true || $( this ).hasClass( "ui-state-disabled" ) ) ) { return; } return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } // copy the guid so direct unbinding works if ( typeof handler !== "string" ) { handlerProxy.guid = handler.guid = handler.guid || handlerProxy.guid || $.guid++; } var match = event.match( /^([\w:-]*)\s*(.*)$/ ), eventName = match[1] + instance.eventNamespace, selector = match[2]; if ( selector ) { delegateElement.delegate( selector, eventName, handlerProxy ); } else { element.bind( eventName, handlerProxy ); } }); }, _off: function( element, eventName ) { eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace; element.unbind( eventName ).undelegate( eventName ); }, _delay: function( handler, delay ) { function handlerProxy() { return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } var instance = this; return setTimeout( handlerProxy, delay || 0 ); }, _hoverable: function( element ) { this.hoverable = this.hoverable.add( element ); this._on( element, { mouseenter: function( event ) { $( event.currentTarget ).addClass( "ui-state-hover" ); }, mouseleave: function( event ) { $( event.currentTarget ).removeClass( "ui-state-hover" ); } }); }, _focusable: function( element ) { this.focusable = this.focusable.add( element ); this._on( element, { focusin: function( event ) { $( event.currentTarget ).addClass( "ui-state-focus" ); }, focusout: function( event ) { $( event.currentTarget ).removeClass( "ui-state-focus" ); } }); }, _trigger: function( type, event, data ) { var prop, orig, callback = this.options[ type ]; data = data || {}; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); // the original event may come from any element // so we need to reset the target on the new event event.target = this.element[ 0 ]; // copy original event properties over to the new event orig = event.originalEvent; if ( orig ) { for ( prop in orig ) { if ( !( prop in event ) ) { event[ prop ] = orig[ prop ]; } } } this.element.trigger( event, data ); return !( $.isFunction( callback ) && callback.apply( this.element[0], [ event ].concat( data ) ) === false || event.isDefaultPrevented() ); } }; $.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) { $.Widget.prototype[ "_" + method ] = function( element, options, callback ) { if ( typeof options === "string" ) { options = { effect: options }; } var hasOptions, effectName = !options ? method : options === true || typeof options === "number" ? defaultEffect : options.effect || defaultEffect; options = options || {}; if ( typeof options === "number" ) { options = { duration: options }; } hasOptions = !$.isEmptyObject( options ); options.complete = callback; if ( options.delay ) { element.delay( options.delay ); } if ( hasOptions && $.effects && $.effects.effect[ effectName ] ) { element[ method ]( options ); } else if ( effectName !== method && element[ effectName ] ) { element[ effectName ]( options.duration, options.easing, callback ); } else { element.queue(function( next ) { $( this )[ method ](); if ( callback ) { callback.call( element[ 0 ] ); } next(); }); } }; }); var widget = $.widget; })); /* * jQuery Iframe Transport Plugin 1.8.3 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /* global define, require, window, document */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define(['jquery'], factory); } else if (typeof exports === 'object') { // Node/CommonJS: factory(require('jquery')); } else { // Browser globals: factory(window.jQuery); } }(function ($) { 'use strict'; // Helper variable to create unique names for the transport iframes: var counter = 0; // The iframe transport accepts four additional options: // options.fileInput: a jQuery collection of file input fields // options.paramName: the parameter name for the file form data, // overrides the name property of the file input field(s), // can be a string or an array of strings. // options.formData: an array of objects with name and value properties, // equivalent to the return data of .serializeArray(), e.g.: // [{name: 'a', value: 1}, {name: 'b', value: 2}] // options.initialIframeSrc: the URL of the initial iframe src, // by default set to "javascript:false;" $.ajaxTransport('iframe', function (options) { if (options.async) { // javascript:false as initial iframe src // prevents warning popups on HTTPS in IE6: /*jshint scripturl: true */ var initialIframeSrc = options.initialIframeSrc || 'javascript:false;', /*jshint scripturl: false */ form, iframe, addParamChar; return { send: function (_, completeCallback) { form = $('
'); form.attr('accept-charset', options.formAcceptCharset); addParamChar = /\?/.test(options.url) ? '&' : '?'; // XDomainRequest only supports GET and POST: if (options.type === 'DELETE') { options.url = options.url + addParamChar + '_method=DELETE'; options.type = 'POST'; } else if (options.type === 'PUT') { options.url = options.url + addParamChar + '_method=PUT'; options.type = 'POST'; } else if (options.type === 'PATCH') { options.url = options.url + addParamChar + '_method=PATCH'; options.type = 'POST'; } // IE versions below IE8 cannot set the name property of // elements that have already been added to the DOM, // so we set the name along with the iframe HTML markup: counter += 1; iframe = $( '' ).bind('load', function () { var fileInputClones, paramNames = $.isArray(options.paramName) ? options.paramName : [options.paramName]; iframe .unbind('load') .bind('load', function () { var response; // Wrap in a try/catch block to catch exceptions thrown // when trying to access cross-domain iframe contents: try { response = iframe.contents(); // Google Chrome and Firefox do not throw an // exception when calling iframe.contents() on // cross-domain requests, so we unify the response: if (!response.length || !response[0].firstChild) { throw new Error(); } } catch (e) { response = undefined; } // The complete callback returns the // iframe content document as response object: completeCallback( 200, 'success', {'iframe': response} ); // Fix for IE endless progress bar activity bug // (happens on form submits to iframe targets): $('') .appendTo(form); window.setTimeout(function () { // Removing the form in a setTimeout call // allows Chrome's developer tools to display // the response result form.remove(); }, 0); }); form .prop('target', iframe.prop('name')) .prop('action', options.url) .prop('method', options.type); if (options.formData) { $.each(options.formData, function (index, field) { $('') .prop('name', field.name) .val(field.value) .appendTo(form); }); } if (options.fileInput && options.fileInput.length && options.type === 'POST') { fileInputClones = options.fileInput.clone(); // Insert a clone for each file input field: options.fileInput.after(function (index) { return fileInputClones[index]; }); if (options.paramName) { options.fileInput.each(function (index) { $(this).prop( 'name', paramNames[index] || options.paramName ); }); } // Appending the file input fields to the hidden form // removes them from their original location: form .append(options.fileInput) .prop('enctype', 'multipart/form-data') // enctype must be set as encoding for IE: .prop('encoding', 'multipart/form-data'); // Remove the HTML5 form attribute from the input(s): options.fileInput.removeAttr('form'); } form.submit(); // Insert the file input fields at their original location // by replacing the clones with the originals: if (fileInputClones && fileInputClones.length) { options.fileInput.each(function (index, input) { var clone = $(fileInputClones[index]); // Restore the original name and form properties: $(input) .prop('name', clone.prop('name')) .attr('form', clone.attr('form')); clone.replaceWith(input); }); } }); form.append(iframe).appendTo(document.body); }, abort: function () { if (iframe) { // javascript:false as iframe src aborts the request // and prevents warning popups on HTTPS in IE6. // concat is used to avoid the "Script URL" JSLint error: iframe .unbind('load') .prop('src', initialIframeSrc); } if (form) { form.remove(); } } }; } }); // The iframe transport returns the iframe content document as response. // The following adds converters from iframe to text, json, html, xml // and script. // Please note that the Content-Type for JSON responses has to be text/plain // or text/html, if the browser doesn't include application/json in the // Accept header, else IE will show a download dialog. // The Content-Type for XML responses on the other hand has to be always // application/xml or text/xml, so IE properly parses the XML response. // See also // https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#content-type-negotiation $.ajaxSetup({ converters: { 'iframe text': function (iframe) { return iframe && $(iframe[0].body).text(); }, 'iframe json': function (iframe) { return iframe && $.parseJSON($(iframe[0].body).text()); }, 'iframe html': function (iframe) { return iframe && $(iframe[0].body).html(); }, 'iframe xml': function (iframe) { var xmlDoc = iframe && iframe[0]; return xmlDoc && $.isXMLDoc(xmlDoc) ? xmlDoc : $.parseXML((xmlDoc.XMLDocument && xmlDoc.XMLDocument.xml) || $(xmlDoc.body).html()); }, 'iframe script': function (iframe) { return iframe && $.globalEval($(iframe[0].body).text()); } } }); })); /* * jQuery File Upload Plugin 5.42.2 * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2010, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT */ /* jshint nomen:false */ /* global define, require, window, document, location, Blob, FormData */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define([ 'jquery', 'jquery.ui.widget' ], factory); } else if (typeof exports === 'object') { // Node/CommonJS: factory( require('jquery'), require('./vendor/jquery.ui.widget') ); } else { // Browser globals: factory(window.jQuery); } }(function ($) { 'use strict'; // Detect file input support, based on // http://viljamis.com/blog/2012/file-upload-support-on-mobile/ $.support.fileInput = !(new RegExp( // Handle devices which give false positives for the feature detection: '(Android (1\\.[0156]|2\\.[01]))' + '|(Windows Phone (OS 7|8\\.0))|(XBLWP)|(ZuneWP)|(WPDesktop)' + '|(w(eb)?OSBrowser)|(webOS)' + '|(Kindle/(1\\.0|2\\.[05]|3\\.0))' ).test(window.navigator.userAgent) || // Feature detection for all other devices: $('').prop('disabled')); // The FileReader API is not actually used, but works as feature detection, // as some Safari versions (5?) support XHR file uploads via the FormData API, // but not non-multipart XHR file uploads. // window.XMLHttpRequestUpload is not available on IE10, so we check for // window.ProgressEvent instead to detect XHR2 file upload capability: $.support.xhrFileUpload = !!(window.ProgressEvent && window.FileReader); $.support.xhrFormDataFileUpload = !!window.FormData; // Detect support for Blob slicing (required for chunked uploads): $.support.blobSlice = window.Blob && (Blob.prototype.slice || Blob.prototype.webkitSlice || Blob.prototype.mozSlice); // Helper function to create drag handlers for dragover/dragenter/dragleave: function getDragHandler(type) { var isDragOver = type === 'dragover'; return function (e) { e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer; var dataTransfer = e.dataTransfer; if (dataTransfer && $.inArray('Files', dataTransfer.types) !== -1 && this._trigger( type, $.Event(type, {delegatedEvent: e}) ) !== false) { e.preventDefault(); if (isDragOver) { dataTransfer.dropEffect = 'copy'; } } }; } // The fileupload widget listens for change events on file input fields defined // via fileInput setting and paste or drop events of the given dropZone. // In addition to the default jQuery Widget methods, the fileupload widget // exposes the "add" and "send" methods, to add or directly send files using // the fileupload API. // By default, files added via file input selection, paste, drag & drop or // "add" method are uploaded immediately, but it is possible to override // the "add" callback option to queue file uploads. $.widget('blueimp.fileupload', { options: { // The drop target element(s), by the default the complete document. // Set to null to disable drag & drop support: dropZone: $(document), // The paste target element(s), by the default undefined. // Set to a DOM node or jQuery object to enable file pasting: pasteZone: undefined, // The file input field(s), that are listened to for change events. // If undefined, it is set to the file input fields inside // of the widget element on plugin initialization. // Set to null to disable the change listener. fileInput: undefined, // By default, the file input field is replaced with a clone after // each input field change event. This is required for iframe transport // queues and allows change events to be fired for the same file // selection, but can be disabled by setting the following option to false: replaceFileInput: true, // The parameter name for the file form data (the request argument name). // If undefined or empty, the name property of the file input field is // used, or "files[]" if the file input name property is also empty, // can be a string or an array of strings: paramName: undefined, // By default, each file of a selection is uploaded using an individual // request for XHR type uploads. Set to false to upload file // selections in one request each: singleFileUploads: true, // To limit the number of files uploaded with one XHR request, // set the following option to an integer greater than 0: limitMultiFileUploads: undefined, // The following option limits the number of files uploaded with one // XHR request to keep the request size under or equal to the defined // limit in bytes: limitMultiFileUploadSize: undefined, // Multipart file uploads add a number of bytes to each uploaded file, // therefore the following option adds an overhead for each file used // in the limitMultiFileUploadSize configuration: limitMultiFileUploadSizeOverhead: 512, // Set the following option to true to issue all file upload requests // in a sequential order: sequentialUploads: false, // To limit the number of concurrent uploads, // set the following option to an integer greater than 0: limitConcurrentUploads: undefined, // Set the following option to true to force iframe transport uploads: forceIframeTransport: false, // Set the following option to the location of a redirect url on the // origin server, for cross-domain iframe transport uploads: redirect: undefined, // The parameter name for the redirect url, sent as part of the form // data and set to 'redirect' if this option is empty: redirectParamName: undefined, // Set the following option to the location of a postMessage window, // to enable postMessage transport uploads: postMessage: undefined, // By default, XHR file uploads are sent as multipart/form-data. // The iframe transport is always using multipart/form-data. // Set to false to enable non-multipart XHR uploads: multipart: true, // To upload large files in smaller chunks, set the following option // to a preferred maximum chunk size. If set to 0, null or undefined, // or the browser does not support the required Blob API, files will // be uploaded as a whole. maxChunkSize: undefined, // When a non-multipart upload or a chunked multipart upload has been // aborted, this option can be used to resume the upload by setting // it to the size of the already uploaded bytes. This option is most // useful when modifying the options object inside of the "add" or // "send" callbacks, as the options are cloned for each file upload. uploadedBytes: undefined, // By default, failed (abort or error) file uploads are removed from the // global progress calculation. Set the following option to false to // prevent recalculating the global progress data: recalculateProgress: true, // Interval in milliseconds to calculate and trigger progress events: progressInterval: 100, // Interval in milliseconds to calculate progress bitrate: bitrateInterval: 500, // By default, uploads are started automatically when adding files: autoUpload: true, // Error and info messages: messages: { uploadedBytes: 'Uploaded bytes exceed file size' }, // Translation function, gets the message key to be translated // and an object with context specific data as arguments: i18n: function (message, context) { message = this.messages[message] || message.toString(); if (context) { $.each(context, function (key, value) { message = message.replace('{' + key + '}', value); }); } return message; }, // Additional form data to be sent along with the file uploads can be set // using this option, which accepts an array of objects with name and // value properties, a function returning such an array, a FormData // object (for XHR file uploads), or a simple object. // The form of the first fileInput is given as parameter to the function: formData: function (form) { return form.serializeArray(); }, // The add callback is invoked as soon as files are added to the fileupload // widget (via file input selection, drag & drop, paste or add API call). // If the singleFileUploads option is enabled, this callback will be // called once for each file in the selection for XHR file uploads, else // once for each file selection. // // The upload starts when the submit method is invoked on the data parameter. // The data object contains a files property holding the added files // and allows you to override plugin options as well as define ajax settings. // // Listeners for this callback can also be bound the following way: // .bind('fileuploadadd', func); // // data.submit() returns a Promise object and allows to attach additional // handlers using jQuery's Deferred callbacks: // data.submit().done(func).fail(func).always(func); add: function (e, data) { if (e.isDefaultPrevented()) { return false; } if (data.autoUpload || (data.autoUpload !== false && $(this).fileupload('option', 'autoUpload'))) { data.process().done(function () { data.submit(); }); } }, // Other callbacks: // Callback for the submit event of each file upload: // submit: function (e, data) {}, // .bind('fileuploadsubmit', func); // Callback for the start of each file upload request: // send: function (e, data) {}, // .bind('fileuploadsend', func); // Callback for successful uploads: // done: function (e, data) {}, // .bind('fileuploaddone', func); // Callback for failed (abort or error) uploads: // fail: function (e, data) {}, // .bind('fileuploadfail', func); // Callback for completed (success, abort or error) requests: // always: function (e, data) {}, // .bind('fileuploadalways', func); // Callback for upload progress events: // progress: function (e, data) {}, // .bind('fileuploadprogress', func); // Callback for global upload progress events: // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func); // Callback for uploads start, equivalent to the global ajaxStart event: // start: function (e) {}, // .bind('fileuploadstart', func); // Callback for uploads stop, equivalent to the global ajaxStop event: // stop: function (e) {}, // .bind('fileuploadstop', func); // Callback for change events of the fileInput(s): // change: function (e, data) {}, // .bind('fileuploadchange', func); // Callback for paste events to the pasteZone(s): // paste: function (e, data) {}, // .bind('fileuploadpaste', func); // Callback for drop events of the dropZone(s): // drop: function (e, data) {}, // .bind('fileuploaddrop', func); // Callback for dragover events of the dropZone(s): // dragover: function (e) {}, // .bind('fileuploaddragover', func); // Callback for the start of each chunk upload request: // chunksend: function (e, data) {}, // .bind('fileuploadchunksend', func); // Callback for successful chunk uploads: // chunkdone: function (e, data) {}, // .bind('fileuploadchunkdone', func); // Callback for failed (abort or error) chunk uploads: // chunkfail: function (e, data) {}, // .bind('fileuploadchunkfail', func); // Callback for completed (success, abort or error) chunk upload requests: // chunkalways: function (e, data) {}, // .bind('fileuploadchunkalways', func); // The plugin options are used as settings object for the ajax calls. // The following are jQuery ajax settings required for the file uploads: processData: false, contentType: false, cache: false }, // A list of options that require reinitializing event listeners and/or // special initialization code: _specialOptions: [ 'fileInput', 'dropZone', 'pasteZone', 'multipart', 'forceIframeTransport' ], _blobSlice: $.support.blobSlice && function () { var slice = this.slice || this.webkitSlice || this.mozSlice; return slice.apply(this, arguments); }, _BitrateTimer: function () { this.timestamp = ((Date.now) ? Date.now() : (new Date()).getTime()); this.loaded = 0; this.bitrate = 0; this.getBitrate = function (now, loaded, interval) { var timeDiff = now - this.timestamp; if (!this.bitrate || !interval || timeDiff > interval) { this.bitrate = (loaded - this.loaded) * (1000 / timeDiff) * 8; this.loaded = loaded; this.timestamp = now; } return this.bitrate; }; }, _isXHRUpload: function (options) { return !options.forceIframeTransport && ((!options.multipart && $.support.xhrFileUpload) || $.support.xhrFormDataFileUpload); }, _getFormData: function (options) { var formData; if ($.type(options.formData) === 'function') { return options.formData(options.form); } if ($.isArray(options.formData)) { return options.formData; } if ($.type(options.formData) === 'object') { formData = []; $.each(options.formData, function (name, value) { formData.push({name: name, value: value}); }); return formData; } return []; }, _getTotal: function (files) { var total = 0; $.each(files, function (index, file) { total += file.size || 1; }); return total; }, _initProgressObject: function (obj) { var progress = { loaded: 0, total: 0, bitrate: 0 }; if (obj._progress) { $.extend(obj._progress, progress); } else { obj._progress = progress; } }, _initResponseObject: function (obj) { var prop; if (obj._response) { for (prop in obj._response) { if (obj._response.hasOwnProperty(prop)) { delete obj._response[prop]; } } } else { obj._response = {}; } }, _onProgress: function (e, data) { if (e.lengthComputable) { var now = ((Date.now) ? Date.now() : (new Date()).getTime()), loaded; if (data._time && data.progressInterval && (now - data._time < data.progressInterval) && e.loaded !== e.total) { return; } data._time = now; loaded = Math.floor( e.loaded / e.total * (data.chunkSize || data._progress.total) ) + (data.uploadedBytes || 0); // Add the difference from the previously loaded state // to the global loaded counter: this._progress.loaded += (loaded - data._progress.loaded); this._progress.bitrate = this._bitrateTimer.getBitrate( now, this._progress.loaded, data.bitrateInterval ); data._progress.loaded = data.loaded = loaded; data._progress.bitrate = data.bitrate = data._bitrateTimer.getBitrate( now, loaded, data.bitrateInterval ); // Trigger a custom progress event with a total data property set // to the file size(s) of the current upload and a loaded data // property calculated accordingly: this._trigger( 'progress', $.Event('progress', {delegatedEvent: e}), data ); // Trigger a global progress event for all current file uploads, // including ajax calls queued for sequential file uploads: this._trigger( 'progressall', $.Event('progressall', {delegatedEvent: e}), this._progress ); } }, _initProgressListener: function (options) { var that = this, xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr(); // Accesss to the native XHR object is required to add event listeners // for the upload progress event: if (xhr.upload) { $(xhr.upload).bind('progress', function (e) { var oe = e.originalEvent; // Make sure the progress event properties get copied over: e.lengthComputable = oe.lengthComputable; e.loaded = oe.loaded; e.total = oe.total; that._onProgress(e, options); }); options.xhr = function () { return xhr; }; } }, _isInstanceOf: function (type, obj) { // Cross-frame instanceof check return Object.prototype.toString.call(obj) === '[object ' + type + ']'; }, _initXHRData: function (options) { var that = this, formData, file = options.files[0], // Ignore non-multipart setting if not supported: multipart = options.multipart || !$.support.xhrFileUpload, paramName = $.type(options.paramName) === 'array' ? options.paramName[0] : options.paramName; options.headers = $.extend({}, options.headers); if (options.contentRange) { options.headers['Content-Range'] = options.contentRange; } if (!multipart || options.blob || !this._isInstanceOf('File', file)) { options.headers['Content-Disposition'] = 'attachment; filename="' + encodeURI(file.name) + '"'; } if (!multipart) { options.contentType = file.type || 'application/octet-stream'; options.data = options.blob || file; } else if ($.support.xhrFormDataFileUpload) { if (options.postMessage) { // window.postMessage does not allow sending FormData // objects, so we just add the File/Blob objects to // the formData array and let the postMessage window // create the FormData object out of this array: formData = this._getFormData(options); if (options.blob) { formData.push({ name: paramName, value: options.blob }); } else { $.each(options.files, function (index, file) { formData.push({ name: ($.type(options.paramName) === 'array' && options.paramName[index]) || paramName, value: file }); }); } } else { if (that._isInstanceOf('FormData', options.formData)) { formData = options.formData; } else { formData = new FormData(); $.each(this._getFormData(options), function (index, field) { formData.append(field.name, field.value); }); } if (options.blob) { formData.append(paramName, options.blob, file.name); } else { $.each(options.files, function (index, file) { // This check allows the tests to run with // dummy objects: if (that._isInstanceOf('File', file) || that._isInstanceOf('Blob', file)) { formData.append( ($.type(options.paramName) === 'array' && options.paramName[index]) || paramName, file, file.uploadName || file.name ); } }); } } options.data = formData; } // Blob reference is not needed anymore, free memory: options.blob = null; }, _initIframeSettings: function (options) { var targetHost = $('').prop('href', options.url).prop('host'); // Setting the dataType to iframe enables the iframe transport: options.dataType = 'iframe ' + (options.dataType || ''); // The iframe transport accepts a serialized array as form data: options.formData = this._getFormData(options); // Add redirect url to form data on cross-domain uploads: if (options.redirect && targetHost && targetHost !== location.host) { options.formData.push({ name: options.redirectParamName || 'redirect', value: options.redirect }); } }, _initDataSettings: function (options) { if (this._isXHRUpload(options)) { if (!this._chunkedUpload(options, true)) { if (!options.data) { this._initXHRData(options); } this._initProgressListener(options); } if (options.postMessage) { // Setting the dataType to postmessage enables the // postMessage transport: options.dataType = 'postmessage ' + (options.dataType || ''); } } else { this._initIframeSettings(options); } }, _getParamName: function (options) { var fileInput = $(options.fileInput), paramName = options.paramName; if (!paramName) { paramName = []; fileInput.each(function () { var input = $(this), name = input.prop('name') || 'files[]', i = (input.prop('files') || [1]).length; while (i) { paramName.push(name); i -= 1; } }); if (!paramName.length) { paramName = [fileInput.prop('name') || 'files[]']; } } else if (!$.isArray(paramName)) { paramName = [paramName]; } return paramName; }, _initFormSettings: function (options) { // Retrieve missing options from the input field and the // associated form, if available: if (!options.form || !options.form.length) { options.form = $(options.fileInput.prop('form')); // If the given file input doesn't have an associated form, // use the default widget file input's form: if (!options.form.length) { options.form = $(this.options.fileInput.prop('form')); } } options.paramName = this._getParamName(options); if (!options.url) { options.url = options.form.prop('action') || location.href; } // The HTTP request method must be "POST" or "PUT": options.type = (options.type || ($.type(options.form.prop('method')) === 'string' && options.form.prop('method')) || '' ).toUpperCase(); if (options.type !== 'POST' && options.type !== 'PUT' && options.type !== 'PATCH') { options.type = 'POST'; } if (!options.formAcceptCharset) { options.formAcceptCharset = options.form.attr('accept-charset'); } }, _getAJAXSettings: function (data) { var options = $.extend({}, this.options, data); this._initFormSettings(options); this._initDataSettings(options); return options; }, // jQuery 1.6 doesn't provide .state(), // while jQuery 1.8+ removed .isRejected() and .isResolved(): _getDeferredState: function (deferred) { if (deferred.state) { return deferred.state(); } if (deferred.isResolved()) { return 'resolved'; } if (deferred.isRejected()) { return 'rejected'; } return 'pending'; }, // Maps jqXHR callbacks to the equivalent // methods of the given Promise object: _enhancePromise: function (promise) { promise.success = promise.done; promise.error = promise.fail; promise.complete = promise.always; return promise; }, // Creates and returns a Promise object enhanced with // the jqXHR methods abort, success, error and complete: _getXHRPromise: function (resolveOrReject, context, args) { var dfd = $.Deferred(), promise = dfd.promise(); context = context || this.options.context || promise; if (resolveOrReject === true) { dfd.resolveWith(context, args); } else if (resolveOrReject === false) { dfd.rejectWith(context, args); } promise.abort = dfd.promise; return this._enhancePromise(promise); }, // Adds convenience methods to the data callback argument: _addConvenienceMethods: function (e, data) { var that = this, getPromise = function (args) { return $.Deferred().resolveWith(that, args).promise(); }; data.process = function (resolveFunc, rejectFunc) { if (resolveFunc || rejectFunc) { data._processQueue = this._processQueue = (this._processQueue || getPromise([this])).pipe( function () { if (data.errorThrown) { return $.Deferred() .rejectWith(that, [data]).promise(); } return getPromise(arguments); } ).pipe(resolveFunc, rejectFunc); } return this._processQueue || getPromise([this]); }; data.submit = function () { if (this.state() !== 'pending') { data.jqXHR = this.jqXHR = (that._trigger( 'submit', $.Event('submit', {delegatedEvent: e}), this ) !== false) && that._onSend(e, this); } return this.jqXHR || that._getXHRPromise(); }; data.abort = function () { if (this.jqXHR) { return this.jqXHR.abort(); } this.errorThrown = 'abort'; that._trigger('fail', null, this); return that._getXHRPromise(false); }; data.state = function () { if (this.jqXHR) { return that._getDeferredState(this.jqXHR); } if (this._processQueue) { return that._getDeferredState(this._processQueue); } }; data.processing = function () { return !this.jqXHR && this._processQueue && that ._getDeferredState(this._processQueue) === 'pending'; }; data.progress = function () { return this._progress; }; data.response = function () { return this._response; }; }, // Parses the Range header from the server response // and returns the uploaded bytes: _getUploadedBytes: function (jqXHR) { var range = jqXHR.getResponseHeader('Range'), parts = range && range.split('-'), upperBytesPos = parts && parts.length > 1 && parseInt(parts[1], 10); return upperBytesPos && upperBytesPos + 1; }, // Uploads a file in multiple, sequential requests // by splitting the file up in multiple blob chunks. // If the second parameter is true, only tests if the file // should be uploaded in chunks, but does not invoke any // upload requests: _chunkedUpload: function (options, testOnly) { options.uploadedBytes = options.uploadedBytes || 0; var that = this, file = options.files[0], fs = file.size, ub = options.uploadedBytes, mcs = options.maxChunkSize || fs, slice = this._blobSlice, dfd = $.Deferred(), promise = dfd.promise(), jqXHR, upload; if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) || options.data) { return false; } if (testOnly) { return true; } if (ub >= fs) { file.error = options.i18n('uploadedBytes'); return this._getXHRPromise( false, options.context, [null, 'error', file.error] ); } // The chunk upload method: upload = function () { // Clone the options object for each chunk upload: var o = $.extend({}, options), currentLoaded = o._progress.loaded; o.blob = slice.call( file, ub, ub + mcs, file.type ); // Store the current chunk size, as the blob itself // will be dereferenced after data processing: o.chunkSize = o.blob.size; // Expose the chunk bytes position range: o.contentRange = 'bytes ' + ub + '-' + (ub + o.chunkSize - 1) + '/' + fs; // Process the upload data (the blob and potential form data): that._initXHRData(o); // Add progress listeners for this chunk upload: that._initProgressListener(o); jqXHR = ((that._trigger('chunksend', null, o) !== false && $.ajax(o)) || that._getXHRPromise(false, o.context)) .done(function (result, textStatus, jqXHR) { ub = that._getUploadedBytes(jqXHR) || (ub + o.chunkSize); // Create a progress event if no final progress event // with loaded equaling total has been triggered // for this chunk: if (currentLoaded + o.chunkSize - o._progress.loaded) { that._onProgress($.Event('progress', { lengthComputable: true, loaded: ub - o.uploadedBytes, total: ub - o.uploadedBytes }), o); } options.uploadedBytes = o.uploadedBytes = ub; o.result = result; o.textStatus = textStatus; o.jqXHR = jqXHR; that._trigger('chunkdone', null, o); that._trigger('chunkalways', null, o); if (ub < fs) { // File upload not yet complete, // continue with the next chunk: upload(); } else { dfd.resolveWith( o.context, [result, textStatus, jqXHR] ); } }) .fail(function (jqXHR, textStatus, errorThrown) { o.jqXHR = jqXHR; o.textStatus = textStatus; o.errorThrown = errorThrown; that._trigger('chunkfail', null, o); that._trigger('chunkalways', null, o); dfd.rejectWith( o.context, [jqXHR, textStatus, errorThrown] ); }); }; this._enhancePromise(promise); promise.abort = function () { return jqXHR.abort(); }; upload(); return promise; }, _beforeSend: function (e, data) { if (this._active === 0) { // the start callback is triggered when an upload starts // and no other uploads are currently running, // equivalent to the global ajaxStart event: this._trigger('start'); // Set timer for global bitrate progress calculation: this._bitrateTimer = new this._BitrateTimer(); // Reset the global progress values: this._progress.loaded = this._progress.total = 0; this._progress.bitrate = 0; } // Make sure the container objects for the .response() and // .progress() methods on the data object are available // and reset to their initial state: this._initResponseObject(data); this._initProgressObject(data); data._progress.loaded = data.loaded = data.uploadedBytes || 0; data._progress.total = data.total = this._getTotal(data.files) || 1; data._progress.bitrate = data.bitrate = 0; this._active += 1; // Initialize the global progress values: this._progress.loaded += data.loaded; this._progress.total += data.total; }, _onDone: function (result, textStatus, jqXHR, options) { var total = options._progress.total, response = options._response; if (options._progress.loaded < total) { // Create a progress event if no final progress event // with loaded equaling total has been triggered: this._onProgress($.Event('progress', { lengthComputable: true, loaded: total, total: total }), options); } response.result = options.result = result; response.textStatus = options.textStatus = textStatus; response.jqXHR = options.jqXHR = jqXHR; this._trigger('done', null, options); }, _onFail: function (jqXHR, textStatus, errorThrown, options) { var response = options._response; if (options.recalculateProgress) { // Remove the failed (error or abort) file upload from // the global progress calculation: this._progress.loaded -= options._progress.loaded; this._progress.total -= options._progress.total; } response.jqXHR = options.jqXHR = jqXHR; response.textStatus = options.textStatus = textStatus; response.errorThrown = options.errorThrown = errorThrown; this._trigger('fail', null, options); }, _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) { // jqXHRorResult, textStatus and jqXHRorError are added to the // options object via done and fail callbacks this._trigger('always', null, options); }, _onSend: function (e, data) { if (!data.submit) { this._addConvenienceMethods(e, data); } var that = this, jqXHR, aborted, slot, pipe, options = that._getAJAXSettings(data), send = function () { that._sending += 1; // Set timer for bitrate progress calculation: options._bitrateTimer = new that._BitrateTimer(); jqXHR = jqXHR || ( ((aborted || that._trigger( 'send', $.Event('send', {delegatedEvent: e}), options ) === false) && that._getXHRPromise(false, options.context, aborted)) || that._chunkedUpload(options) || $.ajax(options) ).done(function (result, textStatus, jqXHR) { that._onDone(result, textStatus, jqXHR, options); }).fail(function (jqXHR, textStatus, errorThrown) { that._onFail(jqXHR, textStatus, errorThrown, options); }).always(function (jqXHRorResult, textStatus, jqXHRorError) { that._onAlways( jqXHRorResult, textStatus, jqXHRorError, options ); that._sending -= 1; that._active -= 1; if (options.limitConcurrentUploads && options.limitConcurrentUploads > that._sending) { // Start the next queued upload, // that has not been aborted: var nextSlot = that._slots.shift(); while (nextSlot) { if (that._getDeferredState(nextSlot) === 'pending') { nextSlot.resolve(); break; } nextSlot = that._slots.shift(); } } if (that._active === 0) { // The stop callback is triggered when all uploads have // been completed, equivalent to the global ajaxStop event: that._trigger('stop'); } }); return jqXHR; }; this._beforeSend(e, options); if (this.options.sequentialUploads || (this.options.limitConcurrentUploads && this.options.limitConcurrentUploads <= this._sending)) { if (this.options.limitConcurrentUploads > 1) { slot = $.Deferred(); this._slots.push(slot); pipe = slot.pipe(send); } else { this._sequence = this._sequence.pipe(send, send); pipe = this._sequence; } // Return the piped Promise object, enhanced with an abort method, // which is delegated to the jqXHR object of the current upload, // and jqXHR callbacks mapped to the equivalent Promise methods: pipe.abort = function () { aborted = [undefined, 'abort', 'abort']; if (!jqXHR) { if (slot) { slot.rejectWith(options.context, aborted); } return send(); } return jqXHR.abort(); }; return this._enhancePromise(pipe); } return send(); }, _onAdd: function (e, data) { var that = this, result = true, options = $.extend({}, this.options, data), files = data.files, filesLength = files.length, limit = options.limitMultiFileUploads, limitSize = options.limitMultiFileUploadSize, overhead = options.limitMultiFileUploadSizeOverhead, batchSize = 0, paramName = this._getParamName(options), paramNameSet, paramNameSlice, fileSet, i, j = 0; if (limitSize && (!filesLength || files[0].size === undefined)) { limitSize = undefined; } if (!(options.singleFileUploads || limit || limitSize) || !this._isXHRUpload(options)) { fileSet = [files]; paramNameSet = [paramName]; } else if (!(options.singleFileUploads || limitSize) && limit) { fileSet = []; paramNameSet = []; for (i = 0; i < filesLength; i += limit) { fileSet.push(files.slice(i, i + limit)); paramNameSlice = paramName.slice(i, i + limit); if (!paramNameSlice.length) { paramNameSlice = paramName; } paramNameSet.push(paramNameSlice); } } else if (!options.singleFileUploads && limitSize) { fileSet = []; paramNameSet = []; for (i = 0; i < filesLength; i = i + 1) { batchSize += files[i].size + overhead; if (i + 1 === filesLength || ((batchSize + files[i + 1].size + overhead) > limitSize) || (limit && i + 1 - j >= limit)) { fileSet.push(files.slice(j, i + 1)); paramNameSlice = paramName.slice(j, i + 1); if (!paramNameSlice.length) { paramNameSlice = paramName; } paramNameSet.push(paramNameSlice); j = i + 1; batchSize = 0; } } } else { paramNameSet = paramName; } data.originalFiles = files; $.each(fileSet || files, function (index, element) { var newData = $.extend({}, data); newData.files = fileSet ? element : [element]; newData.paramName = paramNameSet[index]; that._initResponseObject(newData); that._initProgressObject(newData); that._addConvenienceMethods(e, newData); result = that._trigger( 'add', $.Event('add', {delegatedEvent: e}), newData ); return result; }); return result; }, _replaceFileInput: function (data) { var input = data.fileInput, inputClone = input.clone(true); // Add a reference for the new cloned file input to the data argument: data.fileInputClone = inputClone; $('
').append(inputClone)[0].reset(); // Detaching allows to insert the fileInput on another form // without loosing the file input value: input.after(inputClone).detach(); // Avoid memory leaks with the detached file input: $.cleanData(input.unbind('remove')); // Replace the original file input element in the fileInput // elements set with the clone, which has been copied including // event handlers: this.options.fileInput = this.options.fileInput.map(function (i, el) { if (el === input[0]) { return inputClone[0]; } return el; }); // If the widget has been initialized on the file input itself, // override this.element with the file input clone: if (input[0] === this.element[0]) { this.element = inputClone; } }, _handleFileTreeEntry: function (entry, path) { var that = this, dfd = $.Deferred(), errorHandler = function (e) { if (e && !e.entry) { e.entry = entry; } // Since $.when returns immediately if one // Deferred is rejected, we use resolve instead. // This allows valid files and invalid items // to be returned together in one set: dfd.resolve([e]); }, successHandler = function (entries) { that._handleFileTreeEntries( entries, path + entry.name + '/' ).done(function (files) { dfd.resolve(files); }).fail(errorHandler); }, readEntries = function () { dirReader.readEntries(function (results) { if (!results.length) { successHandler(entries); } else { entries = entries.concat(results); readEntries(); } }, errorHandler); }, dirReader, entries = []; path = path || ''; if (entry.isFile) { if (entry._file) { // Workaround for Chrome bug #149735 entry._file.relativePath = path; dfd.resolve(entry._file); } else { entry.file(function (file) { file.relativePath = path; dfd.resolve(file); }, errorHandler); } } else if (entry.isDirectory) { dirReader = entry.createReader(); readEntries(); } else { // Return an empy list for file system items // other than files or directories: dfd.resolve([]); } return dfd.promise(); }, _handleFileTreeEntries: function (entries, path) { var that = this; return $.when.apply( $, $.map(entries, function (entry) { return that._handleFileTreeEntry(entry, path); }) ).pipe(function () { return Array.prototype.concat.apply( [], arguments ); }); }, _getDroppedFiles: function (dataTransfer) { dataTransfer = dataTransfer || {}; var items = dataTransfer.items; if (items && items.length && (items[0].webkitGetAsEntry || items[0].getAsEntry)) { return this._handleFileTreeEntries( $.map(items, function (item) { var entry; if (item.webkitGetAsEntry) { entry = item.webkitGetAsEntry(); if (entry) { // Workaround for Chrome bug #149735: entry._file = item.getAsFile(); } return entry; } return item.getAsEntry(); }) ); } return $.Deferred().resolve( $.makeArray(dataTransfer.files) ).promise(); }, _getSingleFileInputFiles: function (fileInput) { fileInput = $(fileInput); var entries = fileInput.prop('webkitEntries') || fileInput.prop('entries'), files, value; if (entries && entries.length) { return this._handleFileTreeEntries(entries); } files = $.makeArray(fileInput.prop('files')); if (!files.length) { value = fileInput.prop('value'); if (!value) { return $.Deferred().resolve([]).promise(); } // If the files property is not available, the browser does not // support the File API and we add a pseudo File object with // the input value as name with path information removed: files = [{name: value.replace(/^.*\\/, '')}]; } else if (files[0].name === undefined && files[0].fileName) { // File normalization for Safari 4 and Firefox 3: $.each(files, function (index, file) { file.name = file.fileName; file.size = file.fileSize; }); } return $.Deferred().resolve(files).promise(); }, _getFileInputFiles: function (fileInput) { if (!(fileInput instanceof $) || fileInput.length === 1) { return this._getSingleFileInputFiles(fileInput); } return $.when.apply( $, $.map(fileInput, this._getSingleFileInputFiles) ).pipe(function () { return Array.prototype.concat.apply( [], arguments ); }); }, _onChange: function (e) { var that = this, data = { fileInput: $(e.target), form: $(e.target.form) }; this._getFileInputFiles(data.fileInput).always(function (files) { data.files = files; if (that.options.replaceFileInput) { that._replaceFileInput(data); } if (that._trigger( 'change', $.Event('change', {delegatedEvent: e}), data ) !== false) { that._onAdd(e, data); } }); }, _onPaste: function (e) { var items = e.originalEvent && e.originalEvent.clipboardData && e.originalEvent.clipboardData.items, data = {files: []}; if (items && items.length) { $.each(items, function (index, item) { var file = item.getAsFile && item.getAsFile(); if (file) { data.files.push(file); } }); if (this._trigger( 'paste', $.Event('paste', {delegatedEvent: e}), data ) !== false) { this._onAdd(e, data); } } }, _onDrop: function (e) { e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer; var that = this, dataTransfer = e.dataTransfer, data = {}; if (dataTransfer && dataTransfer.files && dataTransfer.files.length) { e.preventDefault(); this._getDroppedFiles(dataTransfer).always(function (files) { data.files = files; if (that._trigger( 'drop', $.Event('drop', {delegatedEvent: e}), data ) !== false) { that._onAdd(e, data); } }); } }, _onDragOver: getDragHandler('dragover'), _onDragEnter: getDragHandler('dragenter'), _onDragLeave: getDragHandler('dragleave'), _initEventHandlers: function () { if (this._isXHRUpload(this.options)) { this._on(this.options.dropZone, { dragover: this._onDragOver, drop: this._onDrop, // event.preventDefault() on dragenter is required for IE10+: dragenter: this._onDragEnter, // dragleave is not required, but added for completeness: dragleave: this._onDragLeave }); this._on(this.options.pasteZone, { paste: this._onPaste }); } if ($.support.fileInput) { this._on(this.options.fileInput, { change: this._onChange }); } }, _destroyEventHandlers: function () { this._off(this.options.dropZone, 'dragenter dragleave dragover drop'); this._off(this.options.pasteZone, 'paste'); this._off(this.options.fileInput, 'change'); }, _setOption: function (key, value) { var reinit = $.inArray(key, this._specialOptions) !== -1; if (reinit) { this._destroyEventHandlers(); } this._super(key, value); if (reinit) { this._initSpecialOptions(); this._initEventHandlers(); } }, _initSpecialOptions: function () { var options = this.options; if (options.fileInput === undefined) { options.fileInput = this.element.is('input[type="file"]') ? this.element : this.element.find('input[type="file"]'); } else if (!(options.fileInput instanceof $)) { options.fileInput = $(options.fileInput); } if (!(options.dropZone instanceof $)) { options.dropZone = $(options.dropZone); } if (!(options.pasteZone instanceof $)) { options.pasteZone = $(options.pasteZone); } }, _getRegExp: function (str) { var parts = str.split('/'), modifiers = parts.pop(); parts.shift(); return new RegExp(parts.join('/'), modifiers); }, _isRegExpOption: function (key, value) { return key !== 'url' && $.type(value) === 'string' && /^\/.*\/[igm]{0,3}$/.test(value); }, _initDataAttributes: function () { var that = this, options = this.options, clone = $(this.element[0].cloneNode(false)), data = clone.data(); // Avoid memory leaks: clone.remove(); // Initialize options set via HTML5 data-attributes: $.each( data, function (key, value) { var dataAttributeName = 'data-' + // Convert camelCase to hyphen-ated key: key.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); if (clone.attr(dataAttributeName)) { if (that._isRegExpOption(key, value)) { value = that._getRegExp(value); } options[key] = value; } } ); }, _create: function () { this._initDataAttributes(); this._initSpecialOptions(); this._slots = []; this._sequence = this._getXHRPromise(true); this._sending = this._active = 0; this._initProgressObject(this); this._initEventHandlers(); }, // This method is exposed to the widget API and allows to query // the number of active uploads: active: function () { return this._active; }, // This method is exposed to the widget API and allows to query // the widget upload progress. // It returns an object with loaded, total and bitrate properties // for the running uploads: progress: function () { return this._progress; }, // This method is exposed to the widget API and allows adding files // using the fileupload API. The data parameter accepts an object which // must have a files property and can contain additional options: // .fileupload('add', {files: filesList}); add: function (data) { var that = this; if (!data || this.options.disabled) { return; } if (data.fileInput && !data.files) { this._getFileInputFiles(data.fileInput).always(function (files) { data.files = files; that._onAdd(null, data); }); } else { data.files = $.makeArray(data.files); this._onAdd(null, data); } }, // This method is exposed to the widget API and allows sending files // using the fileupload API. The data parameter accepts an object which // must have a files or fileInput property and can contain additional options: // .fileupload('send', {files: filesList}); // The method returns a Promise object for the file upload call. send: function (data) { if (data && !this.options.disabled) { if (data.fileInput && !data.files) { var that = this, dfd = $.Deferred(), promise = dfd.promise(), jqXHR, aborted; promise.abort = function () { aborted = true; if (jqXHR) { return jqXHR.abort(); } dfd.reject(null, 'abort', 'abort'); return promise; }; this._getFileInputFiles(data.fileInput).always( function (files) { if (aborted) { return; } if (!files.length) { dfd.reject(); return; } data.files = files; jqXHR = that._onSend(null, data); jqXHR.then( function (result, textStatus, jqXHR) { dfd.resolve(result, textStatus, jqXHR); }, function (jqXHR, textStatus, errorThrown) { dfd.reject(jqXHR, textStatus, errorThrown); } ); } ); return this._enhancePromise(promise); } data.files = $.makeArray(data.files); if (data.files.length) { return this._onSend(null, data); } } return this._getXHRPromise(false, data && data.context); } }); })); /* * Cloudinary's jQuery library - v1.0.21 * Copyright Cloudinary * see https://github.com/cloudinary/cloudinary_js */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define([ 'jquery', 'jquery.ui.widget', 'jquery.iframe-transport', 'jquery.fileupload' ], factory); } else { // Browser globals: var $ = window.jQuery; factory($); $(function() { if($.fn.cloudinary_fileupload !== undefined) { $("input.cloudinary-fileupload[type=file]").cloudinary_fileupload(); } }); } }(function ($) { 'use strict'; var CF_SHARED_CDN = "d3jpl91pxevbkh.cloudfront.net"; var OLD_AKAMAI_SHARED_CDN = "cloudinary-a.akamaihd.net"; var AKAMAI_SHARED_CDN = "res.cloudinary.com"; var SHARED_CDN = AKAMAI_SHARED_CDN; function utf8_encode (argString) { // http://kevin.vanzonneveld.net // + original by: Webtoolkit.info (http://www.webtoolkit.info/) // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: sowberry // + tweaked by: Jack // + bugfixed by: Onno Marsman // + improved by: Yves Sucaet // + bugfixed by: Onno Marsman // + bugfixed by: Ulrich // + bugfixed by: Rafal Kukawski // + improved by: kirilloid // * example 1: utf8_encode('Kevin van Zonneveld'); // * returns 1: 'Kevin van Zonneveld' if (argString === null || typeof argString === "undefined") { return ""; } var string = (argString + ''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n"); var utftext = '', start, end, stringl = 0; start = end = 0; stringl = string.length; for (var n = 0; n < stringl; n++) { var c1 = string.charCodeAt(n); var enc = null; if (c1 < 128) { end++; } else if (c1 > 127 && c1 < 2048) { enc = String.fromCharCode((c1 >> 6) | 192, (c1 & 63) | 128); } else { enc = String.fromCharCode((c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128); } if (enc !== null) { if (end > start) { utftext += string.slice(start, end); } utftext += enc; start = end = n + 1; } } if (end > start) { utftext += string.slice(start, stringl); } return utftext; } function crc32 (str) { // http://kevin.vanzonneveld.net // + original by: Webtoolkit.info (http://www.webtoolkit.info/) // + improved by: T0bsn // + improved by: http://stackoverflow.com/questions/2647935/javascript-crc32-function-and-php-crc32-not-matching // - depends on: utf8_encode // * example 1: crc32('Kevin van Zonneveld'); // * returns 1: 1249991249 str = utf8_encode(str); var table = "00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D"; var crc = 0; var x = 0; var y = 0; crc = crc ^ (-1); for (var i = 0, iTop = str.length; i < iTop; i++) { y = (crc ^ str.charCodeAt(i)) & 0xFF; x = "0x" + table.substr(y * 9, 8); crc = (crc >>> 8) ^ x; } crc = crc ^ (-1); //convert to unsigned 32-bit int if needed if (crc < 0) {crc += 4294967296;} return crc; } function option_consume(options, option_name, default_value) { var result = options[option_name]; delete options[option_name]; return typeof(result) == 'undefined' ? default_value : result; } function build_array(arg) { if (arg === null || typeof(arg) == 'undefined') { return []; } else if ($.isArray(arg)) { return arg; } else { return [arg]; } } function present(value) { return typeof value != 'undefined' && ("" + value).length > 0; } function process_base_transformations(options) { var transformations = build_array(options.transformation); var all_named = true; for (var i = 0; i < transformations.length; i++) { all_named = all_named && typeof(transformations[i]) == 'string'; } if (all_named) { return []; } delete options.transformation; var base_transformations = []; for (var i = 0; i < transformations.length; i++) { var transformation = transformations[i]; if (typeof(transformation) == 'string') { base_transformations.push("t_" + transformation); } else { base_transformations.push(generate_transformation_string($.extend({}, transformation))); } } return base_transformations; } function process_size(options) { var size = option_consume(options, 'size'); if (size) { var split_size = size.split("x"); options.width = split_size[0]; options.height = split_size[1]; } } function process_html_dimensions(options) { var width = options.width, height = options.height; var has_layer = options.overlay || options.underlay; var crop = options.crop; var use_as_html_dimensions = !has_layer && !options.angle && crop != "fit" && crop != "limit" && crop != "lfill"; if (use_as_html_dimensions) { if (width && !options.html_width && width !== "auto" && parseFloat(width) >= 1) options.html_width = width; if (height && !options.html_height && parseFloat(height) >= 1) options.html_height = height; } if (!crop && !has_layer) { delete options.width; delete options.height; } } var TRANSFORMATION_PARAM_NAME_MAPPING = { angle: 'a', background: 'b', border: 'bo', color: 'co', color_space: 'cs', crop: 'c', default_image: 'd', delay: 'dl', density: 'dn', dpr: 'dpr', effect: 'e', fetch_format: 'f', flags: 'fl', gravity: 'g', height: 'h', opacity: 'o', overlay: 'l', page: 'pg', prefix: 'p', quality: 'q', radius: 'r', transformation: 't', underlay: 'u', width: 'w', x: 'x', y: 'y' }; var TRANSFORMATION_PARAM_VALUE_MAPPING = { angle: function(angle){ return build_array(angle).join("."); }, background: function(background) { return background.replace(/^#/, 'rgb:');}, border: function(border) { if ($.isPlainObject(border)) { var border_width = "" + (border.width || 2); var border_color = (border.color || "black").replace(/^#/, 'rgb:'); border = border_width + "px_solid_" + border_color; } return border; }, color: function(color) { return color.replace(/^#/, 'rgb:');}, dpr: function(dpr) { dpr = dpr.toString(); if (dpr === "auto") { return "1.0"; } else if (dpr.match(/^\d+$/)) { return dpr + ".0"; } else { return dpr; } }, effect: function(effect) { return build_array(effect).join(":");}, flags: function(flags) { return build_array(flags).join(".")}, transformation: function(transformation) { return build_array(transformation).join(".")} }; function generate_transformation_string(options) { var base_transformations = process_base_transformations(options); process_size(options); process_html_dimensions(options); var params = []; for (var param in TRANSFORMATION_PARAM_NAME_MAPPING) { var value = option_consume(options, param); if (!present(value)) continue; if (TRANSFORMATION_PARAM_VALUE_MAPPING[param]) { value = TRANSFORMATION_PARAM_VALUE_MAPPING[param](value); } if (!present(value)) continue; params.push(TRANSFORMATION_PARAM_NAME_MAPPING[param] + "_" + value); } params.sort(); var raw_transformation = option_consume(options, 'raw_transformation'); if (present(raw_transformation)) params.push(raw_transformation); var transformation = params.join(","); if (present(transformation)) base_transformations.push(transformation); return base_transformations.join("/"); } function absolutize(url) { if (!url.match(/^https?:\//)) { var prefix = document.location.protocol + "//" + document.location.host; if (url[0] == '?') { prefix += document.location.pathname; } else if (url[0] != '/') { prefix += document.location.pathname.replace(/\/[^\/]*$/, '/'); } url = prefix + url; } return url; } function cloudinary_url_prefix(public_id, cloud_name, private_cdn, cdn_subdomain, secure_cdn_subdomain, cname, secure, secure_distribution, protocol) { if (cloud_name.match(/^\//) && !secure) { return "/res" + cloud_name; } var prefix = secure ? 'https://' : (window.location.protocol === 'file:' ? "file://" : 'http://'); prefix = protocol ? protocol + '//' : prefix; var shared_domain = !private_cdn; if (secure) { if (!secure_distribution || secure_distribution == OLD_AKAMAI_SHARED_CDN) { secure_distribution = private_cdn ? cloud_name + "-res.cloudinary.com" : SHARED_CDN; } shared_domain = shared_domain || secure_distribution == SHARED_CDN; if (secure_cdn_subdomain == null && shared_domain) { secure_cdn_subdomain = cdn_subdomain; } if (secure_cdn_subdomain) { secure_distribution = secure_distribution.replace('res.cloudinary.com', "res-" + ((crc32(public_id) % 5) + 1) + ".cloudinary.com"); } prefix += secure_distribution; } else if (cname) { var subdomain = cdn_subdomain ? "a" + ((crc32(public_id) % 5) + 1) + "." : ""; prefix += subdomain + cname; } else { prefix += (private_cdn ? cloud_name + "-res" : "res"); prefix += (cdn_subdomain ? "-" + ((crc32(public_id) % 5) + 1) : "") prefix += ".cloudinary.com"; } if (shared_domain) prefix += "/" + cloud_name; return prefix; } function finalize_resource_type(resource_type, type, url_suffix, use_root_path, shorten) { var resource_type_and_type = resource_type + "/" + type; if (url_suffix) { if (resource_type_and_type == "image/upload") { resource_type_and_type = "images"; } else if (resource_type_and_type == "raw/upload") { resource_type_and_type = "files"; } else { throw "URL Suffix only supported for image/upload and raw/upload"; } } if (use_root_path) { if (resource_type_and_type == "image/upload" || resource_type_and_type == "images") { resource_type_and_type = ""; } else { throw "Root path only supported for image/upload"; } } if (shorten && resource_type_and_type == "image/upload") { resource_type_and_type = "iu"; } return resource_type_and_type; } function cloudinary_url(public_id, options) { options = options || {}; var type = option_consume(options, 'type', 'upload'); if (type == 'fetch') { options.fetch_format = options.fetch_format || option_consume(options, 'format'); } var transformation = generate_transformation_string(options); var resource_type = option_consume(options, 'resource_type', "image"); var version = option_consume(options, 'version'); var format = option_consume(options, 'format'); var cloud_name = option_consume(options, 'cloud_name', $.cloudinary.config().cloud_name); if (!cloud_name) throw "Unknown cloud_name"; var private_cdn = option_consume(options, 'private_cdn', $.cloudinary.config().private_cdn); var secure_distribution = option_consume(options, 'secure_distribution', $.cloudinary.config().secure_distribution); var cname = option_consume(options, 'cname', $.cloudinary.config().cname); var cdn_subdomain = option_consume(options, 'cdn_subdomain', $.cloudinary.config().cdn_subdomain); var secure_cdn_subdomain = option_consume(options, 'secure_cdn_subdomain', $.cloudinary.config().secure_cdn_subdomain); var shorten = option_consume(options, 'shorten', $.cloudinary.config().shorten); var secure = option_consume(options, 'secure', window.location.protocol == 'https:'); var protocol = option_consume(options, 'protocol', $.cloudinary.config().protocol); var trust_public_id = option_consume(options, 'trust_public_id'); var url_suffix = option_consume(options, 'url_suffix'); var use_root_path = option_consume(options, 'use_root_path', $.cloudinary.config().use_root_path); if (!private_cdn) { if (url_suffix) throw "URL Suffix only supported in private CDN"; if (use_root_path) throw "Root path only supported in private CDN"; } if (type == 'fetch') { public_id = absolutize(public_id); } if (public_id.search("/") >= 0 && !public_id.match(/^v[0-9]+/) && !public_id.match(/^https?:\//) && !present(version)) { version = 1; } if (public_id.match(/^https?:/)) { if (type == "upload" || type == "asset") return public_id; public_id = encodeURIComponent(public_id).replace(/%3A/g, ":").replace(/%2F/g, "/"); } else { // Make sure public_id is URI encoded. public_id = encodeURIComponent(decodeURIComponent(public_id)).replace(/%3A/g, ":").replace(/%2F/g, "/"); if (url_suffix) { if (url_suffix.match(/[\.\/]/)) throw "url_suffix should not include . or /"; public_id = public_id + "/" + url_suffix; } if (format) { if (!trust_public_id) public_id = public_id.replace(/\.(jpg|png|gif|webp)$/, ''); public_id = public_id + "." + format; } } var resource_type_and_type = finalize_resource_type(resource_type, type, url_suffix, use_root_path, shorten); var prefix = cloudinary_url_prefix(public_id, cloud_name, private_cdn, cdn_subdomain, secure_cdn_subdomain, cname, secure, secure_distribution, protocol); var url = [prefix, resource_type_and_type, transformation, version ? "v" + version : "", public_id].join("/").replace(/([^:])\/+/g, '$1/'); return url; } function default_stoppoints(width) { return 10 * Math.ceil(width / 10); } function prepare_html_url(public_id, options) { if ($.cloudinary.config('dpr') && !options.dpr) { options.dpr = $.cloudinary.config('dpr'); } var url = cloudinary_url(public_id, options); var width = option_consume(options, 'html_width'); var height = option_consume(options, 'html_height'); if (width) options.width = width; if (height) options.height = height; return url; } function get_config(name, options, default_value) { var value = options[name] || $.cloudinary.config(name); if (typeof(value) == 'undefined') value = default_value; return value; } function closest_above(list, value) { var i = list.length - 2; while (i >= 0 && list[i] >= value) { i--; } return list[i+1]; } var cloudinary_config = null; var responsive_config = null; var responsive_resize_initialized = false; var device_pixel_ratio_cache = {}; $.cloudinary = { CF_SHARED_CDN: CF_SHARED_CDN, OLD_AKAMAI_SHARED_CDN: OLD_AKAMAI_SHARED_CDN, AKAMAI_SHARED_CDN: AKAMAI_SHARED_CDN, SHARED_CDN: SHARED_CDN, config: function(new_config, new_value) { if (!cloudinary_config) { cloudinary_config = {}; $('meta[name^="cloudinary_"]').each(function() { cloudinary_config[$(this).attr('name').replace("cloudinary_", '')] = $(this).attr('content'); }); } if (typeof(new_value) != 'undefined') { cloudinary_config[new_config] = new_value; } else if (typeof(new_config) == 'string') { return cloudinary_config[new_config]; } else if (new_config) { cloudinary_config = new_config; } return cloudinary_config; }, url: function(public_id, options) { options = $.extend({}, options); return cloudinary_url(public_id, options); }, url_internal: cloudinary_url, transformation_string: function(options) { options = $.extend({}, options); return generate_transformation_string(options); }, image: function(public_id, options) { options = $.extend({}, options); var url = prepare_html_url(public_id, options); var img = $('').data('src-cache', url).attr(options).cloudinary_update(options); return img; }, facebook_profile_image: function(public_id, options) { return $.cloudinary.image(public_id, $.extend({type: 'facebook'}, options)); }, twitter_profile_image: function(public_id, options) { return $.cloudinary.image(public_id, $.extend({type: 'twitter'}, options)); }, twitter_name_profile_image: function(public_id, options) { return $.cloudinary.image(public_id, $.extend({type: 'twitter_name'}, options)); }, gravatar_image: function(public_id, options) { return $.cloudinary.image(public_id, $.extend({type: 'gravatar'}, options)); }, fetch_image: function(public_id, options) { return $.cloudinary.image(public_id, $.extend({type: 'fetch'}, options)); }, sprite_css: function(public_id, options) { options = $.extend({type: 'sprite'}, options); if (!public_id.match(/.css$/)) options.format = 'css'; return $.cloudinary.url(public_id, options); }, /** * Turn on hidpi (dpr_auto) and responsive (w_auto) processing according to the current container size and the device pixel ratio. * Use the following classes: * - cld-hidpi - only set dpr_auto * - cld-responsive - update both dpr_auto and w_auto * @param: options * - responsive_resize - should responsive images be updated on resize (default: true). * - responsive_debounce - if set, how many milliseconds after resize is done before the image is replaces (default: 100). Set to 0 to disable. * - responsive_use_stoppoints: * - true - always use stoppoints for width * - "resize" - use exact width on first render and stoppoints on resize (default) * - false - always use exact width * Stoppoints - to prevent creating a transformation for every pixel, stop-points can be configured. The smallest stop-point that is larger than * the wanted width will be used. The default stoppoints are all the multiples of 10. See calc_stoppoint for ways to override this. */ responsive: function(options) { responsive_config = $.extend(responsive_config || {}, options); $('img.cld-responsive, img.cld-hidpi').cloudinary_update(responsive_config); var responsive_resize = get_config('responsive_resize', responsive_config, true); if (responsive_resize && !responsive_resize_initialized) { responsive_config.resizing = responsive_resize_initialized = true; var timeout = null; $(window).on('resize', function() { var debounce = get_config('responsive_debounce', responsive_config, 100); function reset() { if (timeout) { clearTimeout(timeout); timeout = null; } } function run() { $('img.cld-responsive').cloudinary_update(responsive_config); } function wait() { reset(); setTimeout(function() { reset(); run(); }, debounce); } if (debounce) { wait(); } else { run(); } }); } }, /** * Compute the stoppoint for the given element and width. * By default the stoppoint will be the smallest multiple of 10 larger than the width. * These can be overridden by either setting the data-stoppoints attribute of an image or using $.cloudinary.config('stoppoints', stoppoints). * The value can be either: * - an ordered list of the wanted stoppoints * - a comma separated ordered list of stoppoints * - a function that returns the stoppoint given the wanted width. */ calc_stoppoint: function (element, width) { var stoppoints = $(element).data('stoppoints') || $.cloudinary.config().stoppoints || default_stoppoints; if (typeof(stoppoints) === 'function') { return stoppoints(width); } if (typeof(stoppoints) === 'string') { stoppoints = $.map(stoppoints.split(","), function(val){ return parseInt(val); }); } return closest_above(stoppoints, width); }, device_pixel_ratio: function() { var dpr = window.devicePixelRatio || 1; var dpr_string = device_pixel_ratio_cache[dpr]; if (!dpr_string) { // Find closest supported DPR (to work correctly with device zoom) var dpr_used = closest_above($.cloudinary.supported_dpr_values, dpr); dpr_string = dpr_used.toString(); if (dpr_string.match(/^\d+$/)) dpr_string += ".0"; device_pixel_ratio_cache[dpr] = dpr_string; } return dpr_string; }, supported_dpr_values: [0.75, 1.0, 1.3, 1.5, 2.0, 3.0] }; $.fn.cloudinary = function(options) { this.filter('img').each(function() { var img_options = $.extend({width: $(this).attr('width'), height: $(this).attr('height'), src: $(this).attr('src')}, $(this).data(), options); var public_id = option_consume(img_options, 'source', option_consume(img_options, 'src')); var url = prepare_html_url(public_id, img_options); $(this).data('src-cache', url).attr({width: img_options.width, height: img_options.height}); }).cloudinary_update(options); return this; }; /** * Update hidpi (dpr_auto) and responsive (w_auto) fields according to the current container size and the device pixel ratio. * Only images marked with the cld-responsive class have w_auto updated. * options: * - responsive_use_stoppoints: * - true - always use stoppoints for width * - "resize" - use exact width on first render and stoppoints on resize (default) * - false - always use exact width * - responsive: * - true - enable responsive on this element. Can be done by adding cld-responsive. * Note that $.cloudinary.responsive() should be called once on the page. */ $.fn.cloudinary_update = function(options) { options = options || {}; var responsive_use_stoppoints = get_config('responsive_use_stoppoints', options, "resize"); var exact = responsive_use_stoppoints === false || (responsive_use_stoppoints == "resize" && !options.resizing); this.filter('img').each(function() { if (options.responsive) { $(this).addClass('cld-responsive'); } var attrs = {}; var src = $(this).data('src-cache') || $(this).data('src'); if (!src) return; var responsive = $(this).hasClass('cld-responsive') && src.match(/\bw_auto\b/); if (responsive) { var parents = $(this).parents(), parentsLength = parents.length, container, containerWidth = 0, nthParent; for (nthParent = 0; nthParent < parentsLength; nthParent+=1) { container = parents[nthParent]; if (container && container.clientWidth) { containerWidth = container.clientWidth; break; } } if (containerWidth == 0) { // container doesn't know the size yet. Usually because the image is hidden or outside the DOM. return; } var requestedWidth = exact ? containerWidth : $.cloudinary.calc_stoppoint(this, containerWidth); var currentWidth = $(this).data('width') || 0; if (requestedWidth > currentWidth) { // requested width is larger, fetch new image $(this).data('width', requestedWidth); } else { // requested width is not larger - keep previous requestedWidth = currentWidth; } src = src.replace(/\bw_auto\b/g, "w_" + requestedWidth); attrs.width = null; attrs.height = null; } // Update dpr according to the device's devicePixelRatio attrs.src = src.replace(/\bdpr_(1\.0|auto)\b/g, "dpr_" + $.cloudinary.device_pixel_ratio()); $(this).attr(attrs); }); return this; }; var webp = null; $.fn.webpify = function(options, webp_options) { var that = this; options = options || {}; webp_options = webp_options || options; if (!webp) { webp = $.Deferred(); var webp_canary = new Image(); webp_canary.onerror = webp.reject; webp_canary.onload = webp.resolve; webp_canary.src = 'data:image/webp;base64,UklGRi4AAABXRUJQVlA4TCEAAAAvAUAAEB8wAiMwAgSSNtse/cXjxyCCmrYNWPwmHRH9jwMA'; } $(function() { webp.done(function() { $(that).cloudinary($.extend({}, webp_options, {format: 'webp'})); }).fail(function() { $(that).cloudinary(options); }); }); return this; }; $.fn.fetchify = function(options) { return this.cloudinary($.extend(options, {'type': 'fetch'})); }; if (!$.fn.fileupload) { return; } $.cloudinary.delete_by_token = function(delete_token, options) { options = options || {}; var url = options.url; if (!url) { var cloud_name = options.cloud_name || $.cloudinary.config().cloud_name; url = "https://api.cloudinary.com/v1_1/" + cloud_name + "/delete_by_token"; } var dataType = $.support.xhrFileUpload ? "json" : "iframe json"; return $.ajax({ url: url, method: "POST", data: {token: delete_token}, headers: {"X-Requested-With": "XMLHttpRequest"}, dataType: dataType }); }; $.fn.cloudinary_fileupload = function(options) { var initializing = !this.data('blueimpFileupload'); if (initializing) { options = $.extend({ maxFileSize: 20000000, dataType: 'json', headers: {"X-Requested-With": "XMLHttpRequest"} }, options); } this.fileupload(options); if (initializing) { this.bind("fileuploaddone", function(e, data) { if (data.result.error) return; data.result.path = ["v", data.result.version, "/", data.result.public_id, data.result.format ? "." + data.result.format : ""].join(""); if (data.cloudinaryField && data.form.length > 0) { var upload_info = [data.result.resource_type, data.result.type, data.result.path].join("/") + "#" + data.result.signature; var multiple = $(e.target).prop("multiple"); var add_field = function() { $('').attr({type: "hidden", name: data.cloudinaryField}).val(upload_info).appendTo(data.form); }; if (multiple) { add_field(); } else { var field = $(data.form).find('input[name="' + data.cloudinaryField + '"]'); if (field.length > 0) { field.val(upload_info); } else { add_field(); } } } $(e.target).trigger('cloudinarydone', data); }); this.bind("fileuploadstart", function(e){ $(e.target).trigger('cloudinarystart'); }); this.bind("fileuploadstop", function(e){ $(e.target).trigger('cloudinarystop'); }); this.bind("fileuploadprogress", function(e,data){ $(e.target).trigger('cloudinaryprogress',data); }); this.bind("fileuploadprogressall", function(e,data){ $(e.target).trigger('cloudinaryprogressall',data); }); this.bind("fileuploadfail", function(e,data){ $(e.target).trigger('cloudinaryfail',data); }); this.bind("fileuploadalways", function(e,data){ $(e.target).trigger('cloudinaryalways',data); }); if (!this.fileupload('option').url) { var cloud_name = options.cloud_name || $.cloudinary.config().cloud_name; var upload_url = "https://api.cloudinary.com/v1_1/" + cloud_name + "/upload"; this.fileupload('option', 'url', upload_url); } } return this; }; $.fn.cloudinary_upload_url = function(remote_url) { this.fileupload('option', 'formData').file = remote_url; this.fileupload('add', { files: [ remote_url ] }); delete(this.fileupload('option', 'formData').file); }; $.fn.unsigned_cloudinary_upload = function(upload_preset, upload_params, options) { options = options || {}; upload_params = $.extend({}, upload_params) || {}; if (upload_params.cloud_name) { options.cloud_name = upload_params.cloud_name; delete upload_params.cloud_name; } // Serialize upload_params for (var key in upload_params) { var value = upload_params[key]; if ($.isPlainObject(value)) { upload_params[key] = $.map(value, function(v, k){return k + "=" + v;}).join("|"); } else if ($.isArray(value)) { if (value.length > 0 && $.isArray(value[0])) { upload_params[key] = $.map(value, function(array_value){return array_value.join(",");}).join("|"); } else { upload_params[key] = value.join(","); } } } if (!upload_params.callback) { upload_params.callback = "/cloudinary_cors.html"; } upload_params.upload_preset = upload_preset; options.formData = upload_params; if (options.cloudinary_field) { options.cloudinaryField = options.cloudinary_field; delete options.cloudinary_field; } var html_options = options.html || {}; html_options["class"] = "cloudinary_fileupload " + (html_options["class"] || ""); if (options.multiple) html_options.multiple = true; this.attr(html_options).cloudinary_fileupload(options); return this; }; $.cloudinary.unsigned_upload_tag = function(upload_preset, upload_params, options) { return $('').attr({type: "file", name: "file"}).unsigned_cloudinary_upload(upload_preset, upload_params, options); }; })); function MediumEditor(elements, options) { 'use strict'; return this.init(elements, options); } if (typeof module === 'object') { module.exports = MediumEditor; } // AMD support else if (typeof define === 'function' && define.amd) { define(function () { 'use strict'; return MediumEditor; }); } (function (window, document) { 'use strict'; function extend(b, a) { var prop; if (b === undefined) { return a; } for (prop in a) { if (a.hasOwnProperty(prop) && b.hasOwnProperty(prop) === false) { b[prop] = a[prop]; } } return b; } // https://github.com/jashkenas/underscore var now = Date.now || function() { return new Date().getTime(); }; // https://github.com/jashkenas/underscore function debounce(func, wait) { var DEBOUNCE_INTERVAL = 50, timeout, args, context, timestamp, result, later; if (!wait && wait !== 0) { wait = DEBOUNCE_INTERVAL; } later = function() { var last = now() - timestamp; if (last < wait && last > 0) { timeout = setTimeout(later, wait - last); } else { timeout = null; result = func.apply(context, args); if (!timeout) { context = args = null; } } }; return function() { context = this; args = arguments; timestamp = now(); if (!timeout) { timeout = setTimeout(later, wait); } return result; }; } function isDescendant(parent, child) { var node = child.parentNode; while (node !== null) { if (node === parent) { return true; } node = node.parentNode; } return false; } // http://stackoverflow.com/questions/5605401/insert-link-in-contenteditable-element // by Tim Down function saveSelection() { var i, len, ranges, sel = this.options.contentWindow.getSelection(); if (sel.getRangeAt && sel.rangeCount) { ranges = []; for (i = 0, len = sel.rangeCount; i < len; i += 1) { ranges.push(sel.getRangeAt(i)); } return ranges; } return null; } function restoreSelection(savedSel) { var i, len, sel = this.options.contentWindow.getSelection(); if (savedSel) { sel.removeAllRanges(); for (i = 0, len = savedSel.length; i < len; i += 1) { sel.addRange(savedSel[i]); } } } // http://stackoverflow.com/questions/1197401/how-can-i-get-the-element-the-caret-is-in-with-javascript-when-using-contentedi // by You function getSelectionStart() { var node = this.options.ownerDocument.getSelection().anchorNode, startNode = (node && node.nodeType === 3 ? node.parentNode : node); return startNode; } // http://stackoverflow.com/questions/4176923/html-of-selected-text // by Tim Down function getSelectionHtml() { var i, html = '', sel, len, container; if (this.options.contentWindow.getSelection !== undefined) { sel = this.options.contentWindow.getSelection(); if (sel.rangeCount) { container = this.options.ownerDocument.createElement('div'); for (i = 0, len = sel.rangeCount; i < len; i += 1) { container.appendChild(sel.getRangeAt(i).cloneContents()); } html = container.innerHTML; } } else if (this.options.ownerDocument.selection !== undefined) { if (this.options.ownerDocument.selection.type === 'Text') { html = this.options.ownerDocument.selection.createRange().htmlText; } } return html; } // https://github.com/jashkenas/underscore function isElement(obj) { return !!(obj && obj.nodeType === 1); } // http://stackoverflow.com/questions/6690752/insert-html-at-caret-in-a-contenteditable-div function insertHTMLCommand(doc, html) { var selection, range, el, fragment, node, lastNode; if (doc.queryCommandSupported('insertHTML')) { return doc.execCommand('insertHTML', false, html); } selection = window.getSelection(); if (selection.getRangeAt && selection.rangeCount) { range = selection.getRangeAt(0); range.deleteContents(); el = doc.createElement("div"); el.innerHTML = html; fragment = doc.createDocumentFragment(); while (el.firstChild) { node = el.firstChild; lastNode = fragment.appendChild(node); } range.insertNode(fragment); // Preserve the selection: if (lastNode) { range = range.cloneRange(); range.setStartAfter(lastNode); range.collapse(true); selection.removeAllRanges(); selection.addRange(range); } } } MediumEditor.prototype = { defaults: { allowMultiParagraphSelection: true, anchorInputPlaceholder: 'Paste or type a link', anchorPreviewHideDelay: 500, buttons: ['bold', 'italic', 'underline', 'anchor', 'header1', 'header2', 'quote'], buttonLabels: false, checkLinkFormat: false, cleanPastedHTML: false, delay: 0, diffLeft: 0, diffTop: -10, disableReturn: false, disableDoubleReturn: false, disableToolbar: false, disableEditing: false, disableAnchorForm: false, disablePlaceholders: false, elementsContainer: false, contentWindow: window, ownerDocument: document, firstHeader: 'h3', forcePlainText: true, placeholder: 'Type your text', secondHeader: 'h4', targetBlank: false, anchorTarget: false, anchorButton: false, anchorButtonClass: 'btn', extensions: {}, activeButtonClass: 'medium-editor-button-active', firstButtonClass: 'medium-editor-button-first', lastButtonClass: 'medium-editor-button-last' }, // http://stackoverflow.com/questions/17907445/how-to-detect-ie11#comment30165888_17907562 // by rg89 isIE: ((navigator.appName === 'Microsoft Internet Explorer') || ((navigator.appName === 'Netscape') && (new RegExp('Trident/.*rv:([0-9]{1,}[.0-9]{0,})').exec(navigator.userAgent) !== null))), init: function (elements, options) { var uniqueId = 1; this.options = extend(options, this.defaults); this.setElementSelection(elements); if (this.elements.length === 0) { return; } this.parentElements = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'pre']; if (!this.options.elementsContainer) { this.options.elementsContainer = document.body; } while (this.options.elementsContainer.querySelector('#medium-editor-toolbar-' + uniqueId)) { uniqueId = uniqueId + 1; } this.id = uniqueId; return this.setup(); }, setup: function () { this.events = []; this.isActive = true; this.initElements() .bindSelect() .bindPaste() .setPlaceholders() .bindElementActions() .bindWindowActions() .passInstance(); }, on: function(target, event, listener, useCapture) { target.addEventListener(event, listener, useCapture); this.events.push([target, event, listener, useCapture]); }, off: function(target, event, listener, useCapture) { var index = this.events.indexOf([target, event, listener, useCapture]), e; if(index !== -1) { e = this.events.splice(index, 1); e[0].removeEventListener(e[1], e[2], e[3]); } }, removeAllEvents: function() { var e = this.events.pop(); while(e) { e[0].removeEventListener(e[1], e[2], e[3]); e = this.events.pop(); } }, initElements: function () { this.updateElementList(); var i, addToolbar = false; for (i = 0; i < this.elements.length; i += 1) { if (!this.options.disableEditing && !this.elements[i].getAttribute('data-disable-editing')) { this.elements[i].setAttribute('contentEditable', true); } if (!this.elements[i].getAttribute('data-placeholder')) { this.elements[i].setAttribute('data-placeholder', this.options.placeholder); } this.elements[i].setAttribute('data-medium-element', true); this.bindParagraphCreation(i); if (!this.options.disableToolbar && !this.elements[i].getAttribute('data-disable-toolbar')) { addToolbar = true; } } // Init toolbar if (addToolbar) { this.initToolbar() .bindButtons() .bindAnchorForm() .bindAnchorPreview(); } return this; }, setElementSelection: function (selector) { this.elementSelection = selector; this.updateElementList(); }, updateElementList: function () { this.elements = typeof this.elementSelection === 'string' ? this.options.ownerDocument.querySelectorAll(this.elementSelection) : this.elementSelection; if (this.elements.nodeType === 1) { this.elements = [this.elements]; } }, // handleBlur is debounced because: // - This method could be called many times due to the type of event handlers that are calling it // - We want a slight delay so that other events in the stack can run, some of which may // prevent the toolbar from being hidden (via this.keepToolbarAlive). handleBlur: debounce(function() { if ( !this.keepToolbarAlive ) { // this.hideToolbarActions(); } }), bindBlur: function(i) { var self = this, blurFunction = function(e){ // If it's not part of the editor, or the toolbar if ( e.target !== self.toolbar && e.target !== self.elements[0] && !isDescendant(self.elements[0], e.target) && !isDescendant(self.toolbar, e.target) && !isDescendant(self.anchorPreview, e.target)) { // Activate the placeholder if (!self.options.disablePlaceholders) { self.placeholderWrapper(self.elements[0], e); } // Hide the toolbar after a small delay so we can prevent this on toolbar click self.handleBlur(); } }; // Hide the toolbar when focusing outside of the editor. this.on(document.body, 'click', blurFunction, true); this.on(document.body, 'focus', blurFunction, true); return this; }, bindKeypress: function(i) { if (this.options.disablePlaceholders) { return this; } var self = this; // Set up the keypress events this.on(this.elements[i], 'keypress', function(event){ self.placeholderWrapper(this,event); }); return this; }, bindClick: function(i) { var self = this; this.on(this.elements[i], 'click', function(){ if (!self.options.disablePlaceholders) { // Remove placeholder this.classList.remove('medium-editor-placeholder'); } if ( self.options.staticToolbar ) { self.setToolbarPosition(); } }); return this; }, /** * This handles blur and keypress events on elements * Including Placeholders, and tooldbar hiding on blur */ bindElementActions: function() { var i; for (i = 0; i < this.elements.length; i += 1) { if (!this.options.disablePlaceholders) { // Active all of the placeholders this.activatePlaceholder(this.elements[i]); } // Bind the return and tab keypress events this.bindReturn(i) .bindTab(i) .bindBlur(i) .bindClick(i) .bindKeypress(i); } return this; }, // Two functions to handle placeholders activatePlaceholder: function (el) { if (!(el.querySelector('img')) && !(el.querySelector('blockquote')) && el.textContent.replace(/^\s+|\s+$/g, '') === '') { el.classList.add('medium-editor-placeholder'); } }, placeholderWrapper: function (el, e) { el.classList.remove('medium-editor-placeholder'); if (e.type !== 'keypress') { this.activatePlaceholder(el); } }, serialize: function () { var i, elementid, content = {}; for (i = 0; i < this.elements.length; i += 1) { elementid = (this.elements[i].id !== '') ? this.elements[i].id : 'element-' + i; content[elementid] = { value: this.elements[i].innerHTML.trim() }; } return content; }, /** * Helper function to call a method with a number of parameters on all registered extensions. * The function assures that the function exists before calling. * * @param {string} funcName name of the function to call * @param [args] arguments passed into funcName */ callExtensions: function (funcName) { if (arguments.length < 1) { return; } var args = Array.prototype.slice.call(arguments, 1), ext, name; for (name in this.options.extensions) { if (this.options.extensions.hasOwnProperty(name)) { ext = this.options.extensions[name]; if (ext[funcName] !== undefined) { ext[funcName].apply(ext, args); } } } }, /** * Pass current Medium Editor instance to all extensions * if extension constructor has 'parent' attribute set to 'true' * */ passInstance: function () { var self = this, ext, name; for (name in self.options.extensions) { if (self.options.extensions.hasOwnProperty(name)) { ext = self.options.extensions[name]; if (ext.parent) { ext.base = self; } } } return self; }, bindParagraphCreation: function (index) { var self = this; this.on(this.elements[index], 'keypress', function (e) { var node, tagName; if (e.which === 32) { node = getSelectionStart.call(self); tagName = node.tagName.toLowerCase(); if (tagName === 'a') { document.execCommand('unlink', false, null); } } }); this.on(this.elements[index], 'keyup', function (e) { var node = getSelectionStart.call(self), tagName, editorElement; if (node && node.getAttribute('data-medium-element') && node.children.length === 0 && !(self.options.disableReturn || node.getAttribute('data-disable-return'))) { document.execCommand('formatBlock', false, 'p'); } if (e.which === 13) { node = getSelectionStart.call(self); tagName = node.tagName.toLowerCase(); editorElement = self.getSelectionElement(); if (!(self.options.disableReturn || editorElement.getAttribute('data-disable-return')) && tagName !== 'li' && !self.isListItemChild(node)) { if (!e.shiftKey) { document.execCommand('formatBlock', false, 'p'); } if (tagName === 'a') { document.execCommand('unlink', false, null); } } } }); return this; }, isListItemChild: function (node) { var parentNode = node.parentNode, tagName = parentNode.tagName.toLowerCase(); while (this.parentElements.indexOf(tagName) === -1 && tagName !== 'div') { if (tagName === 'li') { return true; } parentNode = parentNode.parentNode; if (parentNode && parentNode.tagName) { tagName = parentNode.tagName.toLowerCase(); } else { return false; } } return false; }, bindReturn: function (index) { var self = this; this.on(this.elements[index], 'keypress', function (e) { if (e.which === 13) { if (self.options.disableReturn || this.getAttribute('data-disable-return')) { e.preventDefault(); } else if (self.options.disableDoubleReturn || this.getAttribute('data-disable-double-return')) { var node = getSelectionStart.call(self); if (node && node.textContent === '\n') { e.preventDefault(); } } } }); return this; }, bindTab: function (index) { var self = this; this.on(this.elements[index], 'keydown', function (e) { if (e.which === 9) { // Override tab only for pre nodes var tag = getSelectionStart.call(self).tagName.toLowerCase(); if (tag === 'pre') { e.preventDefault(); document.execCommand('insertHtml', null, ' '); } // Tab to indent list structures! if (tag === 'li') { e.preventDefault(); // If Shift is down, outdent, otherwise indent if (e.shiftKey) { document.execCommand('outdent', e); } else { document.execCommand('indent', e); } } } }); return this; }, buttonTemplate: function (btnType) { var buttonLabels = this.getButtonLabels(this.options.buttonLabels), buttonTemplates = { 'bold': '', 'italic': '', 'underline': '', 'strikethrough': '', 'superscript': '', 'subscript': '', 'anchor': '', 'image': '', 'header1': '', 'header2': '', 'quote': '', 'orderedlist': '', 'unorderedlist': '', 'pre': '', 'indent': '', 'outdent': '', 'justifyCenter': '', 'justifyFull': '', 'justifyLeft': '', 'justifyRight': '' }; return buttonTemplates[btnType] || false; }, // TODO: break method getButtonLabels: function (buttonLabelType) { var customButtonLabels, attrname, buttonLabels = { 'bold': 'B', 'italic': 'I', 'underline': 'U', 'strikethrough': 'A', 'superscript': 'x1', 'subscript': 'x1', 'anchor': '#', 'image': 'image', 'header1': 'H1', 'header2': 'H2', 'quote': '', 'orderedlist': '1.', 'unorderedlist': '', 'pre': '0101', 'indent': '', 'outdent': '', 'justifyCenter': 'C', 'justifyFull': 'J', 'justifyLeft': 'L', 'justifyRight': 'R' }; if (buttonLabelType === 'fontawesome') { customButtonLabels = { 'bold': '', 'italic': '', 'underline': '', 'strikethrough': '', 'superscript': '', 'subscript': '', 'anchor': '', 'image': '', 'quote': '', 'orderedlist': '', 'unorderedlist': '', 'pre': '', 'indent': '', 'outdent': '', 'justifyCenter': '', 'justifyFull': '', 'justifyLeft': '', 'justifyRight': '' }; } else if (typeof buttonLabelType === 'object') { customButtonLabels = buttonLabelType; } if (typeof customButtonLabels === 'object') { for (attrname in customButtonLabels) { if (customButtonLabels.hasOwnProperty(attrname)) { buttonLabels[attrname] = customButtonLabels[attrname]; } } } return buttonLabels; }, initToolbar: function () { if (this.toolbar) { return this; } this.toolbar = this.createToolbar(); this.keepToolbarAlive = false; this.toolbarActions = this.toolbar.querySelector('.medium-editor-toolbar-actions'); this.anchorPreview = this.createAnchorPreview(); if (!this.options.disableAnchorForm) { this.anchorForm = this.toolbar.querySelector('.medium-editor-toolbar-form-anchor'); this.anchorInput = this.anchorForm.querySelector('input.medium-editor-toolbar-anchor-input'); this.anchorTarget = this.anchorForm.querySelector('input.medium-editor-toolbar-anchor-target'); this.anchorButton = this.anchorForm.querySelector('input.medium-editor-toolbar-anchor-button'); } return this; }, createToolbar: function () { var toolbar = document.createElement('div'); toolbar.id = 'medium-editor-toolbar-' + this.id; toolbar.className = 'medium-editor-toolbar'; if ( this.options.staticToolbar ) { toolbar.className += " static-toolbar"; } else { toolbar.className += " stalker-toolbar"; } toolbar.appendChild(this.toolbarButtons()); if (!this.options.disableAnchorForm) { toolbar.appendChild(this.toolbarFormAnchor()); } this.options.elementsContainer.appendChild(toolbar); return toolbar; }, //TODO: actionTemplate toolbarButtons: function () { var btns = this.options.buttons, ul = document.createElement('ul'), li, i, btn, ext; ul.id = 'medium-editor-toolbar-actions' + this.id; ul.className = 'medium-editor-toolbar-actions clearfix'; for (i = 0; i < btns.length; i += 1) { if (this.options.extensions.hasOwnProperty(btns[i])) { ext = this.options.extensions[btns[i]]; btn = ext.getButton !== undefined ? ext.getButton() : null; } else { btn = this.buttonTemplate(btns[i]); } if (btn) { li = document.createElement('li'); if (isElement(btn)) { li.appendChild(btn); } else { li.innerHTML = btn; } ul.appendChild(li); } } return ul; }, toolbarFormAnchor: function () { var anchor = document.createElement('div'), input = document.createElement('input'), target_label = document.createElement('label'), target = document.createElement('input'), button_label = document.createElement('label'), button = document.createElement('input'), close = document.createElement('a'), save = document.createElement('a'); close.setAttribute('href', '#'); close.className = 'medium-editor-toobar-anchor-close'; close.innerHTML = '×'; save.setAttribute('href', '#'); save.className = 'medium-editor-toobar-anchor-save'; save.innerHTML = '✓'; input.setAttribute('type', 'text'); input.className = 'medium-editor-toolbar-anchor-input'; input.setAttribute('placeholder', this.options.anchorInputPlaceholder); target.setAttribute('type', 'checkbox'); target.className = 'medium-editor-toolbar-anchor-target'; target_label.innerHTML = "Open in New Window?"; target_label.insertBefore(target, target_label.firstChild); button.setAttribute('type', 'checkbox'); button.className = 'medium-editor-toolbar-anchor-button'; button_label.innerHTML = "Button"; button_label.insertBefore(button, button_label.firstChild); anchor.className = 'medium-editor-toolbar-form-anchor'; anchor.id = 'medium-editor-toolbar-form-anchor-' + this.id; anchor.appendChild(input); anchor.appendChild(save); anchor.appendChild(close); if (this.options.anchorTarget) { anchor.appendChild(target_label); } if (this.options.anchorButton) { anchor.appendChild(button_label); } return anchor; }, bindSelect: function () { var self = this, i; this.checkSelectionWrapper = function (e) { // Do not close the toolbar when bluring the editable area and clicking into the anchor form if (!self.options.disableAnchorForm && e && self.clickingIntoArchorForm(e)) { return false; } self.checkSelection(); }; this.on(document.documentElement, 'mouseup', this.checkSelectionWrapper); for (i = 0; i < this.elements.length; i += 1) { this.on(this.elements[i], 'keyup', this.checkSelectionWrapper); this.on(this.elements[i], 'blur', this.checkSelectionWrapper); this.on(this.elements[i], 'click', this.checkSelectionWrapper); } return this; }, checkSelection: function () { var newSelection, selectionElement; if (this.keepToolbarAlive !== true && !this.options.disableToolbar) { newSelection = this.options.contentWindow.getSelection(); if ((!this.options.updateOnEmptySelection && newSelection.toString().trim() === '') || (this.options.allowMultiParagraphSelection === false && this.hasMultiParagraphs()) || this.selectionInContentEditableFalse()) { if ( !this.options.staticToolbar ) { this.hideToolbarActions(); } else if (this.anchorForm && this.anchorForm.style.display === 'block') { this.setToolbarButtonStates(); this.showToolbarActions(); } } else { selectionElement = this.getSelectionElement(); if (!selectionElement || selectionElement.getAttribute('data-disable-toolbar')) { if ( !this.options.staticToolbar ) { this.hideToolbarActions(); } } else { this.checkSelectionElement(newSelection, selectionElement); } } } return this; }, clickingIntoArchorForm: function (e) { var self = this; if (e.type && e.type.toLowerCase() === 'blur' && e.relatedTarget && e.relatedTarget === self.anchorInput) { return true; } return false; }, hasMultiParagraphs: function () { var selectionHtml = getSelectionHtml.call(this).replace(/<[\S]+><\/[\S]+>/gim, ''), hasMultiParagraphs = selectionHtml.match(/<(p|h[0-6]|blockquote)>([\s\S]*?)<\/(p|h[0-6]|blockquote)>/g); return (hasMultiParagraphs ? hasMultiParagraphs.length : 0); }, checkSelectionElement: function (newSelection, selectionElement) { var i; this.selection = newSelection; this.selectionRange = this.selection.getRangeAt(0); for (i = 0; i < this.elements.length; i += 1) { if (this.elements[i] === selectionElement) { this.setToolbarButtonStates() .setToolbarPosition() .showToolbarActions(); return; } } if ( !this.options.staticToolbar ) { this.hideToolbarActions(); } }, findMatchingSelectionParent: function(testElementFunction) { var selection = this.options.contentWindow.getSelection(), range, current; if (selection.rangeCount === 0) { return false; } range = selection.getRangeAt(0); current = range.commonAncestorContainer; do { if (current.nodeType === 1){ if ( testElementFunction(current) ) { return current; } // do not traverse upwards past the nearest containing editor if (current.getAttribute('data-medium-element')) { return false; } } current = current.parentNode; } while (current); return false; }, getSelectionElement: function () { return this.findMatchingSelectionParent(function(el) { return el.getAttribute('data-medium-element'); }); }, selectionInContentEditableFalse: function () { return this.findMatchingSelectionParent(function(el) { return (el && el.nodeName !== '#text' && el.getAttribute('contenteditable') === 'false'); }); }, setToolbarPosition: function () { // document.documentElement for IE 9 var scrollTop = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop, container = this.elements[0], containerRect = container.getBoundingClientRect(), containerTop = containerRect.top + scrollTop, buttonHeight = 50, selection = window.getSelection(), range, boundary, middleBoundary, defaultLeft = (this.options.diffLeft) - (this.toolbar.offsetWidth / 2), halfOffsetWidth = this.toolbar.offsetWidth / 2; if ( selection.focusNode === null ) { return this; } this.showToolbar(); if ( this.options.staticToolbar ) { if ( this.options.stickyToolbar ) { // If it's beyond the height of the editor, position it at the bottom of the editor if ( scrollTop > (containerTop + this.elements[0].offsetHeight - this.toolbar.offsetHeight)) { this.toolbar.style.top = (containerTop + this.elements[0].offsetHeight) + 'px'; } // Stick the toolbar to the top of the window else if ( scrollTop > (containerTop - this.toolbar.offsetHeight) ) { this.toolbar.classList.add('sticky-toolbar'); this.toolbar.style.top = "0px"; } // Normal static toolbar position else { this.toolbar.classList.remove('sticky-toolbar'); this.toolbar.style.top = containerTop - this.toolbar.offsetHeight + "px"; } } else { this.toolbar.style.top = containerTop - this.toolbar.offsetHeight + "px"; } this.toolbar.style.left = containerRect.left + "px"; } else if (!selection.isCollapsed) { range = selection.getRangeAt(0); boundary = range.getBoundingClientRect(); middleBoundary = (boundary.left + boundary.right) / 2; if (boundary.top < buttonHeight) { this.toolbar.classList.add('medium-toolbar-arrow-over'); this.toolbar.classList.remove('medium-toolbar-arrow-under'); this.toolbar.style.top = buttonHeight + boundary.bottom - this.options.diffTop + this.options.contentWindow.pageYOffset - this.toolbar.offsetHeight + 'px'; } else { this.toolbar.classList.add('medium-toolbar-arrow-under'); this.toolbar.classList.remove('medium-toolbar-arrow-over'); this.toolbar.style.top = boundary.top + this.options.diffTop + this.options.contentWindow.pageYOffset - this.toolbar.offsetHeight + 'px'; } if (middleBoundary < halfOffsetWidth) { this.toolbar.style.left = defaultLeft + halfOffsetWidth + 'px'; } else if ((this.options.contentWindow.innerWidth - middleBoundary) < halfOffsetWidth) { this.toolbar.style.left = this.options.contentWindow.innerWidth + defaultLeft - halfOffsetWidth + 'px'; } else { this.toolbar.style.left = defaultLeft + middleBoundary + 'px'; } } this.hideAnchorPreview(); return this; }, setToolbarButtonStates: function () { var buttons = this.toolbarActions.querySelectorAll('button'), i; for (i = 0; i < buttons.length; i += 1) { buttons[i].classList.remove(this.options.activeButtonClass); } this.checkActiveButtons(); return this; }, checkActiveButtons: function () { var elements = Array.prototype.slice.call(this.elements), parentNode = this.getSelectedParentElement(); while (parentNode.tagName !== undefined && this.parentElements.indexOf(parentNode.tagName.toLowerCase) === -1) { this.activateButton(parentNode.tagName.toLowerCase()); this.callExtensions('checkState', parentNode); // we can abort the search upwards if we leave the contentEditable element if (elements.indexOf(parentNode) !== -1) { break; } parentNode = parentNode.parentNode; } }, activateButton: function (tag) { var el = this.toolbar.querySelector('[data-element="' + tag + '"]'); if (el !== null && el.className.indexOf(this.options.activeButtonClass) === -1) { el.className += ' ' + this.options.activeButtonClass; } }, bindButtons: function () { var buttons = this.toolbar.querySelectorAll('button'), i, self = this, triggerAction = function (e) { e.preventDefault(); e.stopPropagation(); if (self.selection === undefined) { self.checkSelection(); } if (this.className.indexOf(self.options.activeButtonClass) > -1) { this.classList.remove(self.options.activeButtonClass); } else { this.className += ' ' + self.options.activeButtonClass; } if (this.hasAttribute('data-action')) { self.execAction(this.getAttribute('data-action'), e); } }; for (i = 0; i < buttons.length; i += 1) { this.on(buttons[i], 'click', triggerAction); } this.setFirstAndLastItems(buttons); return this; }, setFirstAndLastItems: function (buttons) { if (buttons.length > 0) { buttons[0].className += ' ' + this.options.firstButtonClass; buttons[buttons.length - 1].className += ' ' + this.options.lastButtonClass; } return this; }, execAction: function (action, e) { if (action.indexOf('append-') > -1) { this.execFormatBlock(action.replace('append-', '')); this.setToolbarPosition(); this.setToolbarButtonStates(); } else if (action === 'anchor') { if (!this.options.disableAnchorForm) { this.triggerAnchorAction(e); } } else if (action === 'image') { this.options.ownerDocument.execCommand('insertImage', false, this.options.contentWindow.getSelection()); } else { this.options.ownerDocument.execCommand(action, false, null); this.setToolbarPosition(); } }, // http://stackoverflow.com/questions/15867542/range-object-get-selection-parent-node-chrome-vs-firefox rangeSelectsSingleNode: function (range) { var startNode = range.startContainer; return startNode === range.endContainer && startNode.hasChildNodes() && range.endOffset === range.startOffset + 1; }, getSelectedParentElement: function () { var selectedParentElement = null, range = this.selectionRange; if (this.rangeSelectsSingleNode(range)) { selectedParentElement = range.startContainer.childNodes[range.startOffset]; } else if (range.startContainer.nodeType === 3) { selectedParentElement = range.startContainer.parentNode; } else { selectedParentElement = range.startContainer; } return selectedParentElement; }, triggerAnchorAction: function () { var selectedParentElement = this.getSelectedParentElement(); if (selectedParentElement.tagName && selectedParentElement.tagName.toLowerCase() === 'a') { this.options.ownerDocument.execCommand('unlink', false, null); } else if (this.anchorForm) { if (this.anchorForm.style.display === 'block') { this.showToolbarActions(); } else { this.showAnchorForm(); } } return this; }, execFormatBlock: function (el) { var selectionData = this.getSelectionData(this.selection.anchorNode); // FF handles blockquote differently on formatBlock // allowing nesting, we need to use outdent // https://developer.mozilla.org/en-US/docs/Rich-Text_Editing_in_Mozilla if (el === 'blockquote' && selectionData.el && selectionData.el.parentNode.tagName.toLowerCase() === 'blockquote') { return this.options.ownerDocument.execCommand('outdent', false, null); } if (selectionData.tagName === el) { el = 'p'; } // When IE we need to add <> to heading elements and // blockquote needs to be called as indent // http://stackoverflow.com/questions/10741831/execcommand-formatblock-headings-in-ie // http://stackoverflow.com/questions/1816223/rich-text-editor-with-blockquote-function/1821777#1821777 if (this.isIE) { if (el === 'blockquote') { return this.options.ownerDocument.execCommand('indent', false, el); } el = '<' + el + '>'; } return this.options.ownerDocument.execCommand('formatBlock', false, el); }, getSelectionData: function (el) { var tagName; if (el && el.tagName) { tagName = el.tagName.toLowerCase(); } while (el && this.parentElements.indexOf(tagName) === -1) { el = el.parentNode; if (el && el.tagName) { tagName = el.tagName.toLowerCase(); } } return { el: el, tagName: tagName }; }, getFirstChild: function (el) { var firstChild = el.firstChild; while (firstChild !== null && firstChild.nodeType !== 1) { firstChild = firstChild.nextSibling; } return firstChild; }, isToolbarShown: function() { return this.toolbar && this.toolbar.classList.contains('medium-editor-toolbar-active'); }, showToolbar: function() { if (this.toolbar && !this.isToolbarShown()) { this.toolbar.classList.add('medium-editor-toolbar-active'); } }, hideToolbar: function() { if (this.isToolbarShown()) { this.toolbar.classList.remove('medium-editor-toolbar-active'); if (this.onHideToolbar) { this.onHideToolbar(); } } }, hideToolbarActions: function () { this.keepToolbarAlive = false; this.hideToolbar(); }, showToolbarActions: function () { var self = this; if (this.anchorForm) { this.anchorForm.style.display = 'none'; } this.toolbarActions.style.display = 'block'; this.keepToolbarAlive = false; // Using setTimeout + options.delay because: // We will actually be displaying the toolbar, which should be controlled by options.delay setTimeout(function () { self.showToolbar(); }, this.options.delay); }, saveSelection: function() { this.savedSelection = saveSelection.call(this); }, restoreSelection: function() { restoreSelection.call(this, this.savedSelection); }, showAnchorForm: function (link_value) { if (!this.anchorForm) { return; } this.toolbarActions.style.display = 'none'; this.saveSelection(); this.anchorForm.style.display = 'block'; this.setToolbarPosition(); this.keepToolbarAlive = true; this.anchorInput.focus(); this.anchorInput.value = link_value || ''; }, bindAnchorForm: function () { if (!this.anchorForm) { return this; } var linkCancel = this.anchorForm.querySelector('a.medium-editor-toobar-anchor-close'), linkSave = this.anchorForm.querySelector('a.medium-editor-toobar-anchor-save'), self = this; this.on(this.anchorForm, 'click', function (e) { e.stopPropagation(); self.keepToolbarAlive = true; }); this.on(this.anchorInput, 'keyup', function (e) { var button = null, target; if (e.keyCode === 13) { e.preventDefault(); if (self.options.anchorTarget && self.anchorTarget.checked) { target = "_blank"; } else { target = "_self"; } if (self.options.anchorButton && self.anchorButton.checked) { button = self.options.anchorButtonClass; } self.createLink(this, target, button); } else if (e.keyCode === 27) { e.preventDefault(); self.showToolbarActions(); restoreSelection.call(self, self.savedSelection); } }); this.on(linkSave, 'click', function(e) { var button = null, target; e.preventDefault(); if ( self.options.anchorTarget && self.anchorTarget.checked) { target = "_blank"; } else { target = "_self"; } if (self.options.anchorButton && self.anchorButton.checked) { button = self.options.anchorButtonClass; } self.createLink(self.anchorInput, target, button); }, true); this.on(this.anchorInput, 'click', function (e) { // make sure not to hide form when cliking into the input e.stopPropagation(); self.keepToolbarAlive = true; }); // Hide the anchor form when focusing outside of it. this.on(this.options.ownerDocument.body, 'click', function (e) { if (e.target !== self.anchorForm && !isDescendant(self.anchorForm, e.target) && !isDescendant(self.toolbarActions, e.target)) { self.keepToolbarAlive = false; self.checkSelection(); } }, true); this.on(this.options.ownerDocument.body, 'focus', function (e) { if (e.target !== self.anchorForm && !isDescendant(self.anchorForm, e.target) && !isDescendant(self.toolbarActions, e.target)) { self.keepToolbarAlive = false; self.checkSelection(); } }, true); this.on(linkCancel, 'click', function (e) { e.preventDefault(); self.showToolbarActions(); restoreSelection.call(self, self.savedSelection); }); return this; }, hideAnchorPreview: function () { this.anchorPreview.classList.remove('medium-editor-anchor-preview-active'); }, // TODO: break method showAnchorPreview: function (anchorEl) { if (this.anchorPreview.classList.contains('medium-editor-anchor-preview-active') || anchorEl.getAttribute('data-disable-preview')) { return true; } var self = this, buttonHeight = 40, boundary = anchorEl.getBoundingClientRect(), middleBoundary = (boundary.left + boundary.right) / 2, halfOffsetWidth, defaultLeft; self.anchorPreview.querySelector('i').textContent = anchorEl.href; halfOffsetWidth = self.anchorPreview.offsetWidth / 2; defaultLeft = self.options.diffLeft - halfOffsetWidth; self.observeAnchorPreview(anchorEl); self.anchorPreview.classList.add('medium-toolbar-arrow-over'); self.anchorPreview.classList.remove('medium-toolbar-arrow-under'); self.anchorPreview.style.top = Math.round(buttonHeight + boundary.bottom - self.options.diffTop + this.options.contentWindow.pageYOffset - self.anchorPreview.offsetHeight) + 'px'; if (middleBoundary < halfOffsetWidth) { self.anchorPreview.style.left = defaultLeft + halfOffsetWidth + 'px'; } else if ((this.options.contentWindow.innerWidth - middleBoundary) < halfOffsetWidth) { self.anchorPreview.style.left = this.options.contentWindow.innerWidth + defaultLeft - halfOffsetWidth + 'px'; } else { self.anchorPreview.style.left = defaultLeft + middleBoundary + 'px'; } if (this.anchorPreview && !this.anchorPreview.classList.contains('medium-editor-anchor-preview-active')) { this.anchorPreview.classList.add('medium-editor-anchor-preview-active'); } return this; }, // TODO: break method observeAnchorPreview: function (anchorEl) { var self = this, lastOver = (new Date()).getTime(), over = true, stamp = function () { lastOver = (new Date()).getTime(); over = true; }, unstamp = function (e) { if (!e.relatedTarget || !/anchor-preview/.test(e.relatedTarget.className)) { over = false; } }, interval_timer = setInterval(function () { if (over) { return true; } var durr = (new Date()).getTime() - lastOver; if (durr > self.options.anchorPreviewHideDelay) { // hide the preview 1/2 second after mouse leaves the link self.hideAnchorPreview(); // cleanup clearInterval(interval_timer); self.off(self.anchorPreview, 'mouseover', stamp); self.off(self.anchorPreview, 'mouseout', unstamp); self.off(anchorEl, 'mouseover', stamp); self.off(anchorEl, 'mouseout', unstamp); } }, 200); this.on(self.anchorPreview, 'mouseover', stamp); this.on(self.anchorPreview, 'mouseout', unstamp); this.on(anchorEl, 'mouseover', stamp); this.on(anchorEl, 'mouseout', unstamp); }, createAnchorPreview: function () { var self = this, anchorPreview = this.options.ownerDocument.createElement('div'); anchorPreview.id = 'medium-editor-anchor-preview-' + this.id; anchorPreview.className = 'medium-editor-anchor-preview'; anchorPreview.innerHTML = this.anchorPreviewTemplate(); this.options.elementsContainer.appendChild(anchorPreview); this.on(anchorPreview, 'click', function () { self.anchorPreviewClickHandler(); }); return anchorPreview; }, anchorPreviewTemplate: function () { return '
' + ' ' + '
'; }, anchorPreviewClickHandler: function (e) { if (!this.options.disableAnchorForm && this.activeAnchor) { var self = this, range = this.options.ownerDocument.createRange(), sel = this.options.contentWindow.getSelection(); range.selectNodeContents(self.activeAnchor); sel.removeAllRanges(); sel.addRange(range); // Using setTimeout + options.delay because: // We may actually be displaying the anchor preview, which should be controlled by options.delay setTimeout(function () { if (self.activeAnchor) { self.showAnchorForm(self.activeAnchor.href); } self.keepToolbarAlive = false; }, this.options.delay); } this.hideAnchorPreview(); }, editorAnchorObserver: function (e) { var self = this, overAnchor = true, leaveAnchor = function () { // mark the anchor as no longer hovered, and stop listening overAnchor = false; self.off(self.activeAnchor, 'mouseout', leaveAnchor); }; if (e.target && e.target.tagName.toLowerCase() === 'a') { // Detect empty href attributes // The browser will make href="" or href="#top" // into absolute urls when accessed as e.targed.href, so check the html if (!/href=["']\S+["']/.test(e.target.outerHTML) || /href=["']#\S+["']/.test(e.target.outerHTML)) { return true; } // only show when hovering on anchors if (this.isToolbarShown()) { // only show when toolbar is not present return true; } this.activeAnchor = e.target; this.on(this.activeAnchor, 'mouseout', leaveAnchor); // Using setTimeout + options.delay because: // - We're going to show the anchor preview according to the configured delay // if the mouse has not left the anchor tag in that time setTimeout(function () { if (overAnchor) { self.showAnchorPreview(e.target); } }, this.options.delay); } }, bindAnchorPreview: function (index) { var i, self = this; this.editorAnchorObserverWrapper = function (e) { self.editorAnchorObserver(e); }; for (i = 0; i < this.elements.length; i += 1) { this.on(this.elements[i], 'mouseover', this.editorAnchorObserverWrapper); } return this; }, checkLinkFormat: function (value) { var re = /^(https?|ftps?|rtmpt?):\/\/|mailto:/; return (re.test(value) ? '' : 'http://') + value; }, setTargetBlank: function (el) { var i; el = el || getSelectionStart.call(this); if (el.tagName.toLowerCase() === 'a') { el.target = '_blank'; } else { el = el.getElementsByTagName('a'); for (i = 0; i < el.length; i += 1) { el[i].target = '_blank'; } } }, setButtonClass: function (buttonClass) { var el = getSelectionStart.call(this), classes = buttonClass.split(' '), i, j; if (el.tagName.toLowerCase() === 'a') { for (j = 0; j < classes.length; j += 1) { el.classList.add(classes[j]); } } else { el = el.getElementsByTagName('a'); for (i = 0; i < el.length; i += 1) { for (j = 0; j < classes.length; j += 1) { el[i].classList.add(classes[j]); } } } }, createLink: function (input, target, buttonClass) { var i, event; if (input.value.trim().length === 0) { this.hideToolbarActions(); return; } restoreSelection.call(this, this.savedSelection); if (this.options.checkLinkFormat) { input.value = this.checkLinkFormat(input.value); } this.options.ownerDocument.execCommand('createLink', false, input.value); if (this.options.targetBlank || target === "_blank") { this.setTargetBlank(); } if (buttonClass) { this.setButtonClass(buttonClass); } if (this.options.targetBlank || target === "_blank" || buttonClass) { event = this.options.ownerDocument.createEvent("HTMLEvents"); event.initEvent("input", true, true, this.options.contentWindow); for (i = 0; i < this.elements.length; i += 1) { this.elements[i].dispatchEvent(event); } } this.checkSelection(); this.showToolbarActions(); input.value = ''; }, positionToolbarIfShown: function() { if (this.isToolbarShown()) { this.setToolbarPosition(); } }, // handleResize is debounced because: // - It will be called when the browser is resizing, which can fire many times very quickly // - For some event (like resize) a slight lag in UI responsiveness is OK and provides performance benefits handleResize: debounce(function() { this.positionToolbarIfShown(); }), bindWindowActions: function () { var self = this; // Add a scroll event for sticky toolbar if ( this.options.staticToolbar && this.options.stickyToolbar ) { // On scroll, re-position the toolbar this.on(window, 'scroll', function() { self.positionToolbarIfShown(); }, true); } this.on(this.options.contentWindow, 'resize', function() { self.handleResize(); }); return this; }, activate: function () { if (this.isActive) { return; } this.setup(); }, // TODO: break method deactivate: function () { var i; if (!this.isActive) { return; } this.isActive = false; if (this.toolbar !== undefined) { this.options.elementsContainer.removeChild(this.anchorPreview); this.options.elementsContainer.removeChild(this.toolbar); delete this.toolbar; delete this.anchorPreview; } for (i = 0; i < this.elements.length; i += 1) { this.elements[i].removeAttribute('contentEditable'); this.elements[i].removeAttribute('data-medium-element'); } this.removeAllEvents(); }, htmlEntities: function (str) { // converts special characters (like <) into their escaped/encoded values (like <). // This allows you to show to display the string without the browser reading it as HTML. return String(str).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); }, bindPaste: function () { var i, self = this; this.pasteWrapper = function (e) { var paragraphs, html = '', p, dataFormatHTML = 'text/html', dataFormatPlain = 'text/plain'; this.classList.remove('medium-editor-placeholder'); if (!self.options.forcePlainText && !self.options.cleanPastedHTML) { return this; } if (window.clipboardData && e.clipboardData === undefined) { e.clipboardData = window.clipboardData; // If window.clipboardData exists, but e.clipboardData doesn't exist, // we're probably in IE. IE only has two possibilities for clipboard // data format: 'Text' and 'URL'. // // Of the two, we want 'Text': dataFormatHTML = 'Text'; dataFormatPlain = 'Text'; } if (e.clipboardData && e.clipboardData.getData && !e.defaultPrevented) { e.preventDefault(); if (self.options.cleanPastedHTML && e.clipboardData.getData(dataFormatHTML)) { return self.cleanPaste(e.clipboardData.getData(dataFormatHTML)); } if (!(self.options.disableReturn || this.getAttribute('data-disable-return'))) { paragraphs = e.clipboardData.getData(dataFormatPlain).split(/[\r\n]/g); for (p = 0; p < paragraphs.length; p += 1) { if (paragraphs[p] !== '') { if (navigator.userAgent.match(/firefox/i) && p === 0) { html += self.htmlEntities(paragraphs[p]); } else { html += '

' + self.htmlEntities(paragraphs[p]) + '

'; } } } insertHTMLCommand(self.options.ownerDocument, html); } else { html = self.htmlEntities(e.clipboardData.getData(dataFormatPlain)); insertHTMLCommand(self.options.ownerDocument, html); } } }; for (i = 0; i < this.elements.length; i += 1) { this.on(this.elements[i], 'paste', this.pasteWrapper); } return this; }, setPlaceholders: function () { if (this.options.disablePlaceholders) { return this; } var i, activatePlaceholder = function (el) { if (!(el.querySelector('img')) && !(el.querySelector('blockquote')) && el.textContent.replace(/^\s+|\s+$/g, '') === '') { el.classList.add('medium-editor-placeholder'); } }, placeholderWrapper = function (e) { this.classList.remove('medium-editor-placeholder'); if (e.type !== 'keypress') { activatePlaceholder(this); } }; for (i = 0; i < this.elements.length; i += 1) { activatePlaceholder(this.elements[i]); this.on(this.elements[i], 'blur', placeholderWrapper); this.on(this.elements[i], 'keypress', placeholderWrapper); } return this; }, cleanPaste: function (text) { /*jslint regexp: true*/ /* jslint does not allow character negation, because the negation will not match any unicode characters. In the regexes in this block, negation is used specifically to match the end of an html tag, and in fact unicode characters *should* be allowed. */ var i, elList, workEl, el = this.getSelectionElement(), multiline = /]*docs-internal-guid[^>]*>/gi), ""], [new RegExp(/<\/b>(]*>)?$/gi), ""], // un-html spaces and newlines inserted by OS X [new RegExp(/\s+<\/span>/g), ' '], [new RegExp(/
/g), '
'], // replace google docs italics+bold with a span to be replaced once the html is inserted [new RegExp(/]*(font-style:italic;font-weight:bold|font-weight:bold;font-style:italic)[^>]*>/gi), ''], // replace google docs italics with a span to be replaced once the html is inserted [new RegExp(/]*font-style:italic[^>]*>/gi), ''], //[replace google docs bolds with a span to be replaced once the html is inserted [new RegExp(/]*font-weight:bold[^>]*>/gi), ''], // replace manually entered b/i/a tags with real ones [new RegExp(/<(\/?)(i|b|a)>/gi), '<$1$2>'], // replace manually a tags with real ones, converting smart-quotes from google docs [new RegExp(/<a\s+href=("|”|“|“|”)([^&]+)("|”|“|“|”)>/gi), ''] ]; /*jslint regexp: false*/ for (i = 0; i < replacements.length; i += 1) { text = text.replace(replacements[i][0], replacements[i][1]); } if (multiline) { // double br's aren't converted to p tags, but we want paragraphs. elList = text.split('

'); this.pasteHTML('

' + elList.join('

') + '

'); this.options.ownerDocument.execCommand('insertText', false, "\n"); // block element cleanup elList = el.querySelectorAll('a,p,div,br'); for (i = 0; i < elList.length; i += 1) { workEl = elList[i]; switch (workEl.tagName.toLowerCase()) { case 'a': if (this.options.targetBlank){ this.setTargetBlank(workEl); } break; case 'p': case 'div': this.filterCommonBlocks(workEl); break; case 'br': this.filterLineBreak(workEl); break; } } } else { this.pasteHTML(text); } }, pasteHTML: function (html) { var elList, workEl, i, fragmentBody, pasteBlock = this.options.ownerDocument.createDocumentFragment(); pasteBlock.appendChild(this.options.ownerDocument.createElement('body')); fragmentBody = pasteBlock.querySelector('body'); fragmentBody.innerHTML = html; this.cleanupSpans(fragmentBody); elList = fragmentBody.querySelectorAll('*'); for (i = 0; i < elList.length; i += 1) { workEl = elList[i]; // delete ugly attributes workEl.removeAttribute('class'); workEl.removeAttribute('style'); workEl.removeAttribute('dir'); if (workEl.tagName.toLowerCase() === 'meta') { workEl.parentNode.removeChild(workEl); } } this.options.ownerDocument.execCommand('insertHTML', false, fragmentBody.innerHTML.replace(/ /g, ' ')); }, isCommonBlock: function (el) { return (el && (el.tagName.toLowerCase() === 'p' || el.tagName.toLowerCase() === 'div')); }, filterCommonBlocks: function (el) { if (/^\s*$/.test(el.textContent)) { el.parentNode.removeChild(el); } }, filterLineBreak: function (el) { if (this.isCommonBlock(el.previousElementSibling)) { // remove stray br's following common block elements el.parentNode.removeChild(el); } else if (this.isCommonBlock(el.parentNode) && (el.parentNode.firstChild === el || el.parentNode.lastChild === el)) { // remove br's just inside open or close tags of a div/p el.parentNode.removeChild(el); } else if (el.parentNode.childElementCount === 1) { // and br's that are the only child of a div/p this.removeWithParent(el); } }, // remove an element, including its parent, if it is the only element within its parent removeWithParent: function (el) { if (el && el.parentNode) { if (el.parentNode.parentNode && el.parentNode.childElementCount === 1) { el.parentNode.parentNode.removeChild(el.parentNode); } else { el.parentNode.removeChild(el.parentNode); } } }, cleanupSpans: function (container_el) { var i, el, new_el, spans = container_el.querySelectorAll('.replace-with'); for (i = 0; i < spans.length; i += 1) { el = spans[i]; new_el = this.options.ownerDocument.createElement(el.classList.contains('bold') ? 'b' : 'i'); if (el.classList.contains('bold') && el.classList.contains('italic')) { // add an i tag as well if this has both italics and bold new_el.innerHTML = '' + el.innerHTML + ''; } else { new_el.innerHTML = el.innerHTML; } el.parentNode.replaceChild(new_el, el); } spans = container_el.querySelectorAll('span'); for (i = 0; i < spans.length; i += 1) { el = spans[i]; // remove empty spans, replace others with their contents if (/^\s*$/.test()) { el.parentNode.removeChild(el); } else { el.parentNode.replaceChild(this.options.ownerDocument.createTextNode(el.textContent), el); } } } }; }(window, document)); /*! drop 0.5.4 */ /*! tether 0.6.5 */ (function(root, factory) { if (typeof define === 'function' && define.amd) { define(factory); } else if (typeof exports === 'object') { module.exports = factory(require,exports,module); } else { root.Tether = factory(); } }(this, function(require,exports,module) { (function() { var Evented, addClass, defer, deferred, extend, flush, getBounds, getOffsetParent, getOrigin, getScrollBarSize, getScrollParent, hasClass, node, removeClass, uniqueId, updateClasses, zeroPosCache, __hasProp = {}.hasOwnProperty, __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }, __slice = [].slice; if (this.Tether == null) { this.Tether = { modules: [] }; } getScrollParent = function(el) { var parent, position, scrollParent, style, _ref; position = getComputedStyle(el).position; if (position === 'fixed') { return el; } scrollParent = void 0; parent = el; while (parent = parent.parentNode) { try { style = getComputedStyle(parent); } catch (_error) {} if (style == null) { return parent; } if (/(auto|scroll)/.test(style['overflow'] + style['overflow-y'] + style['overflow-x'])) { if (position !== 'absolute' || ((_ref = style['position']) === 'relative' || _ref === 'absolute' || _ref === 'fixed')) { return parent; } } } return document.body; }; uniqueId = (function() { var id; id = 0; return function() { return id++; }; })(); zeroPosCache = {}; getOrigin = function(doc) { var id, k, node, v, _ref; node = doc._tetherZeroElement; if (node == null) { node = doc.createElement('div'); node.setAttribute('data-tether-id', uniqueId()); extend(node.style, { top: 0, left: 0, position: 'absolute' }); doc.body.appendChild(node); doc._tetherZeroElement = node; } id = node.getAttribute('data-tether-id'); if (zeroPosCache[id] == null) { zeroPosCache[id] = {}; _ref = node.getBoundingClientRect(); for (k in _ref) { v = _ref[k]; zeroPosCache[id][k] = v; } defer(function() { return zeroPosCache[id] = void 0; }); } return zeroPosCache[id]; }; node = null; getBounds = function(el) { var box, doc, docEl, k, origin, v, _ref; if (el === document) { doc = document; el = document.documentElement; } else { doc = el.ownerDocument; } docEl = doc.documentElement; box = {}; _ref = el.getBoundingClientRect(); for (k in _ref) { v = _ref[k]; box[k] = v; } origin = getOrigin(doc); box.top -= origin.top; box.left -= origin.left; if (box.width == null) { box.width = document.body.scrollWidth - box.left - box.right; } if (box.height == null) { box.height = document.body.scrollHeight - box.top - box.bottom; } box.top = box.top - docEl.clientTop; box.left = box.left - docEl.clientLeft; box.right = doc.body.clientWidth - box.width - box.left; box.bottom = doc.body.clientHeight - box.height - box.top; return box; }; getOffsetParent = function(el) { return el.offsetParent || document.documentElement; }; getScrollBarSize = function() { var inner, outer, width, widthContained, widthScroll; inner = document.createElement('div'); inner.style.width = '100%'; inner.style.height = '200px'; outer = document.createElement('div'); extend(outer.style, { position: 'absolute', top: 0, left: 0, pointerEvents: 'none', visibility: 'hidden', width: '200px', height: '150px', overflow: 'hidden' }); outer.appendChild(inner); document.body.appendChild(outer); widthContained = inner.offsetWidth; outer.style.overflow = 'scroll'; widthScroll = inner.offsetWidth; if (widthContained === widthScroll) { widthScroll = outer.clientWidth; } document.body.removeChild(outer); width = widthContained - widthScroll; return { width: width, height: width }; }; extend = function(out) { var args, key, obj, val, _i, _len, _ref; if (out == null) { out = {}; } args = []; Array.prototype.push.apply(args, arguments); _ref = args.slice(1); for (_i = 0, _len = _ref.length; _i < _len; _i++) { obj = _ref[_i]; if (obj) { for (key in obj) { if (!__hasProp.call(obj, key)) continue; val = obj[key]; out[key] = val; } } } return out; }; removeClass = function(el, name) { var cls, _i, _len, _ref, _results; if (el.classList != null) { _ref = name.split(' '); _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { cls = _ref[_i]; if (cls.trim()) { _results.push(el.classList.remove(cls)); } } return _results; } else { return el.className = el.className.replace(new RegExp("(^| )" + (name.split(' ').join('|')) + "( |$)", 'gi'), ' '); } }; addClass = function(el, name) { var cls, _i, _len, _ref, _results; if (el.classList != null) { _ref = name.split(' '); _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { cls = _ref[_i]; if (cls.trim()) { _results.push(el.classList.add(cls)); } } return _results; } else { removeClass(el, name); return el.className += " " + name; } }; hasClass = function(el, name) { if (el.classList != null) { return el.classList.contains(name); } else { return new RegExp("(^| )" + name + "( |$)", 'gi').test(el.className); } }; updateClasses = function(el, add, all) { var cls, _i, _j, _len, _len1, _results; for (_i = 0, _len = all.length; _i < _len; _i++) { cls = all[_i]; if (__indexOf.call(add, cls) < 0) { if (hasClass(el, cls)) { removeClass(el, cls); } } } _results = []; for (_j = 0, _len1 = add.length; _j < _len1; _j++) { cls = add[_j]; if (!hasClass(el, cls)) { _results.push(addClass(el, cls)); } else { _results.push(void 0); } } return _results; }; deferred = []; defer = function(fn) { return deferred.push(fn); }; flush = function() { var fn, _results; _results = []; while (fn = deferred.pop()) { _results.push(fn()); } return _results; }; Evented = (function() { function Evented() {} Evented.prototype.on = function(event, handler, ctx, once) { var _base; if (once == null) { once = false; } if (this.bindings == null) { this.bindings = {}; } if ((_base = this.bindings)[event] == null) { _base[event] = []; } return this.bindings[event].push({ handler: handler, ctx: ctx, once: once }); }; Evented.prototype.once = function(event, handler, ctx) { return this.on(event, handler, ctx, true); }; Evented.prototype.off = function(event, handler) { var i, _ref, _results; if (((_ref = this.bindings) != null ? _ref[event] : void 0) == null) { return; } if (handler == null) { return delete this.bindings[event]; } else { i = 0; _results = []; while (i < this.bindings[event].length) { if (this.bindings[event][i].handler === handler) { _results.push(this.bindings[event].splice(i, 1)); } else { _results.push(i++); } } return _results; } }; Evented.prototype.trigger = function() { var args, ctx, event, handler, i, once, _ref, _ref1, _results; event = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; if ((_ref = this.bindings) != null ? _ref[event] : void 0) { i = 0; _results = []; while (i < this.bindings[event].length) { _ref1 = this.bindings[event][i], handler = _ref1.handler, ctx = _ref1.ctx, once = _ref1.once; handler.apply(ctx != null ? ctx : this, args); if (once) { _results.push(this.bindings[event].splice(i, 1)); } else { _results.push(i++); } } return _results; } }; return Evented; })(); this.Tether.Utils = { getScrollParent: getScrollParent, getBounds: getBounds, getOffsetParent: getOffsetParent, extend: extend, addClass: addClass, removeClass: removeClass, hasClass: hasClass, updateClasses: updateClasses, defer: defer, flush: flush, uniqueId: uniqueId, Evented: Evented, getScrollBarSize: getScrollBarSize }; }).call(this); (function() { var MIRROR_LR, MIRROR_TB, OFFSET_MAP, Tether, addClass, addOffset, attachmentToOffset, autoToFixedAttachment, defer, extend, flush, getBounds, getOffsetParent, getOuterSize, getScrollBarSize, getScrollParent, getSize, now, offsetToPx, parseAttachment, parseOffset, position, removeClass, tethers, transformKey, updateClasses, within, _Tether, _ref, __slice = [].slice, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; if (this.Tether == null) { throw new Error("You must include the utils.js file before tether.js"); } Tether = this.Tether; _ref = Tether.Utils, getScrollParent = _ref.getScrollParent, getSize = _ref.getSize, getOuterSize = _ref.getOuterSize, getBounds = _ref.getBounds, getOffsetParent = _ref.getOffsetParent, extend = _ref.extend, addClass = _ref.addClass, removeClass = _ref.removeClass, updateClasses = _ref.updateClasses, defer = _ref.defer, flush = _ref.flush, getScrollBarSize = _ref.getScrollBarSize; within = function(a, b, diff) { if (diff == null) { diff = 1; } return (a + diff >= b && b >= a - diff); }; transformKey = (function() { var el, key, _i, _len, _ref1; el = document.createElement('div'); _ref1 = ['transform', 'webkitTransform', 'OTransform', 'MozTransform', 'msTransform']; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { key = _ref1[_i]; if (el.style[key] !== void 0) { return key; } } })(); tethers = []; position = function() { var tether, _i, _len; for (_i = 0, _len = tethers.length; _i < _len; _i++) { tether = tethers[_i]; tether.position(false); } return flush(); }; now = function() { var _ref1; return (_ref1 = typeof performance !== "undefined" && performance !== null ? typeof performance.now === "function" ? performance.now() : void 0 : void 0) != null ? _ref1 : +(new Date); }; (function() { var event, lastCall, lastDuration, pendingTimeout, tick, _i, _len, _ref1, _results; lastCall = null; lastDuration = null; pendingTimeout = null; tick = function() { if ((lastDuration != null) && lastDuration > 16) { lastDuration = Math.min(lastDuration - 16, 250); pendingTimeout = setTimeout(tick, 250); return; } if ((lastCall != null) && (now() - lastCall) < 10) { return; } if (pendingTimeout != null) { clearTimeout(pendingTimeout); pendingTimeout = null; } lastCall = now(); position(); return lastDuration = now() - lastCall; }; _ref1 = ['resize', 'scroll', 'touchmove']; _results = []; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { event = _ref1[_i]; _results.push(window.addEventListener(event, tick)); } return _results; })(); MIRROR_LR = { center: 'center', left: 'right', right: 'left' }; MIRROR_TB = { middle: 'middle', top: 'bottom', bottom: 'top' }; OFFSET_MAP = { top: 0, left: 0, middle: '50%', center: '50%', bottom: '100%', right: '100%' }; autoToFixedAttachment = function(attachment, relativeToAttachment) { var left, top; left = attachment.left, top = attachment.top; if (left === 'auto') { left = MIRROR_LR[relativeToAttachment.left]; } if (top === 'auto') { top = MIRROR_TB[relativeToAttachment.top]; } return { left: left, top: top }; }; attachmentToOffset = function(attachment) { var _ref1, _ref2; return { left: (_ref1 = OFFSET_MAP[attachment.left]) != null ? _ref1 : attachment.left, top: (_ref2 = OFFSET_MAP[attachment.top]) != null ? _ref2 : attachment.top }; }; addOffset = function() { var left, offsets, out, top, _i, _len, _ref1; offsets = 1 <= arguments.length ? __slice.call(arguments, 0) : []; out = { top: 0, left: 0 }; for (_i = 0, _len = offsets.length; _i < _len; _i++) { _ref1 = offsets[_i], top = _ref1.top, left = _ref1.left; if (typeof top === 'string') { top = parseFloat(top, 10); } if (typeof left === 'string') { left = parseFloat(left, 10); } out.top += top; out.left += left; } return out; }; offsetToPx = function(offset, size) { if (typeof offset.left === 'string' && offset.left.indexOf('%') !== -1) { offset.left = parseFloat(offset.left, 10) / 100 * size.width; } if (typeof offset.top === 'string' && offset.top.indexOf('%') !== -1) { offset.top = parseFloat(offset.top, 10) / 100 * size.height; } return offset; }; parseAttachment = parseOffset = function(value) { var left, top, _ref1; _ref1 = value.split(' '), top = _ref1[0], left = _ref1[1]; return { top: top, left: left }; }; _Tether = (function() { _Tether.modules = []; function _Tether(options) { this.position = __bind(this.position, this); var module, _i, _len, _ref1, _ref2; tethers.push(this); this.history = []; this.setOptions(options, false); _ref1 = Tether.modules; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { module = _ref1[_i]; if ((_ref2 = module.initialize) != null) { _ref2.call(this); } } this.position(); } _Tether.prototype.getClass = function(key) { var _ref1, _ref2; if ((_ref1 = this.options.classes) != null ? _ref1[key] : void 0) { return this.options.classes[key]; } else if (((_ref2 = this.options.classes) != null ? _ref2[key] : void 0) !== false) { if (this.options.classPrefix) { return "" + this.options.classPrefix + "-" + key; } else { return key; } } else { return ''; } }; _Tether.prototype.setOptions = function(options, position) { var defaults, key, _i, _len, _ref1, _ref2; this.options = options; if (position == null) { position = true; } defaults = { offset: '0 0', targetOffset: '0 0', targetAttachment: 'auto auto', classPrefix: 'tether' }; this.options = extend(defaults, this.options); _ref1 = this.options, this.element = _ref1.element, this.target = _ref1.target, this.targetModifier = _ref1.targetModifier; if (this.target === 'viewport') { this.target = document.body; this.targetModifier = 'visible'; } else if (this.target === 'scroll-handle') { this.target = document.body; this.targetModifier = 'scroll-handle'; } _ref2 = ['element', 'target']; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { key = _ref2[_i]; if (this[key] == null) { throw new Error("Tether Error: Both element and target must be defined"); } if (this[key].jquery != null) { this[key] = this[key][0]; } else if (typeof this[key] === 'string') { this[key] = document.querySelector(this[key]); } } addClass(this.element, this.getClass('element')); addClass(this.target, this.getClass('target')); if (!this.options.attachment) { throw new Error("Tether Error: You must provide an attachment"); } this.targetAttachment = parseAttachment(this.options.targetAttachment); this.attachment = parseAttachment(this.options.attachment); this.offset = parseOffset(this.options.offset); this.targetOffset = parseOffset(this.options.targetOffset); if (this.scrollParent != null) { this.disable(); } if (this.targetModifier === 'scroll-handle') { this.scrollParent = this.target; } else { this.scrollParent = getScrollParent(this.target); } if (this.options.enabled !== false) { return this.enable(position); } }; _Tether.prototype.getTargetBounds = function() { var bounds, fitAdj, hasBottomScroll, height, out, scrollBottom, scrollPercentage, style, target; if (this.targetModifier != null) { switch (this.targetModifier) { case 'visible': if (this.target === document.body) { return { top: pageYOffset, left: pageXOffset, height: innerHeight, width: innerWidth }; } else { bounds = getBounds(this.target); out = { height: bounds.height, width: bounds.width, top: bounds.top, left: bounds.left }; out.height = Math.min(out.height, bounds.height - (pageYOffset - bounds.top)); out.height = Math.min(out.height, bounds.height - ((bounds.top + bounds.height) - (pageYOffset + innerHeight))); out.height = Math.min(innerHeight, out.height); out.height -= 2; out.width = Math.min(out.width, bounds.width - (pageXOffset - bounds.left)); out.width = Math.min(out.width, bounds.width - ((bounds.left + bounds.width) - (pageXOffset + innerWidth))); out.width = Math.min(innerWidth, out.width); out.width -= 2; if (out.top < pageYOffset) { out.top = pageYOffset; } if (out.left < pageXOffset) { out.left = pageXOffset; } return out; } break; case 'scroll-handle': target = this.target; if (target === document.body) { target = document.documentElement; bounds = { left: pageXOffset, top: pageYOffset, height: innerHeight, width: innerWidth }; } else { bounds = getBounds(target); } style = getComputedStyle(target); hasBottomScroll = target.scrollWidth > target.clientWidth || 'scroll' === [style.overflow, style.overflowX] || this.target !== document.body; scrollBottom = 0; if (hasBottomScroll) { scrollBottom = 15; } height = bounds.height - parseFloat(style.borderTopWidth) - parseFloat(style.borderBottomWidth) - scrollBottom; out = { width: 15, height: height * 0.975 * (height / target.scrollHeight), left: bounds.left + bounds.width - parseFloat(style.borderLeftWidth) - 15 }; fitAdj = 0; if (height < 408 && this.target === document.body) { fitAdj = -0.00011 * Math.pow(height, 2) - 0.00727 * height + 22.58; } if (this.target !== document.body) { out.height = Math.max(out.height, 24); } scrollPercentage = this.target.scrollTop / (target.scrollHeight - height); out.top = scrollPercentage * (height - out.height - fitAdj) + bounds.top + parseFloat(style.borderTopWidth); if (this.target === document.body) { out.height = Math.max(out.height, 24); } return out; } } else { return getBounds(this.target); } }; _Tether.prototype.clearCache = function() { return this._cache = {}; }; _Tether.prototype.cache = function(k, getter) { if (this._cache == null) { this._cache = {}; } if (this._cache[k] == null) { this._cache[k] = getter.call(this); } return this._cache[k]; }; _Tether.prototype.enable = function(position) { if (position == null) { position = true; } addClass(this.target, this.getClass('enabled')); addClass(this.element, this.getClass('enabled')); this.enabled = true; if (this.scrollParent !== document) { this.scrollParent.addEventListener('scroll', this.position); } if (position) { return this.position(); } }; _Tether.prototype.disable = function() { removeClass(this.target, this.getClass('enabled')); removeClass(this.element, this.getClass('enabled')); this.enabled = false; if (this.scrollParent != null) { return this.scrollParent.removeEventListener('scroll', this.position); } }; _Tether.prototype.destroy = function() { var i, tether, _i, _len, _results; this.disable(); _results = []; for (i = _i = 0, _len = tethers.length; _i < _len; i = ++_i) { tether = tethers[i]; if (tether === this) { tethers.splice(i, 1); break; } else { _results.push(void 0); } } return _results; }; _Tether.prototype.updateAttachClasses = function(elementAttach, targetAttach) { var add, all, side, sides, _i, _j, _len, _len1, _ref1, _this = this; if (elementAttach == null) { elementAttach = this.attachment; } if (targetAttach == null) { targetAttach = this.targetAttachment; } sides = ['left', 'top', 'bottom', 'right', 'middle', 'center']; if ((_ref1 = this._addAttachClasses) != null ? _ref1.length : void 0) { this._addAttachClasses.splice(0, this._addAttachClasses.length); } add = this._addAttachClasses != null ? this._addAttachClasses : this._addAttachClasses = []; if (elementAttach.top) { add.push("" + (this.getClass('element-attached')) + "-" + elementAttach.top); } if (elementAttach.left) { add.push("" + (this.getClass('element-attached')) + "-" + elementAttach.left); } if (targetAttach.top) { add.push("" + (this.getClass('target-attached')) + "-" + targetAttach.top); } if (targetAttach.left) { add.push("" + (this.getClass('target-attached')) + "-" + targetAttach.left); } all = []; for (_i = 0, _len = sides.length; _i < _len; _i++) { side = sides[_i]; all.push("" + (this.getClass('element-attached')) + "-" + side); } for (_j = 0, _len1 = sides.length; _j < _len1; _j++) { side = sides[_j]; all.push("" + (this.getClass('target-attached')) + "-" + side); } return defer(function() { if (_this._addAttachClasses == null) { return; } updateClasses(_this.element, _this._addAttachClasses, all); updateClasses(_this.target, _this._addAttachClasses, all); return _this._addAttachClasses = void 0; }); }; _Tether.prototype.position = function(flushChanges) { var elementPos, elementStyle, height, left, manualOffset, manualTargetOffset, module, next, offset, offsetBorder, offsetParent, offsetParentSize, offsetParentStyle, offsetPosition, ret, scrollLeft, scrollTop, scrollbarSize, side, targetAttachment, targetOffset, targetPos, targetSize, top, width, _i, _j, _len, _len1, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _this = this; if (flushChanges == null) { flushChanges = true; } if (!this.enabled) { return; } this.clearCache(); targetAttachment = autoToFixedAttachment(this.targetAttachment, this.attachment); this.updateAttachClasses(this.attachment, targetAttachment); elementPos = this.cache('element-bounds', function() { return getBounds(_this.element); }); width = elementPos.width, height = elementPos.height; if (width === 0 && height === 0 && (this.lastSize != null)) { _ref1 = this.lastSize, width = _ref1.width, height = _ref1.height; } else { this.lastSize = { width: width, height: height }; } targetSize = targetPos = this.cache('target-bounds', function() { return _this.getTargetBounds(); }); offset = offsetToPx(attachmentToOffset(this.attachment), { width: width, height: height }); targetOffset = offsetToPx(attachmentToOffset(targetAttachment), targetSize); manualOffset = offsetToPx(this.offset, { width: width, height: height }); manualTargetOffset = offsetToPx(this.targetOffset, targetSize); offset = addOffset(offset, manualOffset); targetOffset = addOffset(targetOffset, manualTargetOffset); left = targetPos.left + targetOffset.left - offset.left; top = targetPos.top + targetOffset.top - offset.top; _ref2 = Tether.modules; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { module = _ref2[_i]; ret = module.position.call(this, { left: left, top: top, targetAttachment: targetAttachment, targetPos: targetPos, attachment: this.attachment, elementPos: elementPos, offset: offset, targetOffset: targetOffset, manualOffset: manualOffset, manualTargetOffset: manualTargetOffset, scrollbarSize: scrollbarSize }); if ((ret == null) || typeof ret !== 'object') { continue; } else if (ret === false) { return false; } else { top = ret.top, left = ret.left; } } next = { page: { top: top, left: left }, viewport: { top: top - pageYOffset, bottom: pageYOffset - top - height + innerHeight, left: left - pageXOffset, right: pageXOffset - left - width + innerWidth } }; if (document.body.scrollWidth > window.innerWidth) { scrollbarSize = this.cache('scrollbar-size', getScrollBarSize); next.viewport.bottom -= scrollbarSize.height; } if (document.body.scrollHeight > window.innerHeight) { scrollbarSize = this.cache('scrollbar-size', getScrollBarSize); next.viewport.right -= scrollbarSize.width; } if (((_ref3 = document.body.style.position) !== '' && _ref3 !== 'static') || ((_ref4 = document.body.parentElement.style.position) !== '' && _ref4 !== 'static')) { next.page.bottom = document.body.scrollHeight - top - height; next.page.right = document.body.scrollWidth - left - width; } if (((_ref5 = this.options.optimizations) != null ? _ref5.moveElement : void 0) !== false && (this.targetModifier == null)) { offsetParent = this.cache('target-offsetparent', function() { return getOffsetParent(_this.target); }); offsetPosition = this.cache('target-offsetparent-bounds', function() { return getBounds(offsetParent); }); offsetParentStyle = getComputedStyle(offsetParent); elementStyle = getComputedStyle(this.element); offsetParentSize = offsetPosition; offsetBorder = {}; _ref6 = ['Top', 'Left', 'Bottom', 'Right']; for (_j = 0, _len1 = _ref6.length; _j < _len1; _j++) { side = _ref6[_j]; offsetBorder[side.toLowerCase()] = parseFloat(offsetParentStyle["border" + side + "Width"]); } offsetPosition.right = document.body.scrollWidth - offsetPosition.left - offsetParentSize.width + offsetBorder.right; offsetPosition.bottom = document.body.scrollHeight - offsetPosition.top - offsetParentSize.height + offsetBorder.bottom; if (next.page.top >= (offsetPosition.top + offsetBorder.top) && next.page.bottom >= offsetPosition.bottom) { if (next.page.left >= (offsetPosition.left + offsetBorder.left) && next.page.right >= offsetPosition.right) { scrollTop = offsetParent.scrollTop; scrollLeft = offsetParent.scrollLeft; next.offset = { top: next.page.top - offsetPosition.top + scrollTop - offsetBorder.top, left: next.page.left - offsetPosition.left + scrollLeft - offsetBorder.left }; } } } this.move(next); this.history.unshift(next); if (this.history.length > 3) { this.history.pop(); } if (flushChanges) { flush(); } return true; }; _Tether.prototype.move = function(position) { var css, elVal, found, key, moved, offsetParent, point, same, transcribe, type, val, write, writeCSS, _i, _len, _ref1, _ref2, _this = this; if (this.element.parentNode == null) { return; } same = {}; for (type in position) { same[type] = {}; for (key in position[type]) { found = false; _ref1 = this.history; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { point = _ref1[_i]; if (!within((_ref2 = point[type]) != null ? _ref2[key] : void 0, position[type][key])) { found = true; break; } } if (!found) { same[type][key] = true; } } } css = { top: '', left: '', right: '', bottom: '' }; transcribe = function(same, pos) { var xPos, yPos, _ref3; if (((_ref3 = _this.options.optimizations) != null ? _ref3.gpu : void 0) !== false) { if (same.top) { css.top = 0; yPos = pos.top; } else { css.bottom = 0; yPos = -pos.bottom; } if (same.left) { css.left = 0; xPos = pos.left; } else { css.right = 0; xPos = -pos.right; } css[transformKey] = "translateX(" + (Math.round(xPos)) + "px) translateY(" + (Math.round(yPos)) + "px)"; if (transformKey !== 'msTransform') { return css[transformKey] += " translateZ(0)"; } } else { if (same.top) { css.top = "" + pos.top + "px"; } else { css.bottom = "" + pos.bottom + "px"; } if (same.left) { return css.left = "" + pos.left + "px"; } else { return css.right = "" + pos.right + "px"; } } }; moved = false; if ((same.page.top || same.page.bottom) && (same.page.left || same.page.right)) { css.position = 'absolute'; transcribe(same.page, position.page); } else if ((same.viewport.top || same.viewport.bottom) && (same.viewport.left || same.viewport.right)) { css.position = 'fixed'; transcribe(same.viewport, position.viewport); } else if ((same.offset != null) && same.offset.top && same.offset.left) { css.position = 'absolute'; offsetParent = this.cache('target-offsetparent', function() { return getOffsetParent(_this.target); }); if (getOffsetParent(this.element) !== offsetParent) { defer(function() { _this.element.parentNode.removeChild(_this.element); return offsetParent.appendChild(_this.element); }); } transcribe(same.offset, position.offset); moved = true; } else { css.position = 'absolute'; transcribe({ top: true, left: true }, position.page); } if (!moved && this.element.parentNode.tagName !== 'BODY') { this.element.parentNode.removeChild(this.element); document.body.appendChild(this.element); } writeCSS = {}; write = false; for (key in css) { val = css[key]; elVal = this.element.style[key]; if (elVal !== '' && val !== '' && (key === 'top' || key === 'left' || key === 'bottom' || key === 'right')) { elVal = parseFloat(elVal); val = parseFloat(val); } if (elVal !== val) { write = true; writeCSS[key] = css[key]; } } if (write) { return defer(function() { return extend(_this.element.style, writeCSS); }); } }; return _Tether; })(); Tether.position = position; this.Tether = extend(_Tether, Tether); }).call(this); (function() { var BOUNDS_FORMAT, MIRROR_ATTACH, defer, extend, getBoundingRect, getBounds, getOuterSize, getSize, updateClasses, _ref, __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; _ref = this.Tether.Utils, getOuterSize = _ref.getOuterSize, getBounds = _ref.getBounds, getSize = _ref.getSize, extend = _ref.extend, updateClasses = _ref.updateClasses, defer = _ref.defer; MIRROR_ATTACH = { left: 'right', right: 'left', top: 'bottom', bottom: 'top', middle: 'middle' }; BOUNDS_FORMAT = ['left', 'top', 'right', 'bottom']; getBoundingRect = function(tether, to) { var i, pos, side, size, style, _i, _len; if (to === 'scrollParent') { to = tether.scrollParent; } else if (to === 'window') { to = [pageXOffset, pageYOffset, innerWidth + pageXOffset, innerHeight + pageYOffset]; } if (to === document) { to = to.documentElement; } if (to.nodeType != null) { pos = size = getBounds(to); style = getComputedStyle(to); to = [pos.left, pos.top, size.width + pos.left, size.height + pos.top]; for (i = _i = 0, _len = BOUNDS_FORMAT.length; _i < _len; i = ++_i) { side = BOUNDS_FORMAT[i]; side = side[0].toUpperCase() + side.substr(1); if (side === 'Top' || side === 'Left') { to[i] += parseFloat(style["border" + side + "Width"]); } else { to[i] -= parseFloat(style["border" + side + "Width"]); } } } return to; }; this.Tether.modules.push({ position: function(_arg) { var addClasses, allClasses, attachment, bounds, changeAttachX, changeAttachY, cls, constraint, eAttachment, height, left, oob, oobClass, p, pin, pinned, pinnedClass, removeClass, side, tAttachment, targetAttachment, targetHeight, targetSize, targetWidth, to, top, width, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _len5, _m, _n, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8, _this = this; top = _arg.top, left = _arg.left, targetAttachment = _arg.targetAttachment; if (!this.options.constraints) { return true; } removeClass = function(prefix) { var side, _i, _len, _results; _this.removeClass(prefix); _results = []; for (_i = 0, _len = BOUNDS_FORMAT.length; _i < _len; _i++) { side = BOUNDS_FORMAT[_i]; _results.push(_this.removeClass("" + prefix + "-" + side)); } return _results; }; _ref1 = this.cache('element-bounds', function() { return getBounds(_this.element); }), height = _ref1.height, width = _ref1.width; if (width === 0 && height === 0 && (this.lastSize != null)) { _ref2 = this.lastSize, width = _ref2.width, height = _ref2.height; } targetSize = this.cache('target-bounds', function() { return _this.getTargetBounds(); }); targetHeight = targetSize.height; targetWidth = targetSize.width; tAttachment = {}; eAttachment = {}; allClasses = [this.getClass('pinned'), this.getClass('out-of-bounds')]; _ref3 = this.options.constraints; for (_i = 0, _len = _ref3.length; _i < _len; _i++) { constraint = _ref3[_i]; if (constraint.outOfBoundsClass) { allClasses.push(constraint.outOfBoundsClass); } if (constraint.pinnedClass) { allClasses.push(constraint.pinnedClass); } } for (_j = 0, _len1 = allClasses.length; _j < _len1; _j++) { cls = allClasses[_j]; _ref4 = ['left', 'top', 'right', 'bottom']; for (_k = 0, _len2 = _ref4.length; _k < _len2; _k++) { side = _ref4[_k]; allClasses.push("" + cls + "-" + side); } } addClasses = []; tAttachment = extend({}, targetAttachment); eAttachment = extend({}, this.attachment); _ref5 = this.options.constraints; for (_l = 0, _len3 = _ref5.length; _l < _len3; _l++) { constraint = _ref5[_l]; to = constraint.to, attachment = constraint.attachment, pin = constraint.pin; if (attachment == null) { attachment = ''; } if (__indexOf.call(attachment, ' ') >= 0) { _ref6 = attachment.split(' '), changeAttachY = _ref6[0], changeAttachX = _ref6[1]; } else { changeAttachX = changeAttachY = attachment; } bounds = getBoundingRect(this, to); if (changeAttachY === 'target' || changeAttachY === 'both') { if (top < bounds[1] && tAttachment.top === 'top') { top += targetHeight; tAttachment.top = 'bottom'; } if (top + height > bounds[3] && tAttachment.top === 'bottom') { top -= targetHeight; tAttachment.top = 'top'; } } if (changeAttachY === 'together') { if (top < bounds[1] && tAttachment.top === 'top') { if (eAttachment.top === 'bottom') { top += targetHeight; tAttachment.top = 'bottom'; top += height; eAttachment.top = 'top'; } else if (eAttachment.top === 'top') { top += targetHeight; tAttachment.top = 'bottom'; top -= height; eAttachment.top = 'bottom'; } } if (top + height > bounds[3] && tAttachment.top === 'bottom') { if (eAttachment.top === 'top') { top -= targetHeight; tAttachment.top = 'top'; top -= height; eAttachment.top = 'bottom'; } else if (eAttachment.top === 'bottom') { top -= targetHeight; tAttachment.top = 'top'; top += height; eAttachment.top = 'top'; } } if (tAttachment.top === 'middle') { if (top + height > bounds[3] && eAttachment.top === 'top') { top -= height; eAttachment.top = 'bottom'; } else if (top < bounds[1] && eAttachment.top === 'bottom') { top += height; eAttachment.top = 'top'; } } } if (changeAttachX === 'target' || changeAttachX === 'both') { if (left < bounds[0] && tAttachment.left === 'left') { left += targetWidth; tAttachment.left = 'right'; } if (left + width > bounds[2] && tAttachment.left === 'right') { left -= targetWidth; tAttachment.left = 'left'; } } if (changeAttachX === 'together') { if (left < bounds[0] && tAttachment.left === 'left') { if (eAttachment.left === 'right') { left += targetWidth; tAttachment.left = 'right'; left += width; eAttachment.left = 'left'; } else if (eAttachment.left === 'left') { left += targetWidth; tAttachment.left = 'right'; left -= width; eAttachment.left = 'right'; } } else if (left + width > bounds[2] && tAttachment.left === 'right') { if (eAttachment.left === 'left') { left -= targetWidth; tAttachment.left = 'left'; left -= width; eAttachment.left = 'right'; } else if (eAttachment.left === 'right') { left -= targetWidth; tAttachment.left = 'left'; left += width; eAttachment.left = 'left'; } } else if (tAttachment.left === 'center') { if (left + width > bounds[2] && eAttachment.left === 'left') { left -= width; eAttachment.left = 'right'; } else if (left < bounds[0] && eAttachment.left === 'right') { left += width; eAttachment.left = 'left'; } } } if (changeAttachY === 'element' || changeAttachY === 'both') { if (top < bounds[1] && eAttachment.top === 'bottom') { top += height; eAttachment.top = 'top'; } if (top + height > bounds[3] && eAttachment.top === 'top') { top -= height; eAttachment.top = 'bottom'; } } if (changeAttachX === 'element' || changeAttachX === 'both') { if (left < bounds[0] && eAttachment.left === 'right') { left += width; eAttachment.left = 'left'; } if (left + width > bounds[2] && eAttachment.left === 'left') { left -= width; eAttachment.left = 'right'; } } if (typeof pin === 'string') { pin = (function() { var _len4, _m, _ref7, _results; _ref7 = pin.split(','); _results = []; for (_m = 0, _len4 = _ref7.length; _m < _len4; _m++) { p = _ref7[_m]; _results.push(p.trim()); } return _results; })(); } else if (pin === true) { pin = ['top', 'left', 'right', 'bottom']; } pin || (pin = []); pinned = []; oob = []; if (top < bounds[1]) { if (__indexOf.call(pin, 'top') >= 0) { top = bounds[1]; pinned.push('top'); } else { oob.push('top'); } } if (top + height > bounds[3]) { if (__indexOf.call(pin, 'bottom') >= 0) { top = bounds[3] - height; pinned.push('bottom'); } else { oob.push('bottom'); } } if (left < bounds[0]) { if (__indexOf.call(pin, 'left') >= 0) { left = bounds[0]; pinned.push('left'); } else { oob.push('left'); } } if (left + width > bounds[2]) { if (__indexOf.call(pin, 'right') >= 0) { left = bounds[2] - width; pinned.push('right'); } else { oob.push('right'); } } if (pinned.length) { pinnedClass = (_ref7 = this.options.pinnedClass) != null ? _ref7 : this.getClass('pinned'); addClasses.push(pinnedClass); for (_m = 0, _len4 = pinned.length; _m < _len4; _m++) { side = pinned[_m]; addClasses.push("" + pinnedClass + "-" + side); } } if (oob.length) { oobClass = (_ref8 = this.options.outOfBoundsClass) != null ? _ref8 : this.getClass('out-of-bounds'); addClasses.push(oobClass); for (_n = 0, _len5 = oob.length; _n < _len5; _n++) { side = oob[_n]; addClasses.push("" + oobClass + "-" + side); } } if (__indexOf.call(pinned, 'left') >= 0 || __indexOf.call(pinned, 'right') >= 0) { eAttachment.left = tAttachment.left = false; } if (__indexOf.call(pinned, 'top') >= 0 || __indexOf.call(pinned, 'bottom') >= 0) { eAttachment.top = tAttachment.top = false; } if (tAttachment.top !== targetAttachment.top || tAttachment.left !== targetAttachment.left || eAttachment.top !== this.attachment.top || eAttachment.left !== this.attachment.left) { this.updateAttachClasses(eAttachment, tAttachment); } } defer(function() { updateClasses(_this.target, addClasses, allClasses); return updateClasses(_this.element, addClasses, allClasses); }); return { top: top, left: left }; } }); }).call(this); (function() { var defer, getBounds, updateClasses, _ref; _ref = this.Tether.Utils, getBounds = _ref.getBounds, updateClasses = _ref.updateClasses, defer = _ref.defer; this.Tether.modules.push({ position: function(_arg) { var abutted, addClasses, allClasses, bottom, height, left, right, side, sides, targetPos, top, width, _i, _j, _k, _l, _len, _len1, _len2, _len3, _ref1, _ref2, _ref3, _ref4, _ref5, _this = this; top = _arg.top, left = _arg.left; _ref1 = this.cache('element-bounds', function() { return getBounds(_this.element); }), height = _ref1.height, width = _ref1.width; targetPos = this.getTargetBounds(); bottom = top + height; right = left + width; abutted = []; if (top <= targetPos.bottom && bottom >= targetPos.top) { _ref2 = ['left', 'right']; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { side = _ref2[_i]; if ((_ref3 = targetPos[side]) === left || _ref3 === right) { abutted.push(side); } } } if (left <= targetPos.right && right >= targetPos.left) { _ref4 = ['top', 'bottom']; for (_j = 0, _len1 = _ref4.length; _j < _len1; _j++) { side = _ref4[_j]; if ((_ref5 = targetPos[side]) === top || _ref5 === bottom) { abutted.push(side); } } } allClasses = []; addClasses = []; sides = ['left', 'top', 'right', 'bottom']; allClasses.push(this.getClass('abutted')); for (_k = 0, _len2 = sides.length; _k < _len2; _k++) { side = sides[_k]; allClasses.push("" + (this.getClass('abutted')) + "-" + side); } if (abutted.length) { addClasses.push(this.getClass('abutted')); } for (_l = 0, _len3 = abutted.length; _l < _len3; _l++) { side = abutted[_l]; addClasses.push("" + (this.getClass('abutted')) + "-" + side); } defer(function() { updateClasses(_this.target, addClasses, allClasses); return updateClasses(_this.element, addClasses, allClasses); }); return true; } }); }).call(this); (function() { this.Tether.modules.push({ position: function(_arg) { var left, result, shift, shiftLeft, shiftTop, top, _ref; top = _arg.top, left = _arg.left; if (!this.options.shift) { return; } result = function(val) { if (typeof val === 'function') { return val.call(this, { top: top, left: left }); } else { return val; } }; shift = result(this.options.shift); if (typeof shift === 'string') { shift = shift.split(' '); shift[1] || (shift[1] = shift[0]); shiftTop = shift[0], shiftLeft = shift[1]; shiftTop = parseFloat(shiftTop, 10); shiftLeft = parseFloat(shiftLeft, 10); } else { _ref = [shift.top, shift.left], shiftTop = _ref[0], shiftLeft = _ref[1]; } top += shiftTop; left += shiftLeft; return { top: top, left: left }; } }); }).call(this); return this.Tether; })); (function() { var Evented, MIRROR_ATTACH, addClass, allDrops, clickEvents, createContext, extend, hasClass, removeClass, removeFromArray, sortAttach, touchDevice, _ref, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; _ref = Tether.Utils, extend = _ref.extend, addClass = _ref.addClass, removeClass = _ref.removeClass, hasClass = _ref.hasClass, Evented = _ref.Evented; touchDevice = 'ontouchstart' in document.documentElement; clickEvents = ['click']; if (touchDevice) { clickEvents.push('touchstart'); } sortAttach = function(str) { var first, second, _ref1, _ref2; _ref1 = str.split(' '), first = _ref1[0], second = _ref1[1]; if (first === 'left' || first === 'right') { _ref2 = [second, first], first = _ref2[0], second = _ref2[1]; } return [first, second].join(' '); }; MIRROR_ATTACH = { left: 'right', right: 'left', top: 'bottom', bottom: 'top', middle: 'middle', center: 'center' }; allDrops = {}; removeFromArray = function(arr, item) { var index, _results; _results = []; while ((index = arr.indexOf(item)) !== -1) { _results.push(arr.splice(index, 1)); } return _results; }; createContext = function(options) { var DropInstance, defaultOptions, drop, _name; if (options == null) { options = {}; } drop = function() { return (function(func, args, ctor) { ctor.prototype = func.prototype; var child = new ctor, result = func.apply(child, args); return Object(result) === result ? result : child; })(DropInstance, arguments, function(){}); }; extend(drop, { createContext: createContext, drops: [], defaults: {} }); defaultOptions = { classPrefix: 'drop', defaults: { position: 'bottom left', openOn: 'click', constrainToScrollParent: true, constrainToWindow: true, classes: '', remove: false, tetherOptions: {} } }; extend(drop, defaultOptions, options); extend(drop.defaults, defaultOptions.defaults, options.defaults); if (allDrops[_name = drop.classPrefix] == null) { allDrops[_name] = []; } drop.updateBodyClasses = function() { var anyOpen, _drop, _i, _len, _ref1; anyOpen = false; _ref1 = allDrops[drop.classPrefix]; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { _drop = _ref1[_i]; if (!(_drop.isOpened())) { continue; } anyOpen = true; break; } if (anyOpen) { return addClass(document.body, "" + drop.classPrefix + "-open"); } else { return removeClass(document.body, "" + drop.classPrefix + "-open"); } }; DropInstance = (function(_super) { __extends(DropInstance, _super); function DropInstance(options) { this.options = options; this.options = extend({}, drop.defaults, this.options); this.target = this.options.target; if (this.target == null) { throw new Error('Drop Error: You must provide a target.'); } if (this.options.classes) { addClass(this.target, this.options.classes); } drop.drops.push(this); allDrops[drop.classPrefix].push(this); this._boundEvents = []; this.setupElements(); this.setupEvents(); this.setupTether(); } DropInstance.prototype._on = function(element, event, handler) { this._boundEvents.push({ element: element, event: event, handler: handler }); return element.addEventListener(event, handler); }; DropInstance.prototype.setupElements = function() { this.drop = document.createElement('div'); addClass(this.drop, drop.classPrefix); if (this.options.classes) { addClass(this.drop, this.options.classes); } this.content = document.createElement('div'); addClass(this.content, "" + drop.classPrefix + "-content"); if (typeof this.options.content === 'object') { this.content.appendChild(this.options.content); } else { this.content.innerHTML = this.options.content; } return this.drop.appendChild(this.content); }; DropInstance.prototype.setupTether = function() { var constraints, dropAttach; dropAttach = this.options.position.split(' '); dropAttach[0] = MIRROR_ATTACH[dropAttach[0]]; dropAttach = dropAttach.join(' '); constraints = []; if (this.options.constrainToScrollParent) { constraints.push({ to: 'scrollParent', pin: 'top, bottom', attachment: 'together none' }); } else { constraints.push({ to: 'scrollParent' }); } if (this.options.constrainToWindow !== false) { constraints.push({ to: 'window', attachment: 'together' }); } else { constraints.push({ to: 'window' }); } options = { element: this.drop, target: this.target, attachment: sortAttach(dropAttach), targetAttachment: sortAttach(this.options.position), classPrefix: drop.classPrefix, offset: '0 0', targetOffset: '0 0', enabled: false, constraints: constraints }; if (this.options.tetherOptions !== false) { return this.tether = new Tether(extend({}, options, this.options.tetherOptions)); } }; DropInstance.prototype.setupEvents = function() { var clickEvent, closeHandler, events, onUs, openHandler, out, outTimeout, over, _i, _len, _this = this; if (!this.options.openOn) { return; } if (this.options.openOn === 'always') { setTimeout(this.open.bind(this)); return; } events = this.options.openOn.split(' '); if (__indexOf.call(events, 'click') >= 0) { openHandler = function(event) { _this.toggle(); return event.preventDefault(); }; closeHandler = function(event) { if (!_this.isOpened()) { return; } if (event.target === _this.drop || _this.drop.contains(event.target)) { return; } if (event.target === _this.target || _this.target.contains(event.target)) { return; } return _this.close(); }; for (_i = 0, _len = clickEvents.length; _i < _len; _i++) { clickEvent = clickEvents[_i]; this._on(this.target, clickEvent, openHandler); this._on(document, clickEvent, closeHandler); } } if (__indexOf.call(events, 'hover') >= 0) { onUs = false; over = function() { onUs = true; return _this.open(); }; outTimeout = null; out = function() { onUs = false; if (outTimeout != null) { clearTimeout(outTimeout); } return outTimeout = setTimeout(function() { if (!onUs) { _this.close(); } return outTimeout = null; }, 50); }; this._on(this.target, 'mouseover', over); this._on(this.drop, 'mouseover', over); this._on(this.target, 'mouseout', out); return this._on(this.drop, 'mouseout', out); } }; DropInstance.prototype.isOpened = function() { if (this.drop) { return hasClass(this.drop, "" + drop.classPrefix + "-open"); } }; DropInstance.prototype.toggle = function() { if (this.isOpened()) { return this.close(); } else { return this.open(); } }; DropInstance.prototype.open = function() { var _ref1, _ref2, _this = this; if (this.isOpened()) { return; } if (!this.drop.parentNode) { document.body.appendChild(this.drop); } if ((_ref1 = this.tether) != null) { _ref1.enable(); } addClass(this.drop, "" + drop.classPrefix + "-open"); addClass(this.drop, "" + drop.classPrefix + "-open-transitionend"); setTimeout(function() { return addClass(_this.drop, "" + drop.classPrefix + "-after-open"); }); if ((_ref2 = this.tether) != null) { _ref2.position(); } this.trigger('open'); return drop.updateBodyClasses(); }; DropInstance.prototype.close = function() { var handler, _ref1, _this = this; if (!this.isOpened()) { return; } removeClass(this.drop, "" + drop.classPrefix + "-open"); removeClass(this.drop, "" + drop.classPrefix + "-after-open"); this.drop.addEventListener('transitionend', handler = function() { if (!hasClass(_this.drop, "" + drop.classPrefix + "-open")) { removeClass(_this.drop, "" + drop.classPrefix + "-open-transitionend"); } return _this.drop.removeEventListener('transitionend', handler); }); this.trigger('close'); if ((_ref1 = this.tether) != null) { _ref1.disable(); } drop.updateBodyClasses(); if (this.options.remove) { return this.remove(); } }; DropInstance.prototype.remove = function() { var _ref1; this.close(); return (_ref1 = this.drop.parentNode) != null ? _ref1.removeChild(this.drop) : void 0; }; DropInstance.prototype.position = function() { var _ref1; if (this.isOpened()) { return (_ref1 = this.tether) != null ? _ref1.position() : void 0; } }; DropInstance.prototype.destroy = function() { var element, event, handler, _i, _len, _ref1, _ref2, _ref3; this.remove(); if ((_ref1 = this.tether) != null) { _ref1.destroy(); } _ref2 = this._boundEvents; for (_i = 0, _len = _ref2.length; _i < _len; _i++) { _ref3 = _ref2[_i], element = _ref3.element, event = _ref3.event, handler = _ref3.handler; element.removeEventListener(event, handler); } this._boundEvents = []; this.tether = null; this.drop = null; this.content = null; this.target = null; removeFromArray(allDrops[drop.classPrefix], this); return removeFromArray(drop.drops, this); }; return DropInstance; })(Evented); return drop; }; window.Drop = createContext(); document.addEventListener('DOMContentLoaded', function() { return Drop.updateBodyClasses(); }); }).call(this); /*! vex.js, vex.dialog.js 2.2.1 */ (function(){var a;a=function(a){var b,c;return b=!1,a(function(){var d;return d=(document.body||document.documentElement).style,b=void 0!==d.animation||void 0!==d.WebkitAnimation||void 0!==d.MozAnimation||void 0!==d.MsAnimation||void 0!==d.OAnimation,a(window).bind("keyup.vex",function(a){return 27===a.keyCode?c.closeByEscape():void 0})}),c={globalID:1,animationEndEvent:"animationend webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend",baseClassNames:{vex:"vex",content:"vex-content",overlay:"vex-overlay",close:"vex-close",closing:"vex-closing",open:"vex-open"},defaultOptions:{content:"",showCloseButton:!0,escapeButtonCloses:!0,overlayClosesOnClick:!0,appendLocation:"body",className:"",css:{},overlayClassName:"",overlayCSS:{},contentClassName:"",contentCSS:{},closeClassName:"",closeCSS:{}},open:function(b){return b=a.extend({},c.defaultOptions,b),b.id=c.globalID,c.globalID+=1,b.$vex=a("
").addClass(c.baseClassNames.vex).addClass(b.className).css(b.css).data({vex:b}),b.$vexOverlay=a("
").addClass(c.baseClassNames.overlay).addClass(b.overlayClassName).css(b.overlayCSS).data({vex:b}),b.overlayClosesOnClick&&b.$vexOverlay.bind("click.vex",function(b){return b.target===this?c.close(a(this).data().vex.id):void 0}),b.$vex.append(b.$vexOverlay),b.$vexContent=a("
").addClass(c.baseClassNames.content).addClass(b.contentClassName).css(b.contentCSS).append(b.content).data({vex:b}),b.$vex.append(b.$vexContent),b.showCloseButton&&(b.$closeButton=a("
").addClass(c.baseClassNames.close).addClass(b.closeClassName).css(b.closeCSS).data({vex:b}).bind("click.vex",function(){return c.close(a(this).data().vex.id)}),b.$vexContent.append(b.$closeButton)),a(b.appendLocation).append(b.$vex),c.setupBodyClassName(b.$vex),b.afterOpen&&b.afterOpen(b.$vexContent,b),setTimeout(function(){return b.$vexContent.trigger("vexOpen",b)},0),b.$vexContent},getAllVexes:function(){return a("."+c.baseClassNames.vex+':not(".'+c.baseClassNames.closing+'") .'+c.baseClassNames.content)},getVexByID:function(b){return c.getAllVexes().filter(function(){return a(this).data().vex.id===b})},close:function(a){var b;if(!a){if(b=c.getAllVexes().last(),!b.length)return!1;a=b.data().vex.id}return c.closeByID(a)},closeAll:function(){var b;return b=c.getAllVexes().map(function(){return a(this).data().vex.id}).toArray(),(null!=b?b.length:void 0)?(a.each(b.reverse(),function(a,b){return c.closeByID(b)}),!0):!1},closeByID:function(d){var e,f,g,h,i;return f=c.getVexByID(d),f.length?(e=f.data().vex.$vex,i=a.extend({},f.data().vex),g=function(){return i.beforeClose?i.beforeClose(f,i):void 0},h=function(){return f.trigger("vexClose",i),e.remove(),a("body").trigger("vexAfterClose",i),i.afterClose?i.afterClose(f,i):void 0},b?(g(),e.unbind(c.animationEndEvent).bind(c.animationEndEvent,function(){return h()}).addClass(c.baseClassNames.closing)):(g(),h()),!0):void 0},closeByEscape:function(){var b,d,e;return e=c.getAllVexes().map(function(){return a(this).data().vex.id}).toArray(),(null!=e?e.length:void 0)?(d=Math.max.apply(Math,e),b=c.getVexByID(d),b.data().vex.escapeButtonCloses!==!0?!1:c.closeByID(d)):!1},setupBodyClassName:function(){return a("body").bind("vexOpen.vex",function(){return a("body").addClass(c.baseClassNames.open)}).bind("vexAfterClose.vex",function(){return c.getAllVexes().length?void 0:a("body").removeClass(c.baseClassNames.open)})},hideLoading:function(){return a(".vex-loading-spinner").remove()},showLoading:function(){return c.hideLoading(),a("body").append('
')}}},"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof exports?module.exports=a(require("jquery")):window.vex=a(jQuery)}).call(this),function(){var a;a=function(a,b){var c,d;return null==b?a.error("Vex is required to use vex.dialog"):(c=function(b){var c;return c={},a.each(b.serializeArray(),function(){return c[this.name]?(c[this.name].push||(c[this.name]=[c[this.name]]),c[this.name].push(this.value||"")):c[this.name]=this.value||""}),c},d={},d.buttons={YES:{text:"OK",type:"submit",className:"vex-dialog-button-primary"},NO:{text:"Cancel",type:"button",className:"vex-dialog-button-secondary",click:function(a){return a.data().vex.value=!1,b.close(a.data().vex.id)}}},d.defaultOptions={callback:function(){},afterOpen:function(){},message:"Message",input:'',value:!1,buttons:[d.buttons.YES,d.buttons.NO],showCloseButton:!1,onSubmit:function(e){var f,g;return f=a(this),g=f.parent(),e.preventDefault(),e.stopPropagation(),g.data().vex.value=d.getFormValueOnSubmit(c(f)),b.close(g.data().vex.id)},focusFirstInput:!0},d.defaultAlertOptions={message:"Alert",buttons:[d.buttons.YES]},d.defaultConfirmOptions={message:"Confirm"},d.open=function(c){var e;return c=a.extend({},b.defaultOptions,d.defaultOptions,c),c.content=d.buildDialogForm(c),c.beforeClose=function(a){return c.callback(a.data().vex.value)},e=b.open(c),c.focusFirstInput&&e.find('input[type="submit"], textarea, input[type="date"], input[type="datetime"], input[type="datetime-local"], input[type="email"], input[type="month"], input[type="number"], input[type="password"], input[type="search"], input[type="tel"], input[type="text"], input[type="time"], input[type="url"], input[type="week"]').first().focus(),e},d.alert=function(b){return"string"==typeof b&&(b={message:b}),b=a.extend({},d.defaultAlertOptions,b),d.open(b)},d.confirm=function(b){return"string"==typeof b?a.error("dialog.confirm(options) requires options.callback."):(b=a.extend({},d.defaultConfirmOptions,b),d.open(b))},d.prompt=function(b){var c;return"string"==typeof b?a.error("dialog.prompt(options) requires options.callback."):(c={message:'",input:''},b=a.extend({},c,b),d.open(b))},d.buildDialogForm=function(b){var c,e,f;return c=a('
'),f=a('
'),e=a('
'),c.append(f.append(b.message)).append(e.append(b.input)).append(d.buttonsToDOM(b.buttons)).bind("submit.vex",b.onSubmit),c},d.getFormValueOnSubmit=function(a){return a.vex||""===a.vex?"_vex-empty-value"===a.vex?!0:a.vex:a},d.buttonsToDOM=function(c){var d;return d=a('
'),a.each(c,function(e,f){var g;return g=a('').val(f.text).addClass(f.className+" vex-dialog-button "+(0===e?"vex-first ":"")+(e===c.length-1?"vex-last ":"")).bind("click.vex",function(c){return f.click?f.click(a(this).parents("."+b.baseClassNames.content),c):void 0}),g.appendTo(d)}),d},d)},"function"==typeof define&&define.amd?define(["jquery","vex"],a):"object"==typeof exports?module.exports=a(require("jquery"),require("vex")):window.vex.dialog=a(window.jQuery,window.vex)}.call(this); (function() { window.TS = {}; }).call(this); (function() { var __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; }, __hasProp = {}.hasOwnProperty; window.TS.Store = (function() { function Store(_at_id) { this.id = _at_id != null ? _at_id : null; this.STORE = {}; } Store.prototype.get = function(key) { return this.STORE[key]; }; Store.prototype.set = function(key, value) { return this.STORE[key] = value; }; Store.prototype.each = function(callback) { var key, value, _ref, _results; _ref = this.STORE; _results = []; for (key in _ref) { value = _ref[key]; _results.push(typeof callback === "function" ? callback(key, value) : void 0); } return _results; }; return Store; })(); window.TS.Model = (function(_super) { __extends(Model, _super); function Model() { return Model.__super__.constructor.apply(this, arguments); } Model.prototype.save = function(callback) { var data, key, self, value, _ref; if (callback == null) { callback = function() {}; } self = this; data = []; _ref = this.STORE; for (key in _ref) { value = _ref[key]; data.push(value); } return $.ajax({ type: "PATCH", url: self.id, dataType: 'json', contentType: 'application/json', data: JSON.stringify({ contents: data }), success: function(data) { return callback(data); } }); }; return Model; })(window.TS.Store); }).call(this); (function() { window.TS.AdminBar = (function() { function AdminBar(_at_element) { var drop, template; this.element = _at_element; template = this.element.html(); $('body').append(template); $('#ts-admin-bar-edit').on('click', function() { $('#ts-admin-bar').removeClass('ts-hidden'); $('#ts-admin-bar-edit').addClass('ts-hidden'); return window.TS.enable(); }); $('#ts-admin-bar-cancel').on('click', function() { $('#ts-admin-bar').addClass('ts-hidden'); $('#ts-admin-bar-edit').removeClass('ts-hidden'); return window.TS.disable(); }); $('#ts-admin-bar-save').on('click', function() { return window.TS.save(); }); $('#ts-admin-bar input').on('change', function() { var model; model = window.TS.getModel($(this).data('ts-url')); return model.set($(this).data('ts-key'), { field: $(this).data('ts-key'), value: $(this).val(), type: 'text' }); }); drop = new Drop({ target: $('#ts-admin-bar .ts-options i')[0], content: $('#ts-admin-bar-options')[0], position: 'bottom center', openOn: 'click', classes: 'drop-theme-arrows-bounce-dark' }); } AdminBar.prototype.enable = function() {}; AdminBar.prototype.disable = function() {}; return AdminBar; })(); }).call(this); (function() { var buildUploader, setUpDrops; buildUploader = function(element, data) { var $input, elementId; elementId = $(element).attr('id'); $input = $(''); $input.attr({ type: "file", name: "file", "class": 'ts-editable-file-input', 'data-form-data': JSON.stringify(data), 'data-element-id': elementId }).cloudinary_fileupload().bind('cloudinaryprogress', function(e, data) { return $('.ts-progress-bar').css('width', Math.round((data.loaded * 100.0) / data.total) + '%'); }).bind('cloudinarystart', function(e, data) { $(this).prop('disabled', true); return $('body').append($('
').addClass('ts-progress-bar')); }).bind('cloudinarydone', function(e, data) { var $element, imageTag, model, _i, _len, _ref; $element = $("#" + ($(this).data('elementId'))); _ref = $('.ts-editable-link-tag', $element); for (_i = 0, _len = _ref.length; _i < _len; _i++) { imageTag = _ref[_i]; $(imageTag).attr('href', $.cloudinary.url(data.result.public_id, {})); } $element.data('drop').close(); $(this).prop('disabled', false); $('.ts-progress-bar').remove(); model = window.TS.getModel($element.data('ts-url')); return model.set($element.data('ts-key'), { field: $element.data('ts-key'), value: { identifier: data.result.public_id }, type: 'file' }); }); return $input; }; setUpDrops = function(elements) { var drop, drops, element, tsData, _i, _len; drops = []; for (_i = 0, _len = elements.length; _i < _len; _i++) { element = elements[_i]; tsData = $(element).data('tsData'); drop = new Drop({ target: $('.ts-editable-button', element)[0], content: buildUploader(element, tsData)[0], position: 'bottom center', openOn: 'click', classes: 'drop-theme-arrows-bounce-dark' }); $(element).data('drop', drop); drops.push(drop); } return drops; }; window.TS.EditableFile = (function() { function EditableFile(_at_elements) { var element, _i, _len, _ref; this.elements = _at_elements; this.drops = []; _ref = this.elements; for (_i = 0, _len = _ref.length; _i < _len; _i++) { element = _ref[_i]; $(element).append($('
').addClass('ts-editable-button').addClass('ts-button').html("")); } } EditableFile.prototype.enable = function() { this.disable(); return this.drops = setUpDrops(this.elements); }; EditableFile.prototype.disable = function() { var drop, _i, _len, _ref; _ref = this.drops; for (_i = 0, _len = _ref.length; _i < _len; _i++) { drop = _ref[_i]; drop.close(); drop.remove(); drop.destroy(); } return this.drops = []; }; return EditableFile; })(); }).call(this); (function() { var buildUploader, setUpDrops; buildUploader = function(element, data) { var $input, elementId; elementId = $(element).attr('id'); $input = $(''); $input.attr({ type: "file", name: "file", "class": 'ts-editable-image-input', 'data-form-data': JSON.stringify(data), 'data-element-id': elementId }).cloudinary_fileupload().bind('cloudinaryprogress', function(e, data) { return $('.ts-progress-bar').css('width', Math.round((data.loaded * 100.0) / data.total) + '%'); }).bind('cloudinarystart', function(e, data) { $(this).prop('disabled', true); return $('body').append($('
').addClass('ts-progress-bar')); }).bind('cloudinarydone', function(e, data) { var $element, imageTag, model, _i, _len, _ref; $element = $("#" + ($(this).data('elementId'))); _ref = $('.ts-editable-image-tag', $element); for (_i = 0, _len = _ref.length; _i < _len; _i++) { imageTag = _ref[_i]; $(imageTag).attr('src', $.cloudinary.url(data.result.public_id, $(imageTag).data())); } $element.data('drop').close(); $(this).prop('disabled', false); $('.ts-progress-bar').remove(); model = window.TS.getModel($element.data('ts-url')); return model.set($element.data('ts-key'), { field: $element.data('ts-key'), value: { identifier: data.result.public_id }, type: 'image' }); }); return $input; }; setUpDrops = function(elements) { var drop, drops, element, tsData, _i, _len; drops = []; for (_i = 0, _len = elements.length; _i < _len; _i++) { element = elements[_i]; tsData = $(element).data('tsData'); drop = new Drop({ target: $('.ts-editable-button', element)[0], content: buildUploader(element, tsData)[0], position: 'bottom center', openOn: 'click', classes: 'drop-theme-arrows-bounce-dark' }); $(element).data('drop', drop); drops.push(drop); } return drops; }; window.TS.EditableImage = (function() { function EditableImage(_at_elements) { var element, _i, _len, _ref; this.elements = _at_elements; this.drops = []; _ref = this.elements; for (_i = 0, _len = _ref.length; _i < _len; _i++) { element = _ref[_i]; $(element).append($('
').addClass('ts-editable-button').addClass('ts-button').html("")); } } EditableImage.prototype.enable = function() { this.disable(); return this.drops = setUpDrops(this.elements); }; EditableImage.prototype.disable = function() { var drop, _i, _len, _ref; _ref = this.drops; for (_i = 0, _len = _ref.length; _i < _len; _i++) { drop = _ref[_i]; drop.close(); drop.remove(); drop.destroy(); } return this.drops = []; }; return EditableImage; })(); }).call(this); (function() { var buildFields, setUpDrops; buildFields = function(element) { var $button, $element, $input, $li, $ul, field, tsFields, tsNewUrl, tsParentId, _i, _len; $element = $(element); $ul = $('
    '); tsFields = $element.data('tsFields'); tsNewUrl = $element.data('tsUrl'); tsParentId = $element.data('tsParentId'); for (_i = 0, _len = tsFields.length; _i < _len; _i++) { field = tsFields[_i]; $li = $('
  • '); $input = $(''); $input.attr({ type: "text", name: "text", placeholder: field }).data({ 'ts-field': field, 'ts-url': tsNewUrl }).on('change', function(e) { return $(this).parent().parent().data($(this).data('ts-field'), $(this).val()); }).appendTo($li); $li.appendTo($ul); } $li = $('
  • '); $button = $('