]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/reports/xul/template-config.js
do not attempt focus()ing
[working/Evergreen.git] / Open-ILS / web / reports / xul / template-config.js
1 function removeReportAtom (args) {
2         if (!args) args = {};
3
4         var active_tab = filterByAttribute(
5                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
6                 'selected',
7                 'true'
8         )[0];
9         var tabname = active_tab.getAttribute('id');
10
11         var tabpanel = $( tabname + 'panel' );
12         var tree = tabpanel.getElementsByTagName('tree')[0];
13         var fields = getSelectedItems(tree);
14
15
16         for (var i in fields) {
17                 var field = fields[i];
18                 var colname = field.firstChild.firstChild.nextSibling.getAttribute('label');
19                 var relation_alias = field.getAttribute('relation');
20
21                 delete rpt_rel_cache[relation_alias].fields[tabname][colname];
22                 if (tabname == 'dis_tab') {
23                         var _o_tmp = [];
24                         for each (var _o_col in rpt_rel_cache.order_by) {
25                                 if (_o_col.relation == relation_alias && _o_col.field == colname) continue;
26                                 _o_tmp.push( _o_col );
27                         }
28                         rpt_rel_cache.order_by = _o_tmp
29                 }
30
31                 with (rpt_rel_cache[relation_alias].fields) {
32                         if ( getKeys(dis_tab).length == 0 && getKeys(filter_tab).length == 0 && getKeys(aggfilter_tab).length == 0 )
33                                 delete rpt_rel_cache[relation_alias];
34                 }
35         }
36
37         renderSources();
38
39         return true;
40 }
41
42 function addReportAtoms () {
43         var nope = $( 'source-add' ).getAttribute('disabled');
44         if (nope == 'true') return false;
45
46         var class_tree = $('class-view');
47         var transform_tree = $('trans-view');
48
49         var active_tab = filterByAttribute(
50                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
51                 'selected',
52                 'true'
53         )[0];
54
55         var tabname = active_tab.getAttribute('id')
56
57         var items = getSelectedItems(class_tree);
58         var transform = getSelectedItems(transform_tree)[0];
59
60         var reltype = $('path-label').getAttribute('reltype');
61         var class_label = $('path-label').value;
62         var relation_alias = hex_md5(class_label);
63
64         for (var i in items) {
65                 var item = items[i];
66
67                 var class_path = item.getAttribute('fullpath');
68                 var field_class = item.getAttribute('idlclass');
69                 var datatype = item.getAttribute('datatype');
70                 var colname = item.getAttribute('idlfield');
71                 var field_label = item.firstChild.firstChild.getAttribute('label');
72
73                 var table_name = getIDLClass(field_class).getAttributeNS(persistNS,'tablename');
74
75                 if ( !rpt_rel_cache[relation_alias] ) {
76                         rpt_rel_cache[relation_alias] =
77                                 { label : class_label,
78                                   alias : relation_alias,
79                                   path  : class_path,
80                                   reltype  : reltype,
81                                   idlclass  : field_class,
82                                   table : table_name,
83                                   fields: { dis_tab : {}, filter_tab : {}, aggfilter_tab : {} }
84                                 };
85                 }
86
87                 if ( !rpt_rel_cache[relation_alias].fields[tabname][colname] ) {
88                         rpt_rel_cache[relation_alias].fields[tabname][colname] =
89                                 { colname   : colname,
90                                   transform : (transform && transform.getAttribute('name')) || 'Bare',
91                                   aggregate : transform && transform.getAttribute('aggregate'),
92                                   params    : transform && transform.getAttribute('params'),
93                                   transform_label: (transform && transform.getAttribute('alias')) || 'Raw Data',
94                                   alias     : field_label,
95                                   datatype  : datatype,
96                                   op        : '=',
97                                   op_label  : 'Equals',
98                                   op_value  : {},
99                                 };
100
101                         if (!rpt_rel_cache.order_by)
102                                 rpt_rel_cache.order_by = [];
103
104                         if (tabname == 'dis_tab')
105                                 rpt_rel_cache.order_by.push( { relation : relation_alias, field : colname } );
106
107                 } else if (
108                         confirm(
109                                 'You have already added the [' + field_label +
110                                 '] field\nfrom the [' + class_label + '] source. Click OK if you\nwould like ' +
111                                 'to reset this field.'
112                         )
113                 ) {
114                         rpt_rel_cache[relation_alias].fields[tabname][colname] =
115                                 { colname   : colname,
116                                   transform : (transform && transform.getAttribute('name')) || 'Bare',
117                                   aggregate : transform && transform.getAttribute('aggregate'),
118                                   params    : transform && transform.getAttribute('params'),
119                                   transform_label: (transform && transform.getAttribute('alias')) || 'Raw Data',
120                                   alias     : field_label,
121                                   datatype  : datatype,
122                                   op        : '=',
123                                   op_label  : 'Equals',
124                                   op_value  : {},
125                                 };
126                 }
127         }
128
129         renderSources();
130
131         return true;
132 }
133
134 function changeDisplayOrder (dir) {
135         var active_tab = filterByAttribute(
136                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
137                 'selected',
138                 'true'
139         )[0];
140
141         var tabname = active_tab.getAttribute('id');
142
143         var tabpanel = $( tabname + 'panel' );
144         var tree = tabpanel.getElementsByTagName('tree')[0];
145         var item = getSelectedItems(tree)[0];
146
147         var item_pos = tree.view.selection.currentIndex;
148
149         if (dir == 'u') {
150                 if ( item.previousSibling ) {
151                         item.parentNode.insertBefore( item, item.previousSibling );
152                         item_pos--;
153                 }
154         } else if (dir == 'd') {
155                 if ( item.nextSibling ) {
156                         if (item.nextSibling.nextSibling ) item.parentNode.insertBefore( item, item.nextSibling.nextSibling );
157                         else item.parentNode.appendChild( item );
158                         item_pos++;
159                 }
160         }
161         
162         rpt_rel_cache.order_by = [];
163         var ordered_list = tree.getElementsByTagName('treeitem');
164         for (var i = 0; i < ordered_list.length; i++) {
165                 rpt_rel_cache.order_by.push(
166                         { relation : ordered_list[i].getAttribute('relation'),
167                           field    : ordered_list[i].firstChild.firstChild.nextSibling.getAttribute('label')
168                         }
169                 );
170         }
171
172         tree.view.selection.select( item_pos );
173         return true;
174 }
175
176 function alterColumnLabel () {
177         var active_tab = filterByAttribute(
178                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
179                 'selected',
180                 'true'
181         )[0];
182
183         var tabname = active_tab.getAttribute('id');
184
185         var tabpanel = $( tabname + 'panel' );
186         var tree = tabpanel.getElementsByTagName('tree')[0];
187         var item_pos = tree.view.selection.currentIndex;
188
189         var item = getSelectedItems(tree)[0];
190         var relation_alias = item.getAttribute('relation');
191
192         var field = item.firstChild.firstChild;
193         var colname = field.nextSibling.getAttribute('label');
194
195         var new_label = prompt(
196                 "Change the column header to:",
197                 field.getAttribute("label")
198         );
199
200         if (new_label) {
201                 rpt_rel_cache[relation_alias].fields[tabname][colname].alias = new_label;
202                 renderSources(true);
203                 tree.view.selection.select( item_pos );
204         }
205
206         return true;
207 }
208
209 function alterColumnTransform (trans) {
210
211         var transform = OILS_RPT_TRANSFORMS[trans];
212
213         var active_tab = filterByAttribute(
214                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
215                 'selected',
216                 'true'
217         )[0];
218
219         var tabname = active_tab.getAttribute('id');
220
221         var tabpanel = $( tabname + 'panel' );
222         var tree = tabpanel.getElementsByTagName('tree')[0];
223         var item_pos = tree.view.selection.currentIndex;
224         var item =  getSelectedItems(tree)[0];
225         var relation_alias = item.getAttribute('relation');
226
227         var field = item.firstChild.firstChild;
228         var colname = field.nextSibling.getAttribute('label');
229
230         rpt_rel_cache[relation_alias].fields[tabname][colname].transform = trans;
231         rpt_rel_cache[relation_alias].fields[tabname][colname].aggregate = transform.aggregate;
232         rpt_rel_cache[relation_alias].fields[tabname][colname].params = transform.params;
233         rpt_rel_cache[relation_alias].fields[tabname][colname].transform_label = transform.label;
234
235         renderSources(true);
236         tree.view.selection.select( item_pos );
237         return true;
238 }
239
240 function changeOperator (args) {
241
242         var active_tab = filterByAttribute(
243                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
244                 'selected',
245                 'true'
246         )[0];
247
248         var tabname = active_tab.getAttribute('id');
249
250         var tabpanel = $( tabname + 'panel' );
251         var tree = tabpanel.getElementsByTagName('tree')[0];
252         var item_pos = tree.view.selection.currentIndex;
253         var item = getSelectedItems(tree)[0];
254
255         var relation_alias = item.getAttribute('relation');
256
257         var field = item.firstChild.firstChild;
258         var colname = field.nextSibling.getAttribute('label');
259
260         rpt_rel_cache[relation_alias].fields[tabname][colname].op = args.op;
261         rpt_rel_cache[relation_alias].fields[tabname][colname].op_label = args.label;
262
263         renderSources(true);
264         tree.view.selection.select( item_pos );
265         return true;
266 }
267
268 function removeTemplateFilterValue () {
269
270         var active_tab = filterByAttribute(
271                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
272                 'selected',
273                 'true'
274         )[0];
275
276         var tabname = active_tab.getAttribute('id');
277
278         var tabpanel = $( tabname + 'panel' );
279         var tree = tabpanel.getElementsByTagName('tree')[0];
280         var item_pos = tree.view.selection.currentIndex;
281         var items = getSelectedItems(tree);
282
283         for (var i in items) {
284                 var item = items[i];
285                 var relation_alias = item.getAttribute('relation');
286
287                 var field = item.firstChild.firstChild;
288                 var colname = field.nextSibling.getAttribute('label');
289
290                 rpt_rel_cache[relation_alias].fields[tabname][colname].op_value = {};
291         }
292
293         renderSources(true);
294         tree.view.selection.select( item_pos );
295         return true;
296 }
297
298 function timestampSetDate (obj, cal, date) {
299         obj.op_value.value = date;
300         obj.op_value.object = cal.date;
301         obj.op_value.label = '"' + date + '"';
302
303         renderSources(true);
304         return true;
305 }
306
307 var __handler_cache;
308
309 function changeTemplateFilterValue () {
310
311         var active_tab = filterByAttribute(
312                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
313                 'selected',
314                 'true'
315         )[0];
316
317         var tabname = active_tab.getAttribute('id');
318
319         var tabpanel = $( tabname + 'panel' );
320         var tree = tabpanel.getElementsByTagName('tree')[0];
321         var item_pos = tree.view.selection.currentIndex;
322         var items = getSelectedItems(tree);
323
324         var targetCmd = $( tabname + '_value_action' );
325
326         targetCmd.menu = null;
327         targetCmd.command = null;
328         targetCmd.oncommand = null;
329         targetCmd.removeEventListener( 'command', __handler_cache, true );
330
331         for (var i in items) {
332                 var item = items[i];
333                 var relation_alias = item.getAttribute('relation');
334
335                 var field = item.firstChild.firstChild;
336                 var colname = field.nextSibling.getAttribute('label');
337
338                 var obj = rpt_rel_cache[relation_alias].fields[tabname][colname]
339                 var operation = OILS_RPT_FILTERS[obj.op];
340
341                 switch (obj.datatype) {
342                         case 'timestamp':
343                                 var cal_popup = $('calendar-widget');
344
345                                 while (cal_popup.firstChild) cal_popup.removeChild(cal_popup.lastChild);
346                                 var calendar = new Calendar(
347                                         0,
348                                         obj.op_value.object,
349                                         function (cal,date) { return timestampSetDate(obj,cal,date) },
350                                         function (cal) { cal_popup.hidePopup(); cal.destroy(); return true; }
351                                 );
352
353                                 var format = OILS_RPT_TRANSFORMS[obj.transform].cal_format || '%Y-%m-%d';
354
355                                 calendar.setDateFormat(format);
356                                 calendar.create(cal_popup);
357
358                                 targetCmd.menu = 'calendar-widget';
359
360                                 break;
361
362                         case 'bool':
363
364                                 function __bool_value_event_handler () {
365                                         var state, answer;
366
367                                         try {
368                                                 // get a reference to the prompt service component.
369                                                 var promptService = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
370                                                                     .getService(Components.interfaces.nsIPromptService);
371
372                                                 // set the buttons that will appear on the dialog. It should be
373                                                 // a set of constants multiplied by button position constants. In this case,
374                                                 // three buttons appear, Save, Cancel and a custom button.
375                                                 var flags=promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_0 +
376                                                         promptService.BUTTON_TITLE_IS_STRING * promptService.BUTTON_POS_1 +
377                                                         promptService.BUTTON_TITLE_CANCEL * promptService.BUTTON_POS_2;
378
379                                                 // display the dialog box. The flags set above are passed
380                                                 // as the fourth argument. The next three arguments are custom labels used for
381                                                 // the buttons, which are used if BUTTON_TITLE_IS_STRING is assigned to a
382                                                 // particular button. The last two arguments are for an optional check box.
383                                                 answer = promptService.select(
384                                                         window,
385                                                         "Boolean Value",
386                                                         "Select the value, or cancel:",
387                                                         2, ["True", "False"], state
388                                                 );
389                                         } catch (e) {
390                                                 answer = true;
391                                                 state = confirm("Click OK for TRUE and Cancel for FALSE.");
392                                                 state ? state = 0 : state = 1;
393                                         }
394
395                                         if (answer) {
396                                                 if (state) {
397                                                         obj.op_value.value = 'f';
398                                                         obj.op_value.label = 'False';
399                                                 } else {
400                                                         obj.op_value.value = 't';
401                                                         obj.op_value.label = 'True';
402                                                 }
403                                         }
404
405                                         targetCmd.removeEventListener( 'command', __bool_value_event_handler, true );
406                                         renderSources(true);
407                                         tree.view.selection.select( item_pos );
408                                         return true;
409                                 }
410
411                                 __handler_cache = __bool_value_event_handler;
412                                 targetCmd.addEventListener( 'command', __bool_value_event_handler, true );
413
414                                 break;
415
416                         default:
417
418
419                                 var promptstring = "Field does not match one of list (comma separated):";
420
421                                 switch (obj.op) {
422                                         case 'not between':
423                                                 promptstring = "Field value is not between (comma separated):";
424                                                 break;
425
426                                         case 'between':
427                                                 promptstring = "Field value is between (comma separated):";
428                                                 break;
429
430                                         case 'not in':
431                                                 promptstring = "Field does not match one of list (comma separated):";
432                                                 break;
433
434                                         case 'in':
435                                                 promptstring = "Field matches one of list (comma separated):";
436                                                 break;
437
438                                         default:
439                                                 promptstring = "Value " + obj.op_label + ":";
440                                                 break;
441                                 }
442
443                                 function __default_value_event_handler () {
444                                         var _v;
445                                         if (_v  = prompt( promptstring, obj.op_value.value || '' )) {
446                                                 switch (obj.op) {
447                                                         case 'between':
448                                                         case 'not between':
449                                                         case 'not in':
450                                                         case 'in':
451                                                                 obj.op_value.value = _v.split(/\s*,\s*/);
452                                                                 break;
453
454                                                         default:
455                                                                 obj.op_value.value = _v;
456                                                                 break;
457                                                 }
458
459                                                 obj.op_value.label = '"' + obj.op_value.value + '"';
460                                         }
461
462                                         targetCmd.removeEventListener( 'command', __default_value_event_handler, true );
463                                         renderSources(true);
464                                         tree.view.selection.select( item_pos );
465                                         return true;
466                                 }
467
468                                 __handler_cache = __default_value_event_handler;
469                                 targetCmd.addEventListener( 'command', __default_value_event_handler, true );
470
471                                 break;
472                 }
473         }
474
475         return true;
476 }
477
478 function populateOperatorContext () {
479
480         var active_tab = filterByAttribute(
481                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
482                 'selected',
483                 'true'
484         )[0];
485
486         var tabname = active_tab.getAttribute('id');
487
488         var tabpanel = $( tabname + 'panel' );
489         var tree = tabpanel.getElementsByTagName('tree')[0];
490         var item = getSelectedItems(tree)[0];
491
492         var dtypes = [];
493         dtypes.push( item.getAttribute('datatype') );
494
495         var menu = $(tabname + '_op_menu');
496         while (menu.firstChild) menu.removeChild(menu.lastChild);
497
498         for (var i in OILS_RPT_FILTERS) {
499                 var o = OILS_RPT_FILTERS[i];
500                 menu.appendChild(
501                         createMenuItem(
502                                 { label : o.label,
503                                   oncommand : "changeOperator({op:'"+i+"',label:'"+o.label+"'})",
504                                 }
505                         )
506                 );
507                 if (o.labels) {
508                         var keys = getKeys(o.labels);
509                         for ( var k in keys ) {
510                                 var key = keys[k];
511                                 if ( grep(function(x){return key==x},dtypes).length ) {
512                                         menu.appendChild(
513                                                 createMenuItem(
514                                                         { label : o.labels[key],
515                                                           oncommand : "changeOperator({op:'"+i+"',label:'"+o.labels[key]+"'})",
516                                                         }
517                                                 )
518                                         );
519                                 }
520                         }
521                 }
522         }
523 }
524
525 function populateTransformContext () {
526
527         var active_tab = filterByAttribute(
528                 $('used-source-fields-tabbox').getElementsByTagName('tab'),
529                 'selected',
530                 'true'
531         )[0];
532
533         var tabname = active_tab.getAttribute('id');
534
535         var tabpanel = $( tabname + 'panel' );
536         var tree = tabpanel.getElementsByTagName('tree')[0];
537         var item_pos = tree.view.selection.currentIndex;
538         var item = getSelectedItems(tree)[0];
539
540         var transforms = {};
541         var dtype = item.getAttribute('datatype');
542         var item_transforms = getTransforms({ datatype : dtype });
543
544         for (var j in item_transforms) {
545                 transforms[item_transforms[j]] = OILS_RPT_TRANSFORMS[item_transforms[j]];
546                 transforms[item_transforms[j]].name = item_transforms[j];
547         }
548
549         var transformList = [];
550         for (var i in transforms) {
551                 transformList.push( transforms[i] );
552         }
553
554         transformList.sort( sortHashLabels );
555
556         var menu = $(tabname + '_trans_menu');
557         while (menu.firstChild) menu.removeChild(menu.lastChild);
558
559         for (var i in transformList) {
560                 var t = transformList[i];
561
562                 if (tabname.match(/filter/)) {
563                         if (tabname.match(/^agg/)) {
564                                 if (!t.aggregate) continue;
565                         } else {
566                                 if (t.aggregate) continue;
567                         }
568                 }
569
570                 menu.appendChild(
571                         createMenuItem(
572                                 { aggregate : t.aggregate,
573                                   name : t.name,
574                                   alias : t.label,
575                                   label : t.label,
576                                   params : t.params,
577                                   command : function () { return alterColumnTransform(t.name) }
578                                 }
579                         )
580                 );
581         }
582
583         menu.parentNode.setAttribute('disabled','false');
584         if (menu.childNodes.length == 0) {
585                 menu.parentNode.setAttribute('disabled','true');
586         }
587 }
588
589
590 function renderSources (selected) {
591
592         var tree = $('used-sources');
593         var sources = $('used-sources-treetop');
594         var tabs = $('used-source-fields-tabbox').getElementsByTagName('tab');
595
596         if (!selected) {
597                 while (sources.firstChild) sources.removeChild(sources.lastChild);
598         } else {
599                 selected = getSelectedItems(tree);
600                 if (!selected.length) {
601                         selected = undefined;
602                         while (sources.firstChild) sources.removeChild(sources.lastChild);
603                 }
604         }
605
606         for (var j = 0; j < tabs.length; j++) {
607                 var tab = tabs[j];
608                 var tabname = tab.getAttribute('id')
609                 var tabpanel = $( tab.getAttribute('id') + 'panel' );
610                 var fieldtree = tabpanel.getElementsByTagName('treechildren')[0];
611
612                 while (fieldtree.firstChild) fieldtree.removeChild(fieldtree.lastChild);
613         }
614
615         for (var relation_alias in rpt_rel_cache) {
616                 if (!rpt_rel_cache[relation_alias].fields) continue;
617
618                 if (selected) {
619                         if (
620                                 !grep(
621                                         function (x) {
622                                                 return x.getAttribute('relation') == relation_alias;
623                                         },
624                                         selected
625                                 ).length
626                         ) continue;
627                 } else {
628
629                         $('used-sources-treetop').appendChild(
630                                 createTreeItem(
631                                         { relation : rpt_rel_cache[relation_alias].alias,
632                                           idlclass : rpt_rel_cache[relation_alias].idlclass,
633                                           reltype  : rpt_rel_cache[relation_alias].reltype,
634                                           path     : rpt_rel_cache[relation_alias].path,
635                                         },
636                                         createTreeRow(
637                                                 {},
638                                                 createTreeCell({ label : rpt_rel_cache[relation_alias].label }),
639                                                 createTreeCell({ label : rpt_rel_cache[relation_alias].table }),
640                                                 createTreeCell({ label : rpt_rel_cache[relation_alias].alias }),
641                                                 createTreeCell({ label : rpt_rel_cache[relation_alias].reltype })
642                                         )
643                                 )
644                         );
645                 }
646
647                 for each (var tabname in ['filter_tab','aggfilter_tab']) {
648                         tabpanel = $( tabname + 'panel' );
649                         fieldtree = tabpanel.getElementsByTagName('treechildren')[0];
650
651                         for (var colname in rpt_rel_cache[relation_alias].fields[tabname]) {
652                                 with (rpt_rel_cache[relation_alias].fields[tabname][colname]) {
653                                         fieldtree.appendChild(
654                                                 createTreeItem(
655                                                         { relation : relation_alias, datatype : datatype },
656                                                         createTreeRow(
657                                                                 {},
658                                                                 createTreeCell({ label : alias }),
659                                                                 createTreeCell({ label : colname }),
660                                                                 createTreeCell({ label : datatype }),
661                                                                 createTreeCell({ label : transform_label }),
662                                                                 createTreeCell({ label : transform })
663                                                         )
664                                                 )
665                                         );
666
667                                         fieldtree.lastChild.firstChild.appendChild(
668                                                 createTreeCell({ op : op, label : op_label })
669                                         );
670
671                                         if (op_value.value != undefined) {
672                                                 fieldtree.lastChild.firstChild.appendChild(
673                                                         createTreeCell({ label : op_value.label })
674                                                 );
675                                         }
676                                 }
677                         }
678                 }
679         }
680
681         tabpanel = $( 'dis_tabpanel' );
682         fieldtree = tabpanel.getElementsByTagName('treechildren')[0];
683         for each (var order in rpt_rel_cache.order_by) {
684
685                 if (selected) {
686                         if (
687                                 !grep(
688                                         function (x) {
689                                                 return x.getAttribute('relation') == order.relation;
690                                         },
691                                         selected
692                                 ).length
693                         ) continue;
694                 }
695
696                 with (rpt_rel_cache[order.relation].fields.dis_tab[order.field]) {
697                         fieldtree.appendChild(
698                                 createTreeItem(
699                                         { relation : order.relation, datatype : datatype },
700                                         createTreeRow(
701                                                 {},
702                                                 createTreeCell({ label : alias }),
703                                                 createTreeCell({ label : colname }),
704                                                 createTreeCell({ label : datatype }),
705                                                 createTreeCell({ label : transform_label }),
706                                                 createTreeCell({ label : transform })
707                                         )
708                                 )
709                         );
710
711                         fieldtree.lastChild.firstChild.appendChild(
712                                 createTreeCell({ op : op, label : op_label })
713                         );
714
715                         if (op_value.value != undefined) {
716                                 fieldtree.lastChild.firstChild.appendChild(
717                                         createTreeCell({ label : op_value.label })
718                                 );
719                         }
720                 }
721         }
722 }
723
724 var param_count;
725 var tab_use = {
726         dis_tab       : 'select',
727         filter_tab    : 'where',
728         aggfilter_tab : 'having',
729 };
730
731
732 function save_template () {
733         param_count = 0;
734
735         var template = {
736                 version    : 1,
737                 core_class : $('sources-treetop').getElementsByTagName('treeitem')[0].getAttribute('idlclass'),
738                 select     : [],
739                 from       : {},
740                 where      : [],
741                 having     : [],
742                 order_by   : []
743         };
744
745         for (var relname in rpt_rel_cache) {
746                 var relation = rpt_rel_cache[relname];
747                 if (!relation.fields) continue;
748
749                 // first, add the where and having clauses (easier)
750                 for each (var tab_name in [ 'filter_tab', 'aggfilter_tab' ]) {
751                         var tab = relation.fields[tab_name];
752                         for (var field in tab) {
753                                 fleshTemplateField( template, relation, tab_name, field );
754                         }
755                 }
756
757                 // now the from clause
758                 fleshFromPath( template, relation );
759         }
760
761         // and now for select (based on order_by)
762         for each (var order in rpt_rel_cache.order_by)
763                 fleshTemplateField( template, rpt_rel_cache[order.relation], 'dis_tab', order.field );
764
765
766         // and the saving throw ...
767         var cgi = new CGI();
768         var session = cgi.param('ses');
769         fetchUser( session );
770
771         var tmpl = new rt();
772         tmpl.name( $('template-name').value );
773         tmpl.description( $('template-description').value );
774         tmpl.owner(USER.id());
775         tmpl.folder(cgi.param('folder'));
776         tmpl.data(js2JSON(template));
777
778         // prompt( 'template', js2JSON( tmpl ) );
779
780         if(!confirm('Name : '+tmpl.name() + '\nDescription: ' + tmpl.description()+'\nSave Template?'))
781                 return;
782
783         var req = new Request('open-ils.reporter:open-ils.reporter.template.create', session, tmpl);
784         req.request.alertEvent = false;
785         req.callback(
786                 function(r) {
787                         var res = r.getResultObject();
788                         if(checkILSEvent(res)) {
789                                 alertILSEvent(res);
790                         } else {
791                                 if( res && res != '0' ) {
792                                         confirm('Template ' + tmpl.name() + ' was successfully saved.');
793                                         _l('../oils_rpt.xhtml');
794                                 }
795                         }
796                 }
797         );
798
799         req.send();
800 }
801
802 function fleshFromPath ( template, rel ) {
803         var table_path = rel.path.split( /\./ );
804         if (table_path.length > 1 || rel.path.indexOf('-') > -1) table_path.push( rel.idlclass );
805
806         var prev_type = '';
807         var prev_link = '';
808         var current_path = '';
809         var current_obj = template.from;
810         var link;
811         while (link = table_path.shift()) {
812                 if (current_path) current_path += '-';
813                 current_path += link;
814
815                 var leaf = table_path.length == 0 ? true : false;
816
817                 current_obj.path = current_path;
818                 current_obj.table = getIDLClass( link.split(/-/)[0] ).getAttributeNS( persistNS, 'tablename' );
819
820                 if (prev_link != '') {
821                         var prev_class = getIDLClass( prev_link.split(/-/)[0] );
822                         var prev_field = prev_link.split(/-/)[1];
823
824                         var current_link = getIDLLink( prev_class, prev_field );
825                         current_obj.key = current_link.getAttribute('key');
826
827                         if (
828                                 current_link.getAttribute('reltype') != 'has_a' ||
829                                 prev_type == 'left' ||
830                                 rel.reltype != 'has_a'
831                         ) current_obj.type = 'left';
832
833                         prev_type = current_obj.type; 
834                 }
835
836                 if (leaf) {
837                         current_obj.label = rel.label;
838                         current_obj.alias = rel.alias;
839                         current_obj.idlclass = rel.idlclass;
840                         current_obj.template_path = rel.path;
841                 } else {
842                         var current_class = getIDLClass( link.split(/-/)[0] );
843                         var join_field = link.split(/-/)[1];
844                         var join_link = getIDLLink(current_class, join_field);
845
846                         if (join_link.getAttribute('reltype') != 'has_a') {
847                                 var fields_el = current_class.getElementsByTagName('fields')[0];
848                                 join_field = fields_el.getAttributeNS(persistNS, 'primary') + '-' + join_link.getAttribute('key');
849                         }
850
851                         current_obj.alias = hex_md5( current_path ) ;
852                         join_field += '-' + current_obj.alias;
853                         if (table_path.length == 1) join_field += '-' + rel.alias;
854
855                         if (!current_obj.join) current_obj.join = {};
856                         if (!current_obj.join[join_field]) current_obj.join[join_field] = {};
857
858                         if (current_obj.type == 'left') current_obj.join[join_field].type = 'left';
859
860                         current_obj = current_obj.join[join_field];
861                 }
862
863                 prev_link = link;
864         }
865
866
867 }
868
869 function fleshTemplateField ( template, rel, tab_name, field ) {
870
871         if (!rel.fields[tab_name] || !rel.fields[tab_name][field]) return;
872
873         var tab = rel.fields[tab_name];
874
875         var field_path = rel.path + '-' + field;
876         field_path = field_path.replace(/\./g, '-');
877
878         var element = {
879                 alias : tab[field].alias,
880                 column :
881                         { colname : field,
882                           transform : tab[field].transform,
883                           transform_label : tab[field].transform_label
884                         },
885                 path : field_path,
886                 relation : rel.alias
887         };
888
889         if (tab_name.match(/filter/)) {
890                 element.condition = {};
891                 element.condition[tab[field].op] =
892                         tab[field].op_value.value ?
893                                 tab[field].op_value.value :
894                                 '::P' + param_count++;
895         }
896
897         template[tab_use[tab_name]].push(element);
898 }
899