var LoginBox = React.createClass({
    handleLoginSubmit: function (logininfo) {
        $.ajax({
            url: '/loginuser',
            dataType: 'json',
            type: 'POST',
            data: logininfo,
            success: function (data) {
                if (data.redirect) {
                    window.location = data.redirect;
                } else if (data.error) {
                    alert(data.error);
                } else {
                    alert("Login processed");
                }
            }.bind(this),
            error: function (xhr, status, err) {
                console.error(status, err.toString());
                alert("Login error");
            }.bind(this)
        });
    },

    render: function () {
        return (
            <div>
                <h1>Back End Login</h1>
                <LoginForm2 onLoginSubmit={this.handleLoginSubmit} />
            </div>
        );
    }
});

var LoginForm2 = React.createClass({
    getInitialState: function () {
        return {
            useremail: "",
            userpw: ""
        };
    },

    handleSubmit: function (e) {
        e.preventDefault();

        var useremail = this.state.useremail.trim();
        var userpw = this.state.userpw.trim();

        if (!useremail || !userpw) {
            alert("Both fields are required");
            return;
        }

        this.props.onLoginSubmit({
            useremail: useremail,
            userpw: userpw
        });
    },

    setValue: function (field, event) {
        var object = {};
        object[field] = event.target.value;
        this.setState(object);
    },

    render: function () {
        return (
            <form onSubmit={this.handleSubmit}>
                <table>
                    <tbody>
                        <tr>
                            <th>User E-Mail</th>
                            <td>
                                <input
                                    type="email"
                                    value={this.state.useremail}
                                    onChange={this.setValue.bind(this, 'useremail')}
                                />
                            </td>
                        </tr>
                        <tr>
                            <th>Password</th>
                            <td>
                                <input
                                    type="password"
                                    value={this.state.userpw}
                                    onChange={this.setValue.bind(this, 'userpw')}
                                />
                            </td>
                        </tr>
                    </tbody>
                </table>
                <input type="submit" value="Login" />
            </form>
        );
    }
});

ReactDOM.render(
    <LoginBox />,
    document.getElementById('content')
);