<div class="action_menu">
  <a href="/tasks/task_edit/" class="btn btn_add" title="Dodaj zadanie">
    <i class="fa fa-plus"></i>Dodaj zadanie
  </a>
</div>
<div class="projects_container" style="margin-bottom: 25px;">
  <div class="left">
    <div class="_projects">
      <? foreach ( $this -> projects as $project ):?>
        <div class="_project">
          <label for="project_<?= $project[ 'id' ];?>">
            <input type="checkbox" class="g-checkbox" name="projects" value="<?= $project[ 'id' ];?>" <? if ( is_array( $this -> selected_projects ) and in_array( $project['id'], $this -> selected_projects ) ):?>checked<? endif;?>>
            <?= $project[ 'name' ];?> <? if ( $project[ 'client_id' ] ):?>- <small><?= \factory\Crm::get_client_name( (int)$project[ 'client_id' ] );?><? endif;?></small>
          </label>
        </div>
      <? endforeach;?>
    </div>
    <? if ( $this -> user['id'] == 1 ):?>
      <div class="_users">
        <? foreach ( $this -> users as $user ):?>
          <div class="_user">
            <label for="user_<?= $user[ 'id' ];?>">
              <input type="checkbox" class="g-checkbox" name="users" value="<?= $user[ 'id' ];?>" <? if ( is_array( $this -> selected_users ) and in_array( $user['id'], $this -> selected_users ) ):?>checked<? endif;?>>
              <?= $user[ 'name' ];?> <?= $user[ 'surname' ];?>
            </label>
          </div>
        <? endforeach;?>
      </div>
    <? endif;?>
  </div>
  <div class="right">
    <select name="filtr" class="form-control">
      <option value="">--- wybierz filtr ---</option>
      <? foreach ( $this -> tasks_filtrs as $filtr ):?>
        <option value="<?= $filtr[ 'id' ];?>" projects="<?= $filtr['projects'];?>" users="<?= $filtr['users'];?>"><?= $filtr[ 'name' ];?></option>
      <? endforeach;?>
    </select>
    <div class="buttons">
      <a href="#" class="btn btn-success btn_small">zapisz nowy filtr</a>
      <a href="#" class="btn btn-primary btn_small">aktualizuj filtr</a>
    </div>
  </div>
