/* Created by jankoatwarpspeed.com */

(function($) {
    $.fn.formToWizard = function(options) {
        options = $.extend({  
            submitButton: "" 
        }, options); 
        
        var element = this;

        var steps = $(element).find("fieldset");
        var count = steps.size();
        var submmitButtonName = "#" + options.submitButton;
        $(submmitButtonName).hide();						//hide

        // 2
        $(element).before("<ul id='steps'></ul>");

        steps.each(function(i) {
            $(this).wrap("<div id='step" + i + "'></div>");
            $(this).append("<p id='step" + i + "commands'></p>");

            // 2
            var name = $(this).find("legend").html();
            $("#steps").append("<li id='stepDesc" + i + "'>&raquo; " + (i + 1) + "<span>" + name + "</span></li>");

            if (i == 0) {
                createNextButton(i);
                selectStep(i);
            }
            else if (i == count - 1) {
                $("#step" + i).hide();						//hide
                createPrevButton(i);
            }
            else {
                $("#step" + i).hide();						//hide
                createPrevButton(i);
				createNextButton(i);
            }
        });

        function createPrevButton(i) {
            var stepName = "step" + i;
            $("#" + stepName + "commands").append("<a href='#' id='" + stepName + "Prev' class='prev'>< Previous</a>");

            $("#" + stepName + "Prev").bind("click", function(e) {
                $("#" + stepName).hide();					//hide
				// start additions by Michael Pehl
				$.validationEngine.closePrompt(".formError",true); // closing all jquery.validationEngine.js v1.6.3 prompts
				$(".next").hide();
				$(".check" + (i - 1)).show();
				// end additions by Michael Pehl
                $("#step" + (i - 1)).fadeIn(500);				//show
                $(submmitButtonName).fadeOut(500);				//hide
                selectStep(i - 1);
            });
        }

        function createNextButton(i) {
            var stepName = "step" + i;
            $("#" + stepName + "commands").append("<a href='#' id='" + stepName + "Next' class='next'>Next ></a>");

            $("#" + stepName + "Next").bind("click", function(e) {
                $("#" + stepName).hide();					//hide
				// start additions by Michael Pehl
				$.validationEngine.closePrompt(".formError",true); // closing all jquery.validationEngine.js v1.6.3 prompts
				$(".next").hide();
                // end additions by Michael Pehl
				$("#step" + (i + 1)).fadeIn(500);				//show
                if (i + 2 == count)
                    $(submmitButtonName).fadeIn(500);			//show
                selectStep(i + 1);
			});
		}

        function selectStep(i) {
            $("#steps li").removeClass("current");
            $("#stepDesc" + i).addClass("current");
        }

    }
})(jQuery); 
