{% import "mmw/macro.html" as wtf with context %}

<div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
    <h3>{{ _('Change password') }}</h3>
</div>
<div class="modal-body">
{{ wtf.quick_form(change_password_form, 
                  action=url_for_security('change_password'),
                  id="change_password_form", 
                  form_type='horizontal', 
                  button_map={'submit_button': 'primary'})}}

</div>
<div class="modal-footer">
    <button type="button" data-dismiss="modal" class="btn">{{ _('Close') }}</button>
</div>

<script type="text/javascript">

	function change_password(modal_place_holder){
        $("#submit").on('click', function(e){
            e.preventDefault();
            
            var data = {};
            $.each($('#change_password_form').serializeArray(), function(i, item){
                data[item.name] = item.value;
            });
            
            $.ajax({
                type: "POST",
                dataType: "json",
                contentType: "application/json",
                url: "{{url_for_security('change_password')}}",
                data: JSON.stringify(data), 
                success: function(msg){
                    if (msg.meta.code == 200){ 
                        $(modal_place_holder).modal('hide');
                    } else {
                        $('p.help-block').remove();
                        $('div.form-group').removeClass('has-error');
                        
                        $.each(msg.response.errors, function(key, value){
                            var field = $('#change_password_form  #' + key); 
                            field.parents('.form-group').addClass('has-error');
                            
                            $.each(value, function(i,item){
                                field.after('<p class="help-block text-danger">' + item + '</p>');  
                            });
                        });
                    }
                },
                error: function(jqXHR, textStatus, errorThrown){
                    console.log(jqXHR);
                    console.log(textStatus);
                }
            });
        }); //submit
	}
	
</script>
