/**
 * Old form editing controls.
 * @param unknown_type $form_id
 */
function formbuilder_options_editForm($form_id)
{
    global $wpdb, $formbuilder_admin_nav_options;
    /*
     * Permissions control.  Block users who can't create new forms.
     */
    if (!formbuilder_user_can('create')) {
        formbuilder_admin_alert('You do not have permission to access this area.');
        return;
    }
    /*
     * Process submitted form results.
     */
    if (isset($_POST['formbuilder']) and is_array($_POST['formbuilder'])) {
        $_POST['formbuilder'] = formbuilder_array_stripslashes($_POST['formbuilder']);
        $_POST['formbuilderfields'] = formbuilder_array_stripslashes($_POST['formbuilderfields']);
        // Verify the data that was posted.
        // No verification currently done on the main form fields.
        // Check for tags.  Add them separately if necessary.
        if (isset($_POST['formbuilder']['tags'])) {
            $newTags = array();
            $tags = explode(',', $_POST['formbuilder']['tags']);
            foreach ($tags as $tag) {
                $tag = trim($tag);
                $tag = preg_replace("/[^A-Za-z0-9 _-]/isU", "", $tag);
                if ($tag != '') {
                    $newTags[] = $tag;
                }
            }
            // Remove tags no longer in the list.  And trim the new tags list to only include true new tags.
            $originalTags = array();
            $sql = "SELECT * FROM " . FORMBUILDER_TABLE_TAGS . " WHERE form_id = '{$form_id}' ORDER BY tag ASC;";
            $results = $wpdb->get_results($sql, ARRAY_A);
            foreach ($results as $tag) {
                $newTagKey = array_search($tag['tag'], $newTags);
                if ($newTagKey === false) {
                    $sql = "DELETE FROM " . FORMBUILDER_TABLE_TAGS . " WHERE id='{$tag['id']}';";
                    if ($wpdb->query($sql) === false) {
                        $errors[] = __('ERROR.  Your tags failed to update.', 'formbuilder') . ' ' . sprintf(__('The error was: %s', 'formbuilder'), $wpdb->last_error);
                    }
                } else {
                    unset($newTags[$newTagKey]);
                }
            }
            // Add new tags from the list.
            foreach ($newTags as $tag) {
                $request = array('form_id' => $form_id, 'tag' => $tag);
                if ($wpdb->insert(FORMBUILDER_TABLE_TAGS, $request) === false) {
                    $errors[] = sprintf(__("Failed inserting tag '%s'.", 'formbuilder'), $tag) . ' ' . sprintf(__('The error was: %s', 'formbuilder'), $wpdb->last_error);
                }
            }
            unset($_POST['formbuilder']['tags']);
        }
        // Check to ensure that we can save the form data.  List an error message if not.
        if (false === $wpdb->update(FORMBUILDER_TABLE_FORMS, $_POST['formbuilder'], array('id' => $form_id))) {
            $errors[] = __('ERROR.  Your form failed to save.', 'formbuilder') . ' ' . sprintf(__('The error was: %s', 'formbuilder'), $wpdb->last_error);
        }
        // Check to see if we have any form fields to save, while making sure there are no existing error messages.
        if (isset($_POST['formbuilderfields']) and is_array($_POST['formbuilderfields']) and !isset($errors)) {
            // Iterate through the form fields, do verification and save them to the database.
            foreach ($_POST['formbuilderfields'] as $key => $value) {
                // Verify that the field has appropriate data
                $value['field_name'] = clean_field_name($value['field_name']);
                // Verify that the field has a field name at all
                if (!$value['field_name']) {
                    if ($value['field_type'] != 'comments area' and $value['field_type'] != 'page break') {
                        $errors[] = sprintf(__("ERROR.  You have a field on your form with an empty field name.  The field is a '%s'  All fields MUST have a unique field name.", 'formbuilder'), $value['field_type']);
                    }
                }
                // Check to ensure that the field name hasn't already been used.
                if ($value['field_name']) {
                    if (!isset($tmp_field_names[$value['field_name']])) {
                        $tmp_field_names[$value['field_name']] = true;
                    } else {
                        $errors[] = __("ERROR.  You have a duplicate field '" . $value['field_name'] . "' on your form.  All field names must be unique.", 'formbuilder');
                    }
                }
                $result = $wpdb->update(FORMBUILDER_TABLE_FIELDS, $value, array('id' => $key));
                if (false === $result) {
                    $errors[] = __("ERROR.  Problems were detected while saving your form fields.", 'formbuilder') . ' ' . sprintf(__('The error was: %s', 'formbuilder'), $wpdb->last_error);
                }
            }
        }
        if (isset($_POST['fieldAction']) and is_array($_POST['fieldAction'])) {
            $fieldAction = $_POST['fieldAction'];
            $fieldKey = key($fieldAction);
            $fieldValue = current($fieldAction);
            if ($fieldValue == __('Add New Field', 'formbuilder')) {
                if ($fieldKey == "newField") {
                    // Create a new field at the end of the form.
                    $sql = "SELECT * FROM " . FORMBUILDER_TABLE_FIELDS . " WHERE form_id = {$form_id} ORDER BY display_order DESC;";
                    $relatedRows = $wpdb->get_results($sql, ARRAY_A);
                    #						$relatedRows = $tableFields->search_rows("$form_id", "form_id", "display_order DESC");
                    $actionRow = $relatedRows[0];
                    $display_order = $actionRow['display_order'] + 1;
                    $wpdb->insert(FORMBUILDER_TABLE_FIELDS, array('form_id' => $form_id, 'display_order' => $display_order, 'field_value' => '', 'field_label' => '', 'error_message' => '', 'help_text' => ''));
                    $rowID = $wpdb->insert_id;
                    #						$tableFields->save_row($rowID, array("form_id"=>"$form_id", "display_order"=>$display_order));
                }
                if (!isset($errors)) {
                    echo "<meta http-equiv='refresh' content='0;url=#field_{$rowID}' />";
                }
            }
            if ($fieldValue == __("Add Another", 'formbuilder')) {
                $sql = "SELECT * FROM " . FORMBUILDER_TABLE_FIELDS . " WHERE id = {$fieldKey} ORDER BY display_order DESC;";
                $results = $wpdb->get_results($sql, ARRAY_A);
                $actionRow = $results[0];
                #$actionRow = $tableFields->load_row($fieldKey);
                $sql = "SELECT * FROM " . FORMBUILDER_TABLE_FIELDS . " WHERE form_id = {$form_id} ORDER BY display_order DESC;";
                $relatedRows = $wpdb->get_results($sql, ARRAY_A);
                #$relatedRows = $tableFields->search_rows("$form_id", "form_id");
                foreach ($relatedRows as $row) {
                    #$row = $tableFields->load_row($tableRowID);
                    $tableRowID = $row['id'];
                    if ($row['display_order'] >= $actionRow['display_order']) {
                        $row['display_order'] = $row['display_order'] + 1;
                        $wpdb->update(FORMBUILDER_TABLE_FIELDS, $row, array('id' => $tableRowID));
                        #$tableFields->save_row($tableRowID, $row);
                    }
                }
                $wpdb->insert(FORMBUILDER_TABLE_FIELDS, array('form_id' => $form_id, 'display_order' => $actionRow['display_order'], 'field_value' => '', 'field_label' => '', 'error_message' => '', 'help_text' => ''));
                $rowID = $wpdb->insert_id;
                #$rowID = $tableFields->create_row();
                #$tableFields->save_row($rowID, array("form_id"=>"$form_id", "display_order"=>$actionRow['display_order']));
                if (!isset($errors)) {
                    echo "<meta http-equiv='refresh' content='0;url=#field_{$rowID}' />";
                }
            }
            if ($fieldValue == __("Delete", 'formbuilder')) {
                #					$actionRow = $tableFields->load_row($fieldKey);
                #					$relatedRows = $tableFields->search_rows("$form_id", "form_id", "display_order ASC");
                #					$tableFields->remove_row($fieldKey);
                $sql = "SELECT * FROM " . FORMBUILDER_TABLE_FIELDS . " WHERE id = {$fieldKey} ORDER BY display_order DESC;";
                $results = $wpdb->get_results($sql, ARRAY_A);
                $actionRow = $results[0];
                $sql = "SELECT * FROM " . FORMBUILDER_TABLE_FIELDS . " WHERE form_id = {$form_id} ORDER BY display_order ASC;";
                $relatedRows = $wpdb->get_results($sql, ARRAY_A);
                $sql = "DELETE FROM " . FORMBUILDER_TABLE_FIELDS . " WHERE id = '{$fieldKey}';";
                $wpdb->query($sql);
                foreach ($relatedRows as $row) {
                    #						$row = $tableFields->load_row($tableRowID);
                    $tableRowID = $row['id'];
                    if ($row['display_order'] > $actionRow['display_order']) {
                        $row['display_order'] = $row['display_order'] - 1;
                        #							$tableFields->save_row($tableRowID, $row);
                        $wpdb->update(FORMBUILDER_TABLE_FIELDS, $row, array('id' => $tableRowID));
                    }
                }
                if (!isset($errors)) {
                    echo "<meta http-equiv='refresh' content='0;url=#field_" . $relatedRows[0]['id'] . "' />";
                }
            }
            if ($fieldValue == __("Move Up", 'formbuilder')) {
                #					$actionRow = $tableFields->load_row($fieldKey);
                #					$relatedRows = $tableFields->search_rows("$form_id", "form_id", "display_order ASC");
                $sql = "SELECT * FROM " . FORMBUILDER_TABLE_FIELDS . " WHERE id = {$fieldKey} ORDER BY display_order DESC;";
                $results = $wpdb->get_results($sql, ARRAY_A);
                $actionRow = $results[0];
                $sql = "SELECT * FROM " . FORMBUILDER_TABLE_FIELDS . " WHERE form_id = {$form_id} ORDER BY display_order ASC;";
                $relatedRows = $wpdb->get_results($sql, ARRAY_A);
                #					$firstRow = $tableFields->load_row(reset($relatedRows));
                $sql = "SELECT * FROM " . FORMBUILDER_TABLE_FIELDS . " WHERE id = '" . $relatedRows[0]['id'] . "' ORDER BY display_order DESC;";
                $results = $wpdb->get_results($sql, ARRAY_A);
                $firstRow = $results[0];
                $firstPos = $firstRow['display_order'];
                $current_pos = $actionRow['display_order'];
                if ($current_pos > $firstPos) {
                    $current_pos -= 1;
                    $actionRow['display_order'] = $current_pos;
                    foreach ($relatedRows as $row) {
                        #							$row = $tableFields->load_row($tableRowID);
                        $tableRowID = $row['id'];
                        if ($row['display_order'] == $current_pos) {
                            $row['display_order'] = $row['display_order'] + 1;
                            #								$tableFields->save_row($tableRowID, $row);
                            $wpdb->update(FORMBUILDER_TABLE_FIELDS, $row, array('id' => $tableRowID));
                        }
                    }
                    #						$tableFields->save_row($fieldKey, $actionRow);
                    $wpdb->update(FORMBUILDER_TABLE_FIELDS, $actionRow, array('id' => $fieldKey));
                }
                if (!isset($errors)) {
                    echo "<meta http-equiv='refresh' content='0;url=#field_{$fieldKey}' />";
                }
            }
            if ($fieldValue == __("Move Down", 'formbuilder')) {
                #					$actionRow = $tableFields->load_row($fieldKey);
                $sql = "SELECT * FROM " . FORMBUILDER_TABLE_FIELDS . " WHERE id = {$fieldKey} ORDER BY display_order DESC;";
                $results = $wpdb->get_results($sql, ARRAY_A);
                $actionRow = $results[0];
                #					$relatedRows = $tableFields->search_rows("$form_id", "form_id", "display_order DESC");
                $sql = "SELECT * FROM " . FORMBUILDER_TABLE_FIELDS . " WHERE form_id = {$form_id} ORDER BY display_order DESC;";
                $relatedRows = $wpdb->get_results($sql, ARRAY_A);
                #					$firstRow = $tableFields->load_row(reset($relatedRows));
                $sql = "SELECT * FROM " . FORMBUILDER_TABLE_FIELDS . " WHERE id = '" . $relatedRows[0]['id'] . "' ORDER BY display_order DESC;";
                $results = $wpdb->get_results($sql, ARRAY_A);
                $firstRow = $results[0];
                $lastPos = $firstRow['display_order'];
                $current_pos = $actionRow['display_order'];
                if ($current_pos < $lastPos) {
                    $current_pos += 1;
                    $actionRow['display_order'] = $current_pos;
                    foreach ($relatedRows as $row) {
                        #							$row = $tableFields->load_row($tableRowID);
                        $tableRowID = $row['id'];
                        if ($row['display_order'] == $current_pos) {
                            $row['display_order'] = $row['display_order'] - 1;
                            #								$tableFields->save_row($tableRowID, $row);
                            $wpdb->update(FORMBUILDER_TABLE_FIELDS, $row, array('id' => $tableRowID));
                        }
                    }
                    #						$tableFields->save_row($fieldKey, $actionRow);
                    $wpdb->update(FORMBUILDER_TABLE_FIELDS, $actionRow, array('id' => $fieldKey));
                }
                if (!isset($errors)) {
                    echo "<meta http-equiv='refresh' content='0;url=#field_{$fieldKey}' />";
                }
            }
        }
        if (isset($_POST['Save']) and !isset($errors)) {
            $message = sprintf(__("Your form has been saved.  %sYou may click here to return to the main FormBuilder options page.%s", 'formbuilder'), "<a href='" . FB_ADMIN_PLUGIN_PATH . "'>", "</a>");
        }
    }
    // End process submitted form results.
    /*
     * Show any error messages that we need to show.
     */
    if (isset($message)) {
        echo "<div class='updated'><p><strong>{$message}</strong></p></div>";
    }
    if (isset($errors)) {
        foreach ($errors as $error) {
            echo "<div class='updated' style='background-color: #FFBBBB; border: 1px solid red; color: red;'><p><strong>{$error}</strong></p></div>";
        }
    }
    /*
     * Load the form fields from the database.
     */
    $sql = "SELECT * FROM " . FORMBUILDER_TABLE_FORMS . " WHERE id = '{$form_id}';";
    $results = $wpdb->get_results($sql, ARRAY_A);
    $form_fields = $results[0];
    /*
     * Iterate through each field in the forms database for this form.  
     * These are the generic form control fields such as name, subject, recipient.
     */
    foreach ($form_fields as $key => $value) {
        // Create a new field array.
        $field = array();
        // Assign the key to the Field key
        $field['Field'] = $key;
        // If there is a POST value for the field, us it, otherwise use the $value variable which contains the value from the DB.
        if (!isset($_POST['formbuilder'][$key])) {
            $field['Value'] = $value;
        } else {
            $field['Value'] = $_POST['formbuilder'][$key];
        }
        // Add a brief explanation to specific fields of how to enter the data.
        if ($field['Field'] == "name") {
            $field['Title'] = __('What do you want to call this contact form?', 'formbuilder');
            $field['HelpText'] = __('What do you want to call this contact form?', 'formbuilder');
            $field['Type'] = "varchar(255)";
        }
        if ($field['Field'] == "subject") {
            $field['Title'] = __('The subject line for the email you receive from the form.', 'formbuilder');
            $field['HelpText'] = __('The subject line for the email you receive from the form.', 'formbuilder');
            $field['Type'] = "varchar(255)";
        }
        if ($field['Field'] == "recipient") {
            $field['Title'] = __('What email address should the data from this contact form be mailed to?', 'formbuilder');
            $field['HelpText'] = __('What email address should the data from this contact form be mailed to?', 'formbuilder');
            $field['Type'] = "varchar(255)";
        }
        if ($field['Field'] == "method") {
            $field['Title'] = __('How should this form post data?  If you are unsure, leave it on POST', 'formbuilder');
            $field['HelpText'] = __('How should this form post data?  If you are unsure, leave it on POST', 'formbuilder');
            $field['Type'] = "enum(POST,GET)";
        }
        if ($field['Field'] == "action") {
            $field['Title'] = __('You may specify an alternate form processing system if necessary.  If you are unsure, leave it alone.', 'formbuilder');
            $field['HelpText'] = __('You may specify an alternate form processing system if necessary.  If you are unsure, leave it alone.', 'formbuilder');
            $field['Type'] = "enum('|" . __('Form to Email - Convert the form results to an email.', 'formbuilder') . "'";
            if (file_exists(FORMBUILDER_PLUGIN_PATH . "/modules")) {
                $d = dir(FORMBUILDER_PLUGIN_PATH . "/modules");
                while (false !== ($entry = $d->read())) {
                    if ($entry != "." and $entry != "..") {
                        $module_filename = FORMBUILDER_PLUGIN_PATH . "/modules/{$entry}";
                        if (!is_file($module_filename)) {
                            continue;
                        }
                        $module_data = implode("", file($module_filename));
                        if (eregi("\n\\w*name\\: ([^\r\n]+)", $module_data, $regs)) {
                            $module_name = $regs[1];
                        } else {
                            $module_name = $entry;
                        }
                        $field['Type'] .= ",'{$entry}|{$module_name}'";
                        if (eregi("\n\\w*instructions\\: ([^\r\n]+)", $module_data, $regs)) {
                            $module_instructions = "\\n\\n" . addslashes($regs[1]);
                        } else {
                            $module_instructions = "";
                        }
                        $field['HelpText'] .= $module_instructions;
                    }
                }
                $d->close();
            }
            $field['Type'] .= ")";
        }
        if ($field['Field'] == "thankyoutext") {
            $field['Title'] = __('What message would you like to show your visitors?', 'formbuilder');
            $field['HelpText'] = __('What message would you like to show your visitors when the successfully complete the form?', 'formbuilder');
            $field['Type'] = "text";
        }
        if ($field['Field'] == "autoresponse") {
            $field['Title'] = __('You may specify an autoresponse to send back if necessary.', 'formbuilder');
            $field['HelpText'] = __('You may specify an autoresponse to send back if necessary.  You should have alread created them on the main FormBuilder Management page.', 'formbuilder');
            $field['Type'] = "enum('|'";
            $sql = "SELECT * FROM " . FORMBUILDER_TABLE_RESPONSES . ";";
            $response_ids = $wpdb->get_results($sql, ARRAY_A);
            #				$response_ids = $tableResponses->list_rows();
            if ($response_ids) {
                foreach ($response_ids as $response_data) {
                    #					$response_data = $tableResponses->load_row($response_id);
                    $field['Type'] .= ",'" . $response_data['id'] . "|" . $response_data['name'] . "'";
                }
            }
            $field['Type'] .= ")";
        }
        $fields[$key] = $field;
    }
    $all_field_types = formbuilder_get_field_types();
    $all_required_types = formbuilder_get_required_types();
    include FORMBUILDER_PLUGIN_PATH . "html/options_edit_form.inc.php";
}
function formbuilder_process_form($form_id, $data = false)
{
    global $wpdb;
    if (!defined('SID')) {
        define('SID', '');
    }
    $formBuilderTextStrings = formbuilder_load_strings();
    $siteurl = get_option('siteurl');
    $relative_path = str_replace(ABSOLUTE_PATH, "/", FORMBUILDER_PLUGIN_PATH);
    //$page_path = $siteurl . $relative_path;
    $page_path = plugin_dir_url(__DIR__);
    // Pull the form data from the db for the selected form ID.
    $sql = "SELECT * FROM " . FORMBUILDER_TABLE_FORMS . " WHERE id='{$form_id}';";
    $results = $wpdb->get_results($sql, ARRAY_A);
    if ($results) {
        $form = $results[0];
    }
    if (!isset($form) or !$form) {
        return "";
    }
    // Pass the form through a filter that converts all fields to proper htmlentities.
    $form = formbuilder_array_htmlentities($form);
    $allFields = array();
    // If no form action is defined, use a blank string.  (indicates standard process)
    if (!isset($form['action'])) {
        $form['action'] = "";
    }
    $module_status = false;
    // Load the Form Action module, if different than the standard.
    if ($form['action'] != "") {
        if (include_once FORMBUILDER_PLUGIN_PATH . "modules/" . $form['action']) {
            $startup_funcname = "formbuilder_startup_" . preg_replace("#\\..+#is", "", $form['action']);
            $processor_funcname = "formbuilder_process_" . preg_replace("#\\..+#is", "", $form['action']);
            if (function_exists("{$startup_funcname}")) {
                $module_status = $startup_funcname($form);
            }
        }
    } else {
        $module_status = true;
    }
    if (!isset($form['action_target'])) {
        $form['action_target'] = "";
    }
    $formID = clean_field_name($form['name']);
    $formCSSID = "formBuilderCSSID{$formID}";
    if (!$form['action_target'] or $form['action_target'] == "") {
        $form['action_target'] = $_SERVER['REQUEST_URI'] . "#{$formCSSID}";
    }
    $session_id = session_id();
    $sessName = session_name();
    if (SID != "" and strpos($form['action_target'], $sessName) === false) {
        if (strpos($form['action_target'], "?") === false) {
            $form['action_target'] .= "?" . htmlspecialchars(SID);
        } else {
            $form['action_target'] .= "&amp;" . htmlspecialchars(SID);
        }
    }
    if ($module_status !== false) {
        // Retrieve the tags for the form and use as additional CSS classes in order to allow forms with specific tags to use alternate stylesheets.
        $formTags = array();
        $sql = "SELECT * FROM " . FORMBUILDER_TABLE_TAGS . " WHERE form_id = '{$form_id}' ORDER BY tag ASC;";
        $results = $wpdb->get_results($sql, ARRAY_A);
        foreach ($results as $r) {
            $formTags[] = preg_replace('/[^a-z0-9_-]/isU', '', $r['tag']);
        }
        $formTags = implode(' ', $formTags);
        $formDisplay = "";
        $post_errors = '';
        $formDisplay = apply_filters('formbuilder_prepend_formDisplay', $formDisplay);
        $formDisplayID = "formBuilder{$formID}";
        $formDisplayID = apply_filters('formbuilder_formDisplayID', $formDisplayID);
        $formDisplay .= "\n<form class='formBuilderForm form-horizontal {$formTags}' id='{$formDisplayID}' " . "action='" . $form['action_target'] . "' method='" . strtolower($form['method']) . "' onsubmit='return fb_disableForm(this);'>" . "<input type='hidden' name='formBuilderForm[FormBuilderID]' value='" . $form_id . "' />";
        $formDisplay = apply_filters('formbuilder_formDisplay_formStart', $formDisplay);
        // Paged form related controls for CSS and Javascript
        $page_id = 1;
        $new_page = false;
        $formDisplay .= "<div id='formbuilder-{$form_id}-page-{$page_id}'>";
        $formDisplay .= '<script type="text/javascript">

function toggleVis(boxid)
{
	if(document.getElementById(boxid).isVisible == "true")
	{
		toggleVisOff(boxid);
	}
	else
	{
		toggleVisOn(boxid);
	}
}

function toggleVisOn(boxid) 
{
		document.getElementById(boxid).setAttribute("class", "formBuilderHelpTextVisible");
		document.getElementById(boxid).isVisible = "true";
}

function toggleVisOff(boxid) 
{
		document.getElementById(boxid).setAttribute("class", "formBuilderHelpTextHidden");
		document.getElementById(boxid).isVisible = "false";
}

			</script>';
        // The $module_status variable is considered to be an error, if it contains a string.
        if (is_string($module_status)) {
            $formDisplay .= $module_status;
        }
        // Get the fields for the form.
        $sql = "SELECT * FROM " . FORMBUILDER_TABLE_FIELDS . " WHERE form_id = '" . $form['id'] . "' ORDER BY display_order ASC;";
        $related = $wpdb->get_results($sql, ARRAY_A);
        // Filter the fields as needed.
        $related = apply_filters('formbuilder_filter_fields_processing', $related);
        $formDisplay = apply_filters('formbuilder_formDisplay_post_field_filter', $formDisplay);
        $submit_button_set = false;
        // Check for duplicate form submissions.
        if (isset($_POST['formBuilderForm']['FormBuilderID']) and $_POST['formBuilderForm']['FormBuilderID'] == $form_id) {
            $duplicate_check_hash = $form_id . formbuilder_get_hash();
            $old_hash = get_option('formBuilder_duplicate_hash');
            if ($duplicate_check_hash == $old_hash) {
                $post_errors = true;
                $tmp_msg = "\n<div class='formBuilderFailure alert alert-error'><h4>" . $formBuilderTextStrings['form_problem'] . "</h4><p>" . $formBuilderTextStrings['already_submitted'] . "</p>";
                $tmp_msg .= "\n</div>\n" . $formDisplay;
                $formDisplay = $tmp_msg;
            } else {
                update_option('formBuilder_duplicate_hash', $duplicate_check_hash);
            }
        }
        // Begin going through each field on the form and checking it against the submitted data.
        if (count($related) > 0) {
            foreach ($related as $field) {
                $error_msg = "";
                $divClass = "control-group formBuilderField " . preg_replace("#[^a-z0-9]#isU", "-", $field['field_type']);
                $divID = "formBuilderField" . clean_field_name($field['field_name']);
                $lb = "<br/>";
                $visibility = "";
                // Define short versions of the more used form variables.
                $field['name'] = "formBuilderForm[" . $field['field_name'] . "]";
                // If the field type is a checkbox with no predefined field value, give it a field value of "checked".
                if ($field['field_type'] == "checkbox" and $field['field_value'] == "") {
                    $field['field_value'] = "checked";
                }
                if ($field['field_type'] == "required checkbox" and $field['field_value'] == "") {
                    $field['field_value'] = "checked";
                }
                // Fill unset POST vars with empty strings.  Not sure what this was used for, but it is now disabled so as not to mess with other plugins that may also check _POST data. (James: Oct. 19, 2011)
                //if(!isset($_POST['formBuilderForm'][$field['field_name']])) $_POST['formBuilderForm'][$field['field_name']] = "";
                // Determine what submitted value to give to the field values.
                if ($field['field_type'] == 'system field') {
                    // Manually assign value to system fields before anything else.
                    $field['value'] = $field['field_value'];
                } elseif ($field['field_type'] == 'wp user id') {
                    // Manually assign value to system fields before anything else.
                    $wpuser = wp_get_current_user();
                    if ($wpuser->id != 0) {
                        $field['value'] = $wpuser->user_login;
                    }
                    $wpuser = null;
                } elseif (isset($_POST['formBuilderForm']['FormBuilderID']) and $_POST['formBuilderForm']['FormBuilderID'] == $form_id) {
                    // If there is a POST value, assign it to the field.
                    if (!isset($_POST['formBuilderForm'][$field['field_name']])) {
                        $field['value'] = '';
                    } else {
                        $field['value'] = htmlentities(stripslashes($_POST['formBuilderForm'][$field['field_name']]), ENT_QUOTES, get_option('blog_charset'));
                    }
                } elseif (isset($_GET[$field['field_name']])) {
                    // If there is a GET value, assign it to the field.
                    $field['value'] = htmlentities(stripslashes($_GET[$field['field_name']]), ENT_QUOTES, get_option('blog_charset'));
                } else {
                    // Required passwords should not display the default field value.
                    if ($field['field_type'] != 'required password') {
                        // In this case, there is neither a POST nor a GET value, therefore we assign the field value to be whatever the default value was for the field.
                        $field['value'] = $field['field_value'];
                    } else {
                        $field['value'] = "";
                    }
                }
                // Validate POST results against validators.
                if (isset($_POST['formBuilderForm']['FormBuilderID']) and $_POST['formBuilderForm']['FormBuilderID'] == $form_id) {
                    $duplicate_check_hash .= md5($field['value']);
                    if ($field['field_type'] == "spam blocker") {
                        // Check Spam Blocker for any submitted data.
                        if (trim($field['value']) != "") {
                            $post_errors = true;
                        }
                    } elseif ($field['field_type'] == "recipient selection") {
                        // Check to ensure we have been given a valid recipient selection
                        $options = explode("\n", $field['field_value']);
                        if (strpos($options[$field['value']], "|") !== false) {
                            list($option_value, $option_label) = explode("|", $options[$field['value']], 2);
                        } else {
                            $option_value = $option_label = $options[$field['value']];
                        }
                        if (!preg_match('#' . FORMBUILDER_PATTERN_EMAIL . '#isU', $option_value)) {
                            $error_msg = $field['error_message'];
                            $post_errors = true;
                            $missing_post_fields[$divID] = $field['field_label'];
                        }
                    } elseif ($field['field_type'] == "captcha field" and function_exists('imagecreate')) {
                        // Check CAPTCHA to ensure it is correct
                        if (isset($_SESSION['security_code']) and $_SESSION['security_code'] == $field['value'] && !empty($_SESSION['security_code'])) {
                            // Insert you code for processing the form here, e.g emailing the submission, entering it into a database.
                            unset($_SESSION['security_code']);
                        } else {
                            if (!isset($_SERVER['HTTP_COOKIE'])) {
                                $post_errors = true;
                                $missing_post_fields[$divID] = $formBuilderTextStrings['captcha_cookie_problem'];
                            } else {
                                // Insert your code for showing an error message here
                                $post_errors = true;
                                $error_msg = $field['error_message'];
                                $missing_post_fields[$divID] = $field['field_label'];
                            }
                        }
                    } elseif ($field['field_type'] == 'required password') {
                        if ($field['value'] != $field['field_value']) {
                            $post_errors = true;
                            if (!$field['error_message']) {
                                $field['error_message'] = __("The password you entered is incorrect.", 'formbuilder');
                            }
                            $error_msg = $field['error_message'];
                            $missing_post_fields[$divID] = $field['field_label'];
                        }
                    } else {
                        // Check the values of any other required fields.
                        if (!formbuilder_validate_field($field)) {
                            $error_msg = $field['error_message'];
                            $post_errors = true;
                            $missing_post_fields[$divID] = $field['field_label'];
                        }
                    }
                }
                // Prepopulate fields with user details if available
                if ($field['value'] == "") {
                    $wpuser = wp_get_current_user();
                    if ($wpuser->ID != 0) {
                        // User is logged in.  Prepopulate with data.
                        if (preg_match('#^(yourname|name|your_name|display_name|nickname)$#i', $field['field_name'], $regs)) {
                            $field['value'] = $wpuser->display_name;
                        }
                        if (preg_match('#^(firstname|first_name)$#i', $field['field_name'], $regs)) {
                            $field['value'] = $wpuser->first_name;
                        }
                        if (preg_match('#^(lastname|last_name)$#i', $field['field_name'], $regs)) {
                            $field['value'] = $wpuser->last_name;
                        }
                        if (preg_match('#^(email)$#i', $field['field_name'], $regs)) {
                            $field['value'] = $wpuser->user_email;
                        }
                        if (preg_match('#^(full_name|fullname)$#i', $field['field_name'], $regs)) {
                            $field['value'] = trim($wpuser->first_name . " " . $wpuser->last_name);
                        }
                    }
                    $wpuser = null;
                }
                // Display any necessary error msgs.
                if ($error_msg) {
                    $formError = "<div class='formBuilderError'>{$error_msg}</div>";
                } else {
                    $formError = "";
                }
                // Check for required fields, and change the class label details if necessary
                if (isset($field['required_data']) and $field['required_data'] != "none" and $field['required_data'] != "") {
                    $formLabelCSS = "formBuilderLabelRequired control-label";
                } else {
                    $formLabelCSS = "formBuilderLabel control-label";
                }
                // Determine if we need to show help text.
                if ($field['help_text']) {
                    if (DEFINED('FORMBUILDER_HELPTEXT_LABEL')) {
                        $formHelp = "<div class='formBuilderHelpText help-block' id='formBuilderHelpText{$divID}'>" . $field['help_text'] . "</div>";
                        $formHelpJava = "<a href='javascript:;' " . "class='formBuilderHelpTextToggle' " . "onClick='toggleVis(\"formBuilderHelpText{$divID}\");' " . ">" . FORMBUILDER_HELPTEXT_LABEL . "</a>{$formHelp}";
                    } else {
                        $formHelp = "<div class='formBuilderHelpText help-block' id='formBuilderHelpText{$divID}'>" . $field['help_text'] . "</div>";
                        $formHelpJava = "<a href='javascript:;' " . "class='formBuilderHelpTextToggle' " . "onClick='toggleVis(\"formBuilderHelpText{$divID}\");' " . ">?</a>{$formHelp}";
                    }
                } else {
                    $formHelpJava = "";
                    $formHelp = "";
                }
                // Display assorted form fields depending on the type of field.
                switch ($field['field_type']) {
                    case "comments area":
                        $formLabel = "";
                        $formInput = "<div class='formBuilderCommentsField controls'>" . decode_html_entities($field['field_value'], ENT_NOQUOTES, get_option('blog_charset')) . "</div> {$formHelpJava}";
                        $divClass = "formBuilderComment";
                        break;
                    case "hidden field":
                        $formLabel = "";
                        $formInput = "<div class='formBuilderHiddenField controls'><input type='hidden' name='" . $field['name'] . "' value='" . $field['value'] . "' /></div>";
                        $divClass = "formBuilderHidden";
                        break;
                    case "small text area":
                        $formLabel = "<div class='{$formLabelCSS}'>" . decode_html_entities($field['field_label'], ENT_NOQUOTES, get_option('blog_charset')) . " {$formHelpJava}</div>";
                        $formInput = "<div class='formBuilderSmallTextarea controls'><textarea name='" . $field['name'] . "' rows='4' cols='50' " . "id='field{$divID}' onblur=\"fb_ajaxRequest('" . $page_path . "php/formbuilder_parser.php', " . "'formid=" . $form['id'] . "&amp;fieldid=" . $field['id'] . "&amp;val='+document.getElementById('field{$divID}').value, 'formBuilderErrorSpace{$divID}')\" >" . $field['value'] . "</textarea></div>";
                        break;
                    case "large text area":
                        $formLabel = "<div class='{$formLabelCSS}'>" . decode_html_entities($field['field_label'], ENT_NOQUOTES, get_option('blog_charset')) . " {$formHelpJava}</div>";
                        $formInput = "<div class='formBuilderLargeTextarea controls'><textarea name='" . $field['name'] . "' rows='10' cols='80' " . "id='field{$divID}' onblur=\"fb_ajaxRequest('" . $page_path . "php/formbuilder_parser.php', " . "'formid=" . $form['id'] . "&amp;fieldid=" . $field['id'] . "&amp;val='+document.getElementById('field{$divID}').value, " . "'formBuilderErrorSpace{$divID}')\" >" . $field['value'] . "</textarea></div>";
                        break;
                    case "password box":
                        $formLabel = "<div class='{$formLabelCSS}'>" . decode_html_entities($field['field_label'], ENT_NOQUOTES, get_option('blog_charset')) . " </div>";
                        $formInput = "<div class='formBuilderInput controls'><input type='password' name='" . $field['name'] . "' value='" . $field['value'] . "' id='field{$divID}' onblur=\"fb_ajaxRequest('" . $page_path . "php/formbuilder_parser.php', 'formid=" . $form['id'] . "&amp;fieldid=" . $field['id'] . "&amp;val='+document.getElementById('field{$divID}').value, 'formBuilderErrorSpace{$divID}')\" /> {$formHelpJava}</div>";
                        break;
                    case "required password":
                        $formLabel = "<div class='formBuilderLabelRequired'>" . decode_html_entities($field['field_label'], ENT_NOQUOTES, get_option('blog_charset')) . " </div>";
                        $formInput = "<div class='formBuilderInput controls'><input type='password' name='" . $field['name'] . "' value='' id='field{$divID}' /> {$formHelpJava}</div>";
                        break;
                    case "checkbox":
                        if (isset($_POST['formBuilderForm'][$field['field_name']]) and htmlentities(stripslashes($_POST['formBuilderForm'][$field['field_name']]), ENT_NOQUOTES, get_option('blog_charset')) == $field['field_value']) {
                            $selected = "checked";
                        } else {
                            $selected = "";
                        }
                        $formLabel = "<div class='{$formLabelCSS}'><label for='field{$divID}'>" . decode_html_entities($field['field_label'], ENT_NOQUOTES, get_option('blog_charset')) . " </label></div>";
                        $formInput = "<div class='formBuilderInput controls'><input type='checkbox' name='" . $field['name'] . "' id='field{$divID}' value='" . $field['field_value'] . "' {$selected} /> <span class='formBuilderCheckboxDescription'>";
                        if ($field['field_value'] != "checked") {
                            $formInput .= "<label for='field{$divID}'>" . decode_html_entities($field['field_value'], ENT_NOQUOTES, get_option('blog_charset')) . "</label>";
                        }
                        $formInput .= "</span> {$formHelpJava}</div>";
                        break;
                    case "required checkbox":
                        if (isset($_POST['formBuilderForm'][$field['field_name']]) and htmlentities(stripslashes($_POST['formBuilderForm'][$field['field_name']]), ENT_NOQUOTES, get_option('blog_charset')) == $field['field_value']) {
                            $selected = "checked";
                        } else {
                            $selected = "";
                        }
                        $formLabel = "<div class='formBuilderLabelRequired'><label for='field{$divID}'>" . decode_html_entities($field['field_label'], ENT_NOQUOTES, get_option('blog_charset')) . " </label></div>";
                        $formInput = "<div class='formBuilderInput controls'><input type='checkbox' name='" . $field['name'] . "' id='field{$divID}' value='" . $field['field_value'] . "' {$selected} /> <span class='formBuilderCheckboxDescription'>";
                        if ($field['field_value'] != "checked") {
                            $formInput .= "<label for='field{$divID}'>" . decode_html_entities($field['field_value'], ENT_NOQUOTES, get_option('blog_charset')) . "</label>";
                        }
                        $formInput .= "</span> {$formHelpJava}</div>";
                        break;
                    case "radio buttons":
                        $options = explode("\n", $field['field_value']);
                        $formLabel = "<div class='{$formLabelCSS}'>" . decode_html_entities($field['field_label'], ENT_NOQUOTES, get_option('blog_charset')) . " {$formHelpJava}</div>";
                        $formInput = "<div class='formBuilderInput controls'>";
                        foreach ($options as $option_value => $roption) {
                            // Check for a pipe, and if it exists, split the value into value, label.
                            if (strpos($roption, "|") !== FALSE) {
                                list($option_original_value, $option_label) = explode("|", $roption, 2);
                            } else {
                                $option_label = $roption;
                            }
                            $option_label = trim(stripslashes($option_label));
                            $option_label = str_replace("<", "&lt;", $option_label);
                            $option_label = str_replace(">", "&gt;", $option_label);
                            if (isset($_POST['formBuilderForm'][$field['field_name']]) and htmlentities(stripslashes($_POST['formBuilderForm'][$field['field_name']]), ENT_QUOTES, get_option('blog_charset')) == $option_value) {
                                $selected = "checked";
                            } else {
                                $selected = "";
                            }
                            $formInput .= "<div class='formBuilderRadio'><label><input type='radio' name='" . $field['name'] . "' value='{$option_value}' {$selected} /> {$option_label}</label></div>";
                        }
                        $formInput .= "</div>";
                        break;
                    case "selection dropdown":
                        $options = explode("\n", $field['field_value']);
                        $formLabel = "<div class='{$formLabelCSS}'>" . decode_html_entities($field['field_label'], ENT_NOQUOTES, get_option('blog_charset')) . " </div>";
                        $formInput = "<div class='formBuilderSelect controls'>\n<select name='" . $field['name'] . "'>";
                        foreach ($options as $option_value => $roption) {
                            // Check for a pipe, and if it exists, split the value into value|label.
                            if (strpos($roption, "|") !== FALSE) {
                                list($option_original_value, $option_label) = explode("|", $roption, 2);
                            } else {
                                $option_label = $roption;
                            }
                            $option_label = trim(stripslashes($option_label));
                            $option_label = str_replace("<", "&lt;", $option_label);
                            $option_label = str_replace(">", "&gt;", $option_label);
                            // Check to see if the posted data is the same as the value.
                            if (isset($_POST['formBuilderForm'][$field['field_name']]) and htmlentities(stripslashes($_POST['formBuilderForm'][$field['field_name']]), ENT_QUOTES, get_option('blog_charset')) == $option_value) {
                                $selected = "selected = 'selected'";
                            } elseif ($field['value'] == $option_value) {
                                $selected = "selected = 'selected'";
                            } else {
                                $selected = "";
                            }
                            $formInput .= "\n<option value='{$option_value}' {$selected}>{$option_label}</option>";
                        }
                        $formInput .= "\n</select>\n {$formHelpJava}</div>";
                        break;
                    case "captcha field":
                        if (function_exists('imagecreate')) {
                            $formLabel = "<div class='{$formLabelCSS}'>" . decode_html_entities($field['field_label'], ENT_NOQUOTES, get_option('blog_charset')) . " </div>";
                            $formInput = "<div class='formBuilderInput controls'><div class='formBuilderCaptcha'>" . "<img src='" . FORMBUILDER_PLUGIN_URL . "captcha/display.php?" . SID . "' " . "alt='" . decode_html_entities($field['field_label'], ENT_NOQUOTES, get_option('blog_charset')) . "' />" . "<br/><input type='text' name='" . $field['name'] . "' value=''/> {$formHelpJava}</div></div>";
                        } else {
                            $formLabel = "<div class='{$formLabelCSS}'>" . decode_html_entities($field['field_label'], ENT_NOQUOTES, get_option('blog_charset')) . " </div>";
                            $formInput = "<div class='formBuilderInput'>" . $formBuilderTextStrings['captcha_unavailable'] . "</div>";
                        }
                        break;
                    case "spam blocker":
                        $formLabel = "<div class='{$formLabelCSS}'>" . decode_html_entities($field['field_label'], ENT_NOQUOTES, get_option('blog_charset')) . " </div>";
                        $formInput = "<div class='formBuilderInput controls'><input type='text' name='" . $field['name'] . "' value=''/> {$formHelpJava}</div>";
                        $divClass = get_option('formbuilder_spam_blocker');
                        break;
                    case "followup page":
                        $formLabel = "";
                        $formInput = "";
                        break;
                    case "recipient selection":
                        $formLabelCSS = "formBuilderLabelRequired";
                        $options = explode("\n", $field['field_value']);
                        $formLabel = "<div class='{$formLabelCSS}'>" . decode_html_entities($field['field_label'], ENT_NOQUOTES, get_option('blog_charset')) . " </div>";
                        $formInput = "<div class='formBuilderSelect controls'>\n<select name='" . $field['name'] . "'>";
                        foreach ($options as $option_value => $roption) {
                            // Check for a pipe, and if it exists, split the value into value|label.
                            if (strpos($roption, "|") !== FALSE) {
                                list($option_original_value, $option_label) = explode("|", $roption, 2);
                            } else {
                                $option_label = $roption;
                            }
                            $option_label = trim(stripslashes($option_label));
                            $option_label = str_replace("<", "&lt;", $option_label);
                            $option_label = str_replace(">", "&gt;", $option_label);
                            // Check to see if the posted data is the same as the value.
                            if (isset($_POST['formBuilderForm'][$field['field_name']]) and htmlentities(stripslashes($_POST['formBuilderForm'][$field['field_name']]), ENT_QUOTES, get_option('blog_charset')) == $option_value) {
                                $selected = "selected = 'selected'";
                            } elseif ($field['value'] == $option_value) {
                                $selected = "selected = 'selected'";
                            } else {
                                $selected = "";
                            }
                            $formInput .= "\n<option value='{$option_value}' {$selected}>{$option_label}</option>";
                        }
                        $formInput .= "\n</select>\n {$formHelpJava}</div>";
                        break;
                    case "page break":
                        $new_page = true;
                        $formLabel = "<div class='{$formLabelCSS}'>" . decode_html_entities($field['field_label'], ENT_NOQUOTES, get_option('blog_charset')) . " </div>";
                        $formInput = "<div class='formBuilderPageBreak'>";
                        $previous_page_insert = "";
                        if ($page_id > 1) {
                            $previous_page_insert = "<input type='button' name='formbuilder_page_break' value='" . $formBuilderTextStrings['previous'] . "' onclick=" . '"   fb_toggleLayer(\'formbuilder-' . $form_id . '-page-' . $page_id . '\');  fb_toggleLayer(\'formbuilder-' . $form_id . '-page-' . ($page_id - 1) . '\');  "' . " />";
                        }
                        $formInput .= "{$previous_page_insert} <input type='button' name='formbuilder_page_break' value='" . $formBuilderTextStrings['next'] . "' onclick=" . '"  fb_toggleLayer(\'formbuilder-' . $form_id . '-page-' . $page_id . '\');  fb_toggleLayer(\'formbuilder-' . $form_id . '-page-' . ($page_id + 1) . '\');  "' . " />" . "</div>";
                        $page_id++;
                        break;
                    case "reset button":
                        $formLabel = "";
                        $formInput = "<div class='formBuilderSubmit controls'>{$previous_page_insert}<input type='reset' name='" . $field['name'] . "' value='" . decode_html_entities($field['field_label'], ENT_NOQUOTES, get_option('blog_charset')) . "' /> {$formHelpJava}</div>";
                        break;
                    case "submit button":
                        $formLabel = "";
                        $previous_page_insert = "";
                        if ($page_id > 1) {
                            $previous_page_insert = "<input type='button' name='formbuilder_page_break' value='" . $formBuilderTextStrings['previous'] . "' onclick=" . '"   fb_toggleLayer(\'formbuilder-' . $form_id . '-page-' . $page_id . '\');  fb_toggleLayer(\'formbuilder-' . $form_id . '-page-' . ($page_id - 1) . '\');  "' . " />";
                        }
                        $formInput = "<div class='formBuilderSubmit controls'>{$previous_page_insert}<input type='submit' name='" . $field['name'] . "' value='" . decode_html_entities($field['field_label'], ENT_NOQUOTES, get_option('blog_charset')) . "' /> {$formHelpJava}</div>";
                        $submit_button_set = true;
                        break;
                    case "submit image":
                        $formLabel = "";
                        $previous_page_insert = "";
                        if ($page_id > 1) {
                            $previous_page_insert = "<input type='button' name='formbuilder_page_break' value='" . $formBuilderTextStrings['previous'] . "' onclick=" . '"   fb_toggleLayer(\'formbuilder-' . $form_id . '-page-' . $page_id . '\');  fb_toggleLayer(\'formbuilder-' . $form_id . '-page-' . ($page_id - 1) . '\');  "' . " /> {$formHelpJava}";
                        }
                        $formInput = "<div class='formBuilderSubmit controls'>{$previous_page_insert}<input type='image' name='" . $field['name'] . "' src='" . decode_html_entities($field['field_label'], ENT_NOQUOTES, get_option('blog_charset')) . "' value='" . $field['value'] . "' alt='" . $field['value'] . "' /></div>";
                        $submit_button_set = true;
                        break;
                    case "datestamp":
                        $formLabel = "<div class='{$formLabelCSS}'>" . decode_html_entities($field['field_label'], ENT_NOQUOTES, get_option('blog_charset')) . " </div>";
                        if (isset($calendar_loaded) and $calendar_loaded == true) {
                            $calendar_loading_code = "";
                        } else {
                            $calendar_loading_code = "<script src=\"" . $page_path . "js/calendar.js\" type=\"text/javascript\"></script>";
                            $calendar_loaded = true;
                        }
                        $formInput = "<div class='formBuilderDateStamp controls'><input type='text' name='" . $field['name'] . "' value='" . $field['value'] . "' id='field{$divID}' />\n\t\t\t\t\t\t\t\t{$calendar_loading_code}\n\t\t\t\t\t\t\t\t<script type=\"text/javascript\">\n\t\t\t\t\t\t\t\tfb_calendar.set(\"field{$divID}\");\n\t\t\t\t\t\t\t\t</script> {$formHelpJava}\n\t\t\t\t\t\t\t</div>";
                        break;
                    case "unique id":
                        $unique = uniqid();
                        $formLabel = "";
                        $formInput = "<div class='formBuilderHiddenField'><input type='hidden' name='" . $field['name'] . "' value='" . uniqid() . "' /></div>";
                        $divClass = "formBuilderHidden";
                        break;
                    case "system field":
                        $formLabel = "";
                        $formInput = "";
                        break;
                    case "wp user id":
                        $formLabel = "";
                        $formInput = "";
                        break;
                    default:
                        $formLabel = "<div class='{$formLabelCSS}'>" . decode_html_entities($field['field_label'], ENT_NOQUOTES, get_option('blog_charset')) . " </div>";
                        $formInput = "<div class='formBuilderInput controls'><input type='text' " . "name='" . $field['name'] . "' " . "value='" . $field['value'] . "' " . "id='field{$divID}' " . "onblur=\"fb_ajaxRequest('" . $page_path . "php/formbuilder_parser.php', 'formid=" . $form['id'] . "&amp;fieldid=" . $field['id'] . "&amp;val='+document.getElementById('field{$divID}').value, 'formBuilderErrorSpace{$divID}')\"/> {$formHelpJava}</div>";
                        break;
                }
                // Additional processing of form fields
                $formFieldDisplay = '';
                $formFieldDisplay = apply_filters('formbuilder_display_field_filter', $formFieldDisplay, $field);
                if (empty($formFieldDisplay) && $field['field_type'] != 'system field' && $field['field_type'] != 'wp user id') {
                    $formFieldDisplay .= "\n<div class='{$divClass}' id='{$divID}' title='" . $field['error_message'] . "' {$visibility}><a name='{$divID}'></a>";
                    if (isset($_POST['formBuilderForm']['FormBuilderID']) and $_POST['formBuilderForm']['FormBuilderID'] == $form_id) {
                        $formFieldDisplay .= "\n<span id='formBuilderErrorSpace{$divID}'>{$formError}</span>";
                    } elseif (!isset($_GET['supress_errors']) and !isset($_GET['suppress_errors'])) {
                        $formFieldDisplay .= "\n<span id='formBuilderErrorSpace{$divID}'>{$formError}</span>";
                    }
                    $formFieldDisplay .= "\n{$formLabel}";
                    $formFieldDisplay .= "\n{$formInput}";
                    $formFieldDisplay .= "\n</div>";
                }
                // Allow for other methods of displaying the form field
                $formDisplay .= $formFieldDisplay;
                // Check for new page of form details.
                if ($new_page == true) {
                    $formDisplay .= "</div><div id='formbuilder-{$form_id}-page-{$page_id}' title='formbuilder-{$form_id}-page-{$page_id}' style='display:none;'>";
                }
                $new_page = false;
                $allFields[] = $field;
            }
        }
        $referrer_info = get_option('formBuilder_referrer_info');
        if ($referrer_info == 'Enabled') {
            // Hidden fields to include referer, and page uri
            $formDisplay .= "<input type='hidden' name='REFERER' value='" . __('Not Available', 'formbuilder') . "' />";
            if (isset($_SERVER['HTTP_HOST']) and isset($_SERVER['REQUEST_URI'])) {
                $formDisplay .= "<input type='hidden' name='PAGE' value='http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] . "' />";
            }
            // Using JavaScript to populate the referrer field, allows this to work even when pages are served from a cached location on the server.
            $formDisplay .= "\n\t\t\t\t<script type=\"text/javascript\">\n\t\t\t\t\tfunction updateReferrerInfo()\n\t\t\t\t\t{\n\t\t\t\t\t\toFormObject = document.forms['formBuilder{$formID}'];\n\t\t\t\t\t\toFormElement = oFormObject.elements['REFERER'];\n\t\t\t\t\t\toFormElement.value = document.referrer;\n\t\t\t\t\t}\n\t\t\t\t</script>\n\t\t\t\t";
        }
        // Submit Button
        if (!$submit_button_set) {
            $previous_page_insert = "";
            if ($page_id > 1) {
                $previous_page_insert = "<input type='button' name='formbuilder_page_break' " . "value='" . $formBuilderTextStrings['previous'] . "' " . "onclick=" . '"   fb_toggleLayer(\'formbuilder-' . $form_id . '-page-' . $page_id . '\');  ' . '  fb_toggleLayer(\'formbuilder-' . $form_id . '-page-' . ($page_id - 1) . '\');  "' . " />";
            }
            $formDisplay .= "\n<div class='formBuilderSubmit form-actions'>{$previous_page_insert}<input type='submit' name='Submit' value='" . $formBuilderTextStrings['send'] . "' /></div>";
        } else {
            $formDisplay .= "";
        }
        $formDisplay .= "\n</div>\n</form>";
        // End of paged CSS
        $formDisplay = apply_filters('formbuilder_append_formDisplay', $formDisplay);
        // Check posted form data to ensure that we don't have any blacklisted material
        $blacklist_enabled = get_option('formbuilder_blacklist');
        if ($blacklist_enabled == "Enabled") {
            if (isset($_POST['formBuilderForm']['FormBuilderID'])) {
                foreach ($_POST['formBuilderForm'] as $key => $value) {
                    if (formbuilder_on_blacklist($value)) {
                        $post_errors = "There is a word in your form submission that the owners of this site deem to be probable spam.";
                        break;
                    }
                }
            }
        }
        // Check posted form data to ensure that we don't have any greylisted material
        $greylist_enabled = get_option('formbuilder_greylist');
        if ($greylist_enabled == "Enabled") {
            if (isset($_POST['formBuilderForm']['FormBuilderID'])) {
                foreach ($_POST['formBuilderForm'] as $key => $value) {
                    if (formbuilder_on_greylist($value)) {
                        $form['subject'] = "POSSIBLE SPAM: " . $form['subject'];
                        break;
                    }
                }
            }
        }
        // Check posted form data to ensure that we don't have any greylisted material
        $excessive_links_enabled = get_option('formbuilder_excessive_links');
        if ($excessive_links_enabled == "Enabled") {
            if (isset($_POST['formBuilderForm']['FormBuilderID'])) {
                foreach ($_POST['formBuilderForm'] as $key => $value) {
                    if (formbuilder_excessive_links($value)) {
                        $form['subject'] = "POSSIBLE SPAM: " . $form['subject'];
                        break;
                    }
                }
            }
        }
        // Check posted form data to ensure that we don't have any greylisted material
        $formbuilder_spammer_ip_checking = get_option('formbuilder_spammer_ip_checking');
        if ($formbuilder_spammer_ip_checking == "Enabled") {
            if (isset($_POST['formBuilderForm']['FormBuilderID'])) {
                $response = formbuilder_check_spammer_ip($_SERVER['REMOTE_ADDR']);
                if ($response > 0) {
                    $form['subject'] = "POSSIBLE SPAMMER IP: " . $form['subject'];
                }
            }
        }
        // Check posted form data for Akismet Spam
        $akismet_enabled = get_option('formbuilder_akismet');
        if ($akismet_enabled == "Enabled" and function_exists('akismet_http_post')) {
            if (isset($_POST['formBuilderForm']['FormBuilderID'])) {
                if (formbuilder_check_akismet($allFields) == 'true') {
                    $form['subject'] = "POSSIBLE AKISMET SPAM: " . $form['subject'];
                }
            }
        }
        // Create extended form variable.
        $extendedForm = $form;
        $extendedForm['allFields'] = $allFields;
        if (isset($_POST['formBuilderForm']['FormBuilderID']) && $_POST['formBuilderForm']['FormBuilderID'] == $form_id) {
            // Final check of fields before marking form as successfully submitted...
            $extendedForm = apply_filters('formbuilder_submit_final_check', $extendedForm);
            $post_errors = apply_filters('formbuilder_final_errors_filter', $post_errors);
        }
        // Process Form Results if necessary
        if (empty($post_errors) && isset($_POST['formBuilderForm']['FormBuilderID']) && $_POST['formBuilderForm']['FormBuilderID'] == $form_id) {
            // Apply filter to fields after successful form submission.
            $extendedForm = apply_filters('formbuilder_submit_success_pre_value_parsing', $extendedForm);
            // Convert numeric selection values to the real form values
            // Iterate through the form fields to add values to the email sent to the recipient.
            foreach ($extendedForm['allFields'] as $key => $field) {
                // If select box or radio buttons, we need to translate the posted value into the real value.
                if ($field['field_type'] == "recipient selection" or $field['field_type'] == "selection dropdown" or $field['field_type'] == "radio buttons") {
                    $options = explode("\n", $field['field_value']);
                    $roption = $options[$field['value']];
                    // Check for a pipe, and if it exists, split the value into value|label.
                    if (strpos($roption, "|") !== FALSE) {
                        list($option_value, $option_label) = explode("|", $roption, 2);
                    } else {
                        $option_value = $option_label = $roption;
                    }
                    $extendedForm['allFields'][$key]['value'] = trim($option_value);
                }
            }
            $extendedForm = apply_filters('formbuilder_submit_success_post_value_parsing', $extendedForm);
            $msg = "";
            // If enabled, put backup copies of the form data into a database.
            if (get_option('formbuilder_db_xml') != '0') {
                $msg = formbuilder_process_db($form, $extendedForm['allFields']);
            }
            // Check if an alternate form processing system is used.
            // Otherwise just use the default which sends an email to the recipiant.
            if ($form['action'] != "") {
                if (function_exists("{$processor_funcname}")) {
                    $msg = $processor_funcname($form, $extendedForm['allFields']);
                    $func_run = true;
                } else {
                    $msg = formbuilder_process_email($form, $extendedForm['allFields']);
                }
            } else {
                $msg = formbuilder_process_email($form, $extendedForm['allFields']);
            }
            // Check for and process any redirections at this point.
            if (!$msg) {
                formbuilder_check_redirection($form, $extendedForm['allFields']);
            }
            if (!isset($func_run)) {
                if (!$msg) {
                    if (!$form['thankyoutext']) {
                        $form['thankyoutext'] = "<h4>" . $formBuilderTextStrings['success'] . "</h4><p>" . $formBuilderTextStrings['send_success'] . "</p>";
                    }
                    // Populate ~variable~ tags in the autoresponse with values submitted by the user.
                    $txtAllFields = "";
                    foreach ($extendedForm['allFields'] as $field) {
                        if (trim($field['field_name']) != "" and $field['field_type'] != "recipient selection" and $field['field_type'] != "comments area" and $field['field_type'] != "followup page" and $field['field_type'] != "spam blocker" and $field['field_type'] != "page break" and $field['field_type'] != "reset button" and $field['field_type'] != "submit button" and $field['field_type'] != "submit image" and $field['field_type'] != "captcha field") {
                            $key = $field['field_name'];
                            $value = $field['value'];
                            $form['thankyoutext'] = str_replace("~" . $key . "~", $value, $form['thankyoutext']);
                            $txtAllFields .= $key . ": " . $value . "\n";
                        }
                    }
                    $form['thankyoutext'] = str_replace("~FullForm~", nl2br(trim($txtAllFields)), $form['thankyoutext']);
                    $formDisplay = "\n<div class='formBuilderSuccess alert alert-success'>" . decode_html_entities($form['thankyoutext'], ENT_QUOTES, get_option('blog_charset')) . "</div>";
                } else {
                    $formDisplay = "\n<div class='formBuilderFailure alert alert-error'><h4>" . $formBuilderTextStrings['failed'] . "</h4><p>" . $formBuilderTextStrings['send_failed'] . "<br/>{$msg}</p></div>";
                }
            } elseif ($msg) {
                // Only shown if the function returned some sort of failure.
                $formDisplay = "\n<div class='formBuilderFailure alert alert-error'><h4>" . $formBuilderTextStrings['failed'] . "</h4><p>{$msg}</p></div>{$formDisplay}";
            } else {
                $formDisplay = "\n<div class='formBuilderSuccess moduleSuccess alert alert-success'>" . decode_html_entities($form['thankyoutext'], ENT_QUOTES, get_option('blog_charset')) . "</div>";
            }
        } else {
            if (!empty($post_errors) and !empty($missing_post_fields)) {
                $msg = "\n<div class='formBuilderFailure alert alert-error'><h4>" . $formBuilderTextStrings['form_problem'] . "</h4><p>" . $formBuilderTextStrings['send_mistakes'] . "</p>";
                $msg .= "\n<ul>";
                foreach ($missing_post_fields as $idValue => $field_label) {
                    $msg .= "\n<li><a href='#{$idValue}'>{$field_label}</a></li>";
                }
                $msg .= "\n</ul></div>\n" . $formDisplay;
                $formDisplay = $msg;
            } elseif (!empty($post_errors) and is_string($post_errors)) {
                $msg = "\n<div class='formBuilderFailure alert alert-error'><h4>" . $formBuilderTextStrings['form_problem'] . "</h4>";
                $msg .= "\n<p>{$post_errors}</p></div>\n" . $formDisplay;
                $formDisplay = $msg;
            }
        }
        $formDisplay = apply_filters('formbuilder_formDisplay_final', $formDisplay);
        return "<div id='{$formCSSID}'>{$formDisplay}</div>";
    } else {
        return $formBuilderTextStrings['display_error'];
    }
}
function display_customer_edit($row)
{
    global $connection;
    //print_pre($row);
    ?>
    <script>
    function save_customer_details() {
        jQuery.post("get_customer.php?save=1&nomenu=1", jQuery("#customer_form").serialize());
    }
    
    </script>
    
    <?php 
    if ($row['new'] == 1) {
        ?>
        <script>
        
        
        
        
        
        
        window.newID = 0;
        function save_disposition(disposition){
            new Ajax.Request('get_customer.php?save_record=1',{parameters: {phonenumber: <?php 
        echo $_GET['phone_number'];
        ?>
}, onSuccess: function(transport){
                             if (transport.responseText) {
                             var response = transport.responseText;
                             window.newID = parseInt(response);
                             //alert(response);
                             
                             new Ajax.Request('get_customer.php?save_script=1&customer_id='+window.newID+"&"+jQuery("#script_form").serialize(),{onSuccess: function(transport){
                                              if (transport.responseText) {
                                              var response = transport.responseText;
                                              jQuery('#dynamicInput3').fadeOut(3000);
                                              //alert(response);
                                              }
                                              }
                                              });
                             
                             new Ajax.Request('get_customer.php?save_disposition=1',{parameters: {id: window.newID, disposition: disposition, user_id: "<?php 
        echo $_SESSION['user_id'];
        ?>
", extension: "<?php 
        echo $_SESSION['extension'];
        ?>
"}, onSuccess: function(transport){
                                              if (transport.responseText) {
                                              var response = transport.responseText;
                                              //entries_to_ids[counter] = parseInt(response);
                                              //alert(response);
                                              window.location="get_customer.php?phone_number=<?php 
        echo $_GET['phone_number'];
        ?>
&disposition_set=1";
                                              }
                                              }
                                              });
                             }
                             
                             }
                             });
            jQuery("#customer_form").submit();
            
            
        }
        
        
        
        
        
        
        </script>
        <?php 
    } else {
        ?>
        <script>
        
        function save_disposition(disposition){
            new Ajax.Request('get_customer.php?save_disposition=1',{parameters: {id: <?php 
        echo $row['id'];
        ?>
, disposition: disposition, user_id: "<?php 
        echo $_SESSION['user_id'];
        ?>
", extension: "<?php 
        echo $_SESSION['extension'];
        ?>
"}, onSuccess: function(transport){
                             if (transport.responseText) {
                             //alert("x");
                             var response = transport.responseText;
                             //entries_to_ids[counter] = parseInt(response);
                             jQuery('#status_bar').text("Saved Disposition");
                             jQuery('#status_bar').fadeIn(1000);
                             jQuery('#status_bar').fadeOut(1000);
                             //alert(response);
                             }
                             new Ajax.Request('get_customer.php?save_script=1&customer_id='+<?php 
        echo $row['id'];
        ?>
+'&'+jQuery("#script_form").serialize(),{
                                              onSuccess: function(transport){
                                              if (transport.responseText) {
                                              var response = transport.responseText;
                                              jQuery('#dynamicInput3').fadeOut(1000);
                                              //alert(response);
                                              }
                                              //alert("x");
                                              jQuery("#customer_form").submit();
                                              
                                              }
                                              
                                              });
                             
                             
                             }
                             });
            //sleep(3)
            //
        }
        </script>
        <?php 
    }
    ?>
    <script>
    
    
    function reschedule(){
        
        <?php 
    /*foreach ($_GET as $field=>$value) {
      ?>alert('<?=$field."=".$value?>');<?
      }*/
    ?>
        jQuery("#content").append('<div id="reschedule" style="display: none" title="Reschedule Call"><center><form id="reschedule_form">Date: <input id="date-picker" name="date-picker"><br />Time: <input type="text" id="time-picker" name="time-picker" value="<?php 
    echo @date("H:i");
    ?>
" style="width: 50px"><input id="done" type="submit" value="Reschedule Call"></form></div>');
        jQuery('#date-picker').datepicker({
                                          dateFormat : 'yy-mm-dd'
                                          });
        jQuery("#reschedule").dialog();
        jQuery("#reschedule_form").submit(function(e) {
                                          e.preventDefault();
                                          window.location = "get_customer.php?reschedule_number=1&phone_number=<?php 
    echo $_GET['phone_number'];
    ?>
&from=list&date="+jQuery("#date-picker").val()+"&time="+jQuery("#time-picker").val();
                                          //return("false");
                                          //alert("Redirected");
                                          //jQuery("#reschedule").close();
                                          });
    }
    function appointment(){
        
        <?php 
    /*foreach ($_GET as $field=>$value) {
      ?>alert('<?=$field."=".$value?>');<?
      }*/
    ?>
        jQuery("#content").append('<div id="appointment" style="display: none" title="Create Appointment"><center><form id="appointment_form">Date: <input id="date-picker" name="date-picker"><br />Time: <input type="text" id="time-picker" name="time-picker" value="<?php 
    echo @date("H:i");
    ?>
" style="width: 50px"><input id="done" type="submit" value="Create Appointment"></form></div>');
        jQuery('#date-picker').datepicker({
                                          dateFormat : 'yy-mm-dd'
                                          });
        jQuery("#appointment").dialog();
        jQuery("#appointment_form").submit(function(e) {
                                           e.preventDefault();
                                           window.location = "get_customer.php?appointment=1&phone_number=<?php 
    echo $_GET['phone_number'];
    ?>
&customer_id=<?php 
    echo $row['id'];
    ?>
&from=list&date="+jQuery("#date-picker").val()+"&time="+jQuery("#time-picker").val();
                                           });
    }
    
    </script>
    <?php 
    echo '<div class="thin_700px_box">';
    $fields_to_hide[] = "id";
    $fields_to_hide[] = "cleaned_number";
    $fields_to_hide[] = "last_updated";
    $fields_to_hide[] = "status";
    $fields_to_hide[] = "locked_by";
    $fields_to_hide[] = "datetime_locked";
    $fields_to_hide[] = "list_id";
    $fields_to_hide[] = "job_id";
    $fields_to_hide[] = "new";
    $textarea_fields[] = "notes";
    if (isset($_GET['nomenu'])) {
        echo '<form id="customer_form" action="get_customer.php?save=1&nomenu=1" method="post">';
    } else {
        echo '<form id="customer_form" action="get_customer.php?save=1" method="post">';
    }
    echo '<table class="sample">';
    foreach ($row as $field => $value) {
        if (in_array($field, $fields_to_hide)) {
            echo '<input type="hidden" name="' . $field . '" value="' . @stripslashes($value) . '">';
        } else {
            if (in_array($field, $textarea_fields)) {
                echo '<tr><th colspan="2">' . clean_field_name($field) . '</th></tr>';
                echo '<tr><td colspan="2"><textarea cols="60" rows="10" name="' . $field . '">' . stripslashes($value) . '</textarea></td></tr>';
            } else {
                echo '<tr><th>' . clean_field_name($field) . '</th><td><input type="text" name="' . $field . '" value="' . stripslashes($value) . '"></td></tr>';
            }
        }
    }
    echo '<tr><td colspan="2"><input type="hidden" value="save changes"></td></tr>';
    echo '</form>';
    echo "</table>";
    echo '<center><a href="javascript:void(0)" onclick="save_customer_details();appointment();">Create an appointment</a>';
    echo "</div>";
}
			<h3 class="info-box-title hndle"><?php 
_e('Spam Blocker', 'formbuilder');
?>
</h3>
			<div class="inside">
			<p><?php 
printf(__('The FormBuilder can employ a %sspam blocking system%s in order to prevent automated computers from spamming the forms.  To accomplish this we put a field on the form that has been hidden, so that computers can see it, but people cannot.  If the field has been filled out when the form is submitted, the system will assume that a spammer is attempting to use the form, and will ignore the submission.', 'formbuilder'), '<a href="http://truthmedia.com/2008/06/27/feature-reverse-captcha/" title="Read More: FormBuilder Spam Blocking" target="_blank">', '</a>');
?>
</p>
			<p><?php 
_e('In order to help make this spam blocker more effective, you can specify a name for this spam blocker that will be used when it is displayed in the code of your form.', 'formbuilder');
?>
</p>
			<?php 
if (isset($_POST['formBuilder_Spam_Blocker'])) {
    $spam_blocker = clean_field_name($_POST['formBuilder_Spam_Blocker']);
    if ($spam_blocker != "") {
        update_option('formbuilder_spam_blocker', $spam_blocker);
    }
}
$spam_blocker = get_option('formbuilder_spam_blocker');
?>
			<form action="<?php 
echo FB_ADMIN_PLUGIN_PATH;
?>
&fbaction=settings" method="POST">
				<input type="text" name="formBuilder_Spam_Blocker" value="<?php 
echo $spam_blocker;
?>
" />
				<input type="submit" name="Submit" value="<?php 
Exemple #5
0
                 $fields[] = $row['Field'];
             }
         }
     }
     echo '<table class="sample">';
     $printed_header = false;
     /* Row and column offsets are 1 */
     for ($row = 1; $row <= $max; $row++) {
         if (!$printed_header) {
             $printed_header = true;
             echo '<tr>';
             echo '<th>Row</th>';
             for ($col = $start; $col <= sizeof($arr[$row]) - $extra; $col++) {
                 echo '<th><select name="col_' . $col . '"><option value="null">Not Used</option>';
                 foreach ($fields as $field) {
                     echo '<option value="' . $field . '">' . clean_field_name($field) . '</option>';
                 }
                 echo '</select></th>';
             }
             echo '</tr>';
         }
         echo "<tr>";
         echo "<td>{$row}</td>";
         for ($col = $start; $col <= sizeof($arr[$row]); $col++) {
             echo "<td>" . $arr[$row][$col] . "</td>";
         }
         echo "</tr>";
     }
     echo "</table>";
     ?>
 <input type="hidden" name="list_id" value="<?php 
