<?php
  global $isSingleMenu, $preSaveTempId;

  // always edit record 1 for single menu
  $isSingleMenu = (@$schema['menuType'] == 'single');
  if ($isSingleMenu) { $FORM['num'] = 1; }

  // new records - generate $preSaveTempId for uploads if no record number
  $preSaveTempId = '';
  if (!@$FORM['num']) { $preSaveTempId = uniqid('x'); }


//
function showWysiwygGeneratorCode() {
  global $schema, $SETTINGS;

  // get wysiwyg list
  $wysiwygListAsCSV = "";

  foreach ($schema as $name => $fieldHash) {
    if (!is_array($fieldHash))            { continue; } // fields are stored as arrays, other entries are table metadata
    if (@$fieldHash['type'] != 'wysiwyg') { continue; } // skip all but wysiwyg fields

    $fieldSchema = array_merge($fieldHash, array('name' => $name));
    $uploadBrowserCallback = @$fieldSchema['allowUploads'] ? "wysiwygUploadBrowser" : "";
    $includeDomainsInLinks = $SETTINGS['wysiwyg']['includeDomainInLinks'] ? "remove_script_host : false," : "";
    $programUrl            = pathinfo($_SERVER['PHP_SELF'], PATHINFO_DIRNAME);

    // display field
    print <<<__HTML__
<script language="javascript" type="text/javascript"><!--
tinyMCE.init({
      mode : "exact",
      theme : "advanced",

          // Define buttons: Button codes: http://wiki.moxiecode.com/index.php/TinyMCE:Control_reference
          theme_advanced_buttons1 : "styleselect,bold,italic,underline,|,justifyleft,justifycenter,justifyright,|,bullist,numlist,|,outdent,indent,|,removeformat,fullscreen",
          theme_advanced_buttons2 : "forecolor,backcolor,|,link,unlink,anchor,|,hr,image,media,table,|,pastetext,pasteword,|,code",
          theme_advanced_buttons3 : "",
          content_css : "/pa_style.css",
          theme_advanced_styles   : "Header=header;Sub-heading=subheader;bold=bold",

          // Load Plugins: ***NOTE*** plugins must be added both here and in tinyMCE_GZ.init() in edit.php!
          plugins : "inlinepopups,contextmenu,table,fullscreen,paste,media",

          // Paste From Word Settings - Docs: http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/paste
//          paste_use_dialog: true,
//          paste_auto_cleanup_on_paste: true,

          //
          theme_advanced_toolbar_location : "top",
          theme_advanced_toolbar_align : "left",
          elements: '{$fieldSchema['name']}',
          file_browser_callback : "$uploadBrowserCallback",
          relative_urls : false,
          document_base_url: "/",

          $includeDomainsInLinks
          entity_encoding : "raw", // don't store extended chars as entities (&ntilde) or keyword searching won't match them

          verify_html : false, // allow all tags and attributes

          //
          content_css : "$programUrl/css/wysiwyg.css"
    });
//--></script>
__HTML__;
  }
}

