﻿function doOpenRecoForm(id) {
    if (!g_isAuthenticated) {
        DialogboxLogon.ShowModal($("#dialogLogOn"), function(isAuthenticated) {
            if (isAuthenticated) {
                $.saturneoDialogAdvice({ id: id });
            }
        });
    } else {
        $.saturneoDialogAdvice({ id: id });
    }
    return false;
}


(function($) {

    $.saturneoDialogAdvice = function(options) {
        var defaults = {
            id: null
        };

        // ... validate data
        var validatorOptions = {
            rules: {
                Fullname: {
                    required: _isNewAdvisableItem
                },
                City: {
                    required: _isNewAdvisableItem
                },
                Country: {
                    required: _isNewAdvisableItem
                },
                ZipCode: {
                    required: _isNewAdvisableItem
                },
                /*MainEmail: {
                email: function(element) {
                return false;
                },
                required: false
                },*/
                Comment: {
                    required: false
                },
                AdviceTag: {
                    required: function(element) {
                        return $("#AdviceTagList").val() == "";
                    }
                },
                AudienceIds: {
                    required: function(element) {
                        return $("input[name='TargetAudience']:checked").val() == "PrivateAudience";
                    }
                }
            },
            errorPlacement: function(error, element) {
                FormValidation.PlaceErrors({
                    error: error,
                    element: function() { return element[0].name == 'AudienceIds' ? $('#audiences') : element; }
                });
            },
            errorClass: "errorBubble",
            messages: {
                Fullname: "Veuillez préciser le nom complet du professionel ou de l'entreprise.",
                ZipCode: "Veuillez préciser le code postal.",
                Country: "Veuillez préciser le pays.",
                MainEmail: "Veuillez préciser une adresse e-mail valide.",
                City: "Veuillez préciser la ville.",
                Comment: "Veuillez saisir un commentaire.",
                AdviceTag: "Veuillez saisir un mot-clé.",
                AudienceIds: "Sélectionnez au moins un groupe de contacts."
            }
        }; // validatorOptions END

        // Merges received parameters and default values.
        options = $.extend(defaults, options);

        if ($('#dialogAdvice').length != 0) {
            $('#dialogAdvice').dialog('destroy');
            $('#dialogAdvice').empty();
            $('#dialogAdvice').remove();
        }

        if ($('#dialogAdvice').length == 0) {
            var $elt = $('<div id="dialogAdvice"/>').appendTo('body');


            $.ajax({
                type: "POST",
                dataType: "html",
                url: "/Advice/GetAdviceForm",
                data: { id: options.id },
                success: function(responseText, textStatus) {
                    // Update target element
                    $elt.html(responseText);
                    // Open dialog
                    var $dialog = $elt.dialog({
                        resizable: false,
                        draggable: false,
                        //height: 500,
                        width: 580,
                        position: "top",
                        autoOpen: false,
                        modal: true,
                        title: "Création d'une recommandation",
                        open: function() {
                        },
                        close: function() {
                        }
                    }); // dialog

                    var $form = $('#dialogAdvice').find('form:first');
                    _ensureFormInitialization($form);
                    _refreshAdviceDescription();
                    if ($("#adviceDescription").attr("isNewAdvice") == "False") {
                        $('#dialogAdvice').dialog("option", "title", "Modification d'une recommandation");
                    };
                    _suggestAdvisableItem_hide();

                    $form.formwizard(
                        { //wizard settings
                            historyEnabled: false,
                            formPluginEnabled: false,
                            validationEnabled: true,
                            textSubmit: 'Recommander',
                            textNext: 'Suivant',
                            textBack: 'Précédent',
                            afterNext: _afterNext,
                            afterBack: _afterBack, 
                            submitCallback: SavePrivateAdvice,
                            firstStep: options.id == null ? 0 : 1
                        },
                        validatorOptions,
				        {
				            // form plugin settings
				            success: function(data) { alert(data.registration.statusMessage); },
				            beforeSubmit: function(data) { alert("about to send the following data: \n\n" + $.param(data)) },
				            dataType: 'json',
				            resetForm: false
				        }
                    );

                    $dialog.dialog('open');
                },
                error: function(xhr, textStatus, errorThrown) {
                    if (xhr.getResponseHeader('SESSION_EXPIRED') === '1') {
                        $.saturneoNotification("Votre session a expiré.");
                    } else {
                        // $('#result').html(html);
                    }
                },
                complete: function(xhr, textStatus) {
                    if (xhr.getResponseHeader('SESSION_EXPIRED') === '1') {
                        $.saturneoNotification("Votre session a expiré.");
                        //window.location = '/Search';
                        return;
                    }
                }
            }); // ajax

            return;
        } // if

        // Reset form wizard
        var $form = $('#dialogAdvice').find('form:first');
        $form.formwizard('reset', { firstStep: options.id == null ? 0 : 1 });

        // Reset tag editor and comment
        $('#AdviceTag').saturneoTagEditorV1(
            {
                itemsString: $('#AdviceTag').val(),
                separator: new RegExp("[,;%]+", "g"),
                className: "tagEditor"
            }
        );

        // Ensures that the form is initialized.
        // Caution : initialization must occur only once
        function _ensureFormInitialization($form) {

            // Professional data - BEGIN
            $('#Fullname').blur(function() {
                _refreshAdviceDescription();
            });

            $('#suggestAdvisableItemDivClose').click(function() { _suggestAdvisableItem_hide(); });

            // ... suggest professional data
            $('#Fullname, #City, #PhoneNumber, #MainEmail').blur(function() {
                // ... no suggestion if an item is already selected
                if ($("#ItemId", $("#dialogAdvice")).val() != 0) {
                    return;
                }
                // ... no suggestion if no change since last suggestion
                var $form = $('#dialogAdvice').find('form:first');
                var serializedData = $form.serialize();
                var previousData = $.data($('#suggestAdvisableItemDiv')[0], 'suggestParams');
                if (serializedData == previousData) {
                    return;
                }
                // ... no suggestion if suggestion already in progress
                var suggestInProgress = $.data($('#suggestAdvisableItemDiv')[0], 'suggestInProgress');
                if (typeof (suggestInProgress) != 'undedfined' && suggestInProgress == true) {
                    return;
                }

                _doSuggestAdvisableItem(serializedData);
            });

            // ... autocomplete City (based on ZipCode)
            $("#ZipCode", $form).blur(function() {
                $('#City', $form).flushCache();
                var body = $form.serialize();
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: '/Account/GetCityFromZipCode',
                    data: body,
                    success: function(data) {
                        if (data.length == 1 && $("#City", $form).val() == "") {
                            $("#City", $form).val(data[0].Name);
                        }
                    }
                });
            });

            $("#City", $form)
            .autocomplete('/Account/GetCityFromZipCode',
                {
                    dataType: 'json',
                    extraParams: {
                        zipcode: function() { return $("#ZipCode").val(); }
                    },
                    parse: function(data) {
                        var rows = new Array();
                        if ($("#City").attr('readonly') != true) {
                            // Ignore autocomplete data if field is readonly
                            for (var i = 0; i < data.length; i++) {
                                rows[i] = { data: data[i], value: data[i].Name, result: data[i].Name };
                            }
                        }
                        return rows;
                    },
                    formatItem: function(row, i, max) {
                        return row.Name;
                    },
                    width: 300,
                    highlight: false,
                    multiple: false,
                    multipleSeparator: ","
                }
            );

            // Professional data - END

            // Tag editor for the current advice
            $('#AdviceTag').saturneoTagEditorV1(
                {
                    itemsString: $('#AdviceTag').val(),
                    separator: new RegExp("[,;%]+", "g"),
                    className: "tagEditor"
                }
            );

            // Contacts groups
            var divAudiences = $("#audiences");
            var rdbAudience = $("input[name='TargetAudience']:checked");
            rdbAudience.val() == "PrivateContact" ? divAudiences.hide() : divAudiences.show();
            $("input:radio", $form).click(function() {
                if (this.value == "PrivateContact") {
                    divAudiences.slideUp("medium");
                } else {
                    divAudiences.slideDown("medium");
                }
            });


        } // _ensureFormInitialization - END

        function _isNewAdvisableItem() {
            if ($("#ItemId", $("#dialogAdvice")).text() == "") {
                return true;
            } else {
                return false;
            }
        }

        function _loadProfessionalData(id, callback) {
            if (id) {
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: "/Advice/GetAdvisableItemDetailsJson",
                    data: "id=" + id,
                    success: function(adviceForm) {
                        _populateForm(adviceForm, callback);
                        _refreshAdviceDescription();
                    },
                    error: function(error) {
                        ErrorHandler.TechnicalError(error);
                    }
                });
            }
            else {
                _populateForm(null, callback);
                _refreshAdviceDescription();
            }
        }

        function _populateForm(adviceForm, callback) {
            // Professional data
            $('#ItemId').val(adviceForm ? adviceForm.ItemId : '');
            $('#Fullname, #ZipCode, #Country, #City, #PhoneNumber, #MainEmail')
                .val('')
                .attr('readonly', adviceForm);

            if (adviceForm) {
                if (adviceForm.Fullname) $('#Fullname').val(adviceForm.Fullname);
                if (adviceForm.ZipCode) $('#ZipCode').val(adviceForm.ZipCode);
                if (adviceForm.Country) $('#Country').val(adviceForm.Country);
                if (adviceForm.City) $('#City').val(adviceForm.City);
                if (adviceForm.PhoneNumber) $('#PhoneNumber').val(adviceForm.PhoneNumber);
                if (adviceForm.MainEmail) $('#MainEmail').val(adviceForm.MainEmail);
            }
            else {
                $('#Country').val("France");
            }

            // Advice comment and tags
            // Tag editor for the current advice
            $('#Comment, #AdviceTagList').val('');
            if (adviceForm) {
                if (adviceForm.Comment) $('#Comment').val(adviceForm.Comment);
                if (adviceForm.AdviceTagList) {
                    $('#AdviceTag').saturneoTagEditorV1(
                        {
                            itemsString: adviceForm.AdviceTagList,
                            separator: new RegExp("[,;%]+", "g"),
                            className: "tagEditor"
                        }
                    );
                }
            }

            if (adviceForm && !adviceForm.IsNewAdvice) {
                $('#dialogAdvice').dialog("option", "title", "Modification d'une recommandation");
                $("#adviceDescription").attr("isNewAdvice", "False");
            } else {
                $('#dialogAdvice').dialog("option", "title", "Création d'une recommandation");
                $("#adviceDescription").attr("isNewAdvice", "True");
            }

            // Audience
            $("input[name='TargetAudience']").removeAttr("checked");
            $("input[name='AudienceIds']").removeAttr("checked");
            $("#audiences").hide();
            if (adviceForm) {
                if (adviceForm.TargetAudience == "PrivateContact") {
                    $("input[name='TargetAudience']:nth(0)").attr("checked", "checked");
                } else {
                    $("input[name='TargetAudience']:nth(1)").attr("checked", "checked");
                    $("#audiences").show();
                    // Set checkboxes for audiences
                    $("input[name='AudienceIds']").each(function(index) {
                        var id = parseInt($(this).val());
                        if ($.inArray(id, adviceForm.AudienceIds) > -1) {
                            $(this).attr("checked", "checked");
                        }
                    });
                }
            } else {
                $("input[name='TargetAudience']:nth(0)").attr("checked", "checked");
            }

            if (callback && typeof callback == 'function') callback(adviceForm);
        }

        function _afterNext(evenData) {
            if (evenData.currentStep == 1) 
            {
                _suggestAdvisableItem_hide();
            }
        }

        function _afterBack(evenData) {
            // NOP
        }

        function SavePrivateAdvice() {
            var $form = $('#dialogAdvice').find('form:first');
            var formContent = $form.serialize();

            $.ajax({
                type: "POST",
                dataType: "json",
                url: "/Advice/SavePrivateAdvice",
                data: formContent,
                success: function(result) {
                    if (result.success) {
                        if (result.message) {
                            $.saturneoNotification(result.message);
                        }
                        $('#dialogAdvice').dialog('close');
                    } else if (result.errors) {
                        FormValidation.ShowErrors($form, result);
                        // search for first step containing an error.
                        /* TODO DREM 
                        FormValidation.FindContainerForError([
                        { container: $('#chooseprostepform'), data: 'chooseprostep' },
                        { container: $('#advicestepform'), data: 'advicestep' },
                        { container: $('#audiencestepform'), data: 'audiencestep'}],
                        result.errors,
                        function(container, step) {
                        // if one is found, switch to this step and show errors for this step.
                        changeStep(step, true, function() {
                        FormValidation.ShowErrors(container, result);
                        });
                        });
                        */
                    }
                    else if (typeof result.message != 'undefined') {
                        ErrorHandler.TechnicalError(result.message);
                    }
                },
                error: function(error) {
                    ErrorHandler.TechnicalError(error);
                }
            });
        }

        function _refreshAdviceDescription() {
            var fullname = $('#Fullname').val();
            if (fullname)
                $('#adviceDescription').text(fullname).parent().show();
            else
                $('#adviceDescription').parent().hide();
        }


        function _doSuggestAdvisableItem(serializedData) {
            $.data($('#suggestAdvisableItemDiv')[0], 'suggestInProgress', true);
            var $form = $('#dialogAdvice').find('form:first');

            $.data($('#suggestAdvisableItemDiv')[0], 'suggestParams', serializedData);
            $.ajax({
                type: "POST",
                dataType: "json",
                url: "/Search/SuggestUser",
                data: serializedData,
                success: function(result) {
                    try {
                        if (result.Suggestions.length == 0) {
                            $.data($('#suggestAdvisableItemDiv')[0], 'suggestInProgress', false);
                            return;
                        }

                        var items = new Array();
                        $.each(result.Suggestions, function(index, suggestion) {
                            items.push({ text: suggestion.DisplayName, id: suggestion.Id });
                        });
                        $.data($('#suggestAdvisableItemDiv')[0], 'suggestInProgress', false);
                        if (items.length) {
                            _suggestAdvisableItem_show($('#Fullname'), items, function(id) {
                                _loadProfessionalData(id, function() {
                                    //TODO ? changeStep('advicestep');
                                });
                            });
                        } else {
                            _suggestAdvisableItem_hide();
                        }
                    }
                    catch (er) {
                        $.data($('#suggestAdvisableItemDiv')[0], 'suggestInProgress', false);
                    }
                },
                error: function(error) {
                    $.data($('#suggestAdvisableItemDiv')[0], 'suggestInProgress', false);
                    ErrorHandler.TechnicalError(error);
                }
            });
            $.data($('#suggestAdvisableItemDiv')[0], 'suggestInProgress', false);
        }

        function _suggestAdvisableItem_refresh() {
            return $('#suggestAdvisableItemList').html('');
        }

        function _suggestAdvisableItem_populate(items, itemSelectedCallback) {
            var ul = _suggestAdvisableItem_refresh();

            $.each(items, function(index, item) {
                var li = document.createElement('li');
                var a = document.createElement('a');
                a.href = '#';
                $(a).click(function() {
                    itemSelectedCallback(item.id);
                    _suggestAdvisableItem_hide();
                });
                $(a).text(item.text);
                if (item.title)
                    a.title = item.title;

                li.appendChild(a);
                ul[0].appendChild(li);
            });
        }

        function _suggestAdvisableItem_show(element, items, itemSelectedCallback) {
            _suggestAdvisableItem_populate(items, itemSelectedCallback);
            $('#suggestAdvisableItemDiv').fadeIn(500);
        }

        function _suggestAdvisableItem_hide() {
            if ($('#suggestAdvisableItemDiv').length > 0) {
                $.data($('#suggestAdvisableItemDiv')[0], 'suggestInProgress', false);
            }
            $('#suggestAdvisableItemDiv').hide();
        }


    }; // saturneoDialogAdvice - END

})(jQuery);

