document.addEventListener( 'DOMContentLoaded', ( event ) => {

  const solarConditions = document.querySelector( '.page-id-783' );

  if ( solarConditions ) {

    /* Put current date and time in UTC time  */
    const utcDiv = document.querySelector( '.date-utc' );
    if ( utcDiv ) {
      const now = new Date();
      utcDiv.textContent = now.toUTCString();
    }
    /* END Put current date and time in UTC time  */

    /* HF Band Info */
    async function fetchDataAndFillTable() {
      try {
        const response = await fetch( '/wp-admin/admin-ajax.php?action=fetch_data' );
        if ( !response.ok ) {
          throw new Error( `HTTP error! status: ${ response.status }` );
        }
        const data = await response.text(); // Get data in XML format

        // Convert data from XML format to DOM
        const parser = new DOMParser();
        const xml = parser.parseFromString( data, "text/xml" );

        /*console.log( 'xml' );
        console.log( xml );*/

        // Get all 'band' elements from XML
        const bands = xml.querySelectorAll( 'band' );

        // Get table by id
        const table = document.querySelector( '#bandstable' );

        // Get all rows of the table except the first one
        const rows = table.querySelectorAll( 'tbody tr:not(:first-of-type)' );

        // Bypass all 'band' elements
        bands.forEach( band => {
          const bandName = band.getAttribute( 'name' );
          const dayCondition = band.getAttribute( 'time' ) === 'day' ? band.textContent : null;
          const nightCondition = band.getAttribute( 'time' ) === 'night' ? band.textContent : null;

          // Find the corresponding row in the table
          rows.forEach( row => {
            const firstCell = row.querySelector( 'td:first-child' );
            if ( firstCell && firstCell.textContent === bandName ) {
              if ( dayCondition ) {
                const dayCell = firstCell.nextElementSibling;
                dayCell.textContent = dayCondition;
                dayCell.className = "status " + ( dayCondition.toLowerCase() === "good" ? "good" : "bad" );
                dayCell.setAttribute( "alt", bandName + " Band Daytime Conditions" );
              }
              if ( nightCondition ) {
                const nightCell = firstCell.nextElementSibling.nextElementSibling;
                nightCell.textContent = nightCondition;
                nightCell.className = "status " + ( nightCondition.toLowerCase() === "good" ? "good" : "bad" );
                nightCell.setAttribute( "alt", bandName + " Band Nighttime Conditions" );
              }
            }
          } );
        } );


        //Solar Conditions
        let condValues = document.querySelectorAll( '#primaryconds .cond_value' );

        // Insert data into the corresponding elements
        condValues[ 0 ].textContent = xml.getElementsByTagName( 'sunspots' )[ 0 ].childNodes[ 0 ].nodeValue;
        condValues[ 1 ].textContent = xml.getElementsByTagName( 'solarflux' )[ 0 ].childNodes[ 0 ].nodeValue;
        condValues[ 2 ].textContent = xml.getElementsByTagName( 'kindexnt' )[ 0 ].childNodes[ 0 ].nodeValue;
        condValues[ 3 ].textContent = xml.getElementsByTagName( 'solarwind' )[ 0 ].childNodes[ 0 ].nodeValue;
        condValues[ 4 ].textContent = xml.getElementsByTagName( 'signalnoise' )[ 0 ].childNodes[ 0 ].nodeValue;


        //Other Solar Conditions
        let statsCondValues = document.querySelectorAll( '#stats-inner .cond_value' );

        // Insert data into the corresponding elements
        statsCondValues[ 0 ].textContent = xml.getElementsByTagName( 'aindex' )[ 0 ].childNodes[ 0 ].nodeValue;
        statsCondValues[ 1 ].textContent = xml.getElementsByTagName( 'kindex' )[ 0 ].childNodes[ 0 ].nodeValue;
        statsCondValues[ 2 ].textContent = xml.getElementsByTagName( 'xray' )[ 0 ].childNodes[ 0 ].nodeValue;
        statsCondValues[ 3 ].textContent = xml.getElementsByTagName( 'heliumline' )[ 0 ].childNodes[ 0 ].nodeValue;
        statsCondValues[ 4 ].textContent = xml.getElementsByTagName( 'protonflux' )[ 0 ].childNodes[ 0 ].nodeValue;
        statsCondValues[ 5 ].textContent = xml.getElementsByTagName( 'electonflux' )[ 0 ].childNodes[ 0 ].nodeValue;

        statsCondValues[ 6 ].textContent = xml.getElementsByTagName( 'fof2' )[ 0 ].nodeValue ? xml.getElementsByTagName( 'fof2' )[ 0 ].childNodes[ 0 ].nodeValue + ' MHz' : ' MHz';

        statsCondValues[ 7 ].textContent = xml.getElementsByTagName( 'muf' )[ 0 ].childNodes[ 0 ].nodeValue;

        //Format Time
        let updatedData = document.querySelectorAll( '#Inspiration .updated-data' );
        let updatedDataText = xml.getElementsByTagName( 'updated' )[ 0 ].childNodes[ 0 ].nodeValue;
        let parts = updatedDataText.split( " " ); // ["24", "Apr", "2024", "2030", "GMT"]
        let time = parts[ 4 ]; // "2030"

        /*console.log('parts');
        console.log(parts);

        console.log('time');
        console.log(time);*/
        let formattedTime = time.slice( 0, 2 ) + ":" + time.slice( 2 ); // "20:30"
        let formattedData = parts[ 0 ] + " " + parts[ 1 ] + " " + parts[ 2 ] + " " + parts[ 3 ] + " " + formattedTime + " " + parts[ 5 ]; // "24 Apr 2024 20:30 GMT"
        updatedData[ 0 ].textContent = formattedData;

      } catch ( error ) {
        console.error( 'An error occurred while fetching the data.', error );
      }
    }

    fetchDataAndFillTable();
    /* END HF Band Info */
  }

  /*const w5Table = document.querySelector('.page-id-792');

  if (w5Table) {

    fetch( '/wp-admin/admin-ajax.php?action=fetch_api_data', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
      },
      body: 'action=fetch_api_data'
    } )
      .then( response => response.json() )
      .then( data => {
        console.log( 'Data:', data);

        // Create table rows for each object in the array
        const rows = data.map(item => {
          // Create a table cell for each property of the object
          const cells = Object.values(item).map(value => `<td>${value}</td>`).join('');
          // Return the table row
          return `<tr>${cells}</tr>`;
        });

        // Create the full table
        const table = `<table>${rows.join('')}</table>`;

        // Insert the table into the element with the class .w5-table-wrapper
        document.querySelector('.w5-table-wrapper').innerHTML = table;
      } )
      .catch( error => console.error( 'Error:', error ) );
  }*/

} );

