

var AdminSettingsTabs = React.createClass({
    handleChangePage: function (e) {
        e.preventDefault();
        this.props.onPageChange($(e.target).data("page"));
    },
    render: function () {
        return (
            <ul className="nav nav-pills mj-pills" role="tablist">
                <li role="presentation" className="active" data-page="terms" onClick={this.handleChangePage}>
                    <a href="#" id="termsTab" role="tab" data-page="terms" onClick={this.handleChangePage}
                       data-toggle="tab" >
                        <span data-page="terms" onClick={this.handleChangePage}>Term</span>
                        <span className="hidden-xs" data-page="terms" onClick={this.handleChangePage}> Management</span>
                    </a>
                </li>
                <li role="presentation" data-page="questions" onClick={this.handleChangePage}>
                    <a href="#" data-page="questions" onClick={this.handleChangePage} id="questionsTab" role="tab" data-toggle="tab" >
                        <span data-page="questions" onClick={this.handleChangePage}>Questions</span>
                        <span data-page="questions" onClick={this.handleChangePage} className="hidden-xs"> Management</span>
                    </a>
                </li>
                <li role="presentation" data-page="password" onClick={this.handleChangePage}>
                    <a href="#" id="passwordTab" data-page="password" aria-controls="password" role="tab" data-toggle="tab" onClick={this.handleChangePage}>
                        <span data-page="password" onClick={this.handleChangePage}>User</span>
                        <span className="hidden-xs" data-page="password" onClick={this.handleChangePage}> Management</span>
                    </a>
                </li>
                <li role="presentation" data-page="templates" onClick={this.handleChangePage}>
                    <a href="#" id="templateManagerTab"  aria-controls="templates" role="tab" data-toggle="tab" data-page="templates" onClick={this.handleChangePage}>
                        <span data-page="templates" onClick={this.handleChangePage}>Template</span>
                        <span className="hidden-xs" data-page="templates" onClick={this.handleChangePage}> Management</span>
                    </a>
                </li>
            </ul>
        );
    }
});

var NewTerm = React.createClass({
    componentDidMount: function () {
        $('#starty').datetimepicker({
            defaultDate: new Date(),
            format: 'YYYY-MM-DD HH:mm:ss'
        });
        $('#endy').datetimepicker({
            defaultDate: new Date(),
            format: 'YYYY-MM-DD HH:mm:ss'
        });
        $('#deadline').datetimepicker({
            defaultDate: new Date(),
            format: 'YYYY-MM-DD HH:mm:ss'
        });
    },
    getInitialState: function () {
        return ({
            alert: false,
            type: '',
            message: []
        })
    },
    saveTerm: function () {
        $(TermEntity).on('CreatedNewTerm', function () {
            //console.log("UPDATING TERM");
            var result = TermEntity.getTerm();
            if(result.name == $('#tname').val())
            {
                this.props.onChangeActiveTerm(true, 'success', ["Saved Successfully"], result.id);
            }
            else
            {
                this.setState({alert: true, type:  'danger', message: ["Save Failed"]});
            }
            $(TermEntity).off('UpdateTerm');
        }.bind(this));
        var options =
        {
            name: $('#tname').val(),
            studentsperjudge: $('#spj').val(),
            start: $('#starty').val(),
            end: $('#endy').val(),
            location: $('#loc').val(),
            srprojecturl: $('#srurl').val(),
            srprojecttoken: $('#srtok').val(),
            allowjudgestologin: $('#allow').val(),
            mapimage: $('#map').val(),
            active: $('#active').val(),
            statsrefreshrate: $('#rate').val(),
            liveurl: $('#liveurl').val(),
            devurl: $('#devurl').val(),
            order: $('#order').val(),
            deadline: $('#deadline').val(),
            studentscangrades: $('#stu').val()
        };
        ////console.log(options);
        TermEntity.createNewTerm(options);
    },
    handleClear: function () {
        var r = confirm("Are you sure you want to clear?")
        if(r == true)
        {
            $('#tname').val("");
            $('#spj').val("");
            $('#loc').val("");
            $('#srurl').val("");
            $('#srtok').val("");
            $('#devurl').val("");
            $('#liveurl').val("");
            $('#order').val("");
            $('#map').val("");
        }
    },
    render: function () {
        var alert = [<Alert key="message" show={this.state.alert} type={this.state.type} messages={this.state.message}/>];
        return (
            <div>
                {alert}
                <table className="table">
                    <tr>
                        <td style={{textAlign: 'left', verticalAlign: 'bottom'}}>
                            <h3>Term Management</h3>
                        </td>
                        <td style={{textAlign: 'right', verticalAlign: 'bottom'}}>
                            <button id="import-button" type="button" className="btn btn-lightblue"
                                    onClick={this.saveTerm}>Save
                            </button>
                            <button id="import-button" type="button" className="btn btn-lightblue"
                                    onClick={this.handleClear}>Clear
                            </button>
                        </td>
                    </tr>
                </table>

                <h5><b>Selected Term:</b></h5>

                <table className="table table-bordered">
                    <tbody>
                    <tr>
                        <td className="td-primary input-group-addon">Name</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input id="tname" style={{backgroundColor:'transparent', display: 'block', width: '100%'}}
                                   className="borderless" type='text'/>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Is Active?</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <select className="borderless" aria-expanded="true" id="active"
                                    style={{display: 'block', height: '100%', width:'100%'}}>
                                <option value="0" >No</option>
                                <option value="1">Yes</option>
                            </select>                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Allow Judges To Login?</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <select className="borderless" aria-expanded="true" id="allow"
                                    style={{display: 'block', height: '100%', width:'100%'}}>
                                <option value="0" >No</option>
                                <option value="1">Yes</option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Students Can See Grades?</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <select className="borderless" aria-expanded="true" id="stu"
                                    style={{display: 'block', height: '100%', width:'100%'}}>
                                <option value="0" >No</option>
                                <option value="1">Yes</option>
                            </select>
                        </td>
                    </tr>
                    </tbody>
                </table>

                <h5><b>Students per Judge</b></h5>
                <table className="table table-bordered">
                    <tbody>
                    <tr>
                        <td className="td-primary input-group-addon">Exactly</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input style={{backgroundColor:'transparent'}} className="borderless" type='text' id="spj"/>
                        </td>
                    </tr>
                    </tbody>
                </table>

                <h5><b>Stats Refresh Rate In Seconds</b></h5>

                <table className="table table-bordered">
                    <tbody>
                    <tr>
                        <td className="td-primary input-group-addon">0 = Off</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input style={{backgroundColor:'transparent'}} className="borderless" type='text'
                                   id="rate"/>
                        </td>
                    </tr>
                    </tbody>
                </table>

                <h5><b>Event Info</b></h5>

                <table className="table table-bordered">
                    <tbody>
                    <tr>
                        <td className="td-primary input-group-addon">Start Time</td>
                        <td>
                            <div style={{position: "relative"}}>
                                <input id="starty" style={{backgroundColor:'transparent'}} className="borderless" type='text' />
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">End Time</td>
                        <td>
                            <div style={{position: "relative"}}>
                                <input id="endy" style={{backgroundColor:'transparent'}} className="borderless" type='text'  />
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Deadline</td>
                        <td>
                            <div style={{position: "relative"}}>
                                <input id="deadline" style={{backgroundColor:'transparent'}} className="borderless" type='text'  />
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Place</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input style={{backgroundColor:'transparent', display: 'block', width: '100%'}} className="borderless" type='text' id="loc"  />
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Map URL</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input style={{backgroundColor:'transparent', display: 'block', width: '100%'}} className="borderless" type='text' id="map"/>
                        </td>
                    </tr>
                    </tbody>
                </table>

                <h5><b>Senior Project Website</b></h5>

                <table className="table table-bordered">
                    <tbody>
                    <tr>
                        <td className="td-primary input-group-addon">URL</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input style={{backgroundColor:'transparent', display: 'block', width: '100%'}} className="borderless" type='text' id="srurl"  />
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Token</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input style={{backgroundColor:'transparent', display: 'block', width: '100%'}} className="borderless" type='text' id="srtok" />
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Live URL</td>
                        <td className="td-secondary" style={{textAlign:'left', display: 'block', width: '100%'}}>
                            <input style={{backgroundColor:'transparent', display: 'block', width: '100%'}} className="borderless" type='text' id="liveurl" />
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Development URL</td>
                        <td className="td-secondary" style={{textAlign:'left', display: 'block', width: '100%'}}>
                            <input style={{backgroundColor:'transparent', display: 'block', width: '100%'}} className="borderless" type='text' id="devurl" />
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Order</td>
                        <td className="td-secondary" style={{textAlign:'left', display: 'block', width: '100%'}}>
                            <input style={{backgroundColor:'transparent', display: 'block', width: '100%'}} className="borderless" type='text' id="order" />
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>

        );
    }
});

