function custom_form_generate($atts)
{
    global $wpdb;
    //allows us to have database tables access
    extract(shortcode_atts(array('invoice_name' => 'stuff', 'invoice_type_id' => 'stuff'), $atts, 'cfg'));
    set_external_js_css($invoice_type_id);
    // add linked js and css files
    /* Form Validation/Submission Handler */
    if ($_POST) {
        if ($invoice_type_id != 17) {
            $error_messages = custom_form_generate_validation($invoice_type_id);
            $form .= $error_messages;
            //output error messages
        }
        if (!$error_messages) {
            $form .= handle_submission($invoice_type_id);
        }
    }
    // if $_POST
    if (!$_POST || $_POST && $error_messages) {
        $form .= display_form($invoice_type_id);
    }
    return $form;
}
function custom_form_generate($atts)
{
    global $wpdb;
    //allows us to have database tables access
    global $current_user;
    //allows us to get the current user information with the call get_currentuserinfo();
    extract(shortcode_atts(array('invoice_name' => 'stuff', 'invoice_type_id' => 'stuff'), $atts, 'cfg'));
    // is for editable?
    $editable = $wpdb->get_var($wpdb->prepare("SELECT editable FROM wp_invoice_type WHERE invoice_type_id = %d AND invoice_name = %s", $invoice_type_id, $invoice_name));
    $multiple_reg = $wpdb->get_var($wpdb->prepare("SELECT multiple_reg FROM wp_invoice_type WHERE invoice_type_id = %d AND invoice_name = %s", $invoice_type_id, $invoice_name));
    // does the user have a previously created invoice?
    if ($editable) {
        $invoice_no = $wpdb->get_var($wpdb->prepare("SELECT `invoice_no` FROM wp_invoice_table WHERE invoice_type_id = %d AND user_id = %d", $invoice_type_id, $current_user->ID));
    }
    // get all the fields to display
    $results = $wpdb->get_results($wpdb->prepare("SELECT * FROM wp_invoice_info where invoice_type_id = %d ORDER BY field_order ASC", $invoice_type_id));
    $nametracking = "";
    $prevtype = "";
    /* attributes from serialized array field */
    $required = "";
    $prevGroupClass = "";
    $prevGroupClass2 = "";
    $error_messages = custom_form_generate_validation($results);
    $jquery_script = "<script>\n";
    //start generating the form
    $option .= '<form method="post" action="">';
    /* ********** BEGIN form submit */
    //output error messages
    if ($error_messages) {
        $option .= $error_messages;
    }
    if (!$error_messages and $_POST) {
        generateInvoice($invoice_type_id, $invoice_no);
        $option .= '<p class="cstem_im_form_success"> Form Submitted Successfully. You should receive an email shortly. </p>';
    }
    /* END form submit ********** */
    //$readonly = "readonly";
    //if (current_user_can("administrator"))
    $readonly = "";
    //generate form with the first name, last name, email of the user registering.
    get_currentuserinfo();
    //first name
    $option .= '<p class="cstem_im_form_desc">First Name:</p><input type="text" name="firstname" value="' . $current_user->user_firstname . '"' . $readonly . '>';
    //last name
    $option .= '<p class="cstem_im_form_desc">Last Name:</p><input type="text" name="lastname" value="' . $current_user->user_lastname . '"' . $readonly . '>';
    // other's behalf field
    $num_registering = 1;
    if ($_POST["others_behalf"]) {
        $other_behalf_checked = 'checked';
        $num_registering = $_POST["num_registering"];
    }
    if ($multiple_reg) {
        $option .= '<input type="checkbox" id="others_behalf" name="others_behalf" value="yes"' . $other_behalf_checked . '><span class="cstem_im_form_radioText">Are you filling out this form on someone else\'s behalf?</span><br/>';
        $option .= '<div id="num_registering_div"><p class="cstem_im_form_desc" style="margin-top:10px">For how many people do you wish to fill this form out?</p><input type="number" id="num_registering" name="num_registering" min="1" value="' . $num_registering . '" required />';
        $option .= '<p style="font-weight:bold; font-size:9pt">Ensure the email(s) below match exactly with those of the people you are registering for.<br/>
				Note that they must have registered for the site before you will be able to submit an order on their behalf.</p>';
        $option .= '</div><br/>';
    }
    //email
    $option .= '<p class="cstem_im_form_desc">Email:</p><input type="email" id="email" name="email" value="' . $current_user->user_email . '"' . $readonly . ' placeholder="Enter a valid email address" required>';
    $option .= '<div id="email_fields" name="email_fields">';
    $option .= '</div>';
    //user id
    $option .= '<input type="hidden" name="user-id" value="' . $current_user->ID . '">';
    // rest of hidden fields
    foreach ($results as $row) {
        if ($row->field_type == "textboxHidden") {
            $option .= '<input type="hidden" name="' . $row->field_name . '">';
        }
    }
    // foreach: get all hidden fields
    /* ********** Start generating the custom fields of the form */
    $fieldsetCount = 0;
    // count how many fieldsets were opened (needed for groupClass tracking)
    $fieldset2Count = 0;
    // same but for inner fieldsets
    $groupClass2_counter = "1";
    // alternates between 0 and 1 for inner class to alternate background color
    $firstItem = 0;
    // don't add </fieldset> for first item
    /* if there is an exisiting invoice and invoice previously submitted then prepopulate all the fields */
    if ($editable && $invoice_no) {
        $resultsData = $wpdb->get_results($wpdb->prepare("SELECT * FROM `wp_invoice_data` where `invoice_no` = %d;", $invoice_no));
    }
    foreach ($results as $row) {
        $attributesArray = unserialize($row->attributes);
        //nametracking is different that means we have a new field
        if ($nametracking != $row->field_name) {
            if ($nametracking . "_disabled" == $row->field_name) {
                $value = floatval($_POST[$row->field_name]);
                $option .= '<input class="cstem_im_form_disabled" type="text" id="' . $row->field_name . '" name="' . $row->field_name . '" tabindex="-1" onfocus="this.blur()" readonly="readonly" value="' . $value . '">';
            } else {
                if ($prevtype == "dropdown") {
                    //close the dropdown field
                    $option .= '</select>';
                }
                if ($prevtype != "textfield" && $prevtype != "textfieldTitle") {
                    $option .= '</fieldset>';
                }
                /* ***** BEGIN GROUP CLASS ***** */
                if (array_key_exists("groupClass", $attributesArray)) {
                    // only change things if keys are different from before
                    if ($attributesArray["groupClass"] != $prevGroupClass && $prevGroupClass == "") {
                        $option .= '<fieldset class="cstem_im_form_fieldset">';
                        $fieldsetCount++;
                    } elseif ($attributesArray["groupClass"] != $prevGroupClass && $prevGroupClass != "") {
                        $option .= '</fieldset><fieldset class="cstem_im_form_fieldset">';
                    }
                } else {
                    if ($prevGroupClass != "") {
                        $option .= '</fieldset>';
                        $fieldsetCount--;
                    }
                    // if: only close if previous was not a blank
                }
                // else: groupClass key is blank
                /* ***** END GROUP CLASS ***** */
                /* ***** BEGIN GROUP CLASS 2 ***** */
                if (array_key_exists("groupClass2", $attributesArray)) {
                    // only change things if keys are different from before
                    if ($attributesArray["groupClass2"] != $prevGroupClass2 && $prevGroupClass2 == "") {
                        $option .= '<fieldset class="cstem_im_form_fieldset">';
                        $fieldset2Count++;
                    } elseif ($attributesArray["groupClass2"] != $prevGroupClass2 && $prevGroupClass2 != "") {
                        $option .= '</fieldset><fieldset class="cstem_im_form_fieldset">';
                    }
                } else {
                    if ($prevGroupClass2 != "") {
                        $option .= '</fieldset>';
                        $fieldset2Count--;
                    }
                    // if: only close if previous was not a blank
                }
                // else: groupClass key is blank
                /* ***** END GROUP CLASS 2 ***** */
                if ($editable && $invoice_no) {
                    foreach ($resultsData as $row2) {
                        if ($row2->field_name == $row->field_name) {
                            if ($row->field_type == "checkbox") {
                                //echo $row->field_name;
                                $values = explode(", ", $row2->field_value);
                                if (in_array($row->field_value, $values)) {
                                    $checked = "checked";
                                } else {
                                    $checked = "";
                                }
                            } else {
                                if ($row2->field_value == $row->field_value) {
                                    $selected = "selected";
                                    $checked = "checked";
                                } else {
                                    $selected = "";
                                    $checked = "";
                                }
                            }
                        }
                        // if: this is the form field to check
                    }
                    // foreach: loop to find form field
                } elseif ($row->field_type == "checkbox" && in_array($row->field_value, $_POST[$row->field_name])) {
                    $checked = "checked";
                } elseif ($_POST[$row->field_name] == $row->field_value) {
                    $selected = "selected";
                    $checked = "checked";
                } else {
                    $selected = "";
                    $checked = "";
                }
                if (array_key_exists("required", $attributesArray)) {
                    $required = "* ";
                } else {
                    $required = "";
                }
                if (!array_key_exists("hasDisabled", $attributesArray) && $row->field_type != "radio" && $row->field_type != "checkbox") {
                    $hasDisabled = 'style="float:right;"';
                } else {
                    $hasDisabled = "";
                }
                $fieldsetNoBorder = "";
                if (array_key_exists("groupClass2", $attributesArray)) {
                    $fieldsetNoBorder = 'style="border:0px; margin: 0px"';
                } else {
                    $groupClass2_counter = "";
                }
                /* textboxes can have price ranges, so get the right price and put in $fieldcost, otherwise, the first number works */
                $fieldvalue = $row->field_value;
                if ($row->field_type == "textbox") {
                    reset($attributesArray);
                    $max_fieldcost = current($attributesArray);
                    next($attributesArray);
                    $threshold = key($attributesArray);
                    $min_fieldcost = current($attributesArray);
                    reset($attributesArray);
                } else {
                    $fieldcost = $attributesArray[0];
                }
                if (array_key_exists("hasDisabled", $attributesArray)) {
                    if ($row->field_type == "textbox") {
                        $jquery_script .= 'jQuery("#' . $row->field_name . '").keyup(function() {
							var old_val = jQuery("#' . $attributesArray["hasDisabled"] . '").val(); // for new total calculation

							var max = jQuery("#' . $row->field_name . '").attr("max"); // lesser quantities are higher price
							var min = jQuery("#' . $row->field_name . '").attr("min"); // greater quantities are lower price
							var threshold = jQuery("#' . $row->field_name . '").attr("threshold");
							var cost = 0;

							if(jQuery("#' . $row->field_name . '").val() < parseInt(threshold))
								cost = max;
							else
								cost = min;

							jQuery("#' . $attributesArray["hasDisabled"] . '").val(cost * jQuery("#' . $row->field_name . '").val());

							var new_val = parseFloat(jQuery("#total_disabled").val()) + parseFloat(jQuery("#' . $attributesArray["hasDisabled"] . '").val()) - parseFloat(old_val); // new total
							jQuery("#total_disabled").val(new_val); // update total
						});' . "\n";
                        $jquery_script .= 'jQuery("#' . $row->field_name . '").click(function() {
							var old_val = jQuery("#' . $attributesArray["hasDisabled"] . '").val(); // for new total calculation

							var max = jQuery("#' . $row->field_name . '").attr("max"); // lesser quantities are higher price
							var min = jQuery("#' . $row->field_name . '").attr("min"); // greater quantities are lower price
							var threshold = jQuery("#' . $row->field_name . '").attr("threshold");
							var cost = 0;

							if(jQuery("#' . $row->field_name . '").val() < parseInt(threshold))
								cost = max;
							else
								cost = min;

							jQuery("#' . $attributesArray["hasDisabled"] . '").val(cost * jQuery("#' . $row->field_name . '").val());

							var new_val = parseFloat(jQuery("#total_disabled").val()) + parseFloat(jQuery("#' . $attributesArray["hasDisabled"] . '").val()) - parseFloat(old_val); // new total
							jQuery("#total_disabled").val(new_val); // update total
						});' . "\n";
                    } else {
                        $jquery_script .= 'jQuery("#' . $row->field_name . '").keyup(function() {
							var old_val = jQuery("#' . $attributesArray["hasDisabled"] . '").val(); // for new total calculation

							var custom_field = jQuery("#' . $row->field_name . ' option:selected").attr("fieldcost");
							jQuery("#' . $attributesArray["hasDisabled"] . '").val(custom_field);

							var new_val = parseFloat(jQuery("#total_disabled").val()) + parseFloat(jQuery("#' . $attributesArray["hasDisabled"] . '").val()) - parseFloat(old_val); // new total
							jQuery("#total_disabled").val(new_val); // update total
						});' . "\n";
                        $jquery_script .= 'jQuery("#' . $row->field_name . '").click(function() {
							var old_val = jQuery("#' . $attributesArray["hasDisabled"] . '").val(); // for new total calculation

							var custom_field = jQuery("#' . $row->field_name . ' option:selected").attr("fieldcost");
							jQuery("#' . $attributesArray["hasDisabled"] . '").val(custom_field);

							var new_val = parseFloat(jQuery("#total_disabled").val()) + parseFloat(jQuery("#' . $attributesArray["hasDisabled"] . '").val()) - parseFloat(old_val); // new total
							jQuery("#total_disabled").val(new_val); // update total
						});' . "\n";
                    }
                    // else: not a textbox
                }
                // if: it has a disabled box attached to it, then add the corresponding jQuery
                //after closing the fields make the next fields
                switch ($row->field_type) {
                    case "dropdown":
                        //generates dropdowns
                        $option .= '<fieldset id="' . $row->field_name . '_fieldset" class="cstem_im_form_fieldset' . $groupClass2_counter . '" ' . $fieldsetNoBorder . '><p class="cstem_im_form_desc">' . '<span style="color:red">' . $required . '</span>' . $row->field_description . '</p><select class="cstem_im_form_dropdown" ' . $hasDisabled . '  id="' . $row->field_name . '" name="' . $row->field_name . '"><option fieldcost="' . $fieldcost . '" value="' . $row->field_value . '" ' . $selected . '>' . $row->field_value . '</option>';
                        break;
                    case "checkbox":
                        //generates checkboxes
                        $option .= '<fieldset id="' . $row->field_name . '_fieldset" class="cstem_im_form_fieldset' . $groupClass2_counter . '" ' . $fieldsetNoBorder . '><p class="cstem_im_form_descBlock">' . '<span style="color:red">' . $required . '</span>' . $row->field_description . '</p><input type="checkbox" ' . $hasDisabled . ' id="' . $row->field_name . '" name="' . $row->field_name . '[]" fieldcost="' . $fieldcost . '" value="' . $row->field_value . '" ' . $checked . '><span class="cstem_im_form_radioText">' . $row->field_value . '</span><br/>';
                        break;
                    case "radio":
                        //generates radio buttons
                        $option .= '<fieldset id="' . $row->field_name . '_fieldset" class="cstem_im_form_fieldset' . $groupClass2_counter . '" ' . $fieldsetNoBorder . '><p class="cstem_im_form_descBlock">' . '<span style="color:red">' . $required . '</span>' . $row->field_description . '</p><input type="radio" class="cstem_im_form_radio" ' . $hasDisabled . '  id="' . $row->field_name . '" name="' . $row->field_name . '" fieldcost="' . $fieldcost . '" value="' . $row->field_value . '" ' . $checked . '><span class="cstem_im_form_radioText">' . $row->field_value . '</span><br/>';
                        break;
                    case "textbox":
                        //generates a textbox
                        if ($editable && $invoice_no) {
                            foreach ($resultsData as $row2) {
                                if ($row2->field_name == $row->field_name) {
                                    $value = stripslashes($row2->field_value);
                                }
                                // if: this is the form field to check
                            }
                            // foreach: loop to find form field
                        } else {
                            $value = stripslashes($_POST[$row->field_name]);
                        }
                        $option .= '<fieldset id="' . $row->field_name . '_fieldset" class="cstem_im_form_fieldset' . $groupClass2_counter . '" ' . $fieldsetNoBorder . '><p class="cstem_im_form_desc">' . '<span style="color:red">' . $required . '</span>' . $row->field_description . '</p><input type="text" class="cstem_im_form_text" ' . $hasDisabled . ' id="' . $row->field_name . '" name="' . $row->field_name . '" min="' . $min_fieldcost . '" max="' . $max_fieldcost . '" threshold="' . $threshold . '" value="' . $value . '">';
                        break;
                    case "textboxDisabled":
                        // generates a disabled textbox
                        $value = floatval($_POST[$row->field_name]);
                        $option .= '<fieldset id="' . $row->field_name . '_fieldset" class="cstem_im_form_fieldset' . $groupClass2_counter . '" ' . $fieldsetNoBorder . '><p class="cstem_im_form_desc">' . '<span style="color:red">' . $required . '</span>' . $row->field_description . '</p><input type="text" class="cstem_im_form_disabled" tabindex="-1" onfocus="this.blur()" readonly="readonly" id="' . $row->field_name . '" name="' . $row->field_name . '" value="' . $value . '">';
                        break;
                    case "textarea":
                        if ($editable && $invoice_no) {
                            foreach ($resultsData as $row2) {
                                if ($row2->field_name == $row->field_name) {
                                    $value = stripslashes($row2->field_value);
                                }
                                // if: this is the form field to check
                            }
                            // foreach: loop to find form field
                        } else {
                            $value = stripslashes($_POST[$row->field_name]);
                        }
                        $option .= '<fieldset id="' . $row->field_name . '_fieldset" class="cstem_im_form_fieldset' . $groupClass2_counter . '" ' . $fieldsetNoBorder . '><p class="cstem_im_form_desc">' . '<span style="color:red">' . $required . '</span>' . $row->field_description . '</p><textarea class="cstem_im_form_textarea" ' . $hasDisabled . ' id="' . $row->field_name . '" name="' . $row->field_name . '">' . $value . '</textarea>';
                        break;
                    case "textfield":
                        //outputs a block of predefined text
                        $option .= '<p class="blurb">' . '<span style="color:red">' . $required . '</span>' . $row->field_description . '</p>';
                        break;
                    case "textfieldTitle":
                        //outputs a block of predefined text
                        $option .= '<h2 class="cstem_im_form_title">' . '<span style="color:red">' . $required . '</span>' . $row->field_description . '</h2>';
                        break;
                    default:
                        break;
                }
                //$groupClass2_counter = $groupClass2_counter % 2 + 1;
                if ($groupClass2_counter == "1") {
                    $groupClass2_counter = "2";
                } else {
                    $groupClass2_counter = "1";
                }
            }
            // else: new field
        } else {
            if ($editable && $invoice_no) {
                foreach ($resultsData as $row2) {
                    if ($row2->field_name == $row->field_name) {
                        if ($row->field_type == "checkbox") {
                            $values = explode(", ", $row2->field_value);
                            if (in_array($row->field_value, $values)) {
                                $checked = "checked";
                            } else {
                                $checked = "";
                            }
                        } else {
                            if ($row2->field_value == $row->field_value) {
                                $selected = "selected";
                                $checked = "checked";
                            } else {
                                $selected = "";
                                $checked = "";
                            }
                        }
                    }
                    // if: this is the form field to check
                }
                // foreach: loop to find form field
            } elseif ($row->field_type == "checkbox" && in_array($row->field_value, $_POST[$row->field_name])) {
                $checked = "checked";
            } elseif ($_POST[$row->field_name] == $row->field_value) {
                $selected = "selected";
                $checked = "checked";
            } else {
                $selected = "";
                $checked = "";
            }
            /* get fieldcost (needed for disabled textbox value generation) */
            $fieldcost = $attributesArray[0];
            switch ($row->field_type) {
                case "dropdown":
                    //generates dropdowns
                    $option .= '<option fieldcost="' . $fieldcost . '" value="' . $row->field_value . '" ' . $selected . '>' . $row->field_value . '</option>';
                    break;
                case "checkbox":
                    //generates checkboxes
                    $option .= '<input type="checkbox" id="' . $row->field_name . '" name="' . $row->field_name . '[]" fieldcost="' . $fieldcost . '" value="' . $row->field_value . '" ' . $checked . '><span class="cstem_im_form_radioText">' . $row->field_value . '</span><br/>';
                    break;
                case "radio":
                    //generates radio buttons
                    $option .= '<input type="radio" id="' . $row->field_name . '" name="' . $row->field_name . '" fieldcost="' . $fieldcost . '" class="cstem_im_form_radio" value="' . $row->field_value . '" ' . $checked . '><span class="cstem_im_form_radioText">' . $row->field_value . '</span><br/>';
                    break;
                default:
                    break;
            }
        }
        $nametracking = $row->field_name;
        $prevtype = $row->field_type;
        $prevGroupClass = $attributesArray["groupClass"];
        $prevGroupClass2 = $attributesArray["groupClass2"];
    }
    if ($prevtype == "dropdown") {
        //close the dropdown field
        $option .= '</select>';
    }
    /* Pertain to the last field of the form */
    if ($prevtype != "textfield") {
        $option .= '</fieldset>';
    }
    if ($fieldsetCount != 0) {
        // close outer box on group of fields
        $option .= '</fieldset>';
    }
    if ($fieldset2Count != 0) {
        // close outer box on group of fields
        $option .= '</fieldset>';
    }
    //close out the form
    $option .= '<br /><input type="submit" class="cstem_im_form_submit" value="Submit"></form>';
    $option .= '<br/><br/><span style="line-height: 150%">If you encounter any issues, please do not hesitate to contact us at ' . 'itsupport@c-stem.ucdavis.edu. We will make our best effort to get back to you as soon as we can.</span><br/>';
    $jquery_script .= '</script>';
    $option .= $jquery_script;
    return $option;
}