function showFields() {
  global $FORM, $schema, $escapedTableName, $CURRENT_USER;

  $num = (int) @$FORM['num'];

  # error checking
  if ($escapedTableName == '') { die("no tablename specified!"); }
  if ($num != (int) $num)      { die("record number value must be an integer!"); }

  // load record
  $record = array();
  if ($num) {
    $query  = "SELECT * FROM `$escapedTableName` WHERE num = '".mysql_real_escape_string($num)."'";
    $result = mysql_query($query) or die("MySQL Error: ". htmlspecialchars(mysql_error()) . "\n");
    $record = mysql_fetch_assoc($result);
  }

  // create record - set special field values
  //else { NOTE: We may remove this in future versions
  //  $currentDate  = date("Y-m-d H:i:s", getAdjustedLocalTime()); // set default to required Format: YYYY-MM-DD HH:MM:SS
  //  if (!array_key_exists('createdDate', $record))      { $record['createdDate']      = $currentDate; }
  //  if (!array_key_exists('createdByUserNum', $record)) { $record['createdByUserNum'] = $GLOBALS['CURRENT_USER']['num']; }
  //  if (!array_key_exists('updatedDate', $record))      { $record['updatedDate']      = $currentDate; }
  //  if (!array_key_exists('updatedByUserNum', $record)) { $record['updatedByUserNum'] = $GLOBALS['CURRENT_USER']['num']; }
  //}

  // load schema columns
  _showCreatedUpdated($schema, $record);
  foreach ($schema as $name => $fieldHash) {
    if (!is_array($fieldHash)) { continue; } // fields are stored as arrays, other entries are table metadata
    if (@$fieldHash['adminOnly'] && !$CURRENT_USER['isAdmin'] && !$GLOBALS['hasAdminAccess']) { continue; } // skip admin only fields

    $fieldSchema = array_merge($fieldHash, array('name' => $name));

    switch (@$fieldHash['type']) {
      case '': case 'none': break;
      case 'textfield':  _showTextfield($fieldSchema, $record); break;
      case 'textbox':    _showTextbox($fieldSchema, $record);   break;
      case 'wysiwyg':    _showWysiwyg($fieldSchema, $record);   break;
      case 'date':       _showDateTime($fieldSchema, $record);  break;
      case 'list':       _showList($fieldSchema, $record);      break;
      case 'checkbox':   _showCheckbox($fieldSchema, $record);  break;
      case 'upload':     _showUpload($fieldSchema, $record);    break;
      case 'separator':  _showSeparator($fieldSchema, $record); break;
      case 'accessList': _showAccessList($fieldSchema, $record); break;
      default:              echo "<tr><td colspan='2' align='center'><b>field '$name' has unknown field type '" .@$fieldHash['type']. "'</b></td></tr>";     break;
    }
  }

}

function _showCreatedUpdated($schema, $record) {
  global $FORM, $CURRENT_USER, $TABLE_PREFIX, $isSingleMenu;

  // create dates
  $dateFormat  = "M jS, Y - h:i:s A";
  $currentDate = date("Y-m-d H:i:s", getAdjustedLocalTime());  # format: YYYY-MM-DD HH:MM:SS (24hour format)
  $createdDate = date($dateFormat, strtotime( @$record['createdDate'] ? $record['createdDate'] : $currentDate ));
  $updatedDate = date($dateFormat, strtotime( @$record['updatedDate'] ? $record['updatedDate'] : $currentDate ));

  // get user names
  $usernameField = 'username';
  $createdByUsername = "Unknown";
  $updatedByUsername = "Unknown";

  if ($record) { // editing record
    $accountTable = $TABLE_PREFIX . "accounts";
    if (@$record['createdByUserNum']) {
      $query  = "SELECT $usernameField FROM $accountTable WHERE num = '".mysql_real_escape_string($record['createdByUserNum'])."'";
      $result = mysql_query($query) or die("MySQL Error: ". htmlspecialchars(mysql_error()) . "\n");
      list($createdByUsername) = mysql_fetch_row($result);
    }
    if (@$record['updatedByUserNum']) {
      $query  = "SELECT $usernameField FROM $accountTable WHERE num = '".mysql_real_escape_string($record['updatedByUserNum'])."'";
      $result = mysql_query($query) or die("MySQL Error: ". htmlspecialchars(mysql_error()) . "\n");
      list($updatedByUsername) = mysql_fetch_row($result);
    }
  }
  else { // adding record
    $createdByUsername = $CURRENT_USER[$usernameField];
    $updatedByUsername = $CURRENT_USER[$usernameField];
  }

  // show created
  $html = "";
  $showCreated = @$schema['createdDate'] && @$schema['createdByUserNum'] && @$record['createdDate'] != '0000-00-00 00:00:00';
  if ($showCreated) {
    $html .= <<<__HTML__
     <tr>
      <td class="fieldLabel">{$schema['createdDate']['label']}</td>
      <td>$createdDate (by $createdByUsername)</td>
     </tr>
__HTML__;
  }

  // show updated
  $showUpdated = @$schema['updatedDate'] && @$schema['updatedByUserNum'] && @$record['updatedDate'] != '0000-00-00 00:00:00';
  if ($showUpdated) {
    $html .= <<<__HTML__
     <tr>
      <td class="fieldLabel">{$schema['updatedDate']['label']}</td>
      <td>$updatedDate (by $updatedByUsername)</td>
     </tr>
__HTML__;
  }

  // add linebreak
  if ($showCreated || $showUpdated) {
    $html .= <<<__HTML__
    <tr>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
__HTML__;
  }

  print $html;

}



