/* 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();

        // 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("h5").html();
            var name2 = $(this).find("legend").html();
            $("#steps").append("<li id='stepDesc" + i + "'>"+ (i + 1) + ". " + name + "<span>" + name2 + "</span></li>");

            if (i == 0) {
                createNextButton(i);
                selectStep(i);
            }
            else if (i == count - 1) {
                $("#step" + i).hide();
                createPrevButton(i);
            }
            else {
                $("#step" + i).hide();
                createPrevButton(i);
                createNextButton(i);
            }
        });

        function createPrevButton(i) {
            var stepName = "step" + i;
            $("#" + stepName + "commands").append("<a href='#contact_form' id='" + stepName + "Prev' class='button floatLeft prev'>&laquo; Tagasi</a>");

            $("#" + stepName + "Prev").bind("click", function(e) {
                $("#" + stepName).hide();
                $("#step" + (i - 1)).show();
                $(submmitButtonName).hide();
                selectStep(i - 1);
				/*
				$("#steps").removeClass("bg" + i);
				$("#stepDesc" + (i - 1)).removeClass("filled");
				$("#steps").addClass("bg" + (i - 1));
				*/
            });
        }

        function createNextButton(i) {
            var stepName = "step" + i;
            $("#" + stepName + "commands").append("<a href='#contact_form' id='" + stepName + "Next' class='button floatRight next'>Edasi &raquo;</a>");

            $("#" + stepName + "Next").bind("click", function(e) {
                $("#" + stepName).hide();
                $("#step" + (i + 1)).show();
                if (i + 2 == count)
                    $(submmitButtonName).show();
                selectStep(i + 1);
            });
        }

        function selectStep(i) {
            $("#steps li").removeClass("current");
            $("#steps").addClass("bg" + i);
            $("#stepDesc" + i).addClass("current");
			/*
            $("#stepDesc" + (i - 1)).addClass("filled");
			*/
        }

    }
})(jQuery); 