</div>
<div class="gantt-target" style="margin-bottom: 25px;"></div>
<div class="tasks_container">
  <div class="column tasks_new">
    <h2>Nowe zadania</h2>
    <ul>
      <? foreach ( $this -> tasks_new as $task ):?>
        <?
        echo \Tpl::view( 'tasks/task_single', [
          'task' => $task,
          'user' => $this -> user,
          'statuses' => $this -> statuses,
          'task_open' => $this -> open_task_id == $task['id'] ? true : false
        ] );
        ?>
      <? endforeach;?>
    </ul>
  </div>
  <? if ( $this -> user['id'] == 1 ):?>
    <div class="column tasks_fvat">
      <h2>Faktury</h2>
      <ul>
        <? foreach ( $this -> tasks_fvat as $task ):?>
          <?
          echo \Tpl::view( 'tasks/task_single', [
            'task' => $task,
            'user' => $this -> user,
            'statuses' => $this -> statuses,
            'task_open' => $this -> open_task_id == $task['id'] ? true : false
          ] );
          ?>
        <? endforeach;?>
      </ul>
    </div>
  <? endif;?>
  <!-- tasks_suspended -->
  <div class="column tasks_suspended">
    <h2>Zadania zaplanowane</h2>
    <ul>
      <? foreach ( $this -> tasks_suspended as $task ):?>
        <?
        echo \Tpl::view( 'tasks/task_single', [
          'task' => $task,
          'user' => $this -> user,
          'statuses' => $this -> statuses,
          'task_open' => $this -> open_task_id == $task['id'] ? true : false
        ] );
        ?>
      <? endforeach;?>
    </ul>
  </div>
  <!-- tasks_to_do -->
  <div class="column tasks_to_do">
    <h2>Zadania do zrobienia</h2>
    <ul>
      <? foreach ( $this -> tasks_to_do as $task ):?>
        <?
        echo \Tpl::view( 'tasks/task_single', [
          'task' => $task,
          'user' => $this -> user,
          'statuses' => $this -> statuses,
          'task_open' => $this -> open_task_id == $task['id'] ? true : false
        ] );
        ?>
      <? endforeach;?>
    </ul>
  </div>
  <div class="column tasks_to_review">
    <h2>Zadania do sprawdzenia <? if ( $this -> show_tasks_to_review == 'hide' ):?><i class="fa fa-eye" title="Pokaż zadania do sprawdzenia"></i><? else:?><i class="fa fa-times" title="Ukryj zadania do sprawdzenia"></i><? endif;?></h2>
    <ul>
      <? foreach ( $this -> tasks_to_review as $task ):?>
        <?
        echo \Tpl::view( 'tasks/task_single', [
          'task' => $task,
          'user' => $this -> user,
          'statuses' => $this -> statuses,
          'task_open' => $this -> open_task_id == $task['id'] ? true : false
        ] );
        ?>
      <? endforeach;?>
    </ul>
  </div>
  <div class="column tasks_bulk">
    <h2>Do rozliczenia <? if ( $this -> show_tasks_bulk == 'hide' ):?><i class="fa fa-eye" title="Pokaż zadania do rozliczenia"></i><? else:?><i class="fa fa-times" title="Ukryj zadania do rozliczenia"></i><? endif;?></h2>
    <ul>
      <? foreach ( $this -> tasks_bulk as $task ):?>
        <?
        echo \Tpl::view( 'tasks/task_single', [
          'task' => $task,
          'user' => $this -> user,
          'statuses' => $this -> statuses,
          'task_open' => $this -> open_task_id == $task['id'] ? true : false
        ] );
        ?>
      <? endforeach;?>
    </ul>
  </div>
  <div class="column tasks_closed">
    <h2>Zamknięte zadania <? if ( $this -> show_tasks_closed == 'hide' ):?><i class="fa fa-eye" title="Pokaż zamknięte zadania"></i><? else:?><i class="fa fa-times" title="Ukryj zamknięte zadania"></i><? endif;?></h2>
    <ul>
      <? foreach ( $this -> tasks_closed as $task ):?>
        <?
        echo \Tpl::view( 'tasks/task_single', [
          'task' => $task,
          'user' => $this -> user,
          'statuses' => $this -> statuses,
          'task_open' => $this -> open_task_id == $task['id'] ? true : false
        ] );
        ?>
      <? endforeach;?>
    </ul>
  </div>
</div>
<div class="task_popup">

