var Navigation = [];
var Back = false;
var counter = 0;
var terms = {};
//Header used in all of the pages
var Header = React.createClass({
    handleClick: function (e) {
        e.preventDefault();
        var page = e.target.dataset.page;
        this.props.onPageChange(page);
    },
    handleBack: function (e) {
        e.preventDefault();
        this.props.onBack();
    },
    render: function () {
        var result = [];
        var result1 = [];
        var sandwhich = [];
        if(this.props.user.roleid >= 1)
        {
            if(this.props.user.roleid >= 3)
            {
                result1 = [
                    <li key="0">
                        <a data-page="settings" ref="page"  onClick={this.handleClick}>
                            <i data-page="settings" ref="page" className="glyphicon glyphicon-cog"></i>
                            <span data-page="settings"  ref="page">Settings</span>
                        </a>
                    </li>
                ];
            }
            result = [
                <div key="2" className="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                    <ul className="nav navbar-nav navbar-right">
                        <li className="dropdown">
                            <a href="#" className="dropdown-toggle" id="userDrop" data-toggle="dropdown"
                               role="button" aria-expanded="false">
                                <i className="fa fa-user"></i> User <span className="caret"></span>
                            </a>
                            <ul className="dropdown-menu multi-level" role="menu"
                                style={{backgroundColor: '#FFF'}}>
                                <li>
                                    <a href="http://users.cis.fiu.edu/~sadjadi/Upload/SeniorProject/SeniorProject-FloorPlan-Spring2015.png" target="_blank" id="fiuMap"><i className="fa fa-location-arrow"></i> Map</a>
                                </li>
                                {result1}
                                <li className="divider"></li>
                                <li>
                                    <a href="#" id="judgeLogout" data-page="login" onClick={this.handleClick}><i className="fa fa-sign-out"></i> Logout</a>
                                </li>
                            </ul>
                        </li>
                    </ul>
                </div>];

            sandwhich = [
                <button key="1" type="button" className="navbar-toggle collapsed navbar-header-btn"
                        data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    <span className="sr-only">Toggle navigation</span>
                    <span className="icon-bar custom-bar"></span>
                    <span className="icon-bar custom-bar"></span>
                    <span className="icon-bar custom-bar"></span>
                </button>
            ];
        }

        return (
            <header>
                <nav className="navbar navbar-default navbar-fixed-top custom-navbar no-border-radius" role="navigation">
                    <div className="wrapper">
                        <div className="badge">
                            <i className="left"></i>
                            <i className="right"></i>
                            BETA
                        </div>
                    </div>
                    <div className="container">
                        <div className="navbar-header">
                            {sandwhich}
                            <a className="navbar-btn" role="button" onClick={this.handleBack}>
                                <i className="back-icon glyphicon glyphicon-circle-arrow-left"></i><span
                                className="hidden-xs"> Back</span>
                            </a>
                        </div>

                        <div className="navbar-brand-center">
                            <span className="bar-title">Mobile Judge</span>
                        </div>
                        {result}
                    </div>
                </nav>
            </header>
        );
    }
});

var Footer = React.createClass({
    handleClick: function (e) {
        e.preventDefault();
        var page = e.target.id;
        //alert(page);
        this.props.onPageChange(page);
    },
    render: function () {
        var result = '';
        if(this.props.user.roleid == 3)
        {
            result = [
                <footer key="0">
                    <nav className="navbar navbar-default navbar-fixed-bottom">
                        <div className="container-fluid no-padding text-center">
                            <ul className="nav footer-nav-list">
                                <li>
                                    <a href="#" id="adminHome" ref="page" onClick={this.handleClick}>
                                        <i id="adminHome" ref="page" className="fa fa-home"></i>

                                        <div id="adminHome" ref="page">Home</div>
                                    </a>
                                </li>
                                <li>
                                    <a href="#" id="adminPeople" ref="page" onClick={this.handleClick}>
                                        <i id="adminPeople" ref="page" className="fa fa-user"></i>

                                        <div id="adminPeople" ref="page">People</div>
                                    </a>
                                </li>
                                <li>
                                    <a href="#" id="adminEmail" ref="page" onClick={this.handleClick}>
                                        <i id="adminEmail" ref="page" className="fa fa-envelope-o"></i>

                                        <div id="adminEmail" ref="page">Email</div>
                                    </a>
                                </li>
                                <li>
                                    <a href="#" id="adminStats" ref="page" onClick={this.handleClick}>
                                        <i id="adminStats" ref="page" className="fa fa-bar-chart"></i>

                                        <div id="adminStats" ref="page">Stats</div>
                                    </a>
                                </li>
                            </ul>
                        </div>
                    </nav>
                </footer>];
        }
        return (
            <div>
                {result}
            </div>
        );
    }
});