//
function _showTextfield($fieldSchema, $record) {

  // set field attributes
  $inputType     = $fieldSchema['isPasswordField'] ? 'password'                             : 'text';
  $maxLengthAttr = $fieldSchema['maxLength']       ? "maxlength='{$fieldSchema['maxLength']}'" : '';
  $styleWidth    = @$fieldSchema['fieldWidth']     ? "{$fieldSchema['fieldWidth']}px" : "250px";
  $description   = @$fieldSchema['description'];
  $fieldValue    = $record ? @$record{$fieldSchema['name']} : $fieldSchema['defaultValue'];
  $encodedValue  = htmlspecialchars($fieldValue);

  // display field
  print <<<__HTML__
   <tr>
    <td class="fieldLabel">{$fieldSchema['label']}</td>
    <td>
      <input type="$inputType" name="{$fieldSchema['name']}" value="$encodedValue" size="20" $maxLengthAttr style="width: $styleWidth"/>
      $description
    </td>
   </tr>
__HTML__;
}


//
function _showTextbox($fieldSchema, $record) {

  // set field attributes
  $fieldHeight  = $fieldSchema['fieldHeight'] ? $fieldSchema['fieldHeight'] : 100;
  $fieldValue   = $record ? @$record{$fieldSchema['name']} : $fieldSchema['defaultContent'];

  if ($fieldSchema['autoFormat']) {
    $fieldValue = preg_replace("/<br\/>\n/", "\n", $fieldValue); // remove autoformat break tags
  }

  $encodedValue = htmlspecialchars($fieldValue);

  // display field
  print <<<__HTML__
   <tr>
    <td valign="top" class="fieldLabel">{$fieldSchema['label']}</td>
    <td><textarea name="{$fieldSchema['name']}" style="width: 100%; height: {$fieldHeight}px">$encodedValue</textarea></td>
   </tr>
__HTML__;
}


//
function _showWysiwyg($fieldSchema, $record) {

  // set field attributes
  $fieldHeight  = $fieldSchema['fieldHeight'] ? $fieldSchema['fieldHeight'] : 100;
  $fieldValue   = $record ? @$record{$fieldSchema['name']} : $fieldSchema['defaultContent'];

  $encodedValue = htmlspecialchars($fieldValue);

  // display field
  print <<<__HTML__
   <tr>
    <td valign="top" class="fieldLabel">{$fieldSchema['label']}</td>
    <td>
      <textarea name="{$fieldSchema['name']}" id="{$fieldSchema['name']}" rows="5" cols="40" style="width: 100%; height: {$fieldHeight}px; visibility: hidden;">$encodedValue</textarea>
    </td>
   </tr>
__HTML__;
}


