Merge branch 'MDL-40047-master' of git://github.com/ankitagarwal/moodle
[moodle.git] / repository / filepicker.js
blob0d6b9dd87f356c41b1163fc164ce132b0400c004
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     Y.YUI2.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 Y.YUI2.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 Y.YUI2.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                 Y.YUI2.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             // The unlimited value of areamaxbytes is -1, it is defined by FILE_AREA_MAX_BYTES_UNLIMITED.
556             params['areamaxbytes'] = this.options.areamaxbytes ? this.options.areamaxbytes : -1;
557             if (this.options.context && this.options.context.id) {
558                 params['ctx_id'] = this.options.context.id;
559             }
560             if (args['params']) {
561                 for (i in args['params']) {
562                     params[i] = args['params'][i];
563                 }
564             }
565             if (args.action == 'upload') {
566                 var list = [];
567                 for(var k in params) {
568                     var value = params[k];
569                     if(value instanceof Array) {
570                         for(var i in value) {
571                             list.push(k+'[]='+value[i]);
572                         }
573                     } else {
574                         list.push(k+'='+value);
575                     }
576                 }
577                 params = list.join('&');
578             } else {
579                 params = build_querystring(params);
580             }
581             var cfg = {
582                 method: 'POST',
583                 on: {
584                     complete: function(id,o,p) {
585                         if (!o) {
586                             // TODO
587                             alert('IO FATAL');
588                             return;
589                         }
590                         var data = null;
591                         try {
592                             data = Y.JSON.parse(o.responseText);
593                         } catch(e) {
594                             scope.print_msg(M.str.repository.invalidjson, 'error');
595                             scope.display_error(M.str.repository.invalidjson+'<pre>'+stripHTML(o.responseText)+'</pre>', 'invalidjson')
596                             return;
597                         }
598                         // error checking
599                         if (data && data.error) {
600                             scope.print_msg(data.error, 'error');
601                             if (args.onerror) {
602                                 args.onerror(id,data,p);
603                             } else {
604                                 this.fpnode.one('.fp-content').setContent('');
605                             }
606                             return;
607                         } else {
608                             if (data.msg) {
609                                 scope.print_msg(data.msg, 'info');
610                             }
611                             // cache result if applicable
612                             if (args.action != 'upload' && data.allowcaching) {
613                                 scope.cached_responses[params] = data;
614                             }
615                             // invoke callback
616                             args.callback(id,data,p);
617                         }
618                     }
619                 },
620                 arguments: {
621                     scope: scope
622                 },
623                 headers: {
624                     'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
625                 },
626                 data: params,
627                 context: this
628             };
629             if (args.form) {
630                 cfg.form = args.form;
631             }
632             // check if result of the same request has been already cached. If not, request it
633             // (never applicable in case of form submission and/or upload action):
634             if (!args.form && args.action != 'upload' && scope.cached_responses[params]) {
635                 args.callback(null, scope.cached_responses[params], {scope: scope})
636             } else {
637                 Y.io(api, cfg);
638                 if (redraw) {
639                     this.wait();
640                 }
641             }
642         },
643         /** displays the dialog and processes rename/overwrite if there is a file with the same name in the same filearea*/
644         process_existing_file: function(data) {
645             var scope = this;
646             var handleOverwrite = function(e) {
647                 // overwrite
648                 e.preventDefault();
649                 var data = this.process_dlg.dialogdata;
650                 var params = {}
651                 params['existingfilename'] = data.existingfile.filename;
652                 params['existingfilepath'] = data.existingfile.filepath;
653                 params['newfilename'] = data.newfile.filename;
654                 params['newfilepath'] = data.newfile.filepath;
655                 this.hide_header();
656                 this.request({
657                     'params': params,
658                     'scope': this,
659                     'action':'overwrite',
660                     'path': '',
661                     'client_id': this.options.client_id,
662                     'repository_id': this.active_repo.id,
663                     'callback': function(id, o, args) {
664                         scope.hide();
665                         if (scope.options.editor_target && scope.options.env == 'editor') {
666                             // editor needs to update url
667                             scope.options.editor_target.value = data.existingfile.url;
668                             scope.options.editor_target.onchange();
669                         }
670                         var fileinfo = {'client_id':scope.options.client_id,
671                                 'url':data.existingfile.url,
672                                 'file':data.existingfile.filename};
673                         var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
674                         scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
675                     }
676                 }, true);
677             }
678             var handleRename = function(e) {
679                 // inserts file with the new name
680                 e.preventDefault();
681                 var scope = this;
682                 var data = this.process_dlg.dialogdata;
683                 if (scope.options.editor_target && scope.options.env == 'editor') {
684                     scope.options.editor_target.value = data.newfile.url;
685                     scope.options.editor_target.onchange();
686                 }
687                 scope.hide();
688                 var formcallback_scope = scope.options.magicscope ? scope.options.magicscope : scope;
689                 var fileinfo = {'client_id':scope.options.client_id,
690                                 'url':data.newfile.url,
691                                 'file':data.newfile.filename};
692                 scope.options.formcallback.apply(formcallback_scope, [fileinfo]);
693             }
694             var handleCancel = function(e) {
695                 // Delete tmp file
696                 e.preventDefault();
697                 var params = {};
698                 params['newfilename'] = this.process_dlg.dialogdata.newfile.filename;
699                 params['newfilepath'] = this.process_dlg.dialogdata.newfile.filepath;
700                 this.request({
701                     'params': params,
702                     'scope': this,
703                     'action':'deletetmpfile',
704                     'path': '',
705                     'client_id': this.options.client_id,
706                     'repository_id': this.active_repo.id,
707                     'callback': function(id, o, args) {
708                         // let it be in background, from user point of view nothing is happenning
709                     }
710                 }, false);
711                 this.process_dlg.hide();
712                 this.selectui.hide();
713             }
714             if (!this.process_dlg) {
715                 this.process_dlg_node = Y.Node.createWithFilesSkin(M.core_filepicker.templates.processexistingfile);
716                 var node = this.process_dlg_node;
717                 node.generateID();
718                 this.process_dlg = new M.core.dialogue({
719                     draggable    : true,
720                     bodyContent  : node,
721                     headerContent: M.str.repository.fileexistsdialogheader,
722                     centered     : true,
723                     modal        : true,
724                     visible      : false,
725                     zIndex       : this.options.zIndex
726                 });
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 M.core.dialogue({
760                     draggable    : true,
761                     bodyContent  : this.msg_dlg_node,
762                     centered     : true,
763                     modal        : true,
764                     visible      : false,
765                     zIndex       : this.options.zIndex
766                 });
767                 this.msg_dlg_node.one('.fp-msg-butok').on('click', function(e) {
768                     e.preventDefault();
769                     this.msg_dlg.hide();
770                 }, this);
771             }
773             this.msg_dlg.set('headerContent', header);
774             this.msg_dlg_node.removeClass('fp-msg-info').removeClass('fp-msg-error').addClass('fp-msg-'+type)
775             this.msg_dlg_node.one('.fp-msg-text').setContent(Y.Escape.html(msg));
776             this.msg_dlg.show();
777         },
778         view_files: function(appenditems) {
779             this.viewbar_set_enabled(true);
780             this.print_path();
781             /*if ((appenditems == null) && (!this.filelist || !this.filelist.length) && !this.active_repo.hasmorepages) {
782              // TODO do it via classes and adjust for each view mode!
783                 // If there are no items and no next page, just display status message and quit
784                 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
785                 return;
786             }*/
787             if (this.viewmode == 2) {
788                 this.view_as_list(appenditems);
789             } else if (this.viewmode == 3) {
790                 this.view_as_table(appenditems);
791             } else {
792                 this.view_as_icons(appenditems);
793             }
794             this.fpnode.one('.fp-content').setAttribute('tabindex', '0');
795             // Temporary fix for IE8 until MDL-41229 is integrated.
796             // The role dialog is needed for screen reader to read
797             // the filepicker's content (MDL-41232).
798             this.fpnode.one('.fp-content').setAttribute('role', 'dialog');
799             this.fpnode.one('.fp-content').setAttribute('aria-live', 'assertive');
800             // End of temporary fix.
801             this.fpnode.one('.fp-content').focus();
802             // display/hide the link for requesting next page
803             if (!appenditems && this.active_repo.hasmorepages) {
804                 if (!this.fpnode.one('.fp-content .fp-nextpage')) {
805                     this.fpnode.one('.fp-content').append(M.core_filepicker.templates.nextpage);
806                 }
807                 this.fpnode.one('.fp-content .fp-nextpage').one('a,button').on('click', function(e) {
808                     e.preventDefault();
809                     this.fpnode.one('.fp-content .fp-nextpage').addClass('loading');
810                     this.request_next_page();
811                 }, this);
812             }
813             if (!this.active_repo.hasmorepages && this.fpnode.one('.fp-content .fp-nextpage')) {
814                 this.fpnode.one('.fp-content .fp-nextpage').remove();
815             }
816             if (this.fpnode.one('.fp-content .fp-nextpage')) {
817                 this.fpnode.one('.fp-content .fp-nextpage').removeClass('loading');
818             }
819             this.content_scrolled();
820         },
821         content_scrolled: function(e) {
822             setTimeout(Y.bind(function() {
823                 if (this.processingimages) {
824                     return;
825                 }
826                 this.processingimages = true;
827                 var scope = this,
828                     fpcontent = this.fpnode.one('.fp-content'),
829                     fpcontenty = fpcontent.getY(),
830                     fpcontentheight = fpcontent.getStylePx('height'),
831                     nextpage = fpcontent.one('.fp-nextpage'),
832                     is_node_visible = function(node) {
833                         var offset = node.getY()-fpcontenty;
834                         if (offset <= fpcontentheight && (offset >=0 || offset+node.getStylePx('height')>=0)) {
835                             return true;
836                         }
837                         return false;
838                     };
839                 // automatically load next page when 'more' link becomes visible
840                 if (nextpage && !nextpage.hasClass('loading') && is_node_visible(nextpage)) {
841                     nextpage.one('a,button').simulate('click');
842                 }
843                 // replace src for visible images that need to be lazy-loaded
844                 if (scope.lazyloading) {
845                     fpcontent.all('img').each( function(node) {
846                         if (node.get('id') && scope.lazyloading[node.get('id')] && is_node_visible(node)) {
847                             node.setImgRealSrc(scope.lazyloading);
848                         }
849                     });
850                 }
851                 this.processingimages = false;
852             }, this), 200)
853         },
854         treeview_dynload: function(node, cb) {
855             var retrieved_children = {};
856             if (node.children) {
857                 for (var i in node.children) {
858                     retrieved_children[node.children[i].path] = node.children[i];
859                 }
860             }
861             this.request({
862                 action:'list',
863                 client_id: this.options.client_id,
864                 repository_id: this.active_repo.id,
865                 path:node.path?node.path:'',
866                 page:node.page?args.page:'',
867                 scope:this,
868                 callback: function(id, obj, args) {
869                     var list = obj.list;
870                     var scope = args.scope;
871                     // check that user did not leave the view mode before recieving this response
872                     if (!(scope.active_repo.id == obj.repo_id && scope.viewmode == 2 && node && node.getChildrenEl())) {
873                         return;
874                     }
875                     if (cb != null) { // (in manual mode do not update current path)
876                         scope.viewbar_set_enabled(true);
877                         scope.parse_repository_options(obj);
878                     }
879                     node.highlight(false);
880                     node.origlist = obj.list ? obj.list : null;
881                     node.origpath = obj.path ? obj.path : null;
882                     node.children = [];
883                     for(k in list) {
884                         if (list[k].children && retrieved_children[list[k].path]) {
885                             // if this child is a folder and has already been retrieved
886                             node.children[node.children.length] = retrieved_children[list[k].path];
887                         } else {
888                             // append new file to the list
889                             scope.view_as_list([list[k]]);
890                         }
891                     }
892                     if (cb == null) {
893                         node.refresh();
894                     } else {
895                         // invoke callback requested by TreeView component
896                         cb();
897                     }
898                     scope.content_scrolled();
899                 }
900             }, false);
901         },
902        classnamecallback : function(node) {
903             var classname = '';
904             if (node.children) {
905                 classname = classname + ' fp-folder';
906             }
907             if (node.isref) {
908                 classname = classname + ' fp-isreference';
909             }
910             if (node.refcount) {
911                 classname = classname + ' fp-hasreferences';
912             }
913             if (node.originalmissing) {
914                 classname = classname + ' fp-originalmissing';
915             }
916             return Y.Lang.trim(classname);
917         },
918         /** displays list of files in tree (list) view mode. If param appenditems is specified,
919          * appends those items to the end of the list. Otherwise (default behaviour)
920          * clears the contents and displays the items from this.filelist */
921         view_as_list: function(appenditems) {
922             var list = (appenditems != null) ? appenditems : this.filelist;
923             this.viewmode = 2;
924             if (!this.filelist || this.filelist.length==0 && (!this.filepath || !this.filepath.length)) {
925                 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
926                 return;
927             }
929             var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
930             var options = {
931                 viewmode : this.viewmode,
932                 appendonly : (appenditems != null),
933                 filenode : element_template,
934                 callbackcontext : this,
935                 callback : function(e, node) {
936                     // TODO MDL-32736 e is not an event here but an object with properties 'event' and 'node'
937                     if (!node.children) {
938                         if (e.node.parent && e.node.parent.origpath) {
939                             // set the current path
940                             this.filepath = e.node.parent.origpath;
941                             this.filelist = e.node.parent.origlist;
942                             this.print_path();
943                         }
944                         this.select_file(node);
945                     } else {
946                         // save current path and filelist (in case we want to jump to other viewmode)
947                         this.filepath = e.node.origpath;
948                         this.filelist = e.node.origlist;
949                         this.currentpath = e.node.path;
950                         this.print_path();
951                         this.content_scrolled();
952                     }
953                 },
954                 classnamecallback : this.classnamecallback,
955                 dynload : this.active_repo.dynload,
956                 filepath : this.filepath,
957                 treeview_dynload : this.treeview_dynload
958             };
959             this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
960         },
961         /** displays list of files in icon view mode. If param appenditems is specified,
962          * appends those items to the end of the list. Otherwise (default behaviour)
963          * clears the contents and displays the items from this.filelist */
964         view_as_icons: function(appenditems) {
965             this.viewmode = 1;
966             var list = (appenditems != null) ? appenditems : this.filelist;
967             var element_template = Y.Node.create(M.core_filepicker.templates.iconfilename);
968             if ((appenditems == null) && (!this.filelist || !this.filelist.length)) {
969                 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
970                 return;
971             }
972             var options = {
973                 viewmode : this.viewmode,
974                 appendonly : (appenditems != null),
975                 filenode : element_template,
976                 callbackcontext : this,
977                 callback : function(e, node) {
978                     if (e.preventDefault) {
979                         e.preventDefault();
980                     }
981                     if(node.children) {
982                         if (this.active_repo.dynload) {
983                             this.list({'path':node.path});
984                         } else {
985                             this.filelist = node.children;
986                             this.view_files();
987                         }
988                     } else {
989                         this.select_file(node);
990                     }
991                 },
992                 classnamecallback : this.classnamecallback
993             };
994             this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
995         },
996         /** displays list of files in table view mode. If param appenditems is specified,
997          * appends those items to the end of the list. Otherwise (default behaviour)
998          * clears the contents and displays the items from this.filelist */
999         view_as_table: function(appenditems) {
1000             this.viewmode = 3;
1001             var list = (appenditems != null) ? appenditems : this.filelist;
1002             if (!appenditems && (!this.filelist || this.filelist.length==0) && !this.active_repo.hasmorepages) {
1003                 this.display_error(M.str.repository.nofilesavailable, 'nofilesavailable');
1004                 return;
1005             }
1006             var element_template = Y.Node.create(M.core_filepicker.templates.listfilename);
1007             var options = {
1008                 viewmode : this.viewmode,
1009                 appendonly : (appenditems != null),
1010                 filenode : element_template,
1011                 callbackcontext : this,
1012                 sortable : !this.active_repo.hasmorepages,
1013                 callback : function(e, node) {
1014                     if (e.preventDefault) {e.preventDefault();}
1015                     if (node.children) {
1016                         if (this.active_repo.dynload) {
1017                             this.list({'path':node.path});
1018                         } else {
1019                             this.filelist = node.children;
1020                             this.view_files();
1021                         }
1022                     } else {
1023                         this.select_file(node);
1024                     }
1025                 },
1026                 classnamecallback : this.classnamecallback
1027             };
1028             this.fpnode.one('.fp-content').fp_display_filelist(options, list, this.lazyloading);
1029         },
1030         /** If more than one page available, requests and displays the files from the next page */
1031         request_next_page: function() {
1032             if (!this.active_repo.hasmorepages || this.active_repo.nextpagerequested) {
1033                 // nothing to load
1034                 return;
1035             }
1036             this.active_repo.nextpagerequested = true;
1037             var nextpage = this.active_repo.page+1;
1038             var args = {
1039                 page: nextpage,
1040                 repo_id: this.active_repo.id
1041             };
1042             var action = this.active_repo.issearchresult ? 'search' : 'list';
1043             this.request({
1044                 path: this.currentpath,
1045                 scope: this,
1046                 action: action,
1047                 client_id: this.options.client_id,
1048                 repository_id: args.repo_id,
1049                 params: args,
1050                 callback: function(id, obj, args) {
1051                     var scope = args.scope;
1052                     // Check that we are still in the same repository and are expecting this page. We have no way
1053                     // to compare the requested page and the one returned, so we assume that if the last chunk
1054                     // of the breadcrumb is similar, then we probably are on the same page.
1055                     var samepage = true;
1056                     if (obj.path && scope.filepath) {
1057                         var pathbefore = scope.filepath[scope.filepath.length-1];
1058                         var pathafter = obj.path[obj.path.length-1];
1059                         if (pathbefore.path != pathafter.path) {
1060                             samepage = false;
1061                         }
1062                     }
1063                     if (scope.active_repo.hasmorepages && obj.list && obj.page &&
1064                             obj.repo_id == scope.active_repo.id &&
1065                             obj.page == scope.active_repo.page+1 && samepage) {
1066                         scope.parse_repository_options(obj, true);
1067                         scope.view_files(obj.list)
1068                     }
1069                 }
1070             }, false);
1071         },
1072         select_file: function(args) {
1073             var argstitle = args.title;
1074             // Limit the string length so it fits nicely on mobile devices
1075             var titlelength = 30;
1076             if (argstitle.length > titlelength) {
1077                 argstitle = argstitle.substring(0, titlelength) + '...';
1078             }
1079             Y.one('#fp-file_label_'+this.options.client_id).setContent(Y.Escape.html(M.str.repository.select+' '+argstitle));
1080             this.selectui.show();
1081             Y.one('#'+this.selectnode.get('id')).focus();
1082             var client_id = this.options.client_id;
1083             var selectnode = this.selectnode;
1084             var return_types = this.options.repositories[this.active_repo.id].return_types;
1085             selectnode.removeClass('loading');
1086             selectnode.one('.fp-saveas input').set('value', args.title);
1088             var imgnode = Y.Node.create('<img/>').
1089                 set('src', args.realthumbnail ? args.realthumbnail : args.thumbnail).
1090                 setStyle('maxHeight', ''+(args.thumbnail_height ? args.thumbnail_height : 90)+'px').
1091                 setStyle('maxWidth', ''+(args.thumbnail_width ? args.thumbnail_width : 90)+'px');
1092             selectnode.one('.fp-thumbnail').setContent('').appendChild(imgnode);
1094             // filelink is the array of file-link-types available for this repository in this env
1095             var filelinktypes = [2/*FILE_INTERNAL*/,1/*FILE_EXTERNAL*/,4/*FILE_REFERENCE*/];
1096             var filelink = {}, firstfilelink = null, filelinkcount = 0;
1097             for (var i in filelinktypes) {
1098                 var allowed = (return_types & filelinktypes[i]) &&
1099                     (this.options.return_types & filelinktypes[i]);
1100                 if (filelinktypes[i] == 1/*FILE_EXTERNAL*/ && !this.options.externallink && this.options.env == 'editor') {
1101                     // special configuration setting 'repositoryallowexternallinks' may prevent
1102                     // using external links in editor environment
1103                     allowed = false;
1104                 }
1105                 filelink[filelinktypes[i]] = allowed;
1106                 firstfilelink = (firstfilelink==null && allowed) ? filelinktypes[i] : firstfilelink;
1107                 filelinkcount += allowed ? 1 : 0;
1108             }
1109             // make radio buttons enabled if this file-link-type is available and only if there are more than one file-link-type option
1110             // check the first available file-link-type option
1111             for (var linktype in filelink) {
1112                 var el = selectnode.one('.fp-linktype-'+linktype);
1113                 el.addClassIf('uneditable', !(filelink[linktype] && filelinkcount>1));
1114                 el.one('input').set('disabled', (filelink[linktype] && filelinkcount>1) ? '' : 'disabled').
1115                     set('checked', (firstfilelink == linktype) ? 'checked' : '').simulate('change')
1116             }
1118             // TODO MDL-32532: attributes 'hasauthor' and 'haslicense' need to be obsolete,
1119             selectnode.one('.fp-setauthor input').set('value', args.author ? args.author : this.options.author);
1120             this.set_selected_license(selectnode.one('.fp-setlicense'), args.license);
1121             selectnode.one('form #filesource-'+client_id).set('value', args.source);
1123             // display static information about a file (when known)
1124             var attrs = ['datemodified','datecreated','size','license','author','dimensions'];
1125             for (var i in attrs) {
1126                 if (selectnode.one('.fp-'+attrs[i])) {
1127                     var value = (args[attrs[i]+'_f']) ? args[attrs[i]+'_f'] : (args[attrs[i]] ? args[attrs[i]] : '');
1128                     selectnode.one('.fp-'+attrs[i]).addClassIf('fp-unknown', ''+value == '')
1129                         .one('.fp-value').setContent(Y.Escape.html(value));
1130                 }
1131             }
1132         },
1133         setup_select_file: function() {
1134             var client_id = this.options.client_id;
1135             var selectnode = this.selectnode;
1136             var getfile = selectnode.one('.fp-select-confirm');
1137             // bind labels with corresponding inputs
1138             selectnode.all('.fp-saveas,.fp-linktype-2,.fp-linktype-1,.fp-linktype-4,.fp-setauthor,.fp-setlicense').each(function (node) {
1139                 node.all('label').set('for', node.one('input,select').generateID());
1140             });
1141             selectnode.one('.fp-linktype-2 input').setAttrs({value: 2, name: 'linktype'});
1142             selectnode.one('.fp-linktype-1 input').setAttrs({value: 1, name: 'linktype'});
1143             selectnode.one('.fp-linktype-4 input').setAttrs({value: 4, name: 'linktype'});
1144             var changelinktype = function(e) {
1145                 if (e.currentTarget.get('checked')) {
1146                     var allowinputs = e.currentTarget.get('value') != 1/*FILE_EXTERNAL*/;
1147                     selectnode.all('.fp-setauthor,.fp-setlicense,.fp-saveas').each(function(node){
1148                         node.addClassIf('uneditable', !allowinputs);
1149                         node.all('input,select').set('disabled', allowinputs?'':'disabled');
1150                     });
1151                 }
1152             };
1153             selectnode.all('.fp-linktype-2,.fp-linktype-1,.fp-linktype-4').each(function (node) {
1154                 node.one('input').on('change', changelinktype, this);
1155             });
1156             this.populate_licenses_select(selectnode.one('.fp-setlicense select'));
1157             // register event on clicking submit button
1158             getfile.on('click', function(e) {
1159                 e.preventDefault();
1160                 var client_id = this.options.client_id;
1161                 var scope = this;
1162                 var repository_id = this.active_repo.id;
1163                 var title = selectnode.one('.fp-saveas input').get('value');
1164                 var filesource = selectnode.one('form #filesource-'+client_id).get('value');
1165                 var params = {'title':title, 'source':filesource, 'savepath': this.options.savepath};
1166                 var license = selectnode.one('.fp-setlicense select');
1167                 if (license) {
1168                     params['license'] = license.get('value');
1169                     var origlicense = selectnode.one('.fp-license .fp-value');
1170                     if (origlicense) {
1171                         origlicense = origlicense.getContent();
1172                     }
1173                     this.set_preference('recentlicense', license.get('value'));
1174                 }
1175                 params['author'] = selectnode.one('.fp-setauthor input').get('value');
1177                 var return_types = this.options.repositories[this.active_repo.id].return_types;
1178                 if (this.options.env == 'editor') {
1179                     // in editor, images are stored in '/' only
1180                     params.savepath = '/';
1181                 }
1182                 if ((this.options.externallink || this.options.env != 'editor') &&
1183                             (return_types & 1/*FILE_EXTERNAL*/) &&
1184                             (this.options.return_types & 1/*FILE_EXTERNAL*/) &&
1185                             selectnode.one('.fp-linktype-1 input').get('checked')) {
1186                     params['linkexternal'] = 'yes';
1187                 } else if ((return_types & 4/*FILE_REFERENCE*/) &&
1188                         (this.options.return_types & 4/*FILE_REFERENCE*/) &&
1189                         selectnode.one('.fp-linktype-4 input').get('checked')) {
1190                     params['usefilereference'] = '1';
1191                 }
1193                 selectnode.addClass('loading');
1194                 this.request({
1195                     action:'download',
1196                     client_id: client_id,
1197                     repository_id: repository_id,
1198                     'params': params,
1199                     onerror: function(id, obj, args) {
1200                         selectnode.removeClass('loading');
1201                         scope.selectui.hide();
1202                     },
1203                     callback: function(id, obj, args) {
1204                         selectnode.removeClass('loading');
1205                         if (obj.event == 'fileexists') {
1206                             scope.process_existing_file(obj);
1207                             return;
1208                         }
1209                         if (scope.options.editor_target && scope.options.env=='editor') {
1210                             scope.options.editor_target.value=obj.url;
1211                             scope.options.editor_target.onchange();
1212                         }
1213                         scope.hide();
1214                         obj.client_id = client_id;
1215                         var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
1216                         scope.options.formcallback.apply(formcallback_scope, [obj]);
1217                     }
1218                 }, false);
1219             }, this);
1220             var elform = selectnode.one('form');
1221             elform.appendChild(Y.Node.create('<input/>').
1222                 setAttrs({type:'hidden',id:'filesource-'+client_id}));
1223             elform.on('keydown', function(e) {
1224                 if (e.keyCode == 13) {
1225                     getfile.simulate('click');
1226                     e.preventDefault();
1227                 }
1228             }, this);
1229             var cancel = selectnode.one('.fp-select-cancel');
1230             cancel.on('click', function(e) {
1231                 e.preventDefault();
1232                 this.selectui.hide();
1233             }, this);
1234         },
1235         wait: function() {
1236             // First check there isn't already an interval in play, and if there is kill it now.
1237             if (this.waitinterval != null) {
1238                 clearInterval(this.waitinterval);
1239             }
1240             // Prepare the root node we will set content for and the loading template we want to display as a YUI node.
1241             var root = this.fpnode.one('.fp-content');
1242             var content = Y.Node.create(M.core_filepicker.templates.loading).addClass('fp-content-hidden').setStyle('opacity', 0);
1243             var count = 0;
1244             // Initiate an interval, we will have a count which will increment every 100 milliseconds.
1245             // Count 0 - the loading icon will have visibility set to hidden (invisible) and have an opacity of 0 (invisible also)
1246             // Count 5 - the visiblity will be switched to visible but opacity will still be at 0 (inivisible)
1247             // Counts 6 - 15 opacity will be increased by 0.1 making the loading icon visible over the period of a second
1248             // Count 16 - The interval will be cancelled.
1249             var interval = setInterval(function(){
1250                 if (!content || !root.contains(content) || count >= 15) {
1251                     clearInterval(interval);
1252                     return true;
1253                 }
1254                 if (count == 5) {
1255                     content.removeClass('fp-content-hidden');
1256                 } else if (count > 5) {
1257                     var opacity = parseFloat(content.getStyle('opacity'));
1258                     content.setStyle('opacity', opacity + 0.1);
1259                 }
1260                 count++;
1261                 return false;
1262             }, 100);
1263             // Store the wait interval so that we can check it in the future.
1264             this.waitinterval = interval;
1265             // Set the content to the loading template.
1266             root.setContent(content);
1267         },
1268         viewbar_set_enabled: function(mode) {
1269             var viewbar = this.fpnode.one('.fp-viewbar')
1270             if (viewbar) {
1271                 if (mode) {
1272                     viewbar.addClass('enabled').removeClass('disabled')
1273                 } else {
1274                     viewbar.removeClass('enabled').addClass('disabled')
1275                 }
1276             }
1277             this.fpnode.all('.fp-vb-icons,.fp-vb-tree,.fp-vb-details').removeClass('checked')
1278             var modes = {1:'icons', 2:'tree', 3:'details'};
1279             this.fpnode.all('.fp-vb-'+modes[this.viewmode]).addClass('checked');
1280         },
1281         viewbar_clicked: function(e) {
1282             e.preventDefault();
1283             var viewbar = this.fpnode.one('.fp-viewbar')
1284             if (!viewbar || !viewbar.hasClass('disabled')) {
1285                 if (e.currentTarget.hasClass('fp-vb-tree')) {
1286                     this.viewmode = 2;
1287                 } else if (e.currentTarget.hasClass('fp-vb-details')) {
1288                     this.viewmode = 3;
1289                 } else {
1290                     this.viewmode = 1;
1291                 }
1292                 this.viewbar_set_enabled(true)
1293                 this.view_files();
1294                 this.set_preference('recentviewmode', this.viewmode);
1295             }
1296         },
1297         render: function() {
1298             var client_id = this.options.client_id;
1299             var fpid = "filepicker-"+ client_id;
1300             var labelid = 'fp-dialog-label_'+ client_id;
1301             this.fpnode = Y.Node.createWithFilesSkin(M.core_filepicker.templates.generallayout).
1302                 set('id', 'filepicker-'+client_id).set('aria-labelledby', labelid);
1303             this.mainui = new M.core.dialogue({
1304                 extraClasses : ['filepicker'],
1305                 draggable    : true,
1306                 bodyContent  : this.fpnode,
1307                 headerContent: '<span id="'+ labelid +'">'+ M.str.repository.filepicker +'</span>',
1308                 centered     : true,
1309                 modal        : true,
1310                 visible      : false,
1311                 width        : '873px',
1312                 responsiveWidth : 873,
1313                 height       : '558px',
1314                 zIndex       : this.options.zIndex
1315             });
1317             // create panel for selecting a file (initially hidden)
1318             this.selectnode = Y.Node.createWithFilesSkin(M.core_filepicker.templates.selectlayout).
1319                 set('id', 'filepicker-select-'+client_id).
1320                 set('aria-live', 'assertive').
1321                 set('role', 'dialog');
1323             var fplabel = 'fp-file_label_'+ client_id;
1324             this.selectui = new M.core.dialogue({
1325                 headerContent: '<span id="' + fplabel +'">'+M.str.repository.select+'</span>',
1326                 draggable    : true,
1327                 width        : '450px',
1328                 bodyContent  : this.selectnode,
1329                 centered     : true,
1330                 modal        : true,
1331                 visible      : false,
1332                 zIndex       : this.options.zIndex
1333             });
1334             Y.one('#'+this.selectnode.get('id')).setAttribute('aria-labelledby', fplabel);
1335             // event handler for lazy loading of thumbnails and next page
1336             this.fpnode.one('.fp-content').on(['scroll','resize'], this.content_scrolled, this);
1337             // save template for one path element and location of path bar
1338             if (this.fpnode.one('.fp-path-folder')) {
1339                 this.pathnode = this.fpnode.one('.fp-path-folder');
1340                 this.pathbar = this.pathnode.get('parentNode');
1341                 this.pathbar.removeChild(this.pathnode);
1342             }
1343             // assign callbacks for view mode switch buttons
1344             this.fpnode.one('.fp-vb-icons').on('click', this.viewbar_clicked, this);
1345             this.fpnode.one('.fp-vb-tree').on('click', this.viewbar_clicked, this);
1346             this.fpnode.one('.fp-vb-details').on('click', this.viewbar_clicked, this);
1348             // assign callbacks for toolbar links
1349             this.setup_toolbar();
1350             this.setup_select_file();
1351             this.hide_header();
1353             // processing repository listing
1354             // Resort the repositories by sortorder
1355             var sorted_repositories = [];
1356             for (var i in this.options.repositories) {
1357                 sorted_repositories[i] = this.options.repositories[i];
1358             }
1359             sorted_repositories.sort(function(a,b){return a.sortorder-b.sortorder});
1360             // extract one repository template and repeat it for all repositories available,
1361             // set name and icon and assign callbacks
1362             var reponode = this.fpnode.one('.fp-repo');
1363             if (reponode) {
1364                 var list = reponode.get('parentNode');
1365                 list.removeChild(reponode);
1366                 for (i in sorted_repositories) {
1367                     var repository = sorted_repositories[i];
1368                     var node = reponode.cloneNode(true);
1369                     list.appendChild(node);
1370                     node.
1371                         set('id', 'fp-repo-'+client_id+'-'+repository.id).
1372                         on('click', function(e, repository_id) {
1373                             e.preventDefault();
1374                             this.set_preference('recentrepository', repository_id);
1375                             this.hide_header();
1376                             this.list({'repo_id':repository_id});
1377                         }, this /*handler running scope*/, repository.id/*second argument of handler*/);
1378                     node.one('.fp-repo-name').setContent(Y.Escape.html(repository.name));
1379                     node.one('.fp-repo-icon').set('src', repository.icon);
1380                     if (i==0) {
1381                         node.addClass('first');
1382                     }
1383                     if (i==sorted_repositories.length-1) {
1384                         node.addClass('last');
1385                     }
1386                     if (i%2) {
1387                         node.addClass('even');
1388                     } else {
1389                         node.addClass('odd');
1390                     }
1391                 }
1392             }
1393             // display error if no repositories found
1394             if (sorted_repositories.length==0) {
1395                 this.display_error(M.str.repository.norepositoriesavailable, 'norepositoriesavailable')
1396             }
1397             // display repository that was used last time
1398             this.mainui.show();
1399             this.show_recent_repository();
1400         },
1401         parse_repository_options: function(data, appendtolist) {
1402             if (appendtolist) {
1403                 if (data.list) {
1404                     if (!this.filelist) {
1405                         this.filelist = [];
1406                     }
1407                     for (var i in data.list) {
1408                         this.filelist[this.filelist.length] = data.list[i];
1409                     }
1410                 }
1411             } else {
1412                 this.filelist = data.list?data.list:null;
1413                 this.lazyloading = {};
1414             }
1415             this.filepath = data.path?data.path:null;
1416             this.objecttag = data.object?data.object:null;
1417             this.active_repo = {};
1418             this.active_repo.issearchresult = data.issearchresult ? true : false;
1419             this.active_repo.dynload = data.dynload?data.dynload:false;
1420             this.active_repo.pages = Number(data.pages?data.pages:null);
1421             this.active_repo.page = Number(data.page?data.page:null);
1422             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))
1423             this.active_repo.id = data.repo_id?data.repo_id:null;
1424             this.active_repo.nosearch = (data.login || data.nosearch); // this is either login form or 'nosearch' attribute set
1425             this.active_repo.norefresh = (data.login || data.norefresh); // this is either login form or 'norefresh' attribute set
1426             this.active_repo.nologin = (data.login || data.nologin); // this is either login form or 'nologin' attribute is set
1427             this.active_repo.logouttext = data.logouttext?data.logouttext:null;
1428             this.active_repo.logouturl = (data.logouturl || '');
1429             this.active_repo.message = (data.message || '');
1430             this.active_repo.help = data.help?data.help:null;
1431             this.active_repo.manage = data.manage?data.manage:null;
1432             this.print_header();
1433         },
1434         print_login: function(data) {
1435             this.parse_repository_options(data);
1436             var client_id = this.options.client_id;
1437             var repository_id = data.repo_id;
1438             var l = this.logindata = data.login;
1439             var loginurl = '';
1440             var action = data['login_btn_action'] ? data['login_btn_action'] : 'login';
1441             var form_id = 'fp-form-'+client_id;
1443             var loginform_node = Y.Node.create(M.core_filepicker.templates.loginform);
1444             loginform_node.one('form').set('id', form_id);
1445             this.fpnode.one('.fp-content').setContent('').appendChild(loginform_node);
1446             var templates = {
1447                 'popup' : loginform_node.one('.fp-login-popup'),
1448                 'textarea' : loginform_node.one('.fp-login-textarea'),
1449                 'select' : loginform_node.one('.fp-login-select'),
1450                 'text' : loginform_node.one('.fp-login-text'),
1451                 'radio' : loginform_node.one('.fp-login-radiogroup'),
1452                 'checkbox' : loginform_node.one('.fp-login-checkbox'),
1453                 'input' : loginform_node.one('.fp-login-input')
1454             };
1455             var container;
1456             for (var i in templates) {
1457                 if (templates[i]) {
1458                     container = templates[i].get('parentNode');
1459                     container.removeChild(templates[i]);
1460                 }
1461             }
1463             for(var k in l) {
1464                 if (templates[l[k].type]) {
1465                     var node = templates[l[k].type].cloneNode(true);
1466                 } else {
1467                     node = templates['input'].cloneNode(true);
1468                 }
1469                 if (l[k].type == 'popup') {
1470                     // submit button
1471                     loginurl = l[k].url;
1472                     var popupbutton = node.one('button');
1473                     popupbutton.on('click', function(e){
1474                         M.core_filepicker.active_filepicker = this;
1475                         window.open(loginurl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1476                         e.preventDefault();
1477                     }, this);
1478                     loginform_node.one('form').on('keydown', function(e) {
1479                         if (e.keyCode == 13) {
1480                             popupbutton.simulate('click');
1481                             e.preventDefault();
1482                         }
1483                     }, this);
1484                     loginform_node.all('.fp-login-submit').remove();
1485                     action = 'popup';
1486                 } else if(l[k].type=='textarea') {
1487                     // textarea element
1488                     if (node.one('label')) {
1489                         node.one('label').set('for', l[k].id).setContent(l[k].label);
1490                     }
1491                     node.one('textarea').setAttrs({id:l[k].id, name:l[k].name});
1492                 } else if(l[k].type=='select') {
1493                     // select element
1494                     if (node.one('label')) {
1495                         node.one('label').set('for', l[k].id).setContent(l[k].label);
1496                     }
1497                     node.one('select').setAttrs({id:l[k].id, name:l[k].name}).setContent('');
1498                     for (i in l[k].options) {
1499                         node.one('select').appendChild(
1500                             Y.Node.create('<option/>').
1501                                 set('value', l[k].options[i].value).
1502                                 setContent(l[k].options[i].label));
1503                     }
1504                 } else if(l[k].type=='radio') {
1505                     // radio input element
1506                     node.all('label').setContent(l[k].label);
1507                     var list = l[k].value.split('|');
1508                     var labels = l[k].value_label.split('|');
1509                     var radionode = null;
1510                     for(var item in list) {
1511                         if (radionode == null) {
1512                             radionode = node.one('.fp-login-radio');
1513                             radionode.one('input').set('checked', 'checked');
1514                         } else {
1515                             var x = radionode.cloneNode(true);
1516                             radionode.insert(x, 'after');
1517                             radionode = x;
1518                             radionode.one('input').set('checked', '');
1519                         }
1520                         radionode.one('input').setAttrs({id:''+l[k].id+item, name:l[k].name,
1521                             type:l[k].type, value:list[item]});
1522                         radionode.all('label').setContent(labels[item]).set('for', ''+l[k].id+item)
1523                     }
1524                     if (radionode == null) {
1525                         node.one('.fp-login-radio').remove();
1526                     }
1527                 } else {
1528                     // input element
1529                     if (node.one('label')) { node.one('label').set('for', l[k].id).setContent(l[k].label) }
1530                     node.one('input').
1531                         set('type', l[k].type).
1532                         set('id', l[k].id).
1533                         set('name', l[k].name).
1534                         set('value', l[k].value?l[k].value:'')
1535                 }
1536                 container.appendChild(node);
1537             }
1538             // custom label text for submit button
1539             if (data['login_btn_label']) {
1540                 loginform_node.all('.fp-login-submit').setContent(data['login_btn_label'])
1541             }
1542             // register button action for login and search
1543             if (action == 'login' || action == 'search') {
1544                 loginform_node.one('.fp-login-submit').on('click', function(e){
1545                     e.preventDefault();
1546                     this.hide_header();
1547                     this.request({
1548                         'scope': this,
1549                         'action':(action == 'search') ? 'search' : 'signin',
1550                         'path': '',
1551                         'client_id': client_id,
1552                         'repository_id': repository_id,
1553                         'form': {id:form_id, upload:false, useDisabled:true},
1554                         'callback': this.display_response
1555                     }, true);
1556                 }, this);
1557             }
1558             // if 'Enter' is pressed in the form, simulate the button click
1559             if (loginform_node.one('.fp-login-submit')) {
1560                 loginform_node.one('form').on('keydown', function(e) {
1561                     if (e.keyCode == 13) {
1562                         loginform_node.one('.fp-login-submit').simulate('click')
1563                         e.preventDefault();
1564                     }
1565                 }, this);
1566             }
1567         },
1568         display_response: function(id, obj, args) {
1569             var scope = args.scope;
1570             // highlight the current repository in repositories list
1571             scope.fpnode.all('.fp-repo.active').removeClass('active');
1572             scope.fpnode.all('#fp-repo-'+scope.options.client_id+'-'+obj.repo_id).addClass('active')
1573             // add class repository_REPTYPE to the filepicker (for repository-specific styles)
1574             for (var i in scope.options.repositories) {
1575                 scope.fpnode.removeClass('repository_'+scope.options.repositories[i].type)
1576             }
1577             if (obj.repo_id && scope.options.repositories[obj.repo_id]) {
1578                 scope.fpnode.addClass('repository_'+scope.options.repositories[obj.repo_id].type)
1579             }
1580             Y.one('.file-picker .fp-repo-items').focus();
1582             // display response
1583             if (obj.login) {
1584                 scope.viewbar_set_enabled(false);
1585                 scope.print_login(obj);
1586             } else if (obj.upload) {
1587                 scope.viewbar_set_enabled(false);
1588                 scope.parse_repository_options(obj);
1589                 scope.create_upload_form(obj);
1590             } else if (obj.object) {
1591                 M.core_filepicker.active_filepicker = scope;
1592                 scope.viewbar_set_enabled(false);
1593                 scope.parse_repository_options(obj);
1594                 scope.create_object_container(obj.object);
1595             } else if (obj.list) {
1596                 scope.viewbar_set_enabled(true);
1597                 scope.parse_repository_options(obj);
1598                 scope.view_files();
1599             }
1600         },
1601         list: function(args) {
1602             if (!args) {
1603                 args = {};
1604             }
1605             if (!args.repo_id) {
1606                 args.repo_id = this.active_repo.id;
1607             }
1608             if (!args.path) {
1609                 args.path = '';
1610             }
1611             this.currentpath = args.path;
1612             this.request({
1613                 action: 'list',
1614                 client_id: this.options.client_id,
1615                 repository_id: args.repo_id,
1616                 path: args.path,
1617                 page: args.page,
1618                 scope: this,
1619                 callback: this.display_response
1620             }, true);
1621         },
1622         populate_licenses_select: function(node) {
1623             if (!node) {
1624                 return;
1625             }
1626             node.setContent('');
1627             var licenses = this.options.licenses;
1628             var recentlicense = this.get_preference('recentlicense');
1629             if (recentlicense) {
1630                 this.options.defaultlicense=recentlicense;
1631             }
1632             for (var i in licenses) {
1633                 var option = Y.Node.create('<option/>').
1634                     set('selected', (this.options.defaultlicense==licenses[i].shortname)).
1635                     set('value', licenses[i].shortname).
1636                     setContent(Y.Escape.html(licenses[i].fullname));
1637                 node.appendChild(option)
1638             }
1639         },
1640         set_selected_license: function(node, value) {
1641             var licenseset = false;
1642             node.all('option').each(function(el) {
1643                 if (el.get('value')==value || el.getContent()==value) {
1644                     el.set('selected', true);
1645                     licenseset = true;
1646                 }
1647             });
1648             if (!licenseset) {
1649                 // we did not find the value in the list
1650                 var recentlicense = this.get_preference('recentlicense');
1651                 node.all('option[selected]').set('selected', false);
1652                 node.all('option[value='+recentlicense+']').set('selected', true);
1653             }
1654         },
1655         create_object_container: function(data) {
1656             var content = this.fpnode.one('.fp-content');
1657             content.setContent('');
1658             //var str = '<object data="'+data.src+'" type="'+data.type+'" width="98%" height="98%" id="container_object" class="fp-object-container mdl-align"></object>';
1659             var container = Y.Node.create('<object/>').
1660                 setAttrs({data:data.src, type:data.type, id:'container_object'}).
1661                 addClass('fp-object-container');
1662             content.setContent('').appendChild(container);
1663         },
1664         create_upload_form: function(data) {
1665             var client_id = this.options.client_id;
1666             var id = data.upload.id+'_'+client_id;
1667             var content = this.fpnode.one('.fp-content');
1668             var template_name = 'uploadform_'+this.options.repositories[data.repo_id].type;
1669             var template = M.core_filepicker.templates[template_name] || M.core_filepicker.templates['uploadform'];
1670             content.setContent(template);
1672             content.all('.fp-file,.fp-saveas,.fp-setauthor,.fp-setlicense').each(function (node) {
1673                 node.all('label').set('for', node.one('input,select').generateID());
1674             });
1675             content.one('form').set('id', id);
1676             content.one('.fp-file input').set('name', 'repo_upload_file');
1677             if (data.upload.label && content.one('.fp-file label')) {
1678                 content.one('.fp-file label').setContent(data.upload.label);
1679             }
1680             content.one('.fp-saveas input').set('name', 'title');
1681             content.one('.fp-setauthor input').setAttrs({name:'author', value:this.options.author});
1682             content.one('.fp-setlicense select').set('name', 'license');
1683             this.populate_licenses_select(content.one('.fp-setlicense select'))
1684             // append hidden inputs to the upload form
1685             content.one('form').appendChild(Y.Node.create('<input/>').
1686                 setAttrs({type:'hidden',name:'itemid',value:this.options.itemid}));
1687             var types = this.options.accepted_types;
1688             for (var i in types) {
1689                 content.one('form').appendChild(Y.Node.create('<input/>').
1690                     setAttrs({type:'hidden',name:'accepted_types[]',value:types[i]}));
1691             }
1693             var scope = this;
1694             content.one('.fp-upload-btn').on('click', function(e) {
1695                 e.preventDefault();
1696                 var license = content.one('.fp-setlicense select');
1698                 this.set_preference('recentlicense', license.get('value'));
1699                 if (!content.one('.fp-file input').get('value')) {
1700                     scope.print_msg(M.str.repository.nofilesattached, 'error');
1701                     return false;
1702                 }
1703                 this.hide_header();
1704                 scope.request({
1705                         scope: scope,
1706                         action:'upload',
1707                         client_id: client_id,
1708                         params: {'savepath':scope.options.savepath},
1709                         repository_id: scope.active_repo.id,
1710                         form: {id: id, upload:true},
1711                         onerror: function(id, o, args) {
1712                             scope.create_upload_form(data);
1713                         },
1714                         callback: function(id, o, args) {
1715                             if (o.event == 'fileexists') {
1716                                 scope.create_upload_form(data);
1717                                 scope.process_existing_file(o);
1718                                 return;
1719                             }
1720                             if (scope.options.editor_target&&scope.options.env=='editor') {
1721                                 scope.options.editor_target.value=o.url;
1722                                 scope.options.editor_target.onchange();
1723                             }
1724                             scope.hide();
1725                             o.client_id = client_id;
1726                             var formcallback_scope = args.scope.options.magicscope ? args.scope.options.magicscope : args.scope;
1727                             scope.options.formcallback.apply(formcallback_scope, [o]);
1728                         }
1729                 }, true);
1730             }, this);
1731         },
1732         /** setting handlers and labels for elements in toolbar. Called once during the initial render of filepicker */
1733         setup_toolbar: function() {
1734             var client_id = this.options.client_id;
1735             var toolbar = this.fpnode.one('.fp-toolbar');
1736             toolbar.one('.fp-tb-logout').one('a,button').on('click', function(e) {
1737                 e.preventDefault();
1738                 if (!this.active_repo.nologin) {
1739                     this.hide_header();
1740                     this.request({
1741                         action:'logout',
1742                         client_id: this.options.client_id,
1743                         repository_id: this.active_repo.id,
1744                         path:'',
1745                         callback: this.display_response
1746                     }, true);
1747                 }
1748                 if (this.active_repo.logouturl) {
1749                     window.open(this.active_repo.logouturl, 'repo_auth', 'location=0,status=0,width=500,height=300,scrollbars=yes');
1750                 }
1751             }, this);
1752             toolbar.one('.fp-tb-refresh').one('a,button').on('click', function(e) {
1753                 e.preventDefault();
1754                 if (!this.active_repo.norefresh) {
1755                     this.list({ path: this.currentpath });
1756                 }
1757             }, this);
1758             toolbar.one('.fp-tb-search form').
1759                 set('method', 'POST').
1760                 set('id', 'fp-tb-search-'+client_id).
1761                 on('submit', function(e) {
1762                     e.preventDefault();
1763                     if (!this.active_repo.nosearch) {
1764                         this.request({
1765                             scope: this,
1766                             action:'search',
1767                             client_id: this.options.client_id,
1768                             repository_id: this.active_repo.id,
1769                             form: {id: 'fp-tb-search-'+client_id, upload:false, useDisabled:true},
1770                             callback: this.display_response
1771                         }, true);
1772                     }
1773             }, this);
1775             // it does not matter what kind of element is .fp-tb-manage, we create a dummy <a>
1776             // element and use it to open url on click event
1777             var managelnk = Y.Node.create('<a/>').
1778                 setAttrs({id:'fp-tb-manage-'+client_id+'-link', target:'_blank'}).
1779                 setStyle('display', 'none');
1780             toolbar.append(managelnk);
1781             toolbar.one('.fp-tb-manage').one('a,button').
1782                 on('click', function(e) {
1783                     e.preventDefault();
1784                     managelnk.simulate('click')
1785                 });
1787             // same with .fp-tb-help
1788             var helplnk = Y.Node.create('<a/>').
1789                 setAttrs({id:'fp-tb-help-'+client_id+'-link', target:'_blank'}).
1790                 setStyle('display', 'none');
1791             toolbar.append(helplnk);
1792             toolbar.one('.fp-tb-help').one('a,button').
1793                 on('click', function(e) {
1794                     e.preventDefault();
1795                     helplnk.simulate('click')
1796                 });
1797         },
1798         hide_header: function() {
1799             if (this.fpnode.one('.fp-toolbar')) {
1800                 this.fpnode.one('.fp-toolbar').addClass('empty');
1801             }
1802             if (this.pathbar) {
1803                 this.pathbar.setContent('').addClass('empty');
1804             }
1805         },
1806         print_header: function() {
1807             var r = this.active_repo;
1808             var scope = this;
1809             var client_id = this.options.client_id;
1810             this.hide_header();
1811             this.print_path();
1812             var toolbar = this.fpnode.one('.fp-toolbar');
1813             if (!toolbar) { return; }
1815             var enable_tb_control = function(node, enabled) {
1816                 if (!node) { return; }
1817                 node.addClassIf('disabled', !enabled).addClassIf('enabled', enabled)
1818                 if (enabled) {
1819                     toolbar.removeClass('empty');
1820                 }
1821             }
1823             // TODO 'back' permanently disabled for now. Note, flickr_public uses 'Logout' for it!
1824             enable_tb_control(toolbar.one('.fp-tb-back'), false);
1826             // search form
1827             enable_tb_control(toolbar.one('.fp-tb-search'), !r.nosearch);
1828             if(!r.nosearch) {
1829                 var searchform = toolbar.one('.fp-tb-search form');
1830                 searchform.setContent('');
1831                 this.request({
1832                     scope: this,
1833                     action:'searchform',
1834                     repository_id: this.active_repo.id,
1835                     callback: function(id, obj, args) {
1836                         if (obj.repo_id == scope.active_repo.id && obj.form) {
1837                             // if we did not jump to another repository meanwhile
1838                             searchform.setContent(obj.form);
1839                             // Highlight search text when user click for search.
1840                             var searchnode = searchform.one('input[name="s"]');
1841                             if (searchnode) {
1842                                 searchnode.once('click', function(e) {
1843                                     e.preventDefault();
1844                                     this.select();
1845                                 });
1846                             }
1847                         }
1848                     }
1849                 }, false);
1850             }
1852             // refresh button
1853             // weather we use cache for this instance, this button will reload listing anyway
1854             enable_tb_control(toolbar.one('.fp-tb-refresh'), !r.norefresh);
1856             // login button
1857             enable_tb_control(toolbar.one('.fp-tb-logout'), !r.nologin);
1858             if (!r.nologin) {
1859                 var label = r.logouttext ? r.logouttext : M.str.repository.logout;
1860                 toolbar.one('.fp-tb-logout').one('a,button').setContent(label)
1861             }
1863             // manage url
1864             enable_tb_control(toolbar.one('.fp-tb-manage'), r.manage);
1865             Y.one('#fp-tb-manage-'+client_id+'-link').set('href', r.manage);
1867             // help url
1868             enable_tb_control(toolbar.one('.fp-tb-help'), r.help);
1869             Y.one('#fp-tb-help-'+client_id+'-link').set('href', r.help);
1871             // message
1872             enable_tb_control(toolbar.one('.fp-tb-message'), r.message);
1873             toolbar.one('.fp-tb-message').setContent(r.message);
1874         },
1875         print_path: function() {
1876             if (!this.pathbar) {
1877                 return;
1878             }
1879             this.pathbar.setContent('').addClass('empty');
1880             var p = this.filepath;
1881             if (p && p.length!=0 && this.viewmode != 2) {
1882                 for(var i = 0; i < p.length; i++) {
1883                     var el = this.pathnode.cloneNode(true);
1884                     this.pathbar.appendChild(el);
1885                     if (i == 0) {
1886                         el.addClass('first');
1887                     }
1888                     if (i == p.length-1) {
1889                         el.addClass('last');
1890                     }
1891                     if (i%2) {
1892                         el.addClass('even');
1893                     } else {
1894                         el.addClass('odd');
1895                     }
1896                     el.all('.fp-path-folder-name').setContent(Y.Escape.html(p[i].name));
1897                     el.on('click',
1898                             function(e, path) {
1899                                 e.preventDefault();
1900                                 this.list({'path':path});
1901                             },
1902                         this, p[i].path);
1903                 }
1904                 this.pathbar.removeClass('empty');
1905             }
1906         },
1907         hide: function() {
1908             this.selectui.hide();
1909             if (this.process_dlg) {
1910                 this.process_dlg.hide();
1911             }
1912             if (this.msg_dlg) {
1913                 this.msg_dlg.hide();
1914             }
1915             this.mainui.hide();
1916         },
1917         show: function() {
1918             if (this.fpnode) {
1919                 this.hide();
1920                 this.mainui.show();
1921                 this.show_recent_repository();
1922             } else {
1923                 this.launch();
1924             }
1925         },
1926         launch: function() {
1927             this.render();
1928         },
1929         show_recent_repository: function() {
1930             this.hide_header();
1931             this.viewbar_set_enabled(false);
1932             var repository_id = this.get_preference('recentrepository');
1933             this.viewmode = this.get_preference('recentviewmode');
1934             if (this.viewmode != 2 && this.viewmode != 3) {
1935                 this.viewmode = 1;
1936             }
1937             if (this.options.repositories[repository_id]) {
1938                 this.list({'repo_id':repository_id});
1939             }
1940         },
1941         get_preference: function (name) {
1942             if (this.options.userprefs[name]) {
1943                 return this.options.userprefs[name];
1944             } else {
1945                 return false;
1946             }
1947         },
1948         set_preference: function(name, value) {
1949             if (this.options.userprefs[name] != value) {
1950                 M.util.set_user_preference('filepicker_' + name, value);
1951                 this.options.userprefs[name] = value;
1952             }
1953         }
1954     });
1955     var loading = Y.one('#filepicker-loading-'+options.client_id);
1956     if (loading) {
1957         loading.setStyle('display', 'none');
1958     }
1959     M.core_filepicker.instances[options.client_id] = new FilePickerHelper(options);