<?php
    function retrieveSUEmployee($userRow, $suEmployee){
        // Set the return result to nothing until we prove this is a SU
        $result='';
        $suEmployeeHTML='';
        $fieldsDisabled='';
        try {
            // Determine if we have values for the canModify flag
            if ($suEmployee != null and $suEmployee==true){
                // Set it to what we got in
                $suEmployeeHTML = 'checked';
            }

            // Determine if the user editing this is NOT a SU or EXEC
            if ($userRow["UserLevel"]!='SU' && $userRow["UserLevel"]!='EXECUTIVE'){
                // Disable it for editing except for SU's
                $fieldsDisabled = 'style="display: none;"';
            }

            // Determine if a super user
            if ($userRow["CompanyID"]==1){
                $result = 
                    '<tr>' . 
                    '   <td colspan=2>' . 
                    '       <input name="suEmployee" id="suEmployee" type="checkbox" ' . $suEmployeeHTML . ' ' . $fieldsDisabled . '/>
                            <strong><label for="suEmployee" ' . $fieldsDisabled . '>Main Company Employee</label></strong>
                        </td>
                    </tr>';
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return the created HTML
        return $result;
    }

    function getUserLevelAsSelectOptions($userRow, $userLevel, $userNumber, $suEmployee, $fieldsDisabled){
        // Initialize the return
        $result='<input id="userLevel" name="userLevel" type="text" class="intext" value="' . $userLevel . '" readonly="readonly"/>';
        try {
            // Determine if the user is editing his own profile
            if ($userRow["UserID"]!=$userNumber || $userRow["UserLevel"]=='SU'){
                // Determine if this person can even add users
                if ($userRow["UserLevel"]!='SU' &&
                    $userRow["UserLevel"]!='EXECUTIVE'){
                    // GET OUT OF THIS METHOD
                    return $result;
                }

                // Initialize the return
                $result = '';

                // Create the array of levels without the timecard option
                $levels = '';

                // Determine if the user being edited is a SU company user or not
                if ($suEmployee!=null && $suEmployee==0){
                    // Reset the array of levels with the timecard option
                    $levels = array("MINIMAL", "TYPICAL", "MID-MANAGEMENT", "MANAGEMENT", "EXECUTIVE", "SU");
                }
                else {
                    // Reset the array of levels with the timecard option
                    $levels = array("TIMECARD ONLY", "MINIMAL", "TYPICAL", "MID-MANAGEMENT", "MANAGEMENT", "EXECUTIVE", "SU");
                }
                
                // loop through the levels to create the select control
                foreach ($levels as $currentLevel) {
                    // Determine what the user's level is that we are editing
                    $selected = '';
                    if ($userLevel==$currentLevel){
                        // Set this as the selected one
                        $selected = "selected";
                    }

                    // Determine if we are at the level of the modifying user yet.
                    if ($currentLevel==$userRow["UserLevel"]){
                        // Determine if it is their profile that is being edited 
                        if ($userNumber == $userRow["UserID"] || 
                            $userRow["UserLevel"] == 'SU'){
                            // Add this option
                            $result = '<option value="' . $currentLevel . '" ' . $selected . '>' . $currentLevel . '</option>' . $result;
                        }
                        else {
                            // No more levels should be added
                            break;
                        }
                    }
                    else {
                        // Add this option
                        $result = '<option value="' . $currentLevel . '" ' . $selected . '>' . $currentLevel . '</option>' . $result;
                    }
                }

                // Start and finish the select statement
                $result='<select id="userLevel" name="userLevel" ' . $fieldsDisabled . ' >' . $result . '</select>';
            }

        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }

    function getAccountStatusAsSelectOptions($db, $userRow, $accountStatus, $userNumber, $fieldsDisabled){
        // Initialize the return
        $result = '';

        try {
            if ($userRow["UserID"]==$userNumber){
                // Only need a text box to show them their status, since they cannot change their own status
                $result='<input id="accountStatus" name="accountStatus" type="text" class="intext" value="' . $accountStatus . '" readonly="readonly"/>';
            }
            else {
                // Get the type as it is in the database
                $result=$db->getTypeAsSelectOptions('users', 'AccountStatus', 'accountStatus', $accountStatus, null, '', 0, $fieldsDisabled);
            }

        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }

    function retrieveCans($userRow, $canAddAllParent, $canCopyTasks, $canModify, $canModifyChildren, $cannotViewUnsubmittedBlanks, $canModifyRouting){
        // Set the return result to nothing until we prove this is a SU
        $result='';
        $canAddAllParentHTML='';
        $canCopyTasksHTML='';
        $canModifyHTML='';
        $canModifyChildrenHTML='';
        $cannotViewUnsubmittedBlanksHTML='';
        
        try {
            // Determine if we have values for the canAddAllParent flag
            if ($canAddAllParent != null and $canAddAllParent==true){
                // Set it to what we got in
                $canAddAllParentHTML = 'checked';
            }

            // Determine if we have values for the canCopyTask flag
            if ($canCopyTasks != null and $canCopyTasks==true){
                // Set it to what we got in
                $canCopyTasksHTML = 'checked';
            }

            // Determine if we have values for the canModify flag
            if ($canModify != null and $canModify==true){
                // Set it to what we got in
                $canModifyHTML = 'checked';
            }

            // Determine if we have values for the canModifyChildren flag
            if ($canModifyChildren != null and $canModifyChildren==true){
                // Set it to what we got in
                $canModifyChildrenHTML = 'checked';
            }

            // Determine if we have values for the cannotViewUnsubmittedBlanks flag
            if ($cannotViewUnsubmittedBlanks != null and $cannotViewUnsubmittedBlanks==true){
                // Set it to what we got in
                $cannotViewUnsubmittedBlanksHTML = 'checked';
            }
            
            // Determine if we have values for the canModifyRouting flag
            if ($canModifyRouting != null and $canModifyRouting==true){
                // Set it to what we got in
                $canModifyRoutingHTML = 'checked';
            }
            
            // Determine if a super user or executive
            if ($userRow["UserLevel"]=='SU' || 
                $userRow["UserLevel"]=='EXECUTIVE'){
                $result = 
                    '
                    <tr> 
                        <td> 
                            <br>
                            <input name="canModify" id="canModify" type="checkbox" ' . $canModifyHTML . '/>
                            <strong><label for="canModify">Can Make Modifications</label></strong>
                            <br>
                        </td>
                        <td> 
                            <br>
                            <input name="canAddAllParent" id="canAddAllParent" type="checkbox" ' . $canAddAllParentHTML . '/>
                            <strong><label for="canAddAllParent">Can Add Any Task</label></strong>
                            <br>
                        </td>
                    </tr>
                    <tr> 
                        <td> 
                            <br>
                            <input name="canModifyRouting" id="canModifyRouting" type="checkbox" ' . $canModifyRoutingHTML . '/>
                            <strong><label for="canModifyRouting">Can Modify Task Routing</label></strong>
                            <br>
                        </td>
                        <td> 
                            <br>
                            <input name="canCopyTasks" id="canCopyTasks" type="checkbox" ' . $canCopyTasksHTML . '/>
                            <strong><label for="canCopyTasks">Can Copy SubTasks To Parents</label></strong>
                            <br>
                        </td>
                    </tr>
                    <tr> 
                        <td> 
                            <br>
                            <input name="cannotViewUnsubmittedBlanks" id="cannotViewUnsubmittedBlanks" type="checkbox" ' . $cannotViewUnsubmittedBlanksHTML . '/>
                            <strong><label for="cannotViewUnsubmittedBlanks">Cannot View Unsubmitted Blanks</label></strong>
                            <br>
                        </td>
                        <td> 
                            <br>
                            <input name="canModifyChildren" id="canModifyChildren" type="checkbox" ' . $canModifyChildrenHTML . '/>
                            <strong><label for="canModifyChildren">Can Add/Modify Child Tasks</label></strong>
                            <br>
                        </td>
                    </tr>
                    ';
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return the created HTML
        return $result;
    }

    function getUserCheckboxes($userRow, $inReceiveAttachmentUpdate, $inReceivePriorityChangeUpdate, 
                               $inReceiveAddTaskUpdate, $inReceiveMaterialLowStockNotificationUpdate, 
                               $inReceivePayPeriodRolloverUpdate, $inReceiveBlankCutNotificationUpdate,
                               $inReceiveToolLowStockNotificationUpdate, $inReceiveNotesNotificationUpdate){
        // Initialize the return
        $result = '';

        // Initialize the checkbox html values
        $receiveAttachmentUpdate = '';
        $receivePriorityChangeUpdate = '';
        $receiveTaskUpdate = '';
        $receiveMaterialLowStockNotificationUpdate = '';
        $receiveToolLowStockNotificationUpdate = '';
        $receivePayPeriodRolloverUpdate = '';
        $receiveBlankCutNotificationUpdate='';
        $receiveNotesNotificationUpdate='';

        // Determine if we have values for the invoiced flag
        if ($inReceiveAttachmentUpdate != null and $inReceiveAttachmentUpdate==true){
            // Set it to what we got in
            $receiveAttachmentUpdate = 'checked';
        }

        // Determine if we have values for the completed flag
        if ($inReceivePriorityChangeUpdate != null and $inReceivePriorityChangeUpdate==true){
            // Set it to what we got in
            $receivePriorityChangeUpdate = 'checked';
        }

        // Determine if we have values for the closed flag
        if ($inReceiveAddTaskUpdate != null and $inReceiveAddTaskUpdate==true){
            // Set it to what we got in
            $receiveTaskUpdate = 'checked';
        }

        // Determine if the user is a member of the SU Company
        $payPeriodRolloverUpdateHTML='';
        if ($userRow["CompanyID"]==1 ){
            // Determine if this is a SU or Exec of the SU company
            $payPeriodRolloverUpdateEnabledHTML='';
            if ($userRow["UserLevel"]!='SU' && 
                $userRow["UserLevel"]!='EXECUTIVE' ){
                // Disable it
                $payPeriodRolloverUpdateEnabledHTML='class="special disabled" onclick="event.preventDefault();"'; 
            }

            // Determine if we have values for low stock update
            if ($inReceiveMaterialLowStockNotificationUpdate != null and $inReceiveMaterialLowStockNotificationUpdate==true){
                // Set it to what we got in
                $receiveMaterialLowStockNotificationUpdate = 'checked';
            }

            // Create the HTML for the low stock notification check box
            $materialLowStockNotificationUpdateHTML='<br>
                            <input name="receiveMaterialLowStockNotificationUpdate" id="receiveMaterialLowStockNotificationUpdate" type="checkbox" ' . $receiveMaterialLowStockNotificationUpdate . '/>
                            <strong><label for="receiveMaterialLowStockNotificationUpdate">Material Low Stock</label></strong>
                ';
            
            // Determine if we have values for low stock update
            if ($inReceiveToolLowStockNotificationUpdate != null and $inReceiveToolLowStockNotificationUpdate==true){
                // Set it to what we got in
                $receiveToolLowStockNotificationUpdate = 'checked';
            }

            // Create the HTML for the low stock notification check box
            $toolLowStockNotificationUpdateHTML='<br>
                            <input name="receiveToolLowStockNotificationUpdate" id="receiveToolLowStockNotificationUpdate" type="checkbox" ' . $receiveToolLowStockNotificationUpdate . '/>
                            <strong><label for="receiveToolLowStockNotificationUpdate">Tool Low Stock</label></strong>
                ';
            
            // Determine if we have values for PayPeriod Rollover
            if ($inReceivePayPeriodRolloverUpdate != null and $inReceivePayPeriodRolloverUpdate==true){
                // Set it to what we got in
                $receivePayPeriodRolloverUpdate = 'checked';
            }

            // Create the HTML for the pay period notification check box
            $payPeriodRolloverUpdateHTML='<br>
                            <input name="receivePayPeriodRolloverUpdate" id="receivePayPeriodRolloverUpdate" ' . $payPeriodRolloverUpdateEnabledHTML . ' type="checkbox" ' . $receivePayPeriodRolloverUpdate . '/>
                            <strong><label for="receivePayPeriodRolloverUpdate" ' . $payPeriodRolloverUpdateEnabledHTML . '>Pay Period Rollover</label></strong>
                ';

            // Determine if we have values for blank notification updates
            if ($inReceiveBlankCutNotificationUpdate != null and $inReceiveBlankCutNotificationUpdate==true){
                // Set it to what we got in
                $receiveBlankCutNotificationUpdate = 'checked';
            }

            // Create the HTML for the blank notification check box
            $payBlankNotificationUpdateHTML='<br>
                            <input name="receiveBlankCutNotificationUpdate" id="receiveBlankCutNotificationUpdate" type="checkbox" ' . $receiveBlankCutNotificationUpdate . '/>
                            <strong><label for="receiveBlankCutNotificationUpdate">Blank To Be Cut/Blank Cut</label></strong>
                ';
            
            // Determine if we have values for notes notification
            if ($inReceiveNotesNotificationUpdate != null and $inReceiveNotesNotificationUpdate==true){
                // Set it to what we got in
                $receiveNotesNotificationUpdate = 'checked';
            }

            // Create the HTML for the notes notification check box
            $notesNotificationHTML='<br>
                            <input name="receiveNotesNotificationUpdate" id="receiveNotesNotificationUpdate" type="checkbox" ' . $receiveNotesNotificationUpdate . '/>
                            <strong><label for="receiveNotesNotificationUpdate">Receive Final Task Feedback Notes</label></strong>
                ';
        }


        try {
            // Send back the check boxes that are available
            $result='
                        <input name="receiveAttachmentUpdate" id="receiveAttachmentUpdate" type="checkbox" ' . $receiveAttachmentUpdate . '/>
                        <strong><label for="receiveAttachmentUpdate">New Task Attachments</label></strong>
                        <br>
                        <input name="receivePriorityChangeUpdate" id="receivePriorityChangeUpdate" type="checkbox" ' . $receivePriorityChangeUpdate . '/>
                        <strong><label for="receivePriorityChangeUpdate">Task Priority Change</label></strong>
                        <br>
                        <input name="receiveAddTaskUpdate" id="receiveAddTaskUpdate" type="checkbox" ' . $receiveTaskUpdate . '/>
                        <strong><label for="receiveAddTaskUpdate">Add New Task</label></strong>
                        ' .
                        $materialLowStockNotificationUpdateHTML .
                        $toolLowStockNotificationUpdateHTML .
                        $payPeriodRolloverUpdateHTML .
                        $payBlankNotificationUpdateHTML . 
                        $notesNotificationHTML
                        . '
                    ';
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }

    function getPrimaryTaskTypeAsSelectOptions($db, $userRow, $userNumber, $isAddNew=0){
        // Initialize the return
        $result='<select id="primaryTaskType" name="primaryTaskType">';
        $result=$result . '<option value="MACHINING" selected>MACHINING</option>';
        $result=$result . '<option value="DESIGNING">DESIGNING</option>';
        $result=$result . '<option value="PROGRAMMING">PROGRAMMING</option>';
        $result=$result . '<option value="IN-HOUSE">IN-HOUSE</option>';
        $result=$result . '</select>';

        try {
            // Determine if this is a new add
            if (!$isAddNew){
                // If it has not been set, then get what their preference is
                $sql = 'SELECT PrimaryTaskType FROM users WHERE UserID = ' . 
                       $userRow["UserID"];

                // Determine if this is actually for a selected user and not myself
                if ($userNumber!=null){
                    // If it has not been set, then get what their preference is
                    $sql = 'SELECT PrimaryTaskType FROM users WHERE UserID = ' . 
                           $userNumber;
                }

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

                // If there is only one result for a username/password combo, then they are good to go.
                if ($row != null && mysqli_num_rows($row)==1){
                    // Attempt to get the user row
                    $preferenceRow = $row->fetch_assoc();

                    // Start the return with the beginning of the select
                    $result='<select id="primaryTaskType" name="primaryTaskType">';
                    $result=$result . '<option value="MACHINING" ' . ($preferenceRow["PrimaryTaskType"]=='MACHINING'?'selected':'') . '>MACHINING</option>';
                    $result=$result . '<option value="DESIGNING" ' . ($preferenceRow["PrimaryTaskType"]=='DESIGNING'?'selected':'') . '>DESIGNING</option>';
                    $result=$result . '<option value="PROGRAMMING" ' . ($preferenceRow["PrimaryTaskType"]=='PROGRAMMING'?'selected':'') . '>PROGRAMMING</option>';
                    $result=$result . '<option value="IN-HOUSE" ' . ($preferenceRow["PrimaryTaskType"]=='IN-HOUSE'?'selected':'') . '>IN-HOUSE</option>';
                    $result=$result . '</select>';
                }
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }

    function checkThenGetNotesDiv($db, $userRow, $inAssociatedCategoryID, $inCategoryType, &$validationHTML=""){
        // Init all of the settings to the appropriate values
        $noteDiv = '';
        
        // Determine if the user is of the main company and appropriate level
        if ($userRow["CompanyID"]==1 &&
                ($userRow["UserLevel"]=="SU" ||
                 $userRow["UserLevel"]=="EXECUTIVE" ||
                 $userRow["UserLevel"]=="MANAGEMENT" ||
                 $userRow["UserLevel"]=="MID-MANAGEMENT" ||
                 $userRow["UserLevel"]=="TYPICAL")
            )
            {
                // get the div
                $noteDiv = retrieveNotesDiv($db, $userRow, $inAssociatedCategoryID, $inCategoryType, true, $validationHTML);
            }

        // Return the result
        return $noteDiv;
    }

    function getUser($db, $userRow, $userNumber, $isTemplate=false, $applyTemplateID=-1){
        // Init all of the settings to the appropriate values
        $accountStatus = 'ACTIVE';
        $addDate = date('Y-m-d', strtotime("Now"));
        $companyID = $userRow["CompanyID"];
        $eMail = '';
        $firstName = '';
        $initials = '';
        $lastName = '';
        $password = 'Password12345!@#$%';
        $userLevel = 'TYPICAL';
        $userName = '';
        $canModify = 1;
        $canModifyChildren = 0;
        $cannotViewUnsubmittedBlanks = 0;
        $canModifyRouting=0;
        $canAddAllParent = 0;
        $canCopyTasks = 0;
        $firstPayDate = '';
        $payPeriod = '';
        $suEmployee = $userRow["SUEmployee"];
        $hourlyPay = 0;
        $hourlyPayQ1 = 0;
        $hourlyPayQ2 = 0;
        $hourlyPayQ3 = 0;
        $hourlyPayQ4 = 0;
        $tasksPerPage = 0;
        $laborCategoryID = 1;
        $templateName=null;
        $templateID = "";

        $refreshRate = 600;
        $primaryTaskType = 'MACHINING';
        $defaultNewUserPassword = 'Password12345';
        $showWhatFinishedState = 2;
        $receiveAttachmentUpdate = 0;
        $receivePriorityChangeUpdate = 0;
        $receiveAddTaskUpdate = 0;
        $receiveMaterialLowStockNotificationUpdate = 0;
        $receiveToolLowStockNotificationUpdate = 0;
        $receivePayPeriodRolloverUpdate = 0;
        $receiveBlankCutNotificationUpdate = 0;
        $receiveNotesNotificationUpdate = 0;
        $silenceAllNotifications = 0;

        $modifyType = 'add';
        $isAdd=true;
            
        // Setup the html defaults
        $preferenceTab = '';
        $notificationsTab = '';
        $notificationsButton = '';
        $accessibilityTab = '';
        $accessibilityButton='';
        $preferenceTabPrivileged = '';
        $firstPayDateHTML = '';
        $payPeriodHTML = '';
        $hourlyPayHTML = '<input type="hidden" id="hourlyPay" name="hourlyPay" value=""/>';
        $silenceAllNotificationsHTML = '';
        
        // Setup the initial fields disabled HTML to be nothing for now.
        $fieldsDisabled = '';
        $passwordDisabled = '';

        // Calculate the start of this current quarter
        $quarterStart = calculateQuarterStart(null);
        
        // Determine if this is an update or not
        $assocUser = null;
        if ($userNumber && $userNumber>0){
            // Create the query to get the the user to be edited and the user that created the task
            $sql = 'SELECT u.*, u2.UserName AS TemplateName, u2.UserID AS TemplateID ' .
                   'FROM users u ' . 
                   'LEFT JOIN users u2 ON u.LastAppliedUserTemplateID=u2.UserID ' .
                   'WHERE u.UserID=' . $userNumber . ';';

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

            // Attempt to get the user row
            $assocUser = $row->fetch_assoc();

            // Set the things we can
            $accountStatus = $assocUser["AccountStatus"];
            $addDate = date('Y-m-d', strtotime($assocUser["AddDate"]));
            $companyID = $assocUser["CompanyID"];
            $eMail = $assocUser["EMail"];
            $firstName = $assocUser["FirstName"];
            $initials = $assocUser["Initials"];
            $lastName = $assocUser["LastName"];
            $password = $assocUser["Password"];
            $userLevel = $assocUser["UserLevel"];
            $userName = $assocUser["UserName"];
            $canModify = $assocUser["CanModify"];
            $canModifyChildren = $assocUser["CanModifyChildren"];
            $cannotViewUnsubmittedBlanks = $assocUser["CannotViewUnsubmittedBlanks"];
            $canModifyRouting = $assocUser["CanModifyRouting"];
            $canAddAllParent =  $assocUser["CanAddAllParent"];
            $canCopyTasks = $assocUser["CanCopyTasks"];
            $firstPayDate = $assocUser["FirstPayDate"];
            $payPeriod = $assocUser["PayPeriod"];
            $suEmployee = $assocUser["SUEmployee"];
            $hourlyPay = $assocUser["HourlyPayQ" . getQuarterNumber($quarterStart->format("n"))];
            $hourlyPayQ1 = $assocUser["HourlyPayQ1"];
            $hourlyPayQ2 = $assocUser["HourlyPayQ2"];
            $hourlyPayQ3 = $assocUser["HourlyPayQ3"];
            $hourlyPayQ4 = $assocUser["HourlyPayQ4"];
            $tasksPerPage = $assocUser["TasksPerPage"];
            $laborCategoryID = $assocUser["StandardLaborCategoryID"];
            $templateName = $assocUser["TemplateName"];
            $templateID = $assocUser["TemplateID"];

            $refreshRate = $assocUser["RefreshRate"];
            $primaryTaskType = $assocUser["PrimaryTaskType"];
            $defaultNewUserPassword = $assocUser["DefaultNewUserPassword"];
            $showWhatFinishedState = $assocUser["ShowWhatFinishedState"];
            $receiveAttachmentUpdate = $assocUser["ReceiveAttachmentUpdate"];
            $receivePriorityChangeUpdate = $assocUser["ReceivePriorityChangeUpdate"];
            $receiveAddTaskUpdate = $assocUser["ReceiveAddTaskUpdate"];
            $receiveMaterialLowStockNotificationUpdate = $assocUser["ReceiveMaterialLowStockNotificationUpdate"];
            $receiveToolLowStockNotificationUpdate = $assocUser["ReceiveToolLowStockNotificationUpdate"];
            $receivePayPeriodRolloverUpdate = $assocUser["ReceivePayPeriodRolloverUpdate"];
            $receiveBlankCutNotificationUpdate = $assocUser["ReceiveBlankCutNotificationUpdate"];
            $receiveNotesNotificationUpdate = $assocUser["ReceiveNotesNotificationUpdate"];
            $silenceAllNotifications = $assocUser["SilenceAllTaskNotifications"];

            $modifyType = 'update';
            $isAdd=false;
        }

        // Get a comparison of the two levels
        $compareUserLevelResult=compareUserLevel ($db, $userRow, $userRow["UserLevel"], $userLevel);

        // Set as a hidden field silence all notifications
        $notificationsTab = '<input type="hidden" id="silenceAllNotifications" name="silenceAllNotifications" value="' . $silenceAllNotifications . '"/>';

        // Determine if the user editing this is NOT a SU or EXEC
        if ($userRow["UserLevel"]!='SU' && $userRow["UserLevel"]!='EXECUTIVE'){
            // Disable it for editing except for SU's
            $fieldsDisabled = 'disabled';

            // Password should be open for these users
            $passwordDisabled = 'disabled';
        }
        else {
            // Determine if we have values for the silence all notifications flag
            $silenceAllNotificationsCheckedHTML='';
            if ($silenceAllNotifications != null && $silenceAllNotifications==1){
                // Set it to what we got in
                $silenceAllNotificationsCheckedHTML = 'checked';
            }

            // Setup the value of the silence to be what is brought from the database
            $silenceAllNotificationsHTML='<input name="silenceAllNotifications" id="silenceAllNotifications" ' . $fieldsDisabled . ' type="checkbox" ' . $silenceAllNotificationsCheckedHTML . '/>
                                          <strong><label for="silenceAllNotifications" ' . $fieldsDisabled . '>Silence All Notifications</label></strong>
                ';
        }

        // Determine if the user editing this is editing their own profile
        if ($userRow["UserID"] == $userNumber){
            // Password should be open to change their password
            $passwordDisabled = '';
        }

        // Set the hourly pay as hidden for now
        $hourlyPayHTML = '<input type="hidden" id="hourlyPay" name="hourlyPay" value="' . $hourlyPay . '"/>';

        // Determine if the user is editing his own profile so we 
        // can get his personal preferences.
        // TODO: eventually allow users to to see other users as a matrix of who can do what. Involves a linker table.
        if ($userNumber==$userRow["UserID"] || 
            ($compareUserLevelResult==1 && $userRow["CompanyID"]==1 && $userRow["SUEmployee"]==1 && $userRow["AccountStatus"]=='ACTIVE') ||
            $userRow["UserLevel"]=='SU' || $userRow["UserLevel"]=='EXECUTIVE'){
            // Determine if this user can make other users
            if ($userRow["UserLevel"]=='SU' ||
                $userRow["UserLevel"]=='EXECUTIVE') {
                // Set the button to be visible
                $notificationsButton='<button class="childtablink" type="button" onclick="openChildPage(\'tabs-3\', this);" title="Shows most options for notifying people via e-mail.">Notifications</button>';
                
                // Create the notifications things
                $notificationsTab = 
                    '<div id="tabs-3" style="display:none;" class="childtabcontent">   
                        <table width=100%>
                            <tr align="left" valign="bottom">
                                <td align="left">
                                ' 
                                .
                                $silenceAllNotificationsHTML
                                .
                                '
                                </td>
                            </tr>
                        </table>
                        <table width=100%>
                            <tr align="left" valign="bottom">
                                <td width="48%" align="center">
                                    <table width="100%" border="0" cellpadding="0" cellspacing="0" class="usial">
                                        <tr>
                                            <td align="left" valign="middle" style="border: 1px solid black;">
                                            ' . 
                                                getUserStatusNotificationsCheckboxes($db, $userRow, $userNumber) .
                                            ' 
                                            </td>
                                        </tr>
                                        <tr height="20px">
                                        </tr>
                                        <tr>
                                            <td align="left" valign="top" style="border: 1px solid black;">
                                                <div style="text-align: center;">
                                                    <strong>General Notifications</strong>
                                                </div>
                                                <br>
                                                <div style="height: 200px; overflow: scroll;">
                                                    ' . 
                                                    getUserCheckboxes($userRow, $receiveAttachmentUpdate, $receivePriorityChangeUpdate, 
                                                                      $receiveAddTaskUpdate, $receiveMaterialLowStockNotificationUpdate,
                                                                      $receivePayPeriodRolloverUpdate, $receiveBlankCutNotificationUpdate, 
                                                                      $receiveToolLowStockNotificationUpdate, $receiveNotesNotificationUpdate) .   
                                                    ' 
                                                </div>
                                            </td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                        </table>
                    </div> ' ;

                // Determine if this is an SU user
                $mainLaborAreaHTML='';
                $userMachineViewableCheckboxesHTML='';
                $retrieveCansHTML='';
                $accessibilityButton='';
                $accessibilityTab='';
                if ($userRow["SUEmployee"]==1){
                    $mainLaborAreaHTML='
                                    <tr>
                                        <td colspan=4 height="39" align="left" valign="top">
                                            <strong>Main Labor Area: </strong> &nbsp; &nbsp;
                                            ' 
                                            . getLaborCategoryAsSelectOptions($db, $userRow, $laborCategoryID, 'Clocked In') . 
                                            '
                                        </td>
                                    </tr>
                                    ';
                    $userMachineViewableCheckboxesHTML=' 
                                                <td width="50%" align="left" valign="middle" style="border: 1px solid black;">
                                                ' . 
                                                    getUserMachineViewableCheckboxes($db, $userRow, $userNumber) .
                                                ' 
                                                </td>
                                            ';
                    $retrieveCansHTML= retrieveCans($userRow, $canAddAllParent, $canCopyTasks, $canModify, $canModifyChildren, $cannotViewUnsubmittedBlanks, $canModifyRouting);
                    
                    // Setup the visibility button to show on the user form
                    $accessibilityButton='<button class="childtablink" type="button" onclick="openChildPage(\'tabs-4\', this);" title="Options under this tab allows modifying the visibility of certain things to be changed per user.">Accessibility</button>';

                    // Create the notifications things
                    $accessibilityTab = 
                        '<div id="tabs-4" style="display:none;" class="childtabcontent">   
                            <table width=100%>
                                <tr align="left" valign="bottom">
                                    <td width="48%" align="center">
                                        <table width="100%" border="0" cellpadding="0" cellspacing="0" class="usial">
                                            <tr>
                                                <td width="50%" align="left" valign="middle" style="border: 1px solid black;">
                                                ' . 
                                                    getUserStatusViewableCheckboxes($db, $userRow, $userNumber) .
                                                ' 
                                                </td>
                                                '
                                                .
                                                $userMachineViewableCheckboxesHTML
                                                .
                                                '
                                            </tr>
                                            <tr height="20px">
                                                <td colspan=2>
                                                </td>
                                            </tr>
                                            '
                                            .
                                            $retrieveCansHTML
                                            .
                                            '
                                        </table>
                                    </td>
                                </tr>
                            </table>
                        </div> ' ;
                }
            }
            
            // Determine if this user can make other users
            if ($userRow["UserLevel"]=='SU' ||
                $userRow["UserLevel"]=='EXECUTIVE') {
                    // setup the password field for display
                    $preferenceTabPrivileged = '
                                    <tr>
                                        <td colspan=3 height="39" align="left" valign="top"><strong>Password Assigned To New Users:</strong>
                                            <input name="defaultNewUserPassword" type="text" maxlength="50" class="intext" style="width: 50%;" value="' . $defaultNewUserPassword . '"/>
                                        </td>
                                    </tr>';
            }

            // Create the preferences things
            $preferenceTab = 
                '<div id="tabs-2" style="display:none;" class="childtabcontent">
                    <table width=100%>
                        <tr align="left" valign="bottom">
                            <td width="48%" align="center">
                                <table width="100%" border="0" cellpadding="0" cellspacing="0" class="usial">
                                    <tr>
                                        <td colspan=3 height="39" align="left" valign="top"><strong>Refresh Rate:</strong> 
                                        <input name="refreshRate" type="text" maxlength="11" class="intext" style="width: 10%;" value="' . $refreshRate . '"/></td>
                                    </tr>
                                    <tr>
                                        <td colspan=3 height="39" align="left" valign="top">
                                        <strong>Primary Task Type:</strong> 
                                        ' 
                                        . getPrimaryTaskTypeAsSelectOptions($db, $userRow, $userNumber, $isAdd) . 
                                        '
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan=3 height="39" align="left" valign="top">
                                            '
                                            . getShowNoShowCombo($showWhatFinishedState, true, 'font-weight: bold;') .   
                                            '
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan=3 height="39" align="left" valign="top">
                                            '
                                            . getTasksPerPageCombo($tasksPerPage, false, 'font-weight: bold;','','') .   
                                            '
                                        </td>
                                    </tr>
                                    '
                                    .
                                    $mainLaborAreaHTML .
                                    $preferenceTabPrivileged . 
                                    '                          
                                </table>
                            </td>
                        </tr>
                    </table>
                </div> ' ;
        }

        // Determine if this user is of the main company
        $hourlyPayValidationJS="";
        if ($userRow["CompanyID"]==1){
            // Determine if this user is of the right level to see hourly pay info
            if ($userRow["UserLevel"]=='SU' ||
                $userRow["UserLevel"]=='EXECUTIVE'){
                // Create an HTML for visible hourly pay amount
                $hourlyPayHTML = '<tr>
                                    <td colspan=2 height="39" align="center" valign="middle">
                                      <strong>Hourly Pay</strong>
                                      <br>
                                      <table>
                                            <tr>
                                                <td style="text-align:center">
                                                    Q1:<br><input name="hourlyPayQ1" id="hourlyPayQ1" type="text" maxlength="10" class="intext" ' . $fieldsDisabled . ' style="text-align:center; width: 100%; height: 19px" value="' . $hourlyPayQ1 . '"/>
                                                </td>
                                                <td style="text-align:center">
                                                    Q2:<br><input name="hourlyPayQ2" id="hourlyPayQ2" type="text" maxlength="10" class="intext" ' . $fieldsDisabled . ' style="text-align:center; width: 100%; height: 19px" value="' . $hourlyPayQ2 . '"/>
                                                </td>
                                                <td style="text-align:center">
                                                    Q3:<br><input name="hourlyPayQ3" id="hourlyPayQ3" type="text" maxlength="10" class="intext" ' . $fieldsDisabled . ' style="text-align:center; width: 100%; height: 19px" value="' . $hourlyPayQ3 . '"/>
                                                </td>
                                                <td style="text-align:center">
                                                    Q4:<br><input name="hourlyPayQ4" id="hourlyPayQ4" type="text" maxlength="10" class="intext" ' . $fieldsDisabled . ' style="text-align:center; width: 100%; height: 19px" onchange="this.value < 1 ? this.value=this.defaultValue : this.defaultValue=this.value=this.value;" value="' . $hourlyPayQ4 . '"/>
                                                </td>
                                            </tr>
                                      </table>
                                    </td>
                                  </tr>
                                  ';
                
                // Add validation for the fields that should only be for SU company users
                $hourlyPayValidationJS = '
                                frmvalidator.addValidation("hourlyPayQ1",
                                                           "mon",
                                                           "Please enter the hourly pay for Q1 as a monetary number.");
                                frmvalidator.addValidation("hourlyPayQ1",
                                                           "greaterthan=-1",
                                                           "The hourly pay for Q1 should be greater than or equal to zero.");
                                frmvalidator.addValidation("hourlyPayQ2",
                                                           "mon",
                                                           "Please enter the hourly pay for Q2 as a monetary number.");
                                frmvalidator.addValidation("hourlyPayQ2",
                                                           "greaterthan=-1",
                                                           "The hourly pay for Q2 should be greater than or equal to zero.");
                                frmvalidator.addValidation("hourlyPayQ3",
                                                           "mon",
                                                           "Please enter the hourly pay for Q3 as a monetary number.");
                                frmvalidator.addValidation("hourlyPayQ3",
                                                           "greaterthan=-1",
                                                           "The hourly pay for Q3 should be greater than or equal to zero.");
                                frmvalidator.addValidation("hourlyPayQ4",
                                                           "mon",
                                                           "Please enter the hourly pay for Q4 as a monetary number.");
                                frmvalidator.addValidation("hourlyPayQ4",
                                                           "greaterthan=-1",
                                                           "The hourly pay for Q4 should be greater than or equal to zero.");
                                ';
            }
            
            // Determine if this user is of the right level to see paydate info
            if ($userRow["UserLevel"]=='SU' ||
                $userRow["UserLevel"]=='EXECUTIVE' ||
                $userRow["UserLevel"]=='MANAGEMENT'){
                // Create some HTML for first pay date and pay period
                $firstPayDateHTML = '<tr>
                                         <td colspan=2 height="39" align="left" valign="top">
                                            <strong>Pay Period:</strong>
                                            <input name="payDateStart" id="payDateStart" type="datetime-local" step=1 class="intext" style="width: 100%;"  ' . $fieldsDisabled . ' value="' . str_replace(" ","T",$firstPayDate) . '" />
                                            <br><br>
                                         </td>
                                     </tr>';
                $payPeriodHTML = '<tr>
                                      <td height="39" align="left">
                                         <br>
                                         <strong>Pay Frequency:</strong>
                                      </td>
                                      <td height="39" align="left">
                                         ' . $db->getTypeAsSelectOptions('users', 'PayPeriod', 'PayPeriod', $payPeriod, null, '', false, $fieldsDisabled) . '
                                      </td>
                                  </tr>';
            }
        }
        
        // Determin if the user I am looking at is a main company user
        $dateOfAdditionText="Add Date:";
        if ($suEmployee==1 && $companyID==1){
            // Change the date of addition to clarify it is for the date the employee started
            $dateOfAdditionText="Start Date:";
        }
        
        // Set the blanks validation script to nothing at first
        $noteValidationHTML="";
              
        // Setup the template info as though it has NOT had one applied
        $templateInfoHTML='
            <div name="saveAsTemplateGroup" id="saveAsTemplateGroup">
                <input type="hidden" id="originalTemplateID" name="originalTemplateID" value="' . $templateID . '"/>
                <input type="hidden" id="originalTemplateName" name="originalTemplateName" value="' . $templateName . '"/>
                <table width="100%">
                    <tr width="100%">
                    <tr width="100%">
                        <td align="right" width="65%">
                            <strong><label name="saveAsTemplateLabel" id="saveAsTemplateLabel" for="saveAsTemplate"> Save As Template</label></strong>
                            <input name="saveAsTemplate" id="saveAsTemplate" type="checkbox" onchange="document.getElementById(\'saveAsTemplateName\').disabled=!this.checked;"/>
                        </td>
                        <td align="left" width="35%">
                            <input name="saveAsTemplateName" id="saveAsTemplateName" type="text" class="intext" maxlength="50" style="width: 100%;"  value="' . $templateName . '" disabled/>
                        </td>
                    </tr>
                </table>
            </div>
            ';
        
        // Determine if a template has been applied
        if ($templateName!=null){
            // Setup the informational name area
            $templateInfoHTML='
                <table width="100%">
                    <tr width="100%">
                        <td align="right" width="65%"><strong>Last Applied Template:</strong></td>
                        <td align="left" width="35%">' . $templateName . '</td>
                    </tr>
                </table>
                ' . $templateInfoHTML;
        }
            
        // Determine if this is for a template or not
        $infoTab='';     
        $whichForm='User';
        $templateRadioHTML='<br>';
        if ($isTemplate){
            // Set to be using the user template forms
            $whichForm='UserTemplate';
            
            // Set this up as though we are setting up a template
            $infoTab='
                    <div id="tabs-1" style="display:block;" class="childtabcontent">                            
                        <input type="hidden" id="firstName" name="firstName" value="user"/>
                        <input type="hidden" id="lastName" name="lastName" value="template"/>
                        <input type="hidden" id="initials" name="initials" value="utf"/>
                        <input type="hidden" id="newUserEMail" name="newUserEMail" value="temp@temp.com"/>
                        <input type="hidden" id="company" name="company" value="1"/>
                        <input type="hidden" id="addDate" name="addDate" value="' . $addDate . '"/>
                        <input type="hidden" id="accountStatus" name="accountStatus" value="0"/>
                        <input type="hidden" id="pw" name="pw" value="' . random_password(50) . '"/>
                        <input type="hidden" id="newAddressNumbers" name="newAddressNumbers" value="0"/>
                        <table width=100%>
                            <tr align="left" valign="top">
                                <td width="48%" align="center">
                                    <table width="100%" border="0" cellpadding="0" cellspacing="0" class="usial">
                                        <tr>
                                            <td height="39" align="left" valign="top">
                                                <strong>Template Name:</strong>
                                                <table width="100%" border="0" cellpadding="0" cellspacing="0" class="usial">
                                                    <tr>
                                                        <td height="39" align="center" valign="top">
                                                            <input name="userName" type="text" maxlength="50" class="intext" style="width: 100%;"  ' . $fieldsDisabled . ' value="' . $userName . '"/>
                                                        </td>
                                                        <td height="39" width="65%" align="Right" valign="top" style="width: 70%;"><strong>
                                                            (This must be unique)
                                                        </td>
                                                    </tr>
                                                </table>
                                            </td>
                                        </tr>
                                        ' .
                                        retrieveSUEmployee($userRow, $suEmployee) .
                                    '</table>
                                </td>
                                <td width="4%">&nbsp;</td>
                                <td width="48%" align="center">
                                    <table width="100%" border="0" cellpadding="0" cellspacing="0" class="usial">
                                        <tr>
                                          <td height="39" align="left" valign="top">
                                            <strong>Company: </strong>' . getCompanyHTML($db, $userRow, $companyID, "", $fieldsDisabled, false, false, 'width: 70%;') . '
                                          </td>
                                        </tr>
                                        <tr>
                                            <td height="39" align="left" valign="top"><strong>Account Status: </strong>' .
                                            getAccountStatusAsSelectOptions($db, $userRow, $accountStatus, $userNumber, $fieldsDisabled) .
                                            '</td>' .
                                       '</tr>
                                        <tr>
                                            <td height="39" align="left" valign="top"><strong>User Level: </strong>' .
                                            getUserLevelAsSelectOptions($userRow, $userLevel, $userNumber, $suEmployee, $fieldsDisabled) .
                                            '</td>' .
                                       '</tr>
                                    </table>
                                </td>
                            </tr>
                        </table>
                        <br>
                    </div> 
                ';  
        }
        else {
            // Setup the info tab to be a regular user
            $infoTab='
                    <div id="tabs-1" style="display:block;" class="childtabcontent">                            
                        <input type="hidden" id="newAddressNumbers" name="newAddressNumbers" value="0"/>
                        <table width=100%>
                            <tr align="left" valign="top">
                                <td width="48%" align="center">
                                    <table width="100%" border="0" cellpadding="0" cellspacing="0" class="usial">
                                        <tr>
                                            <td height="39" align="left" valign="top">
                                                <strong>First Name:</strong>
                                            </td>
                                            <td height="39" align="left" valign="top">
                                                <input name="firstName" type="text" maxlength="50" class="intext" ' . $fieldsDisabled . ' value="' . $firstName . '"/>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td height="39" align="left" valign="top">
                                                <strong>Last Name:</strong>
                                            </td>
                                            <td height="39" align="left" valign="top">
                                                <input name="lastName" type="text" maxlength="50" class="intext" ' . $fieldsDisabled . ' value="' . $lastName . '"/>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td height="39" align="left" valign="top">
                                                <strong>User Name:</strong>
                                            </td>
                                            <td height="39" align="left" valign="top">
                                                <input name="userName" title="This must be unique" type="text" maxlength="50" class="intext" ' . $fieldsDisabled . ' value="' . $userName . '"/>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td height="39" align="left" valign="top">
                                                <strong>Initials:</strong>
                                            </td>
                                            <td height="39" align="left" valign="top">
                                                <input name="initials" type="text" maxlength="3" class="intext"  ' . $fieldsDisabled . ' value="' . $initials . '"/>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td height="39" align="left" valign="top">
                                                <strong>E-Mail:</strong>
                                            </td>
                                            <td height="39" align="left" valign="top">
                                                <input name="newUserEMail" type="text" maxlength="100" class="intext" ' . $fieldsDisabled . ' value="' . $eMail . '"/>
                                            </td>
                                        </tr>' .
                                        $firstPayDateHTML .    
                                        retrieveSUEmployee($userRow, $suEmployee) .
                                    '</table>
                                </td>
                                <td width="4%">&nbsp;</td>
                                <td width="48%" align="center">
                                    <table width="100%" border="0" cellpadding="0" cellspacing="0" class="usial">
                                        <tr>
                                          <td height="39" align="left" valign="top" width="80%">
                                            <strong>Company: </strong>
                                          </td>
                                          <td height="39" align="left" valign="top">
                                            ' . getCompanyHTML($db, $userRow, $companyID, "", $fieldsDisabled, false, false, 'width:95%;') . '
                                          </td>
                                        </tr>
                                        <tr>
                                          <td height="39" align="left" valign="top">
                                            <strong>' . $dateOfAdditionText . '</strong><br>
                                          </td>
                                          <td height="39" align="left" valign="top">
                                            <input name="addDate" type="date" class="intext" style=""  ' . $fieldsDisabled . ' value="' . $addDate . '"/>
                                          </td>
                                        </tr>
                                        <tr>
                                            <td height="39" align="left" valign="top"><strong>Account Status: </strong>
                                            </td>
                                            <td height="39" align="left" valign="top">
                                                ' . getAccountStatusAsSelectOptions($db, $userRow, $accountStatus, $userNumber, $fieldsDisabled) . '
                                            </td>
                                        </tr>
                                        <tr>
                                            <td height="39" align="left" valign="top">
                                                <strong>User Level: </strong>
                                            </td>
                                            <td height="39" align="left" valign="top">
                                                ' . getUserLevelAsSelectOptions($userRow, $userLevel, $userNumber, $suEmployee, $fieldsDisabled) . '
                                            </td>
                                        </tr>
                                        <tr>
                                            <td height="39" align="left" valign="top">
                                                <strong>Password:</strong>
                                            </td>
                                            <td height="39" align="left" valign="top">
                                                <input name="pw" type="password" class="intext" style="width:95%;" value="' . $password . '" ' . $passwordDisabled . '/>
                                            </td>
                                        </tr>' .
                                        $hourlyPayHTML .
                                        $payPeriodHTML .    
                                    '
                                    </table>
                                </td>
                            </tr>
                            <tr width=100%>
                                <td colspan=4 width=100%>
                                    </table>' .
                                    retrieveCurrentAddresses($db, $userRow, $userNumber, 'UserID') .
                                    '<strong>New Addresses: </strong>
                                    <div id="newAddresses" style="margin: 5 auto; width: 100%; ">
                                    </div>
                                </td>
                            </tr>
                        </table>
                        <p align="right" style="font-weight: bold;font-size: 12px;">
                            <button type="button" onClick="addNewAddress_NicelyFormedRow(\'USER\')" align="right">Add New Address</button>
                        </p>
                        ' 
                        .
                        checkThenGetNotesDiv($db, $userRow, $userNumber, 'EMPLOYEE', $noteValidationHTML)
                        .
                        '
                        <br>
                    </div> 
                ';   
            
            // Determine if this is the appropriate user
            if (($userRow["UserLevel"]=='SU' || $userRow["UserLevel"]=='EXECUTIVE') && 
                ($userRow["SUEmployee"]==1)){
                // Setup the template radio button for this user
                $templateRadioHTML= '
                            <table width="100%">
                                <tr>
                                    <td width="33%">
                                        <fieldset style="border:none;">
                                            <input type="radio" name="applyPreferencesRadio" id="applyPreferencesRadio" value="-1" checked="checked" onchange="javacript:div_hide(\'userToCopy\');div_hide(\'userTemplateToCopy\');div_show(\'saveAsTemplateGroup\');"><b>NONE</b>
                                            <input type="radio" name="applyPreferencesRadio" id="applyPreferencesRadio" value="0" onchange="javacript:div_hide(\'userTemplateToCopy\');div_show(\'userToCopy\');div_hide(\'saveAsTemplateGroup\');"><b>USER</b>
                                            <input type="radio" name="applyPreferencesRadio" id="applyPreferencesRadio" value="1" onchange="javacript:div_hide(\'userToCopy\');div_show(\'userTemplateToCopy\');div_hide(\'saveAsTemplateGroup\');"><b>TEMPLATE</b>
                                        </fieldset>
                                    </td>
                                    <td width="33%">
                                        ' 
                                        .
                                        getUsersToCopyAsSelectOptions($db, $userRow, 'display:none;') . '' .
                                        getUsersToCopyAsSelectOptions($db, $userRow,'display:none;','',true) 
                                        . 
                                        '
                                    </td>
                                    <td width="34%" align="right">
                                    '
                                    .
                                    $templateInfoHTML
                                    .
                                    '
                                    </td>
                                </tr>
                            </table>
                        ';
            }
        }
            
        return '
            <form action="' . $modifyType . $whichForm . '.php?updateUserID=' . $userNumber . '"  method="post" name="' . $modifyType . 'User" id="' . $modifyType . 'User" enctype="multipart/form-data">  
                <div id="updateDiv">
                    <input id="formSubmit" type="submit" onclick="this.disabled=true; this.form.submit();" style="pointer-events: auto; cursor: hand;" value="' . $modifyType . ' user"/>
                    <input type="hidden" id="formSubmitted" name="formSubmitted" value="TRUE"/>
                    <input type="hidden" name="MAX_FILE_SIZE" id="maxFileSize" value="4294967296"/>
                </div> 
                '
                .
                $templateRadioHTML
                .
                '
                <div id="tabs">
                    <button class="childtablink" type="button" onclick="openChildPage(\'tabs-1\', this);" style="border-left: 2px solid forestgreen; border-right: 2px solid forestgreen; border-top: 2px solid forestgreen; border-bottom: none;" title="More specific and personal information.">Info</button>
                    <button class="childtablink" type="button" onclick="openChildPage(\'tabs-2\', this);" title="General non-specific user preferences">Preferences</button>
                    ' . 
                    $notificationsButton .
                    $accessibilityButton .
                    $infoTab .
                    $preferenceTab .
                    $notificationsTab .
                    $accessibilityTab .
                '</div>
            </form>
            <script language="JavaScript">
                // Code for validating the form
                // Visit http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
                // for details
                var frmvalidator = new Validator("' . $modifyType . 'User", "formSubmit");
                frmvalidator.addValidation("firstName",
                                           "required",
                                           "There must be a value for first name.");
                frmvalidator.addValidation("lastName",
                                           "required",
                                           "There must be a value for last name.");
                frmvalidator.addValidation("userName",
                                           "required",
                                           "There must be a value for user name.");
                frmvalidator.addValidation("initials",
                                           "required",
                                           "There must be a value for the initials.");
                frmvalidator.addValidation("newUserEMail",
                                           "required",
                                           "There must be a value for E-Mail.");
                frmvalidator.addValidation("newUserEMail",
                                           "email",
                                           "The e-mail must be in the structure of email@server.com.");
                frmvalidator.addValidation("pw",
                                           "required",
                                           "There must be a value for password."); 
                '
                .
                $hourlyPayValidationJS
                .
                '
                '
                .
                $noteValidationHTML
                . 
                '
            </script>';

    }

    function getUserStatusNotificationsCheckboxes($db, $userRow, $forUserID){
        // Initialize the return
        $result = '';

        try {
            // Create the query to run to get all of the statuses
            $sql='SELECT * ' .
                 'FROM status s ' .
                 'ORDER BY s.ProcessOrder;';
            
            // Query the database for the user 
            $rows = $db->queryDB($sql, $userRow, "user_presentation Form occurance 3");

            // Determine if some rows were returned
            if ($rows == null){
                return $result;
            }
            else{
                // Loop through the returned results
                while ($row=mysqli_fetch_array($rows)){
                    // Reset the checked variable
                    $mainTaskStatusChecked="";
                    $taskStatusChecked="";
                    $noStatusChecked="checked";
                    
                    // Create a query to see if it is in the link table
                    $sql='SELECT * ' .
                         'FROM usertostatuslinker usl ' .
                         'WHERE usl.StatusID=' . $row["StatusID"] . ' ' .
                         'AND usl.UserID=' . $forUserID . ';';
                         
                    // Attempt to change all of the rows that need to be changed
                    $uslrow = $db->queryDB($sql, $userRow, "user_presentation Form occurance 4");

                    // Determine if we only have one row
                    if (mysqli_num_rows($uslrow)==1){
                        // Attempt to get the row
                        $uslrowAssoc = $uslrow->fetch_assoc();
                        
                        // Determine which one they chose
                        switch ($uslrowAssoc["NotificationCategory"]) {
                            case 'ALL':
                                // Setup the checked boxes appropriately
                                $mainTaskStatusChecked="checked";
                                $taskStatusChecked="checked";
                                $noStatusChecked="";

                                // Break out of this switch
                                break;

                            case 'PARENT':
                                // Setup the checked boxes appropriately
                                $mainTaskStatusChecked="checked";
                                $noStatusChecked="";

                                // Break out of this switch
                                break;

                            case 'CHILD':
                                // Setup the checked boxes appropriately
                                $taskStatusChecked="checked";
                                $noStatusChecked="";

                                // Break out of this switch
                                break;
                        }
                    }

                    // Ceate the checkbox for this status with status ID in the name for further reference on database update.
                    $result = $result . '
                                <tr>
                                    <td width="15%" style="text-align:center;">
                                      <input name="' . $row["StatusID"] . '_MainTaskStatusChangeNotification" id="' . $row["StatusID"] . '_MainTaskStatusChangeNotification" type="checkbox" onchange="sortStatusCheckboxState(this, ' . $row["StatusID"] . ');" ' . $mainTaskStatusChecked . '/>
                                    </td>
                                    <td width="15%" style="text-align:center;">
                                      <input name="' . $row["StatusID"] . '_StatusChangeToNotification" id="' . $row["StatusID"] . '_StatusChangeToNotification" type="checkbox" onchange="sortStatusCheckboxState(this, ' . $row["StatusID"] . ');" ' . $taskStatusChecked . '/>
                                    </td>
                                    <td width="15%" style="text-align:center;">
                                      <input name="' . $row["StatusID"] . '_NoStatusChangeToNotification" id="' . $row["StatusID"] . '_NoStatusChangeToNotification" type="checkbox" onchange="sortStatusCheckboxState(this, ' . $row["StatusID"] . ');" ' . $noStatusChecked . '/>
                                    </td>
                                    <td width="5%" style="text-align:left;">
                                    </td>
                                    <td width="50%" style="text-align:left;">
                                      <strong><label>' . $row["Name"] . '</label></strong>
                                    </td>
                                </tr>
                        ';
                }
            }
        } catch (Exception $ex) {
            // Send back whatever was made before the error
            return $result;
        }
        
        // Send back whatever was made 
        return '
                <div style="text-align: center;">
                    <strong>Task Status Notifications</strong>
                    <br><br>
                    <table width="100%">
                        <tr width="100%"> 
                            <td width="15%" style="text-align:center;">
                                Main Task
                            </td>
                            <td width="15%" style="text-align:center;">
                                Sub Tasks
                            </td>
                            <td width="15%" style="text-align:center;">
                                None
                            </td>
                            <td width="5%" style="text-align:left;">
                            </td>
                            <td width="50%" style="text-align:left;">
                                Status Name
                            </td>
                        </tr>
                    </table>
                </div>
                <div style="height: 200px; overflow: scroll;">
                    <table width="100%">
                        ' . 
                        $result . 
                   '</table>
                </div>';
    }

    function getUserStatusViewableCheckboxes($db, $userRow, $forUserID){
        // Initialize the return
        $result = '';

        try {
            // Create the query to run to get all of the statuses
            $sql='SELECT * ' .
                 'FROM status s ' .
                 'ORDER BY s.ProcessOrder;';
            
            // Query the database for the user 
            $rows = $db->queryDB($sql, $userRow, "user_presentation Form occurance 5");

            // Determine if some rows were returned
            if ($rows == null){
                return $result;
            }
            else{
                // Loop through the returned results
                while ($row=mysqli_fetch_array($rows)){
                    // Reset the checked variable
                    $taskStatusViewableChecked="checked";
                    
                    // Create a query to see if it is in the link table
                    $sql='SELECT * ' .
                         'FROM usertostatusviewinglinker usvl ' .
                         'WHERE usvl.StatusID=' . $row["StatusID"] . ' ' .
                         'AND usvl.UserID=' . $forUserID . ';';
                         
                    // Attempt to change all of the rows that need to be changed
                    $uslrow = $db->queryDB($sql, $userRow, "user_presentation Form occurance 6");

                    // Determine if we only have one row
                    if (mysqli_num_rows($uslrow)==1){
                        // Attempt to get the row
                        $uslrowAssoc = $uslrow->fetch_assoc();
                        
                        // Determine which one they chose
                        if ($uslrowAssoc["ViewCategory"]='NOT VIEWABLE'){
                                // Setup the checked boxes appropriately
                                $taskStatusViewableChecked="";
                        }
                    }

                    // Ceate the checkbox for this status with status ID in the name for further reference on database update.
                    $result = $result . '
                                <tr>
                                    <td width="39%" style="text-align:center;">
                                      <input name="' . $row["StatusID"] . '_TaskStatusViewableValue" id="' . $row["StatusID"] . '_TaskStatusViewableValue" type="checkbox" ' . $taskStatusViewableChecked . '/>
                                    </td>
                                    <td width="2%" style="text-align:center;">
                                    </td>
                                    <td width="59%" style="text-align:left;">
                                      <strong><label>' . $row["Name"] . '</label></strong>
                                    </td>
                                </tr>
                        ';
                }
            }
        } catch (Exception $ex) {
            // Send back whatever was made before the error
            return $result;
        }
        
        // Send back whatever was made 
        return '
                <div style="text-align: center;">
                    <strong>Task Status Viewable Values</strong>
                    <br><br>
                    <table width="100%">
                        <tr width="100%"> 
                            <td width="39%" style="text-align:center;">
                                Viewable
                            </td>
                            <td width="2%" style="text-align:center;">
                            </td>
                            <td width="59%" style="text-align:left;">
                                Status Name
                            </td>
                        </tr>
                    </table>
                </div>
                <div style="height: 200px; overflow: scroll;">
                    <table width="100%">
                        ' . 
                        $result . 
                   '</table>
                </div>';
    }

    function updateUserStatusViewableCheckboxes($db, $userRow, $forUserID){
        // Initialize the success return as successful at first
        $success = 1;

        try {
            // Determine if this user should even be updating these preferences
            if ($forUserID==$userRow["UserID"] || 
                ($userRow["UserLevel"]=='EXECUTIVE' && $userRow["CompanyID"]==1 && $userRow["SUEmployee"]==1 && $userRow["AccountStatus"]=='ACTIVE') ||
                $userRow["UserLevel"]=='SU'){
                // Create the query to run to get all of the statuses
                $sql='SELECT * ' .
                     'FROM status s ' .
                     'ORDER BY s.ProcessOrder;';

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

                // Determine if some rows were returned
                if ($rows != null){
                    // Delete all at first to cut down on queries.  It is easiest/fastest that way
                    $sql='DELETE FROM usertostatusviewinglinker ' . 
                         'WHERE UserID=' . $forUserID . ';';

                    // Delete row 
                    $db->queryDB($sql, $userRow, "user_presentation Form occurance 8");

                    // Loop through the returned results
                    while ($row=mysqli_fetch_array($rows)){
                        // Get the current status value
                        $taskStatusViewableUpdate=(isset($_POST[$row["StatusID"] . '_TaskStatusViewableValue'])?1:0);

                        // Determine if it NOT viewable for this person
                        if ($taskStatusViewableUpdate!=1){
                            // Create a query to add this row to the link table
                            $sql='INSERT INTO usertostatusviewinglinker (UserID, StatusID, ViewCategory) ' . 
                                 'VALUES (' . $forUserID . ', ' . $row["StatusID"] . ', "NOT VIEWABLE");';

                            // Get the task row that is being deleted
                            $db->queryDB($sql, $userRow, "user_presentation Form occurance 9");
                        }
                    }
                }
            }
        } catch (Exception $ex) {
            // fail the success
            $success = 0;
        }
        
        // Send back whatever was made 
        return $success;
    }

    function updateUserStatusNotificationsCheckboxes ($db, $userRow, $forUserID){
        // Initialize the success return as successful at first
        $success = 1;

        try {
            // Determine if this user should even be updating these preferences
            if ($userRow["UserLevel"]=='SU' ||
                $userRow["UserLevel"]=='EXECUTIVE') {
                // Create the query to run to get all of the statuses
                $sql='SELECT * ' .
                     'FROM status s ' .
                     'ORDER BY s.ProcessOrder;';

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

                // Determine if some rows were returned
                if ($rows != null){
                    // Delete all at first to cut down on queries.  It is easiest/fastest that way
                    $sql='DELETE FROM usertostatuslinker ' . 
                         'WHERE UserID=' . $forUserID . ';';

                    // Delete rows
                    $db->queryDB($sql, $userRow, "user_presentation Form occurance 11");

                    // Loop through the returned results
                    while ($row=mysqli_fetch_array($rows)){
                        // Get the current status value
                        $mainTaskStatusUpdate=(isset($_POST[$row["StatusID"] . '_MainTaskStatusChangeNotification'])?1:0);
                        $taskStatusUpdate=(isset($_POST[$row["StatusID"] . '_StatusChangeToNotification'])?1:0);
                        $noStatusUpdate=(isset($_POST[$row["StatusID"] . '_NoStatusChangeToNotification'])?1:0);

                        // Determine if it is NOT removing status updates
                        if ($noStatusUpdate!=1){
                            // Set a default of nothing
                            $notificationCategory='';

                            // Determine if it is both at first
                            if ($mainTaskStatusUpdate==1 && $taskStatusUpdate==1){
                                // Set the category to all
                                $notificationCategory='ALL';
                            }
                            else if ($taskStatusUpdate==1){
                                // Set the category to child
                                $notificationCategory='CHILD';
                            }
                            else if ($mainTaskStatusUpdate==1){
                                // Set the category to parent only
                                $notificationCategory='PARENT';
                            }

                            // Create a query to add this row to the link table
                            $sql='INSERT INTO usertostatuslinker (UserID, StatusID, NotificationCategory) ' . 
                                 'VALUES (' . $forUserID . ', ' . $row["StatusID"] . ', "' . $notificationCategory . '");';

                            // Get the task row that is being deleted
                            $db->queryDB($sql, $userRow, "user_presentation Form occurance 12");
                        }
                    }
                }
            }
        } catch (Exception $ex) {
            // fail the success
            $success = 0;
        }
        
        // Send back whatever was made 
        return $success;
    }

    function retrieveLaborCategoriesAsList($db, $userRow, $sortNumber){
        // Init variables
        $updateableTitleRowCellHTML = '';
        $updateableLaborCategoryRowCellHTML = '';
        $sort = "LaborCategoryID, Name, Description ";

        // Determine if there is actually a sort passed in
        if ($sortNumber!=""){
            // Determine which sort the person wants
            switch ($sortNumber) {
                case 1:
                    // Sort as Name then Description
                    $sort = "Name, Description ";

                    break;
                case 5:
                    // Sort as Description then Name
                    $sort = "Description, Name ";

                    break;
                case 10:
                    // Sort as work type, Name, then Description
                    $sort = "IsOnTheClock, Name, Description ";

                    break;
            }
        }

        // Determine if they are at a level to manage labor category
        switch ($userRow["UserLevel"]){
            case 'MANAGEMENT':
            case 'EXECUTIVE':
            case 'SU':
                $updateableTitleRowCellHTML = '
                            <div class="cell updateCell">
                                <p><b>Edit</b></p>
                            </div>
                        ';

                break;
        }
        
        // Initialize the return
        $result = 
            '<input type="hidden" id="sortNumber" name="sortNumber" value="' . $sortNumber . '"/>
             <li class="ui-state-default ui-state-disabled Table">
                <div class="Heading">
                    <div class="cell nameCell" onclick="document.getElementById(\'sortNumber\').value=1; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Name</b></p>
                    </div>
                    <div class="cell descCell" onclick="document.getElementById(\'sortNumber\').value=5; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Description</b></p>
                    </div> 
                    <div class="cell typeCell" onclick="document.getElementById(\'sortNumber\').value=10; CreateAndGotoSearchOptions();" style="cursor: pointer;">
                        <p><b>Type</b></p>
                    </div>' . 
                    $updateableTitleRowCellHTML . '
                </div>
             </li>';

        try {
            // Setup the query to get all labor categories
            $sql='SELECT *
                  FROM laborcategories 
                  ORDER BY ' . $sort . ';';

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

            // Determine if there are any rows before attempting to loop through them
            if ($rows != null && 
                mysqli_num_rows($rows)>0){

                // Loop through the returned results
                $amount=0;
                $lastOneUpdated = '';
                while ($row=mysqli_fetch_array($rows)){
                    // Determine if this is an 'on the clock' job
                    $rowColor="RED";
                    if ($row["IsOnTheClock"]==1){
                        // Set the row color to green
                        $rowColor="GREEN";
                    }
                    
                    // Set it up as though it is NOT deletable
                    $updateableLaborCategoryRowCellHTML = '
                        <div class="cell updateCell">
                            <span>
                                <table>
                                    <tr>
                                        <td>
                                        </td>
                                        <td>
                                            <input type="button" style="font-size:11px;" value="..." title="Edit this labor category." ' . 
                                            'onclick="javascript:window.location=\'updateLaborCategory.php?updateLaborCategoryID=' . $row["LaborCategoryID"] . '\';"/>
                                        </td>
                                    </tr>
                                </table>
                            </span>
                        </div>
                        ';
                    
                    // Determine if this is the general labor option or the clocked out option
                    if ($row["LaborCategoryID"]>2){
                        // Assign the delete button attributes as though deletion is an option
                        $deleteButtonTitle = 'Remove this labor category.';
                        $deleteButtonOnClick = 'onclick="javascript:if (confirm(\'Are you sure you want to delete this labor category?\')) ' .
                                               '{window.location=\'redirectors/delete_labor_category.php?deleteLaborCategoryID=' . $row["LaborCategoryID"] . '\';}"';
                        
                        // Give the the delete option
                        $updateableLaborCategoryRowCellHTML = '
                            <div class="cell updateCell">
                                <span>
                                    <table>
                                        <tr>
                                            <td>
                                                <input type="button" style="font-size:11px; color:LIMEGREEN;" value="X" title="' . 
                                                $deleteButtonTitle . '" ' . $deleteButtonOnClick . '/>
                                            </td>
                                            <td>
                                                <input type="button" style="font-size:11px;" value="..." title="Edit this labor category." ' . 
                                                'onclick="javascript:window.location=\'updateLaborCategory.php?updateLaborCategoryID=' . $row["LaborCategoryID"] . '\';"/>
                                            </td>
                                        </tr>
                                    </table>
                                </span>
                            </div>
                            ';

                    }
                    
                    // Increment the row
                    $amount++;

                    // Add this option to the select
                    $result = $result .
                        '<li class="ui-state-default Table" >
                            <div class="Row" style="background-color: ' . $row["RowColor"] . '; border-style: solid; border-color: BLACK;">
                                <div class="cell nameCell">
                                    <span>
                                        <p>' . $row["Name"] . '</p>
                                    </span>
                                </div> 
                                <div class="cell descCell">
                                    <span>
                                        <p>' . $row["Description"] . '</p>
                                    </span>
                                </div>
                                <div class="cell typeCell" style="background-color: ' . $rowColor . ';";>
                                    <span>
                                        <p>' . (($row["IsOnTheClock"]==1)?"On The Clock":"Off The Clock") . '</p>
                                    </span>
                                </div>' . 
                                $updateableLaborCategoryRowCellHTML . '
                            </div>
                        </li>';
                }
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }
    
    function getLaborCategory($db, $userRow, $laborCategoryID){
        // Init all of the settings to the appropriate values
        $name = '';
        $description = '';
        $rowColor = 'FFFFFF';
        $isOnTheClockHTML = '';
        $isDailyResetHTML = '';
        $modifyType = 'add';
        
        // Determine if this is an update or not
        $laborCategoryAssocTask = null;
        if ($laborCategoryID>0){
            // Determine if the user editing is part of the main company
            if ($userRow["CompanyID"]!=1){
                // We should not even be in here if we are not a main company employee
                return;
            }
            
            // Create the query to get the labor category specified
            $sql = 'SELECT * FROM laborcategories WHERE LaborCategoryID = ' . $laborCategoryID . ';';

            // Attempt to get the labor category
            $secondaryStatusRow = $db->queryDB($sql, $userRow, "user_presentation Form occurance 14");

            // Attempt to get the secondary status row
            $laborCategoryAssocTask = $secondaryStatusRow->fetch_assoc();

            // Set the things we can
            $laborCategoryID = $laborCategoryAssocTask["LaborCategoryID"];
            $name = $laborCategoryAssocTask["Name"];
            $description = $laborCategoryAssocTask["Description"];
            $rowColor = $laborCategoryAssocTask["RowColor"];
            
            // Determine if this is clocked in work
            if ($laborCategoryAssocTask["IsOnTheClock"]==1){
                // Set it to what we got in
                $isOnTheClockHTML = 'checked';
            }

            // Determine if this is a daily reset category 
            if ($laborCategoryAssocTask["IsDailyReset"]==1){
                // Set it to what we got in
                $isDailyResetHTML = 'checked';
            }

            $modifyType = 'update';
        }

        return '
            <form action="' . $modifyType . 'LaborCategory.php?updateLaborCategoryID=' . $laborCategoryID . '" method="post" name="' . $modifyType . 'LaborCategory" enctype="multipart/form-data">  
                <table width=100%>
                    <tr width=100%>
                        <td colspan=1 height="39" align="left" valign="middle">
                            <strong>Labor Category Name:</strong>&nbsp;&nbsp; 
                        </td>
                        <td colspan=3 height="39" align="left" valign="middle" width="75%">
                            <input name="name" type="text" maxlength="25" class="intext" style="width: 100%;" value="' . $name . '"/>
                        </td>
                    </tr>
                    <tr width=100%>
                        <td colspan=1 height="39" align="left" valign="middle">
                            <strong>Labor Category Color:</strong>&nbsp;&nbsp;
                        </td>
                        <td colspan=1 height="39" align="left" valign="middle">
                            <script type="text/javascript">        
                              $(document).ready(
                                function()
                                {
                                  $("#rowColor").jPicker({window:{position:{x:"center",y:"center"},expandable: true,liveUpdate: true}});
                                });
                            </script>
                            <input id="rowColor" name="rowColor" type="text" maxlength="6" value="' . $rowColor . '" style="width: 60px; height: 20px; overflow: auto; resize:none;"/>
                        </td>
                        <td colspan=1 height="39" align="left" valign="middle">
                            <input name="isOnTheClock" id="isOnTheClock" type="checkbox" ' . $isOnTheClockHTML . '/>
                            <strong><label for="isOnTheClock"> Clocked In Work</label></strong>
                        </td>
                        <td colspan=1 height="39" align="left" valign="middle">
                            <input name="isDailyReset" id="isDailyReset" type="checkbox" ' . $isDailyResetHTML . '/>
                            <strong><label for="isOnTheClock"> Daily Reset</label></strong>
                        </td>
                    </tr>
                    <tr width=100%>
                        <td colspan=4 width="100%"><strong>Labor Category Description (1000 characters)</strong><br> 
                            <textarea name="description" maxlength="1000" class="intext" style="width: 100%; height: 100px; overflow: auto; resize:vertical;">' .
                            $description .
                            '</textarea>
                        </td>
                    </tr>
                </table>
                <p align="right">
                    <input type="hidden" id="formSubmitted" name="formSubmitted" value="TRUE"/>
                    <input id="formSubmit" type="submit" style="cursor: hand; cursor: pointer;" value="' . $modifyType . ' Labor Category" />
                </p>
            </form>
            <script language="JavaScript">
                // Code for validating the form
                // Visit http://www.javascript-coder.com/html-form/javascript-form-validation.phtml
                // for details
                var frmvalidator = new Validator("' . $modifyType . 'LaborCategory", "formSubmit");
                frmvalidator.addValidation("name",
                                           "required",
                                           "Please enter the labor category name.");
            </script>';
    }
    
    function getUsersToCopyAsSelectOptions($db, $userRow, $style='', $onchange='', $userTemplateOnly=false){
        // Initialize the return
        $result = '';
        try {
            // Determine if this is an SU user
            if ($userRow["CompanyID"]==1){
                // Create the query to run
                $sql='SELECT UserName, FirstName, LastName, UserID 
                      FROM users
                      WHERE UserTemplateOnly=0
                      ORDER BY UserName;';
                
                // Set the control name
                $controlName='userToCopy';

                // Determine if it is for user template only or not
                if ($userTemplateOnly){
                    // Create the query to run
                    $sql='SELECT UserName, FirstName, LastName, UserID 
                          FROM users
                          WHERE UserTemplateOnly=1
                          ORDER BY UserName;';
                    
                    // Set the control name
                    $controlName='userTemplateToCopy';
                }
                
                // Query the database for the labor categories
                $rows = $db->queryDB($sql, $userRow, "user_presentation Form occurance 15");

                // If there are rows, then they are good to go.
                if ($rows == null){
                    return $result;
                }
                else{
                    // Loop through the status rows
                    $mainTitleDescription='';
                    while ($row=mysqli_fetch_array($rows)){
                        // Create the query to run
                        $displayedName='';

                        // Determine if it is for user template only or not
                        if ($userTemplateOnly){
                            // Set to only display the template name
                            $displayedName=$row["UserName"];
                        }
                        else{
                            // Set it to the name of the user
                            $displayedName=$row["UserName"] . ' (' . $row["FirstName"] . ' ' . $row["LastName"] . ')';
                        }

                        // Add this option to the select
                        $result=$result . '<option value="' . $row["UserID"] . '">' . $displayedName . ' </option>';
                    }
                    
                    // Start the return with the beginning of the select
                    $result='<select title="' . $mainTitleDescription . '" name="' . $controlName . '" id="' . $controlName . '" style="' . $style . '" onchange="' . $onchange . '">' 
                                . $result . 
                            '</select>
                            ';
                }
            }
        } catch (Exception $ex) {
            // Assign the output string as to what happened
            return $result;
        }

        // Return whatever we got
        return $result;
    }
    
    function copyPreferences($db, $userRow, $inUserNumberToCopyTo, $inUserIDToCopyFrom){
        $result = "";
        
        // grabe the incoming variables into local ones
        $userNumberToCopyTo = $inUserNumberToCopyTo;
        $userIDToCopyFrom = $inUserIDToCopyFrom;
        
        try {
            // Create a query to check for the task to copy into
            $sql='SELECT * FROM users WHERE UserID=' . $userNumberToCopyTo . ';';
            
            // Run the query
            $copyToUser = $db->queryDB($sql, $userRow, "user_preferences Form occurance 16");
                
            // Check the results of the queries.  If either returns a row, then that could be cause for abort
            if (mysqli_num_rows($copyToUser)<>1){
                // Send and error message back
                return 'ABORT PREFERENCE COPY (user_preferences)::There ' . 
                       'is no user to copy preferences into.';
            }
            
            // Create a query to check for the task to copy from
            $sql='SELECT * FROM users WHERE UserID=' . $userIDToCopyFrom . ';';
            
            // Run the query
            $copyFromUser = $db->queryDB($sql, $userRow, "user_preferences Form occurance 17");
                
            // Check the results of the queries.  If either returns a row, then that could be cause for abort
            if (mysqli_num_rows($copyFromUser)<>1){
                // Send and error message back
                return 'ABORT PREFERENCE COPY (user_preferences)::There ' . 
                       'is no user or template to copy preferences from.';
            }
            
            // Attempt to get the copy from user row
            $copyFromUserAssoc = $copyFromUser->fetch_assoc();
        
            // Now we can clear the e-mail preferences table for the copy to user. Create a query for this.
            $sql='DELETE FROM usertostatuslinker WHERE UserID=' . $userNumberToCopyTo . ';';
            
            // Run the query
            $db->queryDB($sql, $userRow, "user_preferences Form occurance 18");
            
            // Now we can clear the view preferences table for the copy to user. Create a query for this.
            $sql='DELETE FROM usertostatusviewinglinker WHERE UserID=' . $userNumberToCopyTo . ';';
            
            // Run the query
            $db->queryDB($sql, $userRow, "user_preferences Form occurance 19");

            // Now we can clear the machine view preferences table for the copy to user. Create a query for this.
            $sql='DELETE FROM usertomachineviewinglinker WHERE UserID=' . $userNumberToCopyTo . ';';
            
            // Run the query
            $db->queryDB($sql, $userRow, "user_preferences Form occurance 20");

            // Create a query to insert all e-mail preferences from the 'CopyFrom' user to the 'CopyTo' user 
            $sql='INSERT INTO usertostatuslinker (UserID, StatusID, NotificationCategory) ' .
                 'SELECT ' . $userNumberToCopyTo . ', StatusID, NotificationCategory ' . 
                 'FROM usertostatuslinker WHERE UserID=' . $userIDToCopyFrom . ';';
            
            // run the insert query
            $db->queryDB($sql, $userRow, "user_preferences Form occurance 21");
            
            // Create a query to insert all view preferences from the 'CopyFrom' user to the 'CopyTo' user 
            $sql='INSERT INTO usertostatusviewinglinker (UserID, StatusID, ViewCategory) ' .
                 'SELECT ' . $userNumberToCopyTo . ', StatusID, ViewCategory ' . 
                 'FROM usertostatusviewinglinker WHERE UserID=' . $userIDToCopyFrom . ';';
            
            // run the insert query
            $db->queryDB($sql, $userRow, "user_preferences Form occurance 22");
            
            // Create a query to insert all machine view preferences from the 'CopyFrom' user to the 'CopyTo' user 
            $sql='INSERT INTO usertomachineviewinglinker (UserID, MachineID, ViewCategory) ' .
                 'SELECT ' . $userNumberToCopyTo . ', MachineID, ViewCategory ' . 
                 'FROM usertomachineviewinglinker WHERE UserID=' . $userIDToCopyFrom . ';';
            
            // run the insert query
            $db->queryDB($sql, $userRow, "user_preferences Form occurance 23");
            
            // Create a query to update everything in the users table from one to the other
            $sql='UPDATE users SET ' .
                 'AccountStatus="' . $copyFromUserAssoc["AccountStatus"] . '"' .
                 ', CanAddAllParent=' . $copyFromUserAssoc["CanAddAllParent"] . 
                 ', CanCopyTasks=' . $copyFromUserAssoc["CanCopyTasks"] . 
                 ', CanModify=' . $copyFromUserAssoc["CanModify"] . 
                 ', CanModifyChildren=' . $copyFromUserAssoc["CanModifyChildren"] . 
                 ', CannotViewUnsubmittedBlanks=' . $copyFromUserAssoc["CannotViewUnsubmittedBlanks"] . 
                 ', DefaultNewUserPassword="' . $copyFromUserAssoc["DefaultNewUserPassword"] . '"' .
                 ', LastAppliedUserTemplateID=' . $copyFromUserAssoc["UserID"] . 
                 ', PrimaryTaskType="' . $copyFromUserAssoc["PrimaryTaskType"] . '"' .
                 ', ReceiveAddTaskUpdate=' . $copyFromUserAssoc["ReceiveAddTaskUpdate"] . 
                 ', ReceiveAttachmentUpdate=' . $copyFromUserAssoc["ReceiveAttachmentUpdate"] . 
                 ', ReceiveBlankCutNotificationUpdate=' . $copyFromUserAssoc["ReceiveBlankCutNotificationUpdate"] . 
                 ', ReceiveMaterialLowStockNotificationUpdate=' . $copyFromUserAssoc["ReceiveMaterialLowStockNotificationUpdate"] . 
                 ', ReceiveNotesNotificationUpdate=' . $copyFromUserAssoc["ReceiveNotesNotificationUpdate"] . 
                 ', ReceivePayPeriodRolloverUpdate=' . $copyFromUserAssoc["ReceivePayPeriodRolloverUpdate"] . 
                 ', ReceivePriorityChangeUpdate=' . $copyFromUserAssoc["ReceivePriorityChangeUpdate"] . 
                 ', ReceiveToolLowStockNotificationUpdate=' . $copyFromUserAssoc["ReceiveToolLowStockNotificationUpdate"] . 
                 ', RefreshRate=' . $copyFromUserAssoc["RefreshRate"] . 
                 ', ShowWhatFinishedState=' . $copyFromUserAssoc["ShowWhatFinishedState"] . 
                 ', SilenceAllTaskNotifications=' . $copyFromUserAssoc["SilenceAllTaskNotifications"] . 
                 ', StandardLaborCategoryID=' . $copyFromUserAssoc["StandardLaborCategoryID"] . 
                 ', SUEmployee=' . $copyFromUserAssoc["SUEmployee"] . 
                 ', TasksPerPage=' . $copyFromUserAssoc["TasksPerPage"] . 
                 ', UserLevel="' . $copyFromUserAssoc["UserLevel"] . '"' .
                 ' WHERE UserID=' . $userNumberToCopyTo . ';';
            
            // Run the query to update the preferences
            $db->queryDB($sql, $userRow, "updateUser Form occurance 22");
        } catch (Exception $ex) {
            // Set up an error message for the exception
            return 'ABORT PREFERENCE COPY (user_preferences)::There was ' . 
                   'an error trying to copy preferences from user ID ' . $userIDToCopyFrom . ' ' .
                   'to user ID ' . $userNumberToCopyTo . '.' .
                   '\n\n The error is: \n' . $ex->getMessage();
        }

        // Return whatever we got
        return $result;
    }
    
    // -1 = Level to Check is a lower level than the Level to Check Against
    //  0 = Level to Check is the same as the Level to Check Against
    //  1 = Level to Check is a higher level than the Level to Check Against
    function compareUserLevel ($db, $userRow, $inLevelToCheck, $inLevelToCheckAgainst){
        // Set the default return as it is lower
        $returnValue=-1;
        
        try {
            // Since the getTypeAsArray returns the enums surrounded by single 
            // quotes, lets modify the incoming to match
            $levelToCheck = "'" . $inLevelToCheck . "'";
            $levelToCheckAgainst = "'" . $inLevelToCheckAgainst . "'";
            
            // Attempt to get the user level enum array.  Structured High to low.
            $userLevels=$db->getTypeAsArray("users", "UserLevel", false);

            // Get the position of the two strings
            $levelToCheckPosition=array_search($levelToCheck, $userLevels);
            $levelToCheckAgainstPosition=array_search($levelToCheckAgainst, $userLevels);

            // Determine if the levels are in the array
            if ($levelToCheckPosition===false){
                // throw an exception for the value not being in the array
                throw new Exception('The level to check is not a valid level. Try again.');
            }
            else if ($levelToCheckAgainstPosition===false){
                // throw an exception for the value not being in the array
                throw new Exception('The level to check against is not a valid level. Try again.');
            }

            // Determine the level difference of the two. Higher levels are lower in the array.
            $returnValue=$levelToCheckAgainstPosition<=>$levelToCheckPosition;
        } 
        catch (Exception $exc) {
            // throw the error. Let the calling function handle it.
            throw $exc;
        }
        
        // Return the result
        return $returnValue;
    }
    
    function getUserMachineViewableCheckboxes($db, $userRow, $forUserID){
        // Initialize the return
        $result = '';

        try {
            // Create the query to run to get all of the machines
            $sql='SELECT * ' .
                 'FROM machines m ' .
                 'ORDER BY m.Name;';
            
            // Query the database for the user 
            $rows = $db->queryDB($sql, $userRow, "user_presentation Form occurance 23");

            // Determine if some rows were returned
            if ($rows == null){
                return $result;
            }
            else{
                // Loop through the returned results
                while ($row=mysqli_fetch_array($rows)){
                    // Reset the checked variable
                    $machineViewableChecked="checked";
                    
                    // Create a query to see if it is in the link table
                    $sql='SELECT * ' .
                         'FROM usertomachineviewinglinker umvl ' .
                         'WHERE umvl.MachineID=' . $row["MachineID"] . ' ' .
                         'AND umvl.UserID=' . $forUserID . ';';
                         
                    // Attempt to change all of the rows that need to be changed
                    $umlrow = $db->queryDB($sql, $userRow, "user_presentation Form occurance 24");

                    // Determine if we only have one row
                    if (mysqli_num_rows($umlrow)==1){
                        // Attempt to get the row
                        $umlrowlrowAssoc = $umlrow->fetch_assoc();
                        
                        // Determine which one they chose
                        if ($umlrowlrowAssoc["ViewCategory"]='NOT VIEWABLE'){
                            // Setup the checked boxes appropriately
                            $machineViewableChecked="";
                        }
                    }

                    // Ceate the checkbox for this status with status ID in the name for further reference on database update.
                    $result = $result . '
                                <tr>
                                    <td width="39%" style="text-align:center;">
                                      <input name="' . $row["MachineID"] . '_MachineViewableValue" id="' . $row["MachineID"] . '_MachineViewableValue" type="checkbox" ' . $machineViewableChecked . '/>
                                    </td>
                                    <td width="2%" style="text-align:center;">
                                    </td>
                                    <td width="59%" style="text-align:left;">
                                      <strong><label>' . $row["Name"] . '</label></strong>
                                    </td>
                                </tr>
                        ';
                }
            }
        } catch (Exception $ex) {
            // Send back whatever was made before the error
            return $result;
        }
        
        // Send back whatever was made 
        return '
                <div style="text-align: center;">
                    <strong>Machine Viewable Values</strong>
                    <br><br>
                    <table width="100%">
                        <tr width="100%"> 
                            <td width="39%" style="text-align:center;">
                                Viewable
                            </td>
                            <td width="2%" style="text-align:center;">
                            </td>
                            <td width="59%" style="text-align:left;">
                                Machine Name
                            </td>
                        </tr>
                    </table>
                </div>
                <div style="height: 200px; overflow: scroll;">
                    <table width="100%">
                        ' . 
                        $result . 
                   '</table>
                </div>';
    }

    function updateUserMachineViewableCheckboxes($db, $userRow, $forUserID){
        // Initialize the success return as successful at first
        $success = 1;

        try {
            // Determine if this user should even be updating these preferences
            if ($forUserID==$userRow["UserID"] || 
                ($userRow["UserLevel"]=='EXECUTIVE' && $userRow["CompanyID"]==1 && $userRow["SUEmployee"]==1 && $userRow["AccountStatus"]=='ACTIVE') ||
                $userRow["UserLevel"]=='SU'){
                // Create the query to run to get all of the machines
                $sql='SELECT * ' .
                     'FROM machines m ' .
                     'ORDER BY m.Name;';

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

                // Determine if some rows were returned
                if ($rows != null){
                    // Delete all at first to cut down on queries.  It is easiest/fastest that way
                    $sql='DELETE FROM usertomachineviewinglinker ' . 
                         'WHERE UserID=' . $forUserID . ';';

                    // Delete rows 
                    $db->queryDB($sql, $userRow, "user_presentation Form occurance 26");

                    // Loop through the returned results
                    while ($row=mysqli_fetch_array($rows)){
                        // Get the current machine value
                        $machineViewableUpdate=(isset($_POST[$row["MachineID"] . '_MachineViewableValue'])?1:0);

                        // Determine if it is NOT viewable for this person
                        if ($machineViewableUpdate!=1){
                            // Create a query to add this row to the link table
                            $sql='INSERT INTO usertomachineviewinglinker (UserID, MachineID, ViewCategory) ' . 
                                 'VALUES (' . $forUserID . ', ' . $row["MachineID"] . ', "NOT VIEWABLE");';

                            // Insert the machine row view row
                            $db->queryDB($sql, $userRow, "user_presentation Form occurance 27");
                        }
                    }
                }
            }
        } catch (Exception $ex) {
            // fail the success
            $success = 0;
        }
        
        // Send back whatever was made 
        return $success;
    }
?>   
