// Generated by CoffeeScript 1.9.1
(function() {
  var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    hasProp = {}.hasOwnProperty;

  define(["studiogdo/skeleton", "list/listFilter", "list/listCellForm", "list/listSelectionForm"], function(Skeleton, Filter, DefaultCellForm, DefaultSelectionForm) {
    var ListAndSelection;
    return ListAndSelection = (function(superClass) {
      var BooleanEditForm, CentEditForm;

      extend(ListAndSelection, superClass);

      function ListAndSelection(list1, selected, list_skel, selected_skel, CellForm, SelectionForm) {
        this.list = list1;
        this.selected = selected;
        this.list_skel = list_skel;
        this.selected_skel = selected_skel;
        this.CellForm = CellForm;
        this.SelectionForm = SelectionForm;
        this.deleteCallback = bind(this.deleteCallback, this);
        this.addDeleteButtons = bind(this.addDeleteButtons, this);
        this.selectLine = bind(this.selectLine, this);
        this.fnSettings = bind(this.fnSettings, this);
        this.inlineEditSelectedCallback = bind(this.inlineEditSelectedCallback, this);
        this.commitSelectedList = bind(this.commitSelectedList, this);
        this.commitSelected = bind(this.commitSelected, this);
        this.closeSelected = bind(this.closeSelected, this);
        this.drawSelectedCallback = bind(this.drawSelectedCallback, this);
        this.drawSelectedBOCallback = bind(this.drawSelectedBOCallback, this);
        this.drawSelectedBOCall = bind(this.drawSelectedBOCall, this);
        this.drawSelected = bind(this.drawSelected, this);
        this.showSelected = bind(this.showSelected, this);
        this.hideSelected = bind(this.hideSelected, this);
        this.__drawListCallback = bind(this.__drawListCallback, this);
        this.drawListCallback = bind(this.drawListCallback, this);
        this.drawListBOCallback = bind(this.drawListBOCallback, this);
        this.drawList = bind(this.drawList, this);
        this.showList = bind(this.showList, this);
        this.hideList = bind(this.hideList, this);
        this.mode = "django";
        this.path = null;
        this.selectedPath = null;
        this.bDataTable = true;
        this.sSelectionClass = "selected";
        this.sSelectionEvent = "click";
        this.sEditionEvent = "dblclick";
        this.jCellForm = null;
        this.jSelectionForm = null;
      }

      ListAndSelection.prototype.hideList = function() {
        if (this.list == null) {
          return;
        }
        $(this.list).hide().addClass("hidden");
        if (this.filter != null) {
          if (this.filter instanceof Filter) {
            return this.filter.hideFilter();
          } else {
            return $(this.filter).hide();
          }
        }
      };

      ListAndSelection.prototype.showList = function() {
        if (this.list == null) {
          return;
        }
        $(this.list).removeClass("hidden").show();
        if (this.filter != null) {
          if (this.filter instanceof Filter) {
            return this.filter.showFilter();
          } else {
            return $(this.filter).show();
          }
        }
      };

      ListAndSelection.prototype.drawList = function(path, params, after) {
        var bocall;
        if (path != null) {
          if (this.path == null) {
            this.path = path;
          }
        }
        if (path == null) {
          path = this.path;
        }
        this.hideList();
        if (this.list_skel == null) {
          this.drawListBOCallback();
          return;
        }
        bocall = new BOCall;
        bocall.done = (function(_this) {
          return function() {
            _this.drawListBOCallback(bocall);
            return typeof after === "function" ? after() : void 0;
          };
        })(this);
        return bocall.postFacet(path, this.list_skel, this.mode, params);
      };

      ListAndSelection.prototype.drawListBOCallback = function(bocall) {
        if (bocall != null) {
          $(this.list).html(bocall.responseText);
          this.drawListCallback();
        }
        return $(this.selected).empty();
      };

      ListAndSelection.prototype.drawListCallback = function() {
        var table;
        if (this.bDataTable) {
          table = $("table", this.list);
          if (table.length === 0) {
            table = $("table", this.list.parentNode);
          }
          return table.dataTable(this.fnSettings());
        } else {
          return this.__drawListCallback();
        }
      };

      ListAndSelection.prototype.__drawListCallback = function(oSettings) {
        var date, i, j, k, l, len, len1, len2, len3, len4, len5, len6, len7, m, n, nbaff, nbsel, o, p, q, ref, ref1, ref2, ref3, ref4, ref5, ref6, ref7, span, td, tr, twarn, val;
        this.hideList();
        if (this.list.querySelector("#nbaff span") != null) {
          nbaff = this.list.querySelector("#nbaff span").innerHTML;
        }
        if (this.list.querySelector("#nbsel span") != null) {
          nbsel = this.list.querySelector("#nbsel span").innerHTML;
        }
        if (nbaff !== nbsel) {
          twarn = this.list.querySelector("#table_limit_warn");
          if (twarn != null) {
            twarn.innerHTML = "Attention, la limite d’affichage a été atteinte (" + nbaff + " lignes maximum)";
          }
        }
        ref = $("tbody tr, tfoot tr", this.list);
        for (j = 0, len = ref.length; j < len; j++) {
          tr = ref[j];
          if (!(!$(tr).hasClass("initialized"))) {
            continue;
          }
          if ((this.sSelectionEvent != null) && (this.selected_skel != null)) {
            $(tr).on(this.sSelectionEvent, (function(_this) {
              return function(evt) {
                evt.preventDefault();
                return _this.drawSelected(null, $(evt.delegateTarget).closest("tr"));
              };
            })(this));
          }
          if (this.sEditionEvent != null) {
            ref1 = $("td.editable", tr);
            for (k = 0, len1 = ref1.length; k < len1; k++) {
              td = ref1[k];
              $(td).one(this.sEditionEvent, this.inlineEditSelectedCallback);
            }
          }
          ref2 = $("td.euro span, td span.euro", tr);
          for (l = 0, len2 = ref2.length; l < len2; l++) {
            span = ref2[l];
            val = $(span).text();
            $(span).text(numeral(val).format('0,0$'));
          }
          ref3 = $("td.cent span, td span.cent", tr);
          for (m = 0, len3 = ref3.length; m < len3; m++) {
            span = ref3[m];
            val = $(span).text() / 100;
            $(span).text(numeral(val).format('0,0.00$'));
          }
          ref4 = $("td.date span, td span.date", tr);
          for (n = 0, len4 = ref4.length; n < len4; n++) {
            span = ref4[n];
            date = moment($(span).text());
            if (date.isValid()) {
              moment($(span).text()).lang();
              $(span).text(date.format('L'));
            }
          }
          ref5 = $("td.time span, td span.time", tr);
          for (o = 0, len5 = ref5.length; o < len5; o++) {
            span = ref5[o];
            date = moment($(span).text(), ['HH:mm', 'HH:mm:ss', 'hh:mm', 'hh:mm:ss']);
            if (date.isValid()) {
              $(span).text(date.format('LT'));
            }
          }
          ref6 = $("td.datetime span, td span.datetime", tr);
          for (p = 0, len6 = ref6.length; p < len6; p++) {
            span = ref6[p];
            date = moment($(span).text());
            if (date.isValid()) {
              $(span).text(date.format('LLL'));
            }
          }
          ref7 = $("td.boolean span", tr);
          for (q = 0, len7 = ref7.length; q < len7; q++) {
            span = ref7[q];
            $(span).hide();
            i = $('<i></i>').appendTo($(span).parent());
            val = $(span).text();
            if (val === 'true') {
              i.addClass("icon-ok");
            } else {
              i.addClass("icon-plus-sign");
            }
          }
          $(tr).addClass("initialized");
        }
        return this.showList();
      };

      ListAndSelection.prototype.hideSelected = function() {
        return $(this.selected).hide().addClass("hidden");
      };

      ListAndSelection.prototype.showSelected = function() {
        return $(this.selected).removeClass("hidden").show();
      };

      ListAndSelection.prototype.drawSelected = function(data, tr, after) {
        var path;
        this.hideSelected();
        if (this.jSelectionForm == null) {
          if (this.SelectionForm != null) {
            this.jSelectionForm = new this.SelectionForm(this);
          } else {
            this.jSelectionForm = new DefaultSelectionForm(this);
          }
        }
        if (tr == null) {
          tr = $("tr." + this.sSelectionClass, this.list);
        }
        if (tr.length > 0) {
          path = tr.data("apath");
          this.selectLine(tr);
        } else {
          path = this.jSelectionForm.path;
        }
        if (path == null) {
          return;
        }
        this.selectedPath = path;
        return this.drawSelectedBOCall(data, after);
      };

      ListAndSelection.prototype.drawSelectedBOCall = function(data, after) {
        var bocall, error;
        bocall = new BOCall;
        error = bocall.error;
        bocall.error = (function(_this) {
          return function(info) {
            _this.showSelected();
            return typeof error === "function" ? error(info) : void 0;
          };
        })(this);
        bocall.done = (function(_this) {
          return function() {
            _this.drawSelectedBOCallback(bocall);
            return typeof after === "function" ? after() : void 0;
          };
        })(this);
        return bocall.postFacet(this.selectedPath, this.jSelectionForm.skel, this.mode, data);
      };

      ListAndSelection.prototype.drawSelectedBOCallback = function(bocall) {
        if (this.selected == null) {
          alert('No selection holder defined for the list');
          return;
        }
        this.hideSelected();
        $(this.selected).html(bocall.responseText);
        if (this.jSelectionForm != null) {
          this.jSelectionForm.showSelectedCallback(this.selected);
        }
        return this.drawSelectedCallback();
      };

      ListAndSelection.prototype.drawSelectedCallback = function() {
        return this.showSelected();
      };

      ListAndSelection.prototype.closeSelected = function() {
        this.jSelectionForm = null;
        return $(this.selected).empty();
      };

      ListAndSelection.prototype.commitSelected = function(params, after) {
        var data;
        data = new FormData(this.selected.querySelector("form"));
        return this.drawSelected(data);
      };

      ListAndSelection.prototype.commitSelectedList = function(params, after) {
        var data, key, value;
        data = new FormData(this.selected.querySelector("form"));
        for (key in params) {
          value = params[key];
          data.append(key, value);
        }
        return this.drawList(this.path, data, (function(_this) {
          return function() {
            if (typeof after === "function") {
              after();
            }
            return _this.closeSelected();
          };
        })(this));
      };

      ListAndSelection.prototype.inlineEditSelectedCallback = function(evt) {
        var form, ref, span, td;
        td = evt.currentTarget;
        $(td).one(this.sEditionEvent, this.inlineEditSelectedCallback);
        span = td.querySelector("span");
        if (span == null) {
          return;
        }
        form = td.querySelector("form");
        if (form == null) {
          return;
        }
        if (span.innerText === '') {
          form.classList.remove("hidden");
        }
        if ((ref = this.jCellForm) != null) {
          ref.close();
        }
        if (this.CellForm != null) {
          return this.jCellForm = new this.CellForm(this, span, form);
        } else {
          this.jCellForm = new DefaultCellForm(this, span, form);
          this.jCellForm.firstFocus();
          return this.jCellForm.commit = (function(_this) {
            return function(evt, list) {
              var fdata;
              fdata = new FormData(form);
              _this.drawList(_this.path, fdata);
              return _this.jCellForm = null;
            };
          })(this);
        }
      };

      ListAndSelection.prototype.fnSettings = function() {
        return {
          "aaSorting": [],
          'aLengthMenu': [[10, 25, 100, 500, -1], [10, 25, 100, 500, 'Tous']],
          "bStateSave": true,
          "bLengthChange": true,
          "iDisplayLength": 10,
          "fnDrawCallback": this.__drawListCallback,
          "sDom": "Tlfrtip<'clear'>",
          "sPaginationType": "full_numbers",
          "oLanguage": {
            "sLengthMenu": "Afficher _MENU_ lignes par page",
            "sZeroRecords": "Pas trouvé..",
            "sInfo": "Affichage de _START_ à _END_ sur _TOTAL_ lignes",
            "sInfoEmpty": "Affichage de 0 à 0 sur 0 lignes",
            "sInfoFiltered": "(filtrage sur _MAX_ lignes)",
            "sSearch": "Rechercher",
            "oPaginate": {
              "sFirst": "&nbsp;&nbsp;&nbsp;",
              "sLast": "&nbsp;&nbsp;&nbsp;",
              "sNext": "&nbsp;&nbsp;&nbsp;",
              "sPrevious": "&nbsp;&nbsp;&nbsp;"
            }
          }
        };
      };

      ListAndSelection.prototype.selectLine = function(selected_tr) {
        var j, len, ref, tr;
        if (this.sSelectionClass != null) {
          ref = $("tr", this.list);
          for (j = 0, len = ref.length; j < len; j++) {
            tr = ref[j];
            $(tr).removeClass(this.sSelectionClass);
          }
          return $(selected_tr).addClass(this.sSelectionClass);
        }
      };

      ListAndSelection.prototype.addDeleteButtons = function(msg, where) {

        /*
        Adds delete button on each line.
        Should be added after showListCallback
            showListCallback: (oSettings) =>
            super(oSettings)
            @addDeleteButtons()
         */
        var askConfirmation, button, j, len, ref, results, td;
        if (msg == null) {
          msg = "Voulez-vous réellement faire cette action?";
        }
        if (where == null) {
          where = "tbody tr > td:last-child";
        }
        askConfirmation = (function(_this) {
          return function(evt) {
            var tr;
            evt.stopImmediatePropagation();
            evt.preventDefault();
            if (confirm("Confirmation : " + msg)) {
              tr = $(evt.delegateTarget).closest("tr");
              return _this.deleteCallback(tr.data("apath"));
            }
          };
        })(this);
        ref = this.list.querySelectorAll(where);
        results = [];
        for (j = 0, len = ref.length; j < len; j++) {
          td = ref[j];
          if (!(!(td.classList.contains("dataTables_empty") || td.classList.contains("delete_button")))) {
            continue;
          }
          button = $('<span alt="Détruire" title="Détruire" class="glyphicon glyphicon-trash small"/>').appendTo(td);
          button.css('float', 'right');
          $(td).addClass("delete_button");
          results.push(button.on("click", askConfirmation));
        }
        return results;
      };

      ListAndSelection.prototype.deleteCallback = function(path) {
        var bocall;
        bocall = new BOCall;
        bocall.done = (function(_this) {
          return function() {
            return _this.drawList();
          };
        })(this);
        return bocall.applyCommand(path, "Unplug");
      };

      BooleanEditForm = (function(superClass1) {
        extend(BooleanEditForm, superClass1);

        function BooleanEditForm() {
          this.commit = bind(this.commit, this);
          BooleanEditForm.__super__.constructor.apply(this, arguments);
          this.firstFocus();
        }

        BooleanEditForm.prototype.commit = function(evt, list) {
          var bo, input, td;
          list.editForm = null;
          td = getParentByTagName(evt.target, "TD", true);
          if (!td.classList.contains("boolean")) {
            BooleanEditForm.__super__.commit.apply(this, arguments);
            return;
          }
          bo = new BOCall;
          bo.done = (function(_this) {
            return function() {
              return _this.value.innerHTML = bo.responseText;
            };
          })(this);
          input = evt.target.tagName === 'INPUT' ? evt.target : evt.target.querySelector('INPUT');
          bo.appendBOParam("i_" + td.dataset.apath, input.value);
          return bo.postProp(td.dataset.apath);
        };

        return BooleanEditForm;

      })(DefaultCellForm);

      CentEditForm = (function(superClass1) {
        extend(CentEditForm, superClass1);

        function CentEditForm() {
          this.commit = bind(this.commit, this);
          CentEditForm.__super__.constructor.apply(this, arguments);
          this.firstFocus();
        }

        CentEditForm.prototype.commit = function(evt, list) {
          var bo, input, td;
          list.editForm = null;
          td = getParentByTagName(evt.target, "TD", true);
          if (!td.classList.contains("cent")) {
            CentEditForm.__super__.commit.apply(this, arguments);
            return;
          }
          bo = new BOCall;
          bo.done = (function(_this) {
            return function() {
              return _this.value.innerHTML = bo.responseText;
            };
          })(this);
          input = evt.target.tagName === 'INPUT' ? evt.target : evt.target.querySelector('INPUT');
          bo.appendBOParam("i_" + td.dataset.apath, input.value);
          return bo.postProp(td.dataset.apath);
        };

        return CentEditForm;

      })(DefaultCellForm);

      return ListAndSelection;

    })(Skeleton);
  });

}).call(this);
