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