var Content = React.createClass({
    handleChangePage: function (page) {
        this.props.onPageChange(page);
    },
    render: function () {
        var prop = {onChangePage: this.handleChangePage};
        var result = React.cloneElement(this.props.page, prop);
        return result;
    }
});

var Page = React.createClass({
    getInitialState: function () {
        Filter = [];
        return ({
            currPage: "login",
            user: {
                students: '',
                currentStudents: '',
                oldStudents: '',
                judges: '',
                currentJudges: '',
                oldJudges: '',
                extraList: '',
                template: '',
                extras: [],
                sendList: [],
                sendListNoId: [],
                counter: 0
            },
            student: {}
        })
    },

    handleChangePage: function (page) {
        this.setState({curPage: page});
    },

    handleValueChange: function (filters, extras) {
        this.setState({filters: filters, extras: extras, curPage: 'emailList'});
    },
    handleToBeSent: function (students, judges, extras) {
        var toBeSent = [];
        var toBeSentNoId = [];

        ////console.log('these are the students: ', students);
        ////console.log('these are the judges: ', judges);
        ////console.log('these are the extras: ', extras);
        $.map(students, function (student) {
                var email = student;
                toBeSent.push(email);
        });

        $.map(judges, function (judge) {
                var email = judge;
                toBeSent.push(email);
        });

        $.map(extras, function (extra) {
                toBeSentNoId.push(extra);
        });

        this.setState({sendList: toBeSent, sendListNoId: toBeSentNoId});
    },
    handleSend: function (templateId, users, emails) {
        emailTemplatesInfo = [];
        this.setState({curPage: "emailPreview"});
        console.log(users);
        $.map(users, function (user) {
            return EmailTemplateEntity.sendEmail(user.id, templateId);
        });
        $.map(emails, function (email) {
            return EmailTemplateEntity.sendEmailNoId(email, templateId);
        });
    },
    handleTemplate: function (template) {
        this.setState({template: template})
    },

    handleLoadUser: function (loadedUser){
        ////console.log("HANDLE LOAD USER = ", loadedUser);
        this.setState({user: loadedUser});
    },

    handlePickStudent: function (pStudent){
        this.setState({student: pStudent});
    },

    handleBackButton: function () {
        if(Navigation.length > 0)
        {
            ////console.log("back");
            var page = Navigation.pop();
            Back = true;
            this.setState({curPage: page});
        }
    },
    componentDidMount: function () {
        window.onload = this.handleBrowserBack(this);
    },
    componentWillUnmount: function () {
        if(!Back)
        {
            Navigation.push("login");
        }
        else
        {
            Back = false;
        }
    },
    handleBrowserBack: function (e) {
        if (typeof history.pushState === "function") {
            history.pushState("jibberish", null, null);
            window.onpopstate = function () {
                history.pushState('newjibberish', null, null);
                //////console.log("hello");
                e.handleBackButton();
            };
        }
        else {
            var ignoreHashChange = true;
            window.onhashchange = function () {
                if (!ignoreHashChange) {
                    ignoreHashChange = true;
                    window.location.hash = Math.random();
                }
                else {
                    ignoreHashChange = false;
                }
            };
        }
    },
    render: function () {
        ////console.log("Got Here: ", this.state.curPage);
        var result = '';
        switch (this.state.curPage) {
            case 'adminHome':
                result = <AdminHome />;
                break;
            /*case 'adminEmail':
                result = <Email handler={this.handleChangePage} valueHandler={this.handleValueChange}
                                extrasHandler={this.extrasHandler}/>;
             break;*/
            case 'adminPeople':
                result = <AdminPeople />;
                break;
            case 'adminStats':
                result = <AdminStats />;
                break;
            case 'roleJudge':
                result = <AdminPeople />;
                break;
            case 'emailCreateTemplate':
                result = <EmailCreateTemplate handler={this.handleChangePage}/>
                break;
            case 'emailList':
                result = <EmailList handler={this.handleChangePage} handleToBeSent={this.handleToBeSent}
                                    filters={this.state.filters} extra={this.state.extras}/>
                break;
            case 'emailSelectTemplate':
                ////console.log("emailSelectTemplate");
                result = <EmailSelectTemplate handler={this.handleChangePage} templateHandler={this.handleTemplate}
                                              handleSend={this.handleSend} sendList={this.state.sendList}
                                              sendListNoId={this.state.sendListNoId} user={this.state.user}/>;
                break;
            case 'emailPreview':
                result = <EmailPreview />;
                break;
            case 'settings':
                result = <AdminSettings handler={this.handleChangePage}/>
                break;
            case 'studentHome':
                result = <StudentHome user={this.state.user}/>
                break;
            case 'judgeHome':
                result = <JudgeHome user={this.state.user} handler={this.handleChangePage} handleStudent={this.handlePickStudent}/>
                break;
            case 'forgotPass':
                {console.log("CASE FORGOT");}
                result = <ForgotPass user={this.state.user} handler={this.handleChangePage}/>
                break;
            case 'questions':
                result = <QuestionsPage handler={this.handleChangePage} user={this.state.user} student={this.state.student}/>
                break;
            case 'login':
                result = <Login user={this.state.user} handler={this.handleChangePage} handleUser={this.handleLoadUser}/>;
                break;
            case 'adminEmail':
                cols = [];
                rows = [];
                Chks = [];
                fils = [];
                //result = <Email handler={this.handleChangePage} valueHandler={this.handleValueChange} extrasHandler={this.extrasHandler}/>;
                result = <Email handler={this.handleValueChange}/>;
                break;
            default:
                result = <Login user={this.state.user} handler={this.handleChangePage} handleUser={this.handleLoadUser}/>;
        }
        return (
            <div>
                <Header onPageChange={this.handleChangePage} onBack={this.handleBackButton} user={this.state.user}/>
                <Content page={result} onPageChange={this.handleChangePage}/>
                <Footer onPageChange={this.handleChangePage} user={this.state.user}/>
            </div>
        );
    }
});