</div>
<script type="text/javascript">
  var tasks = [
    <?
    foreach ( $this -> tasks_gantt as $task ) {
      echo '{';
      echo 'start: "'.$task['start'].'",';
      echo 'end: "'.$task['end'].'",';
      echo 'name: "'.$task['name'].'",';
      echo 'id: "'.$task['id'].'",';
      echo 'progress: '. (int)$task['progress'].',';
      if ( $task['custom_class'] )
        echo 'custom_class: "'.$task['custom_class'].'",';
      else
        echo 'custom_class: "",';
      if ( $task['dependencies'] )
        echo 'dependencies: "'.$task['dependencies'].'"';
      else
        echo 'dependencies: ""';
      echo '}';
      if ( $task['id'] != end( $this -> tasks_gantt )['id'] )
        echo ',';
    }
    ?>
    /*{
      start: '2018-10-01',
      end: '2018-10-08',
      name: 'Redesign website',
      id: "Task 0",
      progress: 91
    },
    {
      start: '2018-10-03',
      end: '2018-10-06',
      name: 'Write new content',
      id: "Task 1",
      progress: 55,
      dependencies: 'Task 0'
    },*/
  ]
  var gantt_chart = new Gantt(".gantt-target", tasks, {
    on_click: function (task) {
      console.log(task);
    },
    on_date_change: function(task, start, end) {
      console.log(task, start, end);
      // start datevar m = moment(start);
      var m = moment(start);
      // jeśli godzina > 0 lub minuty > 0, zaokrąglamy do następnego dnia
      if (m.hour() > 0 || m.minute() > 0) {
          m.add(1, 'day').startOf('day');
      } else {
          m.startOf('day'); // upewniamy się, że i tak jest 00:00
      }

      var date_start = m.format('YYYY-MM-DD');
      console.log( 'date_start: ' + date_start);
      // minus 10 hours
      var date_end = moment( end ).format( 'YYYY-MM-DD' );
      console.log( 'date_end: ' + date_end );

      $.ajax({
        url: '/tasks/task_change_dates/',
        type: 'POST',
        data: {
          task_id: task.id,
          date_start: date_start,
          date_end: date_end
        },
        success: function( response ) {
          var data = jQuery.parseJSON( response );
        }
      })
    },
    on_progress_change: function(task, progress) {
      console.log(task, progress);
    },
    on_view_change: function(mode) {
      console.log(mode);
    },
    view_mode: 'Half Day',
    language: 'en'
  });
  console.log(gantt_chart);

  function reload_tasks( projects, users )
  {
    //load tasks by ajax
    $.ajax({
      url: '/tasks/main_view_by_ajax/',
      type: 'POST',
      data: {
        projects: projects,
        users: users
      },
      success: function( response2 )
      {
        var data = jQuery.parseJSON( response2 );
        $( '.tasks_container .tasks_new ul' ).empty().append( data.tasks_new );
        $( '.tasks_container .tasks_to_review ul' ).empty().append( data.tasks_to_review );
        $( '.tasks_container .tasks_closed ul' ).empty().append( data.tasks_closed );
        $( '.tasks_container .tasks_bulk ul' ).empty().append( data.tasks_bulk );
        $( '.tasks_container .tasks_suspended ul' ).empty().append( data.tasks_suspended );
        $( '.tasks_container .tasks_to_do ul' ).empty().append( data.tasks_to_do );
        $( '.tasks_container .tasks_fvat ul' ).empty().append( data.tasks_fvat );
        gantt_chart.refresh( data.tasks_gantt );
      }
    });
  }

  function task_popup( task_id, open_works_time = false ) {

    $.ajax({
      url: '/tasks/task_popup/',
      type: 'POST',
      data: {
        task_id: task_id
      },
      success: function( response )
      {
        $( '.task[task_id="' + task_id + '"]' ).removeClass( 'notopened' );

        $( '.task_popup' ).empty().append( response ).show();

        $( '.task_popup .checklist ul li input.g-checkbox' ).on( 'change', function(e) {

          var action_id = $( this ).parents( 'li' ).attr( 'action_id' );
          var status = $( this ).is( ':checked' ) ? 1 : 0;

          $.ajax({
            type: 'POST',
            cache: false,
            url: '/tasks/action_change_status/',
            data: {
              action_id: action_id,
              status: status
            },
            beforeSend: function() { },
            success: function( response ) {
              task_popup( task_id );
            }
          });
        });

        if ( open_works_time )
          $( '.task_popup .task_details' ).addClass( 'open_works_time' );
      }
    });
  }

  $( 'body' ).on( 'click', '.projects_container .right .btn-primary', function(e) {
    var filtr_id = $( '.projects_container .right select[name="filtr"]' ).val();
    $.ajax({
      url: '/tasks/filtr_update/',
      type: 'POST',
      data: {
        filtr_id: filtr_id,
        projects: jQuery( 'input[name="projects"].g-checkbox:checked' ).map(function() {
          return this.value;
        }).get().join( "," ),
        users: jQuery( 'input[name="users"].g-checkbox:checked' ).map(function() {
          return this.value;
        }).get().join( "," )
      },
      success: function( response ) {

      }
    });
  });

  $( 'body' ).on( 'click', '.projects_container .right .btn-success', function(e) {
    $.ajax({
      url: '/tasks/filtr_save_form/',
      type: 'POST',
      data: {
        projects: jQuery( 'input[name="projects"].g-checkbox:checked' ).map(function() {
          return this.value;
        }).get().join( "," ),
        users: jQuery( 'input[name="users"].g-checkbox:checked' ).map(function() {
          return this.value;
        }).get().join( "," )
      },
      success: function( response )
      {
        var data = jQuery.parseJSON( response );
        if ( data.status == 'success' )
        {
          show_default_popup( data.popup_content );
        }
      }
    });
  });

  $( 'body' ).on( 'click', '.task .name', function(e) {
    e.preventDefault();
    var task_id = $( this ).closest( '.task' ).attr( 'task_id' );
    task_popup( task_id );
    return false;
  });

  $( 'body' ).on( 'click', '.task_popup .close', function(e) {
    e.preventDefault();
    $( '.task_popup' ).empty().hide();
    return false;
  });

  $( 'body' ).on( 'click', '.current_status', function() {
    $( this ).find( '.status_change' ).toggle();
  });

  $('body').on('click', function(e) {
    // Ukryj wszystkie .status_change
    $('.status_change').hide();

    // Sprawdź, czy kliknięcie miało miejsce w jakimś .current_status
    let currentStatusClicked = $(e.target).closest('.current_status');

    if (currentStatusClicked.length) {
      // Jeżeli tak, to wyświetl .status_change dla tego konkretnego .current_status
      currentStatusClicked.find('.status_change').show();
    }
  });

  $( 'body' ).on( 'change', 'select[name="task_status"]', function() {
    var task_id = $( this ).attr( 'task_id' );
    var status = $( this ).val();

    $.ajax({
      url: '/tasks/task_change_status/',
      type: 'POST',
      data: {
        task_id: task_id,
        status: status
      },
      success: function( response )
      {
        var data = jQuery.parseJSON( response );
        if ( data.status == 'success' )
        {
          var projects = jQuery( 'input[name="projects"]:checked' ).map(function() {
            return this.value;
          }).get();
          projects.join( "," );
          var users = jQuery( 'input[name="users"]:checked' ).map(function() {
            return this.value;
          }).get();
          reload_tasks( projects, users );
        }
      }
    });
  });

  <? if ( $this -> user['id'] == 1 ):?>
    $(document).ready(function() {
      // Inicjalizacja sortable
      $('.tasks_container .tasks_suspended ul').sortable({
        classes: {
          "ui-sortable": "highlight"
        },
        stop: function(event, ui) {
          var tasks_order = $( this ).sortable('toArray', { attribute: 'task_id' } );

          $.ajax({
            type: 'POST',
            cache: false,
            url: '/tasks/tasks_order_save/',
            data: {
              tasks_order: tasks_order
            },
            beforeSend: function() {},
            success: function( response ) {

            }
          });
        }
      });

      $('.tasks_container .tasks_bulk ul').sortable({
        classes: {
          "ui-sortable": "highlight"
        },
        stop: function(event, ui) {
          var tasks_order = $( this ).sortable('toArray', { attribute: 'task_id' } );

          $.ajax({
            type: 'POST',
            cache: false,
            url: '/tasks/tasks_order_save/',
            data: {
              tasks_order: tasks_order
            },
            beforeSend: function() {},
            success: function( response ) {

            }
          });
        }
      });

      $('.tasks_container .tasks_to_review ul').sortable({
        classes: {
          "ui-sortable": "highlight"
        },
        stop: function(event, ui) {
          var tasks_order = $( this ).sortable('toArray', { attribute: 'task_id' } );

          $.ajax({
            type: 'POST',
            cache: false,
            url: '/tasks/tasks_order_save/',
            data: {
              tasks_order: tasks_order
            },
            beforeSend: function() {},
            success: function( response ) {

            }
          });
        }
      });

      $('.tasks_container .tasks_to_do ul').sortable({
        classes: {
          "ui-sortable": "highlight"
        },
        stop: function(event, ui) {
          var tasks_order = $( this ).sortable('toArray', { attribute: 'task_id' } );

          $.ajax({
            type: 'POST',
            cache: false,
            url: '/tasks/tasks_order_save/',
            data: {
              tasks_order: tasks_order
            },
            beforeSend: function() {},
            success: function( response ) {

            }
          });
        }
      });

      $('.tasks_container .tasks_closed ul').sortable({
        classes: {
          "ui-sortable": "highlight"
        },
        stop: function(event, ui) {
          var tasks_order = $( this ).sortable('toArray', { attribute: 'task_id' } );

          $.ajax({
            type: 'POST',
            cache: false,
            url: '/tasks/tasks_order_save/',
            data: {
              tasks_order: tasks_order
            },
            beforeSend: function() {},
            success: function( response ) {

            }
          });
        }
      });

      $('.tasks_container .tasks_new ul').sortable({
        classes: {
          "ui-sortable": "highlight"
        },
        stop: function(event, ui) {
          var tasks_order = $( this ).sortable('toArray', { attribute: 'task_id' } );

          $.ajax({
            type: 'POST',
            cache: false,
            url: '/tasks/tasks_order_save/',
            data: {
              tasks_order: tasks_order
            },
            beforeSend: function() {},
            success: function( response ) {

            }
          });
        }
      });
    });
  <? endif;?>

  var task_refresh;
  $( 'body' ).on( 'click', '.task_start', function(e) {
    e.preventDefault();
    var task_id = $( this ).attr( 'task_id' );

    if ( task_refresh ) {
      clearInterval( task_refresh );
    }

    $.ajax({
      type: 'POST',
      cache: false,
      url: '/tasks/task_start/',
      data: {
        task_id: task_id
      },
      beforeSend: function() {},
      success: function( response ) {
        data = jQuery.parseJSON( response );
        if ( data.status == 'success' )
        {
          $( 'li.task .task_end' ).addClass( 'hidden' ).removeClass( 'animate' );
          $( 'li.task .task_start' ).removeClass( 'hidden' );
          $( 'li[task_id="' + task_id + '"] .task_start' ).addClass( 'hidden' );
          $( 'li[task_id="' + task_id + '"] .task_end' ).removeClass( 'hidden' ).addClass( 'animate' );
          $( '.task_popup .task_end' ).removeClass( 'hidden' ).addClass( 'animate' );
          $( '.task_popup .task_start' ).addClass( 'hidden' );
        }
      }
    });
  });

  $( 'body' ).on( 'click', '.task_end', function(e) {
    e.preventDefault();
    var task_id = $( this ).attr( 'task_id' );

    $.ajax({
      type: 'POST',
      cache: false,
      url: '/tasks/task_end/',
      data: {
        task_id: task_id
      },
      beforeSend: function() {},
      success: function( response ) {
        data = jQuery.parseJSON( response );
        if ( data.status == 'success' )
        {
          $( 'li[task_id="' + task_id + '"] .task_start' ).removeClass( 'hidden' );
          $( 'li[task_id="' + task_id + '"] .task_end' ).addClass( 'hidden' ).removeClass( 'animate' );
          $( '.task_popup .task_end' ).addClass( 'hidden' ).removeClass( 'animate' );
          $( '.task_popup .task_start' ).removeClass( 'hidden' );
        }
      }
    });
  });

  $( 'body' ).on( 'click', '.task_popup .task_end', function(e) {
    e.preventDefault();
    var task_id = $( this ).attr( 'task_id' );
    task_popup( task_id );
  });

  $( 'body' ).on( 'click', '.task_popup .comments .new_comment a', function(e){
    e.preventDefault();
    var task_id = $( this ).attr( 'task_id' );
    var text = $( this ).parents( '.new_comment' ).find( '.form-control' ).val();
    $.ajax({
      type: 'POST',
      cache: false,
      url: '/tasks/comment_save/',
      data: {
        text: text,
        task_id: task_id
      },
      beforeSend: function() { },
      success: function( response ) {
        task_popup( task_id );
      }
    });
    return false;
  });

  $( 'body' ).on( 'click', '.task_popup .checklist .new_element a', function(e){
    e.preventDefault();
    var task_id = $( this ).attr( 'task_id' );
    var text = $( this ).parents( '.new_element' ).find( '.form-control' ).val();
    $.ajax({
      type: 'POST',
      cache: false,
      url: '/tasks/action_save/',
      data: {
        text: text,
        task_id: task_id
      },
      beforeSend: function() { },
      success: function( response ) {
        task_popup( task_id );
      }
    });
    return false;
  });

  $( 'body' ).on( 'click', '.task_popup .comments li .delete_comment', function(e){
    e.preventDefault();
    var comment_id = $( this ).attr( 'comment_id' );

    $.confirm({
      title: 'Potwierdź',
      content: 'Na pewno chcesz usunąć wybrany komentarz?',
      type: 'orange',
      closeIcon: true,
      closeIconClass: 'fa fa-close',
      typeAnimated: true,
      animation: 'opacity',
      boxWidth: '500px',
      useBootstrap: false,
      theme: 'material',
      buttons: {
        confirm: {
          text: 'Usuń',
          btnClass: 'btn-red',
          action: function(){
            $.ajax({
              type: 'POST',
              cache: false,
              url: '/tasks/comment_delete/',
              data: {
                comment_id: comment_id
              },
              beforeSend: function() { },
              success: function( response ) {
                task_popup( $( '.task_popup .task_details' ).attr( 'task_id' ) );
              }
            });
          }
        },
        cancel: {
          text: 'Anuluj',
          btnClass: 'btn-default',
          action: function(){
          }
        }
      }
    });
  });

  $( 'body' ).on( 'click', '.task_popup .checklist li .point-delete', function(e){
    e.preventDefault();
    var action_id = $( this ).attr( 'action_id' );

    $.confirm({
      title: 'Potwierdź',
      content: 'Na pewno chcesz usunąć wybrany punkt?',
      type: 'orange',
      closeIcon: true,
      closeIconClass: 'fa fa-close',
      typeAnimated: true,
      animation: 'opacity',
      boxWidth: '500px',
      useBootstrap: false,
      theme: 'material',
      buttons: {
        confirm: {
          text: 'Usuń',
          btnClass: 'btn-red',
          action: function(){
            $.ajax({
              type: 'POST',
              cache: false,
              url: '/tasks/action_delete/',
              data: {
                action_id: action_id
              },
              beforeSend: function() { },
              success: function( response ) {
                task_popup( $( '.task_popup .task_details' ).attr( 'task_id' ) );
              }
            });
          }
        },
        cancel: {
          text: 'Anuluj',
          btnClass: 'btn-default',
          action: function(){
          }
        }
      }
    });
  });

  $( 'body' ).on( 'click', '#filtr_save_form .btn', function(e) {
    e.preventDefault();
    var name = $( '#filtr_save_form input[name="name"]' ).val();
    var projects = $( '#filtr_save_form input[name="projects"]' ).val();
    var users = $( '#filtr_save_form input[name="users"]' ).val();
    var is_default = $( '#filtr_save_form input[name="is_default"]' ).is( ':checked' ) ? 1 : 0;

    $.ajax({
      type: 'POST',
      cache: false,
      url: '/tasks/filtr_save/',
      data: {
        name: name,
        projects: projects,
        users: users,
        is_default: is_default
      },
      beforeSend: function() { },
      success: function( response ) {
        var data = jQuery.parseJSON( response );
        if ( data.status == 'success' )
        {
          // reload page
          document.location.href = '/tasks/main_view/';
        }
      }
    });
  });

  $( 'body' ).on( 'change', 'select[name="filtr"]', function(e) {
    e.preventDefault();
    var projects = $( this ).find( 'option:selected' ).attr( 'projects' );
    var users = $( this ).find( 'option:selected' ).attr( 'users' );
    if ( projects )
    {
      var projects = projects.split( "," );
      // toggle checkboxes and prevent load ajax twice
      $( '.projects_container input[name="projects"].g-checkbox' ).each( function() {
        if ( $.inArray( $( this ).val(), projects ) !== -1 )
          $( this ).attr( 'checked', 'checked' );
        else
          $( this ).removeAttr( 'checked' );
      });

      var users = users.split( "," );
      // toggle checkboxes and prevent load ajax twice
      $( '.projects_container input[name="users"].g-checkbox' ).each( function() {
        if ( $.inArray( $( this ).val(), users ) !== -1 )
          $( this ).attr( 'checked', 'checked' );
        else
          $( this ).removeAttr( 'checked' );
      });
      reload_tasks( projects, users );
    }
  });

  $( 'body' ).on( 'click', '.task_popup .task-delete', function(e) {
    e.preventDefault();
    var task_id = $( this ).attr( 'task_id' );

    $.confirm({
      title: 'Potwierdź',
      content: 'Na pewno chcesz usunąć wybrane zadanie?',
      type: 'orange',
      closeIcon: true,
      closeIconClass: 'fa fa-close',
      typeAnimated: true,
      animation: 'opacity',
      boxWidth: '500px',
      useBootstrap: false,
      theme: 'material',
      buttons: {
        confirm: {
          text: 'Usuń',
          btnClass: 'btn-red',
          action: function(){
            $.ajax({
              type: 'POST',
              cache: false,
              url: '/tasks/task_delete/',
              data: {
                task_id: task_id
              },
              beforeSend: function() { },
              success: function( response ) {
                var data = jQuery.parseJSON( response );
                if ( data.status == 'success' )
                {
                  var checkedVals = jQuery( 'input.g-checkbox:checked' ).map(function() {
                    return this.value;
                  }).get();
                  reload_tasks( checkedVals );
                  $( '.task_popup' ).empty().hide();
                }
              }
            });
          }
        },
        cancel: {
          text: 'Anuluj',
          btnClass: 'btn-default',
          action: function(){
          }
        }
      }
    });
  });

  $( 'body' ).on( 'click', '.tasks_closed i.fa-times', function(e) {
    e.preventDefault();
    document.location.href = '/tasks/main_view/tasks_closed=hide';
  });

  $( 'body' ).on( 'click', '.tasks_closed i.fa-eye', function(e) {
    e.preventDefault();
    document.location.href = '/tasks/main_view/tasks_closed=show';
  });

  $( 'body' ).on( 'click', '.tasks_bulk i.fa-eye', function(e) {
    e.preventDefault();
    document.location.href = '/tasks/main_view/tasks_bulk=show';
  });

  $( 'body' ).on( 'click', '.tasks_bulk i.fa-times', function(e) {
    e.preventDefault();
    document.location.href = '/tasks/main_view/tasks_bulk=hide';
  });

  $( 'body' ).on( 'click', '.tasks_to_review i.fa-eye', function(e) {
    e.preventDefault();
    document.location.href = '/tasks/main_view/tasks_to_review=show';
  });

  $( 'body' ).on( 'click', '.tasks_to_review i.fa-times', function(e) {
    e.preventDefault();
    document.location.href = '/tasks/main_view/tasks_to_review=hide';
  });

  $( 'body' ).on( 'change', '.task_work_date_start', function()
  {
    var date_start = $( this ).val();
    var task_work_id = $( this ).attr( 'task_work_id' );
    $( this ).attr( 'disabled', 'disabled' );

    $.ajax({
      type: 'POST',
      cache: false,
      url: '/tasks/change_task_work_date_start/',
      data: {
        date_start: date_start,
        task_work_id: task_work_id
      },
      beforeSend: function() { },
      success: function( response )
      {
        $( '.task_work_start' ).removeAttr( 'disabled' );
      }
    });
  });

  $( 'body' ).on( 'change', '.task_work_date_end', function()
  {
    var date_end = $( this ).val();
    var task_work_id = $( this ).attr( 'task_work_id' );
    $( this ).attr( 'disabled', 'disabled' );

    $.ajax({
      type: 'POST',
      cache: false,
      url: '/tasks/change_task_work_date_end/',
      data: {
        date_end: date_end,
        task_work_id: task_work_id
      },
      beforeSend: function() { },
      success: function( response )
      {
        $( '.task_work_end' ).removeAttr( 'disabled' );
      }
    });
  });

  $( 'body' ).on( 'click', '.task_popup .time_worked_toggle', function(e){
    e.preventDefault();
    $( '.task_popup .task_details' ).toggleClass( 'open_works_time' );
  });

  $( function()
  {
    $( '.projects_container input.g-checkbox').on( 'change', function (e) {
      var projects = jQuery( 'input[name="projects"].g-checkbox:checked' ).map(function() {
        return this.value;
      }).get();
      var users = jQuery( 'input[name="users"].g-checkbox:checked' ).map(function() {
        return this.value;
      }).get();
      projects.join( "," );
      users.join( "," );
      reload_tasks( projects, users );
    });

    $( 'body' ).on( 'click', '.task_work_details ._work_delete', function(e)
    {
      var work_id = $( this ).attr( 'work_id' );
      var task_id = $( this ).attr( 'task_id' );

      $.confirm({
        title: 'Potwierdź',
        content: 'Na pewno chcesz usunąć wybrane zadanie?',
        type: 'orange',
        closeIcon: true,
        closeIconClass: 'fa fa-close',
        typeAnimated: true,
        animation: 'opacity',
        boxWidth: '500px',
        useBootstrap: false,
        theme: 'material',
        buttons: {
          confirm: {
            text: 'Usuń',
            btnClass: 'btn-red',
            action: function(){
              $.ajax({
                type: 'POST',
                cache: false,
                url: '/tasks/work_delete/',
                data: {
                  work_id: work_id
                },
                beforeSend: function() { },
                success: function( response ) {
                  task_popup( task_id, true );
                }
              });
            }
          },
          cancel: {
            text: 'Anuluj',
            btnClass: 'btn-default',
            action: function(){
            }
          }
        }
      });
    });

    // fullscreen
    $('body').on('click', '.fullscreen', function (e) {
      e.preventDefault();

      const $btn = $(this);
      const $desc = $btn.closest('.description');
      const $popup = $('.task_popup');

      if ($btn.hasClass('active')) {
        // Wyjście z fullscreen
        $btn.removeClass('active');
        $popup.removeClass('fullscreen_enabled');

        // Cofnij .description do oryginalnego miejsca
        $('.description-placeholder').before($('.fullscreen_description').removeClass('fullscreen_description')).remove();

      } else {
        // Wejście w fullscreen
        $btn.addClass('active');
        $popup.addClass('fullscreen_enabled');

        const $placeholder = $('<div class="description-placeholder"></div>');
        $desc.before($placeholder);

        $('body').append($desc.addClass('fullscreen_description'));
      }
    });
  })
</script>