//
function _showDateTime($fieldSchema, $record) {
  global $SETTINGS;

  // get date value(s)
  $currentTime  = date("Y-m-d H:i:s", getAdjustedLocalTime());  # format: YYYY-MM-DD HH:MM:SS (24hour format)
  $fieldValue   = @$record{$fieldSchema['name']} ? $record{$fieldSchema['name']} : $currentTime;

  list($date,$time)       = explode(' ', $fieldValue); // expecting: YYYY-MM-DD HH:MM:SS
  list($year,$month,$day) = explode('-', $date);       // expecting: YYYY-MM-DD
  list($hour24,$min,$sec) = explode(':', $time);         // expecting: HH:MM:SS
  $amOrPm = $hour24 > 12 ? "PM" : "AM";
  $hour12 = (($hour24 % 12) == 0) ? 12 : $hour24 % 12;

  // get month options
  $monthOptions    = '';
  $shortMonthNames = array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
  foreach (range(1,12) as $num) {
    $selectedAttr   = ($num == $month) ? 'selected="selected"' : '';
    $shortMonthName = $shortMonthNames{$num-1};
    $monthOptions .= "<option value=\"$num\" $selectedAttr>$shortMonthName</option>\n";
  }

  // get day options
  $dayOptions    = '';
  foreach (range(1,31) as $num) {
    $selectedAttr   = ($num == $day) ? 'selected="selected"' : '';
    $dayOptions .= "<option value=\"$num\" $selectedAttr>$num</option>\n";
  }

  // get year options
  $yearOptions    = '';
  foreach (range((int) $fieldSchema['yearRangeStart'], (int) $fieldSchema['yearRangeEnd']) as $num) { // (int) for range bug in PHP < 4.23 - see docs
    $selectedAttr   = ($num == $year) ? 'selected="selected"' : '';
    $yearOptions .= "<option value=\"$num\" $selectedAttr>$num</option>\n";
  }

  // get hour options

  $hour24Options = '';
  $hour12Options = '';
  foreach (range(0,23) as $num) {
    $selectedAttr   = ($num == $hour24) ? 'selected="selected"' : '';
    $hour24Options .= "<option value=\"$num\" $selectedAttr>$num</option>\n";
  }
  foreach (range(1,12) as $num) {
    $selectedAttr   = ($num == $hour12) ? 'selected="selected"' : '';
    $hour12Options .= "<option value=\"$num\" $selectedAttr>$num</option>\n";
  }

  // get minute options
  $minOptions = '';
  foreach (range(0,59) as $num) {
    $selectedAttr   = ($num == $min) ? 'selected="selected"' : '';
    $minOptions .= "<option value=\"$num\" $selectedAttr>$num</option>\n";
  }

  // get second options
  $secOptions    = '';
  foreach (range(1,31) as $num) {
    $selectedAttr   = ($num == $sec) ? 'selected="selected"' : '';
    $secOptions .= "<option value=\"$num\" $selectedAttr>$num</option>\n";
  }

  // get AmPm optins
  $amSelectedAttr = ($amOrPm == 'AM') ? 'selected="selected"' : '';
  $pmSelectedAttr = ($amOrPm == 'PM') ? 'selected="selected"' : '';

  // display date field
  print "   <tr>\n";
  print "    <td valign='top' class='fieldLabel'>{$fieldSchema['label']}</td>\n";
  print "    <td>\n";
  print "     <select name='{$fieldSchema['name']}:mon'>$monthOptions</select>\n";
  print "     <select name='{$fieldSchema['name']}:day'>$dayOptions</select>\n";
  print "     <select name='{$fieldSchema['name']}:year'>$yearOptions</select>\n";

  print "     &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;\n";

  if ($fieldSchema['showTime']) {
    if ($fieldSchema['use24HourFormat']) { // show 24 hour time
      print "     <select name='{$fieldSchema['name']}:hour24'>$hour24Options</select>\n";
      print "     <select name='{$fieldSchema['name']}:min'>$minOptions</select>\n";
      if ($fieldSchema['showSeconds']) { print "     <select name='{$fieldSchema['name']}:sec'>$secOptions</select>\n"; }
    }
    else {                                              // show 12 hour time
      print "     <select name='{$fieldSchema['name']}:hour12'>$hour12Options</select>\n";
      print "     <select name='{$fieldSchema['name']}:min'>$minOptions</select>\n";
      if ($fieldSchema['showSeconds']) { print "     <select name='{$fieldSchema['name']}:sec'>$secOptions</select>\n"; }
      print "     <select name='{$fieldSchema['name']}:isPM'>\n";
      print "     <option value='0' $amSelectedAttr>AM</option>\n";
      print "     <option value='1' $pmSelectedAttr>PM</option>\n";
      print "     </select>\n";
    }
  }

  print "         </td>\n";
  print "        </tr>\n";
}