/*document.addEventListener('DOMContentLoaded', function () {
  // functionToRemoveTheAosAnimateClass
  function removeAOSAnimateClass() {
    const subMenus = document.querySelectorAll('#menu-main-menu > li.menu-item > ul.sub-menu');
    subMenus.forEach(function (menu) {
      if (menu.classList.contains('aos-animate')) {
        menu.classList.remove('aos-animate');
      }
    });
  }

  // removingAClassOnPageLoad
  removeAOSAnimateClass();

  // removingAClassWhenScrollingAPage
  window.addEventListener('scroll', removeAOSAnimateClass);
});*/

jQuery( document ).ready( function ( $ ) {
  /*jQuery('#header-menu .menu-header-menu-container').meanmenu({
    meanScreenWidth:"980",
    meanMenuContainer:'.header-section'
  });

  //Social Share
  if (jQuery('a.share').length) {
    jQuery('a.share').on('click', function (e) {
      e.preventDefault();
      jQuery(this).toggleClass('active');
      jQuery('.share-print').toggleClass('active');
    })
  }*/


  /* Meta Single */
  /*let single_post_h2 = jQuery('body.single #left-content h2:first-of-type');

  if(single_post_h2.length) {
    jQuery('body.single #left-content .single-meta-wrap').insertAfter(single_post_h2);
  } else {
    jQuery('body.single #left-content .single-meta-wrap').prependTo('#left-content > .ct-inner-content');
  }*/
  /* Meta Single */

  /*jQuery( "#left-content p iframe" ).wrap( "<div class='youtube-wrap'></div>" );*/

  /*Fix popup youtube-channel*/
  /*if(jQuery( '.ytc_thumb' ).length) {
    jQuery( '.ytc_thumb' ).magnificPopupAU( {
      type: 'iframe',
      mainClass: 'mfp-fade',
      removalDelay: 400,
      preloader: false,
      iframe: {
        patterns: {
          youtube: {
            index: 'youtube.com',
            id: 'v=',
            src: 'https://www.youtube.com/embed/%id%?rel=0&autoplay=1'
          }
        }
      },
    } );
  }*/

  // Open external links in new tab
  /*$( 'a[href^=http]' ).click( function () {
    var a = new RegExp( '/' + window.location.host + '/' );
    if ( !a.test( this.href ) ) {
      window.open( this.href );
      return false;
    }
  } );*/

  // Rank Math Faq Accordion
  let faqWrap = jQuery( '.single-content #rank-math-faq .rank-math-list' );

  if ( faqWrap.length > 0 ) {
    faqWrap.find( '.rank-math-list-item' ).each( function ( i, el ) {
      let faq = jQuery( this );
      let faqTitle = faq.find( '.rank-math-question' );
      let faqContent = faq.find( '.rank-math-answer' );
      if ( i === 0 ) {
        faqContent.slideDown();
        faqTitle.addClass( 'active' );
      } else {
        faqContent.slideUp();
        faqTitle.removeClass( 'active' );
      }
      faq.click( function () {
        faqContent.slideDown( 200 );
        faqTitle.addClass( 'active' );
        jQuery( this ).siblings( '.rank-math-list-item' ).find( '.rank-math-answer' ).slideUp( 200 );
        jQuery( this ).siblings( '.rank-math-list-item' ).find( '.rank-math-question' ).removeClass( 'active' );
      } );
    } );
  }
  // End Rank Math Faq Accordion

  // Wrap the iframe with a center tag
  jQuery( '.single-content-left-col iframe' ).each( function () {
    if ( jQuery( this ).parent( 'p' ) ) {
      jQuery( this ).wrap( '<center></center>' );
    }
  } );
  // End Wrap the iframe with a center tag

  // Ol li more than 15
  let singleOl = jQuery( '.single-content-left-col ol' );
  if ( singleOl.length > 0 ) {
    singleOl.each( function ( i, el ) {
      let maxOl = jQuery( this );
      if ( maxOl.children( 'li' ).length > 15 ) {
        maxOl.css( 'column-count', '2' );
      }
    } )
  }
  // End Ol li more than 15
} );