
$(function(){
  $(document).on('change', '#flip-card', function(){
    alert()
  });
})
$(document).ready(function() {
  'use strict';

  $('.boot-multiselect').multiselect({
      enableCollapsibleOptGroups: true,
      enableClickableOptGroups: true,
      collapseOptGroupsByDefault: true,
      enableFiltering: true,
  });

  if($('header.topbar').length) {

    let topbarPosition = parseInt($('header.topbar').position().top);
    let topbarSize = parseInt($('header.topbar').height());
    let leftbarSize = parseInt($('.left-sidebar').width());  
    let leftColSize = $('table.contact-list').find('tbody').find('tr:first-child').find('td').eq(0).outerWidth();
    let rowSize = parseInt($('table.contact-list').find('tbody').find('tr:first-child').find('td').eq(0).outerHeight());
    let tableSize = parseInt($('table.contact-list').width());
    let marginLeft = parseInt($('.page-wrapper').css('marginLeft'));
    console.log(rowSize)

    

    $(window).scroll(function(){

      let el = $(this);

      //console.log($(this).scrollTop())

      let offset = $(this).scrollTop() - topbarSize - 50;

      if (el.scrollTop() > topbarSize) {
        $('table.contact-list').find('.sticky-header').addClass('fixed d-block').css({'top': offset});
        $('table.contact-list').find('.sticky-header').find('th').each(function(i, v) {
          let d = $('table.contact-list').find('tbody').find('tr:first-child').find('td').eq(i).outerWidth();
          $(this).css({'width': d +'px'});
        })
      } else {
        $('table.contact-list').find('.sticky-header').removeClass('fixed d-block');
      }
    });

    $('.list-table-wrapper').scroll(function(){

      let el = $(this);

      let offset = $(this).scrollLeft();

      //console.log('Scroll: '+ $(this).scrollLeft() +' LeftMarg: '+ marginLeft +' col: '+ leftColSize +' offset: '+ offset)

      if (el.scrollLeft() > leftColSize) {
        $('table.contact-list').find('.actions_column').addClass('fixed').css({'left': offset, 'width': leftColSize});
        $('table.contact-list').find('tbody').find('tr').each(function(i, v) {
          let d = $(this).outerHeight();
          $('table.contact-list').find('tbody').find('tr').eq(i).find('td:first-child').css({'height': d +'px'});
        })
      } else {
        $('table.contact-list').find('.actions_column').removeClass('fixed');
      }
    });
  }

  $(document).on('change', '#licences', function(){

    //console.log($(this).parents('#commonModalForm').find('input[name="vat"]').val());

    if($('#course_id').val() !== 'Select') {

      let totalPrice = parseInt($( "#course_id option:selected" ).data('price')) * parseInt($(this).val());

      let vat = totalPrice * parseInt($(this).parents('#commonModalForm').find('input[name="vat"]').val()) / 100;

      let amount = totalPrice + vat;

      $('input[name="payment_amount"]').val(amount);

      console.log(parseInt($(this).val()));

    }

  });

  $(document).on('change', '#course_id', function(){

    //console.log($(this).parents('#commonModalForm').find('input[name="vat"]').val());

    if($('#licences').val() !== 'Select') {

      let totalPrice = parseInt($( "#course_id option:selected" ).data('price')) * parseInt($('#licences').val());

      let vat = totalPrice * parseInt($(this).parents('#commonModalForm').find('input[name="vat"]').val()) / 100;

      let amount = totalPrice + vat;

      $('input[name="payment_amount"]').val(amount);

      console.log($( "#course_id option:selected" ).data('price'));

    }

  });

  $(document).on('change', 'input[name="mcd"]', function(){

    var url = $(this).parents('form').find('button').data('url').split('?');

    if ($(this).is(":checked")) {

      url = url[0] + '?stage=regions';

    }else {

      url = url[0] + '?stage=services';

    }

    $(this).parents('form').find('button').attr('data-url', url);

  });

  $(document).on('change', 'input[name="employee_range"]', function(){

    var url = $(this).parents('form').find('button').data('url').split('?');

    if ($(this).val() == '0-4') {
      
      url = url[0] + '?stage=qn-employee-range-process';
      
    }else{

      url = url[0] + '?stage=qn-employee-range-hs';

    }

    $(this).parents('form').find('button').attr('data-url', url);

  });

  $(document).on('change', 'input[name="personnel_training"]', function(){

    var url = $(this).parents('form').find('button').data('url').split('?');

    if ($(this).val() == 'yes') {
      
      //url = url[0] + '?stage=qn-personnel-training-evidence';
      
    }else{

      //url = url[0] + '?stage=qn-personnel-employed';

    }

    //$(this).parents('form').find('button').attr('data-url', url);

  });

  /*$(document).on('change', 'input[name="formal_notices"]', function(){

    var r = $(location).attr('href').split('?');

    r = r[1].split('-').pop();

    r = r.split('&');

    console.log(r)

    var url = $(this).parents('form').find('button').data('url').split('?');

    if ($(this).val() == 'yes') {
      
      url = url[0] + '?stage=qn-formal-notices-'+ r[0] +'-evidence';
      
    }else{

      url = url[0] + '?stage=qn-incident-reports';

    }

    $(this).parents('form').find('button').attr('data-url', url);

  });*/

  $(document).on('click', ".open", function () {
        $(".modalDialog1").modal("show");
  });
      
  $(document).on('click', '.close1', function(e){
    e.preventDefault();
      $(".modalDialog1").css("display","none");
      $(".modalDialog1").modal("hide");
  });
    


  $(document).on('change', 'input[name="lead_disposal_certificate"]', function(){

    var url = $(this).parents('form').find('button').data('url').split('?');

    if ($(this).val() == 1) {
      
      url = url[0] + '?stage=waste-disposal';
      
    }else{

      url = url[0] + '?stage=certifications';

    }

    $(this).parents('form').find('button').attr('data-url', url);

  });

  $(document).on('change', '.passport-type', function(){

    var el = $(this);

    var url = $(this).parents('form').find('button').data('url').split('?');

    if ($(this).val() == 17 && $(this).is(':checked')) {

      $('.passport-type' ).each(function(){

        if ($(this).val() != 17) $(this).prop('checked', false);

      });
      
      url = url[0] + '?stage=insurances&prev=passport-types';
      
    }else{

      $('#17').prop('checked', false);

      url = url[0] + '?stage=passport-target';

    }

    $(this).parents('form').find('button').attr('data-url', url);

  });

  $(document).on('change', '#national_coverage', function(){

    $( 'input[type="checkbox"].areas-lc' ).prop('checked', this.checked);


  });


  $(document).on('change', '.areas-lc', function(){

    if (!$(this).is(':checked')) {
      
      $( '#national_coverage' ).prop('checked', this.checked);

    }

  });

  $(".message-recipients").on('change', function(){  

      var el = $(this);         
      el.find('option:selected').each(function(){ 

          var label = $(this).closest('optgroup').prop('label');

          if (label == 'MCD Admin' || label == 'RMH Admin') {
              console.log(label);

              $('.include-all').removeClass('hide');

          }  
      }); 

  });


  $(".services-toggle").click(function() { 

    var type = $(this).attr('id');
    if ($(this).is(':checked')) 
      $("."+ type +'-container').removeClass('hidden');
    else
      $("."+ type +'-container').addClass('hidden');
   
  });


  $(document).on('change', ".not-applicable", function(){

    var el = $(this);

    var url = el.parents('form').find('button').data('url').split('?');

    if (el.is(':checked')) {      
      
      url = url[0] + '?stage=application-summary';

      el.parents('.input-block').find('input[type="checkbox"]').each(function(){

        if ($(this).is(':checked') && $(this).attr('name') != 'registration_4') $(this).prop('checked', false);

      });

    }else{

      url = url[0] + '?stage=applicable-certifications';

    }

    el.parents('form').find('button').attr('data-url', url);
   
  });

  $(document).on('change', ".certificate-registrations", function(){

    var el = $(this);

    var url = el.parents('form').find('button').data('url').split('?');

    if (el.is(':checked')) {

      url = url[0] + '?stage=applicable-certifications';

      el.parents('form').find('button').attr('data-url', url);

      if ($('.not-applicable').is(':checked')) $('.not-applicable').prop('checked', false);

    }
   
  });


  $(".regions").click(function() { 

    var regions = $(".regions:checkbox:checked").map(function(){
      return $(this).val();
    }).get();

    if (regions.length < 2) 
      $('.region-message').addClass('hidden');
    else
      $('.region-message').removeClass('hidden');
   
  });

  $(".qn-trigger").click(function() { 

    if ($(this).val() == 'yes') 
      $('.qn-extra-msg').removeClass('hidden');
    else
      $('.qn-extra-msg').addClass('hidden');
   
  });


  $(".qn-trigger-x").click(function() { 

    if ($(this).val() == 1) 
      $('.qn-extra-msg').removeClass('hidden');
    else
      $('.qn-extra-msg').addClass('hidden');
   
  });


  $(document).on('change', '.chk-qn-question', function(){

    formSubmitControl($(this));
   
  });

  $(document).on('focusout', '.qn-question', function(){

    formSubmitControl($(this));
   
  });

  $(document).on('change', '#role', function(){

    var redirect = "/login-override?role="+ $(this).val();

    window.location.href = redirect;
   
  });

  $(document).on('keyup', '.ppt-target', function(){
    var el = $(this)
    var cur_target = $(this).parents('.modal-body').find('.cur-target').val();
    if (el.val() != "") {
      if (parseInt(el.val()) < parseInt(el.attr('min'))) {
        el.val(el.attr('min'));
      }
      if (parseInt(el.val()) > parseInt(el.attr('max')) && parseInt(el.attr('max')) > 0) {
        el.val(el.attr('max'));
      }
    }else{
      el.val(cur_target);
    }

    console.log(el.val())
  });

  function CircleBar(e) {
    $(e)
      .circleProgress({ fill: { color: "#00EAFF" } })
      .on("circle-animation-progress", function(_event, _progress, stepValue) {
        $(this)
          .find("strong")
          .text(String(parseInt(100 * stepValue)) + "%");
      });
  }
  //CircleBar(".round");

  function formSubmitControl(element) {

    var el = element.parents('.col-val');

    var checks = 0;

    $('.chk-qn-question').each(function(i, v) {
      if(!$(this).is(':checked')) {
        if(!$(this).parents('.col-val').find('.qn-question').val()) {
          checks = 1;
        }
      }
    });

    console.log(checks)

    if(!checks) {
      el.parents('form').find('#commonModalSubmitButton').prop('disabled', false);
    }else{
      el.parents('form').find('#commonModalSubmitButton').prop('disabled', true);
    }

  }


  const downloadCharacterSheet = () => {

    const node = document.getElementById('id-card');

    html2canvas(node).then(canvas => {
      // document.body.appendChild(canvas)
      // var img    = canvas.toDataURL("image/png");
      // document.write('<img src="'+img+'"/>');
      var link = document.createElement('a');
      link.download = 'filename.png';
      link.href = canvas.toDataURL();
      link.click();
    });

  };

  const bindInputToElement = (inputEl, elementEl) => {
    inputEl.addEventListener('change', () => {
      elementEl.textContent = inputEl.value;
    });
  };

  $(document).on('click', '#download-button', downloadCharacterSheet);



  $('.step').each(function(index, element) {
    // element == this
    $(element).not('.active').addClass('done');
    $('.done').html('<i class="icon-ok"></i>');
    if($(this).is('.active')) {
      return false;
    }
  }); 

  /*-------------------------------------
  Sticky NabBar
  -------------------------------------*/
  $(window).on('scroll', function () {
    var scroll = $(window).scrollTop();

    if (scroll >= 1) {
      $('.ugf-nav-wrap').addClass('fixed');
    } else {
      $('.ugf-nav-wrap').removeClass('fixed');
    }
  });


  // Tooltips
  $('.tip').each(function () {
    $(this).tooltip(
    {
      html: true,
      title: $('#' + $(this).data('tip')).html(),
      placement: 'right'
    });
  });

  $('body').popover({
      selector: '[rel=popover]',
      trigger: 'hover',
      html: true,
      content: function () {
          return $(this).parents('.add-more-container').find('#'+$(this).data('tip')).html();
      }
  });


  /*--------------------------------------------
  File Input
  --------------------------------------------*/
  function handleChange(inputId) {
    var fileUploader = document.getElementById(inputId);
    var getFile = fileUploader.files

    
    var uploadedFile = getFile[getFile.length - 1];
    readFile(uploadedFile, inputId);
      

  }

  $('.input-file').on('change', function(e) {
    handleChange(e.target.id);
  });

  function readFile(uploadedFile, inputId) {
    if (uploadedFile) {
      var reader = new FileReader();
      reader.onload = () => {
        var parent = document.getElementById('p-' + inputId);
        parent.innerHTML = `<img class="preview-content img-fluid" src=${reader.result} />`;
      };

      reader.readAsDataURL(uploadedFile);
    }
  }

  // add this function, so the transition would only start running when the page has been fully loaded. This is a fallback in case when someone has turned off their JavaScript. 

  $('.help-toggle').on('click', function(){

    if($('.panel-slide-from-right').hasClass('on')){
      $('.panel-slide-from-right').removeClass('on')
    }else{
      $('.panel-slide-from-right').addClass('on')
    }

  });

  $(document).on('click', '.toggle-btn', function(e){

    e.preventDefault();

    var el = $(this);
    var par = el.parent().siblings();

      if (el.hasClass("active")) {
        //this is if the accordion is open
        el.removeClass("active")
        par.slideUp()
      } else {
        par.slideUp();
        $(".toggle-btn.active").removeClass("active");
        el.addClass("active");
        par.slideDown()
      }

    //$(this).parent().siblings().toggle('is-open')

  });
  
});

function init() {
  var helpbar = document.getElementById("helpbar");
  helpbar.classList.add("transition-after-pageload");
}
count = 10; // Timer
function countDown() {

  var redirect = "/"; // Target URL
  var timer = document.getElementById("timer"); // Timer ID
  if (count > 0) {
    count--;
    timer.innerHTML = "This page will redirect in " + count + " seconds."; // Timer Message
    setTimeout("countDown()", 1000);
  } else {
    window.location.href = redirect;
  }

  //$('#timer').text(timer.innerHTML);
}

window.onload = function() {
  countDown();
  init();
};
