/* Created by jankoatwarpspeed.com */

(function(jQuery) {
    jQuery.fn.formToWizard = function(options) {
        options = jQuery.extend({  
            submitButton: "" 
        }, options); 
        
        var element = this;

        var steps = jQuery(element).find("fieldset");
        var count = steps.size();
        var submmitButtonName = "#" + options.submitButton;
        jQuery(submmitButtonName).hide();

        // 2
        jQuery(element).before("<ul id='steps'></ul>");
        
        /*if (jQuery.browser.mozilla) {
            jQuery(element).keypress(checkForEnter);
         } else {
            jQuery(element).keydown(checkForEnter);
         }*/

        steps.each(function(i) {
            jQuery(this).wrap("<div id='step" + i + "'></div>");
            jQuery(this).append("<p id='step" + i + "commands'></p>");

            // 2
            var name = jQuery(this).find("legend").html();
            jQuery("#steps").append("<li id='stepDesc" + i + "'>Step " + (i + 1) + "<span>" + name + "</span></li>");

            if (i == 0) {
                createNextButton(i);
                selectStep(i);
            }
            else if (i == count - 1) {
                jQuery("#step" + i).hide();
                createPrevButton(i);
            }
            else {
                jQuery("#step" + i).hide();
                createPrevButton(i);
                createNextButton(i);
            }
        });

        function createPrevButton(i) {
            var stepName = "step" + i;
            jQuery("#" + stepName + "commands").append("<a href='#' id='" + stepName + "Prev' class='prev'>< Back</a>");

            jQuery("#" + stepName + "Prev").bind("click", function(e) {
                jQuery("#" + stepName).hide();
                jQuery("#step" + (i - 1)).show();
                jQuery(submmitButtonName).hide();
                selectStep(i - 1);
            });
        }

        function createNextButton(i) {
            var stepName = "step" + i;
            jQuery("#" + stepName + "commands").append("<a href='#' id='" + stepName + "Next' class='next'>Next ></a>");

            jQuery("#" + stepName + "Next").bind("click", function(e) {
                jQuery("#" + stepName).hide();
                jQuery("#step" + (i + 1)).show();
                if (i + 2 == count)
                    jQuery(submmitButtonName).show();
                selectStep(i + 1);
            });
        }
        
        function checkForEnter(event) {
        	if (event.keyCode == 13) {
        		event.preventDefault();
        		selectStep(i+1);
        		alert('');
            }
         }

        function selectStep(i) {
            jQuery("#steps li").removeClass("current");
            jQuery("#stepDesc" + i).addClass("current");
        }

    }
})(jQuery); 