Exemple #6
0
function make_table_sql($table_name, array $profile)
{
    $sql = array();
    $sql[] = "CREATE TABLE `{$table_name}` (";
    $sql[] = "  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,";
    foreach ($profile as $field_name => $field) {
        $field_name = clean_field_name($field_name);
        $line = sprintf("  `%s`", $field_name);
        switch ($field['type']) {
            case 'integer':
                $line .= sprintf(" int(11)");
                if ($field['unsigned']) {
                    $line .= " unsigned ";
                }
                break;
            case 'double':
                $line .= sprintf(" decimal(9,2)");
                if ($field['unsigned']) {
                    $line .= " unsigned ";
                }
                break;
            case 'string':
                if ($field['length'] <= 255) {
                    // For fields that have been empty but are still specified. Benefit of the doubt.
                    if ($field['length'] == 0) {
                        $field['length'] = 255;
                    }
                    $line .= sprintf(" varchar(%d)", $field['length']);
                } else {
                    $line .= sprintf(" text");
                }
                break;
        }
        if ($field['required']) {
            $line .= " NOT NULL";
        } else {
            $line .= " DEFAULT NULL";
        }
        $sql[] = $line . ",";
    }
    $sql[] = "  PRIMARY KEY (`id`)";
    $sql[] = ") ENGINE=InnoDB DEFAULT CHARSET=latin1";
    return join("\n", $sql);
}
Exemple #7
0
    function display_user_edit($row)
    {
        global $connection;
        $fields_to_hide[] = "id";
        $fields_to_ignore[] = "password";
        $textarea_fields[] = "";
        $select_fields[] = "security_level";
        $select_values['security_level'][] = "0";
        $select_names['security_level'][] = "No Access";
        $select_values['security_level'][] = "1";
        $select_names['security_level'][] = "Agent";
        $select_values['security_level'][] = "10";
        $select_names['security_level'][] = "Administrator";
        $select_values['security_level'][] = "100";
        $select_names['security_level'][] = "Super User";
        echo '<form action="users.php?save=1" method="post">';
        echo "<table>";
        foreach ($row as $field => $value) {
            if (in_array($field, $select_fields)) {
                echo '<tr><td>' . clean_field_name($field) . '</td><td><select name="' . $field . '">';
                for ($i = 0; $i < sizeof($select_names[$field]); $i++) {
                    if ($value == $select_values[$field][$i]) {
                        $selected = " selected";
                    } else {
                        $selected = "";
                    }
                    echo '<option value="' . $select_values[$field][$i] . '" ' . $selected . '>' . $select_names[$field][$i] . '</option>';
                }
                echo "</select></td></tr>";
            } else {
                if (in_array($field, $fields_to_ignore)) {
                } else {
                    if (in_array($field, $fields_to_hide)) {
                        echo '<input type="hidden" name="' . $field . '" value="' . $value . '">';
                    } else {
                        if (in_array($field, $textarea_fields)) {
                            echo '<tr><td colspan="2">' . clean_field_name($field) . '</td></tr>';
                            echo '<tr><td colspan="2"><textarea cols="60" rows="10" name="' . $field . '">' . $value . '</textarea></td></tr>';
                        } else {
                            if ($field == "popup_blocker") {
                                echo '<tr><td>' . clean_field_name($field) . '</td>';
                                echo '<td><select name="' . $field . '">';
                                //                .$value.
                                switch ($value) {
                                    case "0":
                                        $blocked = " ";
                                        $unblocked = " selected ";
                                        break;
                                    default:
                                        $blocked = " selected ";
                                        $unblocked = "  ";
                                        break;
                                }
                                echo '<option value="1" ' . $blocked . '>Popup Blocker Disabled</option>';
                                echo '<option value="0" ' . $unblocked . '>Popup Blocker Enabled</option>';
                                echo '</select></td></tr>';
                            } else {
                                if ($field == "use_softphone") {
                                    echo '<tr><td>' . clean_field_name($field) . '</td>';
                                    echo '<td><select name="' . $field . '">';
                                    //                .$value.
                                    switch ($value) {
                                        case "0":
                                            $blocked = " ";
                                            $unblocked = " selected ";
                                            break;
                                        default:
                                            $blocked = " selected ";
                                            $unblocked = "  ";
                                            break;
                                    }
                                    echo '<option value="1" ' . $blocked . '>Use Softphone</option>';
                                    echo '<option value="0" ' . $unblocked . '>Don\'t Use Softphone</option>';
                                    echo '</select></td></tr>';
                                } else {
                                    if ($field == "extension") {
                                        //echo '<tr><td>Agent Number</td><td><input type="text" name="'.$field.'" value="'.$value.'"></td></tr>';
                                        echo '<tr><td>Agent Number</td>';
                                        echo '<td>';
                                        $result_agents = mysqli_query($connection, "SELECT agent_num, pin FROM agent_nums WHERE used = 0 or agent_num = '{$value}'") or die(mysqli_error($connection));
                                        if (mysqli_num_rows($result_agents) == 0) {
                                            echo "No agents remaining...";
                                        } else {
                                            echo '<select name="' . $field . '">';
                                            while ($row = mysqli_fetch_assoc($result_agents)) {
                                                if ($row['agent_num'] == $value) {
                                                    echo '<option value="' . $row['agent_num'] . "!" . $row['pin'] . '" selected>' . $row['agent_num'] . ' (PIN: ' . $row['pin'] . ')</option>';
                                                } else {
                                                    echo '<option value="' . $row['agent_num'] . "!" . $row['pin'] . '">' . $row['agent_num'] . ' (PIN: ' . $row['pin'] . ')</option>';
                                                }
                                            }
                                            echo "</select>";
                                        }
                                        ?>
                <input type="hidden" name="orig_extension" value="<?php 
                                        echo $value;
                                        ?>
">
                <?php 
                                        //echo '<input type="text" name="'.$field.'" value="">
                                        echo '</td></tr>';
                                    } else {
                                        echo '<tr><td>' . clean_field_name($field) . '</td><td><input type="text" name="' . $field . '" value="' . $value . '"></td></tr>';
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        echo '<tr><td colspan="2"><input type="submit" value="save changes"></td></tr>';
        echo '</form>';
        echo "</table>";
    }