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

    // Add includes to PHP files that I will need to access
    include 'php_only_scripts/database.php';
    include 'php_only_scripts/presentation.php';
    include 'php_only_scripts/note_presentation.php';
    include 'php_only_scripts/tasks_presentation.php';
    include 'php_only_scripts/routing_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());
    
    // 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["SUEmployee"]!=1 ||
            $userRow["AccountStatus"]!='ACTIVE'){
            // redirect to the invalid access page
            echo ('<script>window.location = "invalid_access.php";</script>');

            exit;
        }
        else {
            // Set the good to go until they log out
            $gtg = true;
        }
    }
?>
        
﻿<!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 - Machining Tasks</title>

    <meta name="keywords" content="GIS,data,testing,IT" />
    <meta name="description" content="EES Divisions." />
    <?php
        // Determine if they are gtg
        if ($gtg){
            // determine if the refresh rate is a positive number
            if ($userRow["RefreshRate"]>0){
                // Get refresh rate as a variable and multiplied, since we need to make it milli seconds
                $refreshRateInMillis = $userRow["RefreshRate"]*1000;
                
                // Add the refresh rate amount
                echo('<script>var refreshRate=' . $refreshRateInMillis . ';</script>');
            }
            else{
                // Add the refresh rate as none. -1 is nothing.
                echo('<script>var refreshRate=-1;</script>');
            }
        }
    ?>

    <script src="./SpryAssets/SpryMenuBar.js" type="text/javascript"></script>

    <script src="javascript/general.js" type="text/javascript"></script>
    <script src="javascript/notes.js" type="text/javascript"></script>
    <script src="javascript/routing.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 href="scripts/jquery-ui-1.10.4.custom/development-bundle/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css"/>
    
    <link rel="icon" href="images/ees_ico.ico"/> 
    
    <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">
        .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%;
            background-color: darkgray;
        }
        .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;
        }
        .expediteCell
        {
            width: 60px;
            text-align: center;
        }
        .taskIDCell
        {
            width: 75px;
            text-align: center;
        }
        .updateCell
        {
            width: 105px;
            text-align: center;
        }
        .fixtureCell
        {
            width: 13%;
            text-align: center;
        }
        
        .statusCell
        {
            width: 11%;
        }
        .companyCell
        {
            width: 15%;
        }
        .dueDateCell
        {
            width: 80px;
        }
        .assignedToCell
        {
            width: 11%;
            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%;
        }
        
        #Machine_Jobs_Container {width: 100%; height: 100%;}
        #Machine_Jobs_Container h3 { text-align: center; margin: 0; margin-bottom: 2px;}
        #Machine_Jobs_Sort { list-style-type: none; margin: 0; padding: 0; width: 60%; }
        #Machine_Jobs_Sort li { margin: 0px 3px 3px 3px; padding: 3px; font-size: 1.2em; height: 1.5em; }
        html>body #Machine_Jobs_Sort li { height: 1.5em; line-height: 1.2em; }
        .ui-state-highlight {height: 1.5em; line-height: 1.2em; }
  
        .portlet {
          margin: 0 1em 1em 0;
          padding: 0.3em;
          overflow: auto;
          float: left;
          position: fixed; 
        }
        .portlet-header {
          padding: 0.2em 0.3em;
          margin-bottom: 0.5em;
          position: relative;
        }
        .portlet-toggle {
          position: absolute;
          top: 50%;
          right: 0;
          margin-top: -8px;
        }
        .portlet-content {
          padding: 0.4em;
        }
        .portlet-placeholder {
          border: 1px dotted black;
          margin: 0 1em 1em 0;
          height: 50px;
        }
        
        /*----------------------------------------------
        CSS settings for the close button
        ------------------------------------------------*/
        #refreshMachineTasksBtn:hover {
            display:inline-block;
            padding:2px 5px;
            background-color: rgba(60, 108, 155, 1);
        }    
        
        #refreshTasksOnMachineDiv {
            position: fixed;
            left: 80%;
            top: 24%;
            float:right;
            display:inline-block;
            padding:2px 5px;
            background-color: rgba(49, 49, 49, 0);
            z-index: 999999;            
        }  
        
        /*----------------------------------------------
        CSS settings for the users dialog
        ------------------------------------------------*/
        #usersDialog, #machiningUsersDialog, #2QUsersDialog, #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 {
            z-index: -1;
            background:repeating-linear-gradient(
                90deg,
                rgba(255, 0, 127, 1),
                rgba(255, 0, 127, 1) 10px,
                rgba(0, 0, 0, 0) 10px,
                rgba(0, 0, 0, 0) 20px
            );
            background-color:rgba(255,255,255,0.5);
        }
    </style>
    <script>
        var popUp = null;
        var pollTimer = null;

        $(document).ready(function() {
            var indexBefore=-1;
            var machineBefore=-1;
            var indexAfter=-1;
            var machineAfter=-1;
            $(function() {
                // Setup the sortable for tasks
                $( ".tasksSortable" ).sortable({
                    items: "li:not(.ui-state-disabled)",
                    placeholder: "ui-state-highlight",
                    connectWith: ".connectedSortable",
                    stop: function (event, ui) {
                        // Refresh the positions
                        $( ".tasksSortable" ).sortable("refreshPositions");

                        // Get the final resting place
                        indexAfter = ui.item.index();
                        machineAfter = ui.item.parent().attr('id').replace('portletTasks','');

                        // Determine if it has REALLY changed positions
                        if (indexBefore===indexAfter && 
                            machineBefore===machineAfter){
                            // Leave this function, since nothing has really changed
                            return;
                        }
                        else {
                            // Setup the parameters to pass to PHP
                            var params = {
                                "indexBefore" : indexBefore,
                                "machineBefore" : machineBefore, 
                                "indexAfter" : indexAfter,
                                "machineAfter" : machineAfter,
                                "sessionID" : sessionID
                            };

//                            alert ("indexBefore" + indexBefore + " " +
//                                   "machineBefore" + machineBefore + " " +
//                                   "indexAfter" + indexAfter + " " +
//                                   "machineAfter" + machineAfter);

                            // Determine if they are hopping machines
                            var test=false;
                            if (machineBefore!=machineAfter && 
                                confirm ("Are you sure you wish to move this task from one machine to another?")==false){
                                // Refresh the tasks
                                refreshMachineTasks();

                                // Leave this function, since they do not want to move
                                return;
                            }
                            else {
                                // Create the string containing the PHP file to use
                                var url = "php_only_scripts/jquery_only/reorder_tasks_on_machines.php";

                                // Setup AJAX for communication
                                $.ajax({
                                    context : this,
                                    type    : "GET", 
                                    url     : url, 
                                    data    : params, 
                                    dataType: "text", 
                                    encode  : true,
                                    async   : false, 
                                    cache   : false
                                })
                                .done(function(data){
                                    // Determine if it was NOT success
                                    if (data.trim() != ""){
                                        // Check to see if there is a reason NOT to allow the move
                                        if (data.includes("ABORT MOVE")){
                                            // Cancel the move
                                            $(this).sortable("cancel");

                                            // Split the string on the double colon
                                            var errorStrings=data.trim().split("::");

                                            // Give an alert popup of the problem
                                            alert(errorStrings[1]);
                                        }

                                        // Log any errors to the console
                                        console.log(data.trim());
                                    }

                                    // Refresh the machines with the real data
                                    refreshMachineTasks();
                                })
                                .fail(function(data){   
                                    // Cancel the move
                                    $(this).sortable("cancel");

                                    // Log any errors to the console
                                    console.log(data);
                                }); 
                            }
                        }
                    },
                    start: function(event, ui) {
                        // Get the start position and machine that it is on
                        indexBefore = ui.item.index();
                        machineBefore = ui.item.parent().attr('id').replace("portletTasks","");
                    }
                }).disableSelection();
            });

            // Get the tasks initially
            refreshMachineTasks();

            // Now setup the refresh function call the same function
            setupTaskRefresh();

            // Get all of the portlets
            var portlets = document.getElementsByClassName("portlet");
            
            // Position all of the portlets
            positionPortlets(portlets);

            // do some binding
            bind_sortable();
            bind_draggble();

            // Setup the dropable conditions of the portlet
            $(".portlet").droppable({
                accept: '#Machine_Jobs_Sort',
                drop: function(ev, ui) {
                    $(ui.draggable).clone(true).remove().appendTo(this);
                    $(ui.draggable).remove();
                    bind_draggble();
                    bind_sortable();
                }
            });

            // setup functions and variables for the portlet
            $( ".portlet" )
//            .resizable({stack: ".portlet", containment: "#Machine_Jobs_Container"})
//            .draggable({stack: ".portlet", containment: "#Machine_Jobs_Container" })
                .resizable({stack: ".portlet"})
                .draggable({stack: ".portlet"})
                .addClass( "ui-widget ui-widget-content ui-helper-clearfix ui-corner-all" )
                .find( ".portlet-header" )
                .addClass( "ui-widget-header ui-corner-all" )
                .prepend( "<span class='ui-icon ui-icon-minusthick portlet-toggle'></span>");

            $( ".portlet" ).on( "resize", function() {
                this.style.zIndex = "500";
            });
            $( ".portlet" ).on( "scroll", function() {
                this.style.zIndex = "500";
            });
            $( ".portlet" ).on( "click", function() {
                this.style.zIndex = "500";
            });

            // setup functions and variables for portlet toggling
            $( ".portlet-toggle" ).on( "click", function() {
                var icon = $( this );
                icon.toggleClass( "ui-icon-minusthick ui-icon-plusthick" );
                icon.closest( ".portlet" ).find( ".portlet-content" ).toggle();

                // Determine if the content is visible right now
                if (icon.hasClass("ui-icon-plusthick")){
                    // remove the resizeable functionality
                    icon.closest(".portlet").resizable('destroy');

                    // Change the portlet height to be the height of the header plus a little
                    icon.closest(".portlet").height(icon.closest( ".portlet" ).find( ".portlet-header").height() + 10);
                }
                else {
                    // Add back the resizable functionality
//                icon.closest(".portlet").resizable({stack: ".portlet", containment: "#Machine_Jobs_Container"});
                    icon.closest(".portlet").resizable({stack: ".portlet"});

                    // Increase the size of the portlet to be at least close to the height of the container withing to include the header
                    icon.closest(".portlet").height(icon.closest( ".portlet" ).find( ".portlet-content").height()) + icon.closest( ".portlet" ).find( ".portlet-header").height() + 10;
                }
            });
        });
        
        function bind_draggble() {
            $(".portlet").draggable({
//            containment: '#Machine_Jobs_Container',
                connectToSortable: '#Machine_Jobs_Sort'
            });
        }

        function bind_sortable() {
            $("#Machine_Jobs_Sort").sortable({
                receive: function(event, ui) {
                  ui.item.draggable('disable');
                }
            });
        }

        // Create a method to set the portlet start position
        function positionPortlet(thePortlet, topOffset=0, leftOffset=0){
            // Get the container positions
            var parentPositionLeft = window.pageXOffset;
            var parentPositionRight = parentPositionLeft+window.width;
            var parentPositionTop = window.pageYOffset;

            // set the portlet positions
            var portletPositionLeft = parentPositionLeft+leftOffset;
            var portletPositionTop = parentPositionTop+topOffset;
            
            // Determine if the width of the portlet will extend past the window edge
            if ((leftOffset+1000)>parentPositionRight){
                
            }

            // Set the start position of the portlet
            thePortlet.style.left = portletPositionLeft+'px';
            thePortlet.style.top = portletPositionTop+'px';
            
            // Set to a standard width
            thePortlet.style.width = '1000px';
        }
        
        // Create a method to set the portlet start position
        function positionPortlets(portlets){
            // Get the container positions
            var parentPositionLeft = window.pageXOffset;
            var parentPositionRight = parentPositionLeft+window.innerWidth;
            var parentPositionTop = window.pageYOffset;

            // Ensure the portlets are staggered to begin with
            var currentLeft=0;
            var currentTop=40;

            // Loop through them
            for (var i = 0; i < portlets.length; i++) {
                // Determine if the left side plus some for the title will extend past the window right edge
                if ((currentLeft+100)>parentPositionRight){
                    // Reset the current left
                    currentLeft=0;
                }
                
                // set the portlet positions
                var portletPositionLeft = parentPositionLeft+currentLeft;
                var portletPositionTop = parentPositionTop+currentTop;

                // Set the start position of the portlet
                portlets.item(i).style.left = portletPositionLeft+'px';
                portlets.item(i).style.top = portletPositionTop+'px';

                // Set to a standard width
                portlets.item(i).style.width = '1000px';
                
                // Increase the distances for top and left
                currentTop+=40;
                currentLeft+=160;
            }  
        }
        
        function setupTaskRefresh() {
            // Determine if they have a refresh set
            if (refreshRate>0){
                // Set a function to be called on the refresh amount in milliseconds
                setInterval(() => refreshMachineTasks(), refreshRate);
            }
        }

        function refreshMachineTasks() {
            // Setup the parameters to pass to PHP
            var params = {
                "sessionID" : sessionID
            };

            // Create the string containing the PHP file to use
            var url = "php_only_scripts/jquery_only/individual_machine_tasks.php";

            // Setup AJAX for communication
            $.ajax({
                context : this,
                type    : "GET", 
                url     : url, 
                data    : params, 
                dataType: "html", 
                encode  : true,
                async   : false, 
                cache   : false
            })
            .done(function(data){
                // Check to see if there is a reason NOT to allow the move
                if (data.includes("ABORT WHITEBOARD POPULATE")){
                    // Split the string on the double colon
                    var errorStrings=data.trim().split("::");

                    // Give an alert popup of the problem
                    alert(errorStrings[1]);
                }
                else {
                    // Split the return on three pipes
                    var dataToUse=data.trim();
                    var returnValues = dataToUse.split("||||");

                    // Loop through the elements returned
                    for (i = 0; i < returnValues.length; i++) {
                        // Init variables
                        var returnedMachineID = -1;

                        // Split the string again and remove the first in order to get the number
                        var machineAndTask = returnValues[i].split("*|*|*/");

                        // Determine if we have two
                        if (machineAndTask.length===2){
                            // Remove the beginning characters
                            returnedMachineID = machineAndTask[0].replace('/*|*|*','');

                            // attempt to get the portlet
                            var currentPortlet = document.getElementById("portletTasks" + returnedMachineID);

                            // Determine if the portlet exists
                            if (currentPortlet===null){
                                // Alert the user there is a new machine and that we are refreshing the whole browser
                                alert("There has been a new machine added since last you fully refreshed browser.\n\nFully refreshing the browser now.");

                                // Refresh the browser
                                location.reload();
                            }

                            // Replace the list
                            currentPortlet.innerHTML = machineAndTask[1];
                        }
                    }
                }
            })
            .fail(function(data){   
                // Log any errors to the console
                console.log(data);
            }); 
        }
        
        function MoveTaskToQueue(){
            // Setup the parameters to pass to PHP
            var params = {
                "taskID" : taskIDToMove,
                "assignToUserID" : document.getElementById("userIDForMachiningQueue").value,
                "sessionID" : sessionID
            };

            // Create the string containing the PHP file to use
            var url = "php_only_scripts/jquery_only/move_task_to_queue.php";

            // Setup AJAX for communication
            $.ajax({
                context : this,
                type    : "GET", 
                url     : url, 
                data    : params, 
                dataType: "text", 
                encode  : true,
                async   : false, 
                cache   : false
            })
            .done(function(data){
                // Determine if it was NOT success
                if (data.trim() !== ""){
                    // Check to see if there is a reason NOT to allow the move
                    if (data.includes("ABORT MOVE")){
                        // Split the string on the double colon
                        var errorStrings=data.trim().split("::");

                        // Give an alert popup of the problem
                        alert(errorStrings[1]);
                    }

                    // Log any errors to the console
                    console.log(data.trim());
                }
                
                // Refresh the tasks now to show current data
                refreshMachineTasks();
            })
            .fail(function(data){   
                // Log any errors to the console
                console.log(data);
            }); 
        }
        
        function finishMachiningTask(){
            var result="";
            
            // Setup the parameters to pass to PHP
            var params = {
                "taskID" : taskIDToComplete,
                "assignToUserID" : document.getElementById("userIDForNextPhase").value,
                "sessionID" : sessionID
            };

            // Create the string containing the PHP file to use
            var url = "php_only_scripts/jquery_only/finish_machining_task.php";

            // Setup AJAX for communication
            $.ajax({
                context : this,
                type    : "GET", 
                url     : url, 
                data    : params, 
                dataType: "text", 
                encode  : true,
                async   : false, 
                cache   : false
            })
            .done(function(data){
                // Determine if it was NOT success
                if (data.trim() !== ""){
                    // Save the return as the result
                    result=data.trim();
                    
                    // Check to see if there is a reason NOT to allow the move
                    if (data.includes("ABORT MOVE")){
                        // Split the string on the double colon
                        var errorStrings=data.trim().split("::");

                        // Give an alert popup of the problem
                        alert(errorStrings[1]);
                    }
                    else if (data.includes("INFO MESSAGE")){
                        // Split the string on the double colon
                        var infoStrings=data.trim().split("::");

                        // Give an alert popup of the problem
                        alert(infoStrings[1]);
                    }

                    // Refresh the tasks now to show current data
                    refreshMachineTasks();
                    
                    // Log anything to the console
                    console.log(data.trim());
                }
                else {
                    // Refresh the tasks now to show current data
                    refreshMachineTasks();
                }
            })
            .fail(function(data){   
                // Save the return as the result
                result=data.trim();
                
                // Log any errors to the console
                console.log(data);
            }); 
            
            return result;
        }
        
        function checkForMachiningTasks(){
            var returnVal = -1;
            
            // Setup the parameters to pass to PHP
            var params = {
                "machineID" : machineIDForNewMachining
            };
            
            // Create the string containing the PHP file to use
            var url = "php_only_scripts/jquery_only/check_to_see_if_has_machining_task.php";

            // Setup AJAX for communication
            $.ajax({
                context : this,
                type    : "GET", 
                url     : url, 
                data    : params, 
                dataType: "html", 
                encode  : true,
                async   : false, 
                cache   : false
            })
            .done(function(data){
                // Set the result
                returnVal = data.trim();
            })
            .fail(function(data){   
                // Return nothing
                returnVal = data.trim();
            }); 
            
            return returnVal;
        }
        
        function moveTaskToMachining(){
            var successful=true;
            
            // Setup the parameters to pass to PHP
            var params = {
                "taskID" : taskIDToMove,
                "assignToUserID" : document.getElementById("userIDForNextMachining").value,
                "machineID" : machineIDForNewMachining,
                "sessionID" : sessionID
            };

            // Create the string containing the PHP file to use
            var url = "php_only_scripts/jquery_only/move_task_into_machining.php";

            // Setup AJAX for communication
            $.ajax({
                context : this,
                type    : "GET", 
                url     : url, 
                data    : params, 
                dataType: "text", 
                encode  : true,
                async   : false, 
                cache   : false
            })
            .done(function(data){
                // Determine if it was NOT success
                 if (data.trim() !== ""){
                    // Check to see if there is a reason NOT to allow the move
                    if (data.includes("ABORT MOVE")){
                        // Split the string on the double colon
                       var errorStrings=data.trim().split("::");

                        // Give an alert popup of the problem
                        alert(errorStrings[1]);
                        
                        // Set a failed result
                        successful=false
                    }
                    else if (data.includes("INFO MESSAGE")){
                        // Split the string on the double colon
                       var errorStrings=data.trim().split("::");

                        // Give an alert popup of the information
                        alert(errorStrings[1]);
                        
                        // Set a failed result
                        successful=false
                    }

                    // Log any errors to the console
                    console.log(data.trim());
                }
                
                // Refresh the tasks to show current data
                refreshMachineTasks();
            })
            .fail(function(data){   
                // Log any errors to the console
                console.log(data);
                        
                // Set a failed result
                successful=false
            }); 
            
            return successful;
        }
        
        function addStickyImage(fd){
            // Set the return value to success for now
            $success=true;
            
            // Create the string containing the PHP file to use
            var url = "php_only_scripts/jquery_only/add_note_image.php";

            // Setup AJAX for communication
            $.ajax({
                context     : this,
                type        : "GET", 
                url         : url, 
                data        : fd, 
                processData : false,
                contentType : false,
                async       : false 
            })
            .done(function(data){
                // Check to see if there is a reason NOT to allow the move
                if (data.includes("ABORT STICKY NOTE IMAGE")){
                    // Set the return value failed
                    $success=false;

                    // Split the string on the double colon
                    var errorStrings=data.trim().split("::");

                    // Give an alert popup of the problem
                    alert(errorStrings[1]);

                    // Log any errors to the console
                    console.log(data.trim());
                }
                else {
                    // Refresh the tasks now to show current data
                    refreshMachineTasks();
                }
            })
            .fail(function(data){   
                // Log any errors to the console
                console.log(data);
                
                // Set the return value failed
                $success=false;
            }); 
            
            // Return the success value
            return $success;
        }

        var taskIDToComplete=-1;
        var taskIDToMove=-1;
        var taskIDStickyNote=-1;
        var machineIDForNewMachining=-1;
        
        function getUserToAssignNextPhase(){
            // Open the appropriate dialog
            $( "#usersDialog" ).dialog( "open" );
        }
        
        function getUserToMachiningTask(openDialog=true){
            // Determine if they really want to open the dialog at this point or wait
            if (openDialog){
                // Open the appropriate dialog
                $( "#machiningUsersDialog" ).dialog( "open" );
            }
        }
        
        function getUserToMachiningQueueTask(){
            // Open the appropriate dialog
            $( "#2QUsersDialog" ).dialog( "open" );
        }
        
        function addStickyNoteDialog(taskID){
            // Set the global variable to this task ID passed in
            taskIDStickyNote=taskID;
            
            // Open the appropriate dialog
            $( "#addStickyNote" ).dialog( "open" );
        }
        
        var finishMachiningTaskResult = "";
        $( function() {
            // Dialog to put a task into machining. This is the up triangle button (▲).
            $( "#machiningUsersDialog" ).dialog({
                autoOpen: false,
                show: {
                  effect: "pop",
                  duration: 1000
                },
                hide: {
                  effect: "explode",
                  duration: 1000
                },
                width: 'auto',
                modal: true,
                close: function() {
                    // Hide the routing div
                    $('#MU_RouteParamsDiv').hide();
                    
                    // Reset the ID used
                    taskIDToMove=-1;
                },
                buttons: {
                  "Move": function() {
                        // Reset the variable back to it's non-error state
                        finishMachiningTaskResult="";

                        // Attempt to match task tools to the machine tools
                        if (modifyTaskForThePresent(taskIDToMove, machineIDForNewMachining, 0, sessionID)){
                            // Determine if the div element is visible.  Should mean we have routing to deal with.
                            if ($('#MU_RouteParamsDiv').is(":visible")){
                                // Get any notes that they want to say about the current state
                                var completionFeedbackNotesElement = $( "#MU_completionFeedbackNotes" );

                                // Determine if we have that element
                                var completionFeedbackNotes="";
                                if (completionFeedbackNotesElement!=null && completionFeedbackNotesElement!=undefined){
                                    // Get the value in the element
                                    completionFeedbackNotes=completionFeedbackNotesElement.val();
                                }

                                // Lets Move it
                                moveRouteAsNecessary($( "#MU_routeTID" ).val(), $( "#MU_routeCurrentTaskStatusRoutingNodeID" ).val(), completionFeedbackNotes, shallowCopyRouteGoToInfoStrings);

                                // Clear the values used
                                $( "#MU_routeStatusID" ).val(0);
                                $( "#MachiningMoveRoutingHeader" ).val("");
                                $( "#MU_routeNodeEstimatedTime" ).val("");
                                $( "#MU_routeNodeActualTime" ).val("");
                                $( "#MU_completionFeedbackNotes" ).val("");
                                $( "#MU_nextStatusNotes" ).val("");
                                shallowCopyRouteGoToInfoStrings=null;
                            }

                            // we are ready to move the task into machining phase
                            if (moveTaskToMachining()){
                                // Make the packet they need to use for machining
                                window.open('pdf_templates/setup_sheet_with_downloads.php?tid=' + taskIDToMove, '_blank');
                            }
                        }
                        
                        // Close this dialog
                        $( this ).dialog( "close" );
                  },
                  Cancel: function() {
                    // Clear the values used
                    $( "#MU_routeStatusID" ).val(0);
                    $( "#MachiningMoveRoutingHeader" ).val("");
                    $( "#MU_routeNodeEstimatedTime" ).val("");
                    $( "#MU_routeNodeActualTime" ).val("");
                    $( "#MU_completionFeedbackNotes" ).val("");
                    $( "#MU_nextStatusNotes" ).val("");
                    
                    // Close this dialog
                    $( this ).dialog( "close" );
                  }
                }
            });
        } );  
        var shallowCopyRouteGoToInfoStrings=null;
        $( function() {
            // Dialog to end a machining task. This is the checkmark button (✔).
            $( "#usersDialog" ).dialog({
                autoOpen: false,
                show: {
                  effect: "pop",
                  duration: 1000
                },
                hide: {
                  effect: "explode",
                  duration: 1000
                },
                width: 'auto',
                modal: true,
                close: function() {
                    // Hide the routing div
                    $('#U_RouteParamsDiv').hide();
                    
                    // Reset the ID used
                    taskIDToComplete=-1;
                },
                buttons: {
                  "Move": function(event) {
                        // Determine if the div element is visible.  Should mean we have routing to deal with.
                        if ($('#U_RouteParamsDiv').is(":visible")){
                            // Get any notes that they want to say about the current state
                            var completionFeedbackNotesElement = $( "#U_completionFeedbackNotes" );

                            // Determine if we have that element
                            var completionFeedbackNotes="";
                            if (completionFeedbackNotesElement!=null && completionFeedbackNotesElement!=undefined){
                                // Get the value in the element
                                completionFeedbackNotes=completionFeedbackNotesElement.val();
                            }

                            // Lets Move it
                            moveRouteAsNecessary($( "#U_routeTID" ).val(), $( "#U_routeCurrentTaskStatusRoutingNodeID" ).val(), completionFeedbackNotes, routeGoToInfoStrings);

                            // Clear the values used
                            $( "#U_routeStatusID" ).val(0);
                            $( "#UsersMoveRoutingHeader" ).val("");
                            $( "#U_routeNodeEstimatedTime" ).val("");
                            $( "#U_routeNodeActualTime" ).val("");
                            $( "#U_completionFeedbackNotes" ).val("");
                            $( "#U_nextStatusNotes" ).val("");
                        }
                            
                        // Finish the machining task
                        finishMachiningTaskResult=finishMachiningTask();
                        
                        // close this dialog
                        $( this ).dialog( "close" );
                        
                        // Determine if they are wanting to move something into machining
                        if (taskIDToMove>-1){
                            // Open the dialog to actually move the initial task asked for into machining
                            getUserToMachiningTask();
                        }
                  },
                  Cancel: function() {
                    // Clear the values used
                    $( "#U_routeStatusID" ).val(0);
                    $( "#UsersMoveRoutingHeader" ).val("");
                    $( "#U_routeNodeEstimatedTime" ).val("");
                    $( "#U_routeNodeActualTime" ).val("");
                    $( "#U_completionFeedbackNotes" ).val("");
                    $( "#U_nextStatusNotes" ).val("");
                            
                    // close this dialog
                    $( this ).dialog( "close" );
                  }
                }
            });
        } );    
        $( function() {
            // Dialog to put a task into machining. This is the up triangle button (2Q).
            $( "#2QUsersDialog" ).dialog({
                autoOpen: false,
                show: {
                  effect: "pop",
                  duration: 1000
                },
                hide: {
                  effect: "explode",
                  duration: 1000
                },
                width: 'auto',
                modal: true,
                close: function() {
                    // Hide the routing div
                    $('#2Q_RouteParamsDiv').hide();
                    
                    // Reset the ID used
                    taskIDToMove=-1;
                },
                buttons: {
                  "Move": function() {
                      // Determine if the div element is visible.  Should mean we have routing to deal with.
                      if ($('#2Q_RouteParamsDiv').is(":visible")){
                          // Get any notes that they want to say about the current state
                          var completionFeedbackNotesElement = $( "#2Q_completionFeedbackNotes" );

                          // Determine if we have that element
                          var completionFeedbackNotes="";
                          if (completionFeedbackNotesElement!=null && completionFeedbackNotesElement!=undefined){
                              // Get the value in the element
                              completionFeedbackNotes=completionFeedbackNotesElement.val();
                          }

                          // Lets Move it
                          moveRouteAsNecessary($( "#2Q_routeTID" ).val(), $( "#2Q_routeCurrentTaskStatusRoutingNodeID" ).val(), completionFeedbackNotes, routeGoToInfoStrings);

                          // Clear the values used
                          $( "#2Q_routeStatusID" ).val(0);
                          $( "#2QMoveRoutingHeader" ).val("");
                          $( "#2Q_routeNodeEstimatedTime" ).val("");
                          $( "#2Q_routeNodeActualTime" ).val("");
                          $( "#2Q_completionFeedbackNotes" ).val("");
                          $( "#2Q_nextStatusNotes" ).val("");
                      }
                      
                      // Attempt to move it to the queue
                      MoveTaskToQueue();

                      // Close this dialog
                      $( this ).dialog( "close" );
                  },
                  Cancel: function() {
                      // Clear the values used
                      $( "#2Q_routeStatusID" ).val(0);
                      $( "#2QMoveRoutingHeader" ).val("");
                      $( "#2Q_routeNodeEstimatedTime" ).val("");
                      $( "#2Q_routeNodeActualTime" ).val("");
                      $( "#2Q_completionFeedbackNotes" ).val("");
                      $( "#2Q_nextStatusNotes" ).val("");
                          
                      // Close this dialog
                      $( this ).dialog( "close" );
                  }
                }
            });
        } );    
        $( function() {
            $( "#addStickyNote" ).dialog({
                autoOpen: false,
                show: {
                  effect: "pop",
                  duration: 1000
                },
                hide: {
                  effect: "explode",
                  duration: 1000
                },
                width: 'auto',
                modal: true,
                close: function() {
                    // 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("");
                },
                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" );
                        
                            // Refresh the tasks now to show current data
                            refreshMachineTasks();
                        };
                  },
                  Cancel: function() {
                       // Close this dialog
                       $( this ).dialog( "close" );
                  }
                }
            });
        } );    
    </script>
