{% extends "core.twig" %}
{% use "utils.twig" %}

{% block content %}
<div class="row widget" data-widget="datawrapper.InvitationForm">
    <div class="error alert alert-error{% if not alert %} hidden {% endif %}">
        <a class="close" data-dismiss="alert" href="#">&times;</a>
        <div>{{ alert.message }}</div>
    </div>

    <div class="span8 inviation-form form-vertical">
        <form action="#" name="set-password">
            <div class="control-group">
                <label>
                    {% trans "Choose your password" %}
                </label>
                <input class="" name="password1" type="password" class="input-xxlarge span3" value="" placeholder="{% trans "password" %}" /></div>
            <div class="control-group">
                <label>
                    {% trans "Repeat your password" %}
                </label>
                <input class="" name="password2" type="password" class="input-xxlarge span3" value="" placeholder="{% trans "repeat password" %}" />
            </div>
            <div class="control-group">
                <input type='submit' class="btn" value="{% trans "Confirm" %}"/>
            </div>
        </form>
    </div>
</div>

<script type="text/javascript">
$(window).load(function() {

    var salt  = null;
    var token = document.location.pathname.split('/')[document.location.pathname.split('/').length - 1];

    $.ajax('/api/auth/salt', {
        success: function(data){salt = data.data.salt ;}
    });

    $('input[type=submit]').click(function(){
        var pwd1 = $("input[name='password1']");
        var pwd2 = $("input[name='password2']");

        $('.error').addClass('hidden');
        pwd1 = pwd1.val() !== '' ? CryptoJS.HmacSHA256(pwd1.val(), salt).toString() : '';
        pwd2 = pwd2.val() !== '' ? CryptoJS.HmacSHA256(pwd2.val(), salt).toString() : '';

        $.ajax('/api/account/invitation/' + token, {
            dataType: 'json',
            type: 'POST',
            data: JSON.stringify({
                pwd1: pwd1,
                pwd2: pwd2
            }),
            success: function(data) {
                if (data.status === 'ok') {
                    return window.location = '/';
                } else {
                  return $('.error').removeClass('hidden').find('div').text(data.message);
                }
            }
        });
        return false;
    });
});
</script>

{{ parent() }}
{% endblock %}
