summaryrefslogtreecommitdiff
path: root/lib/scripts
diff options
context:
space:
mode:
Diffstat (limited to 'lib/scripts')
-rw-r--r--lib/scripts/behaviour.js42
-rw-r--r--lib/scripts/compatibility.js172
-rw-r--r--lib/scripts/cookie.js71
-rw-r--r--lib/scripts/fileuploader.js1247
-rw-r--r--lib/scripts/fileuploaderextended.js339
-rw-r--r--lib/scripts/helpers.js176
-rw-r--r--lib/scripts/jquery/jquery.cookie.js111
-rw-r--r--lib/scripts/locktimer.js56
-rw-r--r--lib/scripts/media.js465
-rw-r--r--lib/scripts/page.js70
10 files changed, 2353 insertions, 396 deletions
diff --git a/lib/scripts/behaviour.js b/lib/scripts/behaviour.js
index 1580ae86f..cfdc89157 100644
--- a/lib/scripts/behaviour.js
+++ b/lib/scripts/behaviour.js
@@ -1,6 +1,3 @@
-/*jslint sloppy: true */
-/*global jQuery, LANG, document, alert */
-
/**
* Automatic behaviours
*
@@ -16,7 +13,6 @@ var dw_behaviour = {
dw_behaviour.removeHighlightOnClick();
dw_behaviour.quickSelect();
dw_behaviour.checkWindowsShares();
- dw_behaviour.initTocToggle();
dw_behaviour.subscription();
dw_behaviour.revisionBoxHandler();
@@ -67,7 +63,9 @@ var dw_behaviour = {
quickSelect: function(){
jQuery('select.quickselect')
.change(function(e){ e.target.form.submit(); })
- .parents('form').find('input[type=submit]').hide();
+ .parents('form').find('input[type=submit]').each(function(){
+ if (!jQuery(this).hasClass('show')) jQuery(this).hide();
+ });
},
/**
@@ -87,36 +85,6 @@ var dw_behaviour = {
},
/**
- * Adds the toggle switch to the TOC
- */
- initTocToggle: function() {
- var $header = jQuery('#toc__header');
- if(!$header.length) return;
- var $toc = jQuery('#toc__inside');
-
- var $clicky = jQuery(document.createElement('span'))
- .attr('id','toc__toggle')
- .css('cursor','pointer')
- .click(function(){
- $toc.slideToggle(200);
- setClicky();
- });
- $header.prepend($clicky);
-
- var setClicky = function(){
- if($toc.css('display') == 'none'){
- $clicky.html('<span>+</span>');
- $clicky[0].className = 'toc_open';
- }else{
- $clicky.html('<span>&minus;</span>');
- $clicky[0].className = 'toc_close';
- }
- };
-
- setClicky();
- },
-
- /**
* Hide list subscription style if target is a page
*
* @author Adrian Lang <lang@cosmocode.de>
@@ -201,13 +169,13 @@ jQuery.fn.dw_show = function(fn) {
*
* @param bool the current state of the element (optional)
*/
-jQuery.fn.dw_toggle = function(bool) {
+jQuery.fn.dw_toggle = function(bool, fn) {
return this.each(function() {
var $this = jQuery(this);
if (typeof bool === 'undefined') {
bool = $this.is(':hidden');
}
- $this[bool ? "dw_show" : "dw_hide" ]();
+ $this[bool ? "dw_show" : "dw_hide" ](fn);
});
};
diff --git a/lib/scripts/compatibility.js b/lib/scripts/compatibility.js
index ddc8823d3..39f703c71 100644
--- a/lib/scripts/compatibility.js
+++ b/lib/scripts/compatibility.js
@@ -1,6 +1,3 @@
-/*jslint sloppy: true */
-/*global dw_index, dw_qsearch, DEPRECATED_WRAP */
-
/**
* Mark a JavaScript function as deprecated
*
@@ -209,4 +206,173 @@ function jsEscape(text){
return text;
}
+/**
+ * Simple function to check if a global var is defined
+ *
+ * @author Kae Verens
+ * @link http://verens.com/archives/2005/07/25/isset-for-javascript/#comment-2835
+ */
+function isset(varname){
+ DEPRECATED("Use `typeof var !== 'undefined'` instead");
+ return(typeof(window[varname])!='undefined');
+}
+
+/**
+ * Checks if property is undefined
+ *
+ * @param {Object} prop value to check
+ * @return {Boolean} true if matched
+ * @scope public
+ * @author Ilya Lebedev <ilya@lebedev.net>
+ */
+function isUndefined (prop /* :Object */) /* :Boolean */ {
+ DEPRECATED("Use `typeof var === 'undefined'` instead");
+ return (typeof prop == 'undefined');
+}
+
+/**
+ * Checks if property is function
+ *
+ * @param {Object} prop value to check
+ * @return {Boolean} true if matched
+ * @scope public
+ * @author Ilya Lebedev <ilya@lebedev.net>
+ */
+function isFunction (prop /* :Object */) /* :Boolean */ {
+ DEPRECATED("Use `typeof var === 'function'` instead");
+ return (typeof prop == 'function');
+}
+/**
+ * Checks if property is string
+ *
+ * @param {Object} prop value to check
+ * @return {Boolean} true if matched
+ * @scope public
+ * @author Ilya Lebedev <ilya@lebedev.net>
+ */
+function isString (prop /* :Object */) /* :Boolean */ {
+ DEPRECATED("Use `typeof var === 'string'` instead");
+ return (typeof prop == 'string');
+}
+
+/**
+ * Checks if property is number
+ *
+ * @param {Object} prop value to check
+ * @return {Boolean} true if matched
+ * @scope public
+ * @author Ilya Lebedev <ilya@lebedev.net>
+ */
+function isNumber (prop /* :Object */) /* :Boolean */ {
+ DEPRECATED("Use `typeof var === 'number'` instead");
+ return (typeof prop == 'number');
+}
+
+/**
+ * Checks if property is the calculable number
+ *
+ * @param {Object} prop value to check
+ * @return {Boolean} true if matched
+ * @scope public
+ * @author Ilya Lebedev <ilya@lebedev.net>
+ */
+function isNumeric (prop /* :Object */) /* :Boolean */ {
+ DEPRECATED("Use `typeof var === 'number' && !isNaN(var) && isFinite(var)` instead");
+ return isNumber(prop)&&!isNaN(prop)&&isFinite(prop);
+}
+
+/**
+ * Checks if property is array
+ *
+ * @param {Object} prop value to check
+ * @return {Boolean} true if matched
+ * @scope public
+ * @author Ilya Lebedev <ilya@lebedev.net>
+ */
+function isArray (prop /* :Object */) /* :Boolean */ {
+ DEPRECATED("Use `var instanceof Array` instead");
+ return (prop instanceof Array);
+}
+
+/**
+ * Checks if property is regexp
+ *
+ * @param {Object} prop value to check
+ * @return {Boolean} true if matched
+ * @scope public
+ * @author Ilya Lebedev <ilya@lebedev.net>
+ */
+function isRegExp (prop /* :Object */) /* :Boolean */ {
+ DEPRECATED("Use `var instanceof RegExp` instead");
+ return (prop instanceof RegExp);
+}
+
+/**
+ * Checks if property is a boolean value
+ *
+ * @param {Object} prop value to check
+ * @return {Boolean} true if matched
+ * @scope public
+ * @author Ilya Lebedev <ilya@lebedev.net>
+ */
+function isBoolean (prop /* :Object */) /* :Boolean */ {
+ DEPRECATED("Use `typeof var === 'boolean'` instead");
+ return ('boolean' == typeof prop);
+}
+
+/**
+ * Checks if property is a scalar value (value that could be used as the hash key)
+ *
+ * @param {Object} prop value to check
+ * @return {Boolean} true if matched
+ * @scope public
+ * @author Ilya Lebedev <ilya@lebedev.net>
+ */
+function isScalar (prop /* :Object */) /* :Boolean */ {
+ DEPRECATED("Use `typeof var === 'string' || (typeof var === 'number' &&" +
+ " !isNaN(var) && isFinite(var))` instead");
+ return isNumeric(prop)||isString(prop);
+}
+
+/**
+ * Checks if property is empty
+ *
+ * @param {Object} prop value to check
+ * @return {Boolean} true if matched
+ * @scope public
+ * @author Ilya Lebedev <ilya@lebedev.net>
+ */
+function isEmpty (prop /* :Object */) /* :Boolean */ {
+ DEPRECATED();
+ var i;
+ if (isBoolean(prop)) {
+ return false;
+ } else if (isRegExp(prop) && new RegExp("").toString() == prop.toString()) {
+ return true;
+ } else if (isString(prop) || isNumber(prop)) {
+ return !prop;
+ } else if (Boolean(prop) && false != prop) {
+ for (i in prop) {
+ if(prop.hasOwnProperty(i)) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
+/**
+ * Get the computed style of a node.
+ *
+ * @link https://acidmartin.wordpress.com/2008/08/26/style-get-any-css-property-value-of-an-object/
+ * @link http://svn.dojotoolkit.org/src/dojo/trunk/_base/html.js
+ */
+function gcs(node){
+ DEPRECATED('Use jQuery(node).style() instead');
+ if(node.currentStyle){
+ return node.currentStyle;
+ }else{
+ return node.ownerDocument.defaultView.getComputedStyle(node, null);
+ }
+}
diff --git a/lib/scripts/cookie.js b/lib/scripts/cookie.js
index f7d9b5ffb..4dd77beea 100644
--- a/lib/scripts/cookie.js
+++ b/lib/scripts/cookie.js
@@ -2,7 +2,7 @@
* Handles the cookie used by several JavaScript functions
*
* Only a single cookie is written and read. You may only save
-* sime name-value pairs - no complex types!
+* simple name-value pairs - no complex types!
*
* You should only use the getValue and setValue methods
*
@@ -10,7 +10,7 @@
* @author Michal Rezler <m.rezler@centrum.cz>
*/
DokuCookie = {
- data: Array(),
+ data: {},
name: 'DOKU_PREFS',
/**
@@ -19,21 +19,17 @@ DokuCookie = {
* @author Andreas Gohr <andi@splitbrain.org>
*/
setValue: function(key,val){
+ var text = '';
this.init();
this.data[key] = val;
- // prepare expire date
- var now = new Date();
- this.fixDate(now);
- now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000); //expire in a year
-
//save the whole data array
- var text = '';
- for(var key in this.data){
- if (!this.data.hasOwnProperty(key)) continue;
- text += '#'+escape(key)+'#'+this.data[key];
+ jQuery.each(this.data, function (key, val) {
+ if (DokuCookie.data.hasOwnProperty(key)) {
+ text += '#'+encodeURIComponent(key)+'#'+encodeURIComponent(val);
}
- this.setCookie(this.name,text.substr(1),now,DOKU_BASE);
+ });
+ jQuery.cookie(this.name,text.substr(1), {expires: 365, path: DOKU_BASE});
},
/**
@@ -52,51 +48,16 @@ DokuCookie = {
* @author Andreas Gohr <andi@splitbrain.org>
*/
init: function(){
- if(this.data.length) return;
- var text = this.getCookie(this.name);
+ var text, parts, i;
+ if(!jQuery.isEmptyObject(this.data)) {
+ return;
+ }
+ text = jQuery.cookie(this.name);
if(text){
- var parts = text.split('#');
- for(var i=0; i<parts.length; i+=2){
- this.data[unescape(parts[i])] = unescape(parts[i+1]);
+ parts = text.split('#');
+ for(i = 0; i < parts.length; i += 2){
+ this.data[decodeURIComponent(parts[i])] = decodeURIComponent(parts[i+1]);
}
}
- },
-
- /**
- * This sets a cookie by JavaScript
- *
- * @link http://www.webreference.com/js/column8/functions.html
- */
- setCookie: function(name, value, expires_, path_, domain_, secure_) {
- var params = {
- expires: expires_,
- path: path_,
- domain: domain_,
- secure: secure_,
- };
-
- jQuery.cookie(name, value, params);
- },
-
- /**
- * This reads a cookie by JavaScript
- *
- * @link http://www.webreference.com/js/column8/functions.html
- */
- getCookie: function(name) {
- return unescape(jQuery.cookie(name));
- },
-
- /**
- * This is needed for the cookie functions
- *
- * @link http://www.webreference.com/js/column8/functions.html
- */
- fixDate: function(date) {
- var base = new Date(0);
- var skew = base.getTime();
- if (skew > 0){
- date.setTime(date.getTime() - skew);
}
- }
};
diff --git a/lib/scripts/fileuploader.js b/lib/scripts/fileuploader.js
new file mode 100644
index 000000000..e75b8d3a5
--- /dev/null
+++ b/lib/scripts/fileuploader.js
@@ -0,0 +1,1247 @@
+/**
+ * http://github.com/valums/file-uploader
+ *
+ * Multiple file upload component with progress-bar, drag-and-drop.
+ * © 2010 Andrew Valums ( andrew(at)valums.com )
+ *
+ * Licensed under GNU GPL 2 or later and GNU LGPL 2 or later, see license.txt.
+ */
+
+//
+// Helper functions
+//
+
+var qq = qq || {};
+
+/**
+ * Adds all missing properties from second obj to first obj
+ */
+qq.extend = function(first, second){
+ for (var prop in second){
+ first[prop] = second[prop];
+ }
+};
+
+/**
+ * Searches for a given element in the array, returns -1 if it is not present.
+ * @param {Number} [from] The index at which to begin the search
+ */
+qq.indexOf = function(arr, elt, from){
+ if (arr.indexOf) return arr.indexOf(elt, from);
+
+ from = from || 0;
+ var len = arr.length;
+
+ if (from < 0) from += len;
+
+ for (; from < len; from++){
+ if (from in arr && arr[from] === elt){
+ return from;
+ }
+ }
+ return -1;
+};
+
+qq.getUniqueId = (function(){
+ var id = 0;
+ return function(){ return id++; };
+})();
+
+//
+// Events
+
+qq.attach = function(element, type, fn){
+ if (element.addEventListener){
+ element.addEventListener(type, fn, false);
+ } else if (element.attachEvent){
+ element.attachEvent('on' + type, fn);
+ }
+};
+qq.detach = function(element, type, fn){
+ if (element.removeEventListener){
+ element.removeEventListener(type, fn, false);
+ } else if (element.attachEvent){
+ element.detachEvent('on' + type, fn);
+ }
+};
+
+qq.preventDefault = function(e){
+ if (e.preventDefault){
+ e.preventDefault();
+ } else{
+ e.returnValue = false;
+ }
+};
+
+//
+// Node manipulations
+
+/**
+ * Insert node a before node b.
+ */
+qq.insertBefore = function(a, b){
+ b.parentNode.insertBefore(a, b);
+};
+qq.remove = function(element){
+ element.parentNode.removeChild(element);
+};
+
+qq.contains = function(parent, descendant){
+ // compareposition returns false in this case
+ if (parent == descendant) return true;
+
+ if (parent.contains){
+ return parent.contains(descendant);
+ } else {
+ return !!(descendant.compareDocumentPosition(parent) & 8);
+ }
+};
+
+/**
+ * Creates and returns element from html string
+ * Uses innerHTML to create an element
+ */
+qq.toElement = (function(){
+ var div = document.createElement('div');
+ return function(html){
+ div.innerHTML = html;
+ var element = div.firstChild;
+ div.removeChild(element);
+ return element;
+ };
+})();
+
+//
+// Node properties and attributes
+
+/**
+ * Sets styles for an element.
+ * Fixes opacity in IE6-8.
+ */
+qq.css = function(element, styles){
+ if (styles.opacity != null){
+ if (typeof element.style.opacity != 'string' && typeof(element.filters) != 'undefined'){
+ styles.filter = 'alpha(opacity=' + Math.round(100 * styles.opacity) + ')';
+ }
+ }
+ qq.extend(element.style, styles);
+};
+qq.hasClass = function(element, name){
+ var re = new RegExp('(^| )' + name + '( |$)');
+ return re.test(element.className);
+};
+qq.addClass = function(element, name){
+ if (!qq.hasClass(element, name)){
+ element.className += ' ' + name;
+ }
+};
+qq.removeClass = function(element, name){
+ var re = new RegExp('(^| )' + name + '( |$)');
+ element.className = element.className.replace(re, ' ').replace(/^\s+|\s+$/g, "");
+};
+qq.setText = function(element, text){
+ element.innerText = text;
+ element.textContent = text;
+};
+
+//
+// Selecting elements
+
+qq.children = function(element){
+ var children = [],
+ child = element.firstChild;
+
+ while (child){
+ if (child.nodeType == 1){
+ children.push(child);
+ }
+ child = child.nextSibling;
+ }
+
+ return children;
+};
+
+qq.getByClass = function(element, className){
+ if (element.querySelectorAll){
+ return element.querySelectorAll('.' + className);
+ }
+
+ var result = [];
+ var candidates = element.getElementsByTagName("*");
+ var len = candidates.length;
+
+ for (var i = 0; i < len; i++){
+ if (qq.hasClass(candidates[i], className)){
+ result.push(candidates[i]);
+ }
+ }
+ return result;
+};
+
+/**
+ * obj2url() takes a json-object as argument and generates
+ * a querystring. pretty much like jQuery.param()
+ *
+ * how to use:
+ *
+ * `qq.obj2url({a:'b',c:'d'},'http://any.url/upload?otherParam=value');`
+ *
+ * will result in:
+ *
+ * `http://any.url/upload?otherParam=value&a=b&c=d`
+ *
+ * @param Object JSON-Object
+ * @param String current querystring-part
+ * @return String encoded querystring
+ */
+qq.obj2url = function(obj, temp, prefixDone){
+ var uristrings = [],
+ prefix = '&',
+ add = function(nextObj, i){
+ var nextTemp = temp
+ ? (/\[\]$/.test(temp)) // prevent double-encoding
+ ? temp
+ : temp+'['+i+']'
+ : i;
+ if ((nextTemp != 'undefined') && (i != 'undefined')) {
+ uristrings.push(
+ (typeof nextObj === 'object')
+ ? qq.obj2url(nextObj, nextTemp, true)
+ : (Object.prototype.toString.call(nextObj) === '[object Function]')
+ ? encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj())
+ : encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj)
+ );
+ }
+ };
+
+ if (!prefixDone && temp) {
+ prefix = (/\?/.test(temp)) ? (/\?$/.test(temp)) ? '' : '&' : '?';
+ uristrings.push(temp);
+ uristrings.push(qq.obj2url(obj));
+ } else if ((Object.prototype.toString.call(obj) === '[object Array]') && (typeof obj != 'undefined') ) {
+ // we wont use a for-in-loop on an array (performance)
+ for (var i = 0, len = obj.length; i < len; ++i){
+ add(obj[i], i);
+ }
+ } else if ((typeof obj != 'undefined') && (obj !== null) && (typeof obj === "object")){
+ // for anything else but a scalar, we will use for-in-loop
+ for (var i in obj){
+ add(obj[i], i);
+ }
+ } else {
+ uristrings.push(encodeURIComponent(temp) + '=' + encodeURIComponent(obj));
+ }
+
+ return uristrings.join(prefix)
+ .replace(/^&/, '')
+ .replace(/%20/g, '+');
+};
+
+//
+//
+// Uploader Classes
+//
+//
+
+var qq = qq || {};
+
+/**
+ * Creates upload button, validates upload, but doesn't create file list or dd.
+ */
+qq.FileUploaderBasic = function(o){
+ this._options = {
+ // set to true to see the server response
+ debug: false,
+ action: '/server/upload',
+ params: {},
+ button: null,
+ multiple: true,
+ maxConnections: 3,
+ // validation
+ allowedExtensions: [],
+ sizeLimit: 0,
+ minSizeLimit: 0,
+ // events
+ // return false to cancel submit
+ onSubmit: function(id, fileName){},
+ onProgress: function(id, fileName, loaded, total){},
+ onComplete: function(id, fileName, responseJSON){},
+ onCancel: function(id, fileName){},
+ // messages
+ messages: {
+ typeError: "{file} has invalid extension. Only {extensions} are allowed.",
+ sizeError: "{file} is too large, maximum file size is {sizeLimit}.",
+ minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.",
+ emptyError: "{file} is empty, please select files again without it.",
+ onLeave: "The files are being uploaded, if you leave now the upload will be cancelled."
+ },
+ showMessage: function(message){
+ alert(message);
+ }
+ };
+ qq.extend(this._options, o);
+
+ // number of files being uploaded
+ this._filesInProgress = 0;
+ this._handler = this._createUploadHandler();
+
+ if (this._options.button){
+ this._button = this._createUploadButton(this._options.button);
+ }
+
+ this._preventLeaveInProgress();
+};
+
+qq.FileUploaderBasic.prototype = {
+ setParams: function(params){
+ this._options.params = params;
+ },
+ getInProgress: function(){
+ return this._filesInProgress;
+ },
+ _createUploadButton: function(element){
+ var self = this;
+
+ return new qq.UploadButton({
+ element: element,
+ multiple: this._options.multiple && qq.UploadHandlerXhr.isSupported(),
+ onChange: function(input){
+ self._onInputChange(input);
+ }
+ });
+ },
+ _createUploadHandler: function(){
+ var self = this,
+ handlerClass;
+
+ if(qq.UploadHandlerXhr.isSupported()){
+ handlerClass = 'UploadHandlerXhr';
+ } else {
+ handlerClass = 'UploadHandlerForm';
+ }
+
+ var handler = new qq[handlerClass]({
+ debug: this._options.debug,
+ action: this._options.action,
+ maxConnections: this._options.maxConnections,
+ onProgress: function(id, fileName, loaded, total){
+ self._onProgress(id, fileName, loaded, total);
+ self._options.onProgress(id, fileName, loaded, total);
+ },
+ onComplete: function(id, fileName, result){
+ self._onComplete(id, fileName, result);
+ self._options.onComplete(id, fileName, result);
+ },
+ onCancel: function(id, fileName){
+ self._onCancel(id, fileName);
+ self._options.onCancel(id, fileName);
+ }
+ });
+
+ return handler;
+ },
+ _preventLeaveInProgress: function(){
+ var self = this;
+
+ qq.attach(window, 'beforeunload', function(e){
+ if (!self._filesInProgress){return;}
+
+ var e = e || window.event;
+ // for ie, ff
+ e.returnValue = self._options.messages.onLeave;
+ // for webkit
+ return self._options.messages.onLeave;
+ });
+ },
+ _onSubmit: function(id, fileName){
+ this._filesInProgress++;
+ },
+ _onProgress: function(id, fileName, loaded, total){
+ },
+ _onComplete: function(id, fileName, result){
+ this._filesInProgress--;
+ if (result.error){
+ this._options.showMessage(result.error);
+ }
+ },
+ _onCancel: function(id, fileName){
+ this._filesInProgress--;
+ },
+ _onInputChange: function(input){
+ if (this._handler instanceof qq.UploadHandlerXhr){
+ this._uploadFileList(input.files);
+ } else {
+ if (this._validateFile(input)){
+ this._uploadFile(input);
+ }
+ }
+ this._button.reset();
+ },
+ _uploadFileList: function(files){
+ for (var i=0; i<files.length; i++){
+ if ( !this._validateFile(files[i])){
+ return;
+ }
+ }
+
+ for (var i=0; i<files.length; i++){
+ this._uploadFile(files[i]);
+ }
+ },
+ _uploadFile: function(fileContainer){
+ var id = this._handler.add(fileContainer);
+ var fileName = this._handler.getName(id);
+
+ if (this._options.onSubmit(id, fileName) !== false){
+ this._onSubmit(id, fileName);
+ this._handler.upload(id, this._options.params);
+ }
+ },
+ _validateFile: function(file){
+ var name, size;
+
+ if (file.value){
+ // it is a file input
+ // get input value and remove path to normalize
+ name = file.value.replace(/.*(\/|\\)/, "");
+ } else {
+ // fix missing properties in Safari
+ name = file.fileName != null ? file.fileName : file.name;
+ size = file.fileSize != null ? file.fileSize : file.size;
+ }
+
+ if (! this._isAllowedExtension(name)){
+ this._error('typeError', name);
+ return false;
+
+ } else if (size === 0){
+ this._error('emptyError', name);
+ return false;
+
+ } else if (size && this._options.sizeLimit && size > this._options.sizeLimit){
+ this._error('sizeError', name);
+ return false;
+
+ } else if (size && size < this._options.minSizeLimit){
+ this._error('minSizeError', name);
+ return false;
+ }
+
+ return true;
+ },
+ _error: function(code, fileName){
+ var message = this._options.messages[code];
+ function r(name, replacement){ message = message.replace(name, replacement); }
+
+ r('{file}', this._formatFileName(fileName));
+ r('{extensions}', this._options.allowedExtensions.join(', '));
+ r('{sizeLimit}', this._formatSize(this._options.sizeLimit));
+ r('{minSizeLimit}', this._formatSize(this._options.minSizeLimit));
+
+ this._options.showMessage(message);
+ },
+ _formatFileName: function(name){
+ if (name.length > 33){
+ name = name.slice(0, 19) + '...' + name.slice(-13);
+ }
+ return name;
+ },
+ _isAllowedExtension: function(fileName){
+ var ext = (-1 !== fileName.indexOf('.')) ? fileName.replace(/.*[.]/, '').toLowerCase() : '';
+ var allowed = this._options.allowedExtensions;
+
+ if (!allowed.length){return true;}
+
+ for (var i=0; i<allowed.length; i++){
+ if (allowed[i].toLowerCase() == ext){ return true;}
+ }
+
+ return false;
+ },
+ _formatSize: function(bytes){
+ var i = -1;
+ do {
+ bytes = bytes / 1024;
+ i++;
+ } while (bytes > 99);
+
+ return Math.max(bytes, 0.1).toFixed(1) + ['kB', 'MB', 'GB', 'TB', 'PB', 'EB'][i];
+ }
+};
+
+
+/**
+ * Class that creates upload widget with drag-and-drop and file list
+ * @inherits qq.FileUploaderBasic
+ */
+qq.FileUploader = function(o){
+ // call parent constructor
+ qq.FileUploaderBasic.apply(this, arguments);
+
+ // additional options
+ qq.extend(this._options, {
+ element: null,
+ // if set, will be used instead of qq-upload-list in template
+ listElement: null,
+
+ template: '<div class="qq-uploader">' +
+ '<div class="qq-upload-drop-area"><span>Drop files here to upload</span></div>' +
+ '<div class="qq-upload-button">Upload a file</div>' +
+ '<ul class="qq-upload-list"></ul>' +
+ '</div>',
+
+ // template for one item in file list
+ fileTemplate: '<li>' +
+ '<span class="qq-upload-file"></span>' +
+ '<span class="qq-upload-spinner"></span>' +
+ '<span class="qq-upload-size"></span>' +
+ '<a class="qq-upload-cancel" href="#">Cancel</a>' +
+ '<span class="qq-upload-failed-text">Failed</span>' +
+ '</li>',
+
+ classes: {
+ // used to get elements from templates
+ button: 'qq-upload-button',
+ drop: 'qq-upload-drop-area',
+ dropActive: 'qq-upload-drop-area-active',
+ list: 'qq-upload-list',
+
+ file: 'qq-upload-file',
+ spinner: 'qq-upload-spinner',
+ size: 'qq-upload-size',
+ cancel: 'qq-upload-cancel',
+
+ // added to list item when upload completes
+ // used in css to hide progress spinner
+ success: 'qq-upload-success',
+ fail: 'qq-upload-fail'
+ }
+ });
+ // overwrite options with user supplied
+ qq.extend(this._options, o);
+
+ this._element = this._options.element;
+ this._element.innerHTML = this._options.template;
+ this._listElement = this._options.listElement || this._find(this._element, 'list');
+
+ this._classes = this._options.classes;
+
+ this._button = this._createUploadButton(this._find(this._element, 'button'));
+
+ this._bindCancelEvent();
+ this._setupDragDrop();
+};
+
+// inherit from Basic Uploader
+qq.extend(qq.FileUploader.prototype, qq.FileUploaderBasic.prototype);
+
+qq.extend(qq.FileUploader.prototype, {
+ /**
+ * Gets one of the elements listed in this._options.classes
+ **/
+ _find: function(parent, type){
+ var element = qq.getByClass(parent, this._options.classes[type])[0];
+ if (!element){
+ throw new Error('element not found ' + type);
+ }
+
+ return element;
+ },
+ _setupDragDrop: function(){
+ var self = this,
+ dropArea = this._find(this._element, 'drop');
+
+ var dz = new qq.UploadDropZone({
+ element: dropArea,
+ onEnter: function(e){
+ qq.addClass(dropArea, self._classes.dropActive);
+ e.stopPropagation();
+ },
+ onLeave: function(e){
+ e.stopPropagation();
+ },
+ onLeaveNotDescendants: function(e){
+ qq.removeClass(dropArea, self._classes.dropActive);
+ },
+ onDrop: function(e){
+ dropArea.style.display = 'none';
+ qq.removeClass(dropArea, self._classes.dropActive);
+ self._uploadFileList(e.dataTransfer.files);
+ }
+ });
+
+ dropArea.style.display = 'none';
+
+ qq.attach(document, 'dragenter', function(e){
+ if (!dz._isValidFileDrag(e)) return;
+
+ dropArea.style.display = 'block';
+ });
+ qq.attach(document, 'dragleave', function(e){
+ if (!dz._isValidFileDrag(e)) return;
+
+ var relatedTarget = document.elementFromPoint(e.clientX, e.clientY);
+ // only fire when leaving document out
+ if ( ! relatedTarget || relatedTarget.nodeName == "HTML"){
+ dropArea.style.display = 'none';
+ }
+ });
+ },
+ _onSubmit: function(id, fileName){
+ qq.FileUploaderBasic.prototype._onSubmit.apply(this, arguments);
+ this._addToList(id, fileName);
+ },
+ _onProgress: function(id, fileName, loaded, total){
+ qq.FileUploaderBasic.prototype._onProgress.apply(this, arguments);
+
+ var item = this._getItemByFileId(id);
+ var size = this._find(item, 'size');
+ size.style.display = 'inline';
+
+ var text;
+ if (loaded != total){
+ text = Math.round(loaded / total * 100) + '% from ' + this._formatSize(total);
+ } else {
+ text = this._formatSize(total);
+ }
+
+ qq.setText(size, text);
+ },
+ _onComplete: function(id, fileName, result){
+ qq.FileUploaderBasic.prototype._onComplete.apply(this, arguments);
+
+ // mark completed
+ var item = this._getItemByFileId(id);
+ qq.remove(this._find(item, 'cancel'));
+ qq.remove(this._find(item, 'spinner'));
+
+ if (result.success){
+ qq.addClass(item, this._classes.success);
+ } else {
+ qq.addClass(item, this._classes.fail);
+ }
+ },
+ _addToList: function(id, fileName){
+ var item = qq.toElement(this._options.fileTemplate);
+ item.qqFileId = id;
+
+ var fileElement = this._find(item, 'file');
+ qq.setText(fileElement, this._formatFileName(fileName));
+ this._find(item, 'size').style.display = 'none';
+
+ this._listElement.appendChild(item);
+ },
+ _getItemByFileId: function(id){
+ var item = this._listElement.firstChild;
+
+ // there can't be txt nodes in dynamically created list
+ // and we can use nextSibling
+ while (item){
+ if (item.qqFileId == id) return item;
+ item = item.nextSibling;
+ }
+ },
+ /**
+ * delegate click event for cancel link
+ **/
+ _bindCancelEvent: function(){
+ var self = this,
+ list = this._listElement;
+
+ qq.attach(list, 'click', function(e){
+ e = e || window.event;
+ var target = e.target || e.srcElement;
+
+ if (qq.hasClass(target, self._classes.cancel)){
+ qq.preventDefault(e);
+
+ var item = target.parentNode;
+ self._handler.cancel(item.qqFileId);
+ qq.remove(item);
+ }
+ });
+ }
+});
+
+qq.UploadDropZone = function(o){
+ this._options = {
+ element: null,
+ onEnter: function(e){},
+ onLeave: function(e){},
+ // is not fired when leaving element by hovering descendants
+ onLeaveNotDescendants: function(e){},
+ onDrop: function(e){}
+ };
+ qq.extend(this._options, o);
+
+ this._element = this._options.element;
+
+ this._disableDropOutside();
+ this._attachEvents();
+};
+
+qq.UploadDropZone.prototype = {
+ _disableDropOutside: function(e){
+ // run only once for all instances
+ if (!qq.UploadDropZone.dropOutsideDisabled ){
+
+ qq.attach(document, 'dragover', function(e){
+ if (e.dataTransfer){
+ e.dataTransfer.dropEffect = 'none';
+ e.preventDefault();
+ }
+ });
+
+ qq.UploadDropZone.dropOutsideDisabled = true;
+ }
+ },
+ _attachEvents: function(){
+ var self = this;
+
+ qq.attach(self._element, 'dragover', function(e){
+ if (!self._isValidFileDrag(e)) return;
+
+ var effect = e.dataTransfer.effectAllowed;
+ if (effect == 'move' || effect == 'linkMove'){
+ e.dataTransfer.dropEffect = 'move'; // for FF (only move allowed)
+ } else {
+ e.dataTransfer.dropEffect = 'copy'; // for Chrome
+ }
+
+ e.stopPropagation();
+ e.preventDefault();
+ });
+
+ qq.attach(self._element, 'dragenter', function(e){
+ if (!self._isValidFileDrag(e)) return;
+
+ self._options.onEnter(e);
+ });
+
+ qq.attach(self._element, 'dragleave', function(e){
+ if (!self._isValidFileDrag(e)) return;
+
+ self._options.onLeave(e);
+
+ var relatedTarget = document.elementFromPoint(e.clientX, e.clientY);
+ // do not fire when moving a mouse over a descendant
+ if (qq.contains(this, relatedTarget)) return;
+
+ self._options.onLeaveNotDescendants(e);
+ });
+
+ qq.attach(self._element, 'drop', function(e){
+ if (!self._isValidFileDrag(e)) return;
+
+ e.preventDefault();
+ self._options.onDrop(e);
+ });
+ },
+ _isValidFileDrag: function(e){
+ var dt = e.dataTransfer,
+ // do not check dt.types.contains in webkit, because it crashes safari 4
+ isWebkit = navigator.userAgent.indexOf("AppleWebKit") > -1;
+
+ // dt.effectAllowed is none in Safari 5
+ // dt.types.contains check is for firefox
+ return dt && dt.effectAllowed != 'none' &&
+ (dt.files || (!isWebkit && dt.types.contains && dt.types.contains('Files')));
+
+ }
+};
+
+qq.UploadButton = function(o){
+ this._options = {
+ element: null,
+ // if set to true adds multiple attribute to file input
+ multiple: false,
+ // name attribute of file input
+ name: 'file',
+ onChange: function(input){},
+ hoverClass: 'qq-upload-button-hover',
+ focusClass: 'qq-upload-button-focus'
+ };
+
+ qq.extend(this._options, o);
+
+ this._element = this._options.element;
+
+ // make button suitable container for input
+ qq.css(this._element, {
+ position: 'relative',
+ overflow: 'hidden',
+ // Make sure browse button is in the right side
+ // in Internet Explorer
+ direction: 'ltr'
+ });
+
+ this._input = this._createInput();
+};
+
+qq.UploadButton.prototype = {
+ /* returns file input element */
+ getInput: function(){
+ return this._input;
+ },
+ /* cleans/recreates the file input */
+ reset: function(){
+ if (this._input.parentNode){
+ qq.remove(this._input);
+ }
+
+ qq.removeClass(this._element, this._options.focusClass);
+ this._input = this._createInput();
+ },
+ _createInput: function(){
+ var input = document.createElement("input");
+
+ if (this._options.multiple){
+ input.setAttribute("multiple", "multiple");
+ }
+
+ input.setAttribute("type", "file");
+ input.setAttribute("name", this._options.name);
+
+ qq.css(input, {
+ position: 'absolute',
+ // in Opera only 'browse' button
+ // is clickable and it is located at
+ // the right side of the input
+ right: 0,
+ top: 0,
+ fontFamily: 'Arial',
+ // 4 persons reported this, the max values that worked for them were 243, 236, 236, 118
+ fontSize: '118px',
+ margin: 0,
+ padding: 0,
+ cursor: 'pointer',
+ opacity: 0
+ });
+
+ this._element.appendChild(input);
+
+ var self = this;
+ qq.attach(input, 'change', function(){
+ self._options.onChange(input);
+ });
+
+ qq.attach(input, 'mouseover', function(){
+ qq.addClass(self._element, self._options.hoverClass);
+ });
+ qq.attach(input, 'mouseout', function(){
+ qq.removeClass(self._element, self._options.hoverClass);
+ });
+ qq.attach(input, 'focus', function(){
+ qq.addClass(self._element, self._options.focusClass);
+ });
+ qq.attach(input, 'blur', function(){
+ qq.removeClass(self._element, self._options.focusClass);
+ });
+
+ // IE and Opera, unfortunately have 2 tab stops on file input
+ // which is unacceptable in our case, disable keyboard access
+ if (window.attachEvent){
+ // it is IE or Opera
+ input.setAttribute('tabIndex', "-1");
+ }
+
+ return input;
+ }
+};
+
+/**
+ * Class for uploading files, uploading itself is handled by child classes
+ */
+qq.UploadHandlerAbstract = function(o){
+ this._options = {
+ debug: false,
+ action: '/upload.php',
+ // maximum number of concurrent uploads
+ maxConnections: 999,
+ onProgress: function(id, fileName, loaded, total){},
+ onComplete: function(id, fileName, response){},
+ onCancel: function(id, fileName){}
+ };
+ qq.extend(this._options, o);
+
+ this._queue = [];
+ // params for files in queue
+ this._params = [];
+};
+qq.UploadHandlerAbstract.prototype = {
+ log: function(str){
+ if (this._options.debug && window.console) console.log('[uploader] ' + str);
+ },
+ /**
+ * Adds file or file input to the queue
+ * @returns id
+ **/
+ add: function(file){},
+ /**
+ * Sends the file identified by id and additional query params to the server
+ */
+ upload: function(id, params){
+ var len = this._queue.push(id);
+
+ var copy = {};
+ qq.extend(copy, params);
+ this._params[id] = copy;
+
+ // if too many active uploads, wait...
+ if (len <= this._options.maxConnections){
+ this._upload(id, this._params[id]);
+ }
+ },
+ /**
+ * Cancels file upload by id
+ */
+ cancel: function(id){
+ this._cancel(id);
+ this._dequeue(id);
+ },
+ /**
+ * Cancells all uploads
+ */
+ cancelAll: function(){
+ for (var i=0; i<this._queue.length; i++){
+ this._cancel(this._queue[i]);
+ }
+ this._queue = [];
+ },
+ /**
+ * Returns name of the file identified by id
+ */
+ getName: function(id){},
+ /**
+ * Returns size of the file identified by id
+ */
+ getSize: function(id){},
+ /**
+ * Returns id of files being uploaded or
+ * waiting for their turn
+ */
+ getQueue: function(){
+ return this._queue;
+ },
+ /**
+ * Actual upload method
+ */
+ _upload: function(id){},
+ /**
+ * Actual cancel method
+ */
+ _cancel: function(id){},
+ /**
+ * Removes element from queue, starts upload of next
+ */
+ _dequeue: function(id){
+ var i = qq.indexOf(this._queue, id);
+ this._queue.splice(i, 1);
+
+ var max = this._options.maxConnections;
+
+ if (this._queue.length >= max && i < max){
+ var nextId = this._queue[max-1];
+ this._upload(nextId, this._params[nextId]);
+ }
+ }
+};
+
+/**
+ * Class for uploading files using form and iframe
+ * @inherits qq.UploadHandlerAbstract
+ */
+qq.UploadHandlerForm = function(o){
+ qq.UploadHandlerAbstract.apply(this, arguments);
+
+ this._inputs = {};
+};
+// @inherits qq.UploadHandlerAbstract
+qq.extend(qq.UploadHandlerForm.prototype, qq.UploadHandlerAbstract.prototype);
+
+qq.extend(qq.UploadHandlerForm.prototype, {
+ add: function(fileInput){
+ fileInput.setAttribute('name', 'qqfile');
+ var id = 'qq-upload-handler-iframe' + qq.getUniqueId();
+
+ this._inputs[id] = fileInput;
+
+ // remove file input from DOM
+ if (fileInput.parentNode){
+ qq.remove(fileInput);
+ }
+
+ return id;
+ },
+ getName: function(id){
+ // get input value and remove path to normalize
+ return this._inputs[id].value.replace(/.*(\/|\\)/, "");
+ },
+ _cancel: function(id){
+ this._options.onCancel(id, this.getName(id));
+
+ delete this._inputs[id];
+
+ var iframe = document.getElementById(id);
+ if (iframe){
+ // to cancel request set src to something else
+ // we use src="javascript:false;" because it doesn't
+ // trigger ie6 prompt on https
+ iframe.setAttribute('src', 'javascript:false;');
+
+ qq.remove(iframe);
+ }
+ },
+ _upload: function(id, params){
+ var input = this._inputs[id];
+
+ if (!input){
+ throw new Error('file with passed id was not added, or already uploaded or cancelled');
+ }
+
+ var fileName = this.getName(id);
+
+ var iframe = this._createIframe(id);
+ var form = this._createForm(iframe, params);
+ form.appendChild(input);
+
+ var self = this;
+ this._attachLoadEvent(iframe, function(){
+ self.log('iframe loaded');
+
+ var response = self._getIframeContentJSON(iframe);
+
+ self._options.onComplete(id, fileName, response);
+ self._dequeue(id);
+
+ delete self._inputs[id];
+ // timeout added to fix busy state in FF3.6
+ setTimeout(function(){
+ qq.remove(iframe);
+ }, 1);
+ });
+
+ form.submit();
+ qq.remove(form);
+
+ return id;
+ },
+ _attachLoadEvent: function(iframe, callback){
+ qq.attach(iframe, 'load', function(){
+ // when we remove iframe from dom
+ // the request stops, but in IE load
+ // event fires
+ if (!iframe.parentNode){
+ return;
+ }
+
+ // fixing Opera 10.53
+ if (iframe.contentDocument &&
+ iframe.contentDocument.body &&
+ iframe.contentDocument.body.innerHTML == "false"){
+ // In Opera event is fired second time
+ // when body.innerHTML changed from false
+ // to server response approx. after 1 sec
+ // when we upload file with iframe
+ return;
+ }
+
+ callback();
+ });
+ },
+ /**
+ * Returns json object received by iframe from server.
+ */
+ _getIframeContentJSON: function(iframe){
+ // iframe.contentWindow.document - for IE<7
+ var doc = iframe.contentDocument ? iframe.contentDocument: iframe.contentWindow.document,
+ response;
+
+ this.log("converting iframe's innerHTML to JSON");
+ this.log("innerHTML = " + doc.body.innerHTML);
+
+ try {
+ response = eval("(" + doc.body.innerHTML + ")");
+ } catch(err){
+ response = {};
+ }
+
+ return response;
+ },
+ /**
+ * Creates iframe with unique name
+ */
+ _createIframe: function(id){
+ // We can't use following code as the name attribute
+ // won't be properly registered in IE6, and new window
+ // on form submit will open
+ // var iframe = document.createElement('iframe');
+ // iframe.setAttribute('name', id);
+
+ var iframe = qq.toElement('<iframe src="javascript:false;" name="' + id + '" />');
+ // src="javascript:false;" removes ie6 prompt on https
+
+ iframe.setAttribute('id', id);
+
+ iframe.style.display = 'none';
+ document.body.appendChild(iframe);
+
+ return iframe;
+ },
+ /**
+ * Creates form, that will be submitted to iframe
+ */
+ _createForm: function(iframe, params){
+ // We can't use the following code in IE6
+ // var form = document.createElement('form');
+ // form.setAttribute('method', 'post');
+ // form.setAttribute('enctype', 'multipart/form-data');
+ // Because in this case file won't be attached to request
+ var form = qq.toElement('<form method="post" enctype="multipart/form-data"></form>');
+
+ var queryString = qq.obj2url(params, this._options.action);
+
+ form.setAttribute('action', queryString);
+ form.setAttribute('target', iframe.name);
+ form.style.display = 'none';
+ document.body.appendChild(form);
+
+ return form;
+ }
+});
+
+/**
+ * Class for uploading files using xhr
+ * @inherits qq.UploadHandlerAbstract
+ */
+qq.UploadHandlerXhr = function(o){
+ qq.UploadHandlerAbstract.apply(this, arguments);
+
+ this._files = [];
+ this._xhrs = [];
+
+ // current loaded size in bytes for each file
+ this._loaded = [];
+};
+
+// static method
+qq.UploadHandlerXhr.isSupported = function(){
+ var input = document.createElement('input');
+ input.type = 'file';
+
+ return (
+ 'multiple' in input &&
+ typeof File != "undefined" &&
+ typeof (new XMLHttpRequest()).upload != "undefined" );
+};
+
+// @inherits qq.UploadHandlerAbstract
+qq.extend(qq.UploadHandlerXhr.prototype, qq.UploadHandlerAbstract.prototype);
+
+qq.extend(qq.UploadHandlerXhr.prototype, {
+ /**
+ * Adds file to the queue
+ * Returns id to use with upload, cancel
+ **/
+ add: function(file){
+ if (!(file instanceof File)){
+ throw new Error('Passed obj in not a File (in qq.UploadHandlerXhr)');
+ }
+
+ return this._files.push(file) - 1;
+ },
+ getName: function(id){
+ var file = this._files[id];
+ // fix missing name in Safari 4
+ return file.fileName != null ? file.fileName : file.name;
+ },
+ getSize: function(id){
+ var file = this._files[id];
+ return file.fileSize != null ? file.fileSize : file.size;
+ },
+ /**
+ * Returns uploaded bytes for file identified by id
+ */
+ getLoaded: function(id){
+ return this._loaded[id] || 0;
+ },
+ /**
+ * Sends the file identified by id and additional query params to the server
+ * @param {Object} params name-value string pairs
+ */
+ _upload: function(id, params){
+ var file = this._files[id],
+ name = this.getName(id),
+ size = this.getSize(id);
+
+ this._loaded[id] = 0;
+
+ var xhr = this._xhrs[id] = new XMLHttpRequest();
+ var self = this;
+
+ xhr.upload.onprogress = function(e){
+ if (e.lengthComputable){
+ self._loaded[id] = e.loaded;
+ self._options.onProgress(id, name, e.loaded, e.total);
+ }
+ };
+
+ xhr.onreadystatechange = function(){
+ if (xhr.readyState == 4){
+ self._onComplete(id, xhr);
+ }
+ };
+
+ // build query string
+ params = params || {};
+ params['qqfile'] = name;
+ var queryString = qq.obj2url(params, this._options.action);
+
+ xhr.open("POST", queryString, true);
+ xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
+ xhr.setRequestHeader("X-File-Name", encodeURIComponent(name));
+ xhr.setRequestHeader("Content-Type", "application/octet-stream");
+ xhr.send(file);
+ },
+ _onComplete: function(id, xhr){
+ // the request was aborted/cancelled
+ if (!this._files[id]) return;
+
+ var name = this.getName(id);
+ var size = this.getSize(id);
+
+ this._options.onProgress(id, name, size, size);
+
+ if (xhr.status == 200){
+ this.log("xhr - server response received");
+ this.log("responseText = " + xhr.responseText);
+
+ var response;
+
+ try {
+ response = eval("(" + xhr.responseText + ")");
+ } catch(err){
+ response = {};
+ }
+
+ this._options.onComplete(id, name, response);
+
+ } else {
+ this._options.onComplete(id, name, {});
+ }
+
+ this._files[id] = null;
+ this._xhrs[id] = null;
+ this._dequeue(id);
+ },
+ _cancel: function(id){
+ this._options.onCancel(id, this.getName(id));
+
+ this._files[id] = null;
+
+ if (this._xhrs[id]){
+ this._xhrs[id].abort();
+ this._xhrs[id] = null;
+ }
+ }
+}); \ No newline at end of file
diff --git a/lib/scripts/fileuploaderextended.js b/lib/scripts/fileuploaderextended.js
new file mode 100644
index 000000000..ed631a9ea
--- /dev/null
+++ b/lib/scripts/fileuploaderextended.js
@@ -0,0 +1,339 @@
+qq.extend(qq.FileUploader.prototype, {
+ _createUploadHandler: function(){
+ var self = this,
+ handlerClass;
+
+ if(qq.UploadHandlerXhr.isSupported()){
+ handlerClass = 'UploadHandlerXhr';
+ //handlerClass = 'UploadHandlerForm';
+ } else {
+ handlerClass = 'UploadHandlerForm';
+ }
+
+ var handler = new qq[handlerClass]({
+ debug: this._options.debug,
+ action: this._options.action,
+ maxConnections: this._options.maxConnections,
+ onProgress: function(id, fileName, loaded, total){
+ self._onProgress(id, fileName, loaded, total);
+ self._options.onProgress(id, fileName, loaded, total);
+ },
+ onComplete: function(id, fileName, result){
+ self._onComplete(id, fileName, result);
+ self._options.onComplete(id, fileName, result);
+ },
+ onCancel: function(id, fileName){
+ self._onCancel(id, fileName);
+ self._options.onCancel(id, fileName);
+ },
+ onUpload: function(){
+ self._onUpload();
+ }
+ });
+
+ return handler;
+ },
+
+ _onUpload: function(){
+ this._handler.uploadAll(this._options.params);
+ },
+
+ _uploadFile: function(fileContainer){
+ var id = this._handler.add(fileContainer);
+ var fileName = this._handler.getName(id);
+
+ if (this._options.onSubmit(id, fileName) !== false){
+ this._onSubmit(id, fileName);
+ }
+ },
+
+ _addToList: function(id, fileName){
+ var item = qq.toElement(this._options.fileTemplate);
+ item.qqFileId = id;
+
+ var fileElement = this._find(item, 'file');
+ qq.setText(fileElement, fileName);
+ this._find(item, 'size').style.display = 'none';
+
+ var nameElement = this._find(item, 'nameInput');
+ fileName = fileName.toLowerCase();
+ fileName = fileName.replace(/([^a-z0-9_\.\-]+)/g, '_');
+ nameElement.value = fileName;
+ nameElement.id = 'mediamanager__upload_item'+id;
+
+ this._listElement.appendChild(item);
+ }
+
+});
+
+qq.FileUploaderExtended = function(o){
+ // call parent constructor
+ qq.FileUploaderBasic.apply(this, arguments);
+
+ qq.extend(this._options, {
+ element: null,
+ // if set, will be used instead of qq-upload-list in template
+ listElement: null,
+
+ template: '<div class="qq-uploader">' +
+ '<div class="qq-upload-drop-area"><span>' + LANG.media_drop + '</span></div>' +
+ '<div class="qq-upload-button">' + LANG.media_select + '</div>' +
+ '<div class="qq-upload-list"></div>' +
+ '<div><input class="button" type="submit" value="' + LANG.media_upload_btn + '" id="mediamanager__upload_button">' +
+ '<label class="check"><input class="dw__ow" type="checkbox" value="1" name="ow"><span>' + LANG.media_overwrt + '</span></label>' +
+ '</div>' +
+ '</div>',
+
+ // template for one item in file list
+ fileTemplate: '<div class="li">' +
+ '<span class="qq-upload-file qq-upload-file-hidden"></span>' +
+ '<input class="qq-upload-name-input edit" type="text">' +
+ '<span class="qq-upload-spinner-hidden"></span>' +
+ '<span class="qq-upload-size"></span>' +
+ '<a class="qq-upload-cancel" href="#">' + LANG.media_cancel + '</a>' +
+ '<span class="qq-upload-failed-text">Failed</span>' +
+ '</div>',
+
+ classes: {
+ // used to get elements from templates
+ button: 'qq-upload-button',
+ drop: 'qq-upload-drop-area',
+ dropActive: 'qq-upload-drop-area-active',
+ list: 'qq-upload-list',
+ nameInput: 'qq-upload-name-input',
+ file: 'qq-upload-file',
+
+ spinner: 'qq-upload-spinner',
+ size: 'qq-upload-size',
+ cancel: 'qq-upload-cancel',
+
+ // added to list item when upload completes
+ // used in css to hide progress spinner
+ success: 'qq-upload-success',
+ fail: 'qq-upload-fail',
+ failedText : 'qq-upload-failed-text'
+ }
+ });
+
+ qq.extend(this._options, o);
+
+ this._element = this._options.element;
+ this._element.innerHTML = this._options.template;
+ this._listElement = this._options.listElement || this._find(this._element, 'list');
+
+ this._classes = this._options.classes;
+
+ this._button = this._createUploadButton(this._find(this._element, 'button'));
+
+ this._bindCancelEvent();
+ this._bindUploadEvent();
+ this._setupDragDrop();
+};
+
+qq.extend(qq.FileUploaderExtended.prototype, qq.FileUploader.prototype);
+
+qq.extend(qq.FileUploaderExtended.prototype, {
+ _bindUploadEvent: function(){
+ var self = this,
+ list = this._listElement;
+
+ qq.attach(document.getElementById('mediamanager__upload_button'), 'click', function(e){
+ e = e || window.event;
+ var target = e.target || e.srcElement;
+ qq.preventDefault(e);
+ self._handler._options.onUpload();
+
+ jQuery(".qq-upload-name-input").each(function (i) {
+ jQuery(this).attr('disabled', 'disabled');
+ });
+ });
+ },
+
+ _onComplete: function(id, fileName, result){
+ this._filesInProgress--;
+
+ // mark completed
+ var item = this._getItemByFileId(id);
+ qq.remove(this._find(item, 'cancel'));
+ qq.remove(this._find(item, 'spinner'));
+
+ var nameInput = this._find(item, 'nameInput');
+ var fileElement = this._find(item, 'file');
+ qq.setText(fileElement, nameInput.value);
+ qq.removeClass(fileElement, 'qq-upload-file-hidden');
+ qq.remove(nameInput);
+ jQuery('.qq-upload-button, #mediamanager__upload_button').remove();
+ jQuery('.dw__ow').parent().hide();
+ jQuery('.qq-upload-drop-area').remove();
+
+ if (result.success){
+ qq.addClass(item, this._classes.success);
+ $link = '<a href="' + result.link + '" name="h_:' + result.id + '" class="select">' + nameInput.value + '</a>';
+ jQuery(fileElement).html($link);
+
+ } else {
+ qq.addClass(item, this._classes.fail);
+ var fail = this._find(item, 'failedText');
+ if (result.error) qq.setText(fail, result.error);
+ }
+
+ if (document.getElementById('media__content') && !document.getElementById('mediamanager__done_form')) {
+ var action = document.location.href;
+ var i = action.indexOf('?');
+ if (i) action = action.substr(0, i);
+ var button = '<form method="post" action="' + action + '" id="mediamanager__done_form"><div>';
+ button += '<input type="hidden" value="' + result.ns + '" name="ns">';
+ button += '<input class="button" type="submit" value="' + LANG.media_done_btn + '"></div></form>';
+ jQuery('#mediamanager__uploader').append(button);
+ }
+ }
+
+});
+
+qq.extend(qq.UploadHandlerForm.prototype, {
+ uploadAll: function(params){
+ this._uploadAll(params);
+ },
+
+ getName: function(id){
+ var file = this._inputs[id];
+ var name = document.getElementById('mediamanager__upload_item'+id);
+ if (name != null) {
+ return name.value;
+ } else {
+ if (file != null) {
+ // get input value and remove path to normalize
+ return file.value.replace(/.*(\/|\\)/, "");
+ } else {
+ return null;
+ }
+ }
+ },
+
+ _uploadAll: function(params){
+ jQuery(".qq-upload-spinner-hidden").each(function (i) {
+ jQuery(this).addClass('qq-upload-spinner');
+ });
+ for (key in this._inputs) {
+ this.upload(key, params);
+ }
+
+ },
+
+ _upload: function(id, params){
+ var input = this._inputs[id];
+
+ if (!input){
+ throw new Error('file with passed id was not added, or already uploaded or cancelled');
+ }
+
+ var fileName = this.getName(id);
+
+ var iframe = this._createIframe(id);
+ var form = this._createForm(iframe, params);
+ form.appendChild(input);
+
+ var nameInput = qq.toElement('<input name="mediaid" value="' + fileName + '" type="text">');
+ form.appendChild(nameInput);
+
+ var checked = jQuery('.dw__ow').attr('checked');
+ var owCheckbox = jQuery('.dw__ow').clone();
+ owCheckbox.attr('checked', checked);
+ jQuery(form).append(owCheckbox);
+
+ var self = this;
+ this._attachLoadEvent(iframe, function(){
+ self.log('iframe loaded');
+
+ var response = self._getIframeContentJSON(iframe);
+
+ self._options.onComplete(id, fileName, response);
+ self._dequeue(id);
+
+ delete self._inputs[id];
+ // timeout added to fix busy state in FF3.6
+ setTimeout(function(){
+ qq.remove(iframe);
+ }, 1);
+ });
+
+ form.submit();
+ qq.remove(form);
+
+ return id;
+ }
+});
+
+qq.extend(qq.UploadHandlerXhr.prototype, {
+ uploadAll: function(params){
+ this._uploadAll(params);
+ },
+
+ getName: function(id){
+ var file = this._files[id];
+ var name = document.getElementById('mediamanager__upload_item'+id);
+ if (name != null) {
+ return name.value;
+ } else {
+ if (file != null) {
+ // fix missing name in Safari 4
+ return file.fileName != null ? file.fileName : file.name;
+ } else {
+ return null;
+ }
+ }
+ },
+
+ getSize: function(id){
+ var file = this._files[id];
+ if (file == null) return null;
+ return file.fileSize != null ? file.fileSize : file.size;
+ },
+
+ _upload: function(id, params){
+ var file = this._files[id],
+ name = this.getName(id),
+ size = this.getSize(id);
+ if (name == null || size == null) return;
+
+ this._loaded[id] = 0;
+
+ var xhr = this._xhrs[id] = new XMLHttpRequest();
+ var self = this;
+
+ xhr.upload.onprogress = function(e){
+ if (e.lengthComputable){
+ self._loaded[id] = e.loaded;
+ self._options.onProgress(id, name, e.loaded, e.total);
+ }
+ };
+
+ xhr.onreadystatechange = function(){
+ if (xhr.readyState == 4){
+ self._onComplete(id, xhr);
+ }
+ };
+
+ // build query string
+ params = params || {};
+ params['qqfile'] = name;
+ params['ow'] = jQuery('.dw__ow').attr('checked');
+ var queryString = qq.obj2url(params, this._options.action);
+
+ xhr.open("POST", queryString, true);
+ xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
+ xhr.setRequestHeader("X-File-Name", encodeURIComponent(name));
+ xhr.setRequestHeader("Content-Type", "application/octet-stream");
+ xhr.send(file);
+ },
+
+ _uploadAll: function(params){
+ jQuery(".qq-upload-spinner-hidden").each(function (i) {
+ jQuery(this).addClass('qq-upload-spinner');
+ });
+ for (key in this._files) {
+ this.upload(key, params);
+ }
+
+ }
+});
diff --git a/lib/scripts/helpers.js b/lib/scripts/helpers.js
index b0f76cdb0..d6f36967d 100644
--- a/lib/scripts/helpers.js
+++ b/lib/scripts/helpers.js
@@ -2,156 +2,6 @@
* Various helper functions
*/
-
-/**
- * Simple function to check if a global var is defined
- *
- * @author Kae Verens
- * @link http://verens.com/archives/2005/07/25/isset-for-javascript/#comment-2835
- */
-function isset(varname){
- return(typeof(window[varname])!='undefined');
-}
-
-/**
- * Checks if property is undefined
- *
- * @param {Object} prop value to check
- * @return {Boolean} true if matched
- * @scope public
- * @author Ilya Lebedev <ilya@lebedev.net>
- */
-function isUndefined (prop /* :Object */) /* :Boolean */ {
- return (typeof prop == 'undefined');
-}
-
-/**
- * Checks if property is function
- *
- * @param {Object} prop value to check
- * @return {Boolean} true if matched
- * @scope public
- * @author Ilya Lebedev <ilya@lebedev.net>
- */
-function isFunction (prop /* :Object */) /* :Boolean */ {
- return (typeof prop == 'function');
-}
-/**
- * Checks if property is string
- *
- * @param {Object} prop value to check
- * @return {Boolean} true if matched
- * @scope public
- * @author Ilya Lebedev <ilya@lebedev.net>
- */
-function isString (prop /* :Object */) /* :Boolean */ {
- return (typeof prop == 'string');
-}
-
-/**
- * Checks if property is number
- *
- * @param {Object} prop value to check
- * @return {Boolean} true if matched
- * @scope public
- * @author Ilya Lebedev <ilya@lebedev.net>
- */
-function isNumber (prop /* :Object */) /* :Boolean */ {
- return (typeof prop == 'number');
-}
-
-/**
- * Checks if property is the calculable number
- *
- * @param {Object} prop value to check
- * @return {Boolean} true if matched
- * @scope public
- * @author Ilya Lebedev <ilya@lebedev.net>
- */
-function isNumeric (prop /* :Object */) /* :Boolean */ {
- return isNumber(prop)&&!isNaN(prop)&&isFinite(prop);
-}
-
-/**
- * Checks if property is array
- *
- * @param {Object} prop value to check
- * @return {Boolean} true if matched
- * @scope public
- * @author Ilya Lebedev <ilya@lebedev.net>
- */
-function isArray (prop /* :Object */) /* :Boolean */ {
- return (prop instanceof Array);
-}
-
-/**
- * Checks if property is regexp
- *
- * @param {Object} prop value to check
- * @return {Boolean} true if matched
- * @scope public
- * @author Ilya Lebedev <ilya@lebedev.net>
- */
-function isRegExp (prop /* :Object */) /* :Boolean */ {
- return (prop instanceof RegExp);
-}
-
-/**
- * Checks if property is a boolean value
- *
- * @param {Object} prop value to check
- * @return {Boolean} true if matched
- * @scope public
- * @author Ilya Lebedev <ilya@lebedev.net>
- */
-function isBoolean (prop /* :Object */) /* :Boolean */ {
- return ('boolean' == typeof prop);
-}
-
-/**
- * Checks if property is a scalar value (value that could be used as the hash key)
- *
- * @param {Object} prop value to check
- * @return {Boolean} true if matched
- * @scope public
- * @author Ilya Lebedev <ilya@lebedev.net>
- */
-function isScalar (prop /* :Object */) /* :Boolean */ {
- return isNumeric(prop)||isString(prop);
-}
-
-/**
- * Checks if property is empty
- *
- * @param {Object} prop value to check
- * @return {Boolean} true if matched
- * @scope public
- * @author Ilya Lebedev <ilya@lebedev.net>
- */
-function isEmpty (prop /* :Object */) /* :Boolean */ {
- if (isBoolean(prop)) return false;
- if (isRegExp(prop) && new RegExp("").toString() == prop.toString()) return true;
- if (isString(prop) || isNumber(prop)) return !prop;
- if (Boolean(prop)&&false != prop) {
- for (var i in prop) if(prop.hasOwnProperty(i)) return false;
- }
- return true;
-}
-
-/**
- * Checks if property is derived from prototype, applies method if it is not exists
- *
- * @param string property name
- * @return bool true if prototyped
- * @access public
- * @author Ilya Lebedev <ilya@lebedev.net>
- */
-if ('undefined' == typeof Object.hasOwnProperty) {
- Object.prototype.hasOwnProperty = function (prop) {
- return !('undefined' == typeof this[prop] || this.constructor && this.constructor.prototype[prop] && this[prop] === this.constructor.prototype[prop]);
- };
-}
-
/**
* Very simplistic Flash plugin check, probably works for Flash 8 and higher only
*
@@ -163,13 +13,12 @@ function hasFlash(version){
if(navigator.plugins != null && navigator.plugins.length > 0){
ver = navigator.plugins["Shockwave Flash"].description.split(' ')[2].split('.')[0];
}else{
- var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
- ver = axo.GetVariable("$version").split(' ')[1].split(',')[0];
+ ver = (new ActiveXObject("ShockwaveFlash.ShockwaveFlash"))
+ .GetVariable("$version").split(' ')[1].split(',')[0];
}
}catch(e){ }
- if(ver >= version) return true;
- return false;
+ return ver >= version;
}
/**
@@ -204,11 +53,11 @@ function substr_replace(str, replace, start, length) {
* @returns functionref
*/
function bind(fnc/*, ... */) {
- var Aps = Array.prototype.slice;
+ var Aps = Array.prototype.slice,
// Store passed arguments in this scope.
// Since arguments is no Array nor has an own slice method,
// we have to apply the slice method from the Array.prototype
- var static_args = Aps.call(arguments, 1);
+ static_args = Aps.call(arguments, 1);
// Return a function evaluating the passed function with the
// given args and optional arguments passed on invocation.
@@ -219,18 +68,3 @@ function bind(fnc/*, ... */) {
static_args.concat(Aps.call(arguments, 0)));
};
}
-
-/**
- * Get the computed style of a node.
- *
- * @link https://acidmartin.wordpress.com/2008/08/26/style-get-any-css-property-value-of-an-object/
- * @link http://svn.dojotoolkit.org/src/dojo/trunk/_base/html.js
- */
-function gcs(node){
- if(node.currentStyle){
- return node.currentStyle;
- }else{
- return node.ownerDocument.defaultView.getComputedStyle(node, null);
- }
-}
-
diff --git a/lib/scripts/jquery/jquery.cookie.js b/lib/scripts/jquery/jquery.cookie.js
index 6df1faca2..6a3e394b4 100644
--- a/lib/scripts/jquery/jquery.cookie.js
+++ b/lib/scripts/jquery/jquery.cookie.js
@@ -1,96 +1,41 @@
/**
- * Cookie plugin
+ * jQuery Cookie plugin
*
- * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
+ * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
+jQuery.cookie = function (key, value, options) {
-/**
- * Create a cookie with the given name and value and other optional parameters.
- *
- * @example $.cookie('the_cookie', 'the_value');
- * @desc Set the value of a cookie.
- * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
- * @desc Create a cookie with all available options.
- * @example $.cookie('the_cookie', 'the_value');
- * @desc Create a session cookie.
- * @example $.cookie('the_cookie', null);
- * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
- * used when the cookie was set.
- *
- * @param String name The name of the cookie.
- * @param String value The value of the cookie.
- * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
- * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
- * If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
- * If set to null or omitted, the cookie will be a session cookie and will not be retained
- * when the the browser exits.
- * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
- * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
- * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
- * require a secure protocol (like HTTPS).
- * @type undefined
- *
- * @name $.cookie
- * @cat Plugins/Cookie
- * @author Klaus Hartl/klaus.hartl@stilbuero.de
- */
+ // key and at least value given, set cookie...
+ if (arguments.length > 1 && String(value) !== "[object Object]") {
+ options = jQuery.extend({}, options);
-/**
- * Get the value of a cookie with the given name.
- *
- * @example $.cookie('the_cookie');
- * @desc Get the value of a cookie.
- *
- * @param String name The name of the cookie.
- * @return The value of the cookie.
- * @type String
- *
- * @name $.cookie
- * @cat Plugins/Cookie
- * @author Klaus Hartl/klaus.hartl@stilbuero.de
- */
-jQuery.cookie = function(name, value, options) {
- if (typeof value != 'undefined') { // name and value given, set cookie
- options = options || {};
- if (value === null) {
- value = '';
+ if (value === null || value === undefined) {
options.expires = -1;
}
- var expires = '';
- if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
- var date;
- if (typeof options.expires == 'number') {
- date = new Date();
- date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
- } else {
- date = options.expires;
- }
- expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
- }
- // CAUTION: Needed to parenthesize options.path and options.domain
- // in the following expressions, otherwise they evaluate to undefined
- // in the packed version for some reason...
- var path = options.path ? '; path=' + (options.path) : '';
- var domain = options.domain ? '; domain=' + (options.domain) : '';
- var secure = options.secure ? '; secure' : '';
- document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
- } else { // only name given, get cookie
- var cookieValue = null;
- if (document.cookie && document.cookie != '') {
- var cookies = document.cookie.split(';');
- for (var i = 0; i < cookies.length; i++) {
- var cookie = jQuery.trim(cookies[i]);
- // Does this cookie string begin with the name we want?
- if (cookie.substring(0, name.length + 1) == (name + '=')) {
- cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
- break;
- }
- }
+
+ if (typeof options.expires === 'number') {
+ var days = options.expires, t = options.expires = new Date();
+ t.setDate(t.getDate() + days);
}
- return cookieValue;
+
+ value = String(value);
+
+ return (document.cookie = [
+ encodeURIComponent(key), '=',
+ options.raw ? value : encodeURIComponent(value),
+ options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
+ options.path ? '; path=' + options.path : '',
+ options.domain ? '; domain=' + options.domain : '',
+ options.secure ? '; secure' : ''
+ ].join(''));
}
-}; \ No newline at end of file
+
+ // key and possibly options given, get cookie...
+ options = value || {};
+ var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
+ return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
+};
diff --git a/lib/scripts/locktimer.js b/lib/scripts/locktimer.js
index b83840557..857002abf 100644
--- a/lib/scripts/locktimer.js
+++ b/lib/scripts/locktimer.js
@@ -17,8 +17,9 @@ var dw_locktimer = {
*/
init: function(timeout,draft){ //FIXME which elements to pass here?
var $edit = jQuery('#wiki__text');
- if(!$edit.length) return;
- if($edit.attr('readonly')) return;
+ if($edit.length === 0 || $edit.attr('readonly')) {
+ return;
+ }
// init values
dw_locktimer.timeout = timeout*1000;
@@ -26,10 +27,12 @@ var dw_locktimer = {
dw_locktimer.lasttime = new Date();
dw_locktimer.pageid = jQuery('#dw__editform input[name=id]').val();
- if(!dw_locktimer.pageid) return;
+ if(!dw_locktimer.pageid) {
+ return;
+ }
// register refresh event
- jQuery('#wiki__text').keypress(dw_locktimer.refresh);
+ $edit.keypress(dw_locktimer.refresh);
// start timer
dw_locktimer.reset();
},
@@ -66,30 +69,29 @@ var dw_locktimer = {
* Called on keypresses in the edit area
*/
refresh: function(){
- var now = new Date();
- var params = {};
- // refresh every minute only
- if(now.getTime() - dw_locktimer.lasttime.getTime() > 30*1000){
- params['call'] = 'lock';
- params['id'] = dw_locktimer.pageid;
+ var now = new Date(),
+ params = 'call=lock&id=' + dw_locktimer.pageid + '&';
- if(dw_locktimer.draft && jQuery('#dw__editform textarea[name=wikitext]').length > 0){
- params['prefix'] = jQuery('#dw__editform input[name=prefix]').val();
- params['wikitext'] = jQuery('#dw__editform textarea[name=wikitext]').val();
- params['suffix'] = jQuery('#dw__editform input[name=suffix]').val();
- if(jQuery('#dw__editform input[name=date]').length > 0) {
- params['date'] = jQuery('#dw__editform input[name=id]').val();
- }
- }
+ // refresh every minute only
+ if(now.getTime() - dw_locktimer.lasttime.getTime() <= 30*1000) {
+ return;
+ }
- jQuery.post(
- DOKU_BASE + 'lib/exe/ajax.php',
- params,
- dw_locktimer.refreshed,
- 'html'
- );
- dw_locktimer.lasttime = now;
+ // POST everything necessary for draft saving
+ if(dw_locktimer.draft && jQuery('#dw__editform textarea[name=wikitext]').length > 0){
+ params += jQuery('#dw__editform').find('input[name=prefix], ' +
+ 'textarea[name=wikitext], ' +
+ 'input[name=suffix], ' +
+ 'input[name=date]').serialize();
}
+
+ jQuery.post(
+ DOKU_BASE + 'lib/exe/ajax.php',
+ params,
+ dw_locktimer.refreshed,
+ 'html'
+ );
+ dw_locktimer.lasttime = now;
},
/**
@@ -100,7 +102,9 @@ var dw_locktimer = {
data = data.substring(1);
jQuery('#draft__status').html(data);
- if(error != '1') return; // locking failed
+ if(error != '1') {
+ return; // locking failed
+ }
dw_locktimer.reset();
}
};
diff --git a/lib/scripts/media.js b/lib/scripts/media.js
index 1402ad4bf..f4064efd5 100644
--- a/lib/scripts/media.js
+++ b/lib/scripts/media.js
@@ -22,6 +22,12 @@ var dw_mediamanager = {
size: false,
forbidden_opts: {},
+ // File list view type
+ view: false,
+
+ layout_width: 0,
+ layout_height: 0,
+
init: function () {
var $content, $tree;
$content = jQuery('#media__content');
@@ -38,7 +44,8 @@ var dw_mediamanager = {
.delegate('a.select', 'click', dw_mediamanager.select)
// Attach deletion confirmation dialog to the delete buttons
.delegate('#media__content a.btn_media_delete', 'click',
- dw_mediamanager.confirmattach);
+ dw_mediamanager.confirmattach)
+ .delegate('#mediamanager__done_form', 'submit', dw_mediamanager.list);
$tree.dw_tree({toggle_selector: 'img',
load_data: function (show_sublist, $clicky) {
@@ -59,6 +66,43 @@ var dw_mediamanager = {
(opening ? 'minus' : 'plus') + '.gif');
}});
$tree.delegate('a', 'click', dw_mediamanager.list);
+
+ dw_mediamanager.set_filelist_view(dw_mediamanager.view, false);
+ jQuery('#mediamanager__form_sort').find('input[type=submit]').hide();
+ dw_mediamanager.image_diff();
+ dw_mediamanager.init_ajax_uploader();
+
+ // changing opened tab in the file list panel
+ jQuery('#mediamanager__layout_list').delegate('#mediamanager__tabs_files a', 'click', dw_mediamanager.list)
+ // changing type of the file list view
+ .delegate('#mediamanager__tabs_list a', 'click', dw_mediamanager.list_view)
+ // loading file details
+ .delegate('#mediamanager__file_list a', 'click', dw_mediamanager.details)
+ // search form
+ .delegate('#dw__mediasearch', 'submit', dw_mediamanager.list)
+ // "upload as" field autofill
+ .delegate('#upload__file', 'change', dw_mediamanager.suggest)
+ // sort type selection
+ .delegate('#mediamanager__form_sort select', 'change', dw_mediamanager.list)
+ // uploaded images
+ .delegate('.qq-upload-file a', 'click', dw_mediamanager.details);
+
+ // changing opened tab in the file details panel
+ jQuery('#mediamanager__layout_detail').delegate('#mediamanager__tabs_details a', 'click', dw_mediamanager.details)
+ // "update new version" button
+ .delegate('#mediamanager__btn_update', 'submit', dw_mediamanager.list)
+ // revisions form
+ .delegate('#page__revisions', 'submit', dw_mediamanager.details)
+ .delegate('#page__revisions a', 'click', dw_mediamanager.details)
+ // meta edit form
+ .delegate('#mediamanager__save_meta', 'submit', dw_mediamanager.details)
+ // delete button
+ .delegate('#mediamanager__btn_delete', 'submit', dw_mediamanager.details)
+ // "restore this version" button
+ .delegate('#mediamanager__btn_restore', 'submit', dw_mediamanager.details)
+ // less/more recent buttons in media revisions form
+ .delegate('.btn_newer, .btn_older', 'submit', dw_mediamanager.details);
+
},
/**
@@ -201,6 +245,9 @@ var dw_mediamanager = {
$file = jQuery(this);
$name = jQuery('#upload__name');
+
+ if ($name.val() != '') return;
+
if(!$file.length || !$name.length) {
return;
}
@@ -218,33 +265,431 @@ var dw_mediamanager = {
* @author Pierre Spring <pierre.spring@caillou.ch>
*/
list: function (event) {
- var $link, $content;
+ var $link, $content, params;
+ $link = jQuery(this);
event.preventDefault();
jQuery('div.success, div.info, div.error, div.notify').remove();
- $link = jQuery(this);
- $content = jQuery('#media__content');
- $content.html('<img src="' + DOKU_BASE + 'lib/images/loading.gif" alt="..." class="load" />');
+ if (document.getElementById('media__content')) {
+ //popup
+ $content = jQuery('#media__content');
+ } else {
+ //fullscreen media manager
+ $content = jQuery('#mediamanager__layout_list');
+
+ if ($link.hasClass('idx_dir')) {
+ //changing namespace
+ jQuery('#mediamanager__layout_detail').empty();
+ jQuery('#media__tree .selected').each(function(){
+ jQuery(this).removeClass('selected');
+ });
+ $link.addClass('selected');
+ }
+ }
+
+ params = '';
+
+ if ($link[0].search) {
+ params = $link[0].search.substr(1)+'&call=medialist';
+ } else if ($link[0].action) {
+ params = dw_mediamanager.form_params($link)+'&call=medialist';
+ } else if ($link.parents('form')) {
+ params = dw_mediamanager.form_params($link.parents('form'))+'&call=medialist';
+
+ if ($link.parents('form')[0].id == 'mediamanager__form_sort') {
+ DokuCookie.setValue('sort', $link[0].value);
+ params += '&q=' + jQuery('#mediamanager__sort_textfield').val();
+ params += '&mediado=searchlist';
+ }
+ }
// fetch the subtree
+ dw_mediamanager.update_content($content, params);
+
+ if (document.getElementById('media__content')) {
+ //popup
+ $content = jQuery('#media__content');
+ $content.html('<img src="' + DOKU_BASE + 'lib/images/loading.gif" alt="..." class="load" />');
+ } else {
+ //fullscreen media manager
+ jQuery('.scroll-container', $content).html('<img src="' + DOKU_BASE + 'lib/images/loading.gif" alt="..." class="load" />');
+ }
+ },
+
+ /**
+ * Returns form parameters
+ *
+ * @author Kate Arzamastseva <pshns@ukr.net>
+ */
+ form_params: function ($form) {
+ if (!$form.length) return;
+ var elements = $form.serialize();
+ var action = '';
+ var i = $form[0].action.indexOf('?');
+ if (i >= 0) action = $form[0].action.substr(i+1);
+ return elements+'&'+action;
+ },
+
+ /**
+ * Changes view of media files list
+ *
+ * @author Kate Arzamastseva <pshns@ukr.net>
+ */
+ list_view: function (event) {
+ var $link, $content;
+ $link = jQuery(this);
+
+ event.preventDefault();
+
+ $content = jQuery('#mediamanager__file_list');
+
+ if ($link[0].id == 'mediamanager__link_thumbs') {
+ dw_mediamanager.set_filelist_view('thumbs', true);
+
+ } else if ($link[0].id == 'mediamanager__link_list') {
+ dw_mediamanager.set_filelist_view('list', true);
+ }
+ },
+
+ set_filelist_view: function (type, cookies) {
+ var $content = jQuery('#mediamanager__file_list');
+ if (!type) type = DokuCookie.getValue('view');
+
+ if (type == 'thumbs') {
+ $content.removeClass('mediamanager-list');
+ $content.addClass('mediamanager-thumbs');
+ if (cookies) DokuCookie.setValue('view', 'thumbs');
+ dw_mediamanager.view = 'thumbs';
+
+ } else if (type == 'list') {
+ $content.removeClass('mediamanager-thumbs');
+ $content.addClass('mediamanager-list');
+ if (cookies) DokuCookie.setValue('view', 'list');
+ dw_mediamanager.view = 'list';
+ }
+ },
+
+ /**
+ * Lists the content of the right column (image details) using AJAX
+ *
+ * @author Kate Arzamastseva <pshns@ukr.net>
+ */
+ details: function (event) {
+ var $link, $content, params, update_list;
+ $link = jQuery(this);
+
+ event.preventDefault();
+
+ jQuery('div.success, div.info, div.error, div.notify').remove();
+
+ if ($link[0].id == 'mediamanager__btn_delete' && !confirm(LANG['del_confirm'])) return false;
+ if ($link[0].id == 'mediamanager__btn_restore' && !confirm(LANG['restore_confirm'])) return false;
+
+ $content = jQuery('#mediamanager__layout_detail');
+ params = '';
+
+ if ($link[0].search) {
+ params = $link[0].search.substr(1)+'&call=mediadetails';
+ } else if ($link[0].action) {
+ params = dw_mediamanager.form_params($link)+'&call=mediadetails';
+ } else if ($link.parents('form')) {
+ params = dw_mediamanager.form_params($link.parents('form'))+'&call=mediadetails';
+ }
+
+ update_list = ($link[0].id == 'mediamanager__btn_delete' || $link[0].id == 'mediamanager__btn_restore');
+ dw_mediamanager.update_content($content, params, update_list);
+
+ if (jQuery('.scroll-container', $content).length) {
+ jQuery('.scroll-container', $content).html('<img src="' + DOKU_BASE + 'lib/images/loading.gif" alt="..." class="load" />');
+ } else {
+ jQuery($content).html('<img src="' + DOKU_BASE + 'lib/images/loading.gif" alt="..." class="load" />');
+ }
+ },
+
+ update_content: function ($content, params, update_list) {
jQuery.post(
DOKU_BASE + 'lib/exe/ajax.php',
- $link[0].search.substr(1)+'&call=medialist',
+ params,
function (data) {
+ jQuery('.ui-resizable').each(function(){
+ jQuery(this).resizable('destroy');
+ });
+
$content.html(data);
+
dw_mediamanager.prepare_content($content);
dw_mediamanager.updatehide();
+
+ dw_mediamanager.update_resizable();
+ dw_behaviour.revisionBoxHandler();
+ jQuery('#mediamanager__form_sort').find('input[type=submit]').hide();
+ dw_mediamanager.set_filelist_view(dw_mediamanager.view, false);
+ dw_mediamanager.image_diff();
+ dw_mediamanager.init_ajax_uploader();
+
+ if (update_list) {
+ var $link1, $content1, params1;
+ $link1 = jQuery('a.files');
+ params1 = $link1[0].search.substr(1)+'&call=medialist';
+ $content1 = jQuery('#mediamanager__layout_list');
+ dw_mediamanager.update_content($content1, params1);
+ jQuery('.scroll-container', $content1).html('<img src="' + DOKU_BASE + 'lib/images/loading.gif" alt="..." class="load" />');
+ }
},
'html'
);
},
+ window_resize: function () {
+ if (jQuery('#mediamanager__layout').width() == dw_mediamanager.layout_width) {
+ return;
+ }
+
+ dw_mediamanager.layout_width = jQuery('#mediamanager__layout').width();
+ $r = jQuery("#mediamanager__layout .layout-resizable, #mediamanager__layout .layout");
+
+ var w = 0, wSum = 0, mCount = 0, mArray = [];
+ $r.each(function() {
+ w = jQuery(this).width();
+ if (w == parseFloat(jQuery(this).css("min-width"))) {
+ wSum += w;
+ } else {
+ mArray[mCount] = jQuery(this);
+ mCount++;
+ }
+ });
+
+ if (mCount > 0) {
+ var width = (0.95 * jQuery('#mediamanager__layout').width() - wSum - 30);
+ wSum = 0;
+ for(var i = 0; i < mArray.length; i++) {
+ wSum += mArray[i].width();
+ }
+ for(var i = 0; i < mArray.length; i++) {
+ w = mArray[i].width();
+ w = 100*w / wSum;
+ mArray[i].width(width*w/100);
+ }
+ }
+
+ $r.each(function() {
+ w = jQuery(this).width();
+ w = (100 * w / jQuery('#mediamanager__layout').width());
+ w += "%";
+ jQuery(this).width(w);
+ });
+
+ var windowHeight = jQuery(window).height();
+ var height = windowHeight - 300;
+ if (layout_height < height) {
+ layout_height = height;
+ jQuery('#mediamanager__layout .scroll-container').each(function (i) {
+ jQuery(this).height(height);
+ });
+ $resizable.each(function() {
+ jQuery(this).height(height+100);
+ });
+ }
+
+ dw_mediamanager.opacity_slider();
+ dw_mediamanager.portions_slider();
+ },
+
+ /**
+ * Updates mediamanager layout
+ *
+ * @author Kate Arzamastseva <pshns@ukr.net>
+ */
+ update_resizable: function () {
+ $resizable = jQuery("#mediamanager__layout .layout-resizable");
+
+ $resizable.resizable({ handles: 'e' ,
+ resize: function(event, ui){
+ var w = 0;
+ $resizable.each(function() {
+ w += jQuery(this).width();
+ });
+ wSum = w + parseFloat(jQuery('#mediamanager__layout_detail').css("min-width"));
+
+ // max width of resizable column
+ var maxWidth = 0.95 * jQuery('#mediamanager__layout').width() - wSum + jQuery(this).width() - 30;
+ $resizable.resizable( "option", "maxWidth", maxWidth );
+
+ // percentage width of the first two columns
+ var wLeft = ( 100*(w+30) / jQuery('#mediamanager__layout').width() );
+
+ // width of the third column
+ var wRight = 95-wLeft;
+ wRight += "%";
+ jQuery('#mediamanager__layout_detail').width(wRight);
+
+ $resizable.each(function() {
+ w = jQuery(this).width();
+ w = (100 * w / jQuery('#mediamanager__layout').width());
+ w += "%";
+ jQuery(this).width(w);
+ });
+
+ dw_mediamanager.opacity_slider();
+ dw_mediamanager.portions_slider();
+ }
+ });
+
+ var windowHeight = jQuery(window).height();
+ var height = windowHeight - 300;
+ layout_height = height;
+ jQuery('#mediamanager__layout .scroll-container').each(function (i) {
+ jQuery(this).height(height);
+ });
+ $resizable.each(function() {
+ jQuery(this).height(height+100);
+ });
+ },
+
+ /**
+ * Prints 'select' for image difference representation type
+ *
+ * @author Kate Arzamastseva <pshns@ukr.net>
+ */
+ image_diff: function () {
+ if (jQuery('#mediamanager__difftype').length) return;
+
+ $form = jQuery('#mediamanager__form_diffview');
+ if (!$form.length) return;
+
+ $label = jQuery(document.createElement('label'));
+ $label.append('<span>'+LANG.media_diff+'</span>');
+ $select = jQuery(document.createElement('select'))
+ .attr('id', 'mediamanager__difftype')
+ .attr('name', 'difftype')
+ .change(dw_mediamanager.change_diff_type);
+ $select.append(new Option(LANG.media_diff_both, "both"));
+ $select.append(new Option(LANG.media_diff_opacity, "opacity"));
+ $select.append(new Option(LANG.media_diff_portions, "portions"));
+ $label.append($select);
+ $form.append($label);
+
+ // for IE
+ var select = document.getElementById('mediamanager__difftype');
+ select.options[0].text = LANG.media_diff_both;
+ select.options[1].text = LANG.media_diff_opacity;
+ select.options[2].text = LANG.media_diff_portions;
+ },
+
+ /**
+ * Handles selection of image difference representation type
+ *
+ * @author Kate Arzamastseva <pshns@ukr.net>
+ */
+ change_diff_type: function () {
+ $select = jQuery('#mediamanager__difftype');
+ $content = jQuery('#mediamanager__diff');
+
+ params = dw_mediamanager.form_params($select.parents('form'))+'&call=mediadiff';
+ jQuery.post(
+ DOKU_BASE + 'lib/exe/ajax.php',
+ params,
+ function (data) {
+ $content.html(data);
+ dw_mediamanager.portions_slider();
+ dw_mediamanager.opacity_slider();
+ },
+ 'html'
+ );
+ },
+
+ /**
+ * Sets options for opacity diff slider
+ *
+ * @author Kate Arzamastseva <pshns@ukr.net>
+ */
+ opacity_slider: function () {
+ var $slider = jQuery( "#mediamanager__opacity_slider" );
+ if (!$slider.length) return;
+
+ var $image = jQuery('#mediamanager__diff_opacity_image1 img');
+ if (!$image.length) return;
+ $slider.width($image.width()-20);
+
+ $slider.slider();
+ $slider.slider("option", "min", 0);
+ $slider.slider("option", "max", 0.999);
+ $slider.slider("option", "step", 0.001);
+ $slider.slider("option", "value", 0.5);
+ $slider.bind("slide", function(event, ui) {
+ jQuery('#mediamanager__diff_opacity_image2').css({ opacity: $slider.slider("option", "value")});
+ });
+ },
+
+ /**
+ * Sets options for red line diff slider
+ *
+ * @author Kate Arzamastseva <pshns@ukr.net>
+ */
+ portions_slider: function () {
+ var $image1 = jQuery('#mediamanager__diff_portions_image1 img');
+ var $image2 = jQuery('#mediamanager__diff_portions_image2 img');
+ if (!$image1.length || !$image2.length) return;
+
+ var $div = jQuery("#mediamanager__diff_layout");
+ if (!$div.length) return;
+
+ $div.width('100%');
+ $image2.parent().width('97%');
+ $image1.width('100%');
+ $image2.width('100%');
+
+ if ($image1.width() < $div.width()) {
+ $div.width($image1.width());
+ }
+
+ $image2.parent().width('50%');
+ $image2.width($image1.width());
+ $image1.width($image1.width());
+
+ var $slider = jQuery("#mediamanager__portions_slider");
+ if (!$slider.length) return;
+ $slider.width($image1.width()-20);
+
+ $slider.slider();
+ $slider.slider("option", "min", 0);
+ $slider.slider("option", "max", 97);
+ $slider.slider("option", "step", 1);
+ $slider.slider("option", "value", 50);
+ $slider.bind("slide", function(event, ui) {
+ jQuery('#mediamanager__diff_portions_image2').css({ width: $slider.slider("option", "value")+'%'});
+ });
+ },
+
+ params_toarray: function (str) {
+ var vars = [], hash;
+ var hashes = str.split('&');
+ for(var i = 0; i < hashes.length; i++) {
+ hash = hashes[i].split('=');
+ vars[hash[0]] = hash[1];
+ }
+ return vars;
+ },
+
+ init_ajax_uploader: function () {
+ if (!jQuery('#mediamanager__uploader').length) return;
+ if (jQuery('.qq-upload-list').length) return;
+
+ var params = dw_mediamanager.form_params(jQuery('#dw__upload'))+'&call=mediaupload';
+ params = dw_mediamanager.params_toarray(params);
+
+ var uploader = new qq.FileUploaderExtended({
+ element: document.getElementById('mediamanager__uploader'),
+ action: DOKU_BASE + 'lib/exe/ajax.php',
+ params: params
+ });
+ },
+
prepare_content: function ($content) {
// hide syntax example
$content.find('div.example:visible').hide();
- dw_mediamanager.initFlashUpload();
},
/**
@@ -521,4 +966,10 @@ function hasFlash(version){
return ver >= version;
}
+jQuery(document).ready(function() {
+ dw_mediamanager.update_resizable();
+ dw_mediamanager.layout_width = jQuery("#mediamanager__layout").width();
+ jQuery(window).resize(dw_mediamanager.window_resize);
+});
+
jQuery(dw_mediamanager.init);
diff --git a/lib/scripts/page.js b/lib/scripts/page.js
index 05c5ece20..e4033b76d 100644
--- a/lib/scripts/page.js
+++ b/lib/scripts/page.js
@@ -10,6 +10,7 @@ dw_page = {
init: function(){
dw_page.sectionHighlight();
jQuery('a.fn_top').mouseover(dw_page.footnoteDisplay);
+ dw_page.initTocToggle();
},
/**
@@ -20,8 +21,8 @@ dw_page = {
sectionHighlight: function() {
jQuery('form.btn_secedit')
.mouseover(function(){
- var $tgt = jQuery(this).parent();
- var nr = $tgt.attr('class').match(/(\s+|^)editbutton_(\d+)(\s+|$)/)[2];
+ var $tgt = jQuery(this).parent(),
+ nr = $tgt.attr('class').match(/(\s+|^)editbutton_(\d+)(\s+|$)/)[2];
// Walk the DOM tree up (first previous siblings, then parents)
// until boundary element
@@ -73,26 +74,67 @@ dw_page = {
* @author Andreas Gohr <andi@splitbrain.org>
* @author Chris Smith <chris@jalakai.co.uk>
*/
- footnoteDisplay: function(e){
- var $fndiv = dw_page.insituPopup(this, 'insitu__fn');
+ footnoteDisplay: function () {
+ var content = jQuery(jQuery(this).attr('href')) // Footnote text anchor
+ .closest('div.fn').html();
- // locate the footnote anchor element
- var $a = jQuery("#fn__" + e.target.id.substr(5));
- if (!$a.length){ return; }
-
- // anchor parent is the footnote container, get its innerHTML
- var content = new String ($a.parent().parent().html());
+ if (content === null){
+ return;
+ }
// strip the leading content anchors and their comma separators
- content = content.replace(/<sup>.*<\/sup>/gi, '');
- content = content.replace(/^\s+(,\s+)+/,'');
+ content = content.replace(/((^|\s*,\s*)<sup>.*?<\/sup>)+\s*/gi, '');
// prefix ids on any elements with "insitu__" to ensure they remain unique
content = content.replace(/\bid=(['"])([^"']+)\1/gi,'id="insitu__$2');
// now put the content into the wrapper
- $fndiv.html(content);
- $fndiv.show();
+ dw_page.insituPopup(this, 'insitu__fn').html(content).show();
+ },
+
+ /**
+ * Adds the toggle switch to the TOC
+ */
+ initTocToggle: function() {
+ var $header, $clicky, $toc, $tocul, setClicky;
+ $header = jQuery('#toc__header');
+ if(!$header.length) {
+ return;
+ }
+ $toc = jQuery('#toc__inside');
+ $tocul = $toc.children('ul.toc');
+
+ setClicky = function(hiding){
+ if(hiding){
+ $clicky.html('<span>+</span>');
+ $clicky[0].className = 'toc_open';
+ }else{
+ $clicky.html('<span>&minus;</span>');
+ $clicky[0].className = 'toc_close';
+ }
+ };
+
+ $clicky = jQuery(document.createElement('span'))
+ .attr('id','toc__toggle');
+ $header.css('cursor','pointer')
+ .click(function () {
+ var hidden;
+
+ // Assert that $toc instantly takes the whole TOC space
+ $toc.css('height', $toc.height()).show();
+
+ hidden = $tocul.stop(true, true).is(':hidden');
+
+ setClicky(!hidden);
+
+ // Start animation and assure that $toc is hidden/visible
+ $tocul.dw_toggle(hidden, function () {
+ $toc.toggle(hidden);
+ });
+ })
+ .prepend($clicky);
+
+ setClicky();
}
};