MDL-31901: filemanager/picker.js - match coding style
[moodle.git] / repository / filepicker.js
1 // YUI3 File Picker module for moodle
2 // Author: Dongsheng Cai <dongsheng@moodle.com>
4 /**
5  *
6  * File Picker UI
7  * =====
8  * this.fpnode, contains reference to filepicker Node, non-empty if and only if rendered
9  * this.api, stores the URL to make ajax request
10  * this.mainui, YUI Panel
11  * this.selectnode, contains reference to select-file Node
12  * this.selectui, YUI Panel for selecting particular file
13  * this.msg_dlg, YUI Panel for error or info message
14  * this.process_dlg, YUI Panel for processing existing filename
15  * this.treeview, YUI Treeview
16  * this.viewmode, store current view mode
17  * this.pathbar, reference to the Node with path bar
18  * this.pathnode, a Node element representing one folder in a path bar (not attached anywhere, just used for template)
19  *
20  * Filepicker options:
21  * =====
22  * this.options.client_id, the instance id
23  * this.options.contextid
24  * this.options.itemid
25  * this.options.repositories, stores all repositories displaied in file picker
26  * this.options.formcallback
27  *
28  * Active repository options
29  * =====
30  * this.active_repo.id
31  * this.active_repo.nosearch
32  * this.active_repo.norefresh
33  * this.active_repo.nologin
34  * this.active_repo.help
35  * this.active_repo.manage
36  *
37  * Server responses
38  * =====
39  * this.filelist, cached filelist
40  * this.pages
41  * this.page
42  * this.filepath, current path
43  * this.logindata, cached login form
44  */
46 YUI.add('moodle-core_filepicker', function(Y) {
47     /** help function to extract width/height style as a number, not as a string */
48     Y.Node.prototype.getStylePx = function(attr) {
49         var style = this.getStyle(attr);
50         if (''+style == '0' || ''+style == '0px') {
51             return 0;
52         }
53         var matches = style.match(/^([\d\.]+)px$/)
54         if (matches && parseFloat(matches[1])) {
55             return parseFloat(matches[1]);
56         }
57         return null;
58     }
60     /** if condition is met, the class is added to the node, otherwise - removed */
61     Y.Node.prototype.addClassIf = function(className, condition) {
62         if (condition) {
63             this.addClass(className);
64         } else {
65             this.removeClass(className);
66         }
67         return this;
68     }
70     /** sets the width(height) of the node considering existing minWidth(minHeight) */
71     Y.Node.prototype.setStyleAdv = function(stylename, value) {
72         var stylenameCap = stylename.substr(0,1).toUpperCase() + stylename.substr(1, stylename.length-1).toLowerCase();
73         this.setStyle(stylename, '' + Math.max(value, this.getStylePx('min'+stylenameCap)) + 'px')
74         return this;
75     }
77     /**
78      * Displays a list of files (used by filepicker, filemanager) inside the Node
79      *
80      * @param array options
81      *   viewmode : 1 - icons, 2 - tree, 3 - table
82      *   appendonly : whether fileslist need to be appended instead of replacing the existing content
83      *   filenode : Node element that contains template for displaying one file
84      *   callback : On click callback. The element of the fileslist array will be passed as argument
85      *   rightclickcallback : On right click callback (optional).
86      *   callbackcontext : context where callbacks are executed
87      *   sortable : whether content may be sortable (in table mode)
88      *   dynload : allow dynamic load for tree view
89      *   filepath : for pre-building of tree view - the path to the current directory in filepicker format
90      *   treeview_dynload : callback to function to dynamically load the folder in tree view
91      *   classnamecallback : callback to function that returns the class name for an element
92      * @param array fileslist array of files to show, each array element may have attributes:
93      *   title or fullname : file name
94      *   shorttitle (optional) : display file name
95      *   thumbnail : url of image
96      *   icon : url of icon image
97      *   thumbnail_width : width of thumbnail, default 90
98      *   thumbnail_height : height of thumbnail, default 90
99      *   thumbnail_alt : TODO not needed!
100      *   description or thumbnail_title : alt text
101      * @param array lazyloading : reference to the array with lazy loading images
102      */
103     Y.Node.prototype.fp_display_filelist = function(options, fileslist, lazyloading) {
104         var viewmodeclassnames = {1:'fp-iconview', 2:'fp-treeview', 3:'fp-tableview'};
105         var classname = viewmodeclassnames[options.viewmode];
106         var scope = this;
107         /** return whether file is a folder (different attributes in FileManager and FilePicker) */
108         var file_is_folder = function(node) {
109             if (node.children) {return true;}
110             if (node.type && node.type == 'folder') {return true;}
111             return false;
112         };
113         /** return the name of the file (different attributes in FileManager and FilePicker) */
114         var file_get_filename = function(node) {
115             return node.title ? node.title : node.fullname;
116         }
117         /** return display name of the file (different attributes in FileManager and FilePicker) */
118         var file_get_displayname = function(node) {
119             return node.shorttitle ? node.shorttitle : file_get_filename(node);
120         }
121         /** return file description (different attributes in FileManager and FilePicker) */
122         var file_get_description = function(node) {
123             return node.description ? node.description : (node.thumbnail_title ? node.thumbnail_title : file_get_filename(node));
124         }
125         /** help funciton for tree view */
126         var build_tree = function(node, level) {
127             // prepare file name with icon
128             var el = Y.Node.create('<div/>');
129             el.appendChild(options.filenode.cloneNode(true));
131             el.one('.fp-filename').setContent(file_get_displayname(node));
132             // TODO add tooltip with node.title or node.thumbnail_title
133             var tmpnodedata = {className:options.classnamecallback(node)};
134             el.get('children').addClass(tmpnodedata.className);
135             if (node.icon) {
136                 el.one('.fp-icon').appendChild(Y.Node.create('<img/>').set('src', node.icon));
137                 if (node.realicon) {
138                     lazyloading[el.one('.fp-icon img').generateID()] = node.realicon;
139                 }
140             }
141             // create node
142             tmpnodedata.html = el.getContent();
143             var tmpNode = new YAHOO.widget.HTMLNode(tmpnodedata, level, false);
144             if (node.dynamicLoadComplete) {
145                 tmpNode.dynamicLoadComplete = true;
146             }
147             tmpNode.fileinfo = node;
148             tmpNode.isLeaf = !file_is_folder(node);
149             if (!tmpNode.isLeaf) {
150                 if(node.expanded) {
151                     tmpNode.expand();
152                 }
153                 tmpNode.path = node.path ? node.path : (node.filepath ? node.filepath : '');
154                 for(var c in node.children) {
155                     build_tree(node.children[c], tmpNode);
156                 }
157             }
158         };
159         /** initialize tree view */
160         var initialize_tree_view = function() {
161             var parentid = scope.one('.'+classname).get('id');
162             // TODO MDL-32736 use YUI3 gallery TreeView
163             scope.treeview = new YAHOO.widget.TreeView(parentid);
164             if (options.dynload) {
165                 scope.treeview.setDynamicLoad(Y.bind(options.treeview_dynload, options.callbackcontext), 1);
166             }
167             scope.treeview.singleNodeHighlight = true;
168             if (options.filepath && options.filepath.length) {
169                 // we just jumped from icon/details view, we need to show all parents
170                 // we extract as much information as possible from filepath and filelist
171                 // and send additional requests to retrieve siblings for parent folders
172                 var mytree = {};
173                 var mytreeel = null;
174                 for (var i in options.filepath) {
175                     if (mytreeel == null) {
176                         mytreeel = mytree;
177                     } else {
178                         mytreeel.children = [{}];
179                         mytreeel = mytreeel.children[0];
180                     }
181                     var pathelement = options.filepath[i];
182                     mytreeel.path = pathelement.path;
183                     mytreeel.title = pathelement.name;
184                     mytreeel.dynamicLoadComplete = true; // we will call it manually
185                     mytreeel.expanded = true;
186                 }
187                 mytreeel.children = fileslist;
188                 build_tree(mytree, scope.treeview.getRoot());
189                 // manually call dynload for parent elements in the tree so we can load other siblings
190                 if (options.dynload) {
191                     var root = scope.treeview.getRoot();
192                     while (root && root.children && root.children.length) {
193                         root = root.children[0];
194                         if (root.path == mytreeel.path) {
195                             root.origpath = options.filepath;
196                             root.origlist = fileslist;
197                         } else if (!root.isLeaf && root.expanded) {
198                             Y.bind(options.treeview_dynload, options.callbackcontext)(root, null);
199                         }
200                     }
201                 }
202             } else {
203                 // there is no path information, just display all elements as a list, without hierarchy
204                 for(k in fileslist) {
205                     build_tree(fileslist[k], scope.treeview.getRoot());
206                 }
207             }
208             scope.treeview.subscribe('clickEvent', function(e){
209                 e.node.highlight(false);
210                 var callback = options.callback;
211                 if (options.rightclickcallback && e.event.target &&
212                         Y.Node(e.event.target).ancestor('.fp-treeview .fp-contextmenu', true)) {
213                     callback = options.rightclickcallback;
214                 }
215                 Y.bind(callback, options.callbackcontext)(e, e.node.fileinfo);
216                 YAHOO.util.Event.stopEvent(e.event)
217             });
218             // TODO MDL-32736 support right click
219             /*if (options.rightclickcallback) {
220                 scope.treeview.subscribe('dblClickEvent', function(e){
221                     e.node.highlight(false);
222                     Y.bind(options.rightclickcallback, options.callbackcontext)(e, e.node.fileinfo);
223                 });
224             }*/
225             scope.treeview.draw();
226         };
227         /** formatting function for table view */
228         var formatValue = function (o){
229             if (o.data[''+o.column.key+'_f_s']) {return o.data[''+o.column.key+'_f_s'];}
230             else if (o.data[''+o.column.key+'_f']) {return o.data[''+o.column.key+'_f'];}
231             else if (o.value) {return o.value;}
232             else {return '';}
233         };
234         /** formatting function for table view */
235         var formatTitle = function(o) {
236             var el = Y.Node.create('<div/>');
237             el.appendChild(options.filenode.cloneNode(true)); // TODO not node but string!
238             el.get('children').addClass(o.data['classname']);
239             el.one('.fp-filename').setContent(o.value);
240             if (o.data['icon']) {
241                 el.one('.fp-icon').appendChild(Y.Node.create('<img/>').set('src', o.data['icon']));
242                 if (o.data['realicon']) {
243                     lazyloading[el.one('.fp-icon img').generateID()] = o.data['realicon'];
244                 }
245             }
246             if (options.rightclickcallback) {
247                 el.get('children').addClass('fp-hascontextmenu');
248             }
249             // TODO add tooltip with o.data['title'] (o.value) or o.data['thumbnail_title']
250             return el.getContent();
251         }
252         /** sorting function for table view */
253         var sortFoldersFirst = function(a, b, desc) {
254             if (a.get('isfolder') && !b.get('isfolder')) {
255                 return -1;
256             }
257             if (!a.get('isfolder') && b.get('isfolder')) {
258                 return 1;
259             }
260             var aa = a.get(this.key), bb = b.get(this.key), dir = desc ? -1 : 1;
261             return (aa > bb) ? dir : ((aa < bb) ? -dir : 0);
262         }
263         /** initialize table view */
264         var initialize_table_view = function() {
265             var parentid = scope.one('.'+classname).get('id');
266             var cols = [
267                 {key: "displayname", label: M.str.moodle.name, allowHTML: true, formatter: formatTitle,
268                     sortable: true, sortFn: sortFoldersFirst},
269                 {key: "datemodified", label: M.str.moodle.lastmodified, allowHTML: true, formatter: formatValue,
270                     sortable: true, sortFn: sortFoldersFirst},
271                 {key: "size", label: M.str.repository.size, allowHTML: true, formatter: formatValue,
272                     sortable: true, sortFn: sortFoldersFirst},
273                 {key: "mimetype", label: M.str.repository.type, allowHTML: true,
274                     sortable: true, sortFn: sortFoldersFirst}
275             ];
276             scope.tableview = new Y.DataTable({columns: cols});
277             scope.tableview.render('#'+parentid);
278             scope.tableview.delegate('click', function (e, tableview) {
279                 var record = tableview.getRecord(e.currentTarget.get('id'));
280                 if (record) {
281                     var callback = options.callback;
282                     if (options.rightclickcallback && e.target.ancestor('.fp-tableview .fp-contextmenu', true)) {
283                         callback = options.rightclickcallback;
284                     }
285                     Y.bind(callback, this)(e, record.getAttrs());
286                 }
287             }, 'tr', options.callbackcontext, scope.tableview);
288             if (options.rightclickcallback) {
289                 scope.tableview.delegate('contextmenu', function (e, tableview) {
290                     var record = tableview.getRecord(e.currentTarget.get('id'));
291                     if (record) { Y.bind(options.rightclickcallback, this)(e, record.getAttrs()); }
292                 }, 'tr', options.callbackcontext, scope.tableview);
293             }
294         }
295         /** append items in table view mode */
296         var append_files_table = function() {
297             for (var k in fileslist) {
298                 // to speed up sorting and formatting
299                 fileslist[k].displayname = file_get_displayname(fileslist[k]);
300                 fileslist[k].isfolder = file_is_folder(fileslist[k]);
301                 fileslist[k].classname = options.classnamecallback(fileslist[k]);
302             }
303             scope.tableview.addRows(fileslist);
304             scope.tableview.sortable = options.sortable ? true : false;
305         };
306         /** append items in tree view mode */
307         var append_files_tree = function() {
308             if (options.appendonly) {
309                 var parentnode = scope.treeview.getRoot();
310                 if (scope.treeview.getHighlightedNode()) {
311                     parentnode = scope.treeview.getHighlightedNode();
312                     if (parentnode.isLeaf) {parentnode = parentnode.parent;}
313                 }
314                 for (var k in fileslist) {
315                     build_tree(fileslist[k], parentnode);
316                 }
317                 scope.treeview.draw();
318             } else {
319                 // otherwise files were already added in initialize_tree_view()
320             }
321         }
322         /** append items in icon view mode */
323         var append_files_icons = function() {
324             parent = scope.one('.'+classname);
325             for (var k in fileslist) {
326                 var node = fileslist[k];
327                 var element = options.filenode.cloneNode(true);
328                 parent.appendChild(element);
329                 element.addClass(options.classnamecallback(node));
330                 var filenamediv = element.one('.fp-filename');
331                 filenamediv.setContent(file_get_displayname(node));
332                 var imgdiv = element.one('.fp-thumbnail'), width, height, src;
333                 if (node.thumbnail) {
334                     width = node.thumbnail_width ? node.thumbnail_width : 90;
335                     height = node.thumbnail_height ? node.thumbnail_height : 90;
336                     src = node.thumbnail;
337                 } else {
338                     width = 16;
339                     height = 16;
340                     src = node.icon;
341                 }
342                 filenamediv.setStyleAdv('width', width);
343                 imgdiv.setStyleAdv('width', width).setStyleAdv('height', height);
344                 var img = Y.Node.create('<img/>').setAttrs({
345                         src: src,
346                         title: file_get_description(node),
347                         alt: node.thumbnail_alt ? node.thumbnail_alt : file_get_filename(node)}).
348                     setStyle('maxWidth', ''+width+'px').
349                     setStyle('maxHeight', ''+height+'px');
350                 if (node.realthumbnail) {
351                     lazyloading[img.generateID()] = node.realthumbnail;
352                 }
353                 imgdiv.appendChild(img);
354                 element.on('click', function(e, nd) {
355                     if (options.rightclickcallback && e.target.ancestor('.fp-iconview .fp-contextmenu', true)) {
356                         Y.bind(options.rightclickcallback, this)(e, nd);
357                     } else {
358                         Y.bind(options.callback, this)(e, nd);
359                     }
360                 }, options.callbackcontext, node);
361                 if (options.rightclickcallback) {
362                     element.on('contextmenu', options.rightclickcallback, options.callbackcontext, node);
363                 }
364             }
365         }
367         // initialize files view
368         if (!options.appendonly) {
369             var parent = Y.Node.create('<div/>').addClass(classname);
370             this.setContent('').appendChild(parent);
371             parent.generateID();
372             if (options.viewmode == 2) {
373                 initialize_tree_view();
374             } else if (options.viewmode == 3) {
375                 initialize_table_view();
376             } else {
377                 // nothing to initialize for icon view
378             }
379         }
381         // append files to the list
382         if (options.viewmode == 2) {
383             append_files_tree();
384         } else if (options.viewmode == 3) {
385             append_files_table();
386         } else {
387             append_files_icons();
388         }
390     }
391 }, '@VERSION@', {
392     requires:['base', 'node', 'yui2-treeview', 'panel', 'cookie', 'datatable', 'datatable-sort']
393 });
395 M.core_filepicker = M.core_filepicker || {};
397 /**
398  * instances of file pickers used on page
399  */
400 M.core_filepicker.instances = M.core_filepicker.instances || {};
401 M.core_filepicker.active_filepicker = null;
403 /**
404  * HTML Templates to use in FilePicker
405  */
406 M.core_filepicker.templates = M.core_filepicker.templates || {};
408 /**
409 * Set selected file info
411 * @parma object file info
412 */
413 M.core_filepicker.select_file = function(file) {
414     M.core_filepicker.active_filepicker.select_file(file);
417 /**
418  * Init and show file picker
419  */
420 M.core_filepicker.show = function(Y, options) {
421     if (!M.core_filepicker.instances[options.client_id]) {
422         M.core_filepicker.init(Y, options);
423     }
424     M.core_filepicker.instances[options.client_id].show();
425 };
427 M.core_filepicker.set_templates = function(Y, templates) {
428     for (var templid in templates) {
429         M.core_filepicker.templates[templid] = templates[templid];
430     }
433 /**
434  * Add new file picker to current instances
435  */
436 M.core_filepicker.init = function(Y, options) {
437     var FilePickerHelper = function(options) {
438         FilePickerHelper.superclass.constructor.apply(this, arguments);
439     };
441     FilePickerHelper.NAME = "FilePickerHelper";
442     FilePickerHelper.ATTRS = {
443         options: {},
444         lang: {}
445     };
447     Y.extend(FilePickerHelper, Y.Base, {
448         api: M.cfg.wwwroot+'/repository/repository_ajax.php',
449         cached_responses: {},
451         initializer: function(options) {
452             this.options = options;
453             if (!this.options.savepath) {
454                 this.options.savepath = '/';
455             }
456         },
458         destructor: function() {
459         },
461         request: function(args, redraw) {
462             var api = (args.api ? args.api : this.api) + '?action='+args.action;
463             var params = {};
464             var scope = args['scope'] ? args['scope'] : this;
465             params['repo_id']=args.repository_id;
466             params['p'] = args.path?args.path:'';
467             params['page'] = args.page?args.page:'';
468             params['env']=this.options.env;
469             // the form element only accept certain file types
470             params['accepted_types']=this.options.accepted_types;
471             params['sesskey'] = M.cfg.sesskey;
472             params['client_id'] = args.client_id;
473             params['itemid'] = this.options.itemid?this.options.itemid:0;
474             params['maxbytes'] = this.options.maxbytes?this.options.maxbytes:-1;
475             if (this.options.context && this.options.context.id) {
476                 params['ctx_id'] = this.options.context.id;
477             }
478             if (args['params']) {
479                 for (i in args['params']) {
480                     params[i] = args['params'][i];
481                 }
482             }
483             if (args.action == 'upload') {
484                 var list = [];
485                 for(var k in params) {
486                     var value = params[k];
487                     if(value instanceof Array) {
488                         for(var i in value) {
489                             list.push(k+'[]='+value[i]);
490                         }
491                     } else {
492                         list.push(k+'='+value);
493                     }
494                 }
495                 params = list.join('&');
496             } else {
497                 params = build_querystring(params);
498             }
499             var cfg = {
500                 method: 'POST',
501                 on: {
502                     complete: function(id,o,p) {
503                         if (!o) {
504                             // TODO
505                             alert('IO FATAL');
506                             return;
507                         }
508                         var data = null;
509                         try {
510                             data = Y.JSON.parse(o.responseText);
511                         } catch(e) {
512                             scope.print_msg(M.str.repository.invalidjson, 'error');
513                             scope.display_error(M.str.repository.invalidjson+'<pre>'+stripHTML(o.responseText)+'</pre>', 'invalidjson')
514                             return;
515                         }
516                         // error checking
517                         if (data && data.error) {
518                             scope.print_msg(data.error, 'error');
519                             if (args.onerror) {
520                                 args.onerror(id,data,p);
521                             } else {
522                                 this.fpnode.one('.fp-content').setContent('');
523                             }
524                             return;
525                         } else {
526                             if (data.msg) {
527                                 scope.print_msg(data.msg, 'info');
528                             }
529                             // cache result if applicable
530                             if (args.action != 'upload' && data.allowcaching) {
531                                 scope.cached_responses[params] = data;
532                             }
533                             // invoke callback
534                             args.callback(id,data,p);
535                         }
536                     }
537                 },
538                 arguments: {
539                     scope: scope
540                 },
541                 headers: {
542                     'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
543                 },
544                 data: params,
545                 context: this
546             };
547             if (args.form) {
548                 cfg.form = args.form;
549             }
550             // check if result of the same request has been already cached. If not, request it
551             // (never applicable in case of form submission and/or upload action):
552             if (!args.form && args.action != 'upload' && scope.cached_responses[params]) {
553                 args.callback(null, scope.cached_responses[params], {scope: scope})
554             } else {
555                 Y.io(api, cfg);
556                 if (redraw) {
557                     this.wait();
558                 }
559             }
560         },
561         /** displays the dialog and processes rename/overwrite if there is a file with the same name in the same filearea*/
562         process_existing_file: function(data) {
563             var scope = this;
564             var handleOverwrite = function(e) {
565                 // overwrite
566                 e.preventDefault();
567                 var data = this.process_dlg.dialogdata;
568                 var params = {}
569                 params['existingfilename'] = data.existingfile.filename;
570                 params['existingfilepath'] = data.existingfile.filepath;
571                 params['newfilename'] = data.newfile.filename;
572                 params['newfilepath'] = data.newfile.filepath;
573                 this.hide_header();
574                 this.request({
575                     'params': params,
576                     'scope': this,
577                     'action':'overwrite',
578                     'path': '',
579                     'client_id': this.options.client_id,
580                     'repository_id': this.active_repo.id,
581                     'callback': function(id, o, args) {
582                         scope.hide();
583                         // editor needs to update url
584                         // filemanager do nothing
585                         if (scope.options.editor_target && scope.options.env == 'editor') {
586                             scope.options.editor_target.value = data.existingfile.url;
587                             scope.options.editor_target.onchange();
588                         } else if (scope.options.env === 'filepicker') {
589                             var fileinfo = {'client_id':scope.options.client_id,
590                                     'url':data.existingfile.url,
591                                     'file':data.existingfile.filename};
592                             var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
593                             scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
594                         }
595                     }
596                 }, true);
597             }
598             var handleRename = function(e) {
599                 // inserts file with the new name
600                 e.preventDefault();
601                 var scope = this;
602                 var data = this.process_dlg.dialogdata;
603                 if (scope.options.editor_target && scope.options.env == 'editor') {
604                     scope.options.editor_target.value = data.newfile.url;
605                     scope.options.editor_target.onchange();
606                 }
607                 scope.hide();
608                 var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
609                 var fileinfo = {'client_id':scope.options.client_id,
610                                 'url':data.newfile.url,
611                                 'file':data.newfile.filename};
612                 scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
613             }
614             var handleCancel = function(e) {
615                 // Delete tmp file
616                 e.preventDefault();
617                 var params = {};
618                 params['newfilename'] = this.process_dlg.dialogdata.newfile.filename;
619                 params['newfilepath'] = this.process_dlg.dialogdata.newfile.filepath;
620                 this.request({
621                     'params': params,
622                     'scope': this,
623                     'action':'deletetmpfile',
624                     'path': '',
625                     'client_id': this.options.client_id,
626                     'repository_id': this.active_repo.id,
627                     'callback': function(id, o, args) {
628                         // let it be in background, from user point of view nothing is happenning
629                     }
630                 }, false);
631                 this.process_dlg.hide();
632                 this.selectui.hide();
633             }
634             if (!this.process_dlg) {
635                 this.process_dlg_node = Y.Node.create(M.core_filepicker.templates.processexistingfile);
636                 var node = this.process_dlg_node;
637                 node.generateID();
638                 Y.one(document.body).appendChild(node);
639                 this.process_dlg = new Y.Panel({
640                     srcNode      : node,
641                     headerContent: M.str.repository.fileexistsdialogheader,
642                     zIndex       : 800000,
643                     centered     : true,
644                     modal        : true,
645                     visible      : false,
646                     render       : true,
647                     buttons      : {}
648                 });
649                 this.process_dlg.plug(Y.Plugin.Drag,{handles:['#'+node.get('id')+' .yui3-widget-hd']});
650                 node.one('.fp-dlg-butoverwrite').on('click', handleOverwrite, this);
651                 node.one('.fp-dlg-butrename').on('click', handleRename, this);
652                 node.one('.fp-dlg-butcancel').on('click', handleCancel, this);
653                 if (this.options.env == 'editor') {
654                     node.one('.fp-dlg-text').setContent(M.str.repository.fileexistsdialog_editor);
655                 } else {
656                     node.one('.fp-dlg-text').setContent(M.str.repository.fileexistsdialog_filemanager);
657                 }
658             }
659             this.selectnode.removeClass('loading');
660             this.process_dlg.dialogdata = data;
661             this.process_dlg_node.one('.fp-dlg-butrename').setContent(M.util.get_string('renameto', 'repository', data.newfile.filename));
662             this.process_dlg.show();
663         },
664         /** displays error instead of filepicker contents */
665         display_error: function(errortext, errorcode) {
666             this.fpnode.one('.fp-content').setContent(M.core_filepicker.templates.error);
667             this.fpnode.one('.fp-content .fp-error').
668                 addClass(errorcode).
669                 setContent(errortext);
670         },
671         /** displays message in a popup */
672         print_msg: function(msg, type) {
673             var header = M.str.moodle.error;
674             if (type != 'error') {
675                 type = 'info'; // one of only two types excepted
676                 header = M.str.moodle.info;
677             }
678             if (!this.msg_dlg) {
679                 this.msg_dlg_node = Y.Node.create(M.core_filepicker.templates.message);
680                 this.msg_dlg_node.generateID();
681                 Y.one(document.body).appendChild(this.msg_dlg_node);
683                 this.msg_dlg = new Y.Panel({
684                     srcNode      : this.msg_dlg_node,
685                     zIndex       : 800000,
686                     centered     : true,
687                     modal        : true,
688                     visible      : false,
689                     render       : true
690                 });
691                 this.msg_dlg.plug(Y.Plugin.Drag,{handles:['#'+this.msg_dlg_node.get('id')+' .yui3-widget-hd']});
692                 this.msg_dlg_node.one('.fp-msg-butok').on('click', function(e) {
693                     e.preventDefault();
694                     this.msg_dlg.hide();
695                 }, this);
696             }
698             this.msg_dlg.set('headerContent', header);
699             this.msg_dlg_node.removeClass('fp-msg-info').removeClass('fp-msg-error').addClass('fp-msg-'+type)
700             this.msg_dlg_node.one('.fp-msg-text').setContent(msg);
701             this.msg_dlg.show();
702         },
703         view_files: function(appenditems) {
704             this.viewbar_set_enabled(true);
705             this.print_path();
706             /*if ((appenditems == null) && (!this.filelist || !this.filelist.length) && !this.active_repo.hasmorepages) {
707              // TODO do it via classes and adjust for each view mode!
708                 // If there are no items and no next page, just display status message and quit
709                 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
710                 return;
711             }*/
712             if (this.viewmode == 2) {
713                 this.view_as_list(appenditems);
714             } else if (this.viewmode == 3) {
715                 this.view_as_table(appenditems);
716             } else {
717                 this.view_as_icons(appenditems);
718             }
719             // display/hide the link for requesting next page
720             if (!appenditems && this.active_repo.hasmorepages) {
721                 if (!this.fpnode.one('.fp-content .fp-nextpage')) {
722                     this.fpnode.one('.fp-content').append(M.core_filepicker.templates.nextpage);
723                 }
724                 this.fpnode.one('.fp-content .fp-nextpage').one('a,button').on('click', function(e) {
725                     e.preventDefault();
726                     this.fpnode.one('.fp-content .fp-nextpage').addClass('loading');
727                     this.request_next_page();
728                 }, this);
729             }
730             if (!this.active_repo.hasmorepages && this.fpnode.one('.fp-content .fp-nextpage')) {
731                 this.fpnode.one('.fp-content .fp-nextpage').remove();
732             }
733             if (this.fpnode.one('.fp-content .fp-nextpage')) {
734                 this.fpnode.one('.fp-content .fp-nextpage').removeClass('loading');
735             }
736             this.content_scrolled();
737         },
738         content_scrolled: function(e) {
739             setTimeout(Y.bind(function() {
740                 if (this.processingimages) {
741                     return;
742                 }
743                 this.processingimages = true;
744                 var scope = this,
745                     fpcontent = this.fpnode.one('.fp-content'),
746                     fpcontenty = fpcontent.getY(),
747                     fpcontentheight = fpcontent.getStylePx('height'),
748                     nextpage = fpcontent.one('.fp-nextpage'),
749                     is_node_visible = function(node) {
750                         var offset = node.getY()-fpcontenty;
751                         if (offset <= fpcontentheight && (offset >=0 || offset+node.getStylePx('height')>=0)) {
752                             return true;
753                         }
754                         return false;
755                     };
756                 // automatically load next page when 'more' link becomes visible
757                 if (nextpage && !nextpage.hasClass('loading') && is_node_visible(nextpage)) {
758                     nextpage.one('a,button').simulate('click');
759                 }
760                 // replace src for visible images that need to be lazy-loaded
761                 if (scope.lazyloading) {
762                     fpcontent.all('img').each( function(node) {
763                         if (node.get('id') && scope.lazyloading[node.get('id')] && is_node_visible(node)) {
764                             node.set('src', scope.lazyloading[node.get('id')]);
765                             delete scope.lazyloading[node.get('id')];
766                         }
767                     });
768                 }
769                 this.processingimages = false;
770             }, this), 200)
771         },
772         treeview_dynload: function(node, cb) {
773             var retrieved_children = {};
774             if (node.children) {
775                 for (var i in node.children) {
776                     retrieved_children[node.children[i].path] = node.children[i];
777                 }
778             }
779             this.request({
780                 action:'list',
781                 client_id: this.options.client_id,
782                 repository_id: this.active_repo.id,
783                 path:node.path?node.path:'',
784                 page:node.page?args.page:'',
785                 scope:this,
786                 callback: function(id, obj, args) {
787                     var list = obj.list;
788                     var scope = args.scope;
789                     // check that user did not leave the view mode before recieving this response
790                     if (!(scope.active_repo.id == obj.repo_id && scope.viewmode == 2 && node && node.getChildrenEl())) {
791                         return;
792                     }
793                     if (cb != null) { // (in manual mode do not update current path)
794                         scope.viewbar_set_enabled(true);
795                         scope.parse_repository_options(obj);
796                     }
797                     node.highlight(false);
798                     node.origlist = obj.list ? obj.list : null;
799                     node.origpath = obj.path ? obj.path : null;
800                     node.children = [];
801                     for(k in list) {
802                         if (list[k].children && retrieved_children[list[k].path]) {
803                             // if this child is a folder and has already been retrieved
804                             node.children[node.children.length] = retrieved_children[list[k].path];
805                         } else {
806                             // append new file to the list
807                             scope.view_as_list([list[k]]);
808                         }
809                     }
810                     if (cb == null) {
811                         node.refresh();
812                     } else {
813                         // invoke callback requested by TreeView component
814                         cb();
815                     }
816                     scope.content_scrolled();
817                 }
818             }, false);
819         },
820         /** displays list of files in tree (list) view mode. If param appenditems is specified,
821          * appends those items to the end of the list. Otherwise (default behaviour)
822          * clears the contents and displays the items from this.filelist */
823         view_as_list: function(appenditems) {
824             var list = (appenditems != null) ? appenditems : this.filelist;
825             this.viewmode = 2;
826             if (!this.filelist || this.filelist.length==0 && (!this.filepath || !this.filepath.length)) {
827                 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
828                 return;
829             }
831             var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
832             var options = {
833                 viewmode : this.viewmode,
834                 appendonly : (appenditems != null),
835                 filenode : element_template,
836                 callbackcontext : this,
837                 callback : function(e, node) {
838                     // TODO MDL-32736 e is not an event here but an object with properties 'event' and 'node'
839                     if (!node.children) {
840                         if (e.node.parent && e.node.parent.origpath) {
841                             // set the current path
842                             this.filepath = e.node.parent.origpath;
843                             this.filelist = e.node.parent.origlist;
844                             this.print_path();
845                         }
846                         this.select_file(node);
847                     } else {
848                         // save current path and filelist (in case we want to jump to other viewmode)
849                         this.filepath = e.node.origpath;
850                         this.filelist = e.node.origlist;
851                         this.print_path();
852                         this.content_scrolled();
853                     }
854                 },
855                 classnamecallback : function(node) {
856                     return node.children ? 'fp-folder' : '';
857                 },
858                 dynload : this.active_repo.dynload,
859                 filepath : this.filepath,
860                 treeview_dynload : this.treeview_dynload
861             };
862             this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
863         },
864         /** displays list of files in icon view mode. If param appenditems is specified,
865          * appends those items to the end of the list. Otherwise (default behaviour)
866          * clears the contents and displays the items from this.filelist */
867         view_as_icons: function(appenditems) {
868             this.viewmode = 1;
869             var list = (appenditems != null) ? appenditems : this.filelist;
870             var element_template = Y.Node.create(M.core_filepicker.templates.iconfilename);
871             if ((appenditems == null) && (!this.filelist || !this.filelist.length)) {
872                 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
873                 return;
874             }
875             var options = {
876                 viewmode : this.viewmode,
877                 appendonly : (appenditems != null),
878                 filenode : element_template,
879                 callbackcontext : this,
880                 callback : function(e, node) {
881                     if (e.preventDefault) {
882                         e.preventDefault();
883                     }
884                     if(node.children) {
885                         if (this.active_repo.dynload) {
886                             this.list({'path':node.path});
887                         } else {
888                             this.filepath = node.path;
889                             this.filelist = node.children;
890                             this.view_files();
891                         }
892                     } else {
893                         this.select_file(node);
894                     }
895                 },
896                 classnamecallback : function(node) {
897                     return node.children ? 'fp-folder' : '';
898                 }
899             };
900             this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
901         },
902         /** displays list of files in table view mode. If param appenditems is specified,
903          * appends those items to the end of the list. Otherwise (default behaviour)
904          * clears the contents and displays the items from this.filelist */
905         view_as_table: function(appenditems) {
906             this.viewmode = 3;
907             var list = (appenditems != null) ? appenditems : this.filelist;
908             if (!appenditems && (!this.filelist || this.filelist.length==0) && !this.active_repo.hasmorepages) {
909                 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
910                 return;
911             }
912             var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
913             var options = {
914                 viewmode : this.viewmode,
915                 appendonly : (appenditems != null),
916                 filenode : element_template,
917                 callbackcontext : this,
918                 sortable : !this.active_repo.hasmorepages,
919                 callback : function(e, node) {
920                     if (e.preventDefault) {e.preventDefault();}
921                     if (node.children) {
922                         if (this.active_repo.dynload) {
923                             this.list({'path':node.path});
924                         } else {
925                             this.filepath = node.path;
926                             this.filelist = node.children;
927                             this.view_files();
928                         }
929                     } else {
930                         this.select_file(node);
931                     }
932                 },
933                 classnamecallback : function(node) {
934                     return node.children ? 'fp-folder' : '';
935                 }
936             };
937             this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
938         },
939         /** If more than one page available, requests and displays the files from the next page */
940         request_next_page: function() {
941             if (!this.active_repo.hasmorepages || this.active_repo.nextpagerequested) {
942                 // nothing to load
943                 return;
944             }
945             this.active_repo.nextpagerequested = true;
946             var nextpage = this.active_repo.page+1;
947             var args = {page:nextpage, repo_id:this.active_repo.id, path:this.active_repo.path};
948             var action = this.active_repo.issearchresult ? 'search' : 'list';
949             this.request({
950                 scope: this,
951                 action: action,
952                 client_id: this.options.client_id,
953                 repository_id: args.repo_id,
954                 params: args,
955                 callback: function(id, obj, args) {
956                     var scope = args.scope;
957                     // check that we are still in the same repository and are expecting this page
958                     if (scope.active_repo.hasmorepages && obj.list && obj.page &&
959                             obj.repo_id == scope.active_repo.id &&
960                             obj.page == scope.active_repo.page+1 && obj.path == scope.path) {
961                         scope.parse_repository_options(obj, true);
962                         scope.view_files(obj.list)
963                     }
964                 }
965             }, false);
966         },
967         select_file: function(args) {
968             this.selectui.show();
969             var client_id = this.options.client_id;
970             var selectnode = this.selectnode;
971             var return_types = this.options.repositories[this.active_repo.id].return_types;
972             selectnode.removeClass('loading');
973             selectnode.one('.fp-saveas input').set('value', args.title);
975             var imgnode = Y.Node.create('<img/>').
976                 set('src', args.realthumbnail ? args.realthumbnail : args.thumbnail).
977                 setStyle('maxHeight', ''+(args.thumbnail_height ? args.thumbnail_height : 90)+'px').
978                 setStyle('maxWidth', ''+(args.thumbnail_width ? args.thumbnail_width : 90)+'px');
979             selectnode.one('.fp-thumbnail').setContent('').appendChild(imgnode);
981             // filelink is the array of file-link-types available for this repository in this env
982             var filelinktypes = [2/*FILE_INTERNAL*/,1/*FILE_EXTERNAL*/,4/*FILE_REFERENCE*/];
983             var filelink = {}, firstfilelink = null, filelinkcount = 0;
984             for (var i in filelinktypes) {
985                 var allowed = (return_types & filelinktypes[i]) &&
986                     (this.options.return_types & filelinktypes[i]);
987                 if (filelinktypes[i] == 1/*FILE_EXTERNAL*/ && !this.options.externallink && this.options.env == 'editor') {
988                     // special configuration setting 'repositoryallowexternallinks' may prevent
989                     // using external links in editor environment
990                     allowed = false;
991                 }
992                 filelink[filelinktypes[i]] = allowed;
993                 firstfilelink = (firstfilelink==null && allowed) ? filelinktypes[i] : firstfilelink;
994                 filelinkcount += allowed ? 1 : 0;
995             }
996             // make radio buttons enabled if this file-link-type is available and only if there are more than one file-link-type option
997             // check the first available file-link-type option
998             for (var linktype in filelink) {
999                 var el = selectnode.one('.fp-linktype-'+linktype);
1000                 el.addClassIf('uneditable', !(filelink[linktype] && filelinkcount>1));
1001                 el.one('input').set('disabled', (filelink[linktype] && filelinkcount>1) ? '' : 'disabled').
1002                     set('checked', (firstfilelink == linktype) ? 'checked' : '').simulate('change')
1003             }
1005             // TODO MDL-32532: attributes 'hasauthor' and 'haslicense' need to be obsolete,
1006             selectnode.one('.fp-setauthor input').set('value', args.author ? args.author : this.options.author);
1007             this.set_selected_license(selectnode.one('.fp-setlicense'), args.license);
1008             selectnode.one('form #filesource-'+client_id).set('value', args.source);
1010             // display static information about a file (when known)
1011             var attrs = ['datemodified','datecreated','size','license','author','dimensions'];
1012             for (var i in attrs) {
1013                 if (selectnode.one('.fp-'+attrs[i])) {
1014                     var value = (args[attrs[i]+'_f']) ? args[attrs[i]+'_f'] : (args[attrs[i]] ? args[attrs[i]] : '');
1015                     selectnode.one('.fp-'+attrs[i]).addClassIf('fp-unknown', ''+value == '')
1016                         .one('.fp-value').setContent(value);
1017                 }
1018             }
1019         },
1020         setup_select_file: function() {
1021             var client_id = this.options.client_id;
1022             var selectnode = this.selectnode;
1023             var getfile = selectnode.one('.fp-select-confirm');
1024             // bind labels with corresponding inputs
1025             selectnode.all('.fp-saveas,.fp-linktype-2,.fp-linktype-1,.fp-linktype-4,.fp-setauthor,.fp-setlicense').each(function (node) {
1026                 node.all('label').set('for', node.one('input,select').generateID());
1027             });
1028             selectnode.one('.fp-linktype-2 input').setAttrs({value: 2, name: 'linktype'});
1029             selectnode.one('.fp-linktype-1 input').setAttrs({value: 1, name: 'linktype'});
1030             selectnode.one('.fp-linktype-4 input').setAttrs({value: 4, name: 'linktype'});
1031             var changelinktype = function(e) {
1032                 if (e.currentTarget.get('checked')) {
1033                     var allowinputs = e.currentTarget.get('value') != 1/*FILE_EXTERNAL*/;
1034                     selectnode.all('.fp-setauthor,.fp-setlicense,.fp-saveas').each(function(node){
1035                         node.addClassIf('uneditable', !allowinputs);
1036                         node.all('input,select').set('disabled', allowinputs?'':'disabled');
1037                     });
1038                 }
1039             };
1040             selectnode.all('.fp-linktype-2,.fp-linktype-1,.fp-linktype-4').each(function (node) {
1041                 node.one('input').on('change', changelinktype, this);
1042             });
1043             this.populate_licenses_select(selectnode.one('.fp-setlicense select'));
1044             // register event on clicking submit button
1045             getfile.on('click', function(e) {
1046                 e.preventDefault();
1047                 var client_id = this.options.client_id;
1048                 var scope = this;
1049                 var repository_id = this.active_repo.id;
1050                 var title = selectnode.one('.fp-saveas input').get('value');
1051                 var filesource = selectnode.one('form #filesource-'+client_id).get('value');
1052                 var params = {'title':title, 'source':filesource, 'savepath': this.options.savepath};
1053                 var license = selectnode.one('.fp-setlicense select');
1054                 if (license) {
1055                     params['license'] = license.get('value');
1056                     var origlicense = selectnode.one('.fp-license .fp-value');
1057                     if (origlicense) {
1058                         origlicense = origlicense.getContent();
1059                     }
1060                     var newlicenseval = license.get('value');
1061                     if (newlicenseval && this.options.licenses[newlicenseval] != origlicense) {
1062                         Y.Cookie.set('recentlicense', newlicenseval);
1063                     }
1064                 }
1065                 params['author'] = selectnode.one('.fp-setauthor input').get('value');
1067                 var return_types = this.options.repositories[this.active_repo.id].return_types;
1068                 if (this.options.env == 'editor') {
1069                     // in editor, images are stored in '/' only
1070                     params.savepath = '/';
1071                 }
1072                 if ((this.options.externallink || this.options.env != 'editor') &&
1073                             (return_types & 1/*FILE_EXTERNAL*/) &&
1074                             (this.options.return_types & 1/*FILE_EXTERNAL*/) &&
1075                             selectnode.one('.fp-linktype-1 input').get('checked')) {
1076                     params['linkexternal'] = 'yes';
1077                 } else if ((return_types & 4/*FILE_REFERENCE*/) &&
1078                         (this.options.return_types & 4/*FILE_REFERENCE*/) &&
1079                         selectnode.one('.fp-linktype-4 input').get('checked')) {
1080                     params['usefilereference'] = '1';
1081                 }
1083                 selectnode.addClass('loading');
1084                 this.request({
1085                     action:'download',
1086                     client_id: client_id,
1087                     repository_id: repository_id,
1088                     'params': params,
1089                     onerror: function(id, obj, args) {
1090                         selectnode.removeClass('loading');
1091                         scope.selectui.hide();
1092                     },
1093                     callback: function(id, obj, args) {
1094                         selectnode.removeClass('loading');
1095                         if (obj.event == 'fileexists') {
1096                             scope.process_existing_file(obj);
1097                             return;
1098                         }
1099                         if (scope.options.editor_target && scope.options.env=='editor') {
1100                             scope.options.editor_target.value=obj.url;
1101                             scope.options.editor_target.onchange();
1102                         }
1103                         scope.hide();
1104                         obj.client_id = client_id;
1105                         var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
1106                         scope.options.formcallback.apply(formcallback_scope, [obj]);
1107                     }
1108                 }, false);
1109             }, this);
1110             var elform = selectnode.one('form');
1111             elform.appendChild(Y.Node.create('<input/>').
1112                 setAttrs({type:'hidden',id:'filesource-'+client_id}));
1113             elform.on('keydown', function(e) {
1114                 if (e.keyCode == 13) {
1115                     getfile.simulate('click');
1116                     e.preventDefault();
1117                 }
1118             }, this);
1119             var cancel = selectnode.one('.fp-select-cancel');
1120             cancel.on('click', function(e) {
1121                 e.preventDefault();
1122                 this.selectui.hide();
1123             }, this);
1124         },
1125         wait: function() {
1126             this.fpnode.one('.fp-content').setContent(M.core_filepicker.templates.loading);
1127         },
1128         viewbar_set_enabled: function(mode) {
1129             var viewbar = this.fpnode.one('.fp-viewbar')
1130             if (viewbar) {
1131                 if (mode) {
1132                     viewbar.addClass('enabled').removeClass('disabled')
1133                 } else {
1134                     viewbar.removeClass('enabled').addClass('disabled')
1135                 }
1136             }
1137             this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').removeClass('checked')
1138             var modes = {1:'icons', 2:'tree', 3:'details'};
1139             this.fpnode.all('.fp-vb-'+modes[this.viewmode]).addClass('checked');
1140         },
1141         viewbar_clicked: function(e) {
1142             e.preventDefault();
1143             var viewbar = this.fpnode.one('.fp-viewbar')
1144             if (!viewbar || !viewbar.hasClass('disabled')) {
1145                 if (e.currentTarget.hasClass('fp-vb-tree')) {
1146                     this.viewmode = 2;
1147                 } else if (e.currentTarget.hasClass('fp-vb-details')) {
1148                     this.viewmode = 3;
1149                 } else {
1150                     this.viewmode = 1;
1151                 }
1152                 this.viewbar_set_enabled(true)
1153                 this.view_files();
1154                 Y.Cookie.set('recentviewmode', this.viewmode);
1155             }
1156         },
1157         render: function() {
1158             var client_id = this.options.client_id;
1159             this.fpnode = Y.Node.create(M.core_filepicker.templates.generallayout).
1160                 set('id', 'filepicker-'+client_id);
1161             this.selectnode = Y.Node.create(M.core_filepicker.templates.selectlayout);
1162             Y.one(document.body).appendChild(this.fpnode);
1163             this.mainui = new Y.Panel({
1164                 srcNode      : this.fpnode,
1165                 headerContent: M.str.repository.filepicker,
1166                 zIndex       : 500000,
1167                 centered     : true,
1168                 modal        : true,
1169                 visible      : false,
1170                 minWidth     : this.fpnode.getStylePx('minWidth'),
1171                 minHeight    : this.fpnode.getStylePx('minHeight'),
1172                 maxWidth     : this.fpnode.getStylePx('maxWidth'),
1173                 maxHeight    : this.fpnode.getStylePx('maxHeight'),
1174                 render       : true
1175             });
1176             // allow to move the panel dragging it by it's header:
1177             this.mainui.plug(Y.Plugin.Drag,{handles:['#filepicker-'+client_id+' .yui3-widget-hd']});
1178             this.mainui.show();
1179             if (this.mainui.get('y') < 0) {
1180                 this.mainui.set('y', 0);
1181             }
1182             // create panel for selecting a file (initially hidden)
1183             this.selectnode = Y.Node.create(M.core_filepicker.templates.selectlayout).
1184                 set('id', 'filepicker-select-'+client_id);
1185             Y.one(document.body).appendChild(this.selectnode);
1186             this.selectui = new Y.Panel({
1187                 srcNode      : this.selectnode,
1188                 zIndex       : 600000,
1189                 centered     : true,
1190                 modal        : true,
1191                 close        : true,
1192                 render       : true
1193             });
1194             // allow to move the panel dragging it by it's header:
1195             this.selectui.plug(Y.Plugin.Drag,{handles:['#filepicker-select-'+client_id+' .yui3-widget-hd']});
1196             this.selectui.hide();
1197             // event handler for lazy loading of thumbnails and next page
1198             this.fpnode.one('.fp-content').on(['scroll','resize'], this.content_scrolled, this);
1199             // save template for one path element and location of path bar
1200             if (this.fpnode.one('.fp-path-folder')) {
1201                 this.pathnode = this.fpnode.one('.fp-path-folder');
1202                 this.pathbar = this.pathnode.get('parentNode');
1203                 this.pathbar.removeChild(this.pathnode);
1204             }
1205             // assign callbacks for view mode switch buttons
1206             this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').
1207                 on('click', this.viewbar_clicked, this);
1208             // assign callbacks for toolbar links
1209             this.setup_toolbar();
1210             this.setup_select_file();
1211             this.hide_header();
1213             // processing repository listing
1214             // Resort the repositories by sortorder
1215             var sorted_repositories = [];
1216             for (var i in this.options.repositories) {
1217                 sorted_repositories[i] = this.options.repositories[i];
1218             }
1219             sorted_repositories.sort(function(a,b){return a.sortorder-b.sortorder});
1220             // extract one repository template and repeat it for all repositories available,
1221             // set name and icon and assign callbacks
1222             var reponode = this.fpnode.one('.fp-repo');
1223             if (reponode) {
1224                 var list = reponode.get('parentNode');
1225                 list.removeChild(reponode);
1226                 for (i in sorted_repositories) {
1227                     var repository = sorted_repositories[i];
1228                     var node = reponode.cloneNode(true);
1229                     list.appendChild(node);
1230                     node.
1231                         set('id', 'fp-repo-'+client_id+'-'+repository.id).
1232                         on('click', function(e, repository_id) {
1233                             e.preventDefault();
1234                             Y.Cookie.set('recentrepository', repository_id);
1235                             this.hide_header();
1236                             this.list({'repo_id':repository_id});
1237                         }, this /*handler running scope*/, repository.id/*second argument of handler*/);
1238                     node.one('.fp-repo-name').setContent(repository.name);
1239                     node.one('.fp-repo-icon').set('src', repository.icon);
1240                     if (i==0) {
1241                         node.addClass('first');
1242                     }
1243                     if (i==sorted_repositories.length-1) {
1244                         node.addClass('last');
1245                     }
1246                     if (i%2) {
1247                         node.addClass('even');
1248                     } else {
1249                         node.addClass('odd');
1250                     }
1251                 }
1252             }
1253             // display error if no repositories found
1254             if (sorted_repositories.length==0) {
1255                 this.display_error(M.str.repository.norepositoriesavailable, 'norepositoriesavailable')
1256             }
1257             // display repository that was used last time
1258             this.show_recent_repository();
1259         },
1260         parse_repository_options: function(data, appendtolist) {
1261             if (appendtolist) {
1262                 if (data.list) {
1263                     if (!this.filelist) {
1264                         this.filelist = [];
1265                     }
1266                     for (var i in data.list) {
1267                         this.filelist[this.filelist.length] = data.list[i];
1268                     }
1269                 }
1270             } else {
1271                 this.filelist = data.list?data.list:null;
1272                 this.lazyloading = {};
1273             }
1274             this.filepath = data.path?data.path:null;
1275             this.objecttag = data.object?data.object:null;
1276             this.active_repo = {};
1277             this.active_repo.issearchresult = data.issearchresult ? true : false;
1278             this.active_repo.dynload = data.dynload?data.dynload:false;
1279             this.active_repo.pages = Number(data.pages?data.pages:null);
1280             this.active_repo.page = Number(data.page?data.page:null);
1281             this.active_repo.hasmorepages = (this.active_repo.pages && this.active_repo.page && (this.active_repo.page < this.active_repo.pages || this.active_repo.pages == -1))
1282             this.active_repo.id = data.repo_id?data.repo_id:null;
1283             this.active_repo.nosearch = (data.login || data.nosearch); // this is either login form or 'nosearch' attribute set
1284             this.active_repo.norefresh = (data.login || data.norefresh); // this is either login form or 'norefresh' attribute set
1285             this.active_repo.nologin = (data.login || data.nologin); // this is either login form or 'nologin' attribute is set
1286             this.active_repo.logouttext = data.logouttext?data.logouttext:null;
1287             this.active_repo.help = data.help?data.help:null;
1288             this.active_repo.manage = data.manage?data.manage:null;
1289             this.print_header();
1290         },
1291         print_login: function(data) {
1292             this.parse_repository_options(data);
1293             var client_id = this.options.client_id;
1294             var repository_id = data.repo_id;
1295             var l = this.logindata = data.login;
1296             var loginurl = '';
1297             var action = data['login_btn_action'] ? data['login_btn_action'] : 'login';
1298             var form_id = 'fp-form-'+client_id;
1300             var loginform_node = Y.Node.create(M.core_filepicker.templates.loginform);
1301             loginform_node.one('form').set('id', form_id);
1302             this.fpnode.one('.fp-content').setContent('').appendChild(loginform_node);
1303             var templates = {
1304                 'popup' : loginform_node.one('.fp-login-popup'),
1305                 'textarea' : loginform_node.one('.fp-login-textarea'),
1306                 'select' : loginform_node.one('.fp-login-select'),
1307                 'text' : loginform_node.one('.fp-login-text'),
1308                 'radio' : loginform_node.one('.fp-login-radiogroup'),
1309                 'checkbox' : loginform_node.one('.fp-login-checkbox'),
1310                 'input' : loginform_node.one('.fp-login-input')
1311             };
1312             var container;
1313             for (var i in templates) {
1314                 if (templates[i]) {
1315                     container = templates[i].get('parentNode');
1316                     container.removeChild(templates[i]);
1317                 }
1318             }
1320             for(var k in l) {
1321                 if (templates[l[k].type]) {
1322                     var node = templates[l[k].type].cloneNode(true);
1323                 } else {
1324                     node = templates['input'].cloneNode(true);
1325                 }
1326                 if (l[k].type == 'popup') {
1327                     // submit button
1328                     loginurl = l[k].url;
1329                     var popupbutton = node.one('button');
1330                     popupbutton.on('click', function(e){
1331                         M.core_filepicker.active_filepicker = this;
1332                         window.open(loginurl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1333                         e.preventDefault();
1334                     }, this);
1335                     loginform_node.one('form').on('keydown', function(e) {
1336                         if (e.keyCode == 13) {
1337                             popupbutton.simulate('click');
1338                             e.preventDefault();
1339                         }
1340                     }, this);
1341                     loginform_node.all('.fp-login-submit').remove();
1342                     action = 'popup';
1343                 } else if(l[k].type=='textarea') {
1344                     // textarea element
1345                     if (node.one('label')) {
1346                         node.one('label').set('for', l[k].id).setContent(l[k].label);
1347                     }
1348                     node.one('textarea').setAttrs({id:l[k].id, name:l[k].name});
1349                 } else if(l[k].type=='select') {
1350                     // select element
1351                     if (node.one('label')) {
1352                         node.one('label').set('for', l[k].id).setContent(l[k].label);
1353                     }
1354                     node.one('select').setAttrs({id:l[k].id, name:l[k].name}).setContent('');
1355                     for (i in l[k].options) {
1356                         node.one('select').appendChild(
1357                             Y.Node.create('<option/>').
1358                                 set('value', l[k].options[i].value).
1359                                 setContent(l[k].options[i].label));
1360                     }
1361                 } else if(l[k].type=='radio') {
1362                     // radio input element
1363                     node.all('label').setContent(l[k].label);
1364                     var list = l[k].value.split('|');
1365                     var labels = l[k].value_label.split('|');
1366                     var radionode = null;
1367                     for(var item in list) {
1368                         if (radionode == null) {
1369                             radionode = node.one('.fp-login-radio');
1370                             radionode.one('input').set('checked', 'checked');
1371                         } else {
1372                             var x = radionode.cloneNode(true);
1373                             radionode.insert(x, 'after');
1374                             radionode = x;
1375                             radionode.one('input').set('checked', '');
1376                         }
1377                         radionode.one('input').setAttrs({id:''+l[k].id+item, name:l[k].name,
1378                             type:l[k].type, value:list[item]});
1379                         radionode.all('label').setContent(labels[item]).set('for', ''+l[k].id+item)
1380                     }
1381                     if (radionode == null) {
1382                         node.one('.fp-login-radio').remove();
1383                     }
1384                 } else {
1385                     // input element
1386                     if (node.one('label')) { node.one('label').set('for', l[k].id).setContent(l[k].label) }
1387                     node.one('input').
1388                         set('type', l[k].type).
1389                         set('id', l[k].id).
1390                         set('name', l[k].name).
1391                         set('value', l[k].value?l[k].value:'')
1392                 }
1393                 container.appendChild(node);
1394             }
1395             // custom label text for submit button
1396             if (data['login_btn_label']) {
1397                 loginform_node.all('.fp-login-submit').setContent(data['login_btn_label'])
1398             }
1399             // register button action for login and search
1400             if (action == 'login' || action == 'search') {
1401                 loginform_node.one('.fp-login-submit').on('click', function(e){
1402                     e.preventDefault();
1403                     this.hide_header();
1404                     this.request({
1405                         'scope': this,
1406                         'action':(action == 'search') ? 'search' : 'signin',
1407                         'path': '',
1408                         'client_id': client_id,
1409                         'repository_id': repository_id,
1410                         'form': {id:form_id, upload:false, useDisabled:true},
1411                         'callback': this.display_response
1412                     }, true);
1413                 }, this);
1414             }
1415             // if 'Enter' is pressed in the form, simulate the button click
1416             if (loginform_node.one('.fp-login-submit')) {
1417                 loginform_node.one('form').on('keydown', function(e) {
1418                     if (e.keyCode == 13) {
1419                         loginform_node.one('.fp-login-submit').simulate('click')
1420                         e.preventDefault();
1421                     }
1422                 }, this);
1423             }
1424         },
1425         display_response: function(id, obj, args) {
1426             var scope = args.scope
1427             // highlight the current repository in repositories list
1428             scope.fpnode.all('.fp-repo.active').removeClass('active');
1429             scope.fpnode.all('#fp-repo-'+scope.options.client_id+'-'+obj.repo_id).addClass('active')
1430             // add class repository_REPTYPE to the filepicker (for repository-specific styles)
1431             for (var i in scope.options.repositories) {
1432                 scope.fpnode.removeClass('repository_'+scope.options.repositories[i].type)
1433             }
1434             if (obj.repo_id && scope.options.repositories[obj.repo_id]) {
1435                 scope.fpnode.addClass('repository_'+scope.options.repositories[obj.repo_id].type)
1436             }
1437             // display response
1438             if (obj.login) {
1439                 scope.viewbar_set_enabled(false);
1440                 scope.print_login(obj);
1441             } else if (obj.upload) {
1442                 scope.viewbar_set_enabled(false);
1443                 scope.parse_repository_options(obj);
1444                 scope.create_upload_form(obj);
1445             } else if (obj.object) {
1446                 M.core_filepicker.active_filepicker = scope;
1447                 scope.viewbar_set_enabled(false);
1448                 scope.parse_repository_options(obj);
1449                 scope.create_object_container(obj.object);
1450             } else if (obj.list) {
1451                 scope.viewbar_set_enabled(true);
1452                 scope.parse_repository_options(obj);
1453                 scope.view_files();
1454             }
1455         },
1456         list: function(args) {
1457             if (!args) {
1458                 args = {};
1459             }
1460             if (!args.repo_id) {
1461                 args.repo_id = this.active_repo.id;
1462             }
1463             this.request({
1464                 action: 'list',
1465                 client_id: this.options.client_id,
1466                 repository_id: args.repo_id,
1467                 path: args.path,
1468                 page: args.page,
1469                 scope: this,
1470                 callback: this.display_response
1471             }, true);
1472         },
1473         populate_licenses_select: function(node) {
1474             if (!node) {
1475                 return;
1476             }
1477             node.setContent('');
1478             var licenses = this.options.licenses;
1479             var recentlicense = Y.Cookie.get('recentlicense');
1480             if (recentlicense) {
1481                 this.options.defaultlicense=recentlicense;
1482             }
1483             for (var i in licenses) {
1484                 var option = Y.Node.create('<option/>').
1485                     set('selected', (this.options.defaultlicense==licenses[i].shortname)).
1486                     set('value', licenses[i].shortname).
1487                     setContent(licenses[i].fullname);
1488                 node.appendChild(option)
1489             }
1490         },
1491         set_selected_license: function(node, value) {
1492             var licenseset = false;
1493             node.all('option').each(function(el) {
1494                 if (el.get('value')==value || el.getContent()==value) {
1495                     el.set('selected', true);
1496                     licenseset = true;
1497                 }
1498             });
1499             if (!licenseset) {
1500                 // we did not find the value in the list
1501                 var recentlicense = Y.Cookie.get('recentlicense');
1502                 node.all('option[selected]').set('selected', false);
1503                 node.all('option[value='+recentlicense+']').set('selected', true);
1504             }
1505         },
1506         create_object_container: function(data) {
1507             var content = this.fpnode.one('.fp-content');
1508             content.setContent('');
1509             //var str = '<object data="'+data.src+'" type="'+data.type+'" width="98%" height="98%" id="container_object" class="fp-object-container mdl-align"></object>';
1510             var container = Y.Node.create('<object/>').
1511                 setAttrs({data:data.src, type:data.type, id:'container_object'}).
1512                 addClass('fp-object-container');
1513             content.setContent('').appendChild(container);
1514         },
1515         create_upload_form: function(data) {
1516             var client_id = this.options.client_id;
1517             var id = data.upload.id+'_'+client_id;
1518             var content = this.fpnode.one('.fp-content');
1519             content.setContent(M.core_filepicker.templates.uploadform);
1521             content.all('.fp-file,.fp-saveas,.fp-setauthor,.fp-setlicense').each(function (node) {
1522                 node.all('label').set('for', node.one('input,select').generateID());
1523             });
1524             content.one('form').set('id', id);
1525             content.one('.fp-file input').set('name', 'repo_upload_file');
1526             content.one('.fp-saveas input').set('name', 'title');
1527             content.one('.fp-setauthor input').setAttrs({name:'author', value:this.options.author});
1528             content.one('.fp-setlicense select').set('name', 'license');
1529             this.populate_licenses_select(content.one('.fp-setlicense select'))
1530             // append hidden inputs to the upload form
1531             content.one('form').appendChild(Y.Node.create('<input/>').
1532                 setAttrs({type:'hidden',name:'itemid',value:this.options.itemid}));
1533             var types = this.options.accepted_types;
1534             for (var i in types) {
1535                 content.one('form').appendChild(Y.Node.create('<input/>').
1536                     setAttrs({type:'hidden',name:'accepted_types[]',value:types[i]}));
1537             }
1539             var scope = this;
1540             content.one('.fp-upload-btn').on('click', function(e) {
1541                 e.preventDefault();
1542                 var license = content.one('.fp-setlicense select');
1543                 Y.Cookie.set('recentlicense', license.get('value'));
1544                 if (!content.one('.fp-file input').get('value')) {
1545                     scope.print_msg(M.str.repository.nofilesattached, 'error');
1546                     return false;
1547                 }
1548                 this.hide_header();
1549                 scope.request({
1550                         scope: scope,
1551                         action:'upload',
1552                         client_id: client_id,
1553                         params: {'savepath':scope.options.savepath},
1554                         repository_id: scope.active_repo.id,
1555                         form: {id: id, upload:true},
1556                         onerror: function(id, o, args) {
1557                             scope.create_upload_form(data);
1558                         },
1559                         callback: function(id, o, args) {
1560                             if (o.event == 'fileexists') {
1561                                 scope.create_upload_form(data);
1562                                 scope.process_existing_file(o);
1563                                 return;
1564                             }
1565                             if (scope.options.editor_target&&scope.options.env=='editor') {
1566                                 scope.options.editor_target.value=o.url;
1567                                 scope.options.editor_target.onchange();
1568                             }
1569                             scope.hide();
1570                             o.client_id = client_id;
1571                             var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
1572                             scope.options.formcallback.apply(formcallback_scope, [o]);
1573                         }
1574                 }, true);
1575             }, this);
1576         },
1577         /** setting handlers and labels for elements in toolbar. Called once during the initial render of filepicker */
1578         setup_toolbar: function() {
1579             var client_id = this.options.client_id;
1580             var toolbar = this.fpnode.one('.fp-toolbar');
1581             toolbar.one('.fp-tb-logout').one('a,button').on('click', function(e) {
1582                 e.preventDefault();
1583                 if (!this.active_repo.nologin) {
1584                     this.hide_header();
1585                     this.request({
1586                         action:'logout',
1587                         client_id: this.options.client_id,
1588                         repository_id: this.active_repo.id,
1589                         path:'',
1590                         callback: this.display_response
1591                     }, true);
1592                 }
1593             }, this);
1594             toolbar.one('.fp-tb-refresh').one('a,button').on('click', function(e) {
1595                 e.preventDefault();
1596                 if (!this.active_repo.norefresh) {
1597                     this.list();
1598                 }
1599             }, this);
1600             toolbar.one('.fp-tb-search form').
1601                 set('method', 'POST').
1602                 set('id', 'fp-tb-search-'+client_id).
1603                 on('submit', function(e) {
1604                     e.preventDefault();
1605                     if (!this.active_repo.nosearch) {
1606                         this.request({
1607                             scope: this,
1608                             action:'search',
1609                             client_id: this.options.client_id,
1610                             repository_id: this.active_repo.id,
1611                             form: {id: 'fp-tb-search-'+client_id, upload:false, useDisabled:true},
1612                             callback: this.display_response
1613                         }, true);
1614                     }
1615                 }, this);
1617             // it does not matter what kind of element is .fp-tb-manage, we create a dummy <a>
1618             // element and use it to open url on click event
1619             var managelnk = Y.Node.create('<a/>').
1620                 setAttrs({id:'fp-tb-manage-'+client_id+'-link', target:'_blank'}).
1621                 setStyle('display', 'none');
1622             toolbar.append(managelnk);
1623             toolbar.one('.fp-tb-manage').one('a,button').
1624                 on('click', function(e) {
1625                     e.preventDefault();
1626                     managelnk.simulate('click')
1627                 });
1629             // same with .fp-tb-help
1630             var helplnk = Y.Node.create('<a/>').
1631                 setAttrs({id:'fp-tb-help-'+client_id+'-link', target:'_blank'}).
1632                 setStyle('display', 'none');
1633             toolbar.append(helplnk);
1634             toolbar.one('.fp-tb-manage').one('a,button').
1635                 on('click', function(e) {
1636                     e.preventDefault();
1637                     helplnk.simulate('click')
1638                 });
1639         },
1640         hide_header: function() {
1641             if (this.fpnode.one('.fp-toolbar')) {
1642                 this.fpnode.one('.fp-toolbar').addClass('empty');
1643             }
1644             if (this.pathbar) {
1645                 this.pathbar.setContent('').addClass('empty');
1646             }
1647         },
1648         print_header: function() {
1649             var r = this.active_repo;
1650             var scope = this;
1651             var client_id = this.options.client_id;
1652             this.hide_header();
1653             this.print_path();
1654             var toolbar = this.fpnode.one('.fp-toolbar');
1655             if (!toolbar) { return; }
1657             var enable_tb_control = function(node, enabled) {
1658                 if (!node) { return; }
1659                 node.addClassIf('disabled', !enabled).addClassIf('enabled', enabled)
1660                 if (enabled) {
1661                     toolbar.removeClass('empty');
1662                 }
1663             }
1665             // TODO 'back' permanently disabled for now. Note, flickr_public uses 'Logout' for it!
1666             enable_tb_control(toolbar.one('.fp-tb-back'), false);
1668             // search form
1669             enable_tb_control(toolbar.one('.fp-tb-search'), !r.nosearch);
1670             if(!r.nosearch) {
1671                 var searchform = toolbar.one('.fp-tb-search form');
1672                 searchform.setContent('');
1673                 this.request({
1674                     scope: this,
1675                     action:'searchform',
1676                     repository_id: this.active_repo.id,
1677                     callback: function(id, obj, args) {
1678                         if (obj.repo_id == scope.active_repo.id && obj.form) {
1679                             // if we did not jump to another repository meanwhile
1680                             searchform.setContent(obj.form);
1681                         }
1682                     }
1683                 }, false);
1684             }
1686             // refresh button
1687             // weather we use cache for this instance, this button will reload listing anyway
1688             enable_tb_control(toolbar.one('.fp-tb-refresh'), !r.norefresh);
1690             // login button
1691             enable_tb_control(toolbar.one('.fp-tb-logout'), !r.nologin);
1692             if (!r.nologin) {
1693                 var label = r.logouttext ? r.logouttext : M.str.repository.logout;
1694                 toolbar.one('.fp-tb-logout').one('a,button').setContent(label)
1695             }
1697             // manage url
1698             enable_tb_control(toolbar.one('.fp-tb-manage'), r.manage);
1699             Y.one('#fp-tb-manage-'+client_id+'-link').set('href', r.manage);
1701             // help url
1702             enable_tb_control(toolbar.one('.fp-tb-help'), r.help);
1703             Y.one('#fp-tb-help-'+client_id+'-link').set('href', r.help);
1704         },
1705         print_path: function() {
1706             if (!this.pathbar) {
1707                 return;
1708             }
1709             this.pathbar.setContent('').addClass('empty');
1710             var p = this.filepath;
1711             if (p && p.length!=0 && this.viewmode != 2) {
1712                 for(var i = 0; i < p.length; i++) {
1713                     var el = this.pathnode.cloneNode(true);
1714                     this.pathbar.appendChild(el);
1715                     if (i == 0) {
1716                         el.addClass('first');
1717                     }
1718                     if (i == p.length-1) {
1719                         el.addClass('last');
1720                     }
1721                     if (i%2) {
1722                         el.addClass('even');
1723                     } else {
1724                         el.addClass('odd');
1725                     }
1726                     el.all('.fp-path-folder-name').setContent(p[i].name);
1727                     el.on('click',
1728                             function(e, path) {
1729                                 e.preventDefault();
1730                                 this.list({'path':path});
1731                             },
1732                         this, p[i].path);
1733                 }
1734                 this.pathbar.removeClass('empty');
1735             }
1736         },
1737         hide: function() {
1738             this.selectui.hide();
1739             if (this.process_dlg) {
1740                 this.process_dlg.hide();
1741             }
1742             if (this.msg_dlg) {
1743                 this.msg_dlg.hide();
1744             }
1745             this.mainui.hide();
1746         },
1747         show: function() {
1748             if (this.fpnode) {
1749                 this.hide();
1750                 this.mainui.show();
1751                 this.show_recent_repository();
1752             } else {
1753                 this.launch();
1754             }
1755         },
1756         launch: function() {
1757             this.render();
1758         },
1759         show_recent_repository: function() {
1760             this.hide_header();
1761             this.viewbar_set_enabled(false);
1762             var repository_id = Y.Cookie.get('recentrepository');
1763             this.viewmode = Y.Cookie.get('recentviewmode', Number);
1764             if (this.viewmode != 2 && this.viewmode != 3) {
1765                 this.viewmode = 1;
1766             }
1767             if (this.options.repositories[repository_id]) {
1768                 this.list({'repo_id':repository_id});
1769             }
1770         }
1771     });
1772     var loading = Y.one('#filepicker-loading-'+options.client_id);
1773     if (loading) {
1774         loading.setStyle('display', 'none');
1775     }
1776     M.core_filepicker.instances[options.client_id] = new FilePickerHelper(options);
1777 };