<?php

    function getStatusAsDraggableList($db, $userRow){
        // Initialize the return
        $result = '';
        try {
            // Create the query to run
            $sql='SELECT *, ' .
                        '(SELECT DefaultTaskStatusCompletionFactor FROM companies WHERE CompanyID=1) AS DefaultTaskStatusCompletionFactor ' . 
                 'FROM status ' . 
                 'ORDER BY ProcessOrder;';

            // Query the database for the user 
            $rows = $db->queryDB($sql, $userRow, "routing_presentation Form occurance 1");

            // If there are rows, then we are good to go.
            if ($rows == null){
                return $result;
            }
            else{
                $loopNumber=1;
                // Loop through the status rows
                while ($row=mysqli_fetch_array($rows)){
                    // Add this to the list
                    $result=$result . '<li class="Table ViableStatus" style="background-color: #' . $row["StatusRowColor"] . '; cursor: pointer;">
                                        <div style="font-weight:bold; v-alignment:middle;"> ' .
                                          $row["Name"]  .
                                          '<a id="expandLI" name="expandLI" style="float: left; cursor: s-resize; display: none;" onclick="toggleProperties(this);" title="Show or hide the properties of this status routing.">+</a>
                                           <a id="deleteLI" name="deleteLI" class="deleteLI" style="float: right; cursor: not-allowed; display: none;" onclick="deleteRow(this);" title="Delete this status routing step.">x</a>
                                           <a id="moveThisOne" name="moveThisOne" style="float: left; cursor: copy;" onclick="copyRow(this);" title="Clicking this will add it to the list of statuses to move to the routing path."><<</a>
                                        </div>
                                        <div id="expandableLI" style="background-color: white; display:none;"> 
                                          <input type="hidden" id="taskStatusInfoID" name="taskStatusInfoID" value=-1>
                                          <input type="hidden" id="infoStatusID" name="infoStatusID" value=' . $row["StatusID"] . '>
                                          <table>
                                            <tr>
                                                <td colspan=1 align="right">
                                                    <strong><label style="font-size:9pt;" title="The estimated amount of time that it will take to complete this state.">Time (Hrs):</label></strong>
                                                </td>
                                                <td colspan=1 align="left" width="15%">
                                                    <input name="statusInfoEstimatedTime" id="statusInfoEstimatedTime" type="text" maxlength="5" style="width: 100%; height: 15px; font-size:9pt;" value="1.0" onchange="div_show(\'loadSavedTrunk\');" title="The estimated amount of time that it will take to complete this state.">
                                                </td>
                                                <td colspan=1 align="right">
                                                    <strong><label style="font-size:9pt;" title="The the fudge factor allowed for time completion.  Should be a value over one.">Time Factor:</label></strong>
                                                </td>
                                                <td colspan=1 width="15%">
                                                    <input name="statusInfoCompletionFactor" id="statusInfoCompletionFactor" type="text" maxlength="5" style="width: 100%; height: 15px; font-size:9pt;" value="' . $row["DefaultTaskStatusCompletionFactor"] . '" onchange="div_show(\'loadSavedTrunk\');" title="The the fudge factor allowed for time completion.  Should be a value over one."> 
                                                </td>
                                            </tr>
                                            <tr>
                                                <td colspan=4 align="center">
                                                    <br>
                                                    <strong><label style="font-size:9pt;">Notes On Status:</label></strong>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td colspan=4>
                                                    <textarea name="statusInfoNote" id="statusInfoNote" maxlength="4000" class="intext" style="width: 100%; height: 70px; overflow: vertical; resize:vertical" onchange="div_show(\'loadSavedTrunk\');"></textarea>
                                                </td>
                                            </tr>
                                          </table>
                                        </div>
                                      </li>';
                    
                    $loopNumber++;
                }

                // Create the head of the table and add the rows
                $result = '<ul id="availableStatuses" class="sourceList statuses_sortable" ' . 
                          'style="clear: both; width: 165px;"> ' . 
                          '    <li class="ui-state-default ui-state-disabled Table"></li>
                          ' . $result . 
                          '</ul>';
                
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return '';
        }

        // Return whatever we got
        return $result;
    }
    
    function getStatusRoutingAsDraggableList($db, $userRow, $TaskID, $planned){
        // Initialize the return
        $result = '';
        try {
            // Create the query to run
            $sql='SELECT tsi.*, s.Name AS StatusName, s.StatusRowColor ' .
                 'FROM taskstatusinfo_initial tsi ' . 
                 'LEFT JOIN status s ON tsi.StatusID = s.StatusID '  .
                 'WHERE tsi.TaskID = '  . $TaskID . ' ' .
                 'ORDER BY tsi.ExecutionOrder;';

            // Query the database for the user 
            $rows = $db->queryDB($sql, $userRow, "routing_presentation Form occurance 5");

            // If there are rows, then we are good to go.
            if ($rows == null){
                return $result;
            }
            else{
                $loopNumber=1;
                // Loop through the status rows
                while ($row=mysqli_fetch_array($rows)){
                    // Create the LI row for the UL
                    $result=$result . '<li class="Table ViableStatus" style="background-color: #' . $row["StatusRowColor"] . '; cursor: pointer;">
                                        <div style="font-weight:bold; v-alignment:middle;"> ' .
                                          $row["StatusName"]  .
                                          '<a id="expandLI" name="expandLI" style="float: left; cursor: s-resize; display: block;" onclick="toggleProperties(this);" title="Expand the properties of this status routing.">+</a>
                                           <a id="deleteLI" name="deleteLI" class="deleteLI" style="float: right; cursor: not-allowed; display: block;" onclick="deleteRow(this);" title="Delete this status routing step.">x</a>
                                        </div>
                                        <div id="expandableLI" style="background-color: white; display:none;"> 
                                          <input type="hidden" id="taskStatusInfoID" name="taskStatusInfoID" value=' . $row["TaskStatusInfoID"] . '>
                                          <input type="hidden" id="infoStatusID" name="infoStatusID" value=' . $row["StatusID"] . '>
                                          <table>
                                            <tr>
                                                <td colspan=1 align="right">
                                                    <strong><label style="font-size:9pt;" title="The estimated amount of time that it will take to complete this state.">Time (Hrs):</label></strong>
                                                </td>
                                                <td colspan=1 align="left" width="15%">
                                                    <input name="statusInfoEstimatedTime" id="statusInfoEstimatedTime" type="text" maxlength="5" style="width: 100%; height: 15px; font-size:9pt;" value="' . $row["EstimatedTime"] . '" onchange="div_show(\'loadSavedTrunk\');" title="The estimated amount of time that it will take to complete this state.">
                                                </td>
                                                <td colspan=1 align="right">
                                                    <strong><label style="font-size:9pt;" title="The the fudge factor allowed for time completion.  Should be a value over one.">Time Factor:</label></strong>
                                                </td>
                                                <td colspan=1 width="15%">
                                                    <input name="statusInfoCompletionFactor" id="statusInfoCompletionFactor" type="text" maxlength="5" style="width: 100%; height: 15px; font-size:9pt;" value="' . $row["CompletionFactor"] . '" onchange="div_show(\'loadSavedTrunk\');" title="The the fudge factor allowed for time completion.  Should be a value over one."> 
                                                </td>
                                            </tr>
                                            <tr>
                                                <td colspan=4 align="center">
                                                    <br>
                                                    <strong><label style="font-size:9pt;">Notes On Status:</label></strong>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td colspan=4>
                                                    <textarea name="statusInfoNote" id="statusInfoNote" maxlength="4000" class="intext" style="width: 100%; height: 70px; overflow: vertical; resize:vertical" onchange="div_show(\'loadSavedTrunk\');">' . $row["StatusNotes"] . '</textarea>
                                                </td>
                                            </tr>
                                          </table>
                                        </div>
                                      </li>';
                    
                    $loopNumber++;
                }

                // Create the head of the table and add the rows
                $result = '<ul id="initialStatusRouting" class="destinationList statuses_sortable" style="clear: both; width: 400px;"> ' . 
                          '    <li class="ui-state-default ui-state-disabled Table" style="clear: both; width: 400px;"></li>
                          ' . $result . 
                          '</ul>' .
                          '<ul>' . 
                          '    <li class="ui-state-default ui-state-disabled Table" style="width: 410px;"></li> ' .
                          '</ul>';
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return '';
        }

        // Return whatever we got
        return $result;
    }
    
    function getCurrentStatusRoutingListFromHistory($db, $userRow, $taskID, $currentTaskStatusRoutingNodeID, &$currentRoutingBranchesHTML){
        // Initialize the return
        $result = '';
        try {
            // Create the query to run
            $sql='SELECT tsi.*, s.Name AS StatusName, s.StatusRowColor, branches.AmountOfBranches AS BranchAmount ' .
                 'FROM taskstatusinfo_current tsi ' . 
                 'LEFT JOIN status s ON tsi.StatusID = s.StatusID '  .
                 'LEFT JOIN (SELECT MainBranchID, COUNT(*) AS AmountOfBranches FROM taskstatusinfo_current GROUP BY MainBranchID) branches ON tsi.TaskStatusInfoID = branches.MainBranchID ' .
                 'WHERE tsi.TaskID = '  . $taskID . ' ' .
                 'AND tsi.MainBranchID = 0 ' .
                 'ORDER BY tsi.ExecutionOrder;';
            
            // Query the database for the user 
            $rows = $db->queryDB($sql, $userRow, "routing_presentation Form occurance 5");

            // If there are rows, then we are good to go.
            if (mysqli_num_rows($rows)<1){
                return $result;
            }
            else{
                $loopNumber=1;
                // Loop through the status rows
                while ($row=mysqli_fetch_array($rows)){
                    // Set default variables
                    $borderCSS='border-style: dashed; border-color: black; border-width: 2px;';
                    $addRouteNodeElementHTML= '<input id="addCurrentRouteNode' . $row["TaskStatusInfoID"] . '" type="checkbox">';
                    $title='This routing node has not been completed yet.';
                    
                    // Set a variable to state that we have found the current state
                    if ($currentTaskStatusRoutingNodeID == $row["TaskStatusInfoID"]){
                        // Set the border color to green
                        $borderCSS='border-style: dashed; border-color: #0FFF50; border-width: 2px;';
                        $addRouteNodeElementHTML= '<input id="addCurrentRouteNode' . $row["TaskStatusInfoID"] . '" type="checkbox" checked>';
                        $title='This routing node is in the process of being completed.';
                    }
                    // Determine if this row has been finished
                    else if ($row["StatusCompleted"]==1){
                        // Set the border color to red
                        $borderCSS='border-style: solid; border-color: red; border-width: 2px;';
                        $addRouteNodeElementHTML= '<input id="addCurrentRouteNode' . $row["TaskStatusInfoID"] . '" type="checkbox" checked>';
                        $title='This routing node has been completed.';
                    }
                    
                    // Determine if this trunk route has branched
                    $trunkBranchesHTML='';
                    if ($row["BranchAmount"]!=null){
                        // Create a variable to hold the current symbol to be display
                        $currentExpandSymbol='&rarr;';
                        
                        // Create the branches div to add to the branches area
                        $currentRoutingBranchesHTML=$currentRoutingBranchesHTML . getCurrentStatusRoutingBranchList($db, $userRow, $taskID, $row["TaskStatusInfoID"], $currentTaskStatusRoutingNodeID, $currentExpandSymbol);
                        
                        // Create HTML to allow for the branching of this trunk route
                        $trunkBranchesHTML='<a id="expandBranch' . $row["TaskStatusInfoID"] . '" name="expandBranch' . $row["TaskStatusInfoID"] . '" style="display: block;" onclick="div_toggleClassVisibility(\'branch' . $row["TaskStatusInfoID"] . '\', \'expandedBranch\', \'expandAnchor\', this);" title="Expand the branching that happened at this point." class="expandAnchor">' . $currentExpandSymbol . '</a>';
                    }

                    // Determine if they are allowed to modify routing
                    $addRouteNodeChkBxElementHTML='';
                    $disableBecauseNotAllowed='';
                    if ($userRow["CanModifyRouting"]==1){
                        // Create the cell
                        $addRouteNodeChkBxElementHTML='<div class="cell keepRoutingCell" style="border: none;">
                                                      ' . $addRouteNodeElementHTML . '
                                                      </div>';
                    }
                    else{
                        // diable modfication
                        $disableBecauseNotAllowed='disabled';
                        
                        // Do not create a cell and element
                        $addRouteNodeChkBxElementHTML='';
                    }
                    
                    // Create the LI row for the UL
                    $result=$result . '<li class="Table" style="background-color: #' . $row["StatusRowColor"] . '; cursor: pointer;" title="' . $title . '">
                                        <div class="Row" style="font-weight:bold; v-alignment:middle; float: center;"> 
                                            <div class="cell expandCell" style="border: none;">
                                                <a style="cursor: s-resize; display: block;" onclick="expandTree(this, \'expandStatusNode' . $loopNumber . '\');" title="Expand the properties of this status routing.">+</a>
                                            </div>
                                            <div class="cell statusCell" style="' . $borderCSS . '">
                                                ' . $row["StatusName"] . '
                                            </div>
                                            ' . $addRouteNodeChkBxElementHTML . '
                                            <div class="cell branchCell" style="border: none;">
                                                ' . $trunkBranchesHTML . '
                                            </div>
                                        </div>
                                      </li>
                                      <li class="Table ViableStatus" id="expandStatusNode' . $loopNumber . '" style="display:none; background-color: #' . $row["StatusRowColor"] . '; cursor: pointer;">
                                        <div> 
                                          <input type="hidden" id="taskStatusInfoID" name="taskStatusInfoID" value=' . $row["TaskStatusInfoID"] . '>
                                          <input type="hidden" id="taskStatusInfoMainBranchID" name="taskStatusInfoMainBranchID" value=' . $row["MainBranchID"] . '>
                                          <input type="hidden" id="taskStatusInfoMergedToBranchID" name="taskStatusInfoMergedToBranchID" value=' . $row["MergedToBranchID"] . '>
                                          <input type="hidden" id="infoStatusID" name="infoStatusID" value=' . $row["StatusID"] . '>
                                          <input type="hidden" id="executionOrder" name="executionOrder" value=' . $row["ExecutionOrder"] . '>
                                          <input type="hidden" id="branchAmount" name="branchAmount" value=' . $row["BranchAmount"] . '>
                                          <table>
                                            <tr>
                                                <td colspan=1 align="right">
                                                    <strong><label style="font-size:9pt;" title="The estimated amount of time that it will take to complete this state.">Time (Hrs):</label></strong>
                                                </td>
                                                <td colspan=1 align="left" width="15%">
                                                    <input name="statusInfoEstimatedTime" id="statusInfoEstimatedTime" type="text" maxlength="5" style="width: 100%; height: 15px; font-size:9pt;" value="' . $row["EstimatedTime"] . '" onchange="div_show(\'loadSavedTrunk\');" title="The estimated amount of time that it will take to complete this state." ' . $disableBecauseNotAllowed . '>
                                                </td>
                                                <td colspan=1 align="right">
                                                    <strong><label style="font-size:9pt;" title="The the fudge factor allowed for time completion.  Should be a value over one.">Time Factor:</label></strong>
                                                </td>
                                                <td colspan=1 width="15%">
                                                    <input name="statusInfoCompletionFactor" id="statusInfoCompletionFactor" type="text" maxlength="5" style="width: 100%; height: 15px; font-size:9pt;" value="' . $row["CompletionFactor"] . '" onchange="div_show(\'loadSavedTrunk\');" title="The the fudge factor allowed for time completion.  Should be a value over one." ' . $disableBecauseNotAllowed . '> 
                                                </td>
                                            </tr>
                                            <tr>
                                                <td colspan=4 align="center">
                                                    <br>
                                                    <strong><label style="font-size:9pt;">Notes for State:</label></strong>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td colspan=4>
                                                    <textarea name="statusInfoNote" id="statusInfoNote" maxlength="4000" class="intext" style="width: 100%; height: 40px; overflow: vertical; resize:vertical" onchange="div_show(\'loadSavedTrunk\');" ' . $disableBecauseNotAllowed . '>' . $row["StatusNotes"] . '</textarea>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td colspan=4 align="center">
                                                    <br>
                                                    <strong><label style="font-size:9pt;">Feedback On State:</label></strong>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td colspan=4>
                                                    <textarea name="feedbackNote" id="feedbackNote" maxlength="4000" class="intext" style="width: 100%; height: 40px; overflow: vertical; resize:vertical" onchange="div_show(\'loadSavedTrunk\');" Title="These are notes that the completing user may want to either convey to the next person or have on record. Usually notes about difficulty or problems seen.">' . $row["CompletionFeedbackNotes"] . '</textarea>
                                                </td>
                                            </tr>
                                          </table>
                                        </div>
                                      </li>
                                      ';
                    
                    $loopNumber++;
                }

                // Create the head of the table and add the rows
                $result = '<ul id="currentStatusRouting">  ' . 
                          '    <li class="ui-state-default Table" style="clear: both;"></li>
                          ' . $result . 
                          '</ul>' .
                          '<ul>' . 
                          '    <li class="ui-state-default ui-state-disabled Table"></li> ' .
                          '</ul>';                
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return '';
        }

        // Return whatever we got
        return $result;
    }
    
    function getCurrentStatusRoutingList($db, $userRow, $taskID, $currentTaskStatusRoutingNodeID, &$currentRoutingBranchesHTML){
        // Initialize the return
        $result = '';
        try {
            // Create the query to run
            $sql='SELECT tsi.*, (IF(tsi.TimerStartDate IS NULL, tsi.ActualTime, tsi.ActualTime + time_to_sec(timediff(NOW(),tsi.TimerStartDate))/3600)) AS CurrentActualTime, s.Name AS StatusName, s.StatusRowColor, branches.AmountOfBranches AS BranchAmount ' .
                 'FROM taskstatusinfo_current tsi ' . 
                 'LEFT JOIN status s ON tsi.StatusID = s.StatusID '  .
                 'LEFT JOIN (SELECT MainBranchID, COUNT(*) AS AmountOfBranches FROM taskstatusinfo_current GROUP BY MainBranchID) branches ON tsi.TaskStatusInfoID = branches.MainBranchID ' .
                 'WHERE tsi.TaskID = '  . $taskID . ' ' .
                 'AND tsi.MainBranchID = 0 ' .
                 'ORDER BY tsi.ExecutionOrder;';
            
            // Query the database for the user 
            $rows = $db->queryDB($sql, $userRow, "routing_presentation Form occurance 5");

            // If there are rows, then we are good to go.
            if (mysqli_num_rows($rows)<1){
                return $result;
            }
            else{
                $loopNumber=1;
                // Loop through the status rows
                while ($row=mysqli_fetch_array($rows)){
                    // Set default variables
                    $borderCSS='border-style: dashed; border-color: black; border-width: 2px;';
                    $addRouteNodeElementHTML= '<input id="addCurrentRouteNode' . $row["TaskStatusInfoID"] . '" type="checkbox">';
                    $title='This routing node has not been completed yet.';
                    
                    // Set a variable to state that we have found the current state
                    if ($currentTaskStatusRoutingNodeID == $row["TaskStatusInfoID"]){
                        // Set the border color to green
                        $borderCSS='border-style: dashed; border-color: #0FFF50; border-width: 2px;';
                        $addRouteNodeElementHTML= '<input id="addCurrentRouteNode' . $row["TaskStatusInfoID"] . '" type="checkbox" checked>';
                        $title='This routing node is in the process of being completed.';
                    }
                    // Determine if this row has been finished
                    else if ($row["StatusCompleted"]==1){
                        // Set the border color to red
                        $borderCSS='border-style: solid; border-color: red; border-width: 2px;';
                        $addRouteNodeElementHTML= '<input id="addCurrentRouteNode' . $row["TaskStatusInfoID"] . '" type="checkbox" checked>';
                        $title='This routing node has been completed.';
                    }
                    
                    // Determine if this trunk route has branched
                    $trunkBranchesHTML='';
                    if ($row["BranchAmount"]!=null){
                        // Create a variable to hold the current symbol to be display
                        $currentExpandSymbol='&rarr;';
                        
                        // Create the branches div to add to the branches area
                        $currentRoutingBranchesHTML=$currentRoutingBranchesHTML . getCurrentStatusRoutingBranchList($db, $userRow, $taskID, $row["TaskStatusInfoID"], $currentTaskStatusRoutingNodeID, $currentExpandSymbol);
                        
                        // Create HTML to allow for the branching of this trunk route
                        $trunkBranchesHTML='<a id="expandBranch' . $row["TaskStatusInfoID"] . '" name="expandBranch' . $row["TaskStatusInfoID"] . '" style="display: block;" onclick="div_toggleClassVisibility(\'branch' . $row["TaskStatusInfoID"] . '\', \'expandedBranch\', \'expandAnchor\', this);" title="Expand the branching that happened at this point." class="expandAnchor">' . $currentExpandSymbol . '</a>';
                    }

                    // Determine if they are allowed to modify routing
                    $addRouteNodeChkBxElementHTML='';
                    $disableBecauseNotAllowed='';
                    if ($userRow["CanModifyRouting"]==1){
                        // Create the cell
                        $addRouteNodeChkBxElementHTML='<div class="cell keepRoutingCell" style="border: none;">
                                                      ' . $addRouteNodeElementHTML . '
                                                      </div>';
                    }
                    else{
                        // diable modfication
                        $disableBecauseNotAllowed='disabled';
                        
                        // Do not create a cell and element
                        $addRouteNodeChkBxElementHTML='';
                    }
                    
                    // Create the LI row for the UL
                    $result=$result . '<li class="Table" style="background-color: #' . $row["StatusRowColor"] . '; cursor: pointer;" title="' . $title . '">
                                        <div class="Row" style="font-weight:bold; v-alignment:middle; float: center;"> 
                                            <div class="cell expandCell" style="border: none;">
                                                <a style="cursor: s-resize; display: block;" onclick="expandTree(this, \'expandStatusNode' . $loopNumber . '\');" title="Expand the properties of this status routing.">+</a>
                                            </div>
                                            <div class="cell statusCell" style="' . $borderCSS . '">
                                                ' . $row["StatusName"] . '
                                            </div>
                                            ' . $addRouteNodeChkBxElementHTML . '
                                            <div class="cell branchCell" style="border: none;">
                                                ' . $trunkBranchesHTML . '
                                            </div>
                                        </div>
                                      </li>
                                      <li class="Table ViableStatus" id="expandStatusNode' . $loopNumber . '" style="display:none; background-color: #' . $row["StatusRowColor"] . '; cursor: pointer;">
                                        <div> 
                                          <input type="hidden" id="taskStatusInfoID" name="taskStatusInfoID" value=' . $row["TaskStatusInfoID"] . '>
                                          <input type="hidden" id="taskStatusInfoMainBranchID" name="taskStatusInfoMainBranchID" value=' . $row["MainBranchID"] . '>
                                          <input type="hidden" id="taskStatusInfoMergedToBranchID" name="taskStatusInfoMergedToBranchID" value=' . $row["MergedToBranchID"] . '>
                                          <input type="hidden" id="infoStatusID" name="infoStatusID" value=' . $row["StatusID"] . '>
                                          <input type="hidden" id="executionOrder" name="executionOrder" value=' . $row["ExecutionOrder"] . '>
                                          <input type="hidden" id="branchAmount" name="branchAmount" value=' . $row["BranchAmount"] . '>
                                          <table>
                                            <tr>
                                                <td colspan=1 align="right">
                                                    <strong><label style="font-size:9pt;" title="The estimated amount of time that it will take to complete this state.">Estimated Time (Hrs):</label></strong>
                                                </td>
                                                <td colspan=1 align="left" width="15%">
                                                    <input name="statusInfoEstimatedTime" id="statusInfoEstimatedTime" type="text" maxlength="5" style="width: 100%; height: 15px; font-size:9pt;" value="' . $row["EstimatedTime"] . '" onchange="div_show(\'loadSavedTrunk\');" title="The estimated amount of time that it will take to complete this state." ' . $disableBecauseNotAllowed . '>
                                                </td>
                                                <td colspan=1 align="right">
                                                    <strong><label style="font-size:9pt;" title="The the fudge factor allowed for time completion.  Should be a value over one.">Time Factor:</label></strong>
                                                </td>
                                                <td colspan=1 width="15%">
                                                    <input name="statusInfoCompletionFactor" id="statusInfoCompletionFactor" type="text" maxlength="5" style="width: 100%; height: 15px; font-size:9pt;" value="' . $row["CompletionFactor"] . '" onchange="div_show(\'loadSavedTrunk\');" title="The the fudge factor allowed for time completion.  Should be a value over one." ' . $disableBecauseNotAllowed . '> 
                                                </td>
                                            </tr>
                                            <tr>
                                                <td colspan=2 align="right">
                                                    <strong><label style="font-size:9pt;" title="The current actual time that has been used on this routing node.">Current Actual Time (Hrs):</label></strong>
                                                </td>
                                                <td colspan=2 align="left">
                                                    <strong><label style="font-size:9pt;" title="The current actual time that has been used on this routing node.">' . $row["CurrentActualTime"] . ' Hrs</label></strong>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td colspan=4 align="center">
                                                    <br>
                                                    <strong><label style="font-size:9pt;">Notes for State:</label></strong>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td colspan=4>
                                                    <textarea name="statusInfoNote" id="statusInfoNote" maxlength="4000" class="intext" style="width: 100%; height: 40px; overflow: vertical; resize:vertical" onchange="div_show(\'loadSavedTrunk\');" ' . $disableBecauseNotAllowed . '>' . $row["StatusNotes"] . '</textarea>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td colspan=4 align="center">
                                                    <br>
                                                    <strong><label style="font-size:9pt;">Feedback On State:</label></strong>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td colspan=4>
                                                    <textarea name="feedbackNote" id="feedbackNote" maxlength="4000" class="intext" style="width: 100%; height: 40px; overflow: vertical; resize:vertical" onchange="div_show(\'loadSavedTrunk\');" Title="These are notes that the completing user may want to either convey to the next person or have on record. Usually notes about difficulty or problems seen.">' . $row["CompletionFeedbackNotes"] . '</textarea>
                                                </td>
                                            </tr>
                                          </table>
                                        </div>
                                      </li>
                                      ';
                    
                    $loopNumber++;
                }

                // Create the head of the table and add the rows
                $result = '<ul id="currentStatusRouting">  ' . 
                          '    <li class="ui-state-default Table" style="clear: both;"></li>
                          ' . $result . 
                          '</ul>' .
                          '<ul>' . 
                          '    <li class="ui-state-default ui-state-disabled Table"></li> ' .
                          '</ul>';                
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return '';
        }

        // Return whatever we got
        return $result;
    }
    
    function getCurrentStatusRoutingBranchList($db, $userRow, $taskID, $trunkID, $currentTaskStatusRoutingNodeID, &$currentExpandSymbol='&rarr;'){
        // Initialize the return
        $result = '';
        try {
            // Create a variable to set the visibility of the entire bunch of children
            $activeChildrenCSS='display:none;';
            
            // Create the query to run
            $sql='SELECT tsi.*, (IF(tsi.TimerStartDate IS NULL, tsi.ActualTime, tsi.ActualTime + time_to_sec(timediff(NOW(),tsi.TimerStartDate))/3600)) AS CurrentActualTime, s.Name AS StatusName, s.StatusRowColor ' .
                 'FROM taskstatusinfo_current tsi ' . 
                 'LEFT JOIN status s ON tsi.StatusID = s.StatusID '  .
                 'WHERE tsi.TaskID = '  . $taskID . ' ' .
                 'AND tsi.MainBranchID = ' . $trunkID . ' ' .
                 'ORDER BY tsi.TaskStatusInfoID, tsi.ExecutionOrder;';
            
            // Query the database for the user 
            $rows = $db->queryDB($sql, $userRow, "routing_presentation Form occurance 5");

            // If there are rows, then we are good to go.
            if ($rows == null){
                return $result;
            }
            else{
                $loopNumber=1;
                // Loop through the rows
                while ($row=mysqli_fetch_array($rows)){
                    // Set default variables
                    $borderCSS='border-style: dashed; border-color: black; border-width: 2px;';
                    $addRouteNodeElementHTML= '<input id="addCurrentRouteNode' . $row["TaskStatusInfoID"] . '" type="checkbox">';
                    $title='This routing node has not been completed yet.';
                    
                    // Set a variable to state that we have found the current state
                    if ($currentTaskStatusRoutingNodeID == $row["TaskStatusInfoID"]){
                        // Set the border color to green
                        $borderCSS='border-style: dashed; border-color: #0FFF50; border-width: 2px;';
                        $addRouteNodeElementHTML= '<input id="addCurrentRouteNode' . $row["TaskStatusInfoID"] . '" type="checkbox" checked>';
                        $title='This routing node is in the process of being completed.';
                        
                        // This child is active, so display the branch
                        $activeChildrenCSS='display:block;';
                        $currentExpandSymbol='&darr;';
                    }
                    // Determine if this row has been finished
                    else if ($row["StatusCompleted"]==1){
                        // Set the border color to red
                        $borderCSS='border-style: solid; border-color: red; border-width: 2px;';
                        $addRouteNodeElementHTML= '<input id="addCurrentRouteNode' . $row["TaskStatusInfoID"] . '" type="checkbox" checked>';
                        $title='This routing node has been completed.';
                    }
                    
                    // Determine if they are allowed to modify routing
                    $addRouteNodeChkBxElementHTML='';
                    $disableBecauseNotAllowed='';
                    if ($userRow["CanModifyRouting"]==1){
                        // Create the cell
                        $addRouteNodeChkBxElementHTML='<div class="cell keepRoutingCell" style="border: none;">
                                                      ' . $addRouteNodeElementHTML . '
                                                      </div>';
                    }
                    else{
                        // diable modfication
                        $disableBecauseNotAllowed='disabled';
                        
                        // Do not create a cell and element
                        $addRouteNodeChkBxElementHTML='';
                    }
                    
                    // Create the LI row for the UL
                    $result=$result . '<li class="Table" style="background-color: #' . $row["StatusRowColor"] . '; cursor: pointer;" title="' . $title . '">
                                        <div class="Row" style="font-weight:bold; v-alignment:middle; float: center;"> 
                                            <div class="cell expandCell" style="border: none;">
                                                <a id="expandLI" name="expandLI" style="cursor: s-resize; display: block;" onclick="expandTree(this, \'expandStatusNode' . $trunkID . '_' . $loopNumber . '\');" title="Expand the properties of this status routing.">+</a>
                                            </div>
                                            <div class="cell statusCell" style="' . $borderCSS . '">
                                                ' . $row["StatusName"] . '
                                            </div>
                                            ' . $addRouteNodeChkBxElementHTML . '
                                        </div>
                                      </li>
                                      <li class="Table ViableStatus" id="expandStatusNode' . $trunkID . '_' . $loopNumber . '" style="display:none; background-color: #' . $row["StatusRowColor"] . '; cursor: pointer;">
                                        <div> 
                                          <input type="hidden" id="taskStatusInfoID" name="taskStatusInfoID" value=' . $row["TaskStatusInfoID"] . '>
                                          <input type="hidden" id="taskStatusInfoMainBranchID" name="taskStatusInfoMainBranchID" value=' . $row["MainBranchID"] . '>
                                          <input type="hidden" id="taskStatusInfoMergedToBranchID" name="taskStatusInfoMergedToBranchID" value=' . $row["MergedToBranchID"] . '>
                                          <input type="hidden" id="executionOrder" name="executionOrder" value=' . $row["ExecutionOrder"] . '>
                                          <input type="hidden" id="infoStatusID" name="infoStatusID" value=' . $row["StatusID"] . '>
                                          <table>
                                            <tr>
                                                <td colspan=2 align="left">
                                                    <strong><label style="font-size:9pt;" title="The current actual time that has been used on this routing node.">Current Actual Time (Hrs):</label></strong>
                                                </td>
                                                <td colspan=2 align="left">
                                                    <strong><label style="font-size:9pt;" title="The current actual time that has been used on this routing node.">' . $row["CurrentActualTime"] . ' Hrs</label></strong>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td colspan=4 align="center">
                                                    <br>
                                                    <strong><label style="font-size:9pt;">Notes for State:</label></strong>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td colspan=4>
                                                    <textarea name="statusInfoNote" id="statusInfoNote" maxlength="4000" class="intext" style="width: 100%; height: 40px; overflow: vertical; resize:vertical" onchange="div_show(\'loadSavedTrunk\');" ' . $disableBecauseNotAllowed . '>' . $row["StatusNotes"] . '</textarea>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td colspan=4 align="center">
                                                    <br>
                                                    <strong><label style="font-size:9pt;">Feedback On State:</label></strong>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td colspan=4>
                                                    <textarea name="feedbackNote" id="feedbackNote" maxlength="4000" class="intext" style="width: 100%; height: 40px; overflow: vertical; resize:vertical" onchange="div_show(\'loadSavedTrunk\');" Title="These are notes that the completing user may want to either convey to the next person or have on record. Usually notes about difficulty or problems seen.">' . $row["CompletionFeedbackNotes"] . '</textarea>
                                                </td>
                                            </tr>
                                          </table>
                                        </div>
                                      </li>
                                      ';
                    
                    $loopNumber++;
                }

                // Create the head of the table and add the rows
                $result = '<div class="expandedBranch" name="branch' . $trunkID . '" id="branch' . $trunkID . '" style="' . $activeChildrenCSS . '"> ' . 
                          '    <ul> ' . 
                          '        <li class="ui-state-default Table" style="clear: both;"></li>
                          ' . $result . 
                          '    </ul>' .
                          '    <ul>' . 
                          '        <li class="ui-state-default ui-state-disabled Table"></li> ' .
                          '    </ul>' .
                          '</div>';                
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return '';
        }

        // Return whatever we got
        return $result;
    }
    
    function taskHasRouting($db, $userRow, $taskID){
        // Set the value to assume that the task does NOT have routing yet
        $returnValue=false;
        
        // Determine if this is a normal task
        if ($taskID>0){
            // Create the query to determine if there is routing
            $sql='SELECT COUNT(*) AS AmountOfRoutingNodes 
                  FROM taskstatusinfo_initial
                  WHERE TaskID=' . $taskID . ';';

            // Query the database for the routing info
            $row = $db->queryDB($sql, $userRow, "routing_presentation Form occurance 38");
            
            // Attempt to get the information in an array
            $assocHasRouting = $row->fetch_assoc();

            // Determine if we have more than zero route nodes
            if ($assocHasRouting["AmountOfRoutingNodes"]>0){
                // Set the return to true
                $returnValue=true;
            }
        }
        
        // Return the value gotten
        return $returnValue;
    }
    
    
    function getRoutingTemplatesToCopyAsSelectOptions($db, $userRow, $style='', $onchange=''){
        // Initialize the return
        $result = '';
        try {
            // Determine if this is an SU user
            if ($userRow["CompanyID"]==1){
                // Create the query to run
                $sql='SELECT DISTINCT TaskID, RoutingTitle 
                      FROM taskstatusinfo_initial
                      WHERE IsRoutingTemplate=1
                      ORDER BY RoutingTitle;';
                
                // Set the control name
                $controlName='routingTemplateToCopy';

                // Query the database for the labor categories
                $rows = $db->queryDB($sql, $userRow, "routing_presentation Form occurance 38");

                // If there are rows, then they are good to go.
                if ($rows == FALSE){
                    return $result;
                }
                else{
                    // Loop through the status rows
                    while ($row=mysqli_fetch_array($rows)){
                        // Add this option to the select
                        $result=$result . '<option value="' . $row["TaskID"] . '">' . $row["RoutingTitle"] . ' </option>';
                    }
                    
                    // Determine if there are any options
                    if ($result!=''){
                        // Start the return with the beginning of the select
                        $result='<select title="These are the routing templates available to use." name="' . $controlName . '" id="' . $controlName . '" style="' . $style . '" onchange="' . $onchange . '">' 
                                    . $result . 
                                '</select>
                                ';
                    }
                    else {
                        // Create a text box that tells them there is no templates yet.
                        $result = '<input type="text" name="' . $controlName . '" id="' . $controlName . '" style="' . $style . '" disabled value="NONE"\>';
                    }
                }
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }
    
    function copyRouting($db, $userRow, &$currentSuccess, $newTaskID, $taskIDToCopy=null){
        try {
            // Determine if they are currently successful as well as the proper variables are passed in
            if ($currentSuccess && 
                $taskIDToCopy!= null && $taskIDToCopy>0 && 
                $newTaskID!= null && $newTaskID>0){
                // Create the query to copy the initial routing information
                $sql='INSERT INTO taskstatusinfo_initial (TaskID, StatusID, ExecutionOrder, CompletionFactor, EstimatedTime, StatusNotes) ' .
                     'SELECT ' . $newTaskID . ', StatusID, ExecutionOrder, CompletionFactor, EstimatedTime, StatusNotes FROM taskstatusinfo_initial WHERE TaskID=' . $taskIDToCopy . ';';

//echo '<script>alert("' . addslashes($sql) . '");</script>';
//return false;
                // Attempt to update the initial routing
                if (!$db->queryDB($sql, $userRow, "routing_presentation Form occurance 10")){
                    // Set all as a fail
                    $currentSuccess=false;
                }
                else {
                    // Create a query to get the current routing of the task to copy
                    $sql='SELECT tsi.*, s.Name AS StatusName, s.StatusRowColor, branches.AmountOfBranches AS BranchAmount ' .
                         'FROM taskstatusinfo_current tsi ' . 
                         'LEFT JOIN status s ON tsi.StatusID = s.StatusID '  .
                         'LEFT JOIN (SELECT MainBranchID, COUNT(*) AS AmountOfBranches FROM taskstatusinfo_current GROUP BY MainBranchID) branches ON tsi.TaskStatusInfoID = branches.MainBranchID ' .
                         'WHERE tsi.TaskID = '  . $taskIDToCopy . ' ' .
                         'AND tsi.MainBranchID = 0 ' .
                         'ORDER BY tsi.ExecutionOrder;';

                    // Query the database for the user 
                    $rows = $db->queryDB($sql, $userRow, "routing_presentation Form occurance 5");

                    // If there are rows, then we are good to go.
                    if (mysqli_num_rows($rows)>1){
                        // Loop through the status rows
                        while ($row=mysqli_fetch_array($rows)){
                            // Save the Trunk Status Info ID as a number it cannot be
                            $insertedTrunkStatusInfoID=-1;
                                    
                            // Save the Merged To Status Info ID as though it is the trunk
                            $mergeToStatusInfoID=-1;
                                    
                            // Determine if we should get the current trunk ID 
                            if ($row["MainBranchID"]==0){
                                // Determine if the previous loop was writing branches
                                if ($mergeToStatusInfoID==-999){
                                    // Create a query to update all rows for this task ID 
                                    // that has a merge to ID of -999 to the current trunk ID.
                                    $sql='UPDATE taskstatusinfo_current ' .
                                         'SET MergedToBranchID=' . $insertedTrunkStatusInfoID . ' ' .
                                         'WHERE MergedToBranchID=-999 ' . 
                                         'AND TaskID=' . $newTaskID . ';';
                                    
                                    // Attempt to run the update query
                                    $db->queryDB($sql, $userRow, "routing_presentation occurance 3");

                                    // Set it back to a trunk value for merge to
                                    $mergeToStatusInfoID=-1;
                                }
                                
                                // Now save the Trunk ID as the one we are currently working on
                                $insertedTrunkStatusInfoID = mysqli_insert_id($db->getDBConnection());
                            }
                            else {
                                // Set the merged branch to a number that is should not be
                                $mergeToStatusInfoID=-999;
                            }
                            
                            // create a query to insert the new row into the current routing table
                            $sql='INSERT INTO taskstatusinfo_current ' .
                                 '(TaskID, StatusID, ExecutionOrder, CompletionFactor, EstimatedTime, StatusNotes) ' .
                                 'SELECT ' . $newTaskID . ', StatusID, ExecutionOrder, CompletionFactor, EstimatedTime, StatusNotes FROM taskstatusinfo_current WHERE TaskStatusInfoID=' . $row["TaskStatusInfoID"] . ';';
                            
                            // Attempt to run the insert query
                            $db->queryDB($sql, $userRow, "routing_presentation occurance 3");
                        }
                    }
                    else{
                        // Attempt to insert the historical route as the current route
                        $sql='INSERT INTO taskstatusinfo_current (TaskID, StatusID, ExecutionOrder, StatusNotes) ' .
                             'SELECT TaskID, StatusID, ROW_NUMBER() OVER() AS ExecutionOrder, StatusNotes FROM taskstatus WHERE TaskID=' . $taskIDToCopy . ';';
                        
                        // Attempt to run the insert query
                        $db->queryDB($sql, $userRow, "routing_presentation occurance 3");
                    }
                }
            }
        } 
        catch (Exception $ex) {
            // Assign the output string as to what happened
            return false;
        } 
        finally {
            // Return the result
            return $currentSuccess;
        }
    }
?>