var FormBuilderRender = {
    RenderForms: function(form) {
        //Attach the events that highlight the fieldsets when clicked.
        this.BindSelectedFields(form);

        //Add images to drop downs that are image containers.
        this.BindDropDownControls(form);

        //Add the function to keep track of selected price items.
        this.BindPriceFields(form);

        //Load the container for the error messages after the header
        Object.extend(form, { errorSummary: new Element("div", { "style": "display:none;", "class": "errorSummary" }) });
        form.errorSummary.insert(new Element("p").update("Please enter the required information"));
        Element.insert(form.container.select(".formHeader")[0], { after: form.errorSummary });

        //Add the form validation function and properties.
        Object.extend(form, { fldErrors: new Array(), submitEventWatch: this.formHandler.bind(this, form) });
    },

    BindSelectedFields: function(form) {
        //Add the event to the container to ignore the enter button
        form.container.select("input").each(function(input, index) {
            input.observe("keydown", function(event) {
                if (event.keyCode == 13)
                    Event.stop(event);
            } .bindAsEventListener(this));
        }, this);

        //Add the event that highlights fieldsets when they are clicked.
        form.container.select(".fieldItem").each(function(item, index) {
            item.observe("click", function(event, field) {
                $$(".fieldSelected").each(function(item) {
                    if (this.id != item.id)
                        item.removeClassName("fieldSelected");
                });
                field.addClassName("fieldSelected");
            } .bindAsEventListener(this, item));
        }, this);

        //Add the event that highlights fieldsets when they are focused.
        form.container.select("input, textarea, select").each(function(item, index) {
            if (item.type && item.type != "button") {
                item.observe("focus", function(event, element) {
                    var parentDiv = element.up("div.fieldItem");
                    if (!parentDiv.hasClassName("fieldSelected")) {
                        $$(".fieldSelected").each(function(item) {
                            item.removeClassName("fieldSelected");
                        }, this);
                        parentDiv.addClassName("fieldSelected");
                    }
                } .bindAsEventListener(this, item));
            }
        }, this);
    },

    BindDropDownControls: function(form) {
        var imageDomain = form.urlScheme + "www.formbldr.com/images/flags/";

        //Add images to drop downs, like the country list.
        form.container.select(".dropdown-image-container").each(function(dd_container) {
            var dropDown = dd_container.select(".dropdown")[0];
            if (dropDown.options.length > 0) {
                dd_container.select(".dropdown-image")[0].insert(new Element("img", { "src": imageDomain + dropDown.options[dropDown.selectedIndex].value + ".png" }));
                dropDown.observe("change", function(event) {
                    this.next(".dropdown-image", 0).update(new Element("img", { "src": imageDomain + this.options[this.selectedIndex].value + ".png", "width": "16", "height": "11" }));
                });
                dropDown.observe("keypress", function(event) {
                    if (!Prototype.Browser.IE) {
                        this.next(".dropdown-image", 0).update(new Element("img", { "src": imageDomain + this.options[this.selectedIndex].value + ".png", "width": "16", "height": "11" }));
                    }
                });
            }
        });
    },

    BindPriceFields: function(form) {
        //Add the hidden field that tracks selected prices
        Object.extend(form, { priceSelectedField: new Element("input", { "type": "hidden", "name": "priceField_" + form.properties.formID, "value": "" }) });
        form.container.insert(form.priceSelectedField);

        //Go through each fieldset and find the price fields.
        form.fieldsets.each(function(fieldset, fsIndex) {
            var fieldType = form.elements[fsIndex].fieldType;
            fieldset.select("input.priceField").each(function(field, fIndex) {
                if (fieldType == "multiplechoice")
                    field.observe("click", this.PriceFieldUpdate.bindAsEventListener(this, form, fieldset, field, true));
                else
                    field.observe("click", this.PriceFieldUpdate.bindAsEventListener(this, form, fieldset, field, false));

                if (field.checked) {
                    form.priceSelected.push(field.optionID);
                    fieldset.lastSelectedPrice = field.optionID;
                }
            }, this);

            fieldset.select("select.priceField").each(function(field, fIndex) {
                field.observe("change", function(event, form, field) {
                    var optId = field.options[field.selectedIndex].optionID;
                    var index = form.priceSelected.indexOf(field.lastSelectedPrice);
                    if (index >= 0)
                        form.priceSelected.splice(index, 1);
                    form.priceSelected.push(optId);
                    field.lastSelectedPrice = optId;
                } .bindAsEventListener(this, form, field));

                var optId = field.options[field.selectedIndex].optionID;
                form.priceSelected.push(optId);
                field.lastSelectedPrice = optId;
            }, this);
        }, this);
    },

    PriceFieldUpdate: function(event, form, fieldset, field, isMultipleChoice) {
        if (field.checked) {
            if (form.priceSelected.indexOf(field.optionID) < 0) {
                if (isMultipleChoice && fieldset.lastSelectedPrice) {
                    var index = form.priceSelected.indexOf(fieldset.lastSelectedPrice);
                    if (index >= 0)
                        form.priceSelected.splice(index, 1);
                }
                form.priceSelected.push(field.optionID);
                fieldset.lastSelectedPrice = field.optionID;
            }
        } else {
            var pIndex = form.priceSelected.indexOf(field.optionID);
            if (pIndex > 0) {
                form.priceSelected.splice(index, 1);
            }
        }
    },

    formResponseHandler: function(form, frame) {
        //Check to see what the server says about the post.
        var fDoc, fWin;
        //Get access to the iframe document
        if (frame.contentDocument) {
            fDoc = frame.contentDocument;
            fWin = frame.contentWindow;
        } else if (frame.contentWindow) {
            fDoc = frame.contentWindow.document;
            fWin = frame.contentWindow;
        } else {
            fDoc = window.frames[frame.id].document;
            fWin = window.frames[frame.id];
        }
        try {
            var r = fDoc.forms[0]["hfResponse"].value.evalJSON(true);
            this.responseHandler(form, r);
        } catch (err) { }
    },

    responseHandler: function(form, r) {
        if (!r.formResponse.isSuccess) {
            //If there are errors report them
            for (i = 0; i < r.formResponse.elements.length; i++) {
                form.fldErrors.push({ fieldset: form.fieldsets[r.formResponse.elements[i].fieldset], message: r.formResponse.elements[i].message, fields: [] });
            }
            FormBuilderValidate.AddErrors(form);
        } else {
            switch (r.formResponse.confirmationType) {
                case "text":
                    //Show success message
                    this.initializeMessage(r.formResponse.confirmationText, form);
                    break;
                case "redirect":
                    //Redirect to specific url
                    location.href = r.formResponse.confirmationText;
                    break;
                case "form":
                    //Build the form
                    this.buildForm(r.formResponse.confirmationText.evalJSON(true));
                    break;
            }
        }
    },

    buildForm: function(formObj) {
        //Add the form to the body.
        var body = $$("body")[0];
        var newForm = new Element("form", { "action": formObj.action, "method": formObj.method, "target": "_parent" });
        body.insert(newForm);

        //Add the hidden elements
        formObj.elements.each(function(element, index) {
            newForm.insert(new Element("input", { "type": "hidden", "name": element.name, "value": element.value }));
        }, this);

        //Submit the form.
        newForm.submit();
    },

    linkString: function() {
        if (Prototype.Browser.IE)
            return "history.back(2)";
        else
            return "history.go(-2)";
    },

    initializeMessage: function(message, form) {
        //Show the success message in a lightbox.
        FormBuilderLightbox.Show({
            container: form.container,
            afterShow: function(options) {
                //Create elements
                var wrapper = new Element("div", { "class": "confirmation-content" });
                var content = new Element("div", { "class": "confirmation-content-message" });
                var returnLink = new Element("a", { "href": "javascript:" + FormBuilderRender.linkString() + ";" }).update("Return to the previous page");

                //Apply the users success message
                if (options.showMessage)
                    content.update("<p>&nbsp;</p><p><strong>" + options.showMessage + "</strong></p>");

                //Append the link button in a p tag to the content
                content.insert(new Element("p").insert(returnLink));

                //Add it all to the lightbox content holder.
                wrapper.insert(content);
                var lightBoxContent = $$('#lightbox_content .lightbox-content')[0];
                lightBoxContent.update();
                lightBoxContent.insert(wrapper);
            },
            showMessage: message,
            closeable: false
        });
    },

    formHandler: function(form) {
        //Validate the form post.
        form.priceSelectedField.value = form.priceSelected;
        return FormBuilderValidate.Validate(form);
    },

    appendSubmitControls: function(form) {
        var submitContainer = new Element("div", { "class": "submitButtonContainer" });

        var button = new Element("input", {
            "type": "submit",
            "class": "submitButton",
            "value": "Submit"
        });

        button.observe("click", function(event, form) {
            if (form.submitEventWatch) {
                if (!form.submitEventWatch())
                    Event.stop(event);
            }
        } .bindAsEventListener(this, form));

        submitContainer.insert(button);

        if (form.properties.showReportAbuseLink) {
            var span = new Element("span").update("&nbsp;");
            var reportAbuseLink = new Element("a", {
                "href": "/public/reportabuse.aspx",
                "target": "_blank"
            }).update("Report Abuse");
            submitContainer.insert(span);
            submitContainer.insert(reportAbuseLink);
        }

        form.container.insert(submitContainer);
    },

    loadViewState: function(form) {
        if (form.viewStateField.value != "") {
            var frmObj = document.forms[0];
            var viewState = form.viewStateField.value.evalJSON(true);
            viewState.each(function(field, index) {
                var htmlField = frmObj[field.name];
                if (!htmlField.type || htmlField.type.toLowerCase() != "file") {
                    htmlField.value = field.value;
                    if (field.checked)
                        htmlField.checked = true;
                }
            }, this);
        }
    },

    saveViewState: function(form) {
        var viewState = new Array();
        form.container.select("INPUT, SELECT, TEXTAREA").each(function(field, value) {
            if (field.name != "")
                viewState.push({ name: field.name, value: field.value, checked: (field.checked ? true : false) });
        }, this);
        form.viewStateField.value = viewState.toJSON();
    }

}