/* * jQuery UI Widget 1.8.17+amd * https://github.com/blueimp/jQuery-File-Upload * * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Widget */ (function (factory) { if (typeof define === "function" && define.amd) { // Register as an anonymous AMD module: define(["jquery"], factory); } else { // Browser globals: factory(jQuery); } }(function( $, undefined ) { // jQuery 1.4+ if ( $.cleanData ) { var _cleanData = $.cleanData; $.cleanData = function( elems ) { for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { try { $( elem ).triggerHandler( "remove" ); // http://bugs.jquery.com/ticket/8235 } catch( e ) {} } _cleanData( elems ); }; } else { var _remove = $.fn.remove; $.fn.remove = function( selector, keepData ) { return this.each(function() { if ( !keepData ) { if ( !selector || $.filter( selector, [ this ] ).length ) { $( "*", this ).add( [ this ] ).each(function() { try { $( this ).triggerHandler( "remove" ); // http://bugs.jquery.com/ticket/8235 } catch( e ) {} }); } } return _remove.call( $(this), selector, keepData ); }); }; } $.widget = function( name, base, prototype ) { var namespace = name.split( "." )[ 0 ], fullName; name = name.split( "." )[ 1 ]; fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } // create selector for plugin $.expr[ ":" ][ fullName ] = function( elem ) { return !!$.data( elem, name ); }; $[ namespace ] = $[ namespace ] || {}; $[ namespace ][ name ] = function( options, element ) { // allow instantiation without initializing for simple inheritance if ( arguments.length ) { this._createWidget( options, element ); } }; var 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 // $.each( basePrototype, function( key, val ) { // if ( $.isPlainObject(val) ) { // basePrototype[ key ] = $.extend( {}, val ); // } // }); basePrototype.options = $.extend( true, {}, basePrototype.options ); $[ namespace ][ name ].prototype = $.extend( true, basePrototype, { namespace: namespace, widgetName: name, widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name, widgetBaseClass: fullName }, prototype ); $.widget.bridge( name, $[ namespace ][ name ] ); }; $.widget.bridge = function( name, object ) { $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string", args = Array.prototype.slice.call( arguments, 1 ), returnValue = this; // allow multiple hashes to be passed on init options = !isMethodCall && args.length ? $.extend.apply( null, [ true, options ].concat(args) ) : options; // prevent calls to internal methods if ( isMethodCall && options.charAt( 0 ) === "_" ) { return returnValue; } if ( isMethodCall ) { this.each(function() { var instance = $.data( this, name ), methodValue = instance && $.isFunction( instance[options] ) ? instance[ options ].apply( instance, args ) : instance; // TODO: add this back in 1.9 and use $.error() (see #5972) // if ( !instance ) { // throw "cannot call methods on " + name + " prior to initialization; " + // "attempted to call method '" + options + "'"; // } // if ( !$.isFunction( instance[options] ) ) { // throw "no such method '" + options + "' for " + name + " widget instance"; // } // var methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue; return false; } }); } else { this.each(function() { var instance = $.data( this, name ); if ( instance ) { instance.option( options || {} )._init(); } else { $.data( this, name, new object( options, this ) ); } }); } return returnValue; }; }; $.Widget = function( options, element ) { // allow instantiation without initializing for simple inheritance if ( arguments.length ) { this._createWidget( options, element ); } }; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", options: { disabled: false }, _createWidget: function( options, element ) { // $.widget.bridge stores the plugin instance, but we do it anyway // so that it's stored even before the _create function runs $.data( element, this.widgetName, this ); this.element = $( element ); this.options = $.extend( true, {}, this.options, this._getCreateOptions(), options ); var self = this; this.element.bind( "remove." + this.widgetName, function() { self.destroy(); }); this._create(); this._trigger( "create" ); this._init(); }, _getCreateOptions: function() { return $.metadata && $.metadata.get( this.element[0] )[ this.widgetName ]; }, _create: function() {}, _init: function() {}, destroy: function() { this.element .unbind( "." + this.widgetName ) .removeData( this.widgetName ); this.widget() .unbind( "." + this.widgetName ) .removeAttr( "aria-disabled" ) .removeClass( this.widgetBaseClass + "-disabled " + "ui-state-disabled" ); }, widget: function() { return this.element; }, option: function( key, value ) { var options = key; if ( arguments.length === 0 ) { // don't return a reference to the internal hash return $.extend( {}, this.options ); } if (typeof key === "string" ) { if ( value === undefined ) { return this.options[ key ]; } options = {}; options[ key ] = value; } this._setOptions( options ); return this; }, _setOptions: function( options ) { var self = this; $.each( options, function( key, value ) { self._setOption( key, value ); }); return this; }, _setOption: function( key, value ) { this.options[ key ] = value; if ( key === "disabled" ) { this.widget() [ value ? "addClass" : "removeClass"]( this.widgetBaseClass + "-disabled" + " " + "ui-state-disabled" ) .attr( "aria-disabled", value ); } return this; }, enable: function() { return this._setOption( "disabled", false ); }, disable: function() { return this._setOption( "disabled", true ); }, _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.call( this.element[0], event, data ) === false || event.isDefaultPrevented() ); } }; })); /* * jQuery Iframe Transport Plugin 1.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 */ /*jslint unparam: true, nomen: true */ /*global define, window, document */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define(['jquery'], factory); } 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 three 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) // 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}] $.ajaxTransport('iframe', function (options) { if (options.async && (options.type === 'POST' || options.type === 'GET')) { var form, iframe; return { send: function (_, completeCallback) { form = $('
'); // javascript:false as initial iframe src // prevents warning popups on HTTPS in IE6. // 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: iframe = $( '' ).bind('load', function () { var fileInputClones; 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); form.remove(); }); 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 () { $(this).prop('name', 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'); } 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]); $(input).prop('name', clone.prop('name')); 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', 'javascript'.concat(':false;')); } if (form) { form.remove(); } } }; } }); // The iframe transport returns the iframe content document as response. // The following adds converters from iframe to text, json, html, and script: $.ajaxSetup({ converters: { 'iframe text': function (iframe) { return $(iframe[0].body).text(); }, 'iframe json': function (iframe) { return $.parseJSON($(iframe[0].body).text()); }, 'iframe html': function (iframe) { return $(iframe[0].body).html(); }, 'iframe script': function (iframe) { return $.globalEval($(iframe[0].body).text()); } } }); })); /* * jQuery File Upload Plugin 5.7 * 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 */ /*jslint nomen: true, unparam: true, regexp: true */ /*global define, window, document, XMLHttpRequestUpload, Blob, File, FormData, location */ (function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { // Register as an anonymous AMD module: define([ 'jquery', './vendor/jquery.ui.widget', './jquery.iframe-transport' ], factory); } else { // Browser globals: factory(window.jQuery); } }(function ($) { 'use strict'; // 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 namespace used for event handler binding on the dropZone and // fileInput collections. // If not set, the name of the widget ("fileupload") is used. namespace: undefined, // The drop target collection, by the default the complete document. // Set to null or an empty collection to disable drag & drop support: dropZone: $(document), // The file input field collection, that is listened for change events. // If undefined, it is set to the file input fields inside // of the widget element on plugin initialization. // Set to null or an empty collection 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: 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, // 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, // 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 uplaods, 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 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) { 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 collection: // change: function (e, data) {}, // .bind('fileuploadchange', func); // Callback for paste events to the dropZone collection: // paste: function (e, data) {}, // .bind('fileuploadpaste', func); // Callback for drop events of the dropZone collection: // drop: function (e, data) {}, // .bind('fileuploaddrop', func); // Callback for dragover events of the dropZone collection: // dragover: function (e) {}, // .bind('fileuploaddragover', 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 a refresh after assigning a new value: _refreshOptionsList: ['namespace', 'dropZone', 'fileInput'], _isXHRUpload: function (options) { var undef = 'undefined'; return !options.forceIframeTransport && typeof XMLHttpRequestUpload !== undef && typeof File !== undef && (!options.multipart || typeof FormData !== undef); }, _getFormData: function (options) { var formData; if (typeof options.formData === 'function') { return options.formData(options.form); } else if ($.isArray(options.formData)) { return options.formData; } else if (options.formData) { 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; }, _onProgress: function (e, data) { if (e.lengthComputable) { var total = data.total || this._getTotal(data.files), loaded = parseInt( e.loaded / e.total * (data.chunkSize || total), 10 ) + (data.uploadedBytes || 0); this._loaded += loaded - (data.loaded || data.uploadedBytes || 0); data.lengthComputable = true; data.loaded = loaded; data.total = total; // 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', e, data); // Trigger a global progress event for all current file uploads, // including ajax calls queued for sequential file uploads: this._trigger('progressall', e, { lengthComputable: true, loaded: this._loaded, total: this._total }); } }, _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; }; } }, _initXHRData: function (options) { var formData, file = options.files[0]; if (!options.multipart || options.blob) { // For non-multipart uploads and chunked uploads, // file meta data is not part of the request body, // so we transmit this data as part of the HTTP headers. // For cross domain requests, these headers must be allowed // via Access-Control-Allow-Headers or removed using // the beforeSend callback: options.headers = $.extend(options.headers, { 'X-File-Name': file.name, 'X-File-Type': file.type, 'X-File-Size': file.size }); if (!options.blob) { // Non-chunked non-multipart upload: options.contentType = file.type; options.data = file; } else if (!options.multipart) { // Chunked non-multipart upload: options.contentType = 'application/octet-stream'; options.data = options.blob; } } if (options.multipart && typeof FormData !== 'undefined') { 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: options.paramName, value: options.blob }); } else { $.each(options.files, function (index, file) { formData.push({ name: options.paramName, value: file }); }); } } else { if (options.formData instanceof 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(options.paramName, options.blob, file.name); } else { $.each(options.files, function (index, file) { // File objects are also Blob instances. // This check allows the tests to run with // dummy objects: if (file instanceof Blob) { formData.append(options.paramName, file, file.name); } }); } } options.data = formData; } // Blob reference is not needed anymore, free memory: options.blob = null; }, _initIframeSettings: function (options) { // 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 && $('').prop('href', options.url) .prop('host') !== 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, 'iframe'); } }, _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 (!options.paramName) { options.paramName = options.fileInput.prop('name') || 'files[]'; } if (!options.url) { options.url = options.form.prop('action') || location.href; } // The HTTP request method must be "POST" or "PUT": options.type = (options.type || options.form.prop('method') || '') .toUpperCase(); if (options.type !== 'POST' && options.type !== 'PUT') { options.type = 'POST'; } }, _getAJAXSettings: function (data) { var options = $.extend({}, this.options, data); this._initFormSettings(options); this._initDataSettings(options); return options; }, // 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); }, // 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) { var that = this, file = options.files[0], fs = file.size, ub = options.uploadedBytes = options.uploadedBytes || 0, mcs = options.maxChunkSize || fs, // Use the Blob methods with the slice implementation // according to the W3C Blob API specification: slice = file.webkitSlice || file.mozSlice || file.slice, upload, n, jqXHR, pipe; if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) || options.data) { return false; } if (testOnly) { return true; } if (ub >= fs) { file.error = 'uploadedBytes'; return this._getXHRPromise( false, options.context, [null, 'error', file.error] ); } // n is the number of blobs to upload, // calculated via filesize, uploaded bytes and max chunk size: n = Math.ceil((fs - ub) / mcs); // The chunk upload method accepting the chunk number as parameter: upload = function (i) { if (!i) { return that._getXHRPromise(true, options.context); } // Upload the blobs in sequential order: return upload(i -= 1).pipe(function () { // Clone the options object for each chunk upload: var o = $.extend({}, options); o.blob = slice.call( file, ub + i * mcs, ub + (i + 1) * mcs ); // Store the current chunk size, as the blob itself // will be dereferenced after data processing: o.chunkSize = o.blob.size; // Process the upload data (the blob and potential form data): that._initXHRData(o); // Add progress listeners for this chunk upload: that._initProgressListener(o); jqXHR = ($.ajax(o) || that._getXHRPromise(false, o.context)) .done(function () { // Create a progress event if upload is done and // no progress event has been invoked for this chunk: if (!o.loaded) { that._onProgress($.Event('progress', { lengthComputable: true, loaded: o.chunkSize, total: o.chunkSize }), o); } options.uploadedBytes = o.uploadedBytes += o.chunkSize; }); return jqXHR; }); }; // 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 = upload(n); pipe.abort = function () { return jqXHR.abort(); }; return this._enhancePromise(pipe); }, _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'); } this._active += 1; // Initialize the global progress values: this._loaded += data.uploadedBytes || 0; this._total += this._getTotal(data.files); }, _onDone: function (result, textStatus, jqXHR, options) { if (!this._isXHRUpload(options)) { // Create a progress event for each iframe load: this._onProgress($.Event('progress', { lengthComputable: true, loaded: 1, total: 1 }), options); } options.result = result; options.textStatus = textStatus; options.jqXHR = jqXHR; this._trigger('done', null, options); }, _onFail: function (jqXHR, textStatus, errorThrown, options) { options.jqXHR = jqXHR; options.textStatus = textStatus; options.errorThrown = errorThrown; this._trigger('fail', null, options); if (options.recalculateProgress) { // Remove the failed (error or abort) file upload from // the global progress calculation: this._loaded -= options.loaded || options.uploadedBytes || 0; this._total -= options.total || this._getTotal(options.files); } }, _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) { this._active -= 1; options.textStatus = textStatus; if (jqXHRorError && jqXHRorError.always) { options.jqXHR = jqXHRorError; options.result = jqXHRorResult; } else { options.jqXHR = jqXHRorResult; options.errorThrown = jqXHRorError; } this._trigger('always', null, options); if (this._active === 0) { // The stop callback is triggered when all uploads have // been completed, equivalent to the global ajaxStop event: this._trigger('stop'); // Reset the global progress values: this._loaded = this._total = 0; } }, _onSend: function (e, data) { var that = this, jqXHR, slot, pipe, options = that._getAJAXSettings(data), send = function (resolve, args) { that._sending += 1; jqXHR = jqXHR || ( (resolve !== false && that._trigger('send', e, options) !== false && (that._chunkedUpload(options) || $.ajax(options))) || that._getXHRPromise(false, options.context, args) ).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._sending -= 1; that._onAlways( jqXHRorResult, textStatus, jqXHRorError, options ); 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 (!nextSlot.isRejected()) { nextSlot.resolve(); break; } nextSlot = that._slots.shift(); } } }); 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 { pipe = (this._sequence = this._sequence.pipe(send, send)); } // 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 () { var args = [undefined, 'abort', 'abort']; if (!jqXHR) { if (slot) { slot.rejectWith(args); } return send(false, args); } return jqXHR.abort(); }; return this._enhancePromise(pipe); } return send(); }, _onAdd: function (e, data) { var that = this, result = true, options = $.extend({}, this.options, data), limit = options.limitMultiFileUploads, fileSet, i; if (!(options.singleFileUploads || limit) || !this._isXHRUpload(options)) { fileSet = [data.files]; } else if (!options.singleFileUploads && limit) { fileSet = []; for (i = 0; i < data.files.length; i += limit) { fileSet.push(data.files.slice(i, i + limit)); } } data.originalFiles = data.files; $.each(fileSet || data.files, function (index, element) { var files = fileSet ? element : [element], newData = $.extend({}, data, {files: files}); newData.submit = function () { newData.jqXHR = this.jqXHR = (that._trigger('submit', e, this) !== false) && that._onSend(e, this); return this.jqXHR; }; return (result = that._trigger('add', e, newData)); }); return result; }, // File Normalization for Gecko 1.9.1 (Firefox 3.5) support: _normalizeFile: function (index, file) { if (file.name === undefined && file.size === undefined) { file.name = file.fileName; file.size = file.fileSize; } }, _replaceFileInput: function (input) { var inputClone = input.clone(true); $('
').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 // collection 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; } }, _onChange: function (e) { var that = e.data.fileupload, data = { files: $.each($.makeArray(e.target.files), that._normalizeFile), fileInput: $(e.target), form: $(e.target.form) }; if (!data.files.length) { // 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: data.files = [{name: e.target.value.replace(/^.*\\/, '')}]; } if (that.options.replaceFileInput) { that._replaceFileInput(data.fileInput); } if (that._trigger('change', e, data) === false || that._onAdd(e, data) === false) { return false; } }, _onPaste: function (e) { var that = e.data.fileupload, cbd = e.originalEvent.clipboardData, items = (cbd && cbd.items) || [], data = {files: []}; $.each(items, function (index, item) { var file = item.getAsFile && item.getAsFile(); if (file) { data.files.push(file); } }); if (that._trigger('paste', e, data) === false || that._onAdd(e, data) === false) { return false; } }, _onDrop: function (e) { var that = e.data.fileupload, dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer, data = { files: $.each( $.makeArray(dataTransfer && dataTransfer.files), that._normalizeFile ) }; if (that._trigger('drop', e, data) === false || that._onAdd(e, data) === false) { return false; } e.preventDefault(); }, _onDragOver: function (e) { var that = e.data.fileupload, dataTransfer = e.dataTransfer = e.originalEvent.dataTransfer; if (that._trigger('dragover', e) === false) { return false; } if (dataTransfer) { dataTransfer.dropEffect = dataTransfer.effectAllowed = 'copy'; } e.preventDefault(); }, _initEventHandlers: function () { var ns = this.options.namespace; this.options.dropZone .bind('dragover.' + ns, {fileupload: this}, this._onDragOver) .bind('drop.' + ns, {fileupload: this}, this._onDrop) .bind('paste.' + ns, {fileupload: this}, this._onPaste); this.options.fileInput .bind('change.' + ns, {fileupload: this}, this._onChange); }, _destroyEventHandlers: function () { var ns = this.options.namespace; this.options.dropZone .unbind('dragover.' + ns, this._onDragOver) .unbind('drop.' + ns, this._onDrop) .unbind('paste.' + ns, this._onPaste); this.options.fileInput .unbind('change.' + ns, this._onChange); }, _beforeSetOption: function (key, value) { this._destroyEventHandlers(); }, _afterSetOption: function (key, value) { var options = this.options; if (!options.fileInput) { options.fileInput = $(); } if (!options.dropZone) { options.dropZone = $(); } this._initEventHandlers(); }, _setOption: function (key, value) { var refresh = $.inArray(key, this._refreshOptionsList) !== -1; if (refresh) { this._beforeSetOption(key, value); } $.Widget.prototype._setOption.call(this, key, value); if (refresh) { this._afterSetOption(key, value); } }, _create: function () { var options = this.options; options.namespace = options.namespace || this.widgetName; if (options.fileInput === undefined) { options.fileInput = this.element.is('input:file') ? this.element : this.element.find('input:file'); } else if (!options.fileInput) { options.fileInput = $(); } if (!options.dropZone) { options.dropZone = $(); } this._slots = []; this._sequence = this._getXHRPromise(true); this._sending = this._active = this._loaded = this._total = 0; this._initEventHandlers(); }, destroy: function () { this._destroyEventHandlers(); $.Widget.prototype.destroy.call(this); }, enable: function () { $.Widget.prototype.enable.call(this); this._initEventHandlers(); }, disable: function () { this._destroyEventHandlers(); $.Widget.prototype.disable.call(this); }, // 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) { if (!data || this.options.disabled) { return; } data.files = $.each($.makeArray(data.files), this._normalizeFile); 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 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) { data.files = $.each($.makeArray(data.files), this._normalizeFile); if (data.files.length) { return this._onSend(null, data); } } return this._getXHRPromise(false, data && data.context); } }); })); /* jQuery plugin textselect * version: 0.9 * author: Josef Moravec, josef.moravec@gmail.com * updated: Imperavi * */ (function($){$.event.special.textselect={setup:function(data,namespaces) {$(this).data("textselected",false);$(this).data("ttt",data);$(this).bind('mouseup',$.event.special.textselect.handler);},teardown:function(data) {$(this).unbind('mouseup',$.event.special.textselect.handler);},handler:function(event) {var data=$(this).data("ttt");var text=$.event.special.textselect.getSelectedText(data).toString();if(text!='') {$(this).data("textselected",true);event.type="textselect";event.text=text;$.event.handle.apply(this,arguments);}},getSelectedText:function(data) {var text='';var frame=$('#imp_redactor_frame_'+data).get(0);if(frame.contentWindow.getSelection)text=frame.contentWindow.getSelection();else if(frame.contentWindow.document.getSelection) text=frame.contentWindow.document.getSelection();else if(frame.contentWindow.document.selection)text=frame.contentWindow.document.selection.createRange().text;return text;}} $.event.special.textunselect={setup:function(data,namespaces){$(this).data("rttt",data);$(this).data("textselected",false);$(this).bind('mouseup',$.event.special.textunselect.handler);$(this).bind('keyup',$.event.special.textunselect.handlerKey)},teardown:function(data){$(this).unbind('mouseup',$.event.special.textunselect.handler);},handler:function(event){if($(this).data("textselected")){var data=$(this).data("rttt");var text=$.event.special.textselect.getSelectedText(data).toString();if(text==''){$(this).data("textselected",false);event.type="textunselect";$.event.handle.apply(this,arguments);}}},handlerKey:function(event){if($(this).data("textselected")){var data=$(this).data("rttt");var text=$.event.special.textselect.getSelectedText(data).toString();if((event.keyCode=27)&&(text=='')){$(this).data("textselected",false);event.type="textunselect";$.event.handle.apply(this,arguments);}}}}})(jQuery); $.fn.ImperaviLanguages = { ru : { html : 'Код', // Styles dropdown menu styles : { name : 'Стили', paragraph : 'Параграф', quote : 'Цитата', code : 'Код', h2 : 'Заголовок 2', h3 : 'Заголовок 3', h4 : 'Заголовок 4', h5 : 'Заголовок 5', h6 : 'Заголовок 6', }, // Formatting dropdown menu format : { name : 'Формат', bold : 'Полужирный', italic : 'Наклонный', sup : 'Надстрочный', sub : 'Надстрочный', strike : 'Зачеркнутый', remove : 'Очистить форматирование' }, // Lists dropdown menu lists : { name : 'Списки', unordered : 'Обычный список', ordered : 'Нумерованный список', outdent : 'Уменьшить отступ', indent : 'Увеличить отступ' }, // Working with images image : { name : 'Изображение', download : 'Скачать изображение', text : 'Текст', mailto : 'Эл. почта', web : 'URL', title : 'Подсказка', buttons : { save : 'Сохранить', cancel : 'Отменить', insert : 'Вставить', remove : 'Удалить' }, align : { name : 'Обтекание текстом', none : 'нет', left : 'слева', right : 'справа' } }, // Insert and format tables table : { name : 'Таблица', insert : 'Вставить таблицу', remove : 'Удалить таблицу', row: { name : 'Строки', above : 'Добавить строку сверху', below : 'Добавить строку снизу', remove : 'Удалить строку' }, column : { name : 'Столбцы', left : 'Добавить столбец слева', right : 'Добавить столбец справа', remove : 'Удалить столбец', }, header : { add : 'Добавить заголовок', remove : 'Удалить заголовок' } }, // Insert video from youtube etc video : { name : 'Видео', code : 'Код видео ролика' }, // Insert or remove hyperlink to a file file : { name : 'Файл', upload : 'Загрузить', download : 'Скачать', choose : 'Выбрать', or_choose : 'Или выберите', drop : 'Перетащите файл сюда' }, // Insert or remove hyperlink hyperlink : 'Ссылка' } } ; $.fn.ImperaviToolbarDefault = { html : true, // Styles dropdown menu // TODO: User styles here. Move all to format section from here styles : { paragraph : true, quote : true, code : true, h2 : true, h3 : true, h4 : true, h5 : true, h6 : true }, // Formatting dropdown menu format : { bold : true, italic : true, sup : true, sub : true, strike : true, remove : true }, // Lists dropdown menu lists : { unordered : true, ordered : true, outdent : true, indent : true }, // Working with images image : true, // Insert and format tables table : { insert : true, remove : true, header : { add : true, remove : true }, row : { above : true, below : true, remove : true }, column : { left : true, right : true, remove : true } }, // Insert video from youtube etc video : true, // Insert or remove hyperlink to a file file : true, // Insert or remove hyperlink hyperlink : true } ; (function( $ ) { $.fn.ImperaviActionDelegator = function(o) { this.initialize() } $.fn.ImperaviActionDelegator.prototype = { initialize: function() {}, delegateButtonClick: function(button, iframe) { switch (button.attr('rel')) { case 'indent': case 'outdent': alert('yay!') break; case 'video': new $.fn.ImperaviPluginVideo break; case 'image': new $.fn.ImperaviPluginImage break; case 'hyperlink': new $.fn.ImperaviPluginHyperlink break; case 'file': new $.fn.ImperaviPluginFile break; default: return button break; } } } })(jQuery); // Internationalization (function( $ ) { $.fn.ImperaviI18n = function(o) { var o = $.extend({ locale : 'en' }, o) this.initialize(o) } $.fn.ImperaviI18n.prototype = { o : null, locales : null, initialize: function(o) { this.o = $.extend({ locale : $.fn.ImperaviOptions().options.locale }, o) this.locales = $.fn.ImperaviLanguages[this.o.locale] }, t: function(key) { } } })(jQuery); (function( $ ) { $.fn.ImperaviPluginVideo = function(o) { this.initialize(o) } $.fn.ImperaviPluginVideo.prototype = { initialize: function(o) { this.o = o this.dialog = new $.fn.ImperaviDialog({ title : 'Insert video', width : 600, height : 300, onOkay : function() { alert(this.el.find('textarea').val()) this.hide() } }) this.dialog.show() this.dialog.el.addClass('imperavi-plugin-video') this.build() }, build: function() { var textarea = $(document.createElement('textarea')) this.dialog.setContent(textarea) } } })(jQuery); (function( $ ) { $.fn.ImperaviPluginImage = function(o) { this.initialize(o) } $.fn.ImperaviPluginImage.prototype = { initialize: function(o) { this.o = o, this.image = null, this.dialog = new $.fn.ImperaviDialog({ title : 'Insert image', width : 800, height : 600, onRemove : function() { alert('fuck yeah!') this.hide() }, onOkay : function() { //this.doc.selection.createRange().pasteHTML(param); this.hide() } }) this.dialog.show() this.dialog.el.addClass('imperavi-plugin-image') this.build() }, build: function() { // Add 'remove' button this.removeButton = this.dialog.addButton('Remove', 'remove') this.removeButton.hide(); // Create tabs and content for tabs this.tabsArea = this.buildTabsArea() this.uploadTab = this.buildTab('Upload image', this.buildUploadTabContent()) .appendTo(this.tabsArea) .addClass('current') this.pickTab = this.buildTab('Pick image', this.buildPickTabContent()) .appendTo(this.tabsArea) this.dialog.setContent(this.tabsArea) this.switchTabs(); }, // Build tabs container buildTabsArea: function() { var article = $(document.createElement('article')) .addClass('imperavi-tabs') return article }, // Add another one tab buildTab: function(title, content) { var section = $(document.createElement('section')) var heading = $(document.createElement('h3')) .html(title) .addClass('imperavi-tab') .appendTo(section) var content = $(document.createElement('div')) .appendTo(section) .html(content) return section }, // Switch between tabs switchTabs: function() { var currentTab = this.uploadTab this.tabsArea.on('click', '.imperavi-tab', function(e){ e.preventDefault(); if (currentTab.length) { currentTab.removeClass('current') } currentTab = $(this).closest('section').addClass('current') }) }, buildPickTabContent: function() { }, buildUploadTabContent: function() { // Create wrapper var wrapper = $(document.createElement('div')) .attr('id', 'upload-wrapper') // Create place for thumbnail var thumbnail = $(document.createElement('figure')) .addClass('thumbnail') .appendTo(wrapper) var caption = $(document.createElement('span')) .html('No image yet') .appendTo(thumbnail) // Create form var form = $(document.createElement('form')) .attr('enctype', 'multipart/form-data') .attr('method', 'post') .attr('action', '/images') //.attr('accept-charset', 'UTF-8') .appendTo(wrapper) // Choose image from disk field var imageLocal = this.buildInput('Choose image from disk', 'image[image]', 'file') .appendTo(form) // Image url field var imageUrl = this.buildInput('or specify link to image', 'image[url]', 'text') .appendTo(wrapper) // Image align dropdown var imagePos = this.buildAlignSelect().appendTo(wrapper) imageLocal.fileupload({ dataType : 'json', url : '/images', change : function() { thumbnail.addClass('loading') }, done : $.proxy(function (e, data) { thumbnail.empty() thumbnail.removeClass('loading') this.image = $(document.createElement('img')) .attr('src', data.result.thumbnail_url) .attr('width', 300) .attr('height', 340) .appendTo(thumbnail) }, this) }); // Submit form /*form.on("change", ":file", function() { thumbnail.addClass("loading"); $.ajax(form.attr("action"), { files : form.find(":file"), iframe : true, dataType : "json", contentType : 'multipart/form-data', type : form.attr('method') }).always(function() { thumbnail.removeClass("loading"); }).done(function(data) { if (data.errors) { // Some errors occurs alert(data.errors) // TODO } else { // No errors thumbnail.empty() $(document.createElement('img')) .attr('src', data.file) .attr('width', 300) .attr('height', 340) .appendTo(thumbnail) } }); });*/ return wrapper }, buildInput: function(title, name, type) { var wrapper = $(document.createElement('div')) .addClass('field') var label = $(document.createElement('label')) .attr('for', name) .html(title) .appendTo(wrapper) var url = $(document.createElement('input')) .attr('type', type) .attr('name', name) .attr('id', name) .appendTo(wrapper) return wrapper }, buildAlignSelect: function() { var wrapper = $(document.createElement('div')) .addClass('field') var label = $(document.createElement('label')) .attr('for', 'image-align') .html('Image position') .appendTo(wrapper) var select = $(document.createElement('select')) .attr('id', 'image-align') .attr('name', 'image[align]') .appendTo(wrapper) // Create select options var options = { none : 'None', left : 'To left', right : 'To right' } $.each(options, function(value, caption) { var option = $(document.createElement('option')) .attr('value', value) .html(caption) .appendTo(select) if (value == 'left') option.attr('selected', true) }) return wrapper } } })(jQuery); (function( $ ) { $.fn.ImperaviPluginHyperlink = function(o) { this.initialize(o) } $.fn.ImperaviPluginHyperlink.prototype = { initialize: function(o) { this.o = o this.dialog = new $.fn.ImperaviDialog({ title : 'Insert hyperlink', width : 450, height : 237, onRemove : function() { alert('fuck yeah!') this.hide() }, onOkay : function() { alert('fuck') this.hide() } }) this.dialog.show() this.dialog.el.addClass('imperavi-plugin-hyperlink') this.dialog.addButton('Remove', 'remove') this.build() }, build: function() { var wrapper = $(document.createElement('div')) var url = this.build_input('Url', 'url').appendTo(wrapper) var caption = this.build_input('Title', 'title').appendTo(wrapper) this.dialog.setContent(wrapper) }, build_input: function(title, name) { var wrapper = $(document.createElement('div')) .addClass('field') var label = $(document.createElement('label')) .attr('for', name) .html(title) .appendTo(wrapper) var url = $(document.createElement('input')) .attr('type', 'text') .attr('name', name) .attr('id', name) .appendTo(wrapper) return wrapper } } })(jQuery); (function( $ ) { $.fn.ImperaviPluginFile = function(o) { this.initialize(o) } $.fn.ImperaviPluginFile.prototype = { initialize: function(o) { this.o = o this.dialog = new $.fn.ImperaviDialog({ title : 'Attach file', width : 450, height : 237, onRemove : function() { alert('fuck yeah!') this.hide() }, onOkay : function() { alert('fuck') this.hide() } }) this.dialog.show() this.dialog.el.addClass('imperavi-plugin-file') this.dialog.addButton('Remove', 'remove') this.build() }, build: function() { var wrapper = $(document.createElement('div')) var file = this.build_input('File', 'attachment').appendTo(wrapper) //var caption = this.build_input('Title', 'title').appendTo(wrapper) this.dialog.setContent(wrapper) }, build_input: function(title, name) { var wrapper = $(document.createElement('div')) .addClass('field') var label = $(document.createElement('label')) .attr('for', name) .html(title) .appendTo(wrapper) var file = $(document.createElement('input')) .attr('type', 'file') .attr('name', name) .attr('id', name) .appendTo(wrapper) return wrapper } } })(jQuery); // TODO: add custom events // - onShow // - onClose // - onBuilt // - onContentLoaded // - onOkay // - onCancel (function( $ ) { $.fn.ImperaviDialog = function(o) { var o = $.extend({ onOkay : function() { this.hide() }, onCancel : function() { this.hide() }, onClose : function(e) { this.close(e) }, onBuilt : function() {}, onLoad : function() {} }, o) this.initialize(o) } $.fn.ImperaviDialog.prototype = { el : null, o : null, overlay : null, initialize: function(o) { // Retrieve user options passed to imperavi this.o = $.extend($.fn.ImperaviOptions().options.dialog, o) }, build: function() { // Build dialog just once if (this.el) return; // Create overlay this.overlay = new $.fn.ImperaviOverlay() // Dialog window this.el = $(document.createElement('div')) .attr('id', 'imperavi-dialog') .appendTo($('body')); this.container = $(document.createElement('div')) .attr('id', 'imperavi-dialog-container') .appendTo(this.el); // Close button this.closeBtn = $(document.createElement('a')) .attr('href', 'javascript:;') .html('×') .attr('id', 'imperavi-dialog-close') .appendTo(this.container); // Dialog title this.title = $(document.createElement('h1')) .attr('id', 'imperavi-dialog-title') .appendTo(this.container); // Dialog content this.article = $(document.createElement('article')) .attr('id', 'imperavi-dialog-content') .appendTo(this.container); // Buttons panel this.buttons_wrapper = $(document.createElement('div')) .attr('id', 'imperavi-dialog-buttons-wrapper') .appendTo(this.container); this.buttons = $(document.createElement('div')) .attr('id', 'imperavi-dialog-buttons') .appendTo(this.buttons_wrapper); this.okay_button = this.addButton('Okay', 'okay') this.cancel_button = this.addButton('Cancel', 'cancel') // Set default size this.setSize(this.o.width, this.o.height) // Set default title this.setTitle(this.o.title) this.o.onBuilt.call(this) }, addButton: function(caption, name) { var callbackName = 'on' + name.charAt(0).toUpperCase() + name.slice(1) return $(document.createElement('a')) .attr('id', 'imperavi-dialog-' + name) .attr('href', 'javascript:;') .html(caption) .click($.proxy(function(){ this.o[callbackName].call(this) }, this)) .appendTo(this.buttons); }, addEvents: function() { var onCloseCallback = $.proxy(function(e){ this.o.onClose.call(this, e) }, this) $(document).keyup(function(e) { onCloseCallback(e) }) this.closeBtn.click(function(e) { onCloseCallback(e) }) this.overlay.el.click(function(e) { onCloseCallback(e) }) }, removeEvents: function() { var onCloseCallback = $.proxy(function(e){ this.o.onClose.call(this, e) }, this) $(document).unbind('keyup', onCloseCallback) this.closeBtn.unbind('click', onCloseCallback) this.overlay.el.unbind('click', onCloseCallback) }, setSize: function(width, height) { this.el.css({ width : width + 'px', height : height + 'px', marginTop : '-' + height / 2 + 'px', marginLeft : '-' + width / 2 + 'px' }).fadeIn('fast'); this.container.css({ width : width + 'px', height : height + 'px', }) }, setTitle: function(title) { this.title.html(title) }, setContent: function(content) { this.article.html(content) }, // TODO Load content via ajax loadContent: function(url) { this.setContent('') this.o.onLoad.call(this) }, cleanUp: function() { this.removeEvents() this.setContent('') this.setTitle('') }, show: function() { this.build() this.overlay.show() this.el.show() this.addEvents() }, hide: function() { this.el.hide() this.overlay.hide() this.cleanUp() }, close: function(e) { if (e.keyCode == 27 || e.type == 'click') this.hide() } } })(jQuery); (function( $ ) { $.fn.ImperaviOverlay = function(o) { this.initialize(o) } $.fn.ImperaviOverlay.prototype = { el : null, initialize: function(o) { this.o = o }, build: function() { if (this.el) return; this.el = $(document.createElement('div')) .attr('id', 'imperavi-overlay') .appendTo($('body')); }, show: function() { this.build() this.el.show() }, hide: function() { this.el.hide() } } })(jQuery); (function( $ ) { $.fn.ImperaviIframe = function(textarea, o) { this.initialize(textarea, o) } $.fn.ImperaviIframe.prototype = { textarea : null, wrapper : null, el : null, initialize: function(textarea, o) { this.textarea = textarea this.o = o this.textarea.hide(); this.build() this.populate() this.enable(true) }, // Build Iframe object and stuff build: function() { this.wrapper = $(document.createElement('div')) .addClass('imperavi') .insertAfter(this.textarea) this.el = $(document.createElement('iframe')) .appendTo(this.wrapper) .css({ width : this.textarea.outerWidth(), height : this.textarea.outerHeight() }) }, populate: function() { html = '' html += '' //html += '' //html += '' html += '' + this.textarea.val() html += '' this.doc().open(); this.doc().write(html); this.doc().close(); }, enableObjects: function() { if (!$.browser.mozilla) return; //this.doc().execCommand('styleWithCSS', false, false) //this.doc().execCommand('enableObjectResizing', false, false) //this.doc().execCommand('enableInlineTableEditing', false, false) }, observe: function() { }, enable: function(status) { // Located here for Chrome support this.doc().designMode = status ? 'on' : 'off'; this.el.load($.proxy(function() { this.enableObjects(); this.observe(); }, this)); }, doc: function() { var i = this.el.get(0) if (i.contentDocument) return i.contentDocument if (i.contentWindow) return i.contentWindow.document return i.document } } })(jQuery); (function( $ ) { $.fn.ImperaviIframeResizer = function(iframe, o) { this.initialize(iframe, o) } $.fn.ImperaviIframeResizer.prototype = { iframe : null, el : null, initialize: function(iframe, o) { this.iframe = iframe this.o = o this.build() }, build: function() { this.el = $(document.createElement('div')) .addClass('imperavi-resizer') .insertAfter(this.iframe.el) this.el.append($(document.createElement('div'))) } } })(jQuery); (function( $ ) { $.fn.ImperaviToolbar = function(iframe, o) { var o = $.extend({ onButtonClick : function(button) {}, }, o) this.initialize(iframe, o) } $.fn.ImperaviToolbar.prototype = { iframe : null, el : null, initialize: function(iframe, o) { this.iframe = iframe this.o = o this.x = $.fn.ImperaviToolbarDefault // TODO make it pretty this.l = $.fn.ImperaviLanguages.ru // TODO make it pretty this.build() }, // Build Toolbar object build: function() { this.el = $(document.createElement('ul')) .insertBefore(this.iframe.el); $.each(this.x, $.proxy(function(key, value) { // Buttons with dropdown if (typeof value == 'object') { this.el.append(this.addDropdown(key, value)) } else if (typeof value == 'boolean' && value == true) { var title = typeof this.l[key] == 'object' ? this.l[key].name : this.l[key] this.el.append(this.addButton(key, title, null)) } }, this)); }, addButton: function(name, title, caption) { var li = $(document.createElement('li')).addClass('button-' + name) var a = $(document.createElement('a')) .attr('href', 'javascript:;') .attr('rel', name) .attr('title', title) .appendTo(li) // This executes a custom callback on button click .click($.proxy(function(){ this.o.onButtonClick.call(this, a) }, this)) var span = $(document.createElement('span')) .html(caption) .appendTo(a); return li.append(a) }, addDropdown: function(name, items) { var button = this.addButton(name, this.l[name].name, null) var ul = $(document.createElement('ul')) button.addClass('has-dropdown') // Add dropdown items $.each(items, $.proxy(function(key, value) { if (typeof value == 'object') { var separator = true $.each(value, $.proxy(function(key2, value2) { if (value2 == true) { var item = this.addButton(key2, null, this.l[name][key][key2]) if (separator) item.addClass('separator') ul.append(item) separator = false } }, this)); } else if (typeof value == 'boolean' && value == true) { ul.append( this.addButton(key, null, this.l[name][key]) ) } }, this)); return button.append(ul) } } })(jQuery); (function( $ ) { $.fn.imperavi = function(o) { // Editor options var o = $.extend({ locale : 'ru', // TODO replace with $.fn.ImperaviLanguage resizer : $.fn.ImperaviIframeResizer, dialog : $.fn.ImperaviDialog, overlay : $.fn.ImperaviOverlay, iframe : $.fn.ImperaviIframe, toolbar : $.fn.ImperaviToolbar, delegator : $.fn.ImperaviActionDelegator, options : { dialog : { title : 'Default title', width : 500, height : 300 } } }, o) // Global options $.fn.ImperaviOptions = function() { return o } // Main object $.fn.Imperavi = function(el) { this.initialize(el) } $.fn.Imperavi.prototype = { textarea : null, iframe : null, toolbar : null, resizer : null, delegator : null, // Initialize imperavi initialize: function(el) { this.textarea = $(el) this.build() this.autosave() }, build: function() { // Delegate action to another object this.delegator = new o.delegator // Create iframe this.iframe = new o.iframe(this.textarea, o) // Create editor resizer this.resizer = new o.resizer(this.iframe, o) // Create toolbar this.toolbar = new o.toolbar(this.iframe, { onButtonClick : $.proxy(function(button) { this.delegator.delegateButtonClick(button, this.iframe) }, this) }) }, autosave: function() { // TODO: implement } } // Apply imperavi for each selected element return this.each(function() { new $.fn.Imperavi(this) }) } })(jQuery); // Vendor // Imperavi ;