var Term = React.createClass({
    getInitialState: function () {
        $(TermEntity).on('ActiveTermsHasChanged', function () {
            this.props.onChangeActiveTerm();
            var term = this.state.term;
            term.active = 1;
            this.setState({term: term});
        }.bind(this));

        return ({term: '',
            alert: 'false',
            message: [],
            type: ''});
    },
    handleChangeActiveTerm: function (e) {
        e.preventDefault();
        var termid = e.target.dataset.id;
        var options = {
            id: termid,
            active: 1
        };
        TermEntity.setNewActive(options);
    },
    componentWillReceiveProps: function (nextProps) {
        this.setState({
            term: nextProps.active
        });
    },
    componentDidMount: function () {

        var start = this.props.active.start == "0000-00-00 00:00:00" ? new Date() : this.props.active.start;
        var end = this.props.active.end == "0000-00-00 00:00:00" ? new Date() : this.props.active.end;
        var deadline = this.props.active.deadline == "0000-00-00 00:00:00" || this.props.active.deadline == undefined ? new Date() : this.props.active.deadline;
        $('#starty').datetimepicker({
            defaultDate: start,
            format: 'YYYY-MM-DD HH:mm:ss'
        });
        $("#starty").on("dp.change", function (e) {
            //////console.log("HELLO");
            var newTerm = this.state.term;
            newTerm.start = e.target.value;
            this.setState({term: newTerm});
        }.bind(this));
        $('#endy').datetimepicker({
            defaultDate: end,
            format: 'YYYY-MM-DD HH:mm:ss',
        });
        $("#endy").on("dp.change", function (e) {
            var newTerm = this.state.term;
            newTerm.end = e.target.value;
            this.setState({term: newTerm});
        }.bind(this));
        $('#deadline').datetimepicker({
            defaultDate: deadline ,
            format: 'YYYY-MM-DD HH:mm:ss',
        });
        $("#deadline").on("dp.change", function (e) {
            var newTerm = this.state.term;
            newTerm.deadline = e.target.value;
            this.setState({term: newTerm});
        }.bind(this));
        this.setState({term: this.props.active});
    },
    saveTerm: function () {
        $(TermEntity).on('UpdateTerm', function () {
            //console.log("UPDATING TERM");
            var result = TermEntity.getTerm();
            if(result == 1)
                this.props.onChangeActiveTerm(true, 'success', ["Saved Successfully"], this.state.term.id);
            else
                this.props.onChangeActiveTerm(true, 'danger', ["Save Failed"], this.state.term.id);

            $(TermEntity).off('UpdateTerm')
        }.bind(this));
        var options =
        {
            id: this.props.active.id,
            name: $('#tname').val(),
            studentsperjudge: $('#spj').val(),
            start: $('#starty').val(),
            end: $('#endy').val(),
            location: $('#loc').val(),
            srprojecturl: $('#srurl').val(),
            srprojecttoken: $('#srtok').val(),
            allowjudgestologin: $('#allow').val(),
            mapimage: $('#map').val(),
            statsrefreshrate: $('#rate').val(),
            liveurl: $('#liveurl').val(),
            devurl: $('#devurl').val(),
            order: $('#order').val(),
            deadline: $('#deadline').val(),
            studentscangrades: $('#stu').val()
        };
        //////console.log(options);
        TermEntity.updateTerm(options);
    },
    handleChange: function (e) {
        var newTerm = this.state.term;
        switch (e.target.id) {
            case "tname":
                newTerm.name = e.target.value;
                break;
            case "spj":
                newTerm.studentsperjudge = e.target.value;
                break;
            case "starty":
                newTerm.start = e.target.value;
                $('#starty').date(newTerm.start);
                break;
            case "endy":
                newTerm.end = e.target.value;
                $('#endy').date(newTerm.end);
                break;
            case "deadline":
                newTerm.deadline = e.target.value;
                $('#deadline').date(newTerm.deadline);
                break;
            case "loc":
                newTerm.location = e.target.value;
                break;
            case "srurl":
                newTerm.srprojecturl = e.target.value;
                break;
            case "srtok":
                newTerm.srprojecttoken = e.target.value;
                break;
            case "allow":
                newTerm.allowjudgestologin = e.target.value;
                break;
            case "map":
                newTerm.mapimage = e.target.value;
                break;
            case "stu":
                newTerm.studentscangrades = e.target.value;
                break;
            case "rate":
                newTerm.statsrefreshrate = e.target.value;
                break;
            case "liveurl":
                newTerm.liveurl = e.target.value;
                break;
            case "devurl":
                newTerm.devurl = e.target.value;
                break;
            case "order":
                newTerm.order = e.target.value;
                break;
            default:
                break;
        }
        this.setState({term: newTerm});
    },
    handleDelete: function () {
        var r = confirm("Are you sure you want to delete this term?");
        if (r == true) {
            $(TermEntity).on('deleteTerm', function () {
                var result = TermEntity.getTerm();
                if (result = 1) this.props.onChangeActiveTerm(true, 'success', ['Deleted successfully.'], 'any');
                else this.props.onChangeActiveTerm(true, 'danger', ['Failed to delete successfully.'], 'any');
                $(TermEntity).off('deleteTerm');
            }.bind(this));
            TermEntity.deleteTerm(this.state.term.id);
        }
    },
    render: function () {
        var now = new Date();
        var today = now.getFullYear() + "-" + ('0' + (now.getMonth()+1)).slice(-2) + "-" + ('0' + now.getDate()).slice(-2) + " 00:00:00";
        var term = this.state.term;
        var start = term.start == "0000-00-00 00:00:00" ? today : term.start;
        var end = term.end == "0000-00-00 00:00:00" ? today : term.end;
        var deadline = term.deadline == "0000-00-00 00:00:00" ? today : term.deadline;
        var alert = this.state.alert == 'true' ? [<Alert key="message" show={true} type={this.state.type} messages={this.state.message}/>] : "";
        return (
            <div>
                {alert}
                <table className="table">
                    <tr>
                        <td style={{textAlign: 'left', verticalAlign: 'bottom'}}>
                            <h3>Term Management</h3>
                        </td>
                        <td style={{textAlign: 'right', verticalAlign: 'bottom'}}>
                            <button id="import-button" type="button" className="btn btn-lightblue"
                                    onClick={this.saveTerm}>Save
                            </button>
                            <button id="import-button" type="button" className="btn btn-lightblue"
                                    onClick={this.handleDelete}>Delete
                            </button>
                        </td>
                    </tr>
                </table>

                <h5><b>Selected Term:</b></h5>

                <table className="table table-bordered">
                    <tbody>
                    <tr>
                        <td className="td-primary input-group-addon">Name</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input id="tname" style={{backgroundColor:'transparent', display: 'block', width: '100%'}}
                                   className="borderless" type='text' value={term.name} onChange={this.handleChange}/>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Is Active?</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            {term.active == 1 ? "Yes" : "No"} {term.active == 0 ? [<button key="button" style={{float: 'right'}}
                                                                                           type="button"
                                                                                           className="btn btn-sm btn-lightblue"
                                                                                           data-id={term.id}
                                                                                           onClick={this.handleChangeActiveTerm}>
                            Make Active</button>] : ""}
                        </td>
                    </tr>
                        <tr>
                            <td className="td-primary input-group-addon">Allow Judges To Login?</td>
                            <td className="td-secondary" style={{textAlign:'left'}}>
                                <select value={term.allowjudgestologin} className="borderless" aria-expanded="true" id="allow" onChange={this.handleChange}
                                        style={{display: 'block', height: '100%', width:'100%'}}>
                                    <option value="0" >No</option>
                                    <option value="1">Yes</option>
                                </select>
                            </td>
                        </tr>
                        <tr>
                            <td className="td-primary input-group-addon">Students Can See Grades?</td>
                            <td className="td-secondary" style={{textAlign:'left'}}>
                                <select value={term.studentscangrades} className="borderless" aria-expanded="true" id="stu" onChange={this.handleChange}
                                        style={{display: 'block', height: '100%', width:'100%'}}>
                                    <option value="0" >No</option>
                                    <option value="1">Yes</option>
                                </select>
                            </td>
                        </tr>
                    </tbody>
                </table>

                <h5><b>Students per Judge</b></h5>
                <table className="table table-bordered">
                    <tbody>
                    <tr>
                        <td className="td-primary input-group-addon">Exactly</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input style={{backgroundColor:'transparent'}} className="borderless" type='number' id="spj"
                                   min="0" max="100" step="1" value={term.studentsperjudge} onChange={this.handleChange}/>
                        </td>
                    </tr>
                    </tbody>
                </table>

                <h5><b>Stats Refresh Rate In Seconds</b></h5>

                <table className="table table-bordered">
                    <tbody>
                    <tr>
                        <td className="td-primary input-group-addon">0 = Off</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input style={{backgroundColor:'transparent'}} className="borderless" type='number'
                                   min="0" max="100" step="1" value={term.statsrefreshrate} onChange={this.handleChange} id="rate"/>
                        </td>
                    </tr>
                    </tbody>
                </table>

                <h5><b>Event Info</b></h5>

                <table className="table table-bordered">
                    <tbody>
                    <tr>
                        <td className="td-primary input-group-addon">Start Time</td>
                        <td>
                            <div style={{position: "relative"}}>
                                <input id="starty" style={{backgroundColor:'transparent'}} className="borderless"
                                       type='text' value={start} onChange={this.handleChange}/>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">End Time</td>
                        <td>
                            <div style={{position: "relative"}}>
                                <input id="endy" style={{backgroundColor:'transparent'}} className="borderless"
                                       type='text' value={end} onChange={this.handleChange}/>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Deadline</td>
                        <td>
                            <div style={{position: "relative"}}>
                                <input id="deadline" style={{backgroundColor:'transparent'}} className="borderless"
                                       type='text' value={deadline} onChange={this.handleChange}/>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Place</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input style={{backgroundColor:'transparent', display: 'block', width: '100%'}} className="borderless" type='text' id="loc"
                                   value={term.location} onChange={this.handleChange}/>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Map URL</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input style={{backgroundColor:'transparent', display: 'block', width: '100%'}} className="borderless" type='url' id="map"
                                   value={term.mapimage} onChange={this.handleChange}/>
                        </td>
                    </tr>
                    </tbody>
                </table>

                <h5><b>Senior Project Website</b></h5>

                <table className="table table-bordered">
                    <tbody>
                    <tr>
                        <td className="td-primary input-group-addon">URL</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input style={{backgroundColor:'transparent', display: 'block', width: '100%'}}
                                   className="borderless" type='url' id="srurl" value={term.srprojecturl}
                                   onChange={this.handleChange}/>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Token</td>
                        <td className="td-secondary" style={{textAlign:'left', display: 'block', width: '100%'}}>
                            <input style={{backgroundColor:'transparent', display: 'block', width: '100%'}} className="borderless" type='text' id="srtok"
                                   value={term.srprojecttoken} onChange={this.handleChange}/>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Live URL</td>
                        <td className="td-secondary" style={{textAlign:'left', display: 'block', width: '100%'}}>
                            <input style={{backgroundColor:'transparent', display: 'block', width: '100%'}} className="borderless" type='url' id="liveurl"
                                   value={term.liveurl} onChange={this.handleChange}/>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Development URL</td>
                        <td className="td-secondary" style={{textAlign:'left', display: 'block', width: '100%'}}>
                            <input style={{backgroundColor:'transparent', display: 'block', width: '100%'}} className="borderless" type='url' id="devurl"
                                   value={term.devurl} onChange={this.handleChange}/>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Order</td>
                        <td className="td-secondary" style={{textAlign:'left', display: 'block', width: '100%'}}>
                            <input style={{backgroundColor:'transparent', display: 'block', width: '100%'}} className="borderless" type='text' id="order"
                                   value={term.order} onChange={this.handleChange}/>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>
        );
    }
});


