<?php 
    // continue the session
    session_start();
    
    // Add includes to PHP files that I will need to access
    include 'php_only_scripts/global_after_session.php';
    include 'php_only_scripts/sortArrayProblems.php';
    include 'php_only_scripts/database.php';
    include 'php_only_scripts/presentation.php';
    include 'php_only_scripts/task_presentation.php';
    include 'php_only_scripts/note_presentation.php';
    include 'php_only_scripts/note_inner_presentation.php';
    include 'php_only_scripts/stocklist_presentation.php';
    include 'php_only_scripts/tools_presentation.php';
    include 'php_only_scripts/setup_presentation.php';
    include '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';
    
    // 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'];
    }

    // If there is only one result for a username/password combo, then they are good to go.
    if ($currentUser == null){
        exit;
    }
    elseif (mysqli_num_rows($currentUser)==1){
        // Attempt to get the user row
        $userRow = $currentUser->fetch_assoc();
        
        if ($userRow["UserLevel"]!='SU' &&
            $userRow["UserLevel"]!='EXECUTIVE' &&
            $userRow["UserLevel"]!='MANAGEMENT' && 
            $userRow["UserLevel"]!='MID-MANAGEMENT' ||
            $userRow["AccountStatus"]!='ACTIVE'){
                // redirect to the invalid access page
                echo ('<script>window.location = "invalid_access.php";</script>');
                
                exit;
        }
        
        // Set it to zero
        $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 good to go until they log out
        $gtg = true;

        // 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';

                $parentTaskNumber=htmlspecialchars($_POST['parentTaskNumber'], ENT_QUOTES, 'UTF-8');
                $parentTaskNumber = ($parentTaskNumber==null)?0:$parentTaskNumber;
                
                $companyID=htmlspecialchars($_POST['company'], ENT_QUOTES, 'UTF-8');
                $statusID=htmlspecialchars($_POST['status'], ENT_QUOTES, 'UTF-8');
                $userID=htmlspecialchars($_POST['assignedTo']);
                $secondaryStatusID=htmlspecialchars($_POST['secondaryStatus']);
                $createdBy=$userRow["UserID"];
                $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']:0, 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);
                $isPendingApproval=htmlspecialchars(isset($_POST['isPendingApproval'])?1:0);
                $title=htmlspecialchars($_POST['title'], ENT_QUOTES, 'UTF-8');
                $description=htmlspecialchars($_POST['description'], ENT_QUOTES, 'UTF-8');
                $idealDate=htmlspecialchars($_POST['idealDate'], ENT_QUOTES, 'UTF-8');
                $dueDate=htmlspecialchars($_POST['dueDate'], ENT_QUOTES, 'UTF-8');
                $taskPrice=htmlspecialchars($_POST['taskPrice'], ENT_QUOTES, 'UTF-8');
                $deliverableQuantity=htmlspecialchars($_POST['deliverableQuantity'], ENT_QUOTES, 'UTF-8');
                $totalQuantity=htmlspecialchars($_POST['totalQuantity'], 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"]);
                    
                // If we have attachments, the links will be in this HTML to let user's know
                $attachmentHTML = '';

                // Determine if the value is numeric for price. If not, then set it to null.
                if ($taskPrice == null){
                    // Set it as a string null
                    $taskPrice = 'NULL';
                }
                else if (!is_numeric($taskPrice)){
                    // Set it as a string null
                    $taskPrice = 'NULL';
                }

                // Create a query to get the company information of the new task
                $sql = 'SELECT * FROM companies WHERE CompanyID =  ' . $companyID . ';';

                // Attempt to get back the row
                $company = $db->queryDB($sql, $userRow, "addTask Form occurance 1");

                // Attempt to get the user row
                $companyRow = $company->fetch_assoc();
                    
                // Determine if we are making a child of the parent right now
                if ($parentTaskNumber != 0){
                    // Create the query to update any rows that this sub priority interferes with 
                    $sql = 'SELECT Max(SubPriority) AS MaxSubPriority, Count(*) AS Amount FROM tasks ' .
                           'WHERE ParentID = ' . $parentTaskNumber . ' AND ParentID <> 0;';
                    
                    // Run the query
                    $maxSubTaskPriorityRow = $db->queryDB($sql, $userRow, "addTask Form occurance 2");

                    // Determine if we even have a task to update
                    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 ($subPriority>$maxSubTaskPriorityAssocRow["MaxSubPriority"]){
                            // Set the value to be one more the max priority
                            $subPriority = $maxSubTaskPriorityAssocRow["MaxSubPriority"] + 1;
                        }
                        else {
                            // We have to manipulate all rows that are the same or lower priority 
                            $sql = 'UPDATE tasks t SET t.SubPriority=t.SubPriority+1 ' .
                                   'WHERE t.SubPriority >= ' . $subPriority . ' ' .
                                   'AND t.ParentID = ' . $parentTaskNumber . ';'; 
                            
                            // Attempt to run the query and evaluate the response
                            $db->queryDB($sql, $userRow, "addTask Form occurance 3");
                        }
                    }
                }
                else {
                    // Determine if the order is already completed
                    if ($completed or $closed){
                        // Change the priority to one that will never be reached (hopefully)
                        $priority=99999;
                    }
                    
                    // Determine if we have a priority that made it to be less than 1
                    if ($priority<1){
                        // Set it to the first priority
                        $priority=1;
                    }

                    // Create the query to update any rows that this priority interferes with 
                    $sql = 'UPDATE tasks t SET t.Priority=t.Priority+1 ' .
                           'WHERE t.Priority >= ' . $priority . ' ' .
                           'AND t.TypeID = ' . $typeID . ' ' .
                           'AND t.Priority < 99999 ' .
                           'AND t.CompanyID = ' . $companyID . ';'; 

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

                // Create a query to get see if the old status was the machining status and the machining order
                $sql = 'SELECT IF(' . $statusID . '=s.StatusID, 1, 0) AS IsMachining ' .
                       'FROM status s ' .
                       'WHERE Name = "Machining";';

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

                // Determine if we have one row to look at
                $machiningStatusAssocRow=null;
                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"];

                    // Determine if this task is going into machining.
                    if ($machiningStatusAssocRow["IsMachining"]==1) {
                        // Change the issue date to be now minus the server difference
                        $issuedToMachinesDate = 'NOW()';
                    }
                }
                    
                // Let's create the insert query off of what we have
                $sql='INSERT INTO tasks (';
                if ($companyID!=null) {$sql = $sql . 'CompanyID';}
                $sql = $sql . ', Invoiced, Completed, Closed, CleanUp, Expedite, AllPartsSetup, LastUpdatedByID ';
                if ($statusID!=null) {
                    // Setup the Status as a value to be added
                    $sql = $sql . ', StatusID';

                    // Determine if the status ID is higher than submitted
                    if ($statusID>1){
                        // Change it to not be user deletable
                        $sql=$sql . ', UserDeletable';
                    }
                }
                if ($userID!=null) {$sql = $sql . ', UserID';}
                if ($createdBy!=null) {$sql = $sql . ', CreatedByID';}
                if ($typeID!=null) {$sql = $sql . ', TypeID';}
                if ($secondaryStatusID!=null) {$sql = $sql . ', SecondaryStatusID';}
                if ($fixtureID!=null) {$sql = $sql . ', FixtureToUseID';}
                if ($partHardware!=null) {$sql = $sql . ', PartHardware';}
                if ($priority!=null) {$sql = $sql . ', Priority';}
                if ($subPriority!=null) {$sql = $sql . ', SubPriority';}
                if ($deliverableQuantity!=null) {$sql = $sql . ', DeliverableQuantity';}
                if ($totalQuantity!=null) {$sql = $sql . ', TotalQuantity';}
                if ($title!=null) {$sql = $sql . ', Title';}
                if ($description!=null) {$sql = $sql . ', Entry';}
                if ($dueDate!=null) {$sql = $sql . ', DueDate';}
                if ($issuedToMachinesDate!=null) {$sql = $sql . ', IssuedToMachineDate';}
                if ($idealDate!=null) {$sql = $sql . ', IdealDate';}
                if ($parentTaskNumber!=null) {$sql = $sql . ', ParentID';}
                $sql = $sql . ',IsVacuumClean, IsWashForAnodize, HasAllowableCosmeticDamage, IsTappedPostMachining, ' .
                              'PostMachiningTappingInstructions, IsSandblasted, SandBlastingInstructions, PostMachiningNotes, PostMachiningFeedback ' .
                              ', TaskPrice, ProgrammerID, ProgramCheckedByID, OutsideServiceVendorID';
                $sql=$sql .') SELECT DISTINCT ';
                if ($companyID!=null) {$sql = $sql . $companyID;}
                $sql = $sql . ', ' . $invoiced . ', ' . $completed . ', ' . $closed . 
                              ', ' . $cleanUp . ', ' . $expedite . ', '  . $allPartsSetup . 
                              ', ' . $userRow["UserID"];

                if ($statusID!=null) {
                    $sql = $sql . ', ' . $statusID;

                    // Determine if the status ID is higher than submitted
                    if ($statusID>1){
                        // Change it to not be user deletable
                        $sql=$sql . ', 0';
                    }
                }
                if ($userID!=null) {$sql = $sql . ', ' . $userID;}
                if ($createdBy!=null) {$sql = $sql . ', ' . $createdBy;}
                if ($typeID!=null) {$sql = $sql . ', ' . $typeID;}
                if ($secondaryStatusID!=null) {$sql = $sql . ', ' . $secondaryStatusID;}
                if ($fixtureID!=null) {$sql = $sql . ', ' . $fixtureID;}
                if ($partHardware!=null) {$sql = $sql . ', "' . $partHardware . '"';}
                if ($priority!=null) {$sql = $sql . ', if(MAX(Priority) IS NULL, 1, if(' . $priority . ' > MAX(Priority), MAX(Priority)+1, ' . $priority . '))';}
                if ($subPriority!=null) {$sql = $sql . ', ' . $subPriority;}
                if ($deliverableQuantity!=null) {$sql = $sql . ', ' . $deliverableQuantity;}
                if ($totalQuantity!=null) {$sql = $sql . ', ' . $totalQuantity;}
                if ($title!=null) {$sql = $sql . ', "' . $title . '"';}
                if ($description!=null) {$sql = $sql . ', "' . $description . '"';}
                if ($dueDate!=null) {$sql = $sql . ', "' . $dueDate . '"';}
                if ($issuedToMachinesDate!=null) {$sql = $sql . ', ' . $issuedToMachinesDate;}
                if ($idealDate!=null) {$sql = $sql . ', "' . $idealDate . '"';}
                if ($parentTaskNumber!=null) {$sql = $sql . ', ' . $parentTaskNumber;}
                $sql = $sql . ', ' . $isVacuumClean . ', ' . $isWashForAnodize . ', ' . $hasAllowableCosmeticDamage .
                              ', ' . $isTappedPostMachining . ', "' . $postMachiningTappingInstructions  . '"' .
                              ', ' . $isSandblasted . ', "' . $sandBlastingInstructions . '", "' . $postMachiningNotes  . '"' .
                              ', "' . $postMachiningFeedback . '"' . ', ' . $taskPrice . ', ' . $programmerID . ', ' . $programCheckedByID  .
                              ', ' . $outsideServiceVendorID . ' ';
                $sql=$sql .'FROM tasks ' .
                           'WHERE TypeID=' . $typeID . ' ' .
                           'AND CompanyID=' . $companyID . ' ' .
                           'AND Priority < 99999 ' .
                           'AND Closed<>1 ' .
                           'AND Completed<>1;';

//echo '<script>alert("' . addslashes($sql) . '");</script>';

                // Attempt to run the query and evaluate the response
                if (!$db->queryDB($sql, $userRow, "addTask Form occurance 6")){
                    echo ('<script>alert("Task was NOT added to the database. Please check the data and try again.");</script>');
                    // TODO: How do I want to display a failure to the user?
                    // echo '<font color="red">Task was NOT added to the database. <br> Please check the data and try again.</font>';
                }
                else {
                    // Get the most recent ID (task)
                    $newTaskID = mysqli_insert_id($db->getDBConnection());

                    // Set up what the user posted at first, to be changed with logic.
                    $machineID = $_POST["machineID"];
                    $machineTaskOrder=(isset($_POST['machineTaskOrder'])?$_POST['machineTaskOrder']:$_POST['hiddenMachineTaskOrder']);

                    // 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, "addTask Form occurance 7");
                        $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, "addTask Form occurance 8");
                        }

                        // Create the main query into the tasktomachinelinker table
                        $sql = 'INSERT INTO tasktomachinelinker (MachineID, TaskID, TheOrder, IsWaitingToBeReviewed, IsPendingApproval) ' .
                               'VALUES (' . $machineID . ',' . $newTaskID . ',' . $machineTaskOrder . ', ' . $isWaitingToBeReviewed . 
                                        ', ' . $isPendingApproval  . ');';

                        // Attempt to run the query and evaluate the response
                        $db->queryDB($sql, $userRow, "addTask Form occurance 9");
                    }

                    // Set the current status of the parent to one that we do not know.
                    $parentStatusIDAfter = -1;

                    // Create the visualized task orientation as though this IS the parent
                    $firstFour = $newTaskID;
                    $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($newTaskID,4,"0",STR_PAD_LEFT);

                        // Create the update query
                        $sql='UPDATE tasks SET LastUpdatedByID=' . $userRow["UserID"] . ', HasChildren=1 WHERE ParentID=0 AND TaskID=' . $parentTaskNumber;

                        // Run the update query
                        $db->queryDB($sql, $userRow, "addTask Form occurance 10");
                        
                        // 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, "addTask Form occurance 11");

                        // 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 parent status is changing
                            if ($parentStatusID != $parentStatusIDAfter){
                                // Create the query to update the parent status
                                $sql =  'UPDATE tasks SET LastUpdatedByID=' . $userRow["UserID"] . 
                                                       ', StatusID=' . $parentStatusIDAfter . 
                                       ' WHERE TaskID = ' . $parentTaskNumber . ';';

                                // Update the parent status andf check that it changed
                                if ($db->queryDB($sql, $userRow, "addTask Form occurance 12")){
                                    // Since successful, notify everyone who wants to know.
                                    // 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.UserID<>' . $userRow["UserID"] . '
                                          AND u.SilenceAllTaskNotifications<>1 
                                          AND u.AccountStatus="Active"
                                          AND u.UserTemplateOnly=0 
                                          AND ((u.CompanyID = ' . $companyID . ') 
                                               OR (u.CompanyID = 1 AND u.SUEmployee=1) 
                                               OR (u.UserID = ' . $userID . '));';
                                    
                                    // Make the query
                                    $usersToNotify = $db->queryDB($sql, $userRow, "addTask Form occurance 13");

                                    // 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"]=="CHILD" && $parentTaskNumber>0) || 
                                                ($userToNotify["NotificationCategory"]=="PARENT" && $parentTaskNumber==0) || 
                                                ($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 and it is a parent
                                                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 a parent task status ' . $messageToType . 
                                                        '<br><br>COMPANY: "' . $companyRow["CompanyName"] . 
                                                        '"<br>Parent Task Title: "' . $parentTitle . 
                                                        '"<br>Parent TID#: ' . $parentTaskNumber . 
                                                        '<a href="https://www.eestms.com/' . getTMSHome() . 
                                                        '/updateTask.php?updateTaskID=' . $parentTaskNumber . 
                                                        '">  (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 ("Status change Made to '" . 
                                                                                    $parentTitle . "' via changing " . 
                                                                                    "child task status for company '" . 
                                                                                    $companyRow["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.");
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // If the redirection is to a child that is being added, then replace the appropriate word in the redirect string.  Get a count of how many replacements.
                    $count=0;
                    $redirectTo = str_replace("TaskIDToReplace", $newTaskID, $redirectTo, $count);
                    
                    // Determine if there are any replacements
                    if ($count==0 && $parentTaskNumber==0){
                        // Change the redirect to be back to the tasks page of the company and type just added.
                        $redirectTo = 'https://www.eestms.com/' . getTMSHome() . '/tasks.php?cs=' . $companyID . '&ts=' . $fromWhatType;
                    }

                    // 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 (' . $newTaskID . ',' . $parentTaskNumber . ',' . $statusID . ',' . $endedDate . 
                                  ',"Task added at this state by ' . $userRow["FirstName"] . ' ' . $userRow["LastName"] . 
                                  '.",' . $userRow["UserID"] . ', 1, ' . $userID . ');';

                    // Attempt to run the query
                    $db->queryDB($sql, $userRow, "addTask Form occurance 14");
                        
                    // Create an array of positions that are greater than zero to be passed between the tool functions
                    $goodPositions = array();

                    // Add any new tools that the user added
                    $duplicatePositions=addNewToolsToDB($db, $newTaskID, $userRow, $parentTaskNumber, $goodPositions);
                    
                    // Add any new tools that the user added
                    $duplicateSetupOrders|=addNewSetupsToDB($db, $userRow, $updateTaskID);
                        
                    // 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>';
                    }

                    // Now I need to determine if this one is a machining task
                    $sql = 'SELECT IF(' . $statusID . '=s.StatusID, 1, 0) AS IsMachining ' .
                           'FROM status s ' .
                           'WHERE Name = "Machining";';

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

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

                        // Determine if it IS going to machining phase
                        if ($machiningStatusAssocRow["IsMachining"] == 1) {
                            // 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 . ';'; 

                            // Run the update query
                            $db->queryDB($sql, $userRow, "updateTask Form occurance 16");
                            
                            // Set the tools for this newly assigned task
                            setTaskToolsAsSuggested($db, $userRow, $newTaskID, $machineID);
                        }
                    }
                            
                    
                        
                    // Add any new blanks that the user added
                    addNewBlanksToDB($db, $userRow, $newTaskID, $parentTaskNumber);
                        
                    // Add any new notes that the user added
                    addNewNotesToDB($db, $userRow, $newTaskID, $userRow["UserID"], "TASK");

                    // Determine if there are new attachment numbers
                    if (isset($_POST['newAttachmentNumbers']) and $_POST['newAttachmentNumbers']!=0){
                        // Get the amount of new addresses 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    = $_FILES['attachmentElement'.$loopNumber]['name']; 
                                $tmpName  = $_FILES['attachmentElement'.$loopNumber]['tmp_name'];
                                $fileSize = $_FILES['attachmentElement'.$loopNumber]['size'];
                                $fileType = $_FILES['attachmentElement'.$loopNumber]['type'];

                                // Determine if the file size is such that the database han handle storing it. The database can handle 4GB (4,294,967,296 Bytes)
                                if ($fileSize < 4294967296){
                                    //process the file
                                    $fp      = fopen($tmpName, 'r');
                                    $content = fread($fp, filesize($tmpName));
                                    $content = addslashes($content);
                                    fclose($fp);

                                    // 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 ($newTaskID, $userID, '$fileType', " .
                                               "'$fname','$fileSize','$content');";

                                        // Attempt to run the query and get the response
                                        if ($db->queryDB($sql, $userRow, "addTask Form occurance 17")){
                                            // Let the user know that upload of this file worked
                                            echo("The file ('" . $fname . "') was uploaded successfully.<br>");
                                                
                                            // 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.<br>");
                                        }
                                    }
                                    else {
                                        // Let the user know that the blob was NOT uploaded.
                                        echo("The file ('" . $fname . "') did not get uploaded because there was no datum.<br>");
                                    }
                                }
                                else {
                                    // Let the user know the file was NOT uploaded
                                    echo("The file ('" . $fname . "') was not uploaded, because it is too large. File must be under 4GB.<br>");
                                }
                            }   
                        }
                        
                        // Determine if there were NO good attachments added
                        if ($numberGoodAttachments<1){
                            // Set the HTML back to nothing
                            $attachmentHTML='';
                        }
                        else {
                            // Set it with the approipriate 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;
                        }
                    }

                    // 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.SilenceAllTaskNotifications<>1 
                              AND u.UserTemplateOnly=0 
                              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;
                    }

                    // Run the query
                    $usersToNotify = $db->queryDB($sql, $userRow, "addTask Form occurance 18");

                    // 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
                            $textMessageToSend='';

                            // 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
                            if ($userToNotify["UserID"]==$userID){
                                // Change it to an assigned to message
                                $messageToType = " that you are ASSIGNED TO.";
                                $subjectToType = "EES ASSIGNED TO Message: ";
                            }

                            // Determine if the user wants to know about new tasks or if they are a user of
                            // the main company and this is assigned to them
                            if ($userToNotify["CompanyID"]==1 &&
                                    $userToNotify["UserID"]==$userID){
                                // Create the message to add for this
                                $textMessageToSend=$userRow["FirstName"] . ' ' . $userRow["LastName"] . 
                                        ' has added a new task' . $messageToType . 
                                        '<br><br>Task Title: "' . $title . '"' .
                                        '<br>TID#: ' . $firstFour . '-' . $lastFour . 
                                        '<a href="https://www.eestms.com/' . getTMSHome() . '/updateTask.php?updateTaskID=' . 
                                        $newTaskID . '&parentTaskId=' . $parentTaskNumber . '">  (Click To View)</a>.';
                            }
                            else if (($userToNotify["NotificationCategory"]=="CHILD" && $parentTaskNumber>0) || 
                                     ($userToNotify["NotificationCategory"]=="PARENT" && $parentTaskNumber==0) || 
                                     ($userToNotify["NotificationCategory"]=="ALL")){
                                // Create the message to add for this
                                $textMessageToSend=$userRow["FirstName"] . ' ' . $userRow["LastName"] . 
                                        ' has added a new task' . $messageToType . 
                                        '<br><br>Task Title: "' . $title . '"' .
                                        '<br>TID#: ' . $firstFour . '-' . $lastFour . 
                                        '<a href="https://www.eestms.com/' . getTMSHome() . '/updateTask.php?updateTaskID=' . 
                                        $newTaskID . '&parentTaskId=' . $parentTaskNumber . '">  (Click To View)</a>.';
                            }
                            else if ($userToNotify["ReceiveAddTaskUpdate"]){
                                // Make sure we got a company
                                if ($company == null){
                                    // Create the message to add for this
                                    $textMessageToSend=$userRow["FirstName"] . ' ' . $userRow["LastName"] . 
                                            ' has added a new task' . $messageToType . 
                                            '<br><br>Task Title: "' . $title . '"' . 
                                            '<br> TID#: ' . $firstFour . '-' . $lastFour . 
                                            '<a href="https://www.eestms.com/' . getTMSHome() . '/updateTask.php?updateTaskID=' . 
                                            $newTaskID . '&parentTaskId=' . $parentTaskNumber . '">     (Click To View)</a>.';
                                }
                                elseif (mysqli_num_rows($currentUser)==1){
                                    // Create the message to add for this
                                    $textMessageToSend=$userRow["FirstName"] . ' ' . $userRow["LastName"] . 
                                            ' has added a new task' . $messageToType . 
                                            '<br><br>COMPANY: "' . $companyRow["CompanyName"] . '"' . 
                                            '<br>Task Title: "' . $title . '"' . 
                                            '<br>TID#: ' . $firstFour . '-' . $lastFour .
                                            '<a href="https://www.eestms.com/' . getTMSHome() . '/updateTask.php?updateTaskID=' . 
                                            $newTaskID . '&parentTaskId=' . $parentTaskNumber . '">  (Click To View)</a>.';
                                }
                            }

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

                                // Create the subject
                                $subject = htmlspecialchars_decode ($subjectToType . "New task '" . $title . 
                                                       "' added for '" . $companyRow["CompanyName"] . "'.");

                                try {
                                    // 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=' . $newTaskID . '&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);

                                    // 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}\""; 

                                        // 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, "addTask Form occurance 20");

                                        // 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";

                                        // 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 is a parent or a child
                if ($parentTaskNumber>0){
                    // 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 - Add 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/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="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>
    <script language="JavaScript" src="scripts/gen_validatorv4.js" type="text/javascript"></script>
    
    <link rel="icon" href="/images/ees_ico.ico"/> 
    <script src="scripts/jquery.min.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="./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">
        #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%;
        }
        .companyCell
        {
            width: 14%;
        }
        .priCell
        {
            width: 4%;
            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
        {
            width: 20%;
            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 */
        .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: 25%;
        }
        .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: 16.66666666%;
        }
        .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;
        }
        .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;
        }   
    </style>
    <script type="text/javascript">
        function reenableCmbBoxes(){
            // Get the combo boxes and reenable them
            document.getElementById("assignedTo").disabled = false;
        }
    
        $(document).ready(function(){
            $(".suggestStock").click(function(){
                getStock(this.name, 'showSelectStockBackgroundDiv');
            });        
        });        
    </script>
