var FormWizard = function () {


    return {
        //main function to initiate the module
        init: function () {
            if (!jQuery().bootstrapWizard) {
                return;
            }
		var form = $('#stepy_form');
		var error = $('.alert-danger', form);
		var success = $('.alert-success', form);
		form.validate({
			doNotHideMessage: true, //this option enables to show the error/success messages on tab switch.
			errorElement: 'span', //default input error message container
			errorClass: 'help-block help-block-error', // default input error message class
			focusInvalid: false, // do not focus the last invalid input
			rules: {
                username: {
                    required: true,
                    remote: {
                        url: "/register-account/check",
                        type: "post",
                        data: {
                            username: function() {
                                return $( "#username" ).val();
                                }
                              }
                    }
                },
                group_id: {
                    required: true,
                },
                password: {
                    required: true,
                },
                password_conf: {
                    equalTo: "#password"
                },  
                first_name: {
                    required: true
                },  
                last_name: {
                    required: true
                },
            },
            messages: {
                username: {
                    required: 'Username field is required!',
                    remote: "This username is already taken! Try another."
                },
                password: {
                    required: "Password must be set",
                },
                password_conf: {
                    equalTo: "Password didnt match!"
                },
                first_name: {
                    required: 'First name is required!'
                },
                last_name: {
                    required: 'Last name is required!'
                },
                group_id: {
                    required: "Please select join value"
                },                
            },
			// errorPlacement: function (error, element) { // render error placement for each input type
				// error.insertAfter(element); // for other inputs, just perform default behavior
			// },
			
			invalidHandler: function (event, validator) { //display error alert on form submit   
				success.hide();
				error.show();
				App.scrollTo(error, -200);
			},

			highlight: function (element) { // hightlight error inputs
				$(element)
					.closest('.form-group').removeClass('has-success').addClass('has-error'); // set error class to the control group
			},

			unhighlight: function (element) { // revert the change done by hightlight
				$(element)
					.closest('.form-group').removeClass('has-error'); // set error class to the control group
			},
			success: function (label) {
				if (label.attr("for") == "gender" || label.attr("for") == "payment[]") { // for checkboxes and radio buttons, no need to show OK icon
					label
						.closest('.form-group').removeClass('has-error').addClass('has-success');
					label.remove(); // remove error label here
				} else { // display success icon for other inputs
					label
						.addClass('valid') // mark the current input as valid and display OK icon
					.closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group
				}
			},
			submitHandler: function (form) {
				
				var dataString = $('#stepy_form').serialize();
				$.ajax({
					type: "POST",
					url: "/register-account/submit",
					data: dataString,
					cache: false,
					beforeSend: function(){ 
						$("#finish").hide();
						$("#wait").show();
						$("#suksesupdate").hide();
						$("#gagalupdate").hide();
					},
					complete: function(e, xhr, settings){
						if(e.status === 200){
							$("#finish").show();
							$("#wait").hide();
							$("#suksesupdate").show();
							//$("#gagalupdate").hide();
							location.reload();
						}else{
							$("#finish").show();
							$("#wait").hide();
							//$("#suksesupdate").show();
							$("#gagalupdate").show();
						}
					}
					
				});
			
			return false;
			}
		 });
		 var displayConfirm = function() {
                $('#tab2 .form-control-static', form).each(function(){
                    var input = $('[name="'+$(this).attr("data-display")+'"]', form);
                    if (input.is(":radio")) {
                        input = $('[name="'+$(this).attr("data-display")+'"]:checked', form);
                    }
                    if (input.is(":text") || input.is("textarea")) {
                        $(this).html(input.val());
                    } else if (input.is("select")) {
                        $(this).html(input.find('option:selected').text());
                    } else if (input.is(":radio") && input.is(":checked")) {
                        $(this).html(input.attr("data-title"));
                    } else {
						$(this).html(input.val());
					}
                });
            }

            var handleTitle = function(tab, navigation, index) {
                var total = navigation.find('li').length;
                var current = index + 1;
                // set wizard title
                $('.step-title', $('#form_wizard_1')).text('Step ' + (index + 1) + ' of ' + total);
                // set done steps
                jQuery('li', $('#form_wizard_1')).removeClass("done");
                var li_list = navigation.find('li');
                for (var i = 0; i < index; i++) {
                    jQuery(li_list[i]).addClass("done");
                }

                if (current == 1) {
                    $('#form_wizard_1').find('.button-previous').hide();
                } else {
                    $('#form_wizard_1').find('.button-previous').show();
                }

                if (current >= total) {
                    $('#form_wizard_1').find('.button-next').hide();
                    $('#form_wizard_1').find('.button-submit').show();
                    displayConfirm();
                } else {
                    $('#form_wizard_1').find('.button-next').show();
                    $('#form_wizard_1').find('.button-submit').hide();
                }
                App.scrollTo($('.page-title'));
            }

            // default form wizard
            $('#form_wizard_1').bootstrapWizard({
                'nextSelector': '.button-next',
                'previousSelector': '.button-previous',
                onTabClick: function (tab, navigation, index, clickedIndex) {
                    return false;
                    
                    success.hide();
                    error.hide();
                    if (form.valid() == false) {
                        return false;
                    }
                    
                    handleTitle(tab, navigation, clickedIndex);
                },
                onNext: function (tab, navigation, index) {
                    success.hide();
                    error.hide();

                    if (form.valid() == false) {
                        return false;
                    }

                    handleTitle(tab, navigation, index);
                },
                onPrevious: function (tab, navigation, index) {
                    success.hide();
                    error.hide();

                    handleTitle(tab, navigation, index);
                },
                onTabShow: function (tab, navigation, index) {
                    var total = navigation.find('li').length;
                    var current = index + 1;
                    var $percent = (current / total) * 100;
                    $('#form_wizard_1').find('.progress-bar').css({
                        width: $percent + '%'
                    });
                }
            });

            $('#form_wizard_1').find('.button-previous').hide();
            $('#form_wizard_1 .button-submit').click(function () {
                // alert('Finished! Hope you like it :)');
            }).hide();

        }

    };

}();

jQuery(document).ready(function() {
    FormWizard.init();
});