(function($) {

    $.fn.formwizard = function(wizardSettings, validationSettings, formOptions) {

        /**
        * Creates a wizard of all matched elements
        *
        * @constructor
        * @name $.formwizard
        * @param Hash wizardSettings A set of key/value pairs to set as configuration properties for the wizard plugin.
        * @param Hash validationSettings A set of key/value pairs to set as configuration properties for the validation plugin.
        * @param Hash formOptions A set of key/value pairs to set as configuration properties for the form plugin.
        */

        var settings = $.extend({
            historyEnabled: false,
            validationEnabled: false,
            formPluginEnabled: false,
            linkClass: ".link",
            submitStepClass: ".submit_step",
            back: ":reset",
            next: ":submit",
            textSubmit: 'Submit',
            textNext: 'Next',
            textBack: 'Back',
            afterNext: undefined,
            afterBack: undefined,
            serverSideValidationUrls: undefined,
            callable: false,
            submitCallback: undefined,
            firstStep: 0
        }, wizardSettings);

        var formOptionsSuccess = (formOptions) ? formOptions.success : undefined;
        var formSettings = $.extend(formOptions, {
            success: function(data) {
                if (formOptions && formOptions.resetForm || !formOptions) {
                    navigate(0);
                    if (settings.historyEnabled) {
                        $.historyLoad(0);
                    } else {
                        renderStep();
                    }
                }
                if (formOptionsSuccess) {
                    formOptionsSuccess(data);
                } else {
                    alert("success");
                }
            }
        });
        var currentStep = settings.firstStep;
        var previousStep = undefined;
        var form = $(this);
        var steps = $(this).find(".step");
        var backButton = $(this).find(settings.back);
        var nextButton = $(this).find(settings.next);
        var activatedSteps = new Array();
        for (var istep = 0; istep < currentStep; istep++) {
            activatedSteps.push(istep);
        }

        var isLastStep = false;

        var $wizardDialog = form.parents(".ui-dialog-content:first");
        var $wizardDialogParent = form.parents(".ui-dialog:first");

        /** 
        * Navigation event callbacks 
        */
        nextButton.click(function() {
            if (settings.validationEnabled) {
                // Note : validation only occurs for fields that are
                // not disabled -> ie, fields of the current step.
                if (!form.valid()) { form.validate().focusInvalid(); return false; }
            }

            if (isLastStep) {
                for (var i = 0; i < steps.size(); i++) {
                    steps.eq(i).find(":input").removeAttr("disabled");
                }

                if (settings.formPluginEnabled) {
                    form.ajaxSubmit(formSettings);
                    return false;
                }
                if ($.isFunction(settings.submitCallback)) {
                    settings.submitCallback();
                    return false;
                }
                form.submit();
                return false;
            }

            // Doing server side validation for the steps
            if (settings.serverSideValidationUrls) {
                var options = settings.serverSideValidationUrls[currentStep];
                if (options != undefined) {
                    var success = options.success;
                    $.extend(options, { success: function(data, statusText) {
                        if ((success != undefined && success(data, statusText)) || (success == undefined)) {
                            continueToNextStep();
                        }
                    }
                    })
                    form.ajaxSubmit(options);
                    return false;
                }
            }
            continueToNextStep();
            return false;
        });

        backButton.click(function() {
            if (settings.historyEnabled && activatedSteps.length > 0) {
                history.back();
            } else if (activatedSteps.length > 0) {
                handleHistory(activatedSteps[activatedSteps.length - 2]);
            }
            if (settings.afterBack)
                settings.afterBack({ "currentStep": currentStep,
                    "previousStep": previousStep,
                    "isLastStep": isLastStep,
                    "activatedSteps": activatedSteps
                });
            return false;
        });

        /**
        * Continues to the next step in the wizard
        */
        function continueToNextStep() {
            navigate(currentStep);
            renderStep();

            if (settings.historyEnabled) {
                $.historyLoad(currentStep);
            } else {
                handleHistory(currentStep);
            }

            if (settings.afterNext)
                settings.afterNext({ "currentStep": currentStep,
                    "previousStep": previousStep,
                    "isLastStep": isLastStep,
                    "activatedSteps": activatedSteps
                });
        }

        /*
        * Renders the current step and disables the input fields in other steps
        */
        function renderStep() {
            backButton.removeAttr("disabled");
            nextButton.val(settings.textNext);

            if (previousStep != undefined) {
                steps.eq(previousStep)
                    .hide()
					.find(":input")
					.attr("disabled", "disabled");
            }

            var targetWidth = parseInt(steps.eq(currentStep).css('width'));
            var targetTop = $(window).scrollTop() + 55;
            var targetLeft = ($(window).width() - targetWidth) / 2 + $(window).scrollLeft() - 19;

            $wizardDialogParent
                .stop()
                .animate(
                            { width: (targetWidth + 38) + 'px' },
                            { queue: false, duration: 500 }
                        )
                .animate(
                            { top: targetTop + 'px' },
                            { queue: false, duration: 500 }
                        )
                .animate(
                            { left: targetLeft + 'px' },
                            { queue: false,
                                duration: 500,
                                complete: function() {
                                    steps.eq(currentStep)
                                     .show()
                                     .find(":input")
                                     .removeAttr("disabled");
                                }
                            }
                        )
                 ;

            if (isLastStep) {
                for (var i = 0; i < activatedSteps.length; i++) {
                    steps.eq(activatedSteps[i]).find(":input").removeAttr("disabled");
                }
                nextButton.val(settings.textSubmit);
            } else if (currentStep == 0) {
                backButton.attr("disabled", "disabled");
            }
        }

        /**
        * Checks if the step is the last step in a wizard route
        *
        * @name checkIflastStep
        * @type undefined
        * @param Number step The step to check.
        */
        function checkIflastStep(step) {
            var link = getLink(step);

            isLastStep = false;

            if ((("." + link) == settings.submitStepClass) || (link == undefined && (step * 1) == steps.length - 1)) {
                isLastStep = true;
            }
        }

        /**
        * Decides and sets the current step in the wizard 
        *
        * @name navigate
        * @type undefined
        * @param Number step The step to navigate from.
        */
        function navigate(step) {
            var link = getLink(step);

            if (link) {
                var navigationTarget = steps.index($("#" + link));
                if (navigationTarget == -1) {
                    return;
                } else {
                    previousStep = currentStep;
                    currentStep = navigationTarget;
                }
                checkIflastStep(step);
            } else if (link == undefined && !isLastStep) {
                previousStep = currentStep;
                currentStep++;
                checkIflastStep(currentStep);
            }
        }

        /**
        * Finds the valid link for the step (if there is one)
        *
        * @name getLink
        * @type String
        * @param Number step The step to search for valid links
        */
        function getLink(step) {
            var link = undefined;
            var links = steps.eq((step * 1)).find(settings.linkClass);

            if (links != undefined && links.length == 1) {
                link = links.val();
            } else if (links != undefined && links.length > 1) {
                // assume that the link is a radio button or checkbox
                link = steps.eq((step * 1)).find(settings.linkClass + ":checked").val();
            }
            return link;
        }

        /**
        * Handles back navigation (and browser back and forward buttons if history is enabled)
        *
        * @name handleHistory
        * @type undefined
        * @param String hash The hash used in the browser history
        */
        function handleHistory(hash) {
            if (!hash) {
                hash = 0;
            }
            if (activatedSteps[activatedSteps.length - 2] == hash) {
                var elem = activatedSteps.pop();
            } else {
                activatedSteps.push(hash);
            }
            previousStep = currentStep;
            currentStep = hash;
            checkIflastStep(hash);
            renderStep();
        }

        /**
        * Resets the wizard to its original state
        *
        * @name resetWizard
        * @type undefined
        */
        function resetWizard(eventArgs) {
            if (form.resetForm != undefined) {
                form.resetForm();
            }
            if (eventArgs && eventArgs.firstStep) {
                currentStep = eventArgs.firstStep;
            } else {
                currentStep = 0;
            }
            for (var i = 0; i < steps.length; i++) {
                if (i != currentStep) {
                    steps.eq(i).hide().find(":input").attr("disabled", "disabled");
                }
            }
            previousStep = undefined;
            activatedSteps = new Array();
            for (var istep = 0; istep < currentStep; istep++) {
                activatedSteps.push(istep);
            }
            isLastStep = false;
            if (settings.historyEnabled) {
                $.historyLoad(0);
            } else {
                renderStep();
            }
        }

        /**
        * Initialization
        */

        if (settings.validationEnabled && jQuery().validate == undefined) {
            settings.validationEnabled = false;
            alert("the validation plugin needs to be included");
        } else if (settings.validationEnabled) {
            form.validate(validationSettings);
        }

        if (settings.formPluginEnabled && jQuery().ajaxSubmit == undefined) {
            settings.formPluginEnabled = false;
            alert("the form plugin needs to be included");
        }

        // Hide all steps, and disable all input fields, sothat
        // validation is also disabled.
        steps.hide().find(":input").attr("disabled", "disabled"); ;

        if (settings.historyEnabled && $.historyInit == undefined) {
            settings.historyEnabled = false;
            alert("the history plugin needs to be included");
        } else if (settings.historyEnabled) {
            $.historyInit(handleHistory);
        } else {
            handleHistory(currentStep);
        }

        backButton.val(settings.textBack);

        if (settings.callable == true) {
            // provides a way of calling internal methods (note that $.fn.formwizard is redefined)
            $.fn.formwizard = function(event, eventArgs) {
                switch (event) {
                    case 'reset': resetWizard(eventArgs); break;
                }
                return $(this);
            };
        }
        return $(this);
    };
})(jQuery);
