(function ($) {
  $.fn.fauxInput = function (options) {
    this.filter('input:radio, input:checkbox').each(function () {
      var input      = $(this),
          inputType  = input.attr('type'),
          inputId    = input.attr('id'),
          inputName  = input.attr('name'),
          label      = $('label[for=' + inputId + ']'),
          labelText  = label.text(),
          template   = options.template,
          fauxInputHtml,
          fauxInput;

      fauxInputHtml = options.template;
      fauxInputHtml = fauxInputHtml.replace('{inputId}', inputId);
      fauxInputHtml = fauxInputHtml.replace('{inputName}', inputName);
      fauxInputHtml = fauxInputHtml.replace('{inputLabel}', labelText);

      fauxInput = $(fauxInputHtml);

      input.after(fauxInput);

      if (template.match('{inputLabel}')) {
        label.css({'display': 'none'});
      }

      input.css({'position': 'absolute', 'visibility': 'hidden'});

      fauxInput.addClass(inputType);
      fauxInput.addClass(input.attr('checked') ? 'checked' : '');

      fauxInput.bind('click.fauxinput', function () {
        var willBeChecked = !input.attr('checked');

        if (inputType == 'radio' && willBeChecked) {
          fauxInput.addClass('checked');

          input.attr('checked', willBeChecked);

          $('span.radio').filter(function () {
            var filteredSpan = $(this);
            return (filteredSpan.attr('data-name') == inputName && filteredSpan.attr('data-id') != inputId);
          }).each(function () {
            $(this).removeClass('checked');
          });

        } else if (inputType == 'checkbox') {
          if (willBeChecked) {
            fauxInput.addClass('checked');
          } else {
            fauxInput.removeClass('checked');
          }

          input.attr('checked', willBeChecked);
        }

        input.click(); //fire the eventhandlers for the associated 'real' input element
      })
    });

    return this;
  }
})(jQuery);
