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