﻿Cwo.RegisterNamespace("Cwo.Form");

Cwo.SimpleModal = function (title, content, closeButtonLabel, modalClass) {
    if (typeof (modalClass) === "undefined") {
        this.modalClass = "OneColumnModalContainer";
    } else {
        this.modalClass = modalClass;
    }
    var modalHTML = '<div class="' + this.modalClass + '"><div class="Body"><div class="Title"><h6>#Title#</h6><a href="#" class="ModalClose"><span>#CloseButtonLabel#</span></a></div><div class="Content">#Content# <BR></div></div></div>';

    if (title !== null) {
        modalHTML = modalHTML.replace('#Title#', title);
    } else {
        modalHTML = modalHTML.replace('#Title#', 'Title');
    }

    if (content !== null) {
        modalHTML = modalHTML.replace('#Content#', content);
    } else {
        modalHTML = modalHTML.replace('#Content#', 'Content');
    }

    if (closeButtonLabel !== null) {
        modalHTML = modalHTML.replace('#CloseButtonLabel#', closeButtonLabel);
    } else {
        modalHTML = modalHTML.replace('#CloseButtonLabel#', 'Close');
    }

    $("#GlobalModalContainer").html(modalHTML);
    $("#GlobalModalWrapper").height($(document).height()).show();
    $('a.ModalClose').bind('click', function (evt) {
        evt.preventDefault();
        $("#GlobalModalWrapper").hide();
        $("#GlobalModalContainer").html("");
    });
    Cwo.SimpleModal.BindEscape();
};

Cwo.SimpleModal.BindEscape = function () {
    // Bind the escape key to close Simple Modals (we don't bind this globally for all forms as it may introduce usability issues for
    // more complex forms in modals.
    $("#GlobalModalWrapper").addClass('SimpleModal');
    $(document).bind("keyup", function (e) { Cwo.SimpleModal.GlobalKeyPressed(e); });
};

Cwo.SimpleModal.GlobalKeyPressed = function (e) {
    var keyCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode,
        ESCKey = 27;
    
    if (keyCode === ESCKey) {
        if ($("#GlobalModalWrapper").hasClass('SimpleModal')) {
            $("#GlobalModalWrapper").hide().removeClass('SimpleModal');
        }
    }
};