//
function _showList($fieldSchema, $record) {

  // set field attributes
  $listOptions = getListOptionsFromSchema($fieldSchema);
  $fieldValue  = $record ? @$record{$fieldSchema['name']} : '';
  $valignTop   = ($fieldSchema['listType'] != 'pulldown') ? 'valign="top"' : "";

  //
  print "  <tr>\n";
  print "   <td $valignTop class='fieldLabel'>{$fieldSchema['label']}</td>\n";
  print "   <td>\n";

  // pulldown
  if      ($fieldSchema['listType'] == 'pulldown') {
    print "  <select name='{$fieldSchema['name']}'>\n";
    print "  <option value=''>&lt;select&gt;</option>\n";
    foreach ($listOptions as $optionArray) {
      list($value,$label) = $optionArray;
      $encodedValue = htmlspecialchars($value);
      $selectedAttr = ($value == $fieldValue) ? 'selected="selected"' : '';
      $encodedLabel = htmlspecialchars($label);
      print "<option value=\"$encodedValue\" $selectedAttr>$encodedLabel</option>\n";
    }
    print "  </select>\n";
  }

  // radios
  else if ($fieldSchema['listType'] == 'radios') {
    foreach ($listOptions as $optionArray) {
      list($value,$label) = $optionArray;
      $encodedValue = htmlspecialchars($value);
      $encodedLabel = htmlspecialchars($label);
      $checkedAttr  = ($value == $fieldValue) ? 'checked="checked"' : '';
      $idAttr       = "{$fieldSchema['name']}.$encodedValue";

      print "<input type='radio' class='inputRadio' name='{$fieldSchema['name']}' value='$encodedValue' id='$idAttr' $checkedAttr/>\n";
      print "<label for='$idAttr'>$encodedLabel</label><br />\n\n";
    }
  }

  // checkboxes /*** NOTE: This isn't enabled on front end and may be removed in future versions ***/
  else if ($fieldSchema['listType'] == 'checkboxes') {
    $checkedValues = explode(", ", $fieldValue);

    foreach ($listOptions as $optionArray) {
      list($value,$label) = $optionArray;
      $encodedValue = htmlspecialchars($value);
      $encodedLabel = htmlspecialchars($label);
      $checkedAttr  = in_array($value, $checkedValues) ? 'checked="checked"' : '';
      $idAttr       = "{$fieldSchema['name']}.$encodedValue";

      print "<input type='checkbox' class='inputCheckbox' name='{$fieldSchema['name']}[]' value='$encodedValue' id='$idAttr' $checkedAttr/>\n";
      print "<label for='$idAttr'>$encodedLabel</label><br />\n";
    }
  }

  //
  else { die("Unknown listType '{$fieldSchema['listType']}'!"); }


  //
  print "   </td>\n";
  print "  </tr>\n";
}


//
function _showCheckbox($fieldSchema, $record) {

  // set field attributes
  $checkedAttr = '';
  if      ($record && @$record{$fieldSchema['name']})    { $checkedAttr = 'checked="checked"'; }
  else if (!@$record['num'] && $fieldSchema['checkedByDefault']) { $checkedAttr = 'checked="checked"'; }
  $description = @$fieldSchema['description'];

  // display field
  print <<<__HTML__
   <tr>
    <td valign="top" class="fieldLabel">{$fieldSchema['label']}</td>
    <td>
      <input type="hidden"                         name="{$fieldSchema['name']}" value="0" />
      <input type="checkbox" class="inputCheckbox" name="{$fieldSchema['name']}" value="1" id="{$fieldSchema['name']}" $checkedAttr/>
      <label for="{$fieldSchema['name']}">$description</label>
    </td>
   </tr>
__HTML__;
}


//
function _showUpload($fieldSchema, $record) {
  global $menu, $FORM, $preSaveTempId, $SETTINGS;

  // create uploadList url
  $uploadList = "?"
              . "menu=" . urlencode($menu)
              . "&amp;action=uploadList"
              . "&amp;fieldName=" . urlencode($fieldSchema['name'])
              . "&amp;num=" . urlencode(@$FORM['num'])
              . "&amp;preSaveTempId=" . urlencode($preSaveTempId);

  // create uploadLink url
  $uploadLink = "?menu=" . urlencode($menu)
              . "&amp;action=uploadForm"
              . "&amp;fieldName=" . urlencode($fieldSchema['name'])
              . "&amp;num=" . urlencode(@$FORM['num'])
              . "&amp;preSaveTempId=" . urlencode($preSaveTempId)
              . "&amp;TB_iframe=true&amp;height=350&amp;width=700&amp;modal=false";

  // error checking
  $errors = "";
  $uploadDir = @$fieldSchema['useCustomUploadDir'] ? $fieldSchema['customUploadDir'] : $SETTINGS['uploadDir'];
  if     (!file_exists($uploadDir)) { mkdir_recursive($uploadDir, 0755); }  // create upload dir (if not possible, dir not exists error will show below)
  if     (!file_exists($uploadDir)) { $errors .= "Upload directory '" .htmlspecialchars($uploadDir). "' doesn't exist!.<br/>\n"; }
  elseif (!is_writable($uploadDir)) { $errors .= "Upload directory '" .htmlspecialchars($uploadDir). "' isn't writable!.<br/>\n"; }

  // display errors
  if ($errors) { print <<<__HTML__
  <tr>
   <td valign="top" class="fieldLabel"><br/>{$fieldSchema['label']}<br/></td>
   <td style="color: #CC0000; font-weight: bold;"><br/>$errors<br/></td>
  </tr>
__HTML__;
  return;
  }

  // display field
  print <<<__HTML__
  <tr>
   <td></td>
   <td align="right"><br/>These <b><i>uploads</i></b> may be displayed or linked on output page.</td>
  </tr>
   <tr>
    <td valign="top" class="fieldLabel">{$fieldSchema['label']}</td>
    <td>
      <iframe id="{$fieldSchema['name']}_iframe" src="$uploadList" height="55" width="100%" frameborder="0" style="border-width: 1px; border-color: #46A; border-style: solid none; background-color: #EEE"></iframe><br/>
      <div align="center" style="padding: 6px 0px 0px 0px">
        <a href="$uploadLink" class="thickbox"><b>Add or Upload File(s)</b></a><br/>
      </div>
    </td>
   </tr>
__HTML__;
}



