<?php 
    // continue the session
    session_start();

    // Add includes to PHP files that I will need to access
    include_once dirname(__FILE__) . '/php_only_scripts/global_functions.php';
    include_once dirname(__FILE__) . '/php_only_scripts/database.php';
    include_once dirname(__FILE__) . '/php_only_scripts/presentation.php';
    include_once dirname(__FILE__) . '/php_only_scripts/tasks_presentation.php';
    include_once dirname(__FILE__) . '/php_only_scripts/note_presentation.php';
    
    // Init some variables
    $userRow=null;

    // Assume NOT gtg
    $gtg = false;

    // Create and Setup the database
    $db = new Database();
    $db->setupTmsDB();

    // Attempt to log in with this user
    $currentUser = $db->getLoggedInSessionUser(session_id());
    
    // Set passing variables to defaults
    $selectedCompany=-1;
    $selectedStatus=-1;
    $typeTab=1;
    $showWhatFinishedState=0;
    $taskSearchPhrase='';
    $sortNumber=1;
    $tasksPerPage=0;
    $currentPage=1;
        
    // If there is only one result for a username/password combo, then they are good to go.
    if ($currentUser == null){
        // redirect to the login page
        echo ('<script>window.location = ".";</script>');
    }
    elseif (mysqli_num_rows($currentUser)==1){
        // Attempt to get the user row
        $userRow = $currentUser->fetch_assoc();
        
        // Determine if this user has access to this page
        if ($userRow["UserLevel"]=='TIMECARD ONLY' ||
            $userRow["AccountStatus"]!='ACTIVE'){
            // redirect to the invalid access page
            echo ('<script>window.location = "invalid_access.php";</script>');

            exit;
        }
        
        // Set the good to go until they log out
        $gtg = true;

        // Determine if the company combo box changed
        if (isset($_GET['cs'])){
            // Set the session variable to the new value of the combo box
            $selectedCompany = rawurldecode($_GET['cs']);
        }
        
        // Determine if the status combo box changed
        if (isset($_GET['s'])){
            // Set the session variable to the new value of the combo box
            $selectedStatus = rawurldecode($_GET['s']);
        }
        
        // Determine if the type is passed in
        if (isset($_GET['ts'])){
            // Set the session variable type to the one passed in
            $typeTab = rawurldecode($_GET['ts']);
        }
        
        // Determine what type of finished state they want to see 
        if (isset($_GET['sfs'])){
            // Change the option to show whatever they are asking for
            $showWhatFinishedState=rawurldecode($_GET['sfs']);
        }
        
        // Determine how many tasks per page they would like to see
        if (isset($_GET['tpp'])){
            // Change the option to show whatever they are asking for
            $tasksPerPage=rawurldecode($_GET['tpp']);
        }
        
        // Determine what current page we are on
        if (isset($_GET['cp'])){
            // Change the option to show whatever they are asking for
            $currentPage=rawurldecode($_GET['cp']);
        }
        
        // Determine if there is a search phrase
        if (isset($_GET['sp'])){
            // Set the search phrase
            $taskSearchPhrase=rawurldecode($_GET['sp']);
        }

        // Determine if there is a sort preference
        if (isset($_GET['sn']) ){
            // Hold onto the sort info
            $sortNumber = rawurldecode($_GET['sn']);
        }
    }
?>
        
﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Task Management System - Tasks</title>

    <meta name="keywords" content="GIS,data,testing,IT" />
    <meta name="description" content="EES Divisions." />
    <?php
        // determine if the refresh rate is a positive number
        if ($userRow["RefreshRate"]>0){
            // Add the refresh rate line
            echo('<meta http-equiv="refresh" content="' . $userRow["RefreshRate"] . '"/>');
        }
    ?>

    <script src="javascript/general.js" type="text/javascript"></script>
    <script src="javascript/notes.js" type="text/javascript"></script>
    
    <script src="./SpryAssets/SpryMenuBar.js" type="text/javascript"></script>
    <script src="scripts/jquery-ui-1.10.4.custom/js/jquery-1.10.2.js" type="text/javascript"></script>
    <script src="scripts/jquery-ui-1.11.4.custom/jquery-ui.js" type="text/javascript"></script>

    <link rel="icon" href="images/ees_ico.ico"/> 
    <link href="scripts/jquery-ui-1.10.4.custom/development-bundle/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css"/>
    <link href="./SpryAssets/SpryMenuBarHorizontal.css" rel="stylesheet" type="text/css" />
    <link href="./SpryAssets/SpryMenuBarVertical.css" rel="stylesheet" type="text/css" />
    <link rel = "stylesheet" type="text/css" href="./css/contentpage.css" >
        
    <style type="text/css">
        #tasks_sortable
        #tasks_sortable { list-style-type: none; margin: 0; padding: 0; width: 100%; }
        #tasks_sortable li { margin: 0 0 5px 0; padding: 5px 0 5px 0;}

        .Table
        {
            display: table;
            width: 100%;
        }
        .Title
        {
            display: table-caption;
            text-align: center;
            font-weight: bold;
            font-size: larger;
            width: 100%;
        }
        .Heading
        {
            display: table-row;
            font-weight: bold;
            text-align: center;
            width: 100%;
        }
        .Row
        {
            display: table-row;
            width: 100%;
        }
        .cell
        {
            display: table-cell;
            border: solid;
            border-width: thin;
            padding-left: 2px;
            padding-right: 2px;
            font-weight: bold;
            font-size: 11px;
            vertical-align: middle;
        }
        .childrenCell
        {
            width: 100%;
            text-align: right;
        }
        .dateCell
        {
            width: 14%;
            text-align: center;
        }
        .taskIDCell
        {
            width: 10%;
            text-align: center;
        }
        .updateCell
        {
            width: 14%;
            text-align: center;
        }
        .statusCell
        {
            width: 19%;
        }
        .companyCell
        {
            width: 14%;
        }
        .priCell
        {
            width: 4%;
            text-align: center;
        }
        .btn {
          border-left: solid dimgray 1px;
          border-right: solid dimgray 1px;
          border-top: none;
          border-bottom: solid dimgray 1px;
          background-color: lightgrey;
          color: dimgray;
          font-size: 16px;
          cursor: pointer;
          font-weight: bold;
        }        
        span {
            width:100%;
/*          display: inline-block;
          vertical-align: middle;
          line-height: normal;      */
        }
        /*----------------------------------------------
        CSS settings for the users dialog
        ------------------------------------------------*/
        #addStickyNote{
            display:none;
            text-align: center;
        }
        .ui-dialog {
            z-index: 9999 !important;
        }        
        .ui-widget-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
        }    
        .ui-button {
                width: 5em;
        }
        .ui-button-text-only .ui-button-text {
                padding: 2px 5px 5px 2px;
        }
        /*----------------------------------------------
        CSS settings for expedite background
        ------------------------------------------------*/
        .expediteTaskBackground {
            background:repeating-linear-gradient(
                90deg,
                rgba(255, 0, 127, 1),
                rgba(255, 0, 127, 1) 10px,
                rgba(77, 77, 77, .5) 10px,
                rgba(77, 77, 77, .5) 20px
            );
        }

    </style>
    <script>
        var sessionID = "<?php echo session_id(); ?>";
        var taskIDStickyNote = -1;
        
        function ActivateTab(tabNumber) {
            // Activate the appropriate tab
            document.getElementById('theTab' . tabNumber).click();
        }
        
        function CreateURLSearchVariables() {
            // Get all of the variables
            var showWhatFinishedState = document.getElementById('showWhatFinishedState').value===null?'sfs=0':'sfs=' + encodeURIComponent(document.getElementById('showWhatFinishedState').value);
            var tasksPerPage = document.getElementById('tasksPerPage').value===null?'&tpp=30':'&tpp=' + encodeURIComponent(document.getElementById('tasksPerPage').value);
            var companySelected = document.getElementById('companySelected').value===null?'&cs=-1':'&cs=' + encodeURIComponent(document.getElementById('companySelected').value);
            var statusSelected = document.getElementById('statusSelected').value===null?'&s=-1':'&s=' + encodeURIComponent(document.getElementById('statusSelected').value);
            var searchPhrase = document.getElementById('searchPhrase').value===''?'':'&sp=' + encodeURIComponent(document.getElementById('searchPhrase').value);
            var typeSelected = document.getElementById('typeSelected').value===null?'&ts=1':'&ts='+encodeURIComponent(document.getElementById('typeSelected').value);
            var sortNumber = document.getElementById('sortNumber').value===null?'&sn=1':'&sn='+encodeURIComponent(document.getElementById('sortNumber').value);
                
            // Return what we can build up
            return '\?' + showWhatFinishedState + tasksPerPage + companySelected + statusSelected + searchPhrase + typeSelected + sortNumber;
        }
        
        function CreateAndGotoSearchOptions() {
            // Get the base location
            var goToLocation = window.location.href.split('?')[0];

            // Build the location to go to with get variables
            goToLocation = goToLocation + CreateURLSearchVariables();
            
            // Go to the location built
            window.location=goToLocation;
        }
        
        function DeleteTaskAndReturn(taskID) {
            // Build the location and go to it
            window.location='redirectors/delete_task.php' +  CreateURLSearchVariables() + 
                            '&deleteTaskID=' + taskID ;
        }
        
        function HideAllChildren() {
            // Look for all elements of this checkbox class
            const childrenCheckBoxes = document.querySelectorAll(".hideChildren");
            
            // Loop through them to uncheck them
            for (var i = 0, checkBox; checkBox = childrenCheckBoxes[i]; i++) {
                //  Uncheck this one
                checkBox.checked=false;
            }

            // Look for all elements that are of the childrenDiv class
            const childrenDivs = document.querySelectorAll(".childrenDiv");
            
            // Loop through them to hide them
            for (var i = 0, childrenDiv; childrenDiv = childrenDivs[i]; i++) {
                // Hide this one
                childrenDiv.style.display = "none";
            }
        }
        
        function GetChildNumber(s1, s2) {
            // Determine if s1 is not null and is the child number
            if (s1 !== null && s1.toString().includes("children")){
                // Get and send back the return number
                return (s1.split("_"))[s1.split("_").length-1]
            }
            
            // Determine if s2 is not null and is the child number
            if (s2 !== null && s2.toString().includes("children")){
                // Get and send back the return number
                return (s2.split("_"))[s2.split("_").length-1]
            }
            
            // If neither case is true, then return a negative number
            return -1;
        }        
        
        var indexBefore=-1;
        var dragPosition=0;
        $(function() {
            $( "#tasks_sortable" ).sortable({
                update: function (event, ui) {
                $( "#tasks_sortable" ).sortable("refreshPositions");

                var prevElement = ui.item.prev();
                var nextElement = ui.item.next();
                $('span#prev').html(prevElement.html());
                $('span#next').html(nextElement.html());


                    // Set the priority to the first one in case ther is no previous sibling
                    var newPriority = 0;

                    // Attempt to get the previous sibling
                    var target = ui.item.prev();
                    
                    // Determine if there was a previous sibling
                    if (target !== null && target[0].id !== ""){
                        dragPosition = GetChildNumber(prevElement[0].id, nextElement[0].id);
                        
                        // Parse out the priority
                        var arrayForPriority = target[0].id.split('_');

                        // The last one should be the priority
                        newPriority = arrayForPriority[arrayForPriority.length-1];
                    }
                    
                    //alert("Start Position: " + ui.item.startPos);
                    //alert("Finish Position: " + newPriority);
                    
                    $.post("redirectors/reorder_tasks.php", 
                            {
//                                newPosition: newPriority,
                                newPosition: ui.item.index(),
                                lastPosition: ui.item.startPos, 
                                type: document.getElementById('typeSelected').value,
                                lastOneUpdated: document.getElementById('LastOneUpdated').value,
                                companySelected: document.getElementById('companySelected').value
                            }, 
                            function(o){
                                indexBefore = ui.item.index();
                                
                                // Redirect back to a (hopefully) new tasks page
                                CreateAndGotoSearchOptions();
                                
                                //alert("Start Position: " + ui.item.startPos);
                                //alert("Finish Position: " + ui.item.index());
                            }
                          );
                },
                start: function(event, ui) {
                    ui.item.startPos = ui.item.index();

                    // If there are any children nodes open, changed them to hidden
                    HideAllChildren();
                },
                items: "li:not(.ui-state-disabled)"
            });
        });
        
        function addStickyNoteDialog(taskID){
            // Set the global variable to this task ID passed in
            taskIDStickyNote=taskID;
            
            // Open the appropriate dialog
            $( "#addStickyNote" ).dialog( "open" );
        }
        
        $( function() {
            $( "#addStickyNote" ).dialog({
                autoOpen: false,
                show: {
                  effect: "pop",
                  duration: 1000
                },
                hide: {
                  effect: "explode",
                  duration: 1000
                },
                width: 'auto',
                modal: true,
                buttons: {
                  "Save": function() {
                        // Attempt to move it to the queue
                        if (addStickyNote(sessionID, taskIDStickyNote, "TASK", getMultipleSelectCSV(document.getElementById("stickyNoteTo")), document.getElementById("stickyNoteTitle").value, document.getElementById("stickyNoteContent").value)){
                            // Close this dialog
                            $( this ).dialog( "close" );
                        
                            // Reset the user it is going to to be everyone
                            $( "#stickyNoteTo" ).val(-1).change();

                            // Clear the sticky note title box
                            $( "#stickyNoteTitle" ).val("");

                            // Clear the sticky note text box
                            $( "#stickyNoteContent" ).val("");
                            
                            // Reload the window 
                            location.reload()();
                        };
                  },
                  Cancel: function() {
                       // Close this dialog
                       $( this ).dialog( "close" );
                       
                       // Reset the user it is going to to be everyone
                       $( "#stickyNoteTo" ).val(-1).change();
                    
                       // Clear the sticky note title box
                       $( "#stickyNoteTitle" ).val("");
                       
                       // Clear the sticky note text box
                       $( "#stickyNoteContent" ).val("");

                        // Reset the image element
                        $( "#stickyNoteImage" ).val("");
                  }
                }
            });
        });    
    </script>