var AdminSettingsTerms = React.createClass({
    handleChangeActiveTerm: function (alert, type, message, id) {
        if (typeof(alert)==='undefined') alert = false;
        if (typeof(type)==='undefined') type = "";
        if (typeof(message)==='undefined') message = [];
        $(TermEntity).on('TermsHasChanged', function () {
            //alert(TermEntity.getActiveTerm());
            var curTerm = {};

            if(id == 'any')
            {
                curTerm = $.grep(TermEntity.getTerm(), function (term) {
                    return (term.active == 1)
                });
            }
            else {
                curTerm = $.grep(TermEntity.getTerm(), function (term) {
                    return (term.id == id)
                });
            }
            //////console.log(curTerm);
            this.setState({data: TermEntity.getTerm(), term: curTerm, active: 1, alert: alert, message: message, type: type});
            $(TermEntity).off('TermsHasChanged');
        }.bind(this));
        TermEntity.loadTerms();
    },
    getInitialState: function () {
        return (        {
            data: [],
            term: '',
            active: 0,
            alert: false,
            messages: [],
            type: ""
        });
    },
    componentDidMount: function () {
        $(TermEntity).on('TermsHasChanged', function () {
            //alert(TermEntity.getActiveTerm());
            var curTerm = $.grep(TermEntity.getTerm(), function (term) {
                return (term.active == 1)
            });
            //////console.log(curTerm);
            this.setState({data: TermEntity.getTerm(), term: curTerm});
            $(TermEntity).off('TermsHasChanged');
        }.bind(this));
        TermEntity.loadTerms();
    },
    handleChangeTerm: function (e) {
        var id = e.target.value;
        if(this.state.active > 0)
        {
            if (id == "new") {
                this.setState({data: TermEntity.getTerm(), term: "new", active: 0, alert: false});
            }
            else {
                var curTerm = $.grep(TermEntity.getTerm(), function (term) {
                    return (term.id == id)
                });
                ////console.log(curTerm);
                this.setState({data: TermEntity.getTerm(), term: curTerm, active: 0, alert: false});
            }
        }
        else
        {
            if (id == "new") {
                this.setState({data: this.state.data, term: "new"});
            }
            else {
                var newTerm = $.grep(this.state.data, function (term) {
                    return (term.id == id)
                });
                //////console.log(newTerm);
                this.setState({data: this.state.data, term: newTerm, alert: false})
            }
        }

    },
    render: function () {
        var curTerm = {id: 0};
        var alert = [<Alert show={this.state.alert} type={this.state.type} messages={this.state.message}/>];
        if (this.state.term == "new") {
            var shownTerm = [<NewTerm key="new" onChangeActiveTerm={this.handleChangeActiveTerm}/>]
        }
        else {
            var curTerm = this.state.term[0];

            var shownTerm = curTerm != undefined ? [<Term key={curTerm.id} active={curTerm}
                                                          onChangeActiveTerm={this.handleChangeActiveTerm}/>] : "";
            //////console.log(shownTerm);
        }
        return (
            <div role="tabpanel" className="tab-pane" id="manageTerms">
                {alert}
                <table className="table table-bordered">
                    <tbody>
                    <tr>
                        <td className="td-primary input-group-addon">Select Term:</td>
                        <td className="td-secondary">
                            <select className="borderless" aria-expanded="true" onChange={this.handleChangeTerm}
                                    id="termSelect" value={curTerm != undefined ? curTerm.id : 0}
                                    style={{display: 'block', height: '100%', width:'100%'}}>
                                <option value="new">-- Create New Term --</option>
                                {
                                    $.map(this.state.data, function (term) {
                                        return [<option key={term.id} value={term.id}>{term.name}</option>];
                                    })
                                }

                            </select></td>
                    </tr>
                    </tbody>
                </table>

                {shownTerm}

            </div>
        );
    }
});