//
function _showSeparator($fieldSchema, $record) {

  if      ($fieldSchema['separatorType'] == 'blank line') {
    print "    <tr>\n";
    print "     <td>&nbsp;</td>\n";
    print "     <td>&nbsp;</td>\n";
    print "    </tr>\n";
  }

  else if ($fieldSchema['separatorType'] == 'header bar') {
    print "    <tr>\n";
    print "      <td colspan='2'>\n";
    print "        <div class='subheader'><div>{$fieldSchema['separatorHeader']}</div></div>\n";
    print "      </td>\n";
    print "    </tr>\n";
  }

  else if ($fieldSchema['separatorType'] == 'html') {
    # old: print "\n{$fieldSchema['separatorHTML']}\n";
    # new:

     eval("?".">\n". $fieldSchema['separatorHTML'] . "\n");

  }

  else {
    die("Unknown separator type '{$fieldSchema['separatorType']}'!");
  }
}


//
function _showAccessList($fieldSchema, $record) {
  global $FORM, $TABLE_PREFIX;

  // load access list
  $accessList = array();
  if (@$FORM['num']) {
    $query  = "SELECT * FROM `{$TABLE_PREFIX}_accesslist` WHERE userNum = '" . mysql_real_escape_string($FORM['num']) . "'";
    $result = mysql_query($query) or die("MySQL Error: ". htmlspecialchars(mysql_error()) . "\n");
    while ($record = mysql_fetch_assoc($result)) {
      $accessList[ $record['tableName'] ] = $record;
    }
  }


  // get section list
  $sectionList = array();
  foreach (getSchemaTables() as $tableName) {
    $schema = loadSchema($tableName);
    if (@$schema['menuType'] != 'single' && @$schema['menuType'] != 'multi') { continue; }
    if (@$schema['menuHidden'])  { continue; }
    $thisMenu = array();
    $thisMenu['menuName']  = $schema['menuName'];
    $thisMenu['menuOrder'] = $schema['menuOrder'];
    $thisMenu['tableName'] = $tableName;
    $thisMenu['menuType']  = $schema['menuType'];
    array_push($sectionList, $thisMenu);
    }
  uasort($sectionList, '_sortMenusByOrder');  // sort menus by order value

  // display field
  $allAccessLevel     = @$accessList['all']['accessLevel'];
  $sectionsDivStyle   = ($allAccessLevel != 1) ? "display: none;" : "";
?>
   <tr>
    <td class="fieldLabel" valign="top" style="padding-top: 2px"><?php echo $fieldSchema['label']; ?></td>
    <td>

<table border="0" cellspacing="1" cellpadding="0">
 <tr>
  <td class="listHeader" width="305">Section Name</td>
  <td class="listHeader" width="115" align="center">Access</td>
  <td class="listHeader" width="100" align="center">Max Records</td>
 </tr>
 <tr>
  <td class="listRowOdd">All Sections</td>
  <td class="listRowOdd" align="center">
    <select name="accessList[all][accessLevel]" style="width: 100px" onchange="(this.value=='1') ? $('.sectionAccessList').slideDown() : $('.sectionAccessList').slideUp();">
    <option value="0"      <?php selectedIf($allAccessLevel, '0'); ?>>None</option>
    <option value="6"   <?php selectedIf($allAccessLevel, '6'); ?>>Regular</option>
    <option value="9"     <?php selectedIf($allAccessLevel, '9'); ?>>Admin</option>
    <option value="1" <?php selectedIf($allAccessLevel, '1'); ?>>By Section</option>
    </select>
  </td>
  <td class="listRowOdd" align="center">No Limit</td>
 </tr>
</table>

<script type="text/javascript">
function toggleDisabledForAccessListMaxRecords(tablename) {
  var accessLevel = $("#"+tablename+"_accesslevel").val();
  if (accessLevel >= 9) { $("#"+tablename+"_maxRecords").attr("disabled", true).css("background-color","#DDD");  }
  else                  { $("#"+tablename+"_maxRecords").removeAttr("disabled").css("background-color","#FFF");  }
}
</script>

<div class="sectionAccessList" style="<?php echo $sectionsDivStyle; ?>">
<table border="0" cellspacing="1" cellpadding="0">

<?php

// list sections
foreach ($sectionList as $section) {
  $bgColorClass = (@$bgColorClass == "listRowEven") ? 'listRowOdd' : 'listRowEven'; # rotate bgclass
  $fieldnamePrefix = "accessList[{$section['tableName']}]";
  $accessLevel     = @$accessList[ $section['tableName'] ]['accessLevel'];
  $maxRecords      = @$accessList[ $section['tableName'] ]['maxRecords'];
  $maxRecordsAttr  = ($accessLevel >= 9) ? 'style="text-align: center; background-color: #DDD;" disabled="disabled"'
                                         : 'style="text-align: center;"';

?>
 <tr>
  <td class="<?php echo $bgColorClass; ?>" width="305">&nbsp;&nbsp;&nbsp;&nbsp;<?php echo $section['menuName']; ?></td>
  <td class="<?php echo $bgColorClass; ?>" width="115" align="center">
<?php if ($section['menuType'] == 'multi'): ?>
    <select name="<?php echo $fieldnamePrefix; ?>[accessLevel]" id="<?php echo $section['tableName']; ?>_accesslevel" style="width: 100px" onchange="toggleDisabledForAccessListMaxRecords('<?php echo $section['tableName']; ?>')">
    <option value="0" <?php selectedIf($accessLevel, '0'); ?>>None</option>
    <option value="6" <?php selectedIf($accessLevel, '6'); ?>>Regular</option>
    <option value="9" <?php selectedIf($accessLevel, '9'); ?>>Admin</option>
    </select>
<?php elseif ($section['menuType'] == 'single'): ?>
  <input type="hidden"   name="<?php echo $fieldnamePrefix; ?>[accessLevel]" value="0" />
  <input type="checkbox" name="<?php echo $fieldnamePrefix; ?>[accessLevel]" value="9" <?php checkedIf($accessLevel, '9'); ?> />
<?php endif ?>

  </td>
  <td class="<?php echo $bgColorClass; ?>" width="100" align="center">
<?php if ($section['menuType'] == 'multi'): ?>
    <input type="text" name="<?php echo $fieldnamePrefix; ?>[maxRecords]" id="<?php echo $section['tableName']; ?>_maxRecords"
           value="<?php echo $maxRecords; ?>" size="6" maxlength="6"
           <?php echo $maxRecordsAttr; ?> />
<?php elseif ($section['menuType'] == 'single'): ?>
Single Page
<?php endif ?>
  </td>
 </tr>
<?php
}


  print <<<__HTML__
  </table></div>


  <br/><div style="font-size: 11px">
    <b>Access Levels:</b><br/>
    <div style="padding-left: 20px;">
      None - Don't allow user to access this section<br/>
      Regular - User can only access records they have created<br/>
      Admin - User can access any records in this section<br/>
    </div>
    <b>Max Records:</b> Max records user is allowed to create (for regular users only - leave blank for unlimited)
 </div>

    </td>
   </tr>
__HTML__;
}



?>