</head>

<body class="thrColElsHdr">

<div id="container">
  
<!-- start of banner wrap --->

<div id="topContent">
  
<div>
  </div>
</div>
<!-- end of banner wrap --->

  <!-- end #header -->
  <br class="clearfloat" />
  <div id="sidebar1">
      <?php 
        // Determine if we are GTG
        if ($gtg){
            // Render the appropriate presentation for the tasks sidebar
            getSidebar($userRow, 'tasks');
        }
      ?>       
      <br class="clearfloat" />
  <!-- end #sidebar1 -->
  </div>
  
  <!-- start #mainContent -->
  <div id="mainContent">
    <div class="maintitle">Task Management System - Tasks</div>
    <div class="breadcrumb"> <a href="./index.php"> Home </a> > <a href="tasks.php"> Task Management System </a> > <a href="tasks.php"> Tasks </a></div>

    <br>
        
    <?php
        // Add a session variable that is this page URL
        $_SESSION['pageToGoTo']=$_SERVER['REQUEST_URI'];

        // Determine if they are GTG
        if ($gtg){
    ?>
            
        <div id="searchOptions" style='background-color: lightgrey; border-radius: 20px; border-color: darkgray;'>
            <?php
                // Get all of the search abilities
                echo(getDelineations($db, $userRow, $showWhatFinishedState, $tasksPerPage, $typeTab, $selectedCompany, $taskSearchPhrase, $selectedStatus));
            ?>
            <br>
        </div>
            <?php
                // In order to determine the level of this person's account, I need to know their type
                switch ($userRow["UserLevel"]){
                    case 'MID-MANAGEMENT':
                    case 'MANAGEMENT':
                    case 'EXECUTIVE':
                    case 'SU':
                        ?>
                            <ul id="tasks_sortable">
                        <?php

                        // Break out of this case statement
                        break;
                    default: 
                        ?>
                            <ul>
                        <?php
                }

                // get the tasks for the machining list
                echo retrieveParentTasksAsList($db, $userRow, $typeTab, $showWhatFinishedState, $tasksPerPage, $currentPage, $selectedCompany, $taskSearchPhrase, $sortNumber, $selectedStatus);
            ?>
        </ul>
        <script>
            var button = document.getElementById("submitButton"); 
            var textBox = document.getElementById("searchPhrase"); 

            textBox.addEventListener("keyup", function (event) { 
                // Checking if key pressed is ENTER or not 
                // if the key pressed is ENTER 
                // click listener on button is called 
                if (event.keyCode == 13) { 
                    button.click(); 
                } 
            });         
        </script>
    <?php
        }
        else {
            // Set the login failed to true
            $_SESSION['failedLogin']='TRUE';
            
            // redirect to the login page
            echo ('<script>window.location = ".";</script>');
        }
    ?>       
    
    <div id="addStickyNote" title="Create Sticky Note">
        <p style="text-align:center;">
            Add a sticky note for this task.
            <br><br>
                    
            <?php
                // Get a hidden div containing the assign to users
                echo createStickyNoteContent($db, $userRow);
            ?>
        </p>
    </div>            
  <!-- end #mainContent -->
  
  <!-- This clearing element should immediately follow the #mainContent div in order to force the #container div to contain all child floats -->
  <br class="clearfloat" />
  
  <!-- start #footer --></div>
   <div id="footer">
    <p>© 2018 Evolve Engineering and Software. EES, Evolve Engineering and Software, EES Logo are registered marks of Evolve Engineering and Software.</p>
  <!-- end #footer -->
   </div>
<!-- end #container -->
</div>

</body>

</html>