// ------------------------------------------------------------------------ //
//
// Descriptif : Awesome bootstrap checkboxes and checkbox : javascript bindings
//     Detail : http://flatlogic.github.io/awesome-bootstrap-checkbox/demo/
//
//
// Auteur : Victor PERRIER
//
// Date creation : 01/07/2016
// Date modification : 01/07/2016
//
// Version 1.0
//
// ------------------------------------------------------------------------ //

var awesomeCheckboxBinding = new Shiny.InputBinding();
$.extend(awesomeCheckboxBinding, {
  find: function(scope) {
    return $(scope).find(".awesome-checkbox-class");
  },
  getId: function(el) {
    return el.id;
  },
  getValue: function(el) {
    // Select the checkbox objects that have name equal to the grouping div's id
    return $(
      'input:checkbox[name="' + Shiny.$escape(el.id) + '"]:checked'
    ).val();
  },
  setValue: function(el, value) {
    $(
      'input:checkbox[name="' +
        Shiny.$escape(el.id) +
        '"][value="' +
        Shiny.$escape(value) +
        '"]'
    ).prop("checked", true);
  },
  subscribe: function(el, callback) {
    $(el).on("change.awesomeCheckboxBinding", function(event) {
      callback();
    });
  },
  unsubscribe: function(el) {
    $(el).off(".awesomeCheckboxBinding");
  },
  getState: function(el) {
    var $objs = $('input:checkbox[name="' + Shiny.$escape(el.id) + '"]');

    // Store options in an array of objects, each with with value and label
    var options = new Array($objs.length);
    for (var i = 0; i < options.length; i++) {
      options[i] = { value: $objs[i].value, label: this._getLabel($objs[i]) };
    }

    return {
      label: $(el)
        .parent()
        .find('label[for="' + Shiny.$escape(el.id) + '"]')
        .text(),
      value: this.getValue(el),
      options: options
    };
  },
  receiveMessage: function(el, data) {
    var $el = $(el);

    // This will replace all the options
    if (data.hasOwnProperty("options")) {
      // Clear existing options and add each new one
      $el.find("div.shiny-options-group").remove();
      // Backward compatibility: for HTML generated by shinybootstrap2 package
      $el.find("label.checkbox").remove();
      $el.append(data.options);
    }

    if (data.hasOwnProperty("value")) this.setValue(el, data.value);

    if (data.hasOwnProperty("label"))
      $(el)
        .find(
          'label[for="' +
            Shiny.$escape(el.id) +
            Shiny.$escape(data.value) +
            '"]'
        )
        .text(data.label);

    $(el).trigger("change");
  }
});

Shiny.inputBindings.register(awesomeCheckboxBinding, "shiny.awesomeCheckbox");