var AdminSettingsQuestions = React.createClass({
    getInitialState: function () {
        $(QuestionsEntity).on('getQM', function () {
            this.setState(this.setState({items: QuestionsEntity.get(), newItems: [], latestid: 0}));
        }.bind(this));
        $(QuestionsEntity).on('updateQMs', function () {
            QuestionsEntity.saveQM(this.state.newItems);
        }.bind(this));
        $(QuestionsEntity).on('saveQMs', function () {
            if(table != '')
            {
                table.destroy();
                table = '';
            }
            QuestionsEntity.loadQM();
        }.bind(this));
        QuestionsEntity.loadQM();
        return({
            items: [], newItems: [], latestid: 0
        });
    },
    componentDidUpdate: function () {
        table = $('#settingsQuestions').DataTable();
    },
    handleInputChange: function (e) {
        var array = e.target.id.split("-");
        ////console.log(array);
        var id = array[0];
        var field = array[1];
        var items = this.state.items;
        for (var i in items) {
            if(items[i].id == id)
            {
                switch(field)
                {
                    case "order":
                        items[i].order = $('#'+ id + "-" + field).val();
                        break;
                    case "text":
                        items[i].text = $('#'+ id + "-" + field).val();
                        break;
                    case "max":
                        items[i].value = $('#'+ id + "-" + field).val();
                        break;
                    case "enabled":
                        items[i].enabled = items[i].enabled == 1 ? 0 : 1;
                        break;
                    case "del":
                        var r = confirm("Are you sure you want to delete this question?");
                        if (r == true) {
                            if(table != '') {
                                table.destroy();
                            }
                            QuestionsEntity.deleteQM(items[i]);
                            items.splice(i, 1);
                        }
                        break;
                    default:
                        break;
                }
            }
        }
        this.setState({items: items});
    },
    handleNewInputChange: function (e) {
        var array = e.target.id.split("-");
        ////console.log(array);
        var id = array[1];
        var field = array[2];
        var items = this.state.newItems;
        for (var i in items) {
            if(items[i].id == id)
            {
                switch(field)
                {
                    case "order":
                        items[i].order = $('#new-'+ id + "-" + field).val();
                        break;
                    case "text":
                        items[i].text = $('#new-'+ id + "-" + field).val();
                        break;
                    case "max":
                        items[i].value = $('#new-'+ id + "-" + field).val();
                        break;
                    case "enabled":
                        items[i].enabled = items[i].enabled == 1 ? 0 : 1;
                        break;
                    case "del":
                        var r = confirm("Are you sure you want to delete this question?");
                        if (r == true) {
                            if (table != '') {
                                table.destroy();
                            }
                            items.splice(i, 1);
                        }
                        break;
                    default:
                        break;
                }
            }
        }
        this.setState({newItems: items});
    },
    handleAdd: function () {
        var id = this.state.latestid + 1;
        var item = {id: id, text: '', value: 10, enabled: 1, order: 0};
        var items = this.state.newItems;
        items.push(item);
        if(table != '') {
            table.destroy();
        }
        this.setState({newItems: items, latestid: id});
    },
    handleSave: function () {
        QuestionsEntity.updateQM(this.state.items);
    },
    render: function () {
        var self = this;
        var items = this.state.items;
        var newItems = this.state.newItems;
        return (
            <div role="tabpanel" className="tab-pane" id="questionsConfig">
                <table className="table">
                    <tr>
                        <td style={{textAlign: 'left', verticalAlign: 'bottom'}}>
                            <h3>Questions</h3>
                        </td>
                        <td style={{textAlign: 'right', verticalAlign: 'bottom'}}>
                            <button id="import-button" type="button" className="btn btn-lightblue"
                                    onClick={this.handleAdd}>Add
                            </button>
                            <button id="import-button" type="button" className="btn btn-lightblue"
                                    onClick={this.handleSave}>Save
                            </button>
                        </td>
                    </tr>
                </table>

                <table id="settingsQuestions" className="table table-bordered">
                    <thead>
                    <tr>
                        <td>
                            Delete
                        </td>
                        <td>
                            Order
                        </td>
                        <td>
                            Question
                        </td>
                        <td>
                            Max
                        </td>
                        <td>
                            Enabled
                        </td>
                    </tr>
                    </thead>
                    <tbody>
                    {
                        $.map(newItems, function (item){
                            return (
                                <tr key={item.id}>
                                    <td className="td col-md-1 text-center" >
                                        <i id={"new-" + item.id + "-del"} onClick={self.handleNewInputChange} className="fa fa-minus-circle" style={{color: "red"}}></i>
                                    </td>
                                    <td className="td col-md-1">
                                        <input id={"new-" + item.id + "-order"} style={{backgroundColor:'transparent'}} onChange={self.handleNewInputChange}
                                               style={{display: 'block', height: '100%', width:'100%'}} className="borderless" defaultValue={item.order}
                                               type='text'/>
                                    </td>
                                    <td className="td col-md-8" onChange={self.handleNewInputChange}>
                                        <input id={"new-" + item.id + "-text"} style={{backgroundColor:'transparent'}}
                                               style={{display: 'block', height: '100%', width:'100%'}} className="borderless"
                                               type='text' placeholder="-- New Question --"/>
                                    </td>
                                    <td className="td col-md-1" onChange={self.handleNewInputChange}><span style={{display: 'none'}}>{item.order}</span>
                                        <input id={"new-" + item.id + "-max"} style={{backgroundColor:'transparent'}} className="borderless" type='text'
                                               defaultValue={item.value}     />
                                    </td>
                                    <td className="td col-md-1" id={"new-" + item.id + "-enabled"} onClick={self.handleNewInputChange}>
                                        {item.enabled == 1 ? 'Enabled' : 'Disabled'}
                                    </td>
                                </tr>
                            )
                        })
                    }
                    {
                        $.map(items, function (item){
                            return (
                                <tr key={item.id}>
                                    <td className="td col-md-1 text-center">
                                        <i id={item.id + "-del"} onClick={self.handleInputChange} className="fa fa-minus-circle" style={{color: "red"}}></i>
                                    </td>
                                    <td className="td col-md-1"><span style={{display: 'none'}}>{item.order}</span>
                                        <input id={item.id + "-order"} style={{backgroundColor:'transparent'}} onChange={self.handleInputChange}
                                               style={{display: 'block', height: '100%', width:'100%'}} className="borderless"
                                               type='text' value={item.order}/>
                                    </td>
                                    <td className="td col-md-8" onChange={self.handleInputChange}><span style={{display: 'none'}}>{item.text}</span>
                                        <input id={item.id + "-text"} style={{backgroundColor:'transparent', display: 'block', height: '100%', width:'100%'}} className="borderless"
                                               type='text' value={item.text}/>
                                    </td>
                                    <td className="td col-md-1" onChange={self.handleInputChange}><span style={{display: 'none'}}>{item.value}</span>
                                        <input id={item.id + "-max"} style={{backgroundColor:'transparent'}} className="borderless" type='text'
                                               value={item.value}/>
                                    </td>
                                    <td className="td col-md-1" id={item.id + "-enabled"} onClick={self.handleInputChange}>
                                        {item.enabled == 1 ? 'Enabled' : 'Disabled'}
                                    </td>
                                </tr>
                            )
                        })
                    }

                    </tbody>
                </table>
            </div>


        );
    }
});
var states = [];
var AdminSettingsUserCreate = React.createClass({
    getInitialState: function () {
        var self = this;
        $(ProjectsEntity).on('GetAllProjects', function () {
            RolesEntity.all();
        }.bind(this));
        $(RolesEntity).on('GetAllRoles', function () {
            StatesEntity.all();
        }.bind(this));
        $(StatesEntity).on('GetAllStates', function () {
            TermEntity.loadTerms();
        }.bind(this));
        $(TermEntity).on('TermsHasChanged', function () {
            LocationsEntity.all();
        }.bind(this));
        $(LocationsEntity).on('GetAllLocations', function () {
            this.setState({
                terms: TermEntity.getTerm(),
                roles: RolesEntity.get(),
                states: StatesEntity.get(),
                projects: ProjectsEntity.get(),
                locations: LocationsEntity.get()});
        }.bind(this));
        states = [1,2,3,4,5,6,7,8];
        return ({
            user: {},
            terms: {},
            roles: {},
            states: {},
            projects: {},
            locations: {},
            alert: 'false',
            message: [],
            type: '',
            selectedRole: '1'
        });
    },
    componentDidMount: function () {
        ProjectsEntity.loadAllProjects();
    },
    handleClick: function () {
        if($("#password").val() != $("#confirm").val())
        {
            this.setState({alert: true, message: ["Password does not match Confirmation."], type: "danger"});
        }
        else
        {
            var options =
            {
                fname: $('#fname').val(),
                lname: $('#lname').val(),
                email: $('#email').val(),
                pass: $('#password').val(),
                title: $('#title').val(),
                affiliation: $('#affiliation').val(),
                roleid: $('#roles').val(),
                statesid: $('#states').val(),
                projectid: $('#projects').val(),
                locationid: $('#locations').val(),
                termid: $('#terms').val()
            };
            var password = $("#password").val();
            var confirm = $("#confirm").val();
            if(password.length > 1 || confirm.length > 1)
            {

                UserEntity.saveUser(options);
                this.props.onChangePage("password");

            }
            else
            {

                this.setState({alert: 'true', message: ["Passwords cannot be empty"], type: 'danger'});
            }
        }
    },
    handleChange: function (e) {
        switch(e.target.id)
        {
            case "roles":
                this.setState({selectedRole: $(e.target).val()});
                break;
            default:
                break;
        }
    },
    render: function () {
        var alert = this.state.alert == 'true' ? [<Alert show={true} type={this.state.type} messages={this.state.message}/>] : "";
        var user = this.state.user;
        var self = this;
        return (
            <div role="tabpanel" className="tab-pane" id="changePassword">
                {alert}
                <table className="table">
                    <tr>
                        <td style={{textAlign: 'left', verticalAlign: 'bottom'}}>
                            <h3>Create User</h3>
                        </td>
                        <td style={{textAlign: 'right', verticalAlign: 'bottom'}}>
                            <button id="import-button" type="button" onClick={this.handleClick}className="btn btn-lightblue">Save
                            </button>
                        </td>
                    </tr>
                </table>

                <table className="table table-bordered">
                    <tr>
                        <td className="td-primary input-group-addon">First Name:</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input id="fname" style={{backgroundColor:'transparent', width: '100%'}} className="borderless" required/>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Last Name:</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input id="lname" style={{backgroundColor:'transparent', width: '100%'}} className="borderless"
                                   required/>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Email:</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input id="email" type="email" style={{backgroundColor:'transparent', width: '100%'}} className="borderless"
                                   required/>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Password:</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input id="password" style={{backgroundColor:'transparent', width: '100%'}} className="borderless"
                                   type='password'/>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Confirm Password:</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input id="confirm" style={{backgroundColor:'transparent', width: '100%'}} className="borderless"
                                   type='password'/>
                        </td>
                    </tr>

                    <tr>
                        <td className="td-primary input-group-addon">Title:</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input id="title" style={{backgroundColor:'transparent', width: '100%'}} className="borderless"
                                   />
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Affiliation:</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input id="affiliation" style={{backgroundColor:'transparent', width: '100%'}} className="borderless"
                                   />
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Role:</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <select id="roles" onChange={this.handleChange} className="borderless" style={{display: 'block', height: '100%', width:'100%'}} required>
                                {
                                    $.map(this.state.roles, function (role) {
                                        return [<option key={role.id} value={role.id}>{role.name}</option>];
                                    })
                                }
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">State:</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <select id="states" className="borderless" style={{display: 'block', height: '100%', width:'100%'}} required>
                                {
                                    $.map(this.state.states, function (state) {
                                        if(state.roleid == self.state.selectedRole)
                                        {
                                            return [<option key={state.id} value={state.id}>{state.name}</option>];
                                        }
                                    })
                                }
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Project:</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <select id="projects"  className="borderless" style={{display: 'block', height: '100%', width:'100%'}} required>
                                {
                                    $.map(this.state.projects, function (project) {
                                        return [<option key={project.id} value={project.id}>{project.name}</option>];
                                    })
                                }
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Location:</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <select id="locations" className="borderless" style={{display: 'block', height: '100%', width:'100%'}} required>
                                {
                                    $.map(this.state.locations, function (location) {
                                        return [<option key={location.id} value={location.id}>{location.name}</option>];
                                    })
                                }
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Term:</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <select id="terms" className="borderless" style={{display: 'block', height: '100%', width:'100%'}} required>
                                {
                                    $.map(this.state.terms, function (term) {
                                        return [<option key={term.id} value={term.id}>{term.name}</option>];
                                    })
                                }
                            </select>
                        </td>
                    </tr>
                </table>
            </div>
        );
    }
});
var AdminSettingsPassword = React.createClass({
    getInitialState: function () {
        var self = this;
        $(UserEntity).on('GetAllUsers', function () {
            var users = UserEntity.get();
            this.setState({
                user: {roleid: 1},
                terms: TermEntity.getTerm(),
                roles: RolesEntity.get(),
                states: StatesEntity.get(),
                projects: ProjectsEntity.get(),
                locations: LocationsEntity.get()});
            $("#users").autocomplete({
                source: users,
                minLength: 0,
                select: function (event, ui) {
                    $("#users").val(ui.item.label);
                    $("#user-id").val(ui.item.value);
                    self.handleChange(event, ui);
                    return false;
                }
            }).autocomplete("instance")._renderItem = function (ul, item) {
                return $("<li>")
                    .append("<a>" + item.label + "<br><small>" + item.email + "</small></a>")
                    .appendTo(ul);
            };
            ////console.log(users);
        }.bind(this));
        $(UserEntity).on('SaveUser', function () {
            var result = UserEntity.get();
            var message = ['Save failed.'];
            var alert = 'true';
            var type = 'danger';
            if(result.result == 1)
            {
                message = ['Saved successfully.'];
                type = 'success';
                $("#users").val(result.fname + " " + result.lname);
            }
            this.setState({alert: alert, message: message, type: type});
        }.bind(this));
        $(UserEntity).on('DeleteUser', function () {
            var result = UserEntity.get();
            UserEntity.loadAllUsers();
            var message = ['Delete failed.'];
            var alert = 'true';
            var type = 'danger';
            if(result == 1)
            {
                message = ['Deleted successfully.'];
                type = 'success';
                $("#users").val("");
            }
            this.setState({alert: alert, message: message, type: type});
        }.bind(this));
        $(ProjectsEntity).on('GetAllProjects', function () {
            RolesEntity.all();
        }.bind(this));
        $(RolesEntity).on('GetAllRoles', function () {
            StatesEntity.all();
        }.bind(this));
        $(StatesEntity).on('GetAllStates', function () {
            TermEntity.loadTerms();
        }.bind(this));
        $(TermEntity).on('TermsHasChanged', function () {
            LocationsEntity.all();
        }.bind(this));
        $(LocationsEntity).on('GetAllLocations', function () {
            UserEntity.loadAllUsers();
        }.bind(this));
        return ({
            user: {},
            terms: {},
            roles: {},
            states: {},
            projects: {},
            locations: {},
            alert: 'false',
            message: [],
            type: ''
        });
    },
    componentDidMount: function () {
        ProjectsEntity.loadAllProjects();
    },
    handleChange: function (e, ui) {
        this.setState({user: ui.item});
    },
    handleFieldChange: function (e) {
        var user = this.state.user;
        switch (e.target.id) {
            case "fname":
                user.fname = $(e.target).val();
                user.label = user.fname + " " + user.lname;
                break;
            case "lname":
                user.lname = $(e.target).val();
                user.label = user.fname + " " + user.lname;
                break;
            case "title":
                user.title = $(e.target).val();
                break;
            case "affiliation":
                user.affiliation = $(e.target).val();
                break;
            case "email":
                user.email = $(e.target).val();
                break;
            case "states":
                user.statesid = $(e.target).val();
                break;
            case "roles":
                user.roleid = $(e.target).val();
                break;
            case "projects":
                user.projectid = $(e.target).val();
                break;
            case "locations":
                user.locationid = $(e.target).val();
                break;
            case "terms":
                user.termid = $(e.target).val();
                break;
            default:
                break;
        }
        this.setState({user: user});
    },
    handleSave: function () {
        var user = this.state.user;
        var password = $("#password").val();
        var confirm = $("#confirm").val();
        if(password.length > 1 || confirm.length > 1)
        {
            if(password == confirm)
            {
                user.pass = $("#password").val();
                UserEntity.saveUser(user);
            }
            else
            {
                this.setState({alert: 'true', message: ["Passwords do not match."], type: 'danger'});
            }
        }
        else
        {
            user.pass = "";
            UserEntity.saveUser(user);
        }

    },
    handleAdd: function () {
        this.props.onChangePage("usercreate");
    },
    handleDelete: function () {
        var r = confirm("Are you sure you want to delete this user?");
        if (r == true) {
            var user = this.state.user;
            UserEntity.deleteUser(user);
        }
    },
    render: function () {
        var alert = this.state.alert == 'true' ? [<Alert show={true} type={this.state.type} messages={this.state.message}/>] : "";
        var user = this.state.user;
        return (
            <div role="tabpanel" className="tab-pane" id="changePassword">
                {alert}
                <table className="table">
                    <tr>
                        <td style={{textAlign: 'left', verticalAlign: 'bottom'}}>
                            <h3>Users</h3>
                        </td>
                        <td style={{textAlign: 'right', verticalAlign: 'bottom'}}>
                            <button id="import-button" type="button" className="btn btn-lightblue"
                                    onClick={this.handleAdd}>Add
                            </button>
                            <button id="import-button" type="button" className="btn btn-lightblue"
                                    onClick={this.handleSave}>Save
                            </button>
                            <button id="import-button" type="button" className="btn btn-lightblue"
                                    onClick={this.handleDelete}>Delete
                            </button>
                        </td>
                    </tr>
                </table>
                <table className="table table-bordered">
                    <tr>
                        <td className="td-primary input-group-addon">User:</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input id="users" style={{backgroundColor:'transparent', width: '100%'}} className="borderless"
                                   type='text'/>
                            <input type="hidden" id="user-id" />
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">New Password:</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input id="password" style={{backgroundColor:'transparent', width: '100%'}} className="borderless"
                                   type='password'/>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Confirm Password:</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input id="confirm" style={{backgroundColor:'transparent', width: '100%'}} className="borderless"
                                   type='password'/>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">First Name:</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input id="fname" style={{backgroundColor:'transparent', width: '100%'}} className="borderless"
                                   value={user.fname} onChange={this.handleFieldChange} required/>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Last Name:</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input id="lname" style={{backgroundColor:'transparent', width: '100%'}} className="borderless"
                                   value={user.lname} onChange={this.handleFieldChange} required/>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Email:</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input id="email" type="email" style={{backgroundColor:'transparent', width: '100%'}} className="borderless"
                                value={user.email} onChange={this.handleFieldChange} required/>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Title:</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input id="title" style={{backgroundColor:'transparent', width: '100%'}} className="borderless"
                                   value={user.title} onChange={this.handleFieldChange}/>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Affiliation:</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <input id="affiliation" style={{backgroundColor:'transparent', width: '100%'}} className="borderless"
                                   value={user.affiliation} onChange={this.handleFieldChange}/>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Role:</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <select id="roles" value={user.roleid} onChange={this.handleFieldChange} className="borderless" style={{display: 'block', height: '100%', width:'100%'}} required>
                                {
                                    $.map(this.state.roles, function (role) {
                                        return [<option key={role.id} value={role.id} >{role.name}</option>];
                                    })
                                }
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">State:</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <select id="states" value={user.statesid} onChange={this.handleFieldChange} className="borderless" style={{display: 'block', height: '100%', width:'100%'}} required>
                                {
                                    $.map(this.state.states, function (state) {
                                        if(state.roleid == user.roleid) {
                                            return [<option key={state.id} value={state.id}>{state.name}</option>];
                                        }
                                    })
                                }
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Project:</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <select id="projects" value={user.projectid} onChange={this.handleFieldChange} className="borderless" style={{display: 'block', height: '100%', width:'100%'}} required>
                                {
                                    $.map(this.state.projects, function (project) {
                                        return [<option key={project.id} value={project.id}>{project.name}</option>];
                                    })
                                }
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Location:</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <select id="locations" value={user.locationid} onChange={this.handleFieldChange} className="borderless" style={{display: 'block', height: '100%', width:'100%'}} required>
                                {
                                    $.map(this.state.locations, function (location) {
                                        return [<option key={location.id} value={location.id}>{location.name}</option>];
                                    })
                                }
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Term:</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <select id="terms" value={term.id} onChange={this.handleFieldChange} className="borderless" style={{display: 'block', height: '100%', width:'100%'}} required>
                                {
                                    $.map(this.state.terms, function (term) {
                                        return [<option key={term.id} value={term.id}>{term.name}</option>];
                                    })
                                }
                            </select>
                        </td>
                    </tr>
                </table>
            </div>
        );
    }
});

