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