Cwo.Form = function (ButtonID, InitialNodeID, IsSecure, ContentControl, Data, CallbackEvent, OnLoadEvent, isErrorForm) {
    if (ButtonID === "") { ButtonID = null; }
    // private variables
    var cwoForm = this,
        button = $("#" + ButtonID),
        isSecure = IsSecure,
        isModal = true,
        modalContainer = $("#GlobalModalWrapper"),
        modalContent = $("#GlobalModalContainer"),
        loading = $("#GlobalModalLoading"),
        serviceUrl = "/webservices/Form.asmx",
        callbackEvent = (CallbackEvent !== null) ? CallbackEvent : null;

    this.onLoadEvent = (OnLoadEvent !== null) ? OnLoadEvent : null;
    cwoForm.isErrorForm = isErrorForm; // This is a load of the error form - don't go recursive if an error occurs!

    this.Data = (Data === undefined) ? null : Data;

    // Use the custom html control to populate with content if not a modal
    if ((ContentControl !== undefined) && (ContentControl !== "") && (ContentControl !== null)) {
        modalContent = $("#" + ContentControl);
        isModal = false;
    }
    if (!loading.length) {
        modalContainer.html('<div id="GlobalModalLoading"><div></div></div>');
    }
    if (isModal && (!modalContent.length)) {
        modalContainer.append('<div id="GlobalModalContainer"></div>');
        modalContent = $("#GlobalModalContainer");
    }

    // Use the secure URL when https is needed
    if (isSecure) {
        serviceUrl = "/secure/webservices/Form.asmx";
    }

    // public methods
    this.EnquiryID = null;
    this.FormFields = null;
    this.ClearErrors = function () {
        $("div.Error").remove();
        modalContent.find(".Error").removeClass("Error");
    };
    this.DisplayModal = function () {
        if (isModal) {
            modalContainer.height($(document).height());
            modalContainer.show();
            // Hide dropdowns in IE6
            if (Cwo.Page.Browser.IsIE6) {
                $('SELECT').hide();
            }
        }
    };
    this.CloseModal = function () {
        if (isModal) {
            // Hide the modal and clear the content
            modalContainer.hide();
            modalContent.html("");
            if (Cwo.Page.Browser.IsIE6) {
                $('SELECT').show();
            }
        }
    };
    this.Load = function (nodeID) {
        // Send the AJAX request
        NodeID = nodeID;
        var serviceData = { nodeID: NodeID, data: this.Data };
        new Cwo.AjaxCall(serviceUrl + "/Load", JSON.stringify(serviceData), cwoForm.FormLoaded, null, null, cwoForm.isErrorForm);
    };

    this.ShowErrors = function (ErrorMessage, ValidationErrors) {
        modalContainer.find(".ErrorMessage").html("");

        if (ValidationErrors !== null) {
            var errors = ValidationErrors;

            // Display the errors
            for (var i = 0; i < errors.length; i++) {
                if (errors[i].HTMLControlID.length > 0) {
                    $("#" + errors[i].HTMLControlID).parent().addClass("Error").find(".ToolTip").fadeIn();
                    $("#" + errors[i].HTMLControlID).parent().find("div.ToolTip div.One div.Two").html(errors[i].Message);
                } else {
                    //ErrorMessage = errors[i].Message;
                    $("<div>" + errors[i].Message + "</div>").addClass("Error").appendTo(".ErrorMessage");
                    $(".ErrorMessage").show();
                }
            }
        }

        // Show the generic error message
        if (ErrorMessage !== null && ErrorMessage !== "") {
            modalContainer.find(".ErrorMessage").html(ErrorMessage).show();
        }
    };

    this.Submit = function (NodeID) {
        // Populate the data to send with values
        var dictionary = {},
            i = 0,
            control,
            serviceData;

        for (i = 0; i < cwoForm.FormFields.length; i += 1) {
            control = $("#" + cwoForm.FormFields[i].HTMLControlID);

            if (control.is(":checkbox") || control.is(":radio")) {
                // .val() doevsn't work for check boxes and radio buttons
                dictionary[cwoForm.FormFields[i].Name] = control.is(":checked");
            } else {
                dictionary[cwoForm.FormFields[i].Name] = control.val();
            }
        }

        // Send the AJAX request
        serviceData = { nodeID: NodeID, enquiryID: cwoForm.EnquiryID, data: JSON.stringify(dictionary) };
        new Cwo.AjaxCall(serviceUrl + "/Submit", JSON.stringify(serviceData), cwoForm.Response, null, null, cwoForm.isErrorForm);
    };

    this.FormLoaded = function (Data) {
        cwoForm.Response(Data);
        if (cwoForm.onLoadEvent !== null && cwoForm.onLoadEvent !== undefined) {
            cwoForm.onLoadEvent();
        }
    };

    this.Response = function (Data) {
        var i = 0,
            errors;
        if (Data.d.CloseModal !== null && Data.d.CloseModal === true) {
            // No modal & no errors to load; close current.
            cwoForm.CloseModal();
            // When alert response is received, execute the callback function.
            if (callbackEvent !== null) {
                callbackEvent();
            }
        } else {
            // Hide the loading overlay
            loading.hide();
            // Clear any error messages
            cwoForm.ClearErrors();
            // Did the form validate

            if (Data.d.ContentContainer !== null) {
                if (Data.d.ContentContainer.NodeID > 0) {
                    NodeID = Data.d.ContentContainer.NodeID;
                }
                cwoForm.EnquiryID = Data.d.ContentContainer.EnquiryID;
                cwoForm.FormFields = Data.d.ContentContainer.FormFields;
                modalContent.html(Data.d.ContentContainer.Html);
            }


            if (!Data.d.Success) {
                // Did the form validate
                cwoForm.ShowErrors(Data.d.ErrorMessage, Data.d.ValidationErrors);
            }

            // Log the form name to analytics as a "g-code"
            if (Data.d.ContentContainer !== null && Data.d.ContentContainer.NodeName !== undefined) {
                Cwo.LogMIActivity(window.location.pathname + "contact/" + Data.d.ContentContainer.NodeName);
            }

            // Load the HTML into the page
            if ((ContentControl === undefined) || (ContentControl === "") || (ContentControl === null)) {
                scroll(0, 0); // If this is a modal we are scrolling to the top of the page. We don't do this for in-page forms.
            }


            modalContent.find(".ModalClose").unbind('click').bind("click", function (evnt) { evnt.preventDefault(); cwoForm.CloseModal(); });

            // Bind the Submit button
            modalContent.find(".ModalContactButton").unbind('click').bind("click", function () {

                // White out the screen and show a loading icon
                //loading.show().height(modalContent.find(".Body").height());
                loading.show().height(100);

                // Display the modal
                cwoForm.DisplayModal();
                cwoForm.Submit(NodeID);
            });
        }
    };

    // bind the events
    $(document).ready(function () {
        Cwo.Form.OnStart = function () {
            if (ButtonID === null || ButtonID === undefined || ButtonID.length === 0) {
                // When no button ID is sent, load the Form immediately
                cwoForm.DisplayModal();
                cwoForm.Load(InitialNodeID, "");
            } else {
                button.click(function (e) {
                    // Prevent the default action on a button, which will reload the page
                    e.preventDefault();
                    // Display the modal
                    cwoForm.DisplayModal();
                    cwoForm.Load(InitialNodeID, "");
                });
            }
        };

        // Exception handling code to log exceptions to the event viewer
        if (window.navigator.userAgent.indexOf("MSIE") > -1) {
            Cwo.Form.OnStart();
            return;
        }

        try {
            Cwo.Form.OnStart();
        } catch (ex) {
            Cwo.Error.TrackError(ex); // re-throw ex if error should propergate
        }
    });
};