var Alert = React.createClass({
    getInitialState: function () {
        return ({
            show: false,
            type: "info",
            messages: []
        })
    },
    render: function () {
        if (this.props.show != true) {
            return (false);
        }
        var i = 0;
        return (

            <div className={'alert alert-' + this.props.type}>
                {
                    this.props.messages.map(function (m) {
                        return (<p key={i++}>{m}</p>)
                    })
                }
            </div>
        )
    }
});

var AdminSettingsTemplate = React.createClass({
    getInitialState: function () {
        return ({
            emailTemplate: {
                Title: '',
                Subject: '',
                Body: '',
            },
            formErrors: []
        })

    },
    componentWillMount: function () {
        //////console.log("COMPONENT WILL MOUNT");
        $(EmailTemplateEntity).on('EmailTemplatesHasChanged', function () {
            this.setState({emailTemplate: EmailTemplateEntity.getEmailTemplate()});
        }.bind(this))
    },

    componentDidMount: function () {
        try {
            CKEDITOR.instances['templateEditor'].destroy(true);
        } catch (e) {
        }
        CKEDITOR.replace('templateEditor');
    },

    handleClick: function (event) {

        var errors = [];
        var options = {};
        options.title = this.refs.Title.getDOMNode().value;
        options.subject = this.refs.Subject.getDOMNode().value;
        options.body = getText();

        if (options.title.length == 0) {
            errors.push("Title can not be left empty!");
        }
        if (options.subject.length == 0) {
            errors.push("Subject can not be left empty!");
        }

        this.setState({formErrors: errors});
        if (errors.length == 0) {
            EmailTemplateEntity.updateEmailTemplate(options, 2);
            this.props.handler('templates');
        }
    },

    render: function () {
        return (
            <div data-role="page" id="emailCreateTemplate" className="container">
                <Alert show={this.state.formErrors.length > 0} type="danger" messages={this.state.formErrors}/>

                <table className="table table-bordered">
                    <tbody>
                    <tr>
                        <td className="td-primary input-group-addon">Title</td>
                        <td className="td-secondary">
                            <input name="titleInput" ref="Title"
                                   className="form-control flat-input input-app input-upper"></input>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon" nowrap="nowrap">Subject</td>
                        <td className="td-secondary">
                            <input type='text' id="subjectInput" ref="Subject"
                                   className="form-control flat-input input-app input-upper"></input>
                        </td>
                    </tr>
                    <tr>
                        <td className="td-primary input-group-addon">Fields To Insert</td>
                        <td className="td-secondary" style={{textAlign:'left'}}>
                            <select className="borderless " id="fieldSelect"
                                    style={{display: 'block', width:'100%'}} onChange={(function () {
                                                if ((getSelectIndex('fieldSelect') == 'accept')
                                                || (getSelectIndex('fieldSelect') == 'decline')) {
                                                    var placeHolder = "[[" + getSelectIndex('fieldSelect') + "]]";
                                                    (insertText(placeHolder));
                                                    $('#fieldSelect').val('');
                                                }
                                                else {
                                                    var rawText = "[[" + getSelectIndex('fieldSelect') + "]]";
                                                    var reducedText = rawText.split('- ')[1];
                                                    var placeHolder = "[[" + reducedText;
                                                    (insertText(placeHolder));
                                                    $('#fieldSelect').val('');
                                                }
                                            })}>
                                <option value="" disabled selected>Select a Field</option>
                                <option value="email">users - email</option>
                                <option value="fname">users - fname</option>
                                <option value="lname">users - lname</option>
                                <option value="title">users - title</option>
                                <option value="affiliation">users - affiliation</option>
                                <option value="name">terms - name</option>
                                <option value="studentsperjudge">terms - studentsperjudge</option>
                                <option value="start">terms - start</option>
                                <option value="end">terms - end</option>
                                <option value="location">terms - location</option>
                                <option value="mapimage">terms - mapimage</option>
                                <option value="projects">projects - projects</option>
                                <option value="questions">questions - questions</option>
                                <option value="accept">accept</option>
                                <option value="decline">decline</option>
                            </select>
                        </td>
                    </tr>
                    </tbody>
                </table>
                <form>
                    <div>
                        <textarea cols="186" rows="10" id="templateEditor" name="templateEditor"></textarea>
                    </div>
                    <br></br>

                    <div className='form-group'>
                        <div className='input-group full-width'>
                            <button type='button' id='saveTemplate' className='btn btn-lightblue btn-block'
                                    onClick={this.handleClick}>
                                Save
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        );
    }
});

