<script>

$("#table_filter_user").select2({
  placeholder: "Select  User"
})
$("#table_filter_work").select2({
  placeholder: "Select  Work",
  templateResult: format_project_dropdown
})

var project_tasks_view_table = $('#project_tasks_view_table').DataTable({
  "ajax":{
    url :"<?php echo base_url().'project_tasks/select_tasks' ?>", // json datasource
    type: "post", // type of method  , by default would be get
    data: function(d){
      <?php if($page_name=='tasks_view'){?>
        d.date = GetSearchDate();
        d.user = GetSearchUser();
        d.work = GetSearchwork();

        <?php }elseif($page_name=='work_profile' || $page_name=='projects_profile'){ ?>
          d.work =   "<?php echo $work_data->work_id?>";
          <?php } ?>
          <?php if($page_name=='work_profile_master' || $page_name=='work_summary_master'){?>
            d.work_ids = "<?php echo implode(',',$sub_project_ids)?>";
            <?php } ?>
        }
      },
      "bProcessing": true,
      "deferRender": true,
      "bDeferRender": true,
      "scrollX" : true,
      buttons: [
        { extend: 'print', className: 'btn dark btn-outline',exportOptions: {columns: ':visible'},title: 'Project Tasks' },
        { extend: 'csv', className: 'btn purple btn-outline ' },
        { extend: 'colvis', className: 'btn dark btn-outline', text: 'Columns'}
      ],
      dom:"<'row'<'col-sm-6 text-left'B><'col-sm-6 text-right'f>>\n\t\t\t<'row'<'col-sm-12'tr>>\n\t\t\t<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7 dataTables_pager'lp>>", // horizobtal scrollable datatable
      "lengthMenu": [
        [25, 50, 100, -1],
        [25, 50, 100, "All"] // change per page values here
      ],
      "columnDefs": [
        {
          "targets": [13,14,15,16,17,18,19,20,21<?php if($page_name=='work_profile'){ echo ",1"; }?>],
          className: "hidden"
        }
      ],
      'order': false,
      fixedColumns:   true,
      fixedColumns:   {
        leftColumns: 3
      }
    });
    // var project_tasks_activities_view_table = $('#project_tasks_activities_view_table').DataTable({
    //   "ajax":{
    //     url :"<?php echo base_url().'project_tasks/select_activities' ?>", // json datasource
    //     type: "post", // type of method  , by default would be get
    //     data: function(d){
    //       <?php if($page_name=='tasks_view'){?>
    //         d.date = GetSearchDate();
    //         d.user = GetSearchUser();
    //         d.work = GetSearchwork();
    //
    //         <?php }elseif($page_name=='work_profile' || $page_name=='projects_profile'){ ?>
    //           d.work =   "<?php echo $work_data->work_id?>";
    //           <?php } ?>
    //<?php if($page_name=='work_profile_master' || $page_name=='work_summary_master'){?>
      // d.work_ids = "<?php echo implode(',',$sub_project_ids)?>";
      // <?php } ?>
    //         }
    //       },
    //       "bProcessing": true,
    //       "deferRender": true,
    //       "bDeferRender": true,
    //       "scrollX" : true,
    //       buttons: [
    //         { extend: 'print', className: 'btn dark btn-outline',exportOptions: {columns: ':visible'} },
    //         { extend: 'csv', className: 'btn purple btn-outline ' },
    //         { extend: 'colvis', className: 'btn dark btn-outline', text: 'Columns'}
    //       ],
    //       dom:"<'row'<'col-sm-6 text-left'B><'col-sm-6 text-right'f>>\n\t\t\t<'row'<'col-sm-12'tr>>\n\t\t\t<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7 dataTables_pager'lp>>", // horizobtal scrollable datatable
    //       "lengthMenu": [
    //         [25, 50, 100, -1],
    //         [25, 50, 100, "All"] // change per page values here
    //       ],
    //       "columnDefs": [
    //         {
    //           "targets": [],
    //           className: "hidden"
    //         }
    //       ],
    //       'order': false
    //     });
    $(".hide_column").hide();
    $(".hidden").hide();

    function removeProgressStyles(){
      $('#progressbar_update_bar').removeClass('bg-warning');
      $('#task_rogress_value').removeClass('text-warning');
      $('#progressbar_update_bar').removeClass('bg-success');
      $('#task_rogress_value').removeClass('text-success');
      $('#task_rogress_value').removeClass('text-danger');
    }
    function removeProgressStyles2(){
      $('#task_progress_popup').removeClass('bg-warning');
      $('#task_rogress_value2').removeClass('text-warning');
      $('#task_progress_popup').removeClass('bg-success');
      $('#task_rogress_value2').removeClass('text-success');
      $('#task_rogress_value2').removeClass('text-danger');
    }



    $('body').on('click', '#new_activity_task', function() {
      var task_id = $('#data-task-id').val();
      $('#activity_add_task_id').val(task_id).trigger('change');
      $('#activity_add_task_id').attr('disabled',true);
    });

    $('body').on('click', '#project_task_activity_edit_btn', function() {
      var no = $(this).closest('tr').children('td');
      $('#activity_id_edit').val(no.eq(7).text());
      $('#activity_title_edit').val(no.eq(1).text());
      $('#activity_description_edit').val(no.eq(2).text());
      $('#activity_date_edit').datepicker("setDate", no.eq(3).text());
    });
    $('body').on('click', '#project_task_edit_btn', function() {
      var no = $(this).closest('tr').children('td');
      $('#project_task_title_edit').val(no.eq(2).text());
      $('#project_task_description_edit').val(no.eq(3).text());
      $('#project_task_id_edit').val(no.eq(13).text());
      $('#task_assigned_to_edit').val(no.eq(19).text()).trigger('change');
      $('#project_task_start_date_edit').datepicker("setDate", no.eq(17).text());
      $('#project_task_end_date_edit').datepicker("setDate", no.eq(18).text());
      $('#project_task_start_date_actual_edit').datepicker("setDate", no.eq(20).text());
      $('#project_task_end_date_actual_edit').datepicker("setDate", no.eq(21).text());
    });

    $('body').on('click', '#project_task_edit_btn_subtask', function() {
      var no = $(this).closest('tr').children('td');
      $('.subtask_edit').html('Sub ');
      $('#project_task_title_edit').val(no.eq(1).text());
      $('#project_task_description_edit').val(no.eq(10).text());
      $('#project_task_id_edit').val(no.eq(0).text());
      $('#project_task_start_date_edit').datepicker("setDate", no.eq(8).text());
      $('#project_task_end_date_edit').datepicker("setDate", no.eq(9).text());
      $('#project_task_start_date_actual_edit').datepicker("setDate", no.eq(11).text());
      $('#project_task_end_date_actual_edit').datepicker("setDate", no.eq(12).text());
      $('#task_assigned_to_edit').val(no.eq(13).text()).trigger('change');
    });

    var progress_slider = document.getElementById("task_progress");
    noUiSlider.create(progress_slider, {
      start: [0],
      step: 0.5,
      range: {
        min: [0],
        max: [100]
      },
      tooltips: [!0],
      format: wNumb({
        decimals: 1
      })
    });


    var n = document.getElementById("task_progress_current_value");
    progress_slider.noUiSlider.on("update", function(e, t) {
      // n.value = e[t]
      if(parseFloat(e[t])>=n.value){
        var current_progress = e[t];
        $("#task_progress_value").val(current_progress);
        $('#progressbar_update_bar').attr('aria-valuenow',current_progress);
        $('#progressbar_update_bar').attr('style','width: '+current_progress+'%');
        $('#task_rogress_value').html(current_progress+' %');
        if(current_progress==100){
          removeProgressStyles();
          $('#progressbar_update_bar').addClass('bg-success');
          $('#task_rogress_value').addClass('text-success');
        }
        else if(current_progress>0 && current_progress<25){
          removeProgressStyles();
          $('#progressbar_update_bar').addClass('bg-warning');
          $('#task_rogress_value').addClass('text-warning');
        }
        else if(current_progress==0){
          removeProgressStyles();
          $('#task_rogress_value').addClass('text-danger');
        }
        else{
          removeProgressStyles();
        }
      }
    })
    //popup
    <?php if($this->session->userdata('user_role')=='admin' || $this->session->userdata('user_role')=='madmin' || $this->session->userdata('user_role')=='general_manager'){ ?>
      var progress_slider2 = document.getElementById("task_progress2");
      noUiSlider.create(progress_slider2, {
        start: [0],
        step: 0.5,
        range: {
          min: [0],
          max: [100]
        },
        tooltips: [!0],
        format: wNumb({
          decimals: 1
        })
      });
      var n = document.getElementById("task_progress_current_value2");
      progress_slider2.noUiSlider.on("update", function(e, t) {
        // n.value = e[t]
        if(parseFloat(e[t])>=n.value){
          var current_progress = e[t];
          $("#task_progress_value2").val(current_progress);
          $('#task_progress_popup').attr('aria-valuenow',current_progress);
          $('#task_progress_popup').attr('style','width: '+current_progress+'%');
          $('#task_rogress_value2').html(current_progress+' %');
          if(current_progress==100){
            removeProgressStyles2();
            $('#task_progress_popup').addClass('bg-success');
            $('#task_rogress_value2').addClass('text-success');
          }
          else if(current_progress>0 && current_progress<25){
            removeProgressStyles2();
            $('#task_progress_popup').addClass('bg-warning');
            $('#task_rogress_value2').addClass('text-warning');
          }
          else if(current_progress==0){
            removeProgressStyles2();
            $('#task_rogress_value2').addClass('text-danger');
          }
          else{
            removeProgressStyles2();
          }
        }
      })
      <?php } ?>
      $('body').on('click', '#project_task_progress_update_btn_subtask', function() {
        var no = $(this).closest('tr').children('td');
        var progress = parseFloat($(this).data('progress'));
        if(isNaN(progress)){
          progress = 0;
        }
        $('#project_task_id_progress').val(no.eq(0).text());
        $('#progressbar_update_bar').attr('aria-valuenow',progress);
        $('#progressbar_update_bar').attr('style','width: '+progress+'%');
        $('#task_progress_value').val(progress);
        $('#task_progress_current_value').val(progress);
        progress_slider.noUiSlider.updateOptions({
          start: [progress]
        });

      });



      $('body').on('click', '#project_task_delete_btn', function() {
        var no = $(this).closest('tr').children('td');
        $('#project_task_id_delete').val(no.eq(13).text());
      });
      $('body').on('click', '#project_task_delete_btn_subtask', function() {
        var no = $(this).closest('tr').children('td');
        $('.subtask_delete').html('Sub ');
        $('#project_task_id_delete').val(no.eq(0).text());
      });
      $('body').on('click', '#project_task_progress_update_btn', function() {
        var no = $(this).closest('tr').children('td');
        $('#project_task_id_progress').val(no.eq(13).text());
        $('#task_progress_value').val(no.eq(15).text());
        $('#task_progress_current_value').val(no.eq(15).text());
        var progress = parseFloat(no.eq(15).text());
        progress_slider.noUiSlider.updateOptions({
          start: [progress]
        });
      });
      $('body').on('click', '#project_task_activity_delete_btn', function() {
        var no = $(this).closest('tr').children('td');
        $('#project_task_activity_id_delete').val(no.eq(1).text());
      });
      $('body').on('click', '#add_activity_btn_task', function() {
        var no = $(this).closest('tr').children('td');
        $('#activity_add_task_id').val(no.eq(13).text()).trigger('change');
        $('#activity_add_task_id_value').val(no.eq(13).text());
        $('#activities_add_task_select').hide();
      });
      $('body').on('click', '#project_task_add_modal_button', function() {
        $('#parent_task_id').val(0);
        $('.subtask_t').html('');
        $('#task_assigned').show();
      });
      $('body').on('click', '.schedule_task_view_btn', function() {
        var no = $(this).closest('tr').children('td');
        var id = $(this).data('task-id');
        task_view(id);
      });
      function task_view(id){
        $('#data-task-id').val(id);
        $("#subtask_table_body").html('');
        get_activities(id);
        get_task_info(id);
        get_subtask(id);
        //disable onclick for project task
        $.post("<?php echo base_url() ?>project_tasks/select_tasks",{list_type:"json",task_id:id},function (data) {
          var obj=$.parseJSON(data);
          if(obj.data.length > 0){
            $('#project_task_popup_modal').modal('show'); //shows the modal if it is not the project task
          }
        });
      }
      $('#project_task_popup_modal').on('hidden.bs.modal', function () {
        $(this).find('form').trigger('reset');
        $("#task_id_popup").html('');
        $("#task_desc_popup").html('');
        $("#task_supervisor_popup").html('');
        $("#task_name_popup").html('');
        $("#task_start_popup").html('');
        $("#task_end_popup").html('');
        $("#task_complete_popup").html('');
        $("#subtask_table_body").html('');
      });
      $('body').on('click', '#new_subtask', function() {
        var parent_id = $("#task_id_popup").html();
        $('#parent_task_id').val(parent_id);
        $('.subtask_t').html('Sub');
        $('#task_assigned').hide();
      });
      $('body').on('click', '#new_task_schedule', function() {
        $('#parent_task_id').val('');
        $('.subtask_t').html('');
        $('#task_assigned').show();
      });
      $('body').on('click', '#add_task_activity', function() {
        var no = $(this).closest('tr').children('td');
        $('#activity_add_task_id').val('');
        var parent_id = $("#task_id_popup").html();
        $('#parent_task_id').val(parent_id);
      });
      $('body').on('click', '#new_activity_task', function() {
        var id = $("#data-task-id").val();
        $('#activity_add_task_id').val(id).trigger('change');
        $('#activity_add_task_id_value').val(id);
        $('#activities_add_task_select').hide();
      });
      $('#project_task_add_modal,#project_task_progress_update_modal,#add_activity_btn_task,#add_task_activity,#new_activity_task').on('hidden.bs.modal', function () {
        $(this).find('form').trigger('reset');
      })

      $("#schedule_import_from_work_id").select2({
        placeholder: "Select Project",
        dropdownParent: $("#form_project_schedule_import"),
        templateResult: format_project_dropdown
      })
      $("#schedule_import_task_assigned_to").select2({
        placeholder: "Select Supervisor",
        dropdownParent: $("#form_project_schedule_import")
      })
      $("#task_assigned_to").select2({
        placeholder: "Select Supervisor",
        dropdownParent: $("#form_project_task_add")
      })
      $("#project_tasks_work_id").select2({
        placeholder: "Select Work",
        dropdownParent: $("#form_project_task_add"),
        templateResult: format_project_dropdown
      })
      $("#activity_add_task_id").select2({
        placeholder: "Select Task",
        dropdownParent: $("#form_project_task_activity_add")
      })
      $("#activity_edit_task_id").select2({
        placeholder: "Select Task",
        dropdownParent: $("#form_project_task_activity_edit")
      })
      $("#task_assigned_to_edit").select2({
        placeholder: "Select Supervisor",
        dropdownParent: $("#form_project_task_edit")
      })
      $("#planned_start_date,#planned_end_date,#activity_date,#project_task_start_date_edit,#project_task_end_date_edit").datepicker( {
        todayHighlight:!0, orientation:"bottom left", templates: {
          leftArrow: '<i class="la la-angle-left"></i>', rightArrow: '<i class="la la-angle-right"></i>'
        }
      })

      </script>
      <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
      <script src="https://code.highcharts.com/highcharts.js"></script>
      <script>


      function get_activities(task_id) {
        $.post("<?php echo base_url() ?>project_tasks/select_tasks_activities",{task_id:task_id},function (data) {
          var obj=$.parseJSON(data);
          $("#project_tasks_activities_table_body").html('');
          if(parseInt(obj.activity_count)>0){
            var content=obj.content;
            $("#project_tasks_activities_table_body").append(content);
          }
          // $('#project_tasks_activities_view_table').dataTable().fnDestroy();
          // activity_table();
        });
      };
      function get_task_info(task_id) {
        $.post("<?php echo base_url() ?>project_tasks/select_tasks/task_info",{task_id:task_id},function (data) {
          var obj=$.parseJSON(data);
          if(obj.data.length == 0){
            $("#task_id_popup").html(0);
          }
          else{
            $(".project_task_details_modal_tabs").removeClass('active show');
            $(".project_task_details_modal_info_tab").addClass('active show');
            if(obj.data[0]['parent_id']!=0){
              $("#new_subtask").addClass('shownothing');
              $("#subtask_table_body").addClass('shownothing');
              $("#subtask_table").addClass('shownothing');
              $("#subtask_tab_pan").addClass('shownothing');
              $("#project_task_popup_modal_title").text('Project Task Details - Sub Task');
            }
            else{
              $("#new_subtask").removeClass('shownothing');
              $("#subtask_table_body").removeClass('shownothing');
              $("#subtask_table").removeClass('shownothing');
              $("#subtask_tab_pan").removeClass('shownothing');
              $("#project_task_popup_modal_title").text('Project Task Details - Main Task');
            }
            $("#task_id_popup").html(obj.data[0]['id']);
            $("#task_id_popup_update_progress").val(obj.data[0]['id']);
            $("#task_name_popup").val(obj.data[0]['name']);
            $("#task_start_popup").val(obj.data[0]['start_date_planned']);
            $("#task_end_popup").val(obj.data[0]['end_date_planned']);
            $("#task_start_popup_actual").val(obj.data[0]['start_date_actual']);
            $("#task_end_popup_actual").val(obj.data[0]['end_date_actual']);
            $("#task_rogress_value2").html(obj.data[0]['progress']+" %  ");
            $("#task_progress_popup").attr('aria-valuenow',obj.data[0]['progress']);
            $("#task_progress_popup").attr('style','width: '+obj.data[0]['progress']+'%');
            $("#task_desc_popup").val(obj.data[0]['task_desc']);
            $("#task_supervisor_popup").val(obj.data[0]['supervisor']);


          }
        });
      };
      function get_subtask(task_id) {
        $("#subtask_table_body").html('');
        $.post("<?php echo base_url() ?>project_tasks/select_tasks/task_info",{parent_id:task_id},function (data) {
          var obj=$.parseJSON(data);
          var count=obj.data.length;
          var subtasks = obj.data.reverse();
          var new_row ='';
          for (var row = 0; row < count; row++) {
            var slno = row+1;
            new_row += "<tr><th scope='row'>"+slno+"</th><td class='hidden'>"+subtasks[row]['id']+"</td><td>"+subtasks[row]['name']+"</td><td>"+subtasks[row]['assigned_to']+"</td><td>Planned :"+subtasks[row]['start_date_planned']+"<br>Actual :"+subtasks[row]['start_date_actual']+"</td><td>Planned :"+subtasks[row]['end_date_planned']+"<br>Actual :"+subtasks[row]['end_date_actual']+"</td><td class='hidden'>"+subtasks[row]['progress']+"</td><td>"+subtasks[row]['progress']+' %'+"</td><td>"+subtasks[row]['action_btn']+"</td><td class='hidden'>"+subtasks[row]['start_date_planned']+"</td><td class='hidden'>"+subtasks[row]['end_date_planned']+"</td><td class='hidden'>"+subtasks[row]['description']+"</td><td class='hidden'>"+subtasks[row]['start_date_actual']+"</td><td class='hidden'>"+subtasks[row]['end_date_actual']+"</td><td class='hidden'>"+subtasks[row]['supervisor_id']+"</td></tr>";
            // $("#subtask_table_body").append(new_row);
          };
          $("#subtask_table_body").html(new_row);
        });
      };
      function select_tasks(selectid,selected_task){
        var work_id = <?php echo $work_data->work_id?>;
        $('#'+selectid).html('');
        $('#'+selectid).append("<option disabled selected >Select Task</option>");
        $.post("<?php echo base_url() ?>project_tasks/get_tasks",{work_id:work_id},function(data) {
          var obj = $.parseJSON(data);
          var i=0;
          if(obj.count>0) {
            while (i < obj.id.length) {
              $('#'+selectid).append("<option value=" + obj.id[i] + ">" + obj.name[i] + "</option>");
              i++;
            }
            if(selected_task!=''){
              $('#'+selectid).val(selected_task).trigger("change");
            }
          }
        })
      }
      select_tasks('activity_add_task_id');
      select_tasks('activity_edit_task_id');
      // function activity_table() {
      //   var project_tasks_activities_view_table = $('#project_tasks_activities_view_table').dataTable({
      //     "scrollX" : true,
      //     "columnDefs": [
      //     {
      //       "targets": [],
      //       className: "hidden"
      //     }
      //     ],
      //     "bFilter": true,
      //     "bInfo" : true,
      //     'order': false,
      //     'ordering':false,
      //     "pageLength":100
      //   });
      // };

      <?php if($page_name=='work_profile' || $page_name=='work_profile_master'){?>
        function export_gantt(){
          gantt.exportToPDF({
            name:"<?php echo $work_data->work_name ?> - schedule.pdf",
            // skin:"material"
          });
        }
        gantt.attachEvent("onParse", function(){
          $("#btn_gantt_export").show();
        });
        gantt.config.date_format = "%Y-%m-%d";
        gantt.config.highlight_critical_path = true;
        // gantt.config.resource_property = "supervisor_id";
        // gantt.config.resource_store = "supervisors";
        // gantt.locale.labels.section_owner = "Supervisor";

        // gantt.serverList("supervisors", [
        //     {key: 1, label: "John"},
        //     {key: 2, label: "Mike"},
        //     {key: 3, label: "Anna"},
        //     {key: 4, label: "Bill"},
        //     {key: 7, label: "Floe"}
        // ]);
        function initialise_gantt(){
          var zoomConfig = {
            levels: [
              {
                name:"day",
                scale_height: 27,
                min_column_width:80,
                scales:[
                  {unit: "day", step: 1, format: "%d %M"}
                ]
              },
              {
                name:"week",
                scale_height: 50,
                min_column_width:50,
                scales:[
                  {unit: "week", step: 1, format: function (date) {
                    var dateToStr = gantt.date.date_to_str("%d %M");
                    var endDate = gantt.date.add(date, -6, "day");
                    var weekNum = gantt.date.date_to_str("%W")(date);
                    return "#" + weekNum + ", " + dateToStr(date) + " - " + dateToStr(endDate);
                  }},
                  {unit: "day", step: 1, format: "%j %D"}
                ]
              },
              {
                name:"month",
                scale_height: 50,
                min_column_width:120,
                scales:[
                  {unit: "month", format: "%F, %Y"},
                  {unit: "week", format: "Week #%W"}
                ]
              },
              {
                name:"quarter",
                height: 50,
                min_column_width:90,
                scales:[
                  {unit: "month", step: 1, format: "%M"},
                  {
                    unit: "quarter", step: 1, format: function (date) {
                      var dateToStr = gantt.date.date_to_str("%M");
                      var endDate = gantt.date.add(gantt.date.add(date, 3, "month"), -1, "day");
                      return dateToStr(date) + " - " + dateToStr(endDate);
                    }
                  }
                ]
              },
              {
                name:"year",
                scale_height: 50,
                min_column_width: 30,
                scales:[
                  {unit: "year", step: 1, format: "%Y"}
                ]
              }
            ]
          };

          gantt.ext.zoom.init(zoomConfig);
          gantt.ext.zoom.setLevel("day");
          gantt.ext.zoom.attachEvent("onAfterZoom", function(level, config){
            document.querySelector(".gantt_radio[value='" +config.name+ "']").checked = true;
          })
          gantt.templates.rightside_text = function (start, end, task) {
            if (task.planned_end) {
              if (end.getTime() > task.planned_end.getTime()) {
                var overdue = Math.ceil(Math.abs((end.getTime() - task.planned_end.getTime()) / (24 * 60 * 60 * 1000)))-1;
                if(overdue>0){
                  var text = "<b>Overdue: " + overdue + " days</b>";
                  return text;
                }
              }
            }
          };
          gantt.templates.scale_cell_class = function (date) {
            if (date.getDay() == 0 || date.getDay() == 6) {
              return "weekend";
            }
          };
          gantt.templates.timeline_cell_class = function (item, date) {
            if (date.getDay() == 0 || date.getDay() == 6) {
              return "weekend"
            }
          };
          gantt.attachEvent("onGanttReady", function(){
            var tooltips = gantt.ext.tooltips;
            tooltips.tooltip.setViewport(gantt.$task_data);
          });
          // gantt.config.grid_width = 200;
          gantt.config.task_height = 16;
          gantt.config.row_height = 40;
          gantt.attachEvent("onTaskLoading", function(task){
            task.planned_start = gantt.date.parseDate(task.planned_start, "xml_date");
            task.planned_end = gantt.date.parseDate(task.planned_end, "xml_date");
            return true;
          });
          gantt.addTaskLayer(function draw_planned(task) {
            if (task.planned_start && task.planned_end) {
              var sizes = gantt.getTaskPosition(task, task.planned_start, task.planned_end);
              var el = document.createElement('div');
              el.className = 'baseline';
              el.style.left = sizes.left + 'px';
              el.style.width = sizes.width + 'px';
              el.style.top = sizes.top + gantt.config.task_height  + 13 + 'px';
              return el;
            }
            return false;
          });

          gantt.templates.tooltip_text = function(start,end,task){
            return "<b>Task:</b> "+task.text+"<br/><b>Start date:</b> " +
            gantt.templates.tooltip_date_format(start)+
            "<br/><b>End date:</b> "+gantt.templates.tooltip_date_format(end)+"<br/><b>Duration:</b> " + task.duration+" Days";
          };
          gantt.config.lightbox.sections = [
            {name: "description", height: 70, map_to: "text", type: "textarea", focus: true},
            {name: "time", height: 72, map_to: "auto", type: "duration"},
            {name: "baseline", height: 72, map_to: {
              start_date: "planned_start", end_date: "planned_end"}, type: "duration"}
            ];
            gantt.locale.labels.section_baseline = "Planned";
            gantt.config.readonly = true;
            gantt.init("gantt_here");
            var work_id = <?php echo $work_data->work_id?>;
            gantt.load("<?php echo base_url() ?>project_tasks/select_tasks/chart/"+work_id+"/gantt", "json");
            gantt.attachEvent("onTaskClick", function(id,e){
              //any custom logic here
              $('#data-task-id').val(id);
              $("#subtask_table_body").html('');
              get_activities(id);
              get_task_info(id);
              get_subtask(id);
              //disable onclick for project task
              $.post("<?php echo base_url() ?>project_tasks/select_tasks",{list_type:"json",task_id:id},function (data) {
                var obj=$.parseJSON(data);
                if(obj.data.length > 0){
                  $('#project_task_popup_modal').modal('show'); //shows the modal if it is not the project task
                }
              });
              //end of diable
            });
            var radios = document.getElementsByName("scale");
            for (var i = 0; i < radios.length; i++) {
              radios[i].onclick = function (event) {
                gantt.ext.zoom.setLevel(event.target.value);
              };
            }
          }
          function toggleMode(toggle) {
            toggle.enabled = !toggle.enabled;
            if (toggle.enabled) {
              toggle.innerHTML = "Set default Scale";
              //Saving previous scale state for future restore
              saveConfig();
              zoomToFit();
            } else {

              toggle.innerHTML = "Zoom to Fit";
              //Restore previous scale state
              restoreConfig();
              task.render = "split";
              gantt.render();
            }
          }

          var cachedSettings = {};

          function saveConfig() {
            var config = gantt.config;
            cachedSettings = {};
            cachedSettings.scales = config.scales;
            cachedSettings.start_date = config.start_date;
            cachedSettings.end_date = config.end_date;
          }

          function restoreConfig() {
            applyConfig(cachedSettings);
          }

          function applyConfig(config, dates) {

            gantt.config.scales = config.scales;

            if (dates && dates.start_date && dates.end_date) {
              gantt.config.start_date = gantt.date.add(dates.start_date, -1, config.scales[0].subscale_unit);
              gantt.config.end_date = gantt.date.add(gantt.date[config.scales[0].subscale_unit + "_start"](dates.end_date), 2, config.scales[0].subscale_unit);
            } else {
              gantt.config.start_date = gantt.config.end_date = null;
            }
          }


          function zoomToFit() {
            var project = gantt.getSubtaskDates(),
            areaWidth = gantt.$task.offsetWidth;

            for (var i = 0; i < scaleConfigs.length; i++) {
              var columnCount = getUnitsBetween(project.start_date, project.end_date, scaleConfigs[i].scales[0].subscale_unit, scaleConfigs[i].scales[0].step);
              if ((columnCount + 2) * gantt.config.min_column_width <= areaWidth) {
                break;
              }
            }

            if (i == scaleConfigs.length) {
              i--;
            }

            applyConfig(scaleConfigs[i], project);
            task.render = "split";
            gantt.render();
          }

          // get number of columns in timeline
          function getUnitsBetween(from, to, unit, step) {
            var start = new Date(from),
            end = new Date(to);
            var units = 0;
            while (start.valueOf() < end.valueOf()) {
              units++;
              start = gantt.date.add(start, step, unit);
            }
            return units;
          }

          //Setting available scales
          var scaleConfigs = [
            // minutes
            {
              scales: [
                {subscale_unit: "minute", unit: "hour", step: 1, format: "%H"},
                {unit: "minute", step: 1, format: "%H:%i"}
              ]
            },
            // hours
            {
              scales: [
                {subscale_unit: "hour", unit: "day", step: 1, format: "%j %M"},
                {unit: "hour", step: 1, format: "%H:%i"}

              ]
            },
            // days
            {
              scales: [
                {subscale_unit: "day", unit: "month", step: 1, format: "%F"},
                {unit: "day", step: 1, format: "%j"}
              ]
            },
            // weeks
            {
              scales: [
                {subscale_unit: "week", unit: "month", step: 1, date: "%F"},
                {
                  unit: "week", step: 1, template: function (date) {
                    var dateToStr = gantt.date.date_to_str("%d %M");
                    var endDate = gantt.date.add(gantt.date.add(date, 1, "week"), -1, "day");
                    return dateToStr(date) + " - " + dateToStr(endDate);
                  }
                }
              ]
            },
            // months
            {
              scales: [
                {subscale_unit: "month", unit: "year", step: 1, format: "%Y"},
                {unit: "month", step: 1, format: "%M"}
              ]
            },
            // quarters
            {
              scales: [
                {subscale_unit: "month", unit: "year", step: 3, format: "%Y"},
                {
                  unit: "month", step: 3, template: function (date) {
                    var dateToStr = gantt.date.date_to_str("%M");
                    var endDate = gantt.date.add(gantt.date.add(date, 3, "month"), -1, "day");
                    return dateToStr(date) + " - " + dateToStr(endDate);
                  }
                }
              ]
            },
            // years
            {
              scales: [
                {subscale_unit: "year", unit: "year", step: 1, date: "%Y"},
                {
                  unit: "year", step: 5, template: function (date) {
                    var dateToStr = gantt.date.date_to_str("%Y");
                    var endDate = gantt.date.add(gantt.date.add(date, 5, "year"), -1, "day");
                    return dateToStr(date) + " - " + dateToStr(endDate);
                  }
                }
              ]
            },
            // decades
            {
              scales: [
                {
                  subscale_unit: "year", unit: "year", step: 10, template: function (date) {
                    var dateToStr = gantt.date.date_to_str("%Y");
                    var endDate = gantt.date.add(gantt.date.add(date, 10, "year"), -1, "day");
                    return dateToStr(date) + " - " + dateToStr(endDate);
                  }
                },
                {
                  unit: "year", step: 100, template: function (date) {
                    var dateToStr = gantt.date.date_to_str("%Y");
                    var endDate = gantt.date.add(gantt.date.add(date, 100, "year"), -1, "day");
                    return dateToStr(date) + " - " + dateToStr(endDate);
                  }
                }
              ]
            }
          ];
          function zoomIn(){
            gantt.ext.zoom.zoomIn();
          }
          function zoomOut(){
            gantt.ext.zoom.zoomOut()
          }
          initialise_gantt();
          <?php } ?>

          // $('#project_tasks_activities_view_table').dataTable().fnDestroy();
          // activity_table();
          //   $('body').on('click', '#subtask_tab_btn', function() {
          //     $('#project_tasks_activities_view_table').dataTable().fnDestroy();
          //     activity_table();
          //   });

          $('.schedule_tabs').on('click', function(e){
            var table_name = $(this).attr('data-table-name');
            if(table_name!=''){
              var tables = table_name.split(',');
              $.each(tables, function( index, value ){
                var table_name = value;
                eval(table_name).ajax.reload();
              });
            }
          });

          $("#form_project_schedule_import").validate( {
            rules: {
              from_work_id: {
                required: !0
              }
            },
            invalidHandler:function(e, r) {
              var i=$("#form_project_schedule_import_msg");
              i.removeClass("m--hide").show(), mUtil.scrollTo(i, -200)
            }
            , submitHandler:function(e) {

              this.submit();
            }
          });
          </script>
          <style type="text/css">
          .tab-content1 {
            color : white;
            background-color: #428bca;
            padding : 5px 15px;
          }
          .nav-pills1 > li > a {
            border-radius: 0;
          }
          </style>
