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