</head>

<body class="thrColElsHdr">
<script>var sessionID = "<?php echo session_id(); ?>";</script>

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

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

    <style type="text/css">
        #subTaskDiv{
            display:none;
        }
        .EmployeeOption{
            font-weight:bold;
        }
    </style>
    <script type="text/javascript">
    <!--
    var MenuBar2 = new Spry.Widget.MenuBar("TopNav", {imgDown:"./SpryAssets/SpryMenuBarDownHover.gif", imgRight:"./SpryAssets/SpryMenuBarRightHover.gif"});
    //-->
        function checkform(inTaskNumber, hasChildren)
        {
            // set the return variable 
            var returnValue = false;
            
            // Check first and foremost if the session is good
            if (checkForSessionChange(sessionID, true)){
                // Do not need to do these checks if this is a parent with children
                if (hasChildren!==1){
                    // Setup the parameters to pass to PHP
                    var params = {
                        "indexBefore"   : 99998,
                        "indexAfter"    : document.getElementById("machineTaskOrder").value,
                        "machineBefore" : -1,
                        "machineAfter"  : document.getElementById("machineID").value,
                        "statusBefore"  : -1,
                        "statusAfter"   : document.getElementById("status").value,
                        "taskID"        : -1
                    };

                    // 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;
                    }); 

                    // 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 if any setups have the same order number
                        returnValue = checkUniqueSetupOrder();
                    }
                }
                else {
                    // set the return variable to success 
                    returnValue = true;
                }
            }
            
            // return what we got
            return returnValue;
        }    
    
        function displayCorrectCompanyEmployees() {
            // Starte the inner HTML with nobody
            var innerHtml='<option value="-1" selected>Nobody</option>';
            
            // get the companies combo now by ID
            var cmbCompanies = document.getElementById('company');
            
            // Set a blank variable for the company name we are looking at
            var companyName='';
            
            // Loop through to get the selected value
            var selectedCompanyID="";
            for(i = 0; i < cmbCompanies.length; i++) {
                // Determine if it is the selected one 
                if (cmbCompanies[i].selected) {
                    // This is the selected one
                    selectedCompanyID = cmbCompanies.value;
                
                    // Set the company name to be the text box
                    companyName=cmbCompanies[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;
            }
        } 
        
        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==="To Outside Services" ||
                 selectedText==="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;
            }
        }
        
        document.addEventListener('DOMContentLoaded', function() {
            // Change the employees displayed in the combo box depending on the company
            displayCorrectCompanyEmployees();
            
            // Setup the programmers combobox list
            var programmerDiv = document.getElementById('programmerDiv');
            var programCheckedByDiv = document.getElementById('programCheckedByDiv');
            programmerDiv.innerHTML = getSUCompanyEmployeesAsSelectOptions("programmer", "");
            programCheckedByDiv.innerHTML = getSUCompanyEmployeesAsSelectOptions("programCheckedBy", "");
            
            // Disable them
            document.getElementById('programmer').disabled=true;
            document.getElementById('programCheckedBy').disabled=true;
            
        }, false);
    </script>

    </div>
  </div>
</div>
<!-- end of banner wrap --->

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

    <?php
        // Determine if they are GTG
        if ($gtg){
            echo getTask($db, $userRow, null, $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="javascript: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>

</body>

</html>