
$(function(){


  /*--------------------------------------------
  add more
  --------------------------------------------*/

  var $id = 0;

    //var addMore = document.querySelector(".add-more-button");

  $('body').on('click', '.add-more-button', function() {

    $id++;
    
    var el = $(this).parents('#employee_course_registrations').find('.add-more-container');

    var moreContainer = 
    '<div class="row add-more-container-inner"><div class="col-sm-12 col-lg-6"><input type="text" class="form-control form-control-sm" name="course_name_'+ $id +'" placeholder="Course name"></div><div class="col-sm-12 col-lg-3"><input type="text" class="form-control form-control-sm" name="course_date_'+ $id +'" placeholder="e.g. 01-05-1980"></div><div class="col-sm-6 col-lg-2"><div class="file-upload"><button class="file-upload-btn" type="button">Upload</button><input type="file" name="files_'+ $id +'" class="file-upload-input"  /><input type="hidden" name="file_upload_base_'+ $id +'" class="file-upload-base" /><input type="hidden" name="file_name_'+ $id +'" class="file-name"/><span class="file-upload-name"></span></div></div><button type="button" class="col-sm-12 col-lg-1 btn btn-danger btn-add-circle remove-registration"></button></div>';

    el.append(moreContainer);

    $('input[name="file_upload_total"]').val($id);

  });


  $(document).on('click', '.file-upload-btn', function(){

    $(this).parent().find('.file-upload-input').trigger( 'click' );

  });


  $(document).on('change', '.file-upload-input', function(){

    readURL(this);

  });


  $(document).on('click', '.remove-registration', function(){

    removeUpload($(this));

  });


});

function readURL(input) {

  var el = $(input).parent();

  if (input.files && input.files[0]) {

    var reader = new FileReader();

    reader.onload = function(e) {

      //console.log()
      console.log(e.target.result)

      el.find('.file-upload-base').val(e.target.result);

      el.find('.file-upload-name').html(input.files[0].name);

      el.find('.file-name').val(input.files[0].name);


      //$('.file-upload-name').html(e.target.result);

    };

    reader.readAsDataURL(input.files[0]);

  } 

}

function removeUpload(el) {

  el.parents('.add-more-container-inner').find('.file-upload-name').html('');

}
