<?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_after_session.php';
    include_once dirname(__FILE__) . '/php_only_scripts/sortArrayProblems.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/task_presentation.php';
    include_once dirname(__FILE__) . '/php_only_scripts/note_presentation.php';
    include_once dirname(__FILE__) . '/php_only_scripts/note_inner_presentation.php';
    include_once dirname(__FILE__) . '/php_only_scripts/stocklist_presentation.php';
    include_once dirname(__FILE__) . '/php_only_scripts/tools_presentation.php';
    include_once dirname(__FILE__) . '/php_only_scripts/setup_presentation.php';
    include_once dirname(__FILE__) . '/php_only_scripts/blank_presentation.php';
    include_once dirname(__FILE__) . '/php_only_scripts/routing_presentation.php';
    include_once dirname(__FILE__) . '/php_only_scripts/global_functions.php';
    include_once dirname(__FILE__) . '/toolLists_presentation.php';

    // Init some variables
    $userRow=null;
    $fromWhatBaseURL=$_SERVER['HTTP_REFERER'];

    // 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 defaults for the passed in variables
    $fromWhatCompany=-1;
    $fromWhatType=1;

    // now determine if it was posted via get.  That will override it.
    if (isset($_GET['cs']) ){
        // Hold on to the company to return to
        $fromWhatCompany = $_GET['cs'];
    }

    // Determine if the type is passed in
    if (isset($_GET['ts'])){
        // Set the session variable type to the one passed in
        $fromWhatType = $_GET['ts'];
    }

    // Determine if we only have one one user with this session ID
    if (mysqli_num_rows($currentUser)==1){
        // Set the good to go until they log out
        $gtg = true;

        // Attempt to get the user row
        $userRow = $currentUser->fetch_assoc();
        
        // Make the default be no task ID 
        $updateTaskID=-1;
        
        // now determine if it was posted via get.  That will override it.
        if (isset($_GET['updateTaskID']) ){
            // Hold onto the Task ID in a local variable
            $updateTaskID = $_GET['updateTaskID'];
        }

        // Determine if there is anything wonky that would not allow them here
        if ($userRow["AccountStatus"]!='ACTIVE' && 
            $userRow["UserLevel"]!='SU' &&
            $userRow["UserLevel"]!='EXECUTIVE' &&
            $userRow["UserLevel"]!='MID-MANAGEMENT' &&
            $userRow["UserLevel"]!='MANAGEMENT' &&
            $updateTaskID != null && 
            $updateTaskID <= 0){
                // redirect to the invalid access page
                echo ('<script>window.location = "invalid_access.php";</script>');
                
                exit;
        }
        
        // Set the parent default to be none
        $parentTaskNumber=0;
        
        // now determine if it was posted via get.  That will override it.
        if (isset($_GET['parentTaskId']) ){
            // Hold onto the Task ID in a local variable
            $parentTaskNumber = $_GET['parentTaskId'];
        }

        // Set the fact that this task has children to no at first
        $hasChildren=false;

        // Get the current row so that I can figure out the priority situation
        $sql = 'SELECT t.HasChildren ' .
               'FROM tasks t ' .
               'WHERE TaskID=' . $updateTaskID . ';';
        $hasChildrenTaskRow = $db->queryDB($sql, $userRow, "updateTask Form occurance 1");

        // Determine if we even have a task to update
        if (mysqli_num_rows($hasChildrenTaskRow)==1){
            // Get the current task row to work with as the assoc style
            $currentAssocHasChildrenTaskRow = $hasChildrenTaskRow->fetch_assoc();

            // Set whether or not we know this task has children
            $hasChildren=($currentAssocHasChildrenTaskRow["HasChildren"]==1)?true:false;
        }

        // Determine if BOTH the user name AND password has been set
        if (isset($_POST['formSubmitted']) && 
            htmlspecialchars($_POST['formSubmitted'])=='TRUE'){
            // Determine if this user can even modify
            if (!$userRow["CanModify"]){
                // redirect to the tasks page
                echo ('<script>window.location = "' . $fromWhatBaseURL . '";</script>');
            }
            else {
                // Change the form back to NOT being submitted
                $_SESSION['formSubmitted']='FALSE';

                // Get the current row so that I can figure out the priority situation
                $sql = 'SELECT t.*, s.Name, c.CompanyName ' .
                       'FROM tasks t, status s, companies c ' .
                       'WHERE t.StatusID=s.StatusID ' .
                       'AND t.CompanyID=c.CompanyID ' . 
                       'AND TaskID=' . $updateTaskID . ';';
                $currentTaskRow = $db->queryDB($sql, $userRow, "updateTask Form occurance 2");

                // Determine if we even have a task to update
                if (mysqli_num_rows($currentTaskRow)==1){
                    // Get the current task row to work with as the assoc style
                    $currentAssocTaskRow = $currentTaskRow->fetch_assoc();

                    // Create a variable to hold onto the last update timestamp
                    $lastUpdated = $currentAssocTaskRow["LastUpdated"];
                    
                    // Setup variables to be using
                    $companyID=htmlspecialchars($_POST['company'], ENT_QUOTES, 'UTF-8');
                    $statusID=htmlspecialchars($_POST['status'], ENT_QUOTES, 'UTF-8');
                    $userID=htmlspecialchars($_POST['assignedTo']);
                    $secondaryStatusID=htmlspecialchars($_POST['secondaryStatus']);
                    $childrenAssignedToID=htmlspecialchars($_POST['childrenAssignedTo']);
                    $typeID=htmlspecialchars($_POST['taskType'], ENT_QUOTES, 'UTF-8');
                    $fixtureID=htmlspecialchars($_POST['fixture'], ENT_QUOTES, 'UTF-8');
                    $partHardware=htmlspecialchars($_POST['partHardware'], ENT_QUOTES, 'UTF-8');
                    $priority=htmlspecialchars($_POST['priority'], ENT_QUOTES, 'UTF-8');
                    $subPriority=htmlspecialchars(isset($_POST['subPriority'])?$_POST['subPriority']:$_POST['subPriorityHidden'], ENT_QUOTES, 'UTF-8');
                    $deliverableQuantity=htmlspecialchars(isset($_POST['deliverableQuantity'])?$_POST['deliverableQuantity']:$_POST['deliverableQuantityHidden'], ENT_QUOTES, 'UTF-8');
                    $totalQuantity=htmlspecialchars(isset($_POST['totalQuantity'])?$_POST['totalQuantity']:$_POST['totalQuantityHidden'], ENT_QUOTES, 'UTF-8');
                    $invoiced=(isset($_POST['hiddenInvoiced'])?$_POST['hiddenInvoiced']:(isset($_POST['invoiced'])?1:0));
                    $completed=(isset($_POST['hiddenCompleted'])?$_POST['hiddenCompleted']:(isset($_POST['completed'])?1:0));
                    $closed=(isset($_POST['hiddenClosed'])?$_POST['hiddenClosed']:(isset($_POST['closed'])?1:0));
                    $cleanUp=(isset($_POST['hiddenCleanUp'])?$_POST['hiddenCleanUp']:(isset($_POST['cleanUp'])?1:0));
                    $isWaitingToBeReviewed=htmlspecialchars(isset($_POST['isWaitingToBeReviewed'])?1:0);
                    $isPendingTools=htmlspecialchars(isset($_POST['isPendingTools'])?1:0);
                    $isPendingApproval=htmlspecialchars(isset($_POST['isPendingApproval'])?1:0);
                    $title=htmlspecialchars($_POST['title'], ENT_QUOTES, 'UTF-8');
                    $description = trim(htmlspecialchars($_POST['description'], ENT_QUOTES, 'UTF-8'));
                    $hiddenDescription = trim(htmlspecialchars($_POST['hiddenDescription'], ENT_QUOTES, 'UTF-8'));
                    $addDescription = trim(htmlspecialchars($_POST['addDescription'], ENT_QUOTES, 'UTF-8'));
                    $idealDate=htmlspecialchars($_POST['idealDate'], ENT_QUOTES, 'UTF-8');
                    $dueDate=htmlspecialchars($_POST['dueDate'], ENT_QUOTES, 'UTF-8');
                    $redirectTo=$_POST['redirectTo'];
                    $parentStatusID=$_POST['parentStatusID'];
                    $parentStatusNameBefore=$_POST['parentStatusName'];
                    $parentTitle = $_POST["parentTitle"];
                    $expedite=$_POST['expedite'];
                    $issuedToMachinesDate=null;
                
                    $allPartsSetup=htmlspecialchars(isset($_POST['allPartsSetup'])?1:0);
                    $isVacuumClean = htmlspecialchars(isset($_POST['isVacuumClean'])?1:0);
                    $isWashForAnodize = htmlspecialchars(isset($_POST['isWashForAnodize'])?1:0);
                    $hasAllowableCosmeticDamage = htmlspecialchars(isset($_POST['hasAllowableCosmeticDamage'])?0:1);
                    $isTappedPostMachining = htmlspecialchars(isset($_POST['isTappedPostMachining'])?1:0);
                    $postMachiningTappingInstructions = htmlspecialchars($_POST["postMachiningTappingInstructions"]);
                    $isSandblasted = htmlspecialchars(isset($_POST['isSandblasted'])?1:0);
                    $sandBlastingInstructions = htmlspecialchars($_POST["sandBlastingInstructions"]);
                    $postMachiningNotes = htmlspecialchars($_POST["postMachiningNotes"]);
                    $postMachiningFeedback = htmlspecialchars($_POST["postMachiningFeedback"]);
                    $programmerID = htmlspecialchars(trim($_POST["programmer"])==""?-1:$_POST["programmer"]);
                    $programCheckedByID = htmlspecialchars(trim($_POST["programCheckedBy"])==""?-1:$_POST["programCheckedBy"]);
                    $outsideServiceVendorID = htmlspecialchars(trim($_POST["outsideServiceVendorID"])==""?-1:$_POST["outsideServiceVendorID"]);
                    
                    $oldStatusID=htmlspecialchars($_POST['oldStatusID'], ENT_QUOTES, 'UTF-8');
                    $oldSecondaryStatusID=htmlspecialchars($_POST['oldSecondaryStatus']);
                    $localTime=htmlspecialchars($_POST['localTime'], ENT_QUOTES, 'UTF-8');
                    
                    $syncSetups = htmlspecialchars(isset($_POST['syncSetups'])?1:0);
                    
                    // Determine if the user is attempting to add a description
                    if ($addDescription!=null && $addDescription!=""){
                        // Append a line feed, date, who added it and the added description to the description
                        $description=$hiddenDescription . "\n\n" . $localTime . " - Added By " . $userRow["UserName"] . ": " . "\n" . $addDescription;  
                    }
                    
                    // If we have attachments, the links will be in this HTML to let user's know
                    $attachmentHTML = '';

                    // Determine if the user is taking this OUT of completed state and NOT touching priority
                    if ($priority >= 99999 && $completed == 0 && $closed == 0){
                        // Put the priority to be just below 99999
                        $priority=99998;
                    }
                    
                    $taskPrice=htmlspecialchars($_POST['taskPrice'], ENT_QUOTES, 'UTF-8');
                    $rollupPrice=htmlspecialchars($_POST['rollupTaskPrice'], ENT_QUOTES, 'UTF-8');
                    
                    // Determine if the rollup price and the task price are the same
                    // and the task price is not numeric. That means the task price 
                    // should be what is in the database.
                    if ($taskPrice == $rollupPrice || 
                        !is_numeric($taskPrice)){
                        // Set the task price to be what is currently in the database
                        $taskPrice = $currentAssocTaskRow["TaskPrice"];

                        // determine if the price in the database is really null
                        if ($taskPrice==null){
                            // Set the task price to be put in the query as a string null
                            $taskPrice = 'NULL';
                        }
                    }

                    // Create a variable to hold what type of task it is (parent or child)
                    $relativeType = "parent";
                    
                    // Create the visualized task orientation as though this IS the parent
                    $firstFour = str_pad($updateTaskID,4,"0",STR_PAD_LEFT);
                    $lastFour = '0000';

                    // Determine if we are making a child of the parent right now
                    if ($parentTaskNumber != 0){
                        // Isolating the priority logic now since there has been so many problems
                        if ($subPriority!=null && 
                            $currentAssocTaskRow["SubPriority"] != $subPriority){
                            // Change this to child
                            $relativeType = "child";

                            // Create the visualized task orientation as though this IS the parent
                            $firstFour = str_pad($parentTaskNumber,4,"0",STR_PAD_LEFT);
                            $lastFour = str_pad($updateTaskID,4,"0",STR_PAD_LEFT);

                            // Change all sub priorities after this one to fill the gap that this one will vacate
                            $sql = 'UPDATE tasks t SET t.SubPriority=t.SubPriority-1 ' .
                                   'WHERE t.SubPriority >= ' . $currentAssocTaskRow["SubPriority"] . ' ' .
                                   'AND t.SubPriority < 99999 ' .
                                   'AND t.ParentID = ' . $parentTaskNumber . ';'; 

                            // Attempt to run the query
                            $db->queryDB($sql, $userRow, "updateTask Form occurance 3");

                            // Create a query to get the current max priority
                            $sql = 'SELECT Max(SubPriority) AS MaxSubPriority, Count(*) AS Amount ' .
                                   'FROM tasks ' .
                                   'WHERE ParentID = ' . $parentTaskNumber . ' ' .
                                   'AND SubPriority < 99999;';

                            // Run the query
                            $maxSubTaskPriorityRow = $db->queryDB($sql, $userRow, "updateTask Form occurance 4");

                            // Determine if we have one row to look at
                            if (mysqli_num_rows($maxSubTaskPriorityRow)==1){
                                // Get the Row returned
                                $maxSubTaskPriorityAssocRow = $maxSubTaskPriorityRow->fetch_assoc();

                                // Determine if what they are setting for this subtask is higher than the max
                                if ($maxSubTaskPriorityAssocRow["Amount"] > 0 &&
                                    $subPriority>$maxSubTaskPriorityAssocRow["MaxSubPriority"]){
                                    // Set the value to be one more the max priority
                                    $subPriority = $maxSubTaskPriorityAssocRow["MaxSubPriority"] + 1;
                                }
                                else {
                                    // Now make a hole to fit into
                                    $sql = 'UPDATE tasks t SET t.SubPriority=t.SubPriority+1 ' .
                                           'WHERE t.SubPriority >= ' . $subPriority . ' ' .
                                           'AND t.SubPriority < 99999 ' .
                                           'AND t.ParentID = ' . $parentTaskNumber . ';'; 

                                    // Attempt to run the query
                                    $db->queryDB($sql, $userRow, "updateTask Form occurance 5");
                                }
                            }
                        }
                    }
                    else {
                        // Isolating the priority logic now since there has been so many problems
                        if ($priority!=null && ($currentAssocTaskRow["Priority"] != $priority ||
                                                $currentAssocTaskRow["TypeID"] != $typeID ||
                                                $currentAssocTaskRow["CompanyID"] != $companyID ||
                                                $completed == 1 ||
                                                $closed == 1)){
                            // Determine if the order is already completed
                            if ($completed or $closed){
                                // Query to move all rows down that are after the priority that is moving
                                $sql = 'UPDATE tasks SET priority = priority-1 ' .
                                       'WHERE priority > ' . $currentAssocTaskRow["Priority"] . ' ' .
                                       'AND priority < 99999 ' .
                                       'AND TypeID = ' . $typeID . ' ' .
                                       'AND CompanyID = ' . $companyID . ';';

                                // Attempt to change all of the rows that are after the one being completed
                                $db->queryDB($sql, $userRow, "updateTask Form occurance 6");

                                // Change the priority to one that will never be reached (hopefully)
                                $priority=99999;
                            }
                            else {
                                // Determine if they changed this out of completed state 
                                if ($priority>=99999){
                                    // Set it to the max that will be reordered
                                    $priority=99998;
                                }
                                // Determine if somehow they got priority into a number less than one
                                else if ($priority<1){
                                    // Set it as the number 1 priority
                                    $priority=1;
                                }
                                
                                // Determine if the task is changing categories
                                if ($typeID != $currentAssocTaskRow["TypeID"]){
                                    // Create a query to change any of the old type that have a larger priority to fill the gap
                                    $sql = 'UPDATE tasks SET priority = priority-1 ' .
                                           'WHERE priority > ' . ($currentAssocTaskRow["Priority"]) . ' ' .
                                           'AND priority < 99999 ' . 
                                           'AND TypeID = ' . $currentAssocTaskRow["TypeID"] . ' ' .
                                           'AND CompanyID = ' . $currentAssocTaskRow["CompanyID"] . ';';

                                    // Move them
                                    $db->queryDB($sql, $userRow, "updateTask Form occurance 7");
                                }
                                else {
                                    // Create a query to change priority down of any after the one that is moving to close the gap
                                    $sql = 'UPDATE tasks SET priority = priority-1 ' .
                                           'WHERE priority > ' . ($currentAssocTaskRow["Priority"]) . ' ' .
                                           'AND priority < 99999 ' . 
                                           'AND TypeID = ' . $typeID . ' ' .
                                           'AND CompanyID = ' . $currentAssocTaskRow["CompanyID"] . ';';

                                    // Move them
                                    $db->queryDB($sql, $userRow, "updateTask Form occurance 8");
                                }

                                // Let's create the change the current priority to an wierd number for a sec
                                $sql='UPDATE tasks SET Priority=-999 ' . 
                                     'WHERE TaskID=' . $updateTaskID . ' ' .
                                     'OR ParentID = ' . $updateTaskID . ';';

                                // Attempt to change all of the rows that need to be changed
                                $db->queryDB($sql, $userRow, "updateTask Form occurance 9");

                                // Query to move rows up that are before the priority number moving but after where it is moving to
                                $sql = 'UPDATE tasks SET priority = priority+1 ' .
                                       'WHERE priority >= ' . $priority .  ' ' .
                                       'AND priority < 99999 ' . 
                                       'AND TypeID = ' . $typeID . ' ' .
                                       'AND CompanyID = ' . $companyID . ';';

                                // Attempt to change all of the rows that need to be changed
                                $db->queryDB($sql, $userRow, "updateTask Form occurance 10");

                                // Get the max priority of open tasks
                                $sql = 'SELECT (Max(Priority)+1) as MaxPriority ' .
                                            'FROM tasks ' .
                                            'WHERE TypeID = ' . $typeID . ' ' .
                                            'AND CompanyID = ' . $companyID . ' ' .
                                            'AND Priority < 99999 ' .
                                            'AND ParentID = 0 ' .
                                            'AND Closed<>1 ' .
                                            'AND Completed<>1;';
                                
                                $currentMaxPriority = $db->queryDB($sql, $userRow, "updateTask Form occurance 11");
                                $currentAssocMaxPriority = $currentMaxPriority->fetch_assoc();

                                // Determine if the current priority has a greater value than the current greatest value
                                if($currentAssocMaxPriority["MaxPriority"] == null || 
                                   $currentAssocMaxPriority["MaxPriority"] < 1){
                                    // Set the priority to the first one, because there are none
                                    $priority=1;                    
                                }
                                else if($priority  >= $currentAssocMaxPriority["MaxPriority"]){
                                    // Set the priority to the calculated priority
                                    $priority=$currentAssocMaxPriority["MaxPriority"];                    
                                }
                            }
                        }
                    }
                    
                    // Create a query to get see if the old status was the machining status and the machining order
                    $sql = 'SELECT IF(' . $oldStatusID . '=s.StatusID, 1, 0) AS WasMachining, IF(' . $statusID . '=s.StatusID, 1, 0) AS IsMachining, ' .
                           'IF(s.ProcessOrder < (SELECT ProcessOrder FROM status WHERE StatusID=' . $statusID . '), 1,0) AS PassingMachining, ' .
                           'IF(s.ProcessOrder < (SELECT ProcessOrder FROM status WHERE StatusID=' . $oldStatusID . '), 1,0) AS IsFurtherDownTheLine ' .
                           'FROM status s ' .
                           'WHERE Name = "Machining";';

                    // Run the query
                    $machiningStatusRow = $db->queryDB($sql, $userRow, "updateTask Form occurance 12");

                    // Determine if we have one row to look at
                    $machiningStatusAssocRow=null;
                    $isMachining = 0;
                    if (mysqli_num_rows($machiningStatusRow)==1){
                        // Get the Row returned
                        $machiningStatusAssocRow = $machiningStatusRow->fetch_assoc();

                        // set the flag to the value that we determine is going to machining or not
                        $isMachining = $machiningStatusAssocRow["IsMachining"];
                    }
                        
                    // Create a query to get see if the old status was the machining queue status and the machining order
                    $sql = 'SELECT IF(' . $oldStatusID . '=s.StatusID, 1, 0) AS WasMachiningQueue, ' . 
                           'IF(' . $statusID . '=s.StatusID, 1, 0) AS IsMachiningQueue, ' .
                           'IF(s.ProcessOrder < (SELECT ProcessOrder FROM status WHERE StatusID=' . $statusID . '), 1,0) AS PassingMachiningQueue, ' .
                           'IF(s.ProcessOrder < (SELECT ProcessOrder FROM status WHERE StatusID=' . $oldStatusID . '), 1,0) AS IsFurtherDownTheLine ' .
                           'FROM status s ' .
                           'WHERE Name = "Machining Queue";';

                    // Run the query
                    $machiningQueueStatusRow = $db->queryDB($sql, $userRow, "updateTask Form occurance 13");

                    // Determine if we have one row to look at
                    $machiningQueueStatusAssocRow=null;
                    $isMachiningQueue = 0;
                    if (mysqli_num_rows($machiningQueueStatusRow)==1){
                        // Get the Row returned
                        $machiningQueueStatusAssocRow = $machiningQueueStatusRow->fetch_assoc();

                        // Determine if this task is going into machining, was NOT machining AND
                        // is now further down the process.
                        if ($machiningQueueStatusAssocRow["WasMachiningQueue"]!=1 &&   
                            $machiningQueueStatusAssocRow["IsMachiningQueue"] && 
                            !$machiningQueueStatusAssocRow["IsFurtherDownTheLine"]) {
                            // Change the issue date to be now minus the server difference
                            $issuedToMachinesDate = ' DATE_SUB(NOW(), INTERVAL 1 HOUR) ';
                        }
                    }
                        
                    // Setup a variable for the child status to propagate
                    $childStatus = '';

                    // Let's create the update query off of what we have
                    $sql='UPDATE tasks SET ';
                    $sql = $sql . 'LastUpdatedByID=' . $userRow["UserID"];
                    if ($companyID!=null) {$sql = $sql . ', CompanyID=' . $companyID;}
                    if ($typeID!=null) {$sql = $sql . ', TypeID=' . $typeID;}
                    if ($fixtureID!=null) {$sql = $sql . ', FixtureToUseID=' . $fixtureID;}
                    if ($secondaryStatusID!=null) {$sql = $sql . ', SecondaryStatusID=' . $secondaryStatusID;}
                    $sql = $sql . ', PartHardware="' . $partHardware . '"';
                    if ($parentTaskNumber!=null) {$sql = $sql . ', ParentID=' . $parentTaskNumber;}
                    if ($userID!=null) {$sql = $sql . ', UserID=' . $userID;}
                    if ($priority!=null) {$sql = $sql . ', Priority=' . $priority;}
                    if ($subPriority!=null) {$sql = $sql . ', SubPriority=' . $subPriority;}
                    if ($title!=null) {$sql = $sql . ', Title="' . $title . '"';}
                    if ($description!=null) {$sql = $sql . ', Entry="' . $description . '"';}
                    if ($dueDate!=null) {$sql = $sql . ', DueDate="' . $dueDate . '"';}
                    if ($idealDate!=null) {$sql = $sql . ', IdealDate="' . $idealDate . '"';}
                    if ($deliverableQuantity!=null) {$sql = $sql . ', DeliverableQuantity=' . $deliverableQuantity;}
                    if ($totalQuantity!=null) {$sql = $sql . ', TotalQuantity=' . $totalQuantity;}
                    if ($issuedToMachinesDate!=null) {$sql = $sql . ', IssuedToMachineDate=' . $issuedToMachinesDate;}
                    $sql = $sql . ', IsVacuumClean=' . $isVacuumClean;
                    $sql = $sql . ', IsWashForAnodize=' . $isWashForAnodize;
                    $sql = $sql . ', HasAllowableCosmeticDamage=' . $hasAllowableCosmeticDamage;
                    $sql = $sql . ', IsTappedPostMachining=' . $isTappedPostMachining;
                    $sql = $sql . ', PostMachiningTappingInstructions="' . $postMachiningTappingInstructions . '"';
                    $sql = $sql . ', IsSandblasted=' . $isSandblasted;
                    $sql = $sql . ', SandBlastingInstructions="' . $sandBlastingInstructions . '"';
                    $sql = $sql . ', PostMachiningNotes="' . $postMachiningNotes . '"';
                    $sql = $sql . ', PostMachiningFeedback="' . $postMachiningFeedback . '"';
                    $sql = $sql . ', ProgrammerID=' . $programmerID;
                    $sql = $sql . ', ProgramCheckedByID=' . $programCheckedByID;
                    $sql = $sql . ', OutsideServiceVendorID=' . $outsideServiceVendorID;
                    
                    // only update the price if exec or su
                    if ($userRow["UserLevel"]=="SU" || $userRow["UserLevel"]=="EXECUTIVE"){
                        // Set the task price as something to update
                        $sql = $sql . ', TaskPrice=' . $taskPrice;
                    }
                    
                    // Update the flags
                    $sql = $sql . ', Completed=' . $completed . ', Closed=' . $closed. 
                           ', Invoiced=' . $invoiced . ', CleanUp=' . $cleanUp . 
                           ', Expedite=' . $expedite . ', AllPartsSetup=' . $allPartsSetup;
                    
                    // create a status variable too be able to use as propagation as well
                    $statusSQL = '';
                    if ($statusID!=null) {
                        // Setup the Status to be what was set
                        $statusSQL = $statusSQL . ', StatusID=' . $statusID;

                        // Determine if the status ID is higher than submitted
                        if ($statusID>1){
                            // Change it to not be user deletable
                            $statusSQL=$statusSQL . ', UserDeletable=0';
                        }
                    }
                    $sql=$sql . $statusSQL . ' WHERE TaskID=' . $updateTaskID . ' ';
                    $sql=$sql . ' AND ParentID=' . $parentTaskNumber . ';';

//echo '<script>alert("' . addslashes($sql) . '");</script>';
 
                    // Attempt to run the query and evaluate the response
                    if (!$db->queryDB($sql, $userRow, "updateTask Form occurance 14")){
                        echo '<script>alert("Task was NOT updated in the database. Please check the data and try again.");</script>';
                        // TODO: How do I want to display a failure to the user?
                    }
                    else {
                        // Create the visualized task orientation as though this IS the parent
                        $firstFour = str_pad($updateTaskID,4,"0",STR_PAD_LEFT);
                        $lastFour = '0000';

                        // Determine if we just added a child so we can annote the parent appropriately
                        if ($parentTaskNumber != 0){
                            // Create the visualized task orientation as though this IS the parent
                            $firstFour = str_pad($parentTaskNumber,4,"0",STR_PAD_LEFT);
                            $lastFour = str_pad($updateTaskID,4,"0",STR_PAD_LEFT);
                            
                            // Create the update query to update as a parent
                            $sql='UPDATE tasks SET HasChildren=1 WHERE ParentID=0 AND TaskID=' . $parentTaskNumber;
                            
                            // Run the update query
                            $db->queryDB($sql, $userRow, "updateTask Form occurance 15");
                        }
                        else {
                            // Make an update to change common characteristics
                            $sql='UPDATE tasks SET ';
                            if ($companyID!=null) {$sql = $sql . 'CompanyID=' . $companyID;}
                            if ($typeID!=null) {$sql = $sql . ', TypeID=' . $typeID;}
                            if ($priority!=null) {$sql = $sql . ', Priority=' . $priority;}
                            if ($dueDate!=null) {$sql = $sql . ', DueDate="' . $dueDate . '"';}
                            if ($oldSecondaryStatusID!==$secondaryStatusID) {$sql = $sql . ', SecondaryStatusID="' . $secondaryStatusID . '"';}
                            if ($oldStatusID !== $statusID){$sql = $sql . ', UserID=' . $childrenAssignedToID;}
                            
                            // Update the flags
                            $sql = $sql . ', Completed=' . $completed . ', Closed=' . $closed. 
                                   ', Invoiced=' . $invoiced;
                            
                            // Determine if the status has changed
                            if ($oldStatusID != $statusID) {
                                $sql = $sql . $statusSQL;
                            }
                            
                            // Finish up with the where clause
                            $sql=$sql .' WHERE ParentID=' . $updateTaskID . ';';
                            
                            
                            // TODO: How do I handle children with routing? I think I should not allow 
                            //       parents to be put into certain statuses if they have children
                            //       (i.e. Machining, Machining Queue, Etc).  This can be done with a 
                            //       field in the status table that will indicate if this information.
                            
                            
                            // Run the update query
                            $db->queryDB($sql, $userRow, "updateTask Form occurance 16");
                        }
                                                
                        // Set up what the user posted at first, to be changed with logic.
                        $machineID = $_POST["machineID"];
                        $oldMachineID = $_POST["oldMachineID"];
                        $machineTaskOrder=(isset($_POST['machineTaskOrder'])?$_POST['machineTaskOrder']:$_POST['hiddenMachineTaskOrder']);
                        $oldMachineTaskOrder = $_POST["oldMachineTaskOrder"];

                        // Determine if we have one row to look at
                        if (mysqli_num_rows($machiningStatusRow)==1){
                            // Determine if we WERE at machining phase
                            if ($machiningStatusAssocRow["WasMachining"]==1) {
                                // Determine if it is no longer machining (Either up or down) or this machining task is moving to another machine.
                                if ($statusID != $oldStatusID || 
                                    $machineID != $oldMachineID){
                                    // Create a query to remove all suggested tools from both machines
                                    $sql = 'UPDATE assignedtools ' . 
                                           'SET SuggestedChangeNewToolID=-1, SuggestedRemoveToolAfterUse=0, ' . 
                                               'SuggestedExposedLength=0, SuggestedNote="", SuggestedUseNewTool=0 ' . 
                                           'WHERE MachineID = ' . $machineID . ' '; 
                                           'OR MachineID = ' . $oldMachineID . ';'; 

                                    // Run the update query
                                    $db->queryDB($sql, $userRow, "updateTask Form occurance 17");
                                }
                                
                                // Determine if it passing machining down the line
                                if ($machiningStatusAssocRow["PassingMachining"]==1) {
                                    // Set the machine ID to NONE
                                    $machineID=-1;
                                }
                            }
                        }
                        
                        // Determine if any of this has changed before I start the reorder logic
                        if ($machineID != $oldMachineID ||
                            $machineTaskOrder != $oldMachineTaskOrder){
                           
                            // Remove the task from the linker table. Can only have unique tasks here.
                            $sql = 'DELETE FROM tasktomachinelinker WHERE TaskID = ' . $updateTaskID;

                            // Attempt to run the query
                            $db->queryDB($sql, $userRow, "updateTask Form occurance 18");

                            // Determine if we are swapping machines or removing it from machines totally
                            if (($oldMachineID > 0 && $machineID > 0) ||
                                $machineID == -1){
                                // Change the order down for the old machine after this one to fill the gap
                                $sql = 'UPDATE tasktomachinelinker SET TheOrder=TheOrder-1 ' .
                                       'WHERE TheOrder >= ' . $oldMachineTaskOrder . ' ' . 
                                       'AND TheOrder < 99999 ' .
                                       'AND MachineID = ' . $oldMachineID . ';'; 

                                // Attempt to run the query
                                $db->queryDB($sql, $userRow, "updateTask Form occurance 19");
                            }
                            
                            // Determine if we even have anything on a machine now
                            if ($machineID>0){
                                // Create a query to get the max order on the machine in question
                                $sql = 'SELECT (Max(TheOrder)+1) as MaxOrder ' .
                                       'FROM tasktomachinelinker ' .
                                       'WHERE MachineID = ' . $machineID . ' ' .
                                       'AND TheOrder < 99999;';

                                // run the query to get the max order on the machine in question
                                $currentMaxOrder = $db->queryDB($sql, $userRow, "updateTask Form occurance 20");
                                $currentAssocMaxOrder = $currentMaxOrder->fetch_assoc();

                                // Ensure it is a number 
                                if (!is_numeric($machineTaskOrder)){
                                    // Set it to the highest number to order it on the bottom
                                    $machineTaskOrder=99999;
                                }

                                // Determine if there is currently ANY on the machine
                                if($currentAssocMaxOrder["MaxOrder"] == null){
                                    // Set the order to the first one, because there are none
                                    $machineTaskOrder=1;                    
                                }
                                // Determine if the order is greater than the current lowest order (highest number)
                                else if($machineTaskOrder  >= $currentAssocMaxOrder["MaxOrder"]){
                                    // Set the order to the calculated order
                                    $machineTaskOrder=$currentAssocMaxOrder["MaxOrder"];                    
                                }
                                // Then we have to make a hole for this one on this machine
                                else {
                                    // Create a hole in this machine by adding existing tasks down the list
                                    $sql = 'UPDATE tasktomachinelinker SET TheOrder=TheOrder+1 ' .
                                           'WHERE TheOrder >= ' . $machineTaskOrder . ' ' . 
                                           'AND TheOrder < 99999 ' .
                                           'AND MachineID = ' . $machineID . ';'; 

                                    // Attempt to run the query
                                    $db->queryDB($sql, $userRow, "updateTask Form occurance 21");
                                }

                                // Add the task to the link table 
                                $sql = 'INSERT INTO tasktomachinelinker (MachineID, TaskID, TheOrder, IsWaitingToBeReviewed, IsPendingTools, IsPendingApproval) ' .
                                       'VALUES (' . $machineID . ',' . $updateTaskID . ',' . $machineTaskOrder . ', ' . $isWaitingToBeReviewed . 
                                                ', ' . $isPendingTools . ', ' . $isPendingApproval  . ');';
                                
                                // Attempt to run the query 
                                $db->queryDB($sql, $userRow, "updateTask Form occurance 22");
                            }
                        }
                        else {
                            // Create a hole in this machine by adding existing tasks down the list
                            $sql = 'UPDATE tasktomachinelinker ' . 
                                   'SET IsWaitingToBeReviewed=' . $isWaitingToBeReviewed . ', ' . 
                                       'IsPendingTools=' . $isPendingTools . ', ' . 
                                       'IsPendingApproval=' . $isPendingApproval . ' ' . 
                                   'WHERE MachineID=' . $machineID . ' ' . 
                                   'AND TaskID=' . $updateTaskID . ';'; 

                            // Attempt to run the query
                            $db->queryDB($sql, $userRow, "updateTask Form occurance 23");
                        }
                        
                        // Determine if we need to check if the fixture is being used
                        if ($machineID>0){
                            // Create a query to determine if this tasks fixture is being used on another machine
                            $sql='SELECT t.*, m.Name AS MachineName ' . 
                                 'FROM tasktomachinelinker tml ' . 
                                 'LEFT JOIN tasks t on tml.TaskID = t.TaskID ' .
                                 'LEFT JOIN tasks t2 on t.FixtureToUseID = t2.TaskID ' .
                                 'LEFT JOIN machines m on tml.MachineID = m.MachineID ' .
                                 'WHERE tml.MachineID<>' . $machineID . ' ' .
                                 'AND t.FixtureToUseID=' . $fixtureID . ' ' .
                                 'AND t.TaskID<>' . $updateTaskID . ' ' .
                                 'AND m.ShowOnWhiteboard=1 ' .
                                 'AND t2.Entry NOT LIKE "%!!!Not A Unique Fixture!!!%";';

                            // Query the database for the tasks 
                            $rows = $db->queryDB($sql, $userRow, "updateTask Form occurance 24");

                            // Loop through the returned company results
                            $rowNumber = 0;  
                            $taskIDsUsingFixture='';
                            while ($row=mysqli_fetch_array($rows)){
                                // Increment the row number
                                $rowNumber++;

                                // Determine if this is the first one
                                if ($rowNumber==1){
                                    // Setup the first ID in the list
                                    $taskIDsUsingFixture='\n    * ' . $row["TaskID"] . ' ON ' . $row["MachineName"];
                                }
                                else {
                                    // Setup subsequent IDs in the list
                                    $taskIDsUsingFixture=$taskIDsUsingFixture . '\n    * ' . $row["TaskID"] . ' ON ' . $row["MachineName"];
                                }
                            }

                            // Determine if there were rows
                            if ($rowNumber>0){
                                // Let the user know about this
                                echo '<script>alert("There are machines other than the machine this task is on that are using the fixture this task is attempting to use. Here are the details:' . $taskIDsUsingFixture . ' \n\nPlease be sure to take appropriate action if necessary.");</script>';
                            }
                        }

                        // Set the current status of the parent to one that we do not know.
                        $parentStatusIDAfter = -1;
                        
                        // Determine if the status is changing
                        $syncOldCodeForStateChange = false;
                        if ($oldStatusID != $statusID){
                            // This is an update, so start making the update query
                            $sql='UPDATE taskstatus SET ';
                            $sql = $sql . 'EndDate=CURRENT_TIMESTAMP';
                            $sql = $sql . ', Comment="Change in status happening by ' . 
                                   $userRow["FirstName"] . ' ' . $userRow["LastName"] . 
                                   ' from myself."';
                            $sql = $sql . ', CompletingUserID=' . $userRow["UserID"];
                            $sql = $sql . ', Current=0';
                            $sql=$sql .' WHERE TaskID=' . $updateTaskID . ' ';
                            $sql=$sql .' AND ParentID=' . $parentTaskNumber . ' ';
                            $sql=$sql .' AND Current=1;';

                            // Attempt to run the query
                            $db->queryDB($sql, $userRow, "updateTask Form occurance 24");

                            // Determine if we are in delivered state. 10 is that state.
                            // TODO: I should have a flag in the DB for the finishing status
                            $endedDate = 'NULL';
                            If ($statusID==10){
                                // Since this is the delivered state, we end it immediately
                                $endedDate = 'CURRENT_TIMESTAMP';
                            }

                            // This is an insert, so start making the insert query
                            $sql='INSERT INTO taskstatus (TaskID, ParentID, StatusID, EndDate, Comment, StartingUserID, Current, AssignedToUserID) ' .  
                                 'VALUES (' . $updateTaskID . ',' . $parentTaskNumber . ',' . $statusID . ',' . $endedDate . 
                                          ',"Change in status happening by ' . $userRow["FirstName"] . ' ' . $userRow["LastName"] . 
                                          ' from myself.",' . $userRow["UserID"] . ', 1, ' . $userID . ');';

                            // Attempt to run the query
                            $db->queryDB($sql, $userRow, "updateTask Form occurance 25");
                            
                            // Determine if this is a parent or a child so we can make all of the status changes to the children as well.
                            if ($parentTaskNumber == 0){
                                // This is an update, so start making the update query
                                $sql='UPDATE taskstatus SET ';
                                $sql = $sql . 'EndDate=CURRENT_TIMESTAMP';
                                $sql = $sql . ', Comment="Change in status happening by ' . 
                                       $userRow["FirstName"] . ' ' . $userRow["LastName"] . 
                                       ' from my parent."';
                                $sql = $sql . ', CompletingUserID=' . $userRow["UserID"];
                                $sql = $sql . ', Current=0';
                                $sql=$sql .' WHERE ParentID=' . $updateTaskID . ' ';
                                $sql=$sql .' AND Current=1;';

                                // Attempt to run the query
                                $db->queryDB($sql, $userRow, "updateTask Form occurance 26");

                                // This is an insert, so start making the insert query
                                $sql='INSERT INTO taskstatus (TaskID, ParentID, StatusID, EndDate, Comment, StartingUserID, Current, AssignedToUserID) ' .  
                                     'SELECT TaskID,' . $updateTaskID . ', ' . $statusID . ',' . $endedDate . ',"Change in status happening by ' . 
                                             $userRow["FirstName"] . ' ' . $userRow["LastName"] . ' from my parent.",' . 
                                             $userRow["UserID"] . ', 1, ' . $userID . ' FROM tasks WHERE ParentID = ' . $updateTaskID . ';';

                                // Attempt to run the query
                                $db->queryDB($sql, $userRow, "updateTask Form occurance 27");
                            }
                            else {
                                // Create the query to get the correct the parent status
                                $sql =  'SELECT t.*, s.Name as StatusName ' . 
                                        '  FROM tasks t ' . 
                                        '  JOIN status s on t.StatusID = s.StatusID ' . 
                                        '  WHERE t.ParentID = ' . $parentTaskNumber . ' ' .
                                        '  ORDER BY s.ProcessOrder ASC ' . 
                                        '  LIMIT 1';
                                
                                // Get the minimum status currently
                                $currentRollupRow = $db->queryDB($sql, $userRow, "updateTask Form occurance 28");
                                
                                // Ensure that the query came back well
                                if (mysqli_num_rows($currentRollupRow)==1){
                                    $currentAssocRollupRow = $currentRollupRow->fetch_assoc();

                                    // Save the status that we are changing to to this
                                    $parentStatusIDAfter = $currentAssocRollupRow["StatusID"];
                                    $parentStatusNameAfter = $currentAssocRollupRow["StatusName"];
                                    
                                    // Determine if the status is changing
                                    if ($parentStatusID != $parentStatusIDAfter){
                                        // This is updating the parent.  Put an entry into the parents table for statusinfo.
                                        $sql='UPDATE taskstatus SET ';
                                        $sql = $sql . 'EndDate=CURRENT_TIMESTAMP';
                                        $sql = $sql . ', Comment="Change in status happening by ' . 
                                               $userRow["FirstName"] . ' ' . $userRow["LastName"] . 
                                               ' because child TaskID ' . $updateTaskID . ' changed status."';
                                        $sql = $sql . ', CompletingUserID=' . $userRow["UserID"];
                                        $sql = $sql . ', Current=0';
                                        $sql=$sql .' WHERE TaskID=' . $parentTaskNumber . ' ';
                                        $sql=$sql .' AND Current=1;';

                                        // Attempt to run the query
                                        $db->queryDB($sql, $userRow, "updateTask Form occurance 29");

                                        // This is an insert, so start making the insert query
                                        $sql='INSERT INTO taskstatus (TaskID, ParentID, StatusID, EndDate, Comment, StartingUserID, Current, AssignedToUserID) ' .  
                                             'SELECT TaskID,' . $parentTaskNumber . ', ' . $parentStatusIDAfter . ',' . $endedDate . ',"Change in status happening by ' . 
                                                     $userRow["FirstName"] . ' ' . $userRow["LastName"] . ' because child TaskID ' . $updateTaskID . ' changed status.",' . 
                                                     $userRow["UserID"] . ', 1, ' . $userRow["UserID"] . ' FROM tasks WHERE TaskID = ' . $parentTaskNumber . ';';

                                        // Attempt to run the query
                                        $db->queryDB($sql, $userRow, "updateTask Form occurance 30");

                                        // Create the query to update the parent status
                                        $sql =  'UPDATE tasks SET StatusID=' . $parentStatusIDAfter . 
                                                ' WHERE TaskID = ' . $parentTaskNumber . ';';

                                        // Update the parent status and check that it changed
                                        if ($db->queryDB($sql, $userRow, "updateTask Form occurance 31")){
                                            // Since successful, notify everyone who wants to know.
                                            // Let's create and get the users to inform.
                                            $sql='SELECT * 
                                                  FROM users u
                                                  LEFT JOIN (SELECT NotificationCategory, UserID FROM usertostatuslinker 
                                                             WHERE StatusID=' . $parentStatusIDAfter . ') usl ON u.UserID = usl.UserID
                                                  WHERE u.UserID<>' . $userRow["UserID"] . '
                                                  AND u.UserTemplateOnly=0 
                                                  AND u.AccountStatus="Active"
                                                  AND u.SilenceAllTaskNotifications<>1
                                                  AND ((u.CompanyID = ' . $companyID . ') 
                                                       OR (u.CompanyID = 1 AND u.SUEmployee=1) 
                                                       OR (u.UserID = ' . $userID . '));';
        
                                            // Make the query
                                            $usersToNotify = $db->queryDB($sql, $userRow, "updateTask Form occurance 32");

                                            // Loop through the returned results
                                            while ($userToNotify=mysqli_fetch_array($usersToNotify)){
                                                // Determine if this user is the same as the one adding it
                                                if ($userRow["UserID"]!=$userToNotify["UserID"]) {
                                                    // Init the message
                                                    $messageToSend='';

                                                    // Determine if they care about status change or in packaging notifications. 
                                                    //  Also if they are in the SU company and task is being 
                                                    //  assigned to them.  The last is forced.)
                                                    if (($userToNotify["NotificationCategory"]=="PARENT") || 
                                                        ($userToNotify["NotificationCategory"]=="ALL") || 
                                                        ($companyID==1 && $userToNotify["UserID"]==$userID)){
                                                        // Create the message to add for this
                                                        $messageToSend="<br>  ++ The Status has been changed from " .
                                                                       $parentStatusNameBefore . 
                                                                       " to " . $parentStatusNameAfter . ".  ";
                                                        
                                                        // Determine if this one is going into delivered
                                                        if ($parentStatusNameAfter=='Delivered'){
                                                            // Inform that this completes the order
                                                            $messageToSend = $messageToSend . "This completes the FULL order.  It will be invoiced shortly.";
                                                        }

                                                        // add a carriage return
                                                        $messageToSend = $messageToSend . "<br>";
                                                    }

                                                    // First determine if they care about any changes
                                                    if ($messageToSend!="" && 
                                                        preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $userToNotify["EMail"])){

                                                        // Set subscribed to as the default
                                                        $messageToType = " that is under a category that you are currently monitoring.";
                                                        $subjectToType = "EES Subscription Message: ";

                                                        // Determine if this person is assigned to this task or not
                                                        if ($userToNotify["UserID"]==$userID){
                                                            // Change it to an assigned to message
                                                            $messageToType = " that you are ASSIGNED TO.";
                                                            $subjectToType = "EES ASSIGNED TO Message: ";
                                                        }

                                                        // Create the entire message
                                                        $messageToSend= 'There have been changes made by ' . $userRow['FirstName'] . 
                                                                ' ' . $userRow['LastName'] . ' to a child task status ' . 
                                                                'that changed the parent task status' . $messageToType . 
                                                                '<br><br>COMPANY: "' . $currentAssocTaskRow['CompanyName'] . '"' .
                                                                '<br>Parent Task Title: "' . $parentTitle . '"' .
                                                                '<br>Parent TID: ' . $firstFour . '-0000<a href="https://www.eestms.com/' . 
                                                                getTMSHome() . '/updateTask.php?updateTaskID=' . $firstFour . 
                                                                '&parentTaskId=0">  (Click To View)</a>' .
                                                                '<br>Child Task Title: "' . $title . '"' .
                                                                '<br>Child TID: ' . $firstFour . '-' . $lastFour . '<a href="https://www.eestms.com/' .
                                                                getTMSHome() . '/updateTask.php?updateTaskID=' . $lastFour . 
                                                                '&parentTaskId=' . $firstFour . '">  (Click To View)</a>.' . '<br><br>Changes Made:' . 
                                                                $messageToSend;

                                                        // Add a little more message to this notification
                                                        $messageToSend = $messageToSend . '<br><br>If you need help with your user name or password, ' .
                                                                'you can reply to this e-mail or call us at (720)552-7997.<br><br>' .
                                                                'Regards, <br><br>Evolve Engineering and Software Support Team<br>' .
                                                                '(720)552-7997';

                                                        // Decode the quotes to be shown as quotes.  Not weirdness
                                                        $messageToSend = htmlspecialchars_decode ($messageToSend, ENT_COMPAT | ENT_HTML401);

                                                        // Create the subject
                                                        $subject = htmlspecialchars_decode ($subjectToType . "Status change Made to '" . 
                                                                                            $parentTitle . "' via changing " . 
                                                                                            "child task status for company '" . 
                                                                                            $currentAssocTaskRow["CompanyName"] . "'.");
                                                        $headers = "From: EES Mail Admin"." <admin@eestms.com>\r\n"; 
                                                        $headers .= "MIME-Version: 1.0\r\n";
                                                        $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
                                                        
                                                        try {
                                                            // Attempt to mail it
                                                            mail($userToNotify["EMail"],$subject,$messageToSend,$headers);
                                                        } 
                                                        catch (Exception $e) {
                                                            echo("The notification was not sent to " . $userToNotify["EMail"] .
                                                                 " because of an error.");
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            
                            // Create a query to get see if the task was in programming or In Review before
                            $sql = 'SELECT * FROM status ' .
                                   'WHERE (Name = "Programming" OR Name = "In Review" OR Name = "Copy Review" OR Name = "Pink Note Copy Review") ' .
                                   'AND StatusID = ' . $oldStatusID . ';';

                            // Run the query
                            $lastStatusRow = $db->queryDB($sql, $userRow, "updateTask Form occurance 33");

                            // Determine if we have one row to look at
                            if (mysqli_num_rows($lastStatusRow)==1){
                                // Set it to sync up the GCode from these states
                                $syncOldCodeForStateChange = true;
                            }
                        }
                        // determine if the user ID is changing, status did not. If so, keep track of user exchange in history.
                        else if ($currentAssocTaskRow["UserID"] != $userID){
                            // This is an update, so start making the update query
                            $sql='UPDATE taskstatus SET ';
                            $sql = $sql . 'EndDate=CURRENT_TIMESTAMP';
                            $sql = $sql . ', Comment="Change in assigned-to user happening by ' . 
                                   $userRow["FirstName"] . ' ' . $userRow["LastName"] . 
                                   ' from myself."';
                            $sql = $sql . ', CompletingUserID=' . $userRow["UserID"];
                            $sql = $sql . ', Current=0';
                            $sql=$sql .' WHERE TaskID=' . $updateTaskID . ' ';
                            $sql=$sql .' AND ParentID=' . $parentTaskNumber . ' ';
                            $sql=$sql .' AND Current=1;';

                            // Attempt to run the query
                            $db->queryDB($sql, $userRow, "updateTask Form occurance 34");

                            // Determine if we are in delivered state. 10 is that state.
                            // TODO: I should have a flag in the DB for the finishing status
                            $endedDate = 'NULL';
                            If ($statusID==10){
                                // Since this is the delivered state, we end it immediately
                                $endedDate = 'CURRENT_TIMESTAMP';
                            }

                            // This is an insert, so start making the insert query
                            $sql='INSERT INTO taskstatus (TaskID, ParentID, StatusID, EndDate, Comment, StartingUserID, Current, AssignedToUserID) ' .  
                                 'VALUES (' . $updateTaskID . ',' . $parentTaskNumber . ',' . $statusID . ',' . $endedDate . 
                                          ',"Change in assigned-to user happening by ' . $userRow["FirstName"] . ' ' . $userRow["LastName"] . 
                                          ' from myself.",' . $userRow["UserID"] . ', 1, ' . $userID . ');';

                            // Attempt to run the query
                            $db->queryDB($sql, $userRow, "updateTask Form occurance 35");
                        }

                        // Create an array of positions that are greater than zero to be passed between the tool functions
                        $goodPositions = array();

                        // Check if there are any mods to old tools
                        $duplicatePositions=updateOldTools($db, $userRow, $updateTaskID, $parentTaskNumber, $goodPositions);

                        // Add any new tools that the user added
                        $duplicatePositions|=addNewToolsToDB($db, $updateTaskID, $userRow, $parentTaskNumber, $goodPositions);
                        
                        // Determine if there were duplicate positions in the updated area
                        if ($duplicatePositions){
                            // Let them know
                            echo '<script>alert("There were duplicated positions in the tools for this task.  Those were unset.");</script>';
                        }
                        
                        // Determine if it IS a machining phase and the status has changed to machining
                        if ($isMachining == 1 &&
                            ($statusID != $oldStatusID || $machineID != $oldMachineID)) {
                            // Create a query to remove all suggested tools from both machines
                            $sql = 'UPDATE assignedtools ' . 
                                   'SET SuggestedChangeNewToolID=-1, SuggestedRemoveToolAfterUse=0, ' .
                                       'SuggestedExposedLength=0, SuggestedNote="" ' . 
                                   'WHERE MachineID = ' . $machineID . ' ' . 
                                   'OR MachineID = ' . $oldMachineID . ';'; 

                            // Run the update query
                            $db->queryDB($sql, $userRow, "updateTask Form occurance 36");
                            
                            // Set the tools for this newly assigned task
                            setTaskToolsAsSuggested($db, $userRow, $updateTaskID, $machineID);
                        }
                        
                        // Check if there are any mods to old blanks
                        updateOldBlanks($db, $userRow, $updateTaskID, $parentTaskNumber);

                        // Add any new blanks that the user added
                        addNewBlanksToDB($db, $userRow, $updateTaskID, $parentTaskNumber);
                        
                        // Check if there are any mods to old setups
                        if (updateOldSetups($db, $userRow, ($syncOldCodeForStateChange||$syncSetups), $machineID)==true){
                            // Reassign this back to this user and change the status back to the old state.
                            $sql = 'UPDATE tasks t ' . 
                                   'SET t.StatusID=' . $oldStatusID . ', ' .
                                      ' t.UserID=' . $userRow["UserID"] . ' ' .
                                   'WHERE t.TaskID=' . $updateTaskID . ';'; 

                            // Attempt to run the query
                            $db->queryDB($sql, $userRow, "updateTask Form occurance 37");
                            
                            // Change the redirect to go back here.
                            $redirectTo = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on'?"https" : "http") . "://" . $_SERVER['HTTP_HOST'] .  $_SERVER['REQUEST_URI']);
                        }

                        // Add any new setups that the user added
                        addNewSetupsToDB($db, $userRow, $updateTaskID);
                        
                        // Check if there are any mods to old notes
                        updateOldNotes($db, $userRow);

                        // Add any new notes that the user added
                        addNewNotesToDB($db, $userRow, $updateTaskID, $userRow["UserID"], "TASK");

                        // Check if there are any mods to old sticky notes
                        updateOldStickyNotes($db, $userRow);

                        // Add any new sticky notes that the user added
                        addNewStickyNotesToDB($db, $userRow, $updateTaskID, $userRow["UserID"], "TASK");
                
                        // Determine if there are previous ones to delete
                        if (isset($_POST['deleteCurrentAttachments']) and $_POST['deleteCurrentAttachments']!=''){
                            // Get the numbers to remove in order to trim and then work with it
                            $numbersToRemoveAsString = substr($_POST['deleteCurrentAttachments'], 0, -1);

                            // Should be in a good form already. Let's delete them.
                            $sql = "DELETE FROM attachments where AttachmentID in (" . 
                                   $numbersToRemoveAsString . ");";

                            // Run the delete query the selected attachments from that table
                            $db->queryDB($sql, $userRow, "updateTask Form occurance 38");
                        }
                        
                        // Determine if there are new attachment numbers
                        if (isset($_POST['newAttachmentNumbers']) and $_POST['newAttachmentNumbers']!=0){
                            // Get the amount of new attachments as a variable
                            $attachmentNumString=$_POST['newAttachmentNumbers'];
                            $attachmentNums=explode('|', $attachmentNumString);

                            // Start the attachment HTML
                            $attachmentHTML="";
                            
                            // Loop through and get all new attachment elements
                            $numberGoodAttachments=0;
                            foreach ($attachmentNums as $loopNumber){
                                // Get the oversized attribute
                                $oversized = htmlspecialchars($_POST['oversized'.$loopNumber], ENT_QUOTES, 'UTF-8');
                                
                                // determine if the image has been uploaded
                                if(!$oversized && is_uploaded_file($_FILES['attachmentElement'.$loopNumber]['tmp_name'])) {
                                    // Get the properties of the file to upload
                                    $fname    = $db->getDBConnection()->real_escape_string($_FILES['attachmentElement'.$loopNumber]['name']); 
                                    $tmpName  = $db->getDBConnection()->real_escape_string($_FILES['attachmentElement'.$loopNumber]['tmp_name']);
                                    $fileSize = intval($_FILES['attachmentElement'.$loopNumber]['size']);
                                    $fileType = $db->getDBConnection()->real_escape_string($_FILES['attachmentElement'.$loopNumber]['type']);

                                    //process the file
                                    $content = $db->getDBConnection()->real_escape_string(file_get_contents($tmpName));

                                    // Determine if we got any data
                                    if ($content!=null) {
                                        // Determine if the magic quotes option is on
                                        if(!get_magic_quotes_gpc()){
                                            // Add slashes to the name
                                            $fname = addslashes($fname);
                                        }

                                        // Let's create the insert query off of what we have
                                        $sql = "INSERT INTO attachments (TaskID, UserID, " .
                                               "FileType, Title, ByteSize, Datum) " .
                                               "VALUES ($updateTaskID, $userID, '$fileType', " .
                                               "'$fname','$fileSize','$content');";

                                        // Attempt to run the query and get the response
                                        if ($db->queryDB($sql, $userRow, "updateTask Form occurance 39")){
                                            // Let the user know that upload of this file worked
                                            echo("The file ('" . $fname . "') was uploaded successfully.");

                                            // Get the most recent ID (attachmentID)
                                            $newAttachmentID = mysqli_insert_id($db->getDBConnection());

                                            // Increase the amount of successful attachments
                                            $numberGoodAttachments++;
                                        }
                                        else {
                                            // Let the user know that upload of this file did not work
                                            echo("The file ('" . $fname . "') was NOT uploaded successfully.");
                                        }
                                    }
                                    else {
                                        // Let the user know that the blob was NOT uploaded.
                                        echo("The file ('" . $fname . "') did not get uploaded because there was no datum.");
                                    }
                                }   
                            }
                            
                            // Determine if there were NO good attachments added
                            if ($numberGoodAttachments<1){
                                // Set the HTML back to nothing
                                $attachmentHTML='';
                            }
                            else {
                                // Set it with the appropriate number that were uploaded
                                $attachmentHTML="  ++ Attachments: There are " .
                                    $numberGoodAttachments . " new attachments to " .
                                    "this task that are added as links in this " . 
                                    "e-mail.<br><br>" . $attachmentHTML;
                            }
                        }

// TODO: Remove this if statement fully if it works out I really do not need it. I added it originally as 
//       a failsafe for not spamming people, but removed it because I need to know when ANY change happens.                        
//                        // First determine if notifications need to be sent out
//                        if ((($statusID!=null) && ($statusID!=$currentAssocTaskRow["StatusID"])) ||
//                            (($priority!=null) && ($priority!=$currentAssocTaskRow["Priority"])) ||
//                            (isset($_POST['newAttachmentNumbers']) and $_POST['newAttachmentNumbers']!=0) || 
//                            ($userToNotify["CompanyID"]==1 && $userToNotify["UserID"]==$userID)){
                            // Determine if this is a parent or child.  We do not currently notify customers about children changes.
                        
                        
                        // Get the current row so that I can figure out if the task has currently changed
                        $sql = 'SELECT * FROM tasks ' .
                               'WHERE TaskID=' . $updateTaskID . ';';
                        $finalTaskRow = $db->queryDB($sql, $userRow, "updateTask Form occurance 40");

                        // Determine if we even have a task returned
                        if (mysqli_num_rows($finalTaskRow)==1){
                            // Get the current task row to work with as the assoc style
                            $finalAssocTaskRow = $finalTaskRow->fetch_assoc();

                            // Determine if they are the same
                            if (taskRowsHaveMajorDifferences($finalAssocTaskRow, $currentAssocTaskRow) ||
                                (isset($_POST['newAttachmentNumbers']) && 
                                 $_POST['newAttachmentNumbers']!=0)){
                                // Determine if the creator and the assigned to are the same person
// TODO: Determine why I had this in here
//                                if ($userRow["UserID"] != $userID || 
//                                    ($statusRowAssoc["Name"]=='Packaging' &&
//                                     (($userToNotify["CompanyID"]==1 && 
//                                       ($programCheckedByID==$userToNotify["UserID"] ||
//                                        $programmerID==$userToNotify["UserID"]))))){
                                if ($userRow["UserID"] != $userID){
                                    // Include this user.
                                    $sql='OR u.UserID = ' . $userID . ' ';
                                }
                                else {
                                    // Exclude this user since they created it and didn't program it.
                                    $sql='AND u.UserID<>' . $userRow["UserID"] . ' ';
                                }

                                // Determine if this is a parent or not
                                if ($parentTaskNumber == 0){
                                    // Let's create and get the users to inform
                                    $sql='SELECT u.*, usl.NotificationCategory 
                                          FROM users u
                                          LEFT JOIN (SELECT NotificationCategory, UserID FROM usertostatuslinker 
                                                     WHERE StatusID=' . $statusID . ') usl ON u.UserID = usl.UserID
                                          WHERE u.AccountStatus="Active" 
                                          AND u.UserTemplateOnly=0 
                                          AND u.SilenceAllTaskNotifications<>1
                                          AND ((u.CompanyID = ' . $companyID . ') 
                                               OR (u.CompanyID = 1 AND u.SUEmployee=1) 
                                               ' . $sql . ');';
                                }
                                else{
                                    // Let's create and get the users to inform
                                    $sql='SELECT u.*, usl.NotificationCategory 
                                          FROM users u
                                          LEFT JOIN (SELECT NotificationCategory, UserID FROM usertostatuslinker 
                                                     WHERE StatusID=' . $statusID . ') usl ON u.UserID = usl.UserID
                                          WHERE u.CompanyID = 1 
                                          AND u.UserTemplateOnly=0 
                                          AND u.SilenceAllTaskNotifications<>1
                                          AND u.SUEmployee=1 
                                          AND u.AccountStatus="Active"
                                          ' . $sql;
                                }

                                // Make the query
                                $usersToNotify = $db->queryDB($sql, $userRow, "updateTask Form occurance 41");

                                // Loop through the returned results
                                while ($userToNotify=mysqli_fetch_array($usersToNotify)){
                                    // init the initial headers to add for important things
                                    $additionalHeaders="";

                                    // Determine if this user is the same as the one adding it
                                    if ($userRow["UserID"]!=$userToNotify["UserID"]) {
                                        // Init the message
                                        $textMessageToSend='';
                                        
                                        // Determine if the account status has changed and if the user cares about this
                                        if (($statusID!=null) && 
                                            ($statusID!=$currentAssocTaskRow["StatusID"])) {
                                            // Create a query to get the status name that we are changing to
                                            $sql = 'SELECT * FROM status WHERE StatusID = "' . $statusID . '"';
                                            $statusRow = $db->queryDB($sql, $userRow, "updateTask Form occurance 42");
                                            $statusRowAssoc = $statusRow->fetch_assoc();

                                            // Determine if they care about ANY status changing 
                                            // (Receive status change or in packaging notifications. 
                                            //  Also if they are in the SU company and task is being 
                                            //  assigned to them.  The last is forced.)
                                            if (($userToNotify["NotificationCategory"]=="CHILD" && $parentTaskNumber>0) || 
                                                ($userToNotify["NotificationCategory"]=="PARENT" && $parentTaskNumber==0) || 
                                                ($userToNotify["NotificationCategory"]=="ALL") || 
                                                ($userToNotify["CompanyID"]==1 &&
                                                 $userToNotify["UserID"]==$userID)){
                                                // Create the message to add for this
                                                $textMessageToSend="<br>  ++ The Status has been changed from " .
                                                               $currentAssocTaskRow["Name"] . 
                                                               " to " . $statusRowAssoc["Name"] . ".  ";
                                                
                                                // Determine if this one is going into delivered and it is a parent
                                                if ($statusRowAssoc["Name"]=='Delivered' && $parentTaskNumber==0){
                                                    // Inform that this completes the order
                                                    $textMessageToSend = $textMessageToSend . "This completes the FULL order.  It will be invoiced shortly.";
                                                }

                                                // add a carriage return
                                                $textMessageToSend = $textMessageToSend . "<br>";
                                            }
                                            
                                            // Determine if this one is going into delivered and they want to know about final notes
                                            if ($statusRowAssoc["Name"]=='Packaging' &&
                                                ($userToNotify["ReceiveNotesNotificationUpdate"] ||
                                                 ($userToNotify["CompanyID"]==1 && 
                                                  ($programCheckedByID==$userToNotify["UserID"] ||
                                                   $programmerID==$userToNotify["UserID"])))){
                                                // Determine if there are any post machining Feedback Notes
                                                if (($postMachiningFeedback != null &&
                                                     $postMachiningFeedback != '')){
                                                    // Create something for the machining feedback
                                                    $textMessageToSend=$textMessageToSend . 
                                                                       "<br>  ++ There are <b>Post Machining Feedback Notes</b> of:<br>" .
                                                                       $postMachiningFeedback . "<br>";
                                                    
                                                    // Determine if this was the programmer or the programmer manager
                                                    if ($userToNotify["CompanyID"]==1 && 
                                                          ($programCheckedByID==$userToNotify["UserID"] ||
                                                           $programmerID==$userToNotify["UserID"])){
                                                        // Set this as high priority to look at for this user
                                                        $additionalHeaders = "X-Priority: 1 (Highest)\r\n";
                                                        $additionalHeaders .= "X-MSMail-Priority: High\r\n";
                                                        $additionalHeaders .= "Importance: High\r\n";
                                                    }
                                                }
                                                
                                                // Create a query to see if there were any machining operator notes on the setups
                                                $sql='SELECT n.*, ms.Side 
                                                      FROM notes n
                                                      LEFT JOIN machiningsetups ms ON n.AssociatedCategoryID = ms.MachiningSetupID
                                                      LEFT JOIN tasks t ON ms.TaskID = t.TaskID
                                                      WHERE n.Category="OPERATOR_FEEDBACK_NOTE" 
                                                      AND t.TaskID = ' . $updateTaskID . ' 
                                                      AND n.IsSticky=0 
                                                      ORDER BY ms.SetupOrder;';

                                                // Make the query
                                                $setupsWithOperatorNotes = $db->queryDB($sql, $userRow, "updateTask Form occurance 43");

                                                // Determine if there were rows
                                                if (mysqli_num_rows($setupsWithOperatorNotes)>0){
                                                    // Determine if this was the programmer or the programmer manager
                                                    if ($userToNotify["CompanyID"]==1 && 
                                                          ($programCheckedByID==$userToNotify["UserID"] ||
                                                           $programmerID==$userToNotify["UserID"])){
                                                        // Set this as high priority to look at for this user
                                                        $additionalHeaders = "X-Priority: 1 (Highest)\r\n";
                                                        $additionalHeaders .= "X-MSMail-Priority: High\r\n";
                                                        $additionalHeaders .= "Importance: High\r\n";
                                                    }
                                                    
                                                    // Create something for the machining feedback
                                                    $textMessageToSend=$textMessageToSend . 
                                                                       "<br>  ++ There are <b>Operator Feedback Machining Notes</b>:<br>";
                                                                       
                                                    // Loop through the returned results
                                                    $noteNumber=0;
                                                    $sideNumber=0;
                                                    while ($setupWithOperatorNotes=mysqli_fetch_array($setupsWithOperatorNotes)){
                                                        // Determine if the side is different
                                                        if ($sideNumber != $setupWithOperatorNotes["Side"]){
                                                            // Set the side to the current side
                                                            $sideNumber=$setupWithOperatorNotes["Side"];

                                                            // Reset the note number
                                                            $noteNumber=0;
                                                        }

                                                        // Increment the note number
                                                        $noteNumber++;

                                                        // Determine if there is an image or not
                                                        $imageAssociatedInfo='';
                                                        if ($setupWithOperatorNotes["Datum"]!=null){
                                                            // Let the user know there is an image associated with it
                                                            $imageAssociatedInfo="         Attachment - Has an attachment associated<br>";
                                                        }
                                                        
                                                        // Create something for the machining feedback
                                                        $textMessageToSend=$textMessageToSend . 
                                                                           "         Side - " . $sideNumber . "<br>" .
                                                                           "         Note Number - " . $noteNumber . "<br>" .
                                                                           "         Title - " . $setupWithOperatorNotes["Title"] . "<br>" .
                                                                           "         Note Text - " . $setupWithOperatorNotes["Note"] . "<br>" .
                                                                           $imageAssociatedInfo . "<br>";
                                                    }
                                                }                                                
                                            }
                                        }

                                        // Determine if the priority has changed and if the user cares about this
                                        if (($priority!=null) && 
                                            ($priority!=$currentAssocTaskRow["Priority"]) &&
                                            (($userToNotify["ReceivePriorityChangeUpdate"]) || 
                                             ($userToNotify["CompanyID"]==1 &&
                                              $userToNotify["UserID"]==$userID))){
                                                // Create the message to add for this
                                                $textMessageToSend=$textMessageToSend . "<br>  ++ The Priority " .
                                                        "has been changed from " . $currentAssocTaskRow["Priority"] . 
                                                        " to " . $priority . ".<br>";
                                        }

                                        // Determine if there are new attachments and if the user cares about this
                                        if (isset($_POST['newAttachmentNumbers']) && 
                                            $_POST['newAttachmentNumbers']!=0 &&
                                            (($userToNotify["ReceiveAttachmentUpdate"]) || 
                                             ($userToNotify["CompanyID"]==1 &&
                                              $userToNotify["UserID"]==$userID))){
                                                // Create the message to add for this
                                                $textMessageToSend=$textMessageToSend . "<br>  ++ Attachments: There are " .
                                                               $numberGoodAttachments . " new attachments to " .
                                                               "this task that are added as links in this " . 
                                                               "e-mail.<br><br>";
                                        }

                                        // Determine if this user is the user it is assigned to and they are from the primary company
                                        // and if a change that is tracked has NOT been made
                                        if ($userToNotify["CompanyID"]==1 &&
                                            $userToNotify["UserID"]==$userID &&
                                            $textMessageToSend==''){
                                            // Create the message to add for this
                                            $textMessageToSend='<br> ++ Untracked Changes.<br>';
                                        }

                                        // First determine if there has been a message made
                                        if ($textMessageToSend!="" && 
                                            preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $userToNotify["EMail"])){

                                            // Set subscribed to as the default
                                            $messageToType = " that is under a category that you are currently monitoring.";
                                            $subjectToType = "EES Subscription Message: ";
                                            
                                            // Create a variable for attachments and set it to NULL for now
                                            $zipName = '';
                                            
                                            // Determine if this person is assigned to this task or not. Add attachments to the user assigned.
                                            if ($userToNotify["UserID"]==$userID){
                                                // Change it to an assigned to message
                                                $messageToType = " that you are ASSIGNED TO.";
                                                $subjectToType = "EES ASSIGNED TO Message: ";
                                            }
                                                
                                            // Create the entire message
                                            $textMessageToSend= 'There have been changes made by ' . $userRow['FirstName'] . 
                                                    ' ' . $userRow['LastName'] . ' to a task' . $messageToType .
                                                    '<br><br>COMPANY: "' . $currentAssocTaskRow['CompanyName'] . '"' .
                                                    '<br>Task Title: "' . $currentAssocTaskRow['Title'] . '"' . 
                                                    '<br>TID: ' . $firstFour . '-' . $lastFour . '<a href="https://www.eestms.com/' . 
                                                    getTMSHome() . '/updateTask.php?updateTaskID=' . $updateTaskID . 
                                                    '&parentTaskId=' . $parentTaskNumber . '">  (Click To View)</a>.<br><br>Changes Made:' . 
                                                    $textMessageToSend;

                                            // Add a little more message to this notification
                                            $textMessageToSend = $textMessageToSend . '<br><br>If you would like to check ' .
                                                    'on the task, you can do so at <a href="https://www.eestms.com/' . 
                                                    getTMSHome() . '/updateTask.php?updateTaskID=' . $updateTaskID . 
                                                    '&parentTaskId=' . $parentTaskNumber . '">www.eestms.com/' . 
                                                    getTMSHome() . '</a>.<br><br>If you need help with your user ' .
                                                    'name or password, you can reply to this e-mail or call us at ' .
                                                    '(720)552-7997.<br><br>Regards, <br><br>Evolve Engineering and Software ' .
                                                    'Support Team<br>(720)552-7997';

                                            // Decode the quotes to be shown as quotes.  Not weirdness
                                            $textMessageToSend = htmlspecialchars_decode ($textMessageToSend, ENT_COMPAT | ENT_HTML401);

                                            // Create the subject
                                            $subject = htmlspecialchars_decode ($subjectToType . "Change Made to task '" . $currentAssocTaskRow['Title'] . 
                                                                                "' for company '" . $currentAssocTaskRow["CompanyName"] . "'.");
                                            
                                            try {
                                                // Sender 
                                                $from = 'admin@eestms.com'; 

                                                // Header for sender info 
                                                $headers = "From: EES Mail Admin"." <".$from.">\n"; 

                                                // Preparing attachment 
                                                if($zipName != '' && !empty($zipName) > 0){ 
                                                    // Boundary  
                                                    $semi_rand = md5(time());  
                                                    $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";  

                                                    // Headers for attachment  
                                                    $headers .= "MIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"\n" . $additionalHeaders; 

                                                    // Multipart boundary  
                                                    $message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" . 
                                                    "Content-Transfer-Encoding: 7bit\n\n" . $textMessageToSend . "\n\n";  

                                                    // Ensure there is a file there
                                                    if(is_file($zipName)){ 
                                                        // Setup the message for the attachment
                                                        $message .= "--{$mime_boundary}\n"; 
                                                        $fp =    fopen($zipName,"rb"); 
                                                        $data =  fread($fp,filesize($zipName)); 

                                                        fclose($fp); 
                                                        $data = chunk_split(base64_encode($data)); 
                                                        $message .= "Content-Type: application/octet-stream; name=\"".basename($zipName)."\"\n" .  
                                                        "Content-Description: ".basename($zipName)."\n" . 
                                                        "Content-Disposition: attachment;\n" . " filename=\"".basename($zipName)."\"; size=".filesize($zipName).";\n" .  
                                                        "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n"; 
                                                    } 
                                                    $message .= "--{$mime_boundary}--"; 
                                                    $returnpath = "-f" . $from; 

                                                    // Send email 
                                                    $mail = mail($userToNotify["EMail"], $subject, $message, $headers, $returnpath);  
                                                    
                                                    // Run the query
                                                    $currentTaskAttachments = $db->queryDB($sql, $userRow, "updateTask Form occurance 44");

                                                    // Determine if we got something in the query for attachments
                                                    if ($currentTaskAttachments != null){
                                                        // Loop through the returned results
                                                        while ($currentTaskAttachment=mysqli_fetch_array($currentTaskAttachments)){
                                                            // Remove the file
                                                            unlink('./temp/' . $currentTaskAttachment["Title"]);
                                                        }
                                                    }
                                                    
                                                    // Remove the file
                                                    unlink($zipName);
                                                } 
                                                else
                                                {
                                                    // Setup the e-mail for no attachments
                                                    $headers .= "MIME-Version: 1.0\r\n";
                                                    $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
                                                    $headers .= $additionalHeaders; 
                                                    
                                                    // Attempt to mail it
                                                    mail($userToNotify["EMail"],$subject,$textMessageToSend,$headers);
                                                }
                                            } 
                                            catch (Exception $e) {
                                                echo("The notification was not sent to " . $userToNotify["EMail"] .
                                                     " because of an error.");
                                            }
                                        }
                                    }
                                }
                            }
                        }

                        
                        // Determine if this was referred to from the machining screen
                        if (validate_url($redirectTo) &&
                            (strpos($redirectTo, "machiningTasks.php")!=false)) {
                            // Close this window
                            echo ("<script>window.close();</script>");
                        }
                        else {
                            // Determine if this has a redirect.  If none, then it was probably opened from an e-mail.
                            if ($redirectTo==null || $redirectTo==""){
                                // Determine if this is a parent or a child
                                if ($parentTaskNumber==0){
                                    // Redirect to the tasks page of the company of this task
                                    $redirectTo = 'https://www.eestms.com/' . getTMSHome() . '/tasks.php?cs=' . $companyID . '&ts=' . $fromWhatType;
                                }
                                else {
                                    // Redirect to the parent page of the company of this task
                                    $redirectTo = 'https://www.eestms.com/' . getTMSHome() . '/updateTask.php?updateTaskID=' . $parentTaskNumber . '&parentTaskId=0';
                                }
                            }
                            
                            // redirect to the tasks page
                            echo ('<script>window.location = "' . $redirectTo . '";</script>');
                        }
                    }
                }
            }
        }
        else {
            // Set the form submitted session variable to FALSE
            $_POST['formSubmitted']='FALSE';
            
            // Determine if we are going to see a parent
            if ($parentTaskNumber==0 &&
                validate_url($fromWhatBaseURL) &&
                (strpos($fromWhatBaseURL, "updateTask.php")!=false ||
                 strpos($fromWhatBaseURL, "addTask.php")!=false)) {
                // Setup the place to be redirected to as a parent after form submission
                $fromWhatBaseURL = 'https://www.eestms.com/' . getTMSHome() . '/tasks.php?cs=' . $fromWhatCompany . '&ts=' . $fromWhatType;
            }
        }
    }
?>
        
﻿<!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 - Update Task</title>

    <meta name="keywords" content="GIS,data,testing,IT" />
    <meta name="description" content="EES Divisions." />

    <script src="./SpryAssets/SpryMenuBar.js" type="text/javascript"></script>
    
    <script src="javascript/general.js" type="text/javascript"></script>
    <script src="javascript/tasks.js" type="text/javascript"></script>
    <script src="javascript/attachments.js" type="text/javascript"></script>
    <script src="javascript/notes.js" type="text/javascript"></script>
    <script src="javascript/notes_inner.js" type="text/javascript"></script>
    <script src="javascript/tools.js" type="text/javascript"></script>
    <script src="javascript/setups.js" type="text/javascript"></script>
    <script src="javascript/blanks.js" type="text/javascript"></script>
    <script src="javascript/routing.js" type="text/javascript"></script>
    
    <script src="scripts/gen_validatorv4.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 href="scripts/jpicker-1.1.6/css/jPicker-1.1.6.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" />
    
    <link rel="shortcut icon" href="../images/logo_EES_trans_256x256.png"/>
    
    <style type="text/css">
        .statuses_sortable
        .statuses_sortable { list-style-type: none; margin: 0; padding: 0; width: 100%; }
        .statuses_sortable li { margin: 0 0 0 0; padding: 0 0 0 0;}
        .ui-state-highlight { height: 1.5em; line-height: 1.2em; }
        #subTaskDiv{
            display:none;
        }
        .EmployeeOption{
            font-weight:bold;
        }
        .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
        {
            color: black;
            display: table-cell;
            border: solid;
            border-width: thin;
            padding-left: 1px;
            padding-right: 1px;
            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;
        }
        .statusCell
        {
            width: 19%;
        }
        .childStatusCell
        {
            width: 12%;
        }
        .quantityCell
        {
            width: 8%;
            text-align: center;
        }
        .companyCell
        {
            width: 14%;
        }
        .priCell
        {
            width: 4%;
            text-align: center;
        }
        .expandCell
        {
            width: 1%;
            text-align: center;
        }
        .branchCell
        {
            width: 4%;
            text-align: center;
        }
        .keepRoutingCell
        {
            width: 3%;
            text-align: center;
        }
        span {
          display: inline-block;
          vertical-align: middle;
          line-height: normal;      
        }
        
        .updateCell
        {
            width: 17%;
            text-align: center;
        }
        .numberCell
        {
            text-align: center;
            width: 3%;
        }
        .typeCell
        {
            text-align: center;
            width: 20%;
        }
        .sizeCell
        {
            text-align: center;
            width: 20%;
        }
        .checkCell
        {
            text-align: center;
            width: 20%;
        }
        .mainLabelCell
        {
            text-align: left;
            width: 15%;
        }
        .fileInputCell
        {
            text-align: center;
            width: 50%;
        }
        .buttonCell
        {
            text-align: center;
        }
        .noteTableCell
        {
            display: table-cell;
        }
        
        /* styles for the hidden table */
        .ssCatCell
        {
            width: 10%;
            text-align: center;
        }
        .ssNameCell
        {
            width: 40%;
            text-align: center;
        }
        .ssTypeCell
        {
            width: 10%;
            text-align: center;
        }
        .ssAmountCell
        {
            width: 12%;
            text-align: center;
        }
        .ssLLCell
        {
            width: 9%;
            text-align: center;
        }
        .ssUpdateCell
        {
            width: 7%;
            text-align: center;
        }
        
        /* Start CSS for the current notes */
        .fullNoteLabelCell
        {
            text-align: right;
        }
        .fullNoteTextCell
        {
            width: 80%;
            text-align: left;
        }
        .fullLabelCell
        {
            width: 20%;
            text-align: center;
        }
        .fullTextCell
        {
            width: 80%;
            text-align: left;
        }
        .fullAddressCell
        {
            width: 85%;
            text-align: left;
        }
        
        /* Simulate the disabled atribute, but still pass the values */
        .disable{
            pointer-events:none;
            background:lightgrey;
            /* border: solid red 1px; */
        }        
        
        /* Simulate the disabled atribute, but still pass the values */
        .disableaslabel{
            pointer-events:none;
            background: rgba(0, 0, 0, 0);
            border: none;
        }        
        
        /* Simulate the disabled atribute, but still pass the values */
        .setupToolDetailsView{
            background:rgb(232,232,232);
        }        
        
        .disablewithpointer{
            background:lightgrey;
            /* border: solid red 1px; */
        }    
        
        /* Style tab links */
        .tablink {
          float: left;
          border: 1px solid gray;
          outline: none;
          cursor: pointer;
          padding: 5px 5px;
          font-size: 11px;
          width: 15%;
        }
        .tablink:hover {
          background-color: #777;
        }
        /* Style the tab content (and add height:100% for full page content) */
        .tabcontent {
          border: 1px solid gray;
          padding: 5px 5px;
        }
        .childtablink {
          float: left;
          border-left: 1px solid gray;
          border-right: 1px solid gray;
          border-top: 1px solid gray;
          border-bottom: 2px solid forestgreen;
          outline: none;
          cursor: pointer;
          padding: 5px 5px;
          font-size: 11px;
          width: 14.286%;
        }
        .childtablinkblack {
          color:black;
          font-size: 8px;
        }
        .childtablinkred {
          color:red;
          font-size: 8px;
        }
        .childtablinkgreen {
          color:green;
          font-size: 8px;
        }
        .childtablink:hover {
          background-color: #777;
        }
        .childtabcontent {
          border-left: 2px solid forestgreen;
          border-right: 2px solid forestgreen;
          border-top: none;
          border-bottom: 2px solid forestgreen;
          text-align: left;
        }
        /*----------------------------------------------
        CSS settings for HTML div Exact Center
        ------------------------------------------------*/
        #showSelectStock {
            align-items: center;
            width:100%;
            height:100%;
            top:0;
            left:0;
            position:fixed;
            background-color: rgba(49, 49, 49, .95);
            overflow:hidden;
            display: none;
        }
        #showSelectStockBackgroundDiv {
            background-color: rgba(255, 255, 255, 1); 
            overflow-y: scroll; 
            top: 3%;
            left: 4%;
            right: 4%;
            width: 90%; 
            height: 95%; 
            padding: 5px; 
            margin: 0 auto;
            position:absolute;
        }
        #closeSelectStockBtn:hover {
            float:top;
            display:inline-block;
            background-color: rgba(60, 108, 155, 1);
        }    
        #closeSelectStockDiv {
            position: fixed;
            left: 95%;
            top: 48%;
            float:right;
            display:inline-block;
            padding:2px 5px;
            background-color: rgba(49, 49, 49, 0);
        }   
        /*----------------------------------------------
        CSS settings for showing tools
        ------------------------------------------------*/
        .machineNameCell
        {
            text-align: left;
            width: 7%;
        }
        .nameCell, assignedToolsNameCell
        {
            text-align: center;
        }
        .assignedToolsPositionCell
        {
            text-align: center;
            width: 3%;
        }
        .toolsDiameterCell, .assignedToolsDiameterCell
        {
            width: 7%;
            text-align: center;
        }
        .toolsCuttingLengthCell, .assignedToolsCuttingLengthCell
        {
            width: 7%;
            text-align: center;
        }
        .toolsCornerRadiusCell, .assignedToolsCornerRadiusCell
        {
            width: 7%;
            text-align: center;
        }
        .toolsAngleCell, .assignedToolsAngleCell
        {
            width: 7%;
            text-align: center;
        }
        .toolsFluteNumberCell, .assignedToolsFluteNumberCell
        {
            width: 4%;
            text-align: center;
        }
        .toolsTypeCell, .assignedToolsTypeCell, .brandCell, .pnCell
        {
            width: 10%;
            text-align: center;
        }
        .assignedToolsExposedLengthCell
        {
            width: 9%;
            text-align: center;
        }
        .assignedToolsExposedLengthCellYellow
        {
            width: 9%;
            text-align: center;
        }
        .toolUpdateCell
        {
            width: 5%;
            text-align: center;
        }
        .suggestedBackground {
            background:repeating-linear-gradient(
                45deg,
                rgba(77, 77, 77, .5),
                rgba(77, 77, 77, .5) 10px,
                rgba(230, 230, 0, .5) 10px,
                rgba(230, 230, 0, .5) 20px
            );
        }
        .commonToolBackground {
            background:repeating-linear-gradient(
                45deg,
                rgba(204, 0, 0, .5),
                rgba(204, 0, 0, .5) 10px,
                rgba(77, 77, 77, .5) 10px,
                rgba(77, 77, 77, .5) 20px
            );
        }
        #showAllTools, #showAllAssignedTools {
            align-items: center;
            width:100%;
            height:100%;
            top:0;
            left:0;
            display:none;
            position:fixed;
            background-color: rgba(49, 49, 49, .95);
            overflow:hidden;
        }
        
        #showAllToolsBackground, #showAllAssignedToolsBackground {
            background-color: rgba(255, 255, 255, 1); 
            overflow-y: scroll; 
            top: 4%;
            left: 7%;
            right: 7%;
            width: 85%; 
            height: 90%; 
            padding: 10px; 
            margin: 0 auto;
            position:absolute;
        }
        #closeNewBtn:hover, #closeAssignedBtn:hover, #chooseAssignedBtn:hover {
            background-color: rgba(60, 108, 155, 1);
        }    
        #closeDiv, #closeAssignedToolsDiv {
            position: fixed;
            left: 95%;
            top: 48%;
            float:right;
            display:inline-block;
            padding:2px 5px;
            background-color: rgba(49, 49, 49, 0);
        }   
        /*----------------------------------------------
        CSS settings hovering the update button
        ------------------------------------------------*/
        #formSubmit:hover {
            float:right;
            display:inline-block;
            padding:2px 2px;
            background-color: rgba(60, 108, 155, 1);
        }    
        #updateDiv {
            position: sticky;
            left: 50%;
            top: 45%;
            float:right;
            display:inline-block;
            padding:0px 777px;
            clear: right;
            background-color: rgba(49, 49, 49, 0);
            pointer-events: none;
        }   
        /*----------------------------------------------
        CSS settings for the users dialog
        ------------------------------------------------*/
        #waitDialog, #addChildDialog, deleteChildDialog, #addStickyNote, #copyBlankRequest, #moveRoutingNode{
            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(0, 0, 0, 0) 10px,
                rgba(0, 0, 0, 0) 20px
            );
        }
        /*----------------------------------------------
        CSS settings for status history
        ------------------------------------------------*/
        .historyCurrentCell
        {
            width: 6%;
            text-align: center;
        }
        .historyStatusCell
        {
            width: 16%;
            text-align: center;
        }
        .historyUserCell
        {
            width: 12%;
            text-align: center;
        }
        .historyDateCell
        {
            width: 18%;
            text-align: center;
        }
        
    </style>
    <script type="text/javascript">
        $(function() {
            var copyHelper = null;
            var allowMove = false;

            $('.sourceList').sortable({
              connectWith: '.destinationList',
              placeholder: copyHelper,
              forcePlaceholderSize: true,
              items: "li:not(.ui-state-disabled)", 
              opacity: 0.5,
              helper: function(e,li) {
                  // Create the copy helper
                  copyHelper= li.clone().insertAfter(li);
                  
                  // Return a clone of the element
                  return li.clone();
              },
              start: function(e,ui) {
                  // Init that the sortable source object was not received in the correct container
                  allowMove=false;
              },
              receive: function(e,ui) {
                  // set that this has NOT been received by the correct container. This container should NOT receive anything.
                  allowMove=false;
              },
              stop: function(e,ui) {
                  // Get rid of the helper now that we are done
                  copyHelper && copyHelper.remove();

                  // Determine if the source object has been received by the main container
                  if (allowMove===false){
                      // Cancel the move since it is being dropped incorrectly
                      $(this).sortable('cancel');
                  }
                  else {
                    // Allow the expand anchors to be seen
                    ui.item[0].querySelector('#deleteLI').style.display = "block";
                    ui.item[0].querySelector('#expandLI').style.display = "block";
                    ui.item[0].querySelector('#moveThisOne').style.display = "none";
                    
                    // Add the appropriate class to this element
                    ui.item[0].classList.add("DroppedViableStatus");
                    
                    // Since we dropped a status node, then we can reset back.  Show the button.
                    div_show("loadSavedTrunk");
                  }
                  
                  // Reset the source received flag
                  allowMove = false;
              }
            });

            $('.destinationList').sortable({
              connectWith: '.sourceList',
              items: "li:not(.ui-state-disabled)", 
              start: function(e,ui) {
                  // Set that I am starting to sort the destination sortable
                  allowMove=true;
              },
              receive: function(e,ui) {
                  // set that this has been received by the correct container
                  allowMove=true;
                
                  // Clear the helper
                  copyHelper= null;
              },
              stop: function(e,ui) {
                  // Determine if this is within my own container
                  if  (!allowMove){
                    // This sortable should not be dropping anything, so cancel the move
                      $(this).sortable('cancel');
                  }
              }
            });
        })        
        var _isDirty = false;
        var sessionID = "<?php echo session_id(); ?>";
        var subTaskIDStickyNote = -1;
        var deleteTaskID=-1;
        var previousToOutsideServicesValue="";
        var copyBlankID = -1;

        function getWaitDialog(){
            // Open the appropriate dialog
            $( "#waitDialog" ).dialog( "open" );
        }
        
        function getAddChildDialog(){
            // Open the appropriate dialog
            $( "#addChildDialog" ).dialog( "open" );
        }
        
        function getDeleteChildDialog(taskID=-1){
            // Set whatever task ID they passed in
            deleteTaskID=taskID;
            
            // Open the appropriate dialog
            $( "#deleteChildDialog" ).dialog( "open" );
        }
        
        function recalculateToolsForTask(taskNumber=null, machineID=null, sessionID=null)
        {
            // set the return variable 
            var returnValue = false;

            // Determine if there is a task ID
            if (taskNumber==null){
                // Let the user know there is something wrong
                alert ("Cannot modify a null task.  Try again.");
            }
            // Determine if there is a machine ID
            else if (machineID==null || machineID==-1){
                // Let the user know there is something wrong
                alert ("Cannot modify a task to machine that is not on a machine.  Try again.");
            }
            else {
                // Setup the parameters to pass to PHP
                var params = {
                    "machineID"      : machineID,
                    "taskID"         : taskNumber, 
                    "sessionID"      : sessionID
                };

                // Create the string containing the PHP file to use
                var url = "php_only_scripts/jquery_only/recalculate_machining_task_tools.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 recalculate
                        if (data.includes("ABORT")){
                            // 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());

                        // Return a failed result
                        returnValue = false;
                    }
                    else {
                        // If there is NO message coming back, then we are good
                        returnValue = true;
                    }
                })
                .fail(function(data){   
                    // Log any errors to the console
                    console.log(data);

                    // Return a failed result
                    returnValue = false;
                }); 
            }

            // return what we got
            return returnValue;
        }    

        function checkform(inTaskNumber, hasChildren)
        {
            // set the return variable 
            var returnValue = false;

            // Check first and foremost if the session is good
            if (checkForSessionChange(sessionID, true)){
                // attempt to make the task number a number
                var taskNumber = parseInt(inParentTaskNumber, 10);

                // Do not need to do these checks if this is a parent with children
                if (hasChildren!==1){
                    // First determine if ANYTHING is changing
                    if (document.getElementById("oldMachineTaskOrder").value!==document.getElementById("machineTaskOrder").value ||
                        document.getElementById("oldMachineID").value!==document.getElementById("machineID").value ||
                        document.getElementById("oldStatusID").value!==document.getElementById("status").value){
                        // Setup the parameters to pass to PHP
                        var params = {
                            "indexBefore"   : document.getElementById("oldMachineTaskOrder").value,
                            "indexAfter"    : document.getElementById("machineTaskOrder").value,
                            "machineBefore" : document.getElementById("oldMachineID").value,
                            "machineAfter"  : document.getElementById("machineID").value,
                            "statusBefore"  : document.getElementById("oldStatusID").value,
                            "statusAfter"   : document.getElementById("status").value,
                            "taskID"        : taskNumber
                        };

                        // Create the string containing the PHP file to use
                        var url = "php_only_scripts/jquery_only/check_to_allow_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")){
                                    // 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());

                                // Return a failed result
                                returnValue = false;
                            }
                            else {
                                // If there is NO message coming back, then we can update
                                returnValue = true;
                            }
                        })
                        .fail(function(data){   
                            // Log any errors to the console
                            console.log(data);

                            // Return a failed result
                            returnValue = false;
                        }); 
                    }
                    else {
                        // No changes on this one, so validation is successful
                        returnValue = true;
                    }

                    // Determine if we need to do this
                    if (returnValue){
                        // Now try to check the tools are not duplicated
                        returnValue = checkUniqueToolPositions();
                    }

                    // Determine if we need to do this
                    if (returnValue){
                        // Now try to check there are no tools that are the same
                        returnValue = hasUniqueTools();
                    }

                    // Determine if we need to do this
                    if (returnValue){
                        // Now try to check if any setups have the same order number
                        returnValue = checkUniqueSetupOrder();
                    }

                    // Determine if we need to do this
                    if (returnValue){
                        // Now try to check race condition
                        returnValue = checkRaceCondition(inParentTaskNumber, startServerTime);
                    }
                }
                else {
                    // set the return variable to success 
                    returnValue = true;
                }
            }
            
            // return what we got
            return returnValue;
        }    
    
        function checkRaceCondition(inTaskNumber, inStartDate)
        {
            // set the return variable 
            var returnValue = false;

            // attempt to make the task number a number
            var taskNumber = parseInt(inTaskNumber, 10);
            
            // Setup the parameters to pass to PHP
            var params = {
                "updateStartTime"  : inStartDate,
                "taskID"           : taskNumber
            };

            // Create the string containing the PHP file to use
            var url = "php_only_scripts/jquery_only/check_race_condition.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 for failure
                    if (data.includes("ABORT")){
                        // 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());

                    // Return a failed result
                    returnValue = false;
                }
                else {
                    // If there is a true coing back, then we are GTG
                    returnValue = true;
                }
            })
            .fail(function(data){   
                // Log any errors to the console
                console.log(data);

                // Return a failed result
                returnValue = false;
            }); 
            
            // return what we got
            return returnValue;
        }    

        function importMachiningTasks(inParentTaskNumber, inTaskToCopy)
        {
            // set the return variable 
            var returnValue = false;

            // Check first and foremost if the session is good
            if (checkForSessionChange(sessionID, true)){
                // attempt to make the parent task number a number
                var parentTaskNumber = parseInt(inParentTaskNumber, 10);

                // attempt to make the copy task number a number
                var copyTaskNumber = parseInt(inTaskToCopy, 10);

                // Setup the parameters to pass to PHP
                var params = {
                    "sessionID"         :  sessionID,
                    "parentTaskNumber"  :  parentTaskNumber,
                    "copyTaskNumber"    :  copyTaskNumber
                };

                // Create the string containing the PHP file to use
                var url = "php_only_scripts/jquery_only/import_machining_tasks.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){
                    // Check to see if there is a reason NOT to allow the move
                    if (data.includes("ABORT COPY")){
                        // 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());

                        // Return a failed result
                        returnValue = false;
                    }
                    else {
                        // Set the children as the returned value for now
                        var childrenTasksHTML = data.trim();
                        
                        // Check to see if there is a reason NOT to allow the move
                        if (childrenTasksHTML.includes("INFORMATIONAL MESSAGE")){
                            // Split the string on the double percentage and then 
                            // again on the double colon to get the info message
                            var infoMessage=(childrenTasksHTML.split("%%")[1]).split("::")[1];

                            // Now set the children as the first part of the first split
                            childrenTasksHTML=childrenTasksHTML.split("%%")[0];

                            // Give an alert popup of the informational message
                            alert(infoMessage);
                        }
                        
                        // If there is no error text, then we must have the new sub-tasks
                        returnValue = true;
                        
                        // Check to see if there is a reason NOT to allow the move
                        if (childrenTasksHTML.includes("FULL REFRESH")){
                            // Split the string on the double colon
                            var infoStrings=childrenTasksHTML.split("::");

                            // Give an alert popup of what is happening
                            alert(infoStrings[1]);

                            // Refresh the page
                            location.reload(true);
                        }
                        else {
                            // Replace the subtasks with the HTML returned.
                            document.getElementById("childrenTasks").innerHtml=childrenTasksHTML;
                        }
                    }
                    
                    // Close the dialog
                    $("#waitDialog").dialog( "close" );
                })
                .fail(function(data){   
                    // Log any errors to the console
                    console.log(data);

                    // Return a failed result
                    returnValue = false;
                }); 
            }
            
            // return what we got
            return returnValue;
        }    
    
        function cleanTask(inUpdateTaskNumber, withSubtaskDelete=0)
        {
            // set the return variable 
            var returnValue = false;

            // Check first and foremost if the session is good
            if (checkForSessionChange(sessionID, true)){
                // attempt to make the parent task number a number
                var updateTaskNumber = parseInt(inUpdateTaskNumber, 10);

                // Setup the parameters to pass to PHP
                var params = {
                    "sessionID"          :  sessionID,
                    "updateTaskNumber"   :  updateTaskNumber, 
                    "withSubtaskDelete"  :  withSubtaskDelete
                };

                // Create the string containing the PHP file to use
                var url = "php_only_scripts/jquery_only/surface_clean_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){
                    // Check to see if there is a reason NOT to allow the move
                    if (data.includes("ABORT CLEAN")){
                        // 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());

                        // Return a failed result
                        returnValue = false;
                    }
                    else if (data.includes("FULL REFRESH")){
                        // Split the string on the double colon
                        var infoStrings=data.trim().split("::");

                        // Give an alert popup of what is happening
                        alert(infoStrings[1]);
                        
                        // Refresh the page
                        location.reload(true);

                        // Return a good result
                        returnValue = true;
                    }
                    else {
                        // Determine if they deleted a subtask
                        if (withSubtaskDelete===1){
                            // Set the children div to have the return values
                            document.getElementById("childrenTasks").innerHtml=data.trim();
                        }
                        
                        // If there is no error text, then we must have the new sub-tasks
                        returnValue = true;
                    }
                })
                .fail(function(data){   
                    // Log any errors to the console
                    console.log(data);

                    // Return a failed result
                    returnValue = false;
                }); 
            }
            
            // return what we got
            return returnValue;
        }    
    
        function reenableCmbBoxes(){
            // Get the combo boxes and reenable them
            document.getElementById("assignedTo").disabled = false;
        }
    
        function displayCorrectCompanyEmployees() {
            // Starte the inner HTML with nobody
            var innerHtml='<option value="-1" selected>Nobody</option>';
            
            // get the companies combo now by ID
            var ctrlCompanies = document.getElementById('company');
            
            // Set a blank variable for the company name we are looking at
            var companyName='';
            
            // Determine if this is hidden or if this is a combo box
            if (ctrlCompanies.type==="hidden"){
                // This is the selected one
                selectedCompanyID = ctrlCompanies.value;
                
                // Set the company name to be the text box
                companyName=document.getElementById('companyName').value;
            }
            else {
                // Loop through to get the selected value
                var selectedCompanyID="";
                for(i = 0; i < ctrlCompanies.length; i++) {
                    // Determine if it is the selected one 
                    if (ctrlCompanies[i].selected) {
                        // This is the selected one
                        selectedCompanyID = ctrlCompanies.value;
                
                        // Set the company name to be the text box
                        companyName=ctrlCompanies[i].text;
                    }
                }
            }
            
            // Determine if the SU company is defined
            if (typeof(companies["1"]) !== 'undefined' && 
                companies["1"] !== null) {
                // Add the SU company group
                innerHtml = innerHtml + '<optgroup label="Evolve Engineering & Software">';
                        
                // Loop through the values in super company's array
                var suCompanyEmployees = companies["1"].employees;
                for(i = 0; i < suCompanyEmployees.length; i++) {
                    // add this option
                    innerHtml = innerHtml + '<option class="EmployeeOption" value="' + suCompanyEmployees[i].UserID + '">' + suCompanyEmployees[i].UserName + ' (' + suCompanyEmployees[i].FirstName + ' ' + suCompanyEmployees[i].LastName + ')</option>';
                }
            }
            
            // Determine if the selected company is NOT the SU company
            if (selectedCompanyID!=="1"){
                // Determine if there are any employees in this array for this company
                if (typeof(companies[selectedCompanyID.toString()]) !== 'undefined' && 
                    companies[selectedCompanyID.toString()] !== null){
                    // Add the SU company group
                    innerHtml = innerHtml + '<optgroup label="' + companyName  + '">';

                    // Loop through the values in selected company's array
                    var selectedCompanyEmployees = companies[selectedCompanyID.toString()].employees;
                    for(i = 0; i < selectedCompanyEmployees.length; i++) {
                        innerHtml = innerHtml + '<option value="' + selectedCompanyEmployees[i].UserID + '">' + selectedCompanyEmployees[i].UserName + ' (' + selectedCompanyEmployees[i].FirstName + ' ' + selectedCompanyEmployees[i].LastName + ')</option>';
                    }
                }
            }

            // get the employees task assigned to combo now by ID
            var cmbTaskEmployees = document.getElementById('assignedTo');

            // Determine if the task assigned to combo box exists
            if (typeof(cmbTaskEmployees) !== 'undefined' && cmbTaskEmployees !== null){
                cmbTaskEmployees.innerHTML=innerHtml;
            }

            // get the children assigned to combo box
            var cmbTaskEmployeesForChildren = document.getElementById('childrenAssignedTo');

            // Determine if the task assigned to combo box exists
            if (typeof(cmbTaskEmployeesForChildren) !== 'undefined' && 
                cmbTaskEmployeesForChildren !== null && 
                cmbTaskEmployeesForChildren.type !== "hidden"){
                cmbTaskEmployeesForChildren.innerHTML=innerHtml;
            }
        } 
        
        function addStickyNoteDialog(taskID){
            // Set the global variable to this task ID passed in
            subTaskIDStickyNote=taskID;
            
            // Open the appropriate dialog
            $( "#addStickyNote" ).dialog( "open" );
        }
        
        function copyBlankRequestDialog(blankID){
            // Set the global variable to this blank ID passed in
            copyBlankID=blankID;
            
            // Open the appropriate dialog
            $( "#copyBlankRequest" ).dialog( "open" );
        }
        
        function outsideServiceCheck(selectedText){
            // Determine if we have a value for the text in the combo box and 
            // if the value is one of the two states that should show the vendor
            // Combobox.
            if (selectedText!==null && 
                (selectedText.trim()==="To Outside Services" ||
                 selectedText.trim()==="Outside Services")){
                // Show the vendors
                div_show('vendorCell');
                
                // Determine if the previous state was NOT one of the two
                if (previousToOutsideServicesValue!=="To Outside Services" &&
                    previousToOutsideServicesValue!=="Outside Services"){
                    // Change the hidden element to be nothing
                    document.getElementById('outsideServiceVendorID').value=-1;

                    // Change the combo box to be nothing
                    document.getElementById('vendor').value=-1;
                }
            }
            else {
                // Hide the vendors
                div_hide('vendorCell');
                
                // Change the hidden element to be nothing
                document.getElementById('outsideServiceVendorID').value=-1;

                // Change the combo box to be nothing
                document.getElementById('vendor').value=-1;
            }
        }
        
        function intoProgrammingServiceCheck(selectedText, hasFeedback, copiedFromTID){
            // Determine if we have a value for the text in the combo box and 
            // if the value is into programming.
            if (hasFeedback!==null && hasFeedback===1 &&
                copiedFromTID!==null && copiedFromTID>0 &&
                selectedText!==null && selectedText.trim()==="Programming"){
                // Inform the programmer
                alert("This task was copied from Task ID (" + copiedFromTID + ").  That task has feedback notes. Please ensure these are reviewed before programming the task.");
            }
            else if (hasFeedback!==null && hasFeedback===1 &&
                copiedFromTID!==null && copiedFromTID>0 &&
                selectedText!==null && 
                (selectedText.trim()==="Machining Queue" || selectedText.trim()==="Machining")){
                // Inform the programmer
                alert("This task was copied from Task ID (" + copiedFromTID + "). That task has feedback notes.  This is the last time for you to check the copied from task's feedback notes before this copied task goes on to machining.");
            }
        }
        
        document.addEventListener('DOMContentLoaded', function() {
            // Change the employees displayed in the combo box depending on the company
            displayCorrectCompanyEmployees();

            // Set the value of the assigned to to be what the original task ID is
            document.getElementById('assignedTo').value=originalTaskAssignedToID;

            // Add any employee combo boxes that need to be added
            addEmployeesToCurrentSetups();

            // Setup the programmers combobox list
            var programmerDiv = document.getElementById('programmerDiv');
            var programCheckedByDiv = document.getElementById('programCheckedByDiv');
            programmerDiv.innerHTML = getSUCompanyEmployeesAsSelectOptions("programmer", "");
            programCheckedByDiv.innerHTML = getSUCompanyEmployeesAsSelectOptions("programCheckedBy", "");
            
            // Set the value of the programmers combo boxes
            document.getElementById('programmer').value=originalProgrammerID;
            document.getElementById('programCheckedBy').value=originalProgramCheckedByID;
            
            // Activate the general info tab.  TODO: Determine why this is happening.
            document.getElementById("defaultOpen").click();
            
        }, false);

        $(document).ready(function(){
            $(".suggestStock").click(function(){
                getStock(this.name, 'showSelectStockBackgroundDiv', sessionID);
            }); 

            $(':input').change(function () {
                // Determine if this one has a class of non form
                if (!this.classList.contains("notinput")){
                    // It is dirty
                    _isDirty = true;
                }
            });

            // Disable or enable according to the current machine info
            enableOrderControl(document.getElementById("machineID").value);
        });    
        
        $( function() {
            $( "#waitDialog" ).dialog({
                closeOnEscape: true,
                autoOpen: false,
                show: {
                  effect: "pop",
                  duration: 1000
                },
                hide: {
                  effect: "explode",
                  duration: 1000
                },
                width: '400px',
                modal: true,
                buttons: {
                  "Ok": function() {
                      // Determine if there is even a value in the task to copy 
                      if (document.getElementById('copyTaskID').value!==""){
                          // Get the main task ID
                          var taskID=document.getElementById('taskID').value;
                          
                          // Get information about if we are currently a known parent
                          var isParent = (document.getElementById("hasChildren").value==="1")?true:false;
                          
                          // Attempt to add the child and get the success
                          var importSuccess = importMachiningTasks(taskID, document.getElementById('copyTaskID').value);
                          
                          // Check the success of copying the child(ren) as well as if it is currently a parent
                          if (importSuccess &&
                              isParent){
                              // Reload the element
                              $( "#childrenTasks" ).load(window.location.href + " #childrenTasks" );            
                          }
                          else {
                              // Now clean the new parent
                              cleanTask(taskID);
                              
                              // Reload the whole page for this one instead of just the children
                              window.location.reload(true);
                          }
                      }
                      else {
                          // let the user know of the failure
                          alert("SubTasks were NOT added because no value was entered for the TID to copy.");
                      }

                      // Close this dialog
                      $( this ).dialog( "close" );
                  },
                  Cancel: function() {
                      // Just close this dialog
                      $( this ).dialog( "close" );
                  }
                }
            });
        } );  
        
        $( function() {
            $( "#addChildDialog" ).dialog({
                closeOnEscape: true,
                autoOpen: false,
                show: {
                  effect: "pop",
                  duration: 1000
                },
                hide: {
                  effect: "explode",
                  duration: 1000
                },
                width: '400px',
                modal: true,
                buttons: {
                  "Ok": function() {
                      // Init variables
                      var success=false;
                      
                      // Get the main task ID
                      var taskID=document.getElementById('taskID').value;
                      
                      // Attempt to clean the parent task
                      success = cleanTask(taskID);
                      
                      // Check for success before submission
                      if (success){
                          // Set the redirect now that we know we are good
                          document.getElementById('redirectTo').value='addTask.php?parentTaskId=' + document.getElementById('taskID').value + '&updateTaskID=-1&cs=' + document.getElementById('company').value + '&ts=' + document.getElementById('taskType').value;

                          // Submit the form
                          document.getElementById("updateTask").submit();
                      }
                      else {
                          // let the user know of the failure
                          alert("SubTasks were NOT added because this task could not be modified to be a parent.");
                      }

                      // Close this dialog
                      $( this ).dialog( "close" );
                  },
                  Cancel: function() {
                      // Just close this dialog
                      $( this ).dialog( "close" );
                  }
                }
            });
        } );  
        
        $( function() {
            $( "#deleteChildDialog" ).dialog({
                closeOnEscape: true,
                autoOpen: false,
                show: {
                  effect: "pop",
                  duration: 1000
                },
                hide: {
                  effect: "explode",
                  duration: 1000
                },
                width: '400px',
                modal: true,
                buttons: {
                  "Ok": function() {
                      // Attempt to delete the child task
                      success = cleanTask(deleteTaskID, 1);
                      
                      // Check for success before submission
                      if (success){
                          // Reload the element
                          $( "#childrenTasks" ).load(window.location.href + " #childrenTasks" );            
                      }
                      else {
                          // let the user know of the failure
                          alert("The task was not deleted.");
                      }

                      // Close this dialog
                      $( this ).dialog( "close" );
                  },
                  Cancel: function() {
                      // Just 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,
                buttons: {
                  "Choose": function() {
                        // Attempt to move it to the queue
                        if (addStickyNote(sessionID, subTaskIDStickyNote, "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("");
                  }
                }
            });
        }); 
        
        $( function() {
            $( "#copyBlankRequest" ).dialog({
                autoOpen: false,
                show: {
                  effect: "pop",
                  duration: 1000
                },
                hide: {
                  effect: "explode",
                  duration: 1000
                },
                width: 'auto',
                modal: true,
                buttons: {
                  "Copy": function() {
                        var blankQuantity = document.getElementById("blankQuantity").value;
                        var addedBlankReason = document.getElementById("addedBlankReason").value;
                        var blankRushed = document.getElementById("blankRushed");

                        // Determine if the quantity is a valid number
                        if (isNaN(blankQuantity) || blankQuantity<1){
                            // let them know with an alert
                            alert("The quantity is not an appropriate value.  Try again");
                            
                            // Reset the quantity
                            $( "#blankQuantity" ).val("").change();
                        }
                        else if(addedBlankReason==null || addedBlankReason==""){
                            // let them know with an alert
                            alert("A reason must be entered for creating duplicates of this blank.  Try again");
                        }
                        else {
                            // Attempt to move it to the queue
                            if (copyBlank(sessionID, copyBlankID, blankQuantity, addedBlankReason, blankRushed.checked)){
                                // Close this dialog
                                $( this ).dialog( "close" );

                                // Reset the quantity
                                $( "#blankQuantity" ).val("").change();

                                // Clear the reason
                                $( "#addedBlankReason" ).val("");

                                // Uncheck the rushed field
                                $('#blankRushed').prop('checked', false);

                                // 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("");
                  }
                }
            });
        });    
        
        $( function() {
            $( "#moveRoutingNode" ).dialog({
                autoOpen: false,
                show: {
                  effect: "pop",
                  duration: 300
                },
                hide: {
                  effect: "explode",
                  duration: 300
                },
                width: 'auto',
                modal: true,
                buttons: {
                  "Move": function() {
                        // Determine if the status to go to is a positive status
                        if ($( "#routeStatusID" ).val()>0){
                            // Get any notes that they want to say about the current state
                            var completionFeedbackNotesElement = $( "#completionFeedbackNotes" );

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

                            // Set the status
                            $("#status").val($( "#routeStatusID" ).val());
                        }
                        
                        // Do some manipulation of the form depending on the status value
                        prefillOrderControl($("#status option:selected").text()); 
                        outsideServiceCheck($("#status option:selected").text()); 
                        intoProgrammingServiceCheck($("#status option:selected").text(), copiedFromHasFeedback, copiedFromTaskID);
                        
                        // Click the form submit button
                        $("#formSubmit").click();
                        
                        // Determine if it can move into machining and if the status to go to is a positive status
                        if (!wantsFirstPositionOnMachineWithMachiningTask && $( "#routeStatusID" ).val()>0){
                            // Lets Move it
                            moveRouteAsNecessary($( "#routeTID" ).val(), $( "#routeCurrentTaskStatusRoutingNodeID" ).val(), completionFeedbackNotes, routeGoToInfoStrings);
                        }
                        else {
                            // Reset the flag
                            wantsFirstPositionOnMachineWithMachiningTask=false;

                            // Reset the status
                            $("#status").val($( "#oldStatusID" ).val());
                        }
                        
                        // Clear values
                        $( "#routeStatusID" ).val(0);
                        $( "#moveRoutingHeader" ).val("");
                        $( "#routeNodeEstimatedTime" ).val("");
                        $( "#routeNodeActualTime" ).val("");
                        $( "#completionFeedbackNotes" ).val("");
                        $( "#nextStatusNotes" ).val("");
                            
                        // Close this dialog
                        $( this ).dialog( "close" );
                  },
                  Cancel: function() {
                        // Close this dialog
                        $( this ).dialog( "close" );
                       
                        // Clear the values used
                        $( "#routeStatusID" ).val(0);
                        $( "#moveRoutingHeader" ).val("");
                        $( "#routeNodeEstimatedTime" ).val("");
                        $( "#routeNodeActualTime" ).val("");
                        $( "#completionFeedbackNotes" ).val("");
                        $( "#nextStatusNotes" ).val("");
                        
                        // Change back to the old status since they canceled
                        var oldStatusID=$("#oldStatusID").val();
                        $("#status").val(oldStatusID);
                  }
                }
            });
        });    
    </script>
</head>

<body class="thrColElsHdr">
    <div id="container">

    <!-- start of banner wrap --->

    <div id="topContent">

    <div>
       <div class="MenuBarHorizontal" id="navBar">  
        </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 - Update Task</div>
    <div class="breadcrumb"> <a href="../index.html"> Home </a> > <a href="tasks.php"> Task Management System </a> > <a href=
          "<?php echo ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on'?"https" : "http") . "://" . $_SERVER['HTTP_HOST'] .  $_SERVER['REQUEST_URI']); ?>"> Update Task </a></div>
    <?php
        // Determine if they are GTG
        if ($gtg){
            // Show just the info for the task
            echo getTask($db, $userRow, $updateTaskID, $parentTaskNumber, $fromWhatCompany, $fromWhatType, $fromWhatBaseURL);
        }
        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>');
        }
    ?>       
        
  <!-- end #mainContent -->
  </div>
  
  <!-- 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>

    <div id="showSelectStock">
        <div id="showSelectStockBackgroundDiv">
        </div>
        <button id="closeSelectStockBtn" onclick="div_hide('showSelectStock');">Close</button>
    <!-- Popup Div Ends Here -->
    </div>


    <div id="gCodeTools" style="display:none; text-align: center; vertical-align: middle;">
    </div>

    <div id="showAllTools">
        <div id="showAllToolsBackground">
            <div id="closeDiv">
                <button id="closeNewBtn" onclick="javascript:div_hide('showAllTools');">Close</button>
            </div>        
            <div id="toolsListed" style="text-align: center; vertical-align: middle;">
            </div>
        </div>
    <!-- Popup Div Ends Here -->
    </div>
    
    <div id="showAllAssignedTools">
        <div id="showAllAssignedToolsBackground">
            <div id="closeAssignedToolsDiv">
                <button id="closeAssignedBtn" onclick="javascript:div_hide('showAllAssignedTools')">Close</button>
                <button id="chooseAssignedBtn" onclick="javascript:addChosenTools(); div_hide('showAllAssignedTools')">Choose</button>
            </div>   
            <div id="assignedToolsListed" style="text-align: center; vertical-align: middle;">
            </div>
        </div>
    </div>
    
    <div id="addChildDialog" title="Add SubTask" style="display:none;">
        <p style="text-align:center;">
            This will add a subtask to this task.
            <br><br>
            If this current task is already a machining task, all machining information (blanks, setups, tools, notes, etc) will be deleted from it.
            <br><br>
            This may take a while.
            <br><br>
            Continue?
        </p>
    </div>  
    
    <div id="deleteChildDialog" title="Delete SubTask" style="display:none;">
        <p style="text-align:center;">
            Are you sure that you want to delete this SubTask?
        </p>
    </div>  
    
    <div id="waitDialog" title="Copy SubTasks" style="display:none;">
        <p style="text-align:center;">
            <?php
                // Determine if they are GTG
                if ($hasChildren){
                    // Show the message for children
                    echo ('<input type="hidden" name="hasChildren" id="hasChildren" value="' . $hasChildren . '"/>' .
                          'This will copy subtask(s) or a main machining task from the task ID listed to this task.' .
                          '<br><br>' . 
                          'Depending on the amount of tasks to copy, this may take a while.' .
                          '<br><br>' . 
                          'Continue?');
                }
                else {
                    // Show the message for children
                    echo ('<input type="hidden" name="hasChildren" id="hasChildren" value="' . $hasChildren . '"/>' .
                          'This will copy subtask(s) or a main machining task from the task ID listed to this task.' .
                          '<br><br>' . 
                          'If this current task is already a machining task, all machining information (blanks, setups, tools, notes, etc) will be deleted from it.' . 
                          '<br><br>' . 
                          'If you would like to maintain the machining information in this task, but use this task as a parent, copy this task into itself first. ' . 
                          '<br><br>' . 
                          'Depending on the amount of tasks to copy, this may take a while.' .
                          '<br><br>' . 
                          'Continue?');
                }
            ?>   
        </p>
    </div>  
    
    <div id="addStickyNote" title="Create Sticky Note" style="display:none;">
        <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>            
    <div id="moveRoutingNode" title="Move Routing" style="display:none;">
        <div id="RouteParamsDiv">
            <p style="text-align:center;">
                <label name="moveRoutingHeader" id="moveRoutingHeader" style="color:green;">Move the task routing.</label>
                <br><br>
                <label name="moveRoutingHeader2" id="moveRoutingHeader2" 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="routeTID" id="routeTID" value="' . $hasChildren . '"/>
                <input type="hidden" name="routeStatusID" id="routeStatusID" value="' . $hasChildren . '"/>
                <input type="hidden" name="routeCurrentTaskStatusRoutingNodeID" id="routeCurrentTaskStatusRoutingNodeID" value="' . $hasChildren . '"/>
                <table width="100%" border="0">
                    <tr>
                        <td height="39" align="left" colspan=1>
                            <strong><label for="routeNodeEstimatedTime">Current State Estimated Time:</label></strong>
                            <input type="text" maxlength="25" name="routeNodeEstimatedTime" id="routeNodeEstimatedTime" style="width:40%;" value="" disabled/>
                        </td>
                        <td height="39" align="left" colspan=1>
                            <strong><label for="routeNodeActualTime">Current Calculated Actual Time:</label></strong>
                            <input type="text" maxlength="25" name="routeNodeActualTime" id="routeNodeActualTime" style="width:40%;" value="" disabled/>
                        </td>
                    </tr>
                    <tr>
                        <td height="39" align="left" colspan=2>
                            <strong><label name="completionFeedbackNotesLabel" id="completionFeedbackNotesLabel" for="completionFeedbackNotes">Feedback On Current State:</label></strong><br>
                            <textarea name="completionFeedbackNotes" id="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="nextStatusNotesLabel" id="nextStatusNotesLabel" for="nextStatusNotes">Notes for Next State:</label></strong><br>
                            <textarea name="nextStatusNotes" id="nextStatusNotes" maxlength="2000" style="width: 100%; height: 125px; overflow: auto; resize:none" value="" disabled/></textarea>
                        </td>
                    </tr>
                </table>
            </p>
        </div>
    </div>            
    <div id="copyBlankRequest" title="Copy Blank Request">
        <p style="text-align:center;">
            Add duplicate blanks.
            <br><br>
                    
            <?php
                // Get a hidden div containing the assign to users
                echo createBlankCopyContent($userRow);
            ?>
        </p>
    </div>            
<!-- Popup Div Ends Here -->
</body>
<!--    <script>alert((document.getElementById("hasChildren").value==="1")?true:false);</script>-->
</html>