var AdminSettings = React.createClass({
    getInitialState: function () {
        return (
        {curPage: ''}
        )
    },
    componentWillUnmount: function () {
        if(!Back)
        {
            Navigation.push("settings");
        }
        else
        {
            Back = false;
        }
    },
    handleChangePage: function (page) {
        this.setState({curPage: page});
    },
    handlePage: function () {
        this.props.handler();
    },
    componentWillUpdate: function () {
        if(table != '')
        {
            table.destroy();
            table = '';
        }
        $(UserEntity).off();
        $(TermEntity).off();
        $(LocationsEntity).off();
        $(ProjectsEntity).off();
        $(RolesEntity).off();
        $(StatesEntity).off();
        $(GradeEntity).off();
        $(QuestionsEntity).off();
    },
    render: function () {
        var Page = [];

        switch (this.state.curPage) {
            case "terms":
                Page = [<AdminSettingsTerms key="terms" onChangePage={this.handleChangePage}/>];
                break;
            case "questions":
                Page = [<AdminSettingsQuestions key="ques" onChangePage={this.handleChangePage}/>];
                break;
            case "password":
                Page = [<AdminSettingsPassword key="pass" onChangePage={this.handleChangePage} />];
                break;
            case "usercreate":
                Page = [<AdminSettingsUserCreate key="ucreate" onChangePage={this.handleChangePage} />];
                break;
            case "templates":
                Page = [<EmailCreateTemplate key="templates" handler={this.handlePage} onChangePage={this.handleChangePage} />];
                break;
            default:
                Page = [<AdminSettingsTerms key="terms" onChangePage={this.handleChangePage}/>];
                break;
        }
        return (
            <div className="container">
                <div className="page-header">
                    <h1>Settings
                        <small> Admin</small>
                    </h1>
                </div>

                <AdminSettingsTabs key="tabs" onPageChange={this.handleChangePage}/>

                <br></br>

                {Page}
            </div>
        );
    }
});
