/**
* Template Name: Amoeba
* Updated: Mar 10 2023 with Bootstrap v5.2.3
* Template URL: https://bootstrapmade.com/free-one-page-bootstrap-template-amoeba/
* Author: BootstrapMade.com
* License: https://bootstrapmade.com/license/
*/
(async function() {
  "use strict";

  /**
   * Easy selector helper function
   */
  const select = (el, all = false) => {
    el = el.trim()
    if (all) {
      return [...document.querySelectorAll(el)]
    } else {
      return document.querySelector(el)
    }
  }

  /**
   * Easy event listener function
   */
  const on = (type, el, listener, all = false) => {
    let selectEl = select(el, all)
    if (selectEl) {
      if (all) {
        selectEl.forEach(e => e.addEventListener(type, listener))
      } else {
        selectEl.addEventListener(type, listener)
      }
    }
  }

  /**
   * Easy on scroll event listener 
   */
  const onscroll = (el, listener) => {
    el.addEventListener('scroll', listener)
  }

  /**
   * Navbar links active state on scroll
   */
  let navbarlinks = select('#navbar .scrollto', true)
  const navbarlinksActive = () => {
    let position = window.scrollY + 200
    navbarlinks.forEach(navbarlink => {
      if (!navbarlink.hash) return
      let section = select(navbarlink.hash)
      if (!section) return
      if (position >= section.offsetTop && position <= (section.offsetTop + section.offsetHeight)) {
        navbarlink.classList.add('active')
      } else {
        navbarlink.classList.remove('active')
      }
    })
  }
  window.addEventListener('load', navbarlinksActive)
  onscroll(document, navbarlinksActive)

  /**
   * Scrolls to an element with header offset
   */
  const scrollto = (el) => {
    let header = select('#header')
    let offset = header.offsetHeight

    if (!header.classList.contains('header-scrolled')) {
      offset -= 20
    }

    let elementPos = select(el).offsetTop
    window.scrollTo({
      top: elementPos - offset,
      behavior: 'smooth'
    })
  }

  /**
   * Toggle .header-scrolled class to #header when page is scrolled
   */
  let selectHeader = select('#header')
  if (selectHeader) {
    const headerScrolled = () => {
      if (window.scrollY > 100) {
        selectHeader.classList.add('header-scrolled')
      } else {
        selectHeader.classList.remove('header-scrolled')
      }
    }
    window.addEventListener('load', headerScrolled)
    onscroll(document, headerScrolled)
  }

  /**
   * Back to top button
   */
  let backtotop = select('.back-to-top')
  if (backtotop) {
    const toggleBacktotop = () => {
      if (window.scrollY > 100) {
        backtotop.classList.add('active')
      } else {
        backtotop.classList.remove('active')
      }
    }
    window.addEventListener('load', toggleBacktotop)
    onscroll(document, toggleBacktotop)
  }

  /**
   * Mobile nav toggle
   */
  on('click', '.mobile-nav-toggle', function(e) {
    select('#navbar').classList.toggle('navbar-mobile')
    this.classList.toggle('bi-list')
    this.classList.toggle('bi-x')
  })

  /**
   * Mobile nav dropdowns activate
   */
  on('click', '.navbar .dropdown > a', function(e) {
    if (select('#navbar').classList.contains('navbar-mobile')) {
      e.preventDefault()
      this.nextElementSibling.classList.toggle('dropdown-active')
    }
  }, true)

  /**
   * Scrool with ofset on links with a class name .scrollto
   */
  on('click', '.scrollto', function(e) {
    if (select(this.hash)) {
      e.preventDefault()

      let navbar = select('#navbar')
      if (navbar.classList.contains('navbar-mobile')) {
        navbar.classList.remove('navbar-mobile')
        let navbarToggle = select('.mobile-nav-toggle')
        navbarToggle.classList.toggle('bi-list')
        navbarToggle.classList.toggle('bi-x')
      }
      scrollto(this.hash)
    }
  }, true)

  /**
   * Scroll with ofset on page load with hash links in the url
   */
  window.addEventListener('load', () => {
    if (window.location.hash) {
      if (select(window.location.hash)) {
        scrollto(window.location.hash)
      }
    }
  });




  // loading
  const loader = document.querySelector("#loading");

// showing loading
function displayLoading() {
    loader.classList.add("display");
    // to stop loading after some time
    // setTimeout(() => {
    //     loader.classList.remove("display");
    // }, 5000);
}

// hiding loading 
function hideLoading() {
    loader.classList.remove("display");
}


  // Submit button

  document.querySelector('form').addEventListener('submit', async (event) => {
    event.preventDefault(); // Prevent form submission from refreshing the page
    displayLoading();
    const form = event.target;
    const formData = new FormData(form); // Create a FormData object to store form data
  
    try {
      // const response = await fetch('https://emailapi.thrickodithanamscb.in/email', {  
        const response = await fetch('http://localhost:3333/email', {  
        method: 'POST',
        body: formData,
      });
  
      if (response.ok) {
       
        response.json().then((data) => {
          hideLoading()
          
          alert('Form submitted successfully!')
          
          form.reset(); // Clear form inputs after successful submission
          console.log(data); // Handle the response data as needed
        });
      } else {
         hideLoading()
        alert('Error submitting form. Please try again.');
      }
    } catch (error) {
      //error caused when sending large file because of server time limit reaches 
      //error shows but the email is send successfully
      
      hideLoading()
      alert('Form submitted successfully!');
    }
  });
  
  //size validation and pdf selection

  function addEventListenersToIds(ids, event, listener) {
    ids.forEach(function (id) {
      var element = document.getElementById(id);
      element.addEventListener(event, listener);
    });
  }
  
  var fileInputIds = ['TenderFile', 'PaymentFile'];
  
  addEventListenersToIds(fileInputIds, 'change', checkfileformat);
 
  // const fileInput = document.getElementById('TenderFile');
  // fileInput.addEventListener('change', checkfileformat);

  function checkfileformat(event) {
    var fileInput = event.target;
    var file = fileInput.files[0];
    var size = file.size;
    var fileName = file.name;
    var fileExtension = fileName.split('.').pop().toLowerCase();
    //var allowedFormats = ['pdf', 'zip'];
    var allowedFormats = ['pdf'];

    if (allowedFormats.indexOf(fileExtension) === -1) {
      // alert("Only PDF and ZIP files are allowed.");
      alert("Only PDF files are allowed.");
      fileInput.value = '';
      return false;
    }

    var maxSize = 5 * 1024 * 1024; // 5MB in bytes
    if (size > maxSize) {
      alert("File size exceeds the 5MB limit.");
      fileInput.value = '';
      return false;
    }

    // alert("File uploaded sucessfully.");
    return true;
  }

})()