
// ------------------------------------------------------------------------ //
//
// Descriptif : Awesome bootstrap checkboxes and radio : 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 exportsAw = window.Shiny = window.Shiny || {};
var $escapeAw = exportsAw.$escape = function(val) {
  return val.replace(/([!"#$%&'()*+,.\/:;<=>?@\[\\\]^`{|}~])/g, '\\$1');
};

// radioBs input binding
var awesomeRadioBinding = new Shiny.InputBinding();
$.extend(awesomeRadioBinding, {
  find: function(scope) {
    return $(scope).find('.awesome-radio-class');
  },
  getId: function(el) {
    return el.id;
  },
  getValue: function(el) {
    // Select the radio objects that have name equal to the grouping div's id
    return $('input:radio[name="' + $escapeAw(el.id) + '"]:checked').val();
  },
  setValue: function(el, value) {
    $('input:radio[name="' + $escapeAw(el.id) + '"][value="' + $escapeAw(value) + '"]').prop('checked', true);
  },
  subscribe: function(el, callback) {
    $(el).on('change.awesomeRadioBinding', function(event) {
      callback();
    });
  },
  unsubscribe: function(el) {
    $(el).off('.awesomeRadioBinding');
  },
  getState: function(el) {
    var $objs = $('input:radio[name="' + $escapeAw(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="' + $escapeAw(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.radio').remove();
      $el.append(data.options);
    }

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

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

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

Shiny.inputBindings.register(awesomeRadioBinding, 'shiny.awesomeRadio');