</head>

<body class="thrColElsHdr">
    <script>var sessionID = "<?php echo session_id(); ?>";</script>
<div id="container">
  
<!-- start of banner wrap --->

<div id="topContent">
  
<div>
   <div class="MenuBarHorizontal" id="navBar">  <ul id="TopNav" class="MenuBarHorizontal">

    <script type="text/javascript">
    <!--
    var MenuBar2 = new Spry.Widget.MenuBar("TopNav", {imgDown:"./SpryAssets/SpryMenuBarDownHover.gif", imgRight:"./SpryAssets/SpryMenuBarRightHover.gif"});
    //-->
    </script>

    </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 - Machining Tasks</div>
    <div class="breadcrumb"> <a href="../index.html"> Home </a> > <a href="tasks.php"> Task Management System </a> > <a href="machiningTasks.php"> Machining Tasks </a></div>

    <br>
        
    <?php
        // Determine if they are GTG
        if ($gtg){
    ?>
        <div>
            <div id="refreshTasksOnMachineDiv">
                <button id="refreshMachineTasksBtn" onclick="javascript:window.refreshMachineTasks();">Refresh</button>
            </div>        
            <div id="Machine_Jobs_Container">
                <div id="Machine_Jobs_Sort">
                    <?php
                    // get the tasks for the machining list
                    echo retrieveMachinesToHoldTasks($db, $userRow);
                    ?>
                </div>
            </div>
         </div>              
        </ul>    
    <?php
        }
        else {
            // Set the login failed to true
            $_SESSION['failedLogin']='TRUE';
            
            // Add a session variable that is this page URL
            $_SESSION['pageToGoTo']=$_SERVER['REQUEST_URI'];

            // redirect to the login page
            echo ('<script>window.location = ".";</script>');
        }
    ?>       
    
    <div id="usersDialog" title="Choose User">
        <div id="U_TitleDiv">
            <p style="text-align:center;">
                Select user to assign the next phase of this task to or cancel to quit change.
                <br><br>
                <?php
                    // Get a hidden div containing the assign to users
                    echo createUsersToAssignContent($db, $userRow, "userIDForNextPhase", "last machining task");
                ?>
            </p>
        </div>
        <div id="U_RouteParamsDiv" style="display:none;">
            <p style="text-align:center;">
                <input type="hidden" name="U_routeTID" id="U_routeTID" value=-1/>
                <input type="hidden" name="U_routeCurrentTaskStatusRoutingNodeID" id="U_routeCurrentTaskStatusRoutingNodeID" value=-1/>
                <label name="UsersMoveRoutingHeader" id="UsersMoveRoutingHeader" style="color:green;">Move the task routing.</label>
                <br><br>
                <label name="UsersMoveRoutingHeader2" id="UsersMoveRoutingHeader2" style="color:red;">** This will NOT save the task first, so any wanted unsaved data should be saved before moving the route. **</label>
                <input type="hidden" name="U_routeTID" id="U_routeTID" value="' . $hasChildren . '"/>
                <input type="hidden" name="U_routeStatusID" id="U_routeStatusID" value="' . $hasChildren . '"/>
                <input type="hidden" name="U_routeCurrentTaskStatusRoutingNodeID" id="U_routeCurrentTaskStatusRoutingNodeID" value="' . $hasChildren . '"/>
                <table width="100%" border="0">
                    <tr>
                        <td height="39" align="left" colspan=1>
                            <strong><label for="U_routeNodeEstimatedTime">Current State Estimated Time:</label></strong>
                            <input type="text" maxlength="25" name="U_routeNodeEstimatedTime" id="U_routeNodeEstimatedTime" style="width:40%;" value="" disabled/>
                        </td>
                        <td height="39" align="left" colspan=1>
                            <strong><label for="U_routeNodeActualTime">Current Calculated Actual Time:</label></strong>
                            <input type="text" maxlength="25" name="U_routeNodeActualTime" id="U_routeNodeActualTime" style="width:40%;" value="" disabled/>
                        </td>
                    </tr>
                    <tr>
                        <td height="39" align="left" colspan=2>
                            <strong><label name="U_completionFeedbackNotesLabel" id="U_completionFeedbackNotesLabel" for="U_completionFeedbackNotes">Feedback On Current State:</label></strong><br>
                            <textarea name="U_completionFeedbackNotes" id="U_completionFeedbackNotes" maxlength="2000" style="width: 100%; height: 125px; overflow: auto; resize:none" value=""/></textarea>
                        </td>
                    </tr>
                    <tr>
                        <td height="39" align="left" colspan=2>
                            <strong><label name="U_nextStatusNotesLabel" id="U_nextStatusNotesLabel" for="U_nextStatusNotes">Notes for Next State:</label></strong><br>
                            <textarea name="U_nextStatusNotes" id="U_nextStatusNotes" maxlength="2000" style="width: 100%; height: 125px; overflow: auto; resize:none" value="" disabled/></textarea>
                        </td>
                    </tr>
                </table>
            </p>
        </div>
    </div>    
    <div id="machiningUsersDialog" title="Choose User">
        <div id="MU_TitleDiv">
            <p style="text-align:center;">
                Select user to assign machining phase of this task to or cancel to quit change.
                <br><br>
                <?php
                    // Get a hidden div containing the assign to users
                    echo createUsersToAssignContent($db, $userRow, "userIDForNextMachining", "next machining task");
                ?>
            </p>
        </div>
        <div id="MU_RouteParamsDiv" style="display:none;">
            <p style="text-align:center;">
                <input type="hidden" name="MU_routeTID" id="MU_routeTID" value=-1/>
                <input type="hidden" name="MU_routeCurrentTaskStatusRoutingNodeID" id="MU_routeCurrentTaskStatusRoutingNodeID" value=-1/>
               <label name="MachiningMoveRoutingHeader" id="MachiningMoveRoutingHeader" style="color:green;">Move the task routing.</label>
                <br><br>
                <label name="MachiningMoveRoutingHeader2" id="MachiningMoveRoutingHeader2" style="color:red;">** This will NOT save the task first, so any wanted unsaved data should be saved before moving the route. **</label>
                <input type="hidden" name="MU_routeTID" id="MU_routeTID" value="' . $hasChildren . '"/>
                <input type="hidden" name="MU_routeStatusID" id="MU_routeStatusID" value="' . $hasChildren . '"/>
                <input type="hidden" name="MU_routeCurrentTaskStatusRoutingNodeID" id="MU_routeCurrentTaskStatusRoutingNodeID" value="' . $hasChildren . '"/>
                <table width="100%" border="0">
                    <tr>
                        <td height="39" align="left" colspan=1>
                            <strong><label for="MU_routeNodeEstimatedTime">Current State Estimated Time:</label></strong>
                            <input type="text" maxlength="25" name="MU_routeNodeEstimatedTime" id="MU_routeNodeEstimatedTime" style="width:40%;" value="" disabled/>
                        </td>
                        <td height="39" align="left" colspan=1>
                            <strong><label for="MU_routeNodeActualTime">Current Calculated Actual Time:</label></strong>
                            <input type="text" maxlength="25" name="MU_routeNodeActualTime" id="MU_routeNodeActualTime" style="width:40%;" value="" disabled/>
                        </td>
                    </tr>
                    <tr>
                        <td height="39" align="left" colspan=2>
                            <strong><label name="MU_completionFeedbackNotesLabel" id="MU_completionFeedbackNotesLabel" for="MU_completionFeedbackNotes">Feedback On Current State:</label></strong><br>
                            <textarea name="MU_completionFeedbackNotes" id="MU_completionFeedbackNotes" maxlength="2000" style="width: 100%; height: 125px; overflow: auto; resize:none" value=""/></textarea>
                        </td>
                    </tr>
                    <tr>
                        <td height="39" align="left" colspan=2>
                            <strong><label name="MU_nextStatusNotesLabel" id="MU_nextStatusNotesLabel" for="MU_nextStatusNotes">Notes for Next State:</label></strong><br>
                            <textarea name="MU_nextStatusNotes" id="MU_nextStatusNotes" maxlength="2000" style="width: 100%; height: 125px; overflow: auto; resize:none" value="" disabled/></textarea>
                        </td>
                    </tr>
                </table>
            </p>
        </div>
    </div>            
    <div id="2QUsersDialog" title="Choose User">
        <div id="2Q_TitleDiv">
            <p style="text-align:center;">
                Select user to assign machining queue phase of this task to or cancel to quit change.
                <br><br>
                <?php
                    // Get a hidden div containing the assign to users
                    echo createUsersToAssignContent($db, $userRow, "userIDForMachiningQueue", "task to queue");
                ?>
            </p>
        </div>
        <div id="2Q_RouteParamsDiv" style="display:none;">
            <p style="text-align:center;">
                <input type="hidden" name="2Q_routeTID" id="2Q_routeTID" value=-1/>
                <input type="hidden" name="2Q_routeCurrentTaskStatusRoutingNodeID" id="2Q_routeCurrentTaskStatusRoutingNodeID" value=-1/>
                <label name="2QMoveRoutingHeader" id="2QMoveRoutingHeader" style="color:green;">Move the task routing.</label>
                <br><br>
                <label name="2QMoveRoutingHeader2" id="2QMoveRoutingHeader2" style="color:red;">** This will NOT save the task first, so any wanted unsaved data should be saved before moving the route. **</label>
                <input type="hidden" name="2Q_routeTID" id="2Q_routeTID" value="' . $hasChildren . '"/>
                <input type="hidden" name="2Q_routeStatusID" id="2Q_routeStatusID" value="' . $hasChildren . '"/>
                <input type="hidden" name="2Q_routeCurrentTaskStatusRoutingNodeID" id="2Q_routeCurrentTaskStatusRoutingNodeID" value="' . $hasChildren . '"/>
                <table width="100%" border="0">
                    <tr>
                        <td height="39" align="left" colspan=1>
                            <strong><label for="2Q_routeNodeEstimatedTime">Current State Estimated Time:</label></strong>
                            <input type="text" maxlength="25" name="2Q_routeNodeEstimatedTime" id="2Q_routeNodeEstimatedTime" style="width:40%;" value="" disabled/>
                        </td>
                        <td height="39" align="left" colspan=1>
                            <strong><label for="2Q_routeNodeActualTime">Current Calculated Actual Time:</label></strong>
                            <input type="text" maxlength="25" name="2Q_routeNodeActualTime" id="2Q_routeNodeActualTime" style="width:40%;" value="" disabled/>
                        </td>
                    </tr>
                    <tr>
                        <td height="39" align="left" colspan=2>
                            <strong><label name="2Q_completionFeedbackNotesLabel" id="2Q_completionFeedbackNotesLabel" for="2Q_completionFeedbackNotes">Feedback On Current State:</label></strong><br>
                            <textarea name="2Q_completionFeedbackNotes" id="2Q_completionFeedbackNotes" maxlength="2000" style="width: 100%; height: 125px; overflow: auto; resize:none" value=""/></textarea>
                        </td>
                    </tr>
                    <tr>
                        <td height="39" align="left" colspan=2>
                            <strong><label name="2Q_nextStatusNotesLabel" id="2Q_nextStatusNotesLabel" for="2Q_nextStatusNotes">Notes for Next State:</label></strong><br>
                            <textarea name="2Q_nextStatusNotes" id="2Q_nextStatusNotes" maxlength="2000" style="width: 100%; height: 125px; overflow: auto; resize:none" value="" disabled/></textarea>
                        </td>
                    </tr>
                </table>
            </p>
        </div>
    </div>            
    <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>