var Alert = React.createClass({
        getInitialState: function () {
            return ({
                show: false,
                type: "info",
                messages: []
            })
        },
        render: function (){
            if(this.props.show != true)
            {
                return (false);
            }
            return(
                <div className={'alert alert-' + this.props.type}>
                    {
                        this.props.messages.map(function(m, i){
                            return (<p key={i}>{m}</p>)
                        })
                    }
                </div>
            )
        }
    })

function getStatus($status) {
    switch ($status) {
        case "1":
            return "Prospective";
        case "2":
            return "Invited";
        case "3":
            return "Rejected";
        case "4":
            return "Pending";
        case "5":
            return "Registered";
        case "6":
            return "Attended";
        case "7":
            return "Started Grading";
        case "8":
            return "Graded";
        case "9":
            return "Active";
        case "10":
            return "Dropped";
        case "11":
            return "Incomplete";
        case "12":
            return "Removed";
        default:
            return "Unknown Status";
    }
};

var ABC = React.createClass({
    handleClick: function (j, e) {
        e.preventDefault();
        var i = 0;
        while ($("#" + j + i).length == 0) {
            i++;
            if (i == 1000) {
                //alert("nothing found");
                break;
            }
        }
        $('html, body').animate({
            scrollTop: ($("#" + j + i).offset().top - 100)
        }, 1000);
    },
    render: function () {
        var alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
        var self = this;
        return (
            <div id="abc">
                {
                    $.map(alphabet, function (letter) {
                        return [<span key={letter} id={letter} onClick={self.handleClick.bind(null,letter.toUpperCase())}>{letter.toUpperCase()} </span>];
                    })
                }
            </div>
        );
    }
});

function DownloadJSON2CSV(objArray)
{
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

    var str = '';

    for (var i = 0; i < array.length; i++) {
        var line = '';

        for (var index in array[i]) {
            line += '"' + array[i][index] + '",';
        }


        line.slice(0,line.Length-1);

        str += line + "\r\n";
    }
    var uri = 'data:text/csv;charset=utf-8;base64,' + window.btoa(str);
    var downloadLink = document.createElement("a");
    downloadLink.href = uri;
    downloadLink.download = "grades.csv";

    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
}
