// Self-calling function that passes in an anonymous jQuery 1.9.1 for use with
// the $ variable.
(function($) {

  $(function() { try {

    // Remove duplicate ID attributes … likely they’re all from Rails auto-generated form fields any way.
    // We’ll keep the ID on the first element in the DOM that has it.
    var allIds = $('[id]').toArray().map(function(el) { return $(el).attr('id'); });
    var duplicateIds = allIds.filter(function(a, i) {
      return allIds.indexOf(a) === i && allIds.lastIndexOf(a) !== i;
    });
    $.each(duplicateIds, function() {
      $('[id='+this+']:gt(0)').removeAttr('id');
    });


    // Create special “Learn more” buttons for each slide that has a link
    var moreText = $('#learn-more-text').data('learn-more');
    $('.ss-text-scroller .ss-link-wrapper').each(function() {
      var $textBox = $(this).children('.ss-text-box');
      $textBox.append(
        $('<span class="ss-link-button o-button o-button--small u-theme--background-color--base">' +
          moreText +
          '</span>'
        )
      );
    });


    // This adds the correct amount of height to the mobile slideshow text.
    if ($(window).width() < 700) {
      var $elems = $( ".ss-text-box" ),
          tallestDivHeight = 0;

      $elems.each(function() {
        var $t = $(this),
            thisDivsHeight = $t.outerHeight();

        if (thisDivsHeight > tallestDivHeight) tallestDivHeight = thisDivsHeight;
      });

      $( ".ss-text-scroller", ".c-page-header__feature" ).css({ 'min-height': tallestDivHeight });
    }


    // Remove all empty widget containers
    $('.WidgetContainer').filter(':empty').remove();



    // Helper functions for transforming widgets into ALPS theme blocks

    // Makes a block wrapper. This is what most #content_from_widget_above & #content_from_widget_below widgets will be
    // transformed into.
    function makeBlockWrapper(contents) {
      var $wrapper;
      $wrapper = $('<div class="c-block-wrap u-spacing"></div>');

      if (contents.$title) {
        $wrapper.append(
          $('<div class="c-block__heading u-theme--border-color--darker"></div>')
            .append(contents.$title
              .addClass('c-block__heading-title u-theme--color--darker')
            )
        );
      }

      if (contents.$blocks) {
        $wrapper.append(
          $('<div class="c-block-wrap__content u-spacing"></div>')
            .append(contents.$blocks)
        );
      }

      return $wrapper;
    }

    // Makes a simple content block following the Content Block molecule from ALPS v3.
    // https://alps.adventist.io/v3/?p=molecules-content-block
    function makeContentBlock(contents) {
      var $block;
      $block = $('<div class="c-block c-block__text u-theme--border-color--darker u-border--left u-spacing--half"></div>');

      if (contents.$img) {
        $block.append(contents.$img.addClass('c-block__image').removeAttr('style'));
        $block.addClass('has-image u-clear-fix');
      }

      if (contents.$title) {
        contents.$title
          .addClass('u-theme--color--darker u-font--primary--m')
          .contents().filter(function() {
            return this.nodeType === 3 && $.trim($(this).text()).length > 0;
          }).wrap('<strong></strong>');
        contents.$title.find('a')
          .addClass('c-block__title-link u-theme--link-hover--dark')
          .wrapInner('<strong></strong>');
        $block.append(contents.$title);
      }

      if (contents.$description) {
        if (!contents.$description.is('p')) {
          contents.$description.contents().filter(function() {
            return this.nodeType === 3 && $.trim($(this).text()).length > 0;
          }).wrap('<p></p>');
        }
        $block.append(
          contents.$description.addClass('c-block__body text')
        );
      }

      return $block;
    }

    // Makes a stacked media block following the Media Block Stacked molecule from ALPS v3.
    // https://alps.adventist.io/v3/?p=molecules-media-block-stacked
    function makeStackedMediaBlock(contents) {
      var $block, $content;
      $block = $('<div class="c-media-block c-block c-block__stacked c-media-block__stacked" />');

      if (contents.$img) {
        $image = $('<div class="c-media-block__image c-block__image" />')
        $block.append($image);

        if (contents.$img.is('img')) {
          $image.append('<div class="c-block__image-wrap" />')
            .append(contents.$img);
        } else {
          $image.append(contents.$img.addClass('c-block__image-wrap'));
        }
      }

      if (contents.$title || contents.$description) {
        $block.append('<div class="c-media-block__content c-block__content u-spacing u-color--gray" />')
          .append('<div class="u-spacing c-block__group c-media-block__group" />')
            .append('<div class="u-spacing u-width--100p c-block__main-content" />');
        $content = $block.find('.c-block__main-content');
      }

      if (contents.$title) {
        if (contents.$title.is('h3,h4')) {
          $content.append(contents.$title
            .addClass('c-media-block__title c-block__title u-theme--color--darker')
          );
        } else {
          $content.append($('<h3 class="c-media-block__title c-block__title u-theme--color--darker" />')
            .append(contents.$title)
          );
        }
        $block.find('.c-block__title a')
          .addClass('c-block__title-link u-theme--link-hover--dark');
      }

      if (contents.$description) {
        if (contents.$description.is('div,p')) {
          $content.append(contents.$description
            .addClass('c-media-block__description c-block__description')
          );
        } else {
          $content.append($('<p class="c-media-block__description c-block__description" />')
            .append(contents.$description)
          );
        }
      }

      return $block;
    }

    // Makes a content block slider as seen in the Testimonies organism in ALPS v3.
    // https://alps.adventist.io/v3/?p=organisms-testimonies
    function makeContentBlockSlider(contents) {
      var $block;
      $block = $('<div class="u-spacing u-position--relative"></div>');

      if (contents.$title) {
        $block.append(
          // using .u-space--zero--bottom instead of .u-space--bottom or .u-space--double--bottom because the margins
          // are not collapsing between this element and the next.
          $('<div class="c-block__heading u-theme--border-color--darker u-space--zero--bottom"></div>')
            .append(contents.$title.addClass('c-block__heading-title u-theme--color--darker'))
        );
      }

      if (contents.$blocks) {
        $block.append(
          $('<div class="l-grid l-grid-wrap l-grid-wrap--3-of-7 js-carousel__multi-item"></div>')
            .append(contents.$blocks)
        );
        contents.$blocks
          .wrap('<div class="l-grid-item--3-col l-grid-item--l--1-col u-space--bottom u-padding--zero--sides"></div>')
          .addClass('u-padding--right u-padding--left u-border--left u-theme--border-color--darker u-spacing--half');
      }

      return $block;
    }

    // Makes a generic form block following the style of the Search Filter molecule from ALPS v3.
    // https://alps.adventist.io/v3/?p=molecules-search-filter
    function makeFormBlock(contents) {
      var $block;
      $block = $('<div class="u-spacing u-background-color--gray--light u-padding u-theme--border-color--darker u-border--left can-be--dark-dark"></div>');

      if (contents.$form) {
        if (contents.fields) {
          $.each(contents.fields, function(_, field) {
            var $field = $('<div class="u-spacing--quarter form-input" />');

            if (field.label) {
              $field.append($('<label class="u-font--secondary--s" />').text(field.label));
            }

            $field.append(field.$field);
            contents.$form.append($field);
          });
        }

        if (contents.$submit) {
          contents.$form.append(
            $('<p class="u-space--left form-submit"></p>')
              .append(contents.$submit.addClass('submit'))
          );
        }

        $block.append(contents.$form);
      }

      if (contents.$description) {
        $block.append(contents.$description.addClass('text'));
      }

      return $block;
    }

    // Makes an inline form block following the Inline Form molecule from ALPS v3 and mixing it with the Search Filter
    // molecule from ALPS v3.
    // Inline Form: https://alps.adventist.io/v3/?p=molecules-inline-form
    // Search Filter: https://alps.adventist.io/v3/?p=molecules-search-filter
    function makeInlineFormBlock(contents) {
      var $block;
      $block = makeFormBlock(contents);

      $block.find('form').addClass('c-form--inline');

      if (contents.fields) {
        $block.find('.form-input').each(function() {
          var $wrapper  = $(this);
          var $contents = $wrapper.contents();
          var fieldType = $wrapper.is('.form__checkbox')  ? 'checkbox'  :
                          $wrapper.is('.form__radio')     ? 'radio'     :
                          $wrapper.is('.form__select')    ? 'select'    :
                                                            'other';
          $wrapper.before($contents).remove();
          $contents.filter('input, textarea, select').addClass('form-input');
          if ($contents.filter('input').length) {
            $contents.filter('input').attr('placeholder', $contents.filter('label').detach().text());
          }
        });
      }

      return $block;
    }


    $('#rightsidebar, #leftsidebar')
      .addClass('u-padding--right u-spacing--double');

    $('#content_from_widget_above, #content_from_widget_below')
      .addClass('c-article u-spacing--triple');



    // Widget-specific block transformations

    // Adventist ID widgets
    $('.widget-adventist-id-adventist-beliefs, .widget-adventist-id-living-the-adventist-life').each(function() {
      var $widget = $(this).find('.widgetdiv4');

      $widget.replaceWith(makeBlockWrapper({
        $title: $widget.find('.widgettitle'),
        $blocks: $widget.find('.widgetcontent')
      }));
    });

    // Adventist News Network widget
    $('.widget-adventist-news-network').each(function() {
      var $widget = $(this).find('.widgetdiv4');

      $widget.find('.ann-widget').replaceWith(function() {
        var $block = $(this);
        return makeContentBlock({
          $title: $block.find('> h4'),
          $img: $block.find('> img'),
          $description: $block.find('> p')
        });
      });

      $widget.replaceWith(makeBlockWrapper({
        $title: $widget.find('.widgettitle'),
        $blocks: $widget.find('.c-block')
      }));
    });

    // Bible Info widget
    $('.widget-bibleinfo').each(function() {
      var $widget = $(this).find('.widgetdiv4');

      $widget.replaceWith(makeBlockWrapper({
        $title: $widget.find('.widgettitle'),
        $blocks: makeInlineFormBlock({
          $form: $widget.find('.bibleinfo-widget > .widgetcontent > form'),
          fields: [
            {
              $field: $widget.find('.text_field').removeAttr('id').detach(),
              label: $widget.find('label').detach().text()
            }
          ],
          $submit: $widget.find('.submitbutton').detach(),
          $description: $widget.find('.bibleinfo-widget > .widgetcontent > p')
        })
      }));
    });

    // Events widget
    $('.widget-events-widget').each(function() {
      var $widget = $(this).find('.widgetdiv4');

      $widget.find('.ContentTitle').contents().unwrap().wrap('<strong/>');
      $widget.has('.EventInfo').replaceWith(makeBlockWrapper({
        $title: $widget.find('.widgettitle'),
        $blocks: makeContentBlock({$description: $widget.find('.EventInfo')})
      }));
    });

    // Feed Aggregator widget
    $('.widget-feed-aggregator-widget').each(function() {
      var $widget = $(this).find('.widgetdiv4');

      $widget.find('.ArticleWidgetBlock').replaceWith(function() {
        var $block = $(this);
        return makeContentBlock({
          $title: $block.find('.AbstractTitle'),
          $description: $block.find('> p')
        });
      });

      $widget.replaceWith(makeBlockWrapper({
        $title: $widget.find('.widgettitle'),
        $blocks: $widget.find('.c-block')
      }));
    });

    // Forms widget
    $('.widget-forms-widget').each(function() {
      var $widget   = $(this).find('.widgetdiv4');
      var $contents = $widget.find('.widgetcontent');

      // Give it a stylish gray background and the classic left border:
      $contents.addClass('u-spacing u-background-color--gray--light u-padding u-theme--border-color--darker u-border--left');

      // No more floaters!
      $contents.find('.float-left-field').removeClass('float-left-field');
      $contents.find('.clear, .clear-floated-field').remove();

      // Let’s get some spacing
      $contents.find('form').removeClass('forms').addClass('u-spacing--double')
        .find('.errorExplanation').css('margin-top', 0);
      $contents.find('.fieldset').addClass('u-spacing');
      $contents.find('.errorExplanation:empty')
        .nextAll('.fieldset').first().css('margin-top', 0);

      $widget.replaceWith(makeBlockWrapper({
        $title: $widget.find('.widgettitle'),
        $blocks: $contents
      }));
    });

    // Gracenotes widget
    $('.widget-grace-notes').each(function() {
      var $widget = $(this).find('.widgetdiv4');

      $widget.find('.gracenotes-widget').replaceWith(function() {
        var $block = $(this);
        return makeContentBlock({
          $title: $block.find('> h4'),
          $img: $block.find('> img'),
          $description: $block.find('> p')
        });
      });

      $widget.replaceWith(makeBlockWrapper({
        $title: $widget.find('.widgettitle'),
        $blocks: $widget.find('.c-block')
      }));
    });

    // Live Media widget
    $('.widget-live-media-widget').each(function() {
      var $widget = $(this).find('.widgetdiv4');

      $widget.find('.livemedia-widget').wrapInner('<div />')
        .replaceWith(function() {
          return makeContentBlock({ $description: $(this).find('> div') });
        });

      $widget.replaceWith(makeBlockWrapper({
        $title: $widget.find('.widgettitle'),
        $blocks: $widget.find('.c-block')
      }));
    });

    // Login widget
    $('.widget-login-widget').each(function() {
      var $widget = $(this).find('.widgetdiv4');

      $widget.find('.login-widget').replaceWith(function() {
        var $block = $(this);
        return makeContentBlock({
          $title: $block.find('p').first(),
          $description: $block.find('> *:nth-of-type(n+1)')
        });
      });

      $widget.replaceWith(makeBlockWrapper({
        $title: $widget.find('.widgettitle'),
        $blocks: $widget.find('.c-block')
      }));
    });

    // Media Hub widget ("list of media")
    $('.widget-media-hub').has('.media_widget_list').each(function() {
      var $widget = $(this).find('.widgetdiv4');

      $widget.find('.media_widget_list .media_asset')
        .replaceWith(function() {
          $block = $(this);
          return makeStackedMediaBlock({
            $img: $block.find('.ma_image'),
            $title: $block.find('.media-title'),
            $description: $block.find('.media-presenter')
          });
        });

      $widget.replaceWith(makeContentBlockSlider({
        $title: $widget.find('.widgettitle'),
        $blocks: $widget.find('.media_widget_list > .c-media-block')
      }));
    });

    // Media Hub widget ("list of channels")
    $('.widget-media-hub').has('.channels_list').each(function() {
      var $widget = $(this).find('.widgetdiv4');

      $widget.find('ul.channels_list').contents().unwrap()
        .filter('li').wrap('<p class="text">').contents().unwrap();
    });

    // Sabbath Time widget
    $('.widget-sabbath-time').each(function() {
      var $widget = $(this).find('.widgetdiv4');

      var $title  = $widget.find('.widgettitle');
      var $block  = $widget.find('.sabbathtime-widget');
      var $place  = $block.find('p:first-of-type');
      var $desc   = $block.find('p:nth-of-type(n+1)');

      $place.find('strong').remove();

      $widget.replaceWith(makeStackedMediaBlock({
        $img: $block.find('img'),
        $title: $title.add($place),
        $description: $desc
      }));
    });

    // Static Content widget
    $('.widget-static-content-widget').each(function() {
      var $widget = $(this).find('.widgetdiv4');

      $widget.find('.ContentInfo').wrapInner('<div />')
        .replaceWith(function() {
          return makeContentBlock({ $description: $(this).find('> div') });
        });

      $widget.replaceWith(makeBlockWrapper({
        $title: $widget.find('.widgettitle'),
        $blocks: $widget.find('.c-block')
      }));
    });
    $('#content_from_widget_above, #content_from_widget_below')
      .find('.widget-static-content-widget .c-block__body')
        .addClass('u-spacing');
    $('#leftsidebar, #rightsidebar, #sidebar_breakout')
      .find('.widget-static-content-widget .c-block__body')
        .addClass('u-spacing--half u-font--primary--s');

    // Who’s Online widget
    $('.widget-whos-online-widget').each(function() {
      var $widget = $(this).find('.widgetdiv4');

      $widget.wrapInner('<div class="find-me" />');

      $widget.replaceWith(makeBlockWrapper({
        $title: $widget.find('.widgettitle').detach(),
        $blocks: makeContentBlock({
          $description: $widget.find('.find-me')
        })
      }));
    });


    // Overrides & catch-alls
    var $containers = $('#leftsidebar, #rightsidebar, #sidebar_breakout, #content_from_widget_above, #content_from_widget_below');
    $containers.find('.widgetdiv4')
      .contents().filter(function() {
        return this.nodeType === 3 && $.trim($(this).text()).length > 0;
      }).wrap('<p></p>').end().end()
      .addClass('u-spacing')
        .children(':not(.c-block__heading, .widgettitle, script, .calendar-widget)')
          .addClass('c-block-wrap__content c-block c-block__text c-block__body u-border--left u-color--gray u-theme--border-color--darker--left u-spacing--half')
        .end()
      .end()
      .find(':not(.c-block__heading) > .widgettitle')
        .addClass('c-block__heading-title u-theme--color--darker')
        .wrap('<div class="c-block__heading u-theme--border-color--darker" />')
      .end()
      .find('form')
        .addClass('u-spacing--double')
        .closest('.c-block')
          .addClass('u-background-color--gray--light u-padding')
        .end()
      .end()
      .find('.c-block-wrap__content > .c-block__heading')
        .each(function() { $(this).insertBefore($(this).parent()); })
      .end()
      .find('*').not('.text')
        .find('ul, ol').filter(function() { return $(this).closest('.c-block-wrap, .accordion-content').length == 0 })
          .parent()
            .addClass('u-spacing')
          .end()
          .wrap('<div class="text" />')
        .end().end()
        .find('ul, ol').filter(function() { return $(this).closest('.c-block-wrap, .accordion-content').length > 0 })
          .addClass('text')
        .end().end()
        .find('p').not('.text')
          .addClass('text')
        .end().end()
      .end().end();

    $('.c-article__body > div, .c-article__body li > div').addClass('text u-spacing c-block__body');

    $('.widget-recipes')
      .find('.recipe_image img').unwrap().wrap('<p class="text" />').end()
      .find('.recipes_info').removeClass('recipes_info');


    $('#sidebar_breakout')
      .find('.widgetdiv3')
        .find('.text, .c-block__main-content > *').not('.c-block__title')
          .addClass('u-theme--color--lighter')
        .end().end()
        .find('button, .btn')
          .addClass('o-button--lighter')
        .end()
        .find('h1, h6, .c-block__title, .c-block__heading-title')
          .removeClass('u-theme--color--darker')
          .addClass('u-color--white')
        .end()
        .find('.widgetcontent')
          .addClass('u-spacing')
            .children().not('button, .btn, .o-button, .o-button--lighter')
              .addClass('u-theme--color--lighter')
            .end()
          .end()
        .end();



    // Adventist ID widgets
    $('#content_from_widget_above, #content_from_widget_below')
      .find('.widget-adventist-id-adventist-beliefs, .widget-adventist-id-living-the-adventist-life')
      .each(function() {
        $widget = $(this);
        $widget.find('.widgetcontent p')
          .addClass('c-block__body text')
          .prependTo($widget.find('.c-block-wrap__content'));
        $widget.find('.c-block-wrap__content')
          .wrapInner('<div class="find-me"><div class="and-me-too u-spacing" /></div>')
          .find('.find-me').replaceWith(function() {
            return makeContentBlock({
              $description: $(this).find('.and-me-too')
            });
          });
        $widget.find('.and-me-too').removeClass('text');
        $widget.find('li.adventist-life-callout')
          .replaceWith(function() {
            $callout = $(this);
            $callout.find('a').contents().filter(function() {
              return this.nodeType === 3 && $.trim($(this).text()).length > 0;
            }).wrap('<span class="adventist-life-callout__text"></span>');
            return $('<div class="adventist-life-callout l-grid-item--3-col l-grid-item--m--1-col" />')
              .attr('id', $callout.attr('id'))
              .append($callout.contents());
          });
        $widget.find('ul.cf').replaceWith(function() {
          return $('<div class="l-grid"></div>').append($(this).contents());
        });
      });

    $('.widget-adventist-id-adventist-beliefs, .widget-adventist-id-living-the-adventist-life')
      .find('.btn-go')
        .append('<span class="u-icon u-icon--m u-path-fill--base u-space--half--left"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 96.35 82.35"><path d="M70.87,66.46A10.22,10.22,0,0,1,60.65,76.68H15.89A10.22,10.22,0,0,1,5.67,66.46h0V21.71A10.22,10.22,0,0,1,15.89,11.49H53.6c.93-.22,1.82-.41,2.66-.57l-1.39-5.1h-39A15.91,15.91,0,0,0,0,21.71V66.46A15.91,15.91,0,0,0,15.89,82.35H60.64a15.91,15.91,0,0,0,15.9-15.89V47.19l-5.67,4Z" fill="#ffffff"/><path d="M95.34,23.7,62.43.73C60.34-.73,59.19.08,59.86,2.54L63.47,15.8s-39,0-36.54,42.45C37.44,31.81,63.81,33.78,63.81,33.78l-4,14.53c-.67,2.46.48,3.27,2.57,1.81l32.9-23a2,2,0,0,0,.06-3.42Z" fill="#ffffff"/></svg></span>').end()
      .find('.go')
        .append('<span class="u-icon u-icon--m u-path-fill--base"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 96.35 82.35"><path d="M70.87,66.46A10.22,10.22,0,0,1,60.65,76.68H15.89A10.22,10.22,0,0,1,5.67,66.46h0V21.71A10.22,10.22,0,0,1,15.89,11.49H53.6c.93-.22,1.82-.41,2.66-.57l-1.39-5.1h-39A15.91,15.91,0,0,0,0,21.71V66.46A15.91,15.91,0,0,0,15.89,82.35H60.64a15.91,15.91,0,0,0,15.9-15.89V47.19l-5.67,4Z" fill="#ffffff"/><path d="M95.34,23.7,62.43.73C60.34-.73,59.19.08,59.86,2.54L63.47,15.8s-39,0-36.54,42.45C37.44,31.81,63.81,33.78,63.81,33.78l-4,14.53c-.67,2.46.48,3.27,2.57,1.81l32.9-23a2,2,0,0,0,.06-3.42Z" fill="#ffffff"/></svg></span>');

    $('#adventistSpirituality > a')
      .prepend('<span class="u-icon u-icon--l u-path-fill--dark"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 67 67"><path d="M33.5,0a33.5,33.5,0,0,0-.25,67h.25a33.5,33.5,0,0,0,0-67ZM6.56,21l14.28,7.21.37-.82L8.38,17.67A30,30,0,0,1,16.76,9L26,22.53l.84-.49L20,7A29.5,29.5,0,0,1,31.68,3.85L33,20.5H34L35.47,3.87A29.49,29.49,0,0,1,47.09,7.09L40.33,22l.77.44L50.34,9a30,30,0,0,1,8.32,8.69L45.38,26.63l.46.8,14.64-6.35a29.49,29.49,0,0,1,2.71,11.4H45.42a12,12,0,0,0-23.69,0H3.82A29.51,29.51,0,0,1,6.56,21Zm35,11.47H31v0l-.08,0h-5.3a8.21,8.21,0,0,1,16,0ZM3.93,36.26H28.67c-5,2.53-9.37,6-9.62,11-.23,4.57,3,9.44,6.5,14.6l.21.31A29.77,29.77,0,0,1,3.93,36.26ZM33.5,63.21c-.87,0-1.74,0-2.6-.12-.73-1.13-1.47-2.24-2.2-3.33-3.1-4.62-6.54-10.08-6.44-13.4.16-5.53,6.71-9,8.83-10.1h3c-3.41,3.22-4.19,6-4.2,8.18,0,3.09,2.4,5.58,5.32,7.61,4,2.78,7.29,5.23,11.59,8A29.52,29.52,0,0,1,33.5,63.21Zm17-5.34c-4.7-2.78-8.64-5.5-13.14-8.39-1.1-.71-3.6-2.54-4.36-4.83-.93-2.81-.2-5.49,3.28-8.38H63.07A29.71,29.71,0,0,1,50.47,57.86Z" fill="#ffffff"/></svg></span>');
    $('#adventistVitality > a')
      .prepend('<span class="u-icon u-icon--l u-path-fill--dark"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 57 51"><path d="M28.5,51l-1.23-.87C26.15,49.36,0,30.78,0,15.46,0,6.21,5.94,0,14.78,0,19.5,0,24.4,2.35,28.5,6.52,32.6,2.35,37.5,0,42.22,0,51.06,0,57,6.21,57,15.46c0,15.32-26.15,33.9-27.27,34.68ZM14.78,4.12C7,4.12,4.22,10,4.22,15.46c0,10.38,16.49,24.7,24.28,30.44,7.78-5.74,24.28-20.06,24.28-30.44C52.78,10,50,4.12,42.22,4.12c-3.69,0-7.63,2-11,5.6,2.85,3.88,4.57,8.22,4.67,11.87a8.58,8.58,0,0,1-2.43,6.2,6.87,6.87,0,0,1-9.91,0,8.59,8.59,0,0,1-2.44-6.2c.11-3.66,1.83-8,4.67-11.87C22.41,6.14,18.47,4.12,14.78,4.12Zm13.72,9a17.59,17.59,0,0,0-3.17,8.56,4.5,4.5,0,0,0,1.24,3.21,2.6,2.6,0,0,0,3.85,0,4.49,4.49,0,0,0,1.24-3.21A17.58,17.58,0,0,0,28.5,13.15Z" fill="#ffffff"/></svg></span>');
    $('#adventistService > a')
      .prepend('<span class="u-icon u-icon--l u-path-fill--dark"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 63 63"><path d="M55.79,29.12v4.93A10.69,10.69,0,0,1,45.18,44.8H40.33a9,9,0,0,1-17.66,0H17.73A10.69,10.69,0,0,1,7.12,34.06v-5A9.17,9.17,0,0,1,9,11a9.17,9.17,0,0,1,1.73,18.15v4.92a7,7,0,0,0,6.95,7h4.9a9.12,9.12,0,0,1,7-7.21V29.12a9,9,0,1,1,3.66,0v4.76a9.12,9.12,0,0,1,7,7.21h4.81a7,7,0,0,0,6.95-7V29.12a9,9,0,1,1,3.66,0Zm-41.36-9A5.39,5.39,0,1,0,9,25.61,5.43,5.43,0,0,0,14.43,20.16Zm22.46,0a5.39,5.39,0,1,0-5.38,5.45A5.43,5.43,0,0,0,36.88,20.16ZM31.5,37.39a5.45,5.45,0,1,0,5.38,5.45A5.43,5.43,0,0,0,31.5,37.39ZM54,14.7a5.46,5.46,0,1,0,5.39,5.46A5.43,5.43,0,0,0,54,14.7Z" fill="#ffffff"/></svg></span>');


    // Documents Extension
    $('#document_groups.layout')
      .addClass('text');


    // Photo Albums Extension
    $('.photo_album, .photo_album_return, .photo_album_return + h3 + p')
      .addClass('text');
    $('#photo-title').parent().parent()
      .addClass('text');
    $('.PhotoAlbumToolbar').parent()
      .addClass('text');


    // News & Events Extension
    $('#news.layout').each(function() {
      $news = $(this);
      $news.addClass('u-spacing--triple');

      $news.contents().filter(function() {
        return this.nodeType === 3 && $.trim($(this).text()).length > 0;
      }).wrap('<div class="text"><p></p></div>');

      // move the title up to the page title bar
      var pageTitle = $news.find('h2').first().remove().html();
      $('.c-page-header__simple--inner h1').html(pageTitle);

      // wrap the navigation list in a nav
      $news.find('.subscribe_nav')
        .wrap('<nav class="c-page-menu" role="navigation"></nav>')
        .addClass('o-inline-list');



      /* NOTE: this transformation is not yet complete, there is still more to be done! */

      /*
      <li>
        <div>
          <h3><a href="/news_entries/55">title</a></h3>
          <p class="meta">Posted on <strong>
            01 January, 2017</strong></p>
        </div>
        <div class="news_desc">description</div>
      </li>
      */

      /*
      <div class="u-spacing c-block__group c-media-block__group">
        <div class="u-spacing">
          <h3 class="c-media-block__title c-block__title u-theme--color--dark u-font--primary--l">
            Item Title
          </h3>
          <p class="c-media-block__description c-block__description">Item description</p>
        </div>
        <div class="c-media-block__meta c-block__meta u-theme--color--base">
          <span class="c-block__category u-text-transform--upper">Item category</span>
          <time class="c-block__date u-text-transform--upper" datetime="2017-12-28">December 28, 2017</time>
        </div>
      </div>
      */

      var $archives = $news.find('.news_list');
      if ($archives.length > 0) {
        $newsItems = $archives.children('li');
        $newsItems.each(function() {
          $item   = $(this);
          title   = $item.find('h3').html();
          desc    = $item.find('.news_desc').text();
          $meta   = $item.find('.meta');
          date    = (function() {
            try {
              return new Date($meta.find('strong').text());
            } catch(error) {
              return null;
            }
          })();

          $item.addClass('u-spacing c-block__group c-media-block__group');
          $item.children('div').first().addClass('u-spacing');
          $item.children('.news_desc')
            .removeClass('news_desc')
            .addClass('c-media-block__meta c-block__meta u-theme--color--base')
            .html('<time class="c-block__date u-text-transform--upper"></time>')
            .find('time').text(date.toLocaleString(jQuery('html').attr('lang') || 'en-US', { month: 'long', day: 'numeric', year: 'numeric' }));
        });
      }
    });

    // Event (calendar) Extension
    var pageTitle = $('#event.layout > h2, .calendar_header > h1').first().remove().html();
    if (pageTitle) {
      $('.c-page-header__simple--inner h1').html(pageTitle);
    }
    $('.calendar-day-events > ul, ul.actions, #calendar_options > ul').addClass('o-inline-list');

    // Announcements Extension
    $('.c-article__body > div').has('#announcements.layout').removeClass('text');
    var pageTitle = $('#announcements.layout > .largecontent > h2').first().remove().html();
    if (pageTitle) {
      $('.c-page-header__simple--inner h1').html(pageTitle);
    }

    // News Extension
    $('ul.news_list').addClass('o-inline-list');

    // Podcasts Extension
    $('ul.products_list, ul.external-podcast-list').addClass('o-inline-list');
    var pageTitle = $('#podcasts.layout, #podcast.layout, #external_podcasts.layout, #external_podcast.layout').find('h2').first().remove().html();
    if (pageTitle) {
      $('.c-page-header__simple--inner h1').html(pageTitle);
    }

    // Content Series Extension
    $('.content-series-entry-full .body').removeClass('body');

    // Bibleinfo Extension
    var pageTitle = $('.bibleinfo_powered_by ~ h2').first().remove().html();
    if (pageTitle) {
      $('.c-page-header__simple--inner h1').html(pageTitle);
    }
    $('.c-article__body .bibleinfo').not(':has(.content-column)').addClass('text u-spacing c-block__body');
    $('.c-article__body .bibleinfo .content-column').addClass('text u-spacing c-block__body');

    // ALPS expects all blockquote content to be within <p> tags
    $("blockquote").contents().filter(function() {
      return this.nodeType === 3 && $.trim($(this).text()).length > 0;
    }).wrap("<p></p>");
    // It also styles them better if we’re explicit about the left border
    $('.text blockquote')
      .addClass('u-theme--border-color--darker--left');
    $('#sidebar_breakout .text blockquote')
      .addClass('u-theme--border-color--lighter--left');

    // fixup above-broken subscription links in general
    $('a.subscribe-rss').css({background: 'transparent url(/assets/icon-rss.gif) no-repeat scroll left', 'padding-left': '20px'});
    $('ul.subscribe_nav > li').css({display: 'inline', 'list-style': 'none', padding: '0 15px 0 0'});
  

  } catch(error) {
    // For now, let’s just catch any error that may occur, log it out to the console, and keep on keepin’ on.
    console.error(error);
  }});

})(jQuery);
