4ec75a673594ae3b39f04b2b6a516a96791558ae
[plstackapi.git] / planetstack / core / xoslib / static / js / xoslib / xosHelper.js
1 HTMLView = Marionette.ItemView.extend({
2   render: function() {
3       this.$el.append(this.options.html);
4   },
5 });
6
7 SliceSelectorOption = Marionette.ItemView.extend({
8     template: "#xos-sliceselector-option",
9     tagName: "option",
10     attributes: function() {
11         if (this.options.selectedID == this.model.get("id")) {
12             return { value: this.model.get("id"), selected: 1 };
13         } else {
14             return { value: this.model.get("id") };
15         }
16     },
17 });
18
19 SliceSelectorView = Marionette.CompositeView.extend({
20     template: "#xos-sliceselector-select",
21     childViewContainer: "select",
22     childView: SliceSelectorOption,
23
24     events: {"change select": "onSliceChanged"},
25
26     childViewOptions: function() {
27         return { selectedID: this.options.selectedID || this.selectedID || null };
28     },
29
30     onSliceChanged: function() {
31         this.sliceChanged(this.$el.find("select").val());
32     },
33
34     sliceChanged: function(id) {
35         console.log("sliceChanged " + id);
36     },
37 });
38
39 FilteredCompositeView = Marionette.CompositeView.extend( {
40     showCollection: function() {
41       var ChildView;
42       this.collection.each(function(child, index) {
43         if (this.filter && !this.filter(child)) {
44             return;
45         }
46         ChildView = this.getChildView(child);
47         this.addChild(child, ChildView, index);
48       }, this);
49
50     },
51 });
52
53 XOSRouter = Marionette.AppRouter.extend({
54         initialize: function() {\r
55             this.routeStack=[];\r
56         },\r
57 \r
58         onRoute: function(x,y,z) {\r
59              this.routeStack.push(Backbone.history.fragment);\r
60              this.routeStack = this.routeStack.slice(-32);   // limit the size of routeStack to something reasonable\r
61         },\r
62 \r
63         prevPage: function() {\r
64              return this.routeStack.slice(-1)[0];
65         },
66
67         showPreviousURL: function() {
68             prevPage = this.prevPage();
69             //console.log("showPreviousURL");
70             //console.log(this.routeStack);
71             if (prevPage) {
72                 this.navigate("#"+prevPage, {trigger: false, replace: true} );
73             }
74         },
75
76         navigate: function(href, options) {
77             if (options.force) {
78                 Marionette.AppRouter.prototype.navigate.call(this, "nowhere", {trigger: false, replace: true});
79             }
80             Marionette.AppRouter.prototype.navigate.call(this, href, options);
81         },
82     });\r
83
84 Backbone.Syphon.InputReaders.register('select', function(el) {
85     // Modify syphon so that if a select has "syphonall" in the class, then
86     // the value of every option will be returned, regardless of whether of
87     // not it is selected.
88     if (el.hasClass("syphonall")) {
89         result = [];
90         _.each(el.find("option"), function(option) {
91             result.push($(option).val());
92         });
93         return result;
94     }
95     return el.val();
96 });
97
98 XOSApplication = Marionette.Application.extend({
99     detailBoxId: "#detailBox",
100     errorBoxId: "#errorBox",
101     errorCloseButtonId: "#close-error-box",
102     successBoxId: "#successBox",
103     successCloseButtonId: "#close-success-box",
104     errorTemplate: "#xos-error-template",
105     successTemplate: "#xos-success-template",
106     logMessageCount: 0,
107
108     confirmDialog: function(view, event, callback) {
109         $("#xos-confirm-dialog").dialog({
110            autoOpen: false,
111            modal: true,
112            buttons : {
113                 "Confirm" : function() {
114                   $(this).dialog("close");
115                   if (event) {
116                       view.trigger(event);
117                   }
118                   if (callback) {
119                       callback();
120                   }
121                 },
122                 "Cancel" : function() {
123                   $(this).dialog("close");
124                 }
125               }
126             });
127         $("#xos-confirm-dialog").dialog("open");
128     },
129
130     popupErrorDialog: function(responseText) {
131         try {
132             parsed_error=$.parseJSON(responseText);
133             width=300;
134         }
135         catch(err) {
136             parsed_error=undefined;
137             width=640;    // django stacktraces like wide width
138         }
139         console.log(responseText);
140         console.log(parsed_error);
141         if (parsed_error) {
142             $("#xos-error-dialog").html(templateFromId("#xos-error-response")(parsed_error));
143         } else {
144             $("#xos-error-dialog").html(templateFromId("#xos-error-rawresponse")({responseText: responseText}))
145         }
146
147         $("#xos-error-dialog").dialog({
148             modal: true,
149             width: width,
150             buttons: {
151                 Ok: function() { $(this).dialog("close"); }
152             }
153         });
154     },
155
156     hideLinkedItems: function(result) {
157         var index=0;
158         while (index<4) {
159             this["linkedObjs" + (index+1)].empty();
160             index = index + 1;
161         }
162     },
163
164     hideTabs: function() { $("#tabs").hide(); },
165     showTabs: function() { $("#tabs").show(); },
166
167     createListHandler: function(listViewName, collection_name, regionName, title) {
168         var app=this;
169         return function() {
170             listView = new app[listViewName];
171             app[regionName].show(listView);
172             app.hideLinkedItems();
173             $("#contentTitle").html(templateFromId("#xos-title-list")({"title": title}));
174             $("#detail").show();
175             app.hideTabs();
176
177             listButtons = new XOSListButtonView({linkedView: listView});
178             app["rightButtonPanel"].show(listButtons);
179         }
180     },
181
182     createAddHandler: function(detailName, collection_name, regionName, title) {
183         var app=this;
184         return function() {
185             console.log("addHandler");
186
187             app.hideLinkedItems();
188             app.hideTabs();
189
190             model = new xos[collection_name].model();
191             detailViewClass = app[detailName];
192             detailView = new detailViewClass({model: model, collection:xos[collection_name]});
193             app[regionName].show(detailView);
194
195             detailButtons = new XOSDetailButtonView({linkedView: detailView});
196             app["rightButtonPanel"].show(detailButtons);
197         }
198     },
199
200     createAddChildHandler: function(addChildName, collection_name) {
201         var app=this;
202         return function(parent_modelName, parent_fieldName, parent_id) {
203             app.Router.showPreviousURL();
204             model = new xos[collection_name].model();
205             model.attributes[parent_fieldName] = parent_id;
206             model.readOnlyFields.push(parent_fieldName);
207             detailViewClass = app[addChildName];
208             var detailView = new detailViewClass({model: model, collection:xos[collection_name]});
209             detailView.dialog = $("xos-addchild-dialog");
210             app["addChildDetail"].show(detailView);
211             $("#xos-addchild-dialog").dialog({
212                autoOpen: false,
213                modal: true,
214                width: 640,
215                buttons : {
216                     "Save" : function() {
217                       var addDialog = this;
218                       detailView.synchronous = true;
219                       detailView.afterSave = function() { console.log("addChild afterSave"); $(addDialog).dialog("close"); }
220                       detailView.save();
221
222                       //$(this).dialog("close");
223                     },
224                     "Cancel" : function() {
225                       $(this).dialog("close");
226                     }
227                   }
228                 });
229             $("#xos-addchild-dialog").dialog("open");
230         }
231     },
232
233     createDeleteHandler: function(collection_name) {
234         var app=this;
235         return function(model_id) {
236             console.log("deleteCalled");
237             collection = xos[collection_name];
238             model = collection.get(model_id);
239             assert(model!=undefined, "failed to get model " + model_id + " from collection " + collection_name);
240             app.Router.showPreviousURL();
241             app.deleteDialog(model);
242         }
243     },
244
245     createDetailHandler: function(detailName, collection_name, regionName, title) {
246         var app=this;
247         showModelId = function(model_id) {
248             $("#contentTitle").html(templateFromId("#xos-title-detail")({"title": title}));
249
250             collection = xos[collection_name];
251             model = collection.get(model_id);
252             if (model == undefined) {
253                 app[regionName].show(new HTMLView({html: "failed to load object " + model_id + " from collection " + collection_name}));
254             } else {
255                 detailViewClass = app[detailName];
256                 detailView = new detailViewClass({model: model});
257                 app[regionName].show(detailView);
258                 detailView.showLinkedItems();
259
260                 detailButtons = new XOSDetailButtonView({linkedView: detailView});
261                 app["rightButtonPanel"].show(detailButtons);
262             }
263         }
264         return showModelId;
265     },
266
267     /* error handling callbacks */
268
269     hideError: function() {
270         if (this.logWindowId) {
271         } else {
272             $(this.errorBoxId).hide();
273             $(this.successBoxId).hide();
274         }
275     },
276
277     showSuccess: function(result) {
278          result["statusclass"] = "success";
279          if (this.logTableId) {
280              this.appendLogWindow(result);
281          } else {
282              $(this.successBoxId).show();
283              $(this.successBoxId).html(_.template($(this.successTemplate).html())(result));
284              var that=this;
285              $(this.successCloseButtonId).unbind().bind('click', function() {
286                  $(that.successBoxId).hide();
287              });
288          }
289     },
290
291     showError: function(result) {
292          result["statusclass"] = "failure";
293          if (this.logTableId) {
294              this.appendLogWindow(result);
295              this.popupErrorDialog(result.responseText);
296          } else {
297              // this is really old stuff
298              $(this.errorBoxId).show();
299              $(this.errorBoxId).html(_.template($(this.errorTemplate).html())(result));
300              var that=this;
301              $(this.errorCloseButtonId).unbind().bind('click', function() {
302                  $(that.errorBoxId).hide();
303              });
304          }
305     },
306
307     showInformational: function(result) {
308          result["statusclass"] = "inprog";
309          if (this.logTableId) {
310              return this.appendLogWindow(result);
311          } else {
312              return undefined;
313          }
314     },
315
316     appendLogWindow: function(result) {
317         // compute a new logMessageId for this log message
318         logMessageId = "logMessage" + this.logMessageCount;
319         this.logMessageCount = this.logMessageCount + 1;
320         result["logMessageId"] = logMessageId;
321
322         logMessageTemplate=$("#xos-log-template").html();
323         assert(logMessageTemplate != undefined, "logMessageTemplate is undefined");
324         newRow = _.template(logMessageTemplate, result);
325         assert(newRow != undefined, "newRow is undefined");
326
327         if (result["infoMsgId"] != undefined) {
328             // We were passed the logMessageId of an informational message,
329             // and the caller wants us to replace that message with our own.
330             // i.e. replace an informational message with a success or an error.
331             $("#"+result["infoMsgId"]).replaceWith(newRow);
332         } else {
333             // Create a brand new log message rather than replacing one.
334             logTableBody = $(this.logTableId + " tbody");
335             logTableBody.prepend(newRow);
336         }
337
338         if (this.statusMsgId) {
339             $(this.statusMsgId).html( templateFromId("#xos-status-template")(result) );
340         }
341
342         limitTableRows(this.logTableId, 5);
343
344         return logMessageId;
345     },
346
347     saveError: function(model, result, xhr, infoMsgId) {
348         console.log("saveError");
349         result["what"] = "save " + model.modelName + " " + model.attributes.humanReadableName;
350         result["infoMsgId"] = infoMsgId;
351         this.showError(result);
352     },
353
354     saveSuccess: function(model, result, xhr, infoMsgId, addToCollection) {
355         console.log("saveSuccess");
356         if (model.addToCollection) {
357             console.log("addToCollection");
358             console.log(model.addToCollection);
359             model.addToCollection.add(model);
360             model.addToCollection.sort();
361             model.addToCollection = undefined;
362         }
363         result = {status: xhr.xhr.status, statusText: xhr.xhr.statusText};
364         result["what"] = "save " + model.modelName + " " + model.attributes.humanReadableName;
365         result["infoMsgId"] = infoMsgId;
366         this.showSuccess(result);
367     },
368
369     destroyError: function(model, result, xhr, infoMsgId) {
370         result["what"] = "destroy " + model.modelName + " " + model.attributes.humanReadableName;
371         result["infoMsgId"] = infoMsgId;
372         this.showError(result);
373     },
374
375     destroySuccess: function(model, result, xhr, infoMsgId) {
376         result = {status: xhr.xhr.status, statusText: xhr.xhr.statusText};
377         result["what"] = "destroy " + model.modelName + " " + model.attributes.humanReadableName;
378         result["infoMsgId"] = infoMsgId;
379         this.showSuccess(result);
380     },
381
382     /* end error handling callbacks */
383
384     destroyModel: function(model) {
385          //console.log("destroyModel"); console.log(model);
386          this.hideError();
387          var infoMsgId = this.showInformational( {what: "destroy " + model.modelName + " " + model.attributes.humanReadableName, status: "", statusText: "in progress..."} );
388          var that = this;
389          model.destroy({error: function(model, result, xhr) { that.destroyError(model,result,xhr,infoMsgId);},
390                         success: function(model, result, xhr) { that.destroySuccess(model,result,xhr,infoMsgId);}});
391     },
392
393     deleteDialog: function(model, afterDelete) {
394         var that=this;
395         assert(model!=undefined, "deleteDialog's model is undefined");
396         //console.log("deleteDialog"); console.log(model);
397         this.confirmDialog(null, null, function() {
398             //console.log("deleteConfirm"); console.log(model);
399             modelName = model.modelName;
400             that.destroyModel(model);
401             if (afterDelete=="list") {
402                 that.navigate("list", modelName);
403             }
404         });
405     },
406 });
407
408 XOSButtonView = Marionette.ItemView.extend({
409             events: {"click button.btn-xos-save-continue": "submitContinueClicked",
410                      "click button.btn-xos-save-leave": "submitLeaveClicked",
411                      "click button.btn-xos-save-another": "submitAddAnotherClicked",
412                      "click button.btn-xos-delete": "deleteClicked",
413                      "click button.btn-xos-add": "addClicked",
414                      "click button.btn-xos-refresh": "refreshClicked",
415                      },
416
417             submitLeaveClicked: function(e) {
418                      this.options.linkedView.submitLeaveClicked.call(this.options.linkedView, e);
419                      },
420
421             submitContinueClicked: function(e) {
422                      this.options.linkedView.submitContinueClicked.call(this.options.linkedView, e);
423                      },
424
425             submitAddAnotherClicked: function(e) {
426                      this.options.linkedView.submitAddAnotherClicked.call(this.options.linkedView, e);
427                      },
428
429             submitDeleteClicked: function(e) {
430                      this.options.linkedView.deleteClicked.call(this.options.linkedView, e);
431                      },
432
433             addClicked: function(e) {
434                      this.options.linkedView.addClicked.call(this.options.linkedView, e);
435                      },
436
437             refreshClicked: function(e) {
438                      this.options.linkedView.refreshClicked.call(this.options.linkedView, e);
439                      },
440             });
441
442 XOSDetailButtonView = XOSButtonView.extend({ template: "#xos-savebuttons-template" });
443 XOSListButtonView = XOSButtonView.extend({ template: "#xos-listbuttons-template" });
444
445 /* XOSDetailView
446       extend with:
447          app - MarionetteApplication
448          template - template (See XOSHelper.html)
449 */
450
451 XOSDetailView = Marionette.ItemView.extend({
452             tagName: "div",
453
454             viewInitializers: [],
455
456             events: {"click button.btn-xos-save-continue": "submitContinueClicked",
457                      "click button.btn-xos-save-leave": "submitLeaveClicked",
458                      "click button.btn-xos-save-another": "submitAddAnotherClicked",
459                      "click button.btn-xos-delete": "deleteClicked",
460                      "change input": "inputChanged"},
461
462             /* inputChanged is watching the onChange events of the input controls. We
463                do this to track when this view is 'dirty', so we can throw up a warning
464                if the user tries to change his slices without saving first.
465             */
466
467             initialize: function() {
468                 this.on("saveSuccess", this.onAfterSave);
469                 this.synchronous = false;
470             },
471
472             onShow: function() {
473                 _.each(this.viewInitializers, function(initializer) {
474                     initializer();
475                 });
476             },
477
478             afterSave: function(e) {
479             },
480
481             onAfterSave: function(e) {
482                 this.afterSave(e);
483             },
484
485             inputChanged: function(e) {
486                 this.dirty = true;
487             },
488
489             submitContinueClicked: function(e) {
490                 console.log("saveContinue");
491                 e.preventDefault();
492                 this.afterSave = function() { };
493                 this.save();
494             },
495
496             submitLeaveClicked: function(e) {
497                 console.log("saveLeave");
498                 e.preventDefault();
499                 var that=this;
500                 this.afterSave = function() {
501                     that.app.navigate("list", that.model.modelName);
502                 }
503                 this.save();
504             },
505
506             submitAddAnotherClicked: function(e) {
507                 console.log("saveAnother");
508                 console.log(this);
509                 e.preventDefault();
510                 var that=this;
511                 this.afterSave = function() {
512                     console.log("addAnother afterSave");
513                     that.app.navigate("add", that.model.modelName);
514                 }
515                 this.save();
516             },
517
518             save: function() {
519                 this.app.hideError();
520                 var data = Backbone.Syphon.serialize(this);
521                 var that = this;
522                 var isNew = !this.model.id;
523
524                 console.log(data);
525
526                 this.$el.find(".help-inline").remove();
527
528                 /* although model.validate() is called automatically by
529                    model.save, we call it ourselves, so we can throw up our
530                    validation error before creating the infoMsg in the log
531                 */
532                 errors =  this.model.xosValidate(data);
533                 if (errors) {
534                     this.onFormDataInvalid(errors);
535                     return;
536                 }
537
538                 if (isNew) {
539                     this.model.attributes.humanReadableName = "new " + this.model.modelName;
540                     this.model.addToCollection = this.collection;
541                 } else {
542                     this.model.addToCollection = undefined;
543                 }
544
545                 var infoMsgId = this.app.showInformational( {what: "save " + this.model.modelName + " " + this.model.attributes.humanReadableName, status: "", statusText: "in progress..."} );
546
547                 this.model.save(data, {error: function(model, result, xhr) { that.app.saveError(model,result,xhr,infoMsgId);},
548                                        success: function(model, result, xhr) { that.app.saveSuccess(model,result,xhr,infoMsgId);
549                                                                                if (that.synchronous) {
550                                                                                    that.trigger("saveSuccess");
551                                                                                }
552                                                                              }});
553                 this.dirty = false;
554
555                 if (!this.synchronous) {
556                     this.afterSave();
557                 }
558             },
559
560             deleteClicked: function(e) {
561                 e.preventDefault();
562                 this.app.deleteDialog(this.model, "list");
563             },
564
565             tabClick: function(tabId, regionName) {
566                     region = this.app[regionName];
567                     if (this.currentTabRegion != undefined) {
568                         this.currentTabRegion.$el.hide();
569                     }
570                     if (this.currentTabId != undefined) {
571                         $(this.currentTabId).removeClass('active');
572                     }
573                     this.currentTabRegion = region;
574                     this.currentTabRegion.$el.show();
575
576                     this.currentTabId = tabId;
577                     $(tabId).addClass('active');
578             },
579
580             showTabs: function(tabs) {
581                 template = templateFromId("#xos-tabs-template", {tabs: tabs});
582                 $("#tabs").html(template(tabs));
583                 var that = this;
584
585                 _.each(tabs, function(tab) {
586                     var regionName = tab["region"];
587                     var tabId = '#xos-nav-'+regionName;
588                     $(tabId).bind('click', function() { that.tabClick(tabId, regionName); });
589                 });
590
591                 $("#tabs").show();
592             },
593
594             showLinkedItems: function() {
595                     tabs=[];
596
597                     tabs.push({name: "details", region: "detail"});
598
599                     makeFilter = function(relatedField, relatedId) {
600                         return function(model) { return model.attributes[relatedField] == relatedId; }
601                     };
602
603                     var index=0;
604                     for (relatedName in this.model.collection.relatedCollections) {
605                         var relatedField = this.model.collection.relatedCollections[relatedName];
606                         var relatedId = this.model.id;
607                         regionName = "linkedObjs" + (index+1);
608
609                         relatedListViewClassName = relatedName + "ListView";
610                         assert(this.app[relatedListViewClassName] != undefined, relatedListViewClassName + " not found");
611                         relatedListViewClass = this.app[relatedListViewClassName].extend({collection: xos[relatedName],
612                                                                                           filter: makeFilter(relatedField, relatedId),
613                                                                                           parentModel: this.model});
614                         this.app[regionName].show(new relatedListViewClass());
615                         if (this.app.hideTabsByDefault) {
616                             this.app[regionName].$el.hide();
617                         }
618                         tabs.push({name: relatedName, region: regionName});
619                         index = index + 1;
620                     }
621
622                     while (index<4) {
623                         this.app["linkedObjs" + (index+1)].empty();
624                         index = index + 1;
625                     }
626
627                     this.showTabs(tabs);
628                     this.tabClick('#xos-nav-detail', 'detail');
629               },
630
631             onFormDataInvalid: function(errors) {
632                 var self=this;
633                 var markErrors = function(value, key) {
634                     var $inputElement = self.$el.find("[name='" + key + "']");
635                     var $inputContainer = $inputElement.parent();
636                     //$inputContainer.find(".help-inline").remove();
637                     var $errorEl = $("<span>", {class: "help-inline error", text: value});
638                     $inputContainer.append($errorEl).addClass("error");
639                 }
640                 _.each(errors, markErrors);
641             },
642
643              templateHelpers: function() { return { modelName: this.model.modelName,
644                                                     collectionName: this.model.collectionName,
645                                                     addFields: this.model.addFields,
646                                                     listFields: this.model.listFields,
647                                                     detailFields: this.options.detailFields || this.detailFields || this.model.detailFields,
648                                                     foreignFields: this.model.foreignFields,
649                                                     detailLinkFields: this.model.detailLinkFields,
650                                                     inputType: this.model.inputType,
651                                                     model: this.model,
652                                                     detailView: this,
653                                                     choices: this.options.choices || this.choices || this.model.choices || {},
654                                          }},
655 });
656
657 XOSDetailView_sliver = XOSDetailView.extend( {
658     events: $.extend(XOSDetailView.events,
659         {"change #field_deploymentNetwork": "onDeploymentNetworkChange"}
660     ),
661
662     onShow: function() {
663         // Note that this causes the selects to be updated a second time. The
664         // first time was when the template was originally invoked, and the
665         // selects will all have the full unfiltered set of candidates. Then
666         // onShow will fire, and we'll update them with the filtered values.
667         this.onDeploymentNetworkChange();
668     },
669
670     onDeploymentNetworkChange: function(e) {
671         var deploymentID = this.$el.find("#field_deploymentNetwork").val();
672
673         console.log("onDeploymentNetworkChange");
674         console.log(deploymentID);
675
676         filterFunc = function(model) { return (model.attributes.deployment==deploymentID); }
677         newSelect = idToSelect("node",
678                                this.model.attributes.node,
679                                this.model.foreignFields["node"],
680                                "humanReadableName",
681                                false,
682                                filterFunc);
683         this.$el.find("#field_node").html(newSelect);
684
685         filterFunc = function(model) { for (index in model.attributes.deployments) {
686                                           item=model.attributes.deployments[index];
687                                           if (item.toString()==deploymentID.toString()) return true;
688                                         };
689                                         return false;
690                                      }
691         newSelect = idToSelect("flavor",
692                                this.model.attributes.flavor,
693                                this.model.foreignFields["flavor"],
694                                "humanReadableName",
695                                false,
696                                filterFunc);
697         this.$el.find("#field_flavor").html(newSelect);
698
699         filterFunc = function(model) { for (index in xos.imageDeployments.models) {
700                                            imageDeployment = xos.imageDeployments.models[index];
701                                            if ((imageDeployment.attributes.deployment == deploymentID) && (imageDeployment.attributes.image == model.id)) {
702                                                return true;
703                                            }
704                                        }
705                                        return false;
706                                      };
707         newSelect = idToSelect("image",
708                                this.model.attributes.image,
709                                this.model.foreignFields["image"],
710                                "humanReadableName",
711                                false,
712                                filterFunc);
713         this.$el.find("#field_image").html(newSelect);
714     },
715 });
716
717 /* XOSItemView
718       This is for items that will be displayed as table rows.
719       extend with:
720          app - MarionetteApplication
721          template - template (See XOSHelper.html)
722 */
723
724 XOSItemView = Marionette.ItemView.extend({
725              tagName: 'tr',
726              className: 'test-tablerow',
727
728              templateHelpers: function() { return { modelName: this.model.modelName,
729                                                     collectionName: this.model.collectionName,
730                                                     listFields: this.model.listFields,
731                                                     addFields: this.model.addFields,
732                                                     detailFields: this.model.detailFields,
733                                                     foreignFields: this.model.foreignFields,
734                                                     detailLinkFields: this.model.detailLinkFields,
735                                                     inputType: this.model.inputType,
736                                                     model: this.model,
737                                          }},
738 });
739
740 /* XOSListView:
741       extend with:
742          app - MarionetteApplication
743          childView - class of ItemView, probably an XOSItemView
744          template - template (see xosHelper.html)
745          collection - collection that holds these objects
746          title - title to display in template
747 */
748
749 XOSListView = FilteredCompositeView.extend({
750              childViewContainer: 'tbody',
751              parentModel: null,
752
753              events: {"click button.btn-xos-add": "addClicked",
754                       "click button.btn-xos-refresh": "refreshClicked",
755                      },
756
757              _fetchStateChange: function() {
758                  if (this.collection.fetching) {
759                     $("#xos-list-title-spinner").show();
760                  } else {
761                     $("#xos-list-title-spinner").hide();
762                  }
763              },
764
765              addClicked: function(e) {
766                 e.preventDefault();
767                 this.app.Router.navigate("add" + firstCharUpper(this.collection.modelName), {trigger: true});
768              },
769
770              refreshClicked: function(e) {
771                  e.preventDefault();
772                  this.collection.refresh(refreshRelated=true);
773              },
774
775              initialize: function() {
776                  this.listenTo(this.collection, 'change', this._renderChildren)
777                  this.listenTo(this.collection, 'sort', function() { console.log("sort"); })
778                  this.listenTo(this.collection, 'add', function() { console.log("add"); })
779                  this.listenTo(this.collection, 'fetchStateChange', this._fetchStateChange);
780
781                  // Because many of the templates use idToName(), we need to
782                  // listen to the collections that hold the names for the ids
783                  // that we want to display.
784                  for (i in this.collection.foreignCollections) {
785                      foreignName = this.collection.foreignCollections[i];
786                      if (xos[foreignName] == undefined) {
787                          console.log("Failed to find xos class " + foreignName);
788                      }
789                      this.listenTo(xos[foreignName], 'change', this._renderChildren);
790                      this.listenTo(xos[foreignName], 'sort', this._renderChildren);
791                  }
792              },
793
794              getAddChildHash: function() {
795                 if (this.parentModel) {
796                     parentFieldName = this.parentModel.relatedCollections[this.collection.collectionName];
797                     parentFieldName = parentFieldName || "unknown";
798
799                     /*parentFieldName = "unknown";
800
801                     for (fieldName in this.collection.foreignFields) {
802                         cname = this.collection.foreignFields[fieldName];
803                         if (cname = this.collection.collectionName) {
804                             parentFieldName = fieldName;
805                         }
806                     }*/
807                     return "#addChild" + firstCharUpper(this.collection.modelName) + "/" + this.parentModel.modelName + "/" + parentFieldName + "/" + this.parentModel.id; // modelName, fieldName, id
808                 } else {
809                     return null;
810                 }
811              },
812
813              templateHelpers: function() {
814                 return { title: this.title,
815                          addChildHash: this.getAddChildHash(),
816                          foreignFields: this.collection.foreignFields,
817                          listFields: this.collection.listFields,
818                          detailLinkFields: this.collection.detailLinkFields, };
819              },
820 });
821
822 XOSDataTableView = Marionette.View.extend( {
823     el: '<div style="overflow: hidden">' +
824         '<h3 class="xos-list-title title_placeholder"></h3>' +
825         '<div class="header_placeholder"></div>' +
826         '<table></table>' +
827         '<div class="footer_placeholder"></div>' +
828         '</div>',
829
830     filter: undefined,
831
832      events: {"click button.btn-xos-add": "addClicked",
833               "click button.btn-xos-refresh": "refreshClicked",
834              },
835
836      _fetchStateChange: function() {
837          if (this.collection.fetching) {
838             $("#xos-list-title-spinner").show();
839          } else {
840             $("#xos-list-title-spinner").hide();
841          }
842      },
843
844      addClicked: function(e) {
845         e.preventDefault();
846         this.app.Router.navigate("add" + firstCharUpper(this.collection.modelName), {trigger: true});
847      },
848
849      refreshClicked: function(e) {
850          e.preventDefault();
851          this.collection.refresh(refreshRelated=true);
852      },
853
854
855     initialize: function() {
856         $(this.el).find(".footer_placeholder").html( xosListFooterTemplate({addChildHash: this.getAddChildHash()}) );
857         $(this.el).find(".header_placeholder").html( xosListHeaderTemplate() );
858
859         this.listenTo(this.collection, 'fetchStateChange', this._fetchStateChange);
860     },
861
862     render: function() {
863         var view = this;
864
865         view.columnsByIndex = [];
866         view.columnsByFieldName = {};
867         _.each(this.collection.listFields, function(fieldName) {
868             inputType = view.options.inputType || view.inputType || {};
869             mRender = undefined;
870             mSearchText = undefined;
871             sTitle = fieldNameToHumanReadable(fieldName);
872             bSortable = true;
873             if (fieldName=="backend_status") {
874                 mRender = function(x,y,z) { return xosBackendStatusIconTemplate(z); };
875                 sTitle = "";
876                 bSortable = false;
877             } else if (fieldName in view.collection.foreignFields) {
878                 var foreignCollection = view.collection.foreignFields[fieldName];
879                 mSearchText = function(x) { return idToName(x, foreignCollection, "humanReadableName"); };
880             } else if (inputType[fieldName] == "spinner") {
881                 mRender = function(x,y,z) { return xosDataTableSpinnerTemplate( {value: x, collectionName: view.collection.collectionName, fieldName: fieldName, id: z.id, app: view.app} ); };
882             }
883             if ($.inArray(fieldName, view.collection.detailLinkFields)>=0) {
884                 var collectionName = view.collection.collectionName;
885                 mRender = function(x,y,z) { return '<a href="#' + collectionName + '/' + z.id + '">' + x + '</a>'; };
886             }
887             thisColumn = {sTitle: sTitle, bSortable: bSortable, mData: fieldName, mRender: mRender, mSearchText: mSearchText};
888             view.columnsByIndex.push( thisColumn );
889             view.columnsByFieldName[fieldName] = thisColumn;
890         });
891
892         if (!view.noDeleteColumn) {
893             deleteColumn = {sTitle: "", bSortable: false, mRender: function(x,y,z) { return xosDeleteButtonTemplate({modelName: view.collection.modelName, id: z.id}); }, mData: function() { return "delete"; }};
894             view.columnsByIndex.push(deleteColumn);
895             view.columnsByFieldName["delete"] = deleteColumn;
896         };
897
898         oTable = $(this.el).find("table").dataTable( {
899             "bJQueryUI": true,
900             "bStateSave": true,
901             "bServerSide": true,
902             "aoColumns": view.columnsByIndex,
903
904             fnServerData: function(sSource, aoData, fnCallback, settings) {
905                 var compareColumns = function(sortCols, sortDirs, a, b) {
906                     a = a[sortCols[0]];
907                     b = b[sortCols[0]];
908                     result = (a==b) ? 0 : ((a<b) ? -1 : 1);
909                     if (sortDirs[0] == "desc") {
910                         result = -result;
911                     }
912                     return result;
913                 };
914
915                 var searchMatch = function(row, sSearch) {
916                     for (fieldName in row) {
917                         if (fieldName in view.columnsByFieldName) {
918                             try {
919                                 value = row[fieldName].toString();
920                             } catch(e) {
921                                 continue;
922                             }
923                             if (value.indexOf(sSearch) >= 0) {
924                                 return true;
925                             }
926                         }
927                     }
928                     return false;
929                 };
930
931                 //console.log(aoData);
932 \r
933                 // function used to populate the DataTable with the current\r
934                 // content of the collection\r
935                 var populateTable = function()\r
936                 {\r
937                   //console.log("populatetable!");\r
938 \r
939                   // clear out old row views\r
940                   rows = [];\r
941 \r
942                   sSearch = null;\r
943                   iDisplayStart = 0;\r
944                   iDisplayLength = 1000;\r
945                   sortDirs = [];\r
946                   sortCols = [];\r
947                   _.each(aoData, function(param) {\r
948                       if (param.name == "sSortDir_0") {\r
949                           sortDirs = [param.value];\r
950                       } else if (param.name == "iSortCol_0") {\r
951                           sortCols = [view.columnsByIndex[param.value].mData];\r
952                       } else if (param.name == "iDisplayStart") {\r
953                           iDisplayStart = param.value;\r
954                       } else if (param.name == "iDisplayLength") {\r
955                           iDisplayLength = param.value;\r
956                       } else if (param.name == "sSearch") {\r
957                           sSearch = param.value;\r
958                       }\r
959                   });\r
960 \r
961                   aaData = view.collection.toJSON();\r
962 \r
963                   // apply backbone filtering on the models\r
964                   if (view.filter) {\r
965                       aaData = aaData.filter( function(row) { model = {}; model.attributes = row; return view.filter(model); } );\r
966                   }\r
967 \r
968                   var totalSize = aaData.length;\r
969 \r
970                   // turn the ForeignKey fields into human readable things\r
971                   for (rowIndex in aaData) {\r
972                       row = aaData[rowIndex];\r
973                       for (fieldName in row) {\r
974                           if (fieldName in view.columnsByFieldName) {\r
975                               mSearchText = view.columnsByFieldName[fieldName].mSearchText;\r
976                               if (mSearchText) {\r
977                                   row[fieldName] = mSearchText(row[fieldName]);\r
978                               }\r
979                           }\r
980                       }\r
981                   }\r
982 \r
983                   // apply datatables search\r
984                   if (sSearch) {\r
985                       aaData = aaData.filter( function(row) { return searchMatch(row, sSearch); });\r
986                   }\r
987 \r
988                   var filteredSize = aaData.length;\r
989 \r
990                   // apply datatables sort\r
991                   aaData.sort(function(a,b) { return compareColumns(sortCols, sortDirs, a, b); });\r
992 \r
993                   // slice it for pagination\r
994                   aaData = aaData.slice(iDisplayStart, iDisplayStart+iDisplayLength);\r
995 \r
996                   return fnCallback({iTotalRecords: totalSize,\r
997                          iTotalDisplayRecords: filteredSize,\r
998                          aaData: aaData});\r
999                 };\r
1000 \r
1001                 aoData.shift(); // ignore sEcho
1002                 populateTable();
1003
1004                 view.listenTo(view.collection, 'change', populateTable);
1005                 view.listenTo(view.collection, 'add', populateTable);
1006                 view.listenTo(view.collection, 'remove', populateTable);
1007             },
1008         } );
1009
1010         return this;
1011     },
1012
1013      getAddChildHash: function() {
1014         if (this.parentModel) {
1015             parentFieldName = this.parentModel.relatedCollections[this.collection.collectionName];
1016             parentFieldName = parentFieldName || "unknown";
1017
1018             /*parentFieldName = "unknown";
1019
1020             for (fieldName in this.collection.foreignFields) {
1021                 cname = this.collection.foreignFields[fieldName];
1022                 if (cname = this.collection.collectionName) {
1023                     parentFieldName = fieldName;
1024                 }
1025             }*/
1026             return "#addChild" + firstCharUpper(this.collection.modelName) + "/" + this.parentModel.modelName + "/" + parentFieldName + "/" + this.parentModel.id; // modelName, fieldName, id
1027         } else {
1028             return null;
1029         }
1030      },
1031
1032 });
1033
1034 idToName = function(id, collectionName, fieldName) {
1035     return xos.idToName(id, collectionName, fieldName);
1036 };
1037
1038 makeIdToName = function(collectionName, fieldName) {
1039     return function(id) { return idToName(id, collectionName, fieldName); }
1040 };
1041
1042 /* Constructs lists of <option> html blocks for items in a collection.
1043
1044    selectedId = the id of an object that should be selected, if any
1045    collectionName = name of collection
1046    fieldName = name of field within models of collection that will be displayed
1047 */
1048
1049 idToOptions = function(selectedId, collectionName, fieldName, filterFunc) {
1050     result=""
1051     for (index in xos[collectionName].models) {
1052         linkedObject = xos[collectionName].models[index];
1053         linkedId = linkedObject["id"];
1054         linkedName = linkedObject.attributes[fieldName];
1055         if (linkedId == selectedId) {
1056             selected = " selected";
1057         } else {
1058             selected = "";
1059         }
1060         if ((filterFunc) && (!filterFunc(linkedObject))) {
1061             continue;
1062         }
1063         result = result + '<option value="' + linkedId + '"' + selected + '>' + linkedName + '</option>';
1064     }
1065     return result;
1066 };
1067
1068 /* Constructs an html <select> and the <option>s to go with it.
1069
1070    variable = variable name to return to form
1071    selectedId = the id of an object that should be selected, if any
1072    collectionName = name of collection
1073    fieldName = name of field within models of collection that will be displayed
1074 */
1075
1076 idToSelect = function(variable, selectedId, collectionName, fieldName, readOnly, filterFunc) {
1077     if (readOnly) {
1078         readOnly = " readonly";
1079     } else {
1080         readOnly = "";
1081     }
1082     result = '<select name="' + variable + '" id="field_' + variable + '"' + readOnly + '>' +
1083              idToOptions(selectedId, collectionName, fieldName, filterFunc) +
1084              '</select>';
1085     return result;
1086 }
1087
1088 choicesToOptions = function(selectedValue, choices) {
1089     result="";
1090     for (index in choices) {
1091         choice = choices[index];
1092         displayName = choice[0];
1093         value = choice[1];
1094         if (value == selectedValue) {
1095             selected = " selected";
1096         } else {
1097             selected = "";
1098         }
1099         result = result + '<option value="' + value + '"' + selected + '>' + displayName + '</option>';
1100     }
1101     return result;
1102 }
1103
1104 choicesToSelect = function(variable, selectedValue, choices) {
1105     result = '<select name="' + variable + '" id="field_' + variable + '">' +
1106              choicesToOptions(selectedValue, choices) +
1107              '</select>';
1108     return result;
1109 }