function createRepeatOption() {
    return {
        repeatType: 1,
        param1: '',
        param2: '',
        param3: '',
        param4: '',
        param5: '',
        endBy: 1,
        endByValue: '',
        exceptOn: ''
    }
}

class Calendar extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            date: new Date(),
            weeks: [],
            existingBookingId: null,
            existingBookingSpace: '',
            existingBookingTime: '',
            selectedDate: new Date(),
            selectedFromTime: '',
            selectedToTime: '',
            selectedToTimeDisplay: '',
            selectedSpace: '',
            selectedNotes: '',
            selected: false,
            bookingData: this.getEmptyBookingData(),
            forbidSessions: null,
            repeatOption: createRepeatOption(),
            users: []
        };
    }

    toggleCalendar() {
        var c = $(".calendar:first");
        if(c.css("marginTop")=="0px"){
            c.animate({marginTop: -165},100);
        }else if(c.css("marginTop")=="-165px"){
            c.animate({marginTop: 0},100);
        }
    }

    closeCalendar() {
        var c = $(".calendar:first");
        c.animate({marginTop: -165},100);
    }

    refreshPoints(){
        if(this.props.logged_in){
            $.get('/user/get_points', function(result){
                if(result.success){
                    $("#labelMinutesRemain").text((result.data / 60).toFixed(2));
                }else{
                    alert(result.message);
                }
            })
        }
    }

    getEmptyBookingData(){
        var bookingData = {};
        var _this = this;

        $.each(_this.props.spaces,function(i, space){

            var singleSpaceSessions = [];

            $.each(_this.props.timespans, function(i, timespan){

                $.each(_this.props.minutesPerSession, function(i, minutes){
                    var session = { 'user': '', 'time': timespan.split(':')[0] + ':' + minutes, 'available': true, 'notes': '', 'groupByTime': '', 'booking_id': null, 'owned': false };
                    singleSpaceSessions.push(session);
                })
            })

            bookingData[space] = singleSpaceSessions;
        })

        return bookingData;

    }

    convertDateString(date){
        var month = (date.getMonth() + 1).toString();
        var day = date.getDate().toString();

        if(month.length==1){
            month = '0' + month;
        }

        if(day.length==1){
            day = '0' + day;
        }

        return date.getFullYear() + '-' + month + '-' + day;
    }

    searchBookingData(date){
        var bookingData = this.getEmptyBookingData();
        var _this = this;


        $.get('/booking/search?date=' + this.convertDateString(date), function(result){
            if(result.success) {
                console.log(result.data);
                for(var d in result.data.bookingData){
                    if(d != undefined){

                        for(var r = 0; r < result.data.bookingData[d].length; r++){

                            var darr = bookingData[d];
                            var rd = result.data.bookingData[d][r];

                            for(var t = rd.session_from; t <= rd.session_to; t++){
                                var data = darr[t];
                                data.available = false;
                                data.groupByTime = darr[rd.session_from].time;
                                data.notes = rd.notes;
                                data.booking_id = rd.booking_id;
                                data.user = rd.user;
                                data.owned = rd.owned;
                            }
                        }
                    }
                }

                _this.setState({bookingData: bookingData, forbidSessions: result.data.forbidSessions});

            }else{
                alert(result.message);
            }
        })

    }

    getSessionIndexFromTime(time){
        var _this = this;
        var idx = -1;
        var sessionIndex = -1;
        $.each(_this.props.timespans, function(i, timespan){
            $.each(_this.props.minutesPerSession, function(i, minutes){
                idx++;
                if(timespan.split(':')[0] + ':' + minutes == time){
                    sessionIndex = idx;
                }
            })
        })

        return sessionIndex;
    }

    nextMonth() {
        var curDate = this.state.date;
        curDate.setMonth(this.state.date.getMonth() + 1);
        curDate.setDate(1);

        this.clearSelected();

	    var curMonth = (curDate.getMonth() + 1) + "";
	    var curDay = (curDate.getDate() + "");

	    if(curMonth.length == 1) curMonth = "0" + curMonth;
	    if(curDay.length == 1) curDay = "0" + curDay;

        this.setState({date: new Date(curDate.getFullYear() + '-' + curMonth + '-' + curDay),
            selectedDate: new Date(curDate.getFullYear() + '-' + curMonth + '-' + curDay),
            weeks: this.getAllWeeksOfMonth(curDate.getMonth(), curDate.getFullYear()), bookingData: this.getEmptyBookingData()});
        this.searchBookingData(curDate);
    }

    prevMonth() {
        var curDate = this.state.date;
        var oldMonth = this.state.date.getMonth();

        while(curDate.getMonth()==oldMonth){
            curDate.setMonth(this.state.date.getMonth() - 1);
        }

        var month = curDate.getMonth();

        curDate.setDate(this.state.selectedDate.getDate());

        if(curDate.getMonth() != month){
            curDate.setDate(0);
        }

	    var curMonth = (curDate.getMonth() + 1) + "";
        var curDay = (curDate.getDate() + "");

        if(curMonth.length == 1) curMonth = "0" + curMonth;
        if(curDay.length == 1) curDay = "0" + curDay;

        this.clearSelected();
        this.setState({date: new Date(curDate.getFullYear() + '-' + curMonth + '-' + curDay),
            selectedDate: new Date(curDate.getFullYear() + '-' + curMonth + '-' + curDay),
            weeks: this.getAllWeeksOfMonth(curDate.getMonth(), curDate.getFullYear()), bookingData: this.getEmptyBookingData()});
        this.searchBookingData(curDate);
    }

    clearSelected(){
        $(".booking-info").hide();
        $("#txtBookingInfoNotes").val('');
        this.setState({selectedFromTime: '', selectedToTime: '', selectedToTimeDisplay: '', selectedSpace: '', selectedNotes: '', selected: false, existingBookingTime: '', existingBookingSpace: '', existingBookingId: null});
    }

    selectDate(selDate){
        if(isMobile) this.closeCalendar();
        this.clearSelected();
        this.setState({selectedDate: selDate, bookingData: this.getEmptyBookingData()});
        this.searchBookingData(selDate);
    }

    addSpace(){

        var selectedSpace = this.state.selectedSpace;
        var selectedFromTime = this.state.selectedFromTime;
        var selectedToTime = this.state.selectedToTime;

        if(selectedSpace != "" && selectedFromTime != "" && selectedToTime != ""){
            for(var i = 0; i < this.props.spaces.length; i++){
                if(this.props.spaces[i] == selectedSpace){

                    var added = false;

                    for(var t = i - 1; t >= 0; t--){

                        var space = this.props.spaces[t];
                        var valid = true;

                        $("#moreSpaces div").each(function(){
                            if($(this).text()==space){
                                valid = false;
                            }
                        })

                        if(valid) {
                            $.each(this.state.bookingData[space], (r, d) => {
                                if (d.time >= selectedFromTime && d.time <= selectedToTime) {
                                    if(!d.available){
                                        valid = false;
                                        return;
                                    }
                                }
                            })
                        }

                        if(valid){
                            $("#moreSpaces").append("<div>" + space + "</div>");
                            added = true;
                            break;
                        }

                    }

                    if(!added){
                        for(var t = i + 1; t < this.props.spaces.length; t++){

                            var space = this.props.spaces[t];
                            var valid = true;

                            $("#moreSpaces div").each(function(){
                                if($(this).text()==space){
                                    valid = false;
                                }
                            })

                            if(valid) {
                                $.each(this.state.bookingData[space], (r, d) => {
                                    if (d.time >= selectedFromTime && d.time <= selectedToTime) {
                                        if(!d.available){
                                            valid = false;
                                            return;
                                        }
                                    }
                                })
                            }

                            if(valid){
                                $("#moreSpaces").append("<div>" + space + "</div>");
                                added = true;
                                break;
                            }

                        }
                    }

                    break;
                }
            }
        }
    }

    selectTime(sessionInfo){

        this.closeCalendar();

        if(this.props.logged_in){
            var time = sessionInfo.split(',')[0]
            var untilTime = sessionInfo.split(',')[1];
            var space = sessionInfo.split(',')[2];
            var _this = this;
            var validSelected = true;
            var fromTime = this.state.selectedFromTime;
            var toTime = this.state.selectedToTime;
            var selectedSpace = this.state.selectedSpace;
            var wholeSessionValid = false;

            if((this.state.selectedSpace != '' && this.state.existingBookingTime == '')){
                if(this.state.selectedSpace == space){

                    //Check if "until time" is valid
                    if(time > this.state.selectedFromTime){

                        
                        //everyone can select 15 minutes per session
                        if(time > this.state.selectedFromTime){
                        	toTime = time;
                        }

                        wholeSessionValid = true

                        $.each(this.state.bookingData[selectedSpace], function(i, session){
                            if(session.time >= fromTime && session.time <= toTime) {
                                if (!session.available) {
                                    wholeSessionValid = false;
                                }
                            }
                        });
                    }
                }
            }

            if(wholeSessionValid){

            }else{
                fromTime = time;
                toTime = "";
                untilTime = "";
            }

            if(validSelected){
                this.clearSelected();
                this.setState({selectedFromTime: fromTime, selectedToTime: toTime, selectedSpace: space, selectedToTimeDisplay: untilTime, selected: validSelected});

                $(".booking-info").show();

            }else{
                this.clearSelected();
            }

        }else{
            $("#loginModal").modal("show");
        }

    }

    saveSession(){

        if(this.state.selected &&
            this.state.selectedFromTime != '' &&
            this.state.selectedSpace != '' &&
            this.state.selectedToTime != ''){

            var bookingData = this.state.bookingData;
            var groupByTime = this.state.selectedFromTime;
            var fromTime = this.state.selectedFromTime;
            var toTime = this.state.selectedToTime;
            var space = this.state.selectedSpace;
            var date = this.state.selectedDate;
            var notes = $("#txtBookingInfoNotes").val();
            var success = true;
            var _this = this;

            var moreSpaces = [];

            $("#moreSpaces div").each(function(){
                moreSpaces.push($(this).text());
            });

            //get data of repeat booking
            var repeatType = $("#repeatTab .nav-link.active").data("type");

            if(repeatType == undefined || repeatType == null){
                repeatType = "";
            }

            var endBy;
            var endAfter;
            var exceptOn;
            var param1 = '';
            var param2 = '';
            var param3 = '';
            var param4 = '';
            var param5 = '';

            if(repeatType=="day"){

                if($("[name='radioHowOften']:checked").val()=="1"){
                    //every weekdays
                    param1 = "weekdays";
                }else if($("[name='radioHowOften']:checked").val()=="2"){
                    //every weekend days
                    param1 = "weekend_days";
                }else if($("[name='radioHowOften']:checked").val()=="3"){
                    //every n day(s)
                    param1 = "every_days";
                    param2 = $("#txtOftenDay").val();
                }

            }else if(repeatType=="week"){

                param1 = $("#txtEveryWeek").val();
                param2 = "";
                $(".nav-link.active[data-day]").each(function(){
                    if(param2 != "") param2 += ",";
                    param2 += $(this).data("day");
                });

            }else if(repeatType=="month"){

                param1 = $("#txtEveryMonth").val();
                var everyMonthType = $("[name='radioDayEveryMonth']:checked").val();

                if(everyMonthType=="1"){
                    param2 = "day_of_month";
                    param3 = $("#selDayEveryMonth1").val();
                }else if(everyMonthType=="2"){
                    param2 = "day_of_week";
                    param3 = $("#selDayEveryMonth2a").val();
                    param4 = $("#selDayEveryMonth2b").val();
                }
            }

            if($("[name='radioEndBy']:checked").val()=="1"){
                endBy = $("#txtEndBy").val();
            }else if($("[name='radioEndBy']:checked").val()=="2"){
                endAfter = $("#txtEndAfter").val();
            }

            exceptOn = $("#dateExceptOn").val();


            if(this.state.existingBookingId != null){

                //Update old record

                $.ajax({
                    type: "POST",
                    url: '/booking/update',
                    data: {
                        id: _this.state.existingBookingId,
                        notes: notes,
                        more_spaces: moreSpaces,
                        reoccurrence: repeatType == '' ? null : {
                            repeat_type: repeatType.toUpperCase(),
                            param1: param1.toUpperCase(),
                            param2: param2.toUpperCase(),
                            param3: param3.toUpperCase(),
                            param4: param4.toUpperCase(),
                            param5: param5.toUpperCase(),
                            end_by: endBy,
                            end_after: endAfter,
                            except_on: exceptOn
                        }
                    },
                    async: true,
                    success : function(result) {
                        if(!result.success){
                            alert(result.message);
                        }
                        _this.searchBookingData(_this.state.selectedDate);
                    }
                });

                this.clearSelected();

            }else{

                //Create new record

                $.each(bookingData[this.state.selectedSpace], function(i, session){
                    if(session.time >= fromTime && session.time <= toTime){
                        if(!session.available){
                            success = false;
                        }
                    }
                });

                if(success){

                    $.ajax({
                        type: "POST",
                        url: '/booking/create',
                        data: {
                            space: this.state.selectedSpace,
                            more_spaces: moreSpaces,
                            session_from: this.getSessionIndexFromTime(fromTime),
                            session_to: this.getSessionIndexFromTime(toTime),
                            user_id: $("#selectUser").val(),
                            notes: notes,
                            date: this.convertDateString(this.state.selectedDate),
                            reoccurrence: repeatType == '' ? null : {
                                repeat_type: repeatType.toUpperCase(),
                                param1: param1.toUpperCase(),
                                param2: param2.toUpperCase(),
                                param3: param3.toUpperCase(),
                                param4: param4.toUpperCase(),
                                param5: param5.toUpperCase(),
                                end_by: endBy,
                                end_after: endAfter,
                                except_on: exceptOn
                            }
                        },
                        async: true,
                        success : function(result) {
                            if(!result.success){
                                alert(result.message);
                            }
                            _this.searchBookingData(_this.state.selectedDate);
                        }
                    });

                }else{
                    alert("Invalid session is selected.");
                }

                this.clearSelected();

            }


        }
    }

    //data: { space, time }
    selectExistingBooking(data){
        this.closeCalendar();
        this.clearSelected();
        $(".booking-info").show();
        this.setState({existingBookingTime: data.time, existingBookingId: data.booking_id, existingBookingSpace: data.space, selectedFromTime: data.time, selectedToTime: data.toTime, selectedToTimeDisplay: data.toTimeDisplay, selectedSpace: data.space, selectedNotes: data.notes, selected: true});
        $("#txtBookingInfoNotes").val(data.notes);

        $.get("/booking/get_reoccurrence?booking_id=" + data.booking_id, function(result){
            if(result.data != null){
                $("#btnDeleteRepeat").show();
            }else{
                $("#btnDeleteRepeat").hide();
            }
        })
    }

    deleteBooking(deleteRepeat){
        var _this = this;

        if(confirm("Confirm to remove this booking?")){
            $.post('/booking/delete', { id: this.state.existingBookingId, delete_repeat: deleteRepeat}, function(result){
                if(result.success){
                    $("#txtBookingInfoNotes").val("");
                    _this.setState({ existingBookingSpace: '', existingBookingTime: '', existingBookingId: null });
                    _this.searchBookingData(_this.state.selectedDate);
                }else{
                    alert(result.message);
                }
            })

            this.clearSelected();
        }
    }

    componentDidUpdate(){
        $('.datepicker-common').datepicker({
            format: 'yyyy-m-dd'
        });

        $('#dateExceptOn').datepicker({
            format: 'yyyy-m-dd',
            multidate: true
        });

        //Default values
        $(".repeat-common-control").hide();
        $("[name='radioEndBy']:first").click();
        $("[name='radioHowOften']:first").click();
        $("#txtEndAfter").val("2");
        $("#txtOftenDay").val("1");
        $("#txtEveryWeek").val("1");
        this.selectDayOfWeek(new Date().getDay());
        $("#txtEveryMonth").val("1");
        $("[name='radioDayEveryMonth']:first").click();
    }

    changeRepeatTab(active){
        if(!active){
            $(".repeat-common-control").hide();
        }else{
            $(".repeat-common-control").show();

            $(".booking-info:first").css({maxHeight: $(window).innerHeight() - $(".booking-info:first").offset().top})
        }
    }

    clearAllExceptionDate(){
        $('#dateExceptOn').datepicker('clearDates');
    }

    selectRepeatEndBy(val){
        if(val==1){
            $("#txtEndBy").show();
            $("#txtEndAfter").parent().hide();
        }else if(val==2){
            $("#txtEndBy").hide();
            $("#txtEndAfter").parent().show();
        }
    }

    selectHowOften(val){
        if(val==1){
            $("#txtOftenDay").parent().hide();
        }else if(val==2){
            $("#txtOftenDay").parent().hide();
        }else if(val==3){
            $("#txtOftenDay").parent().show();
        }
    }

    selectDayOfWeek(val){
        $("[data-day]").each(function(){
            if($(this).data('day')==val.toString()){
                if($(this).hasClass('active')){
                    $(this).removeClass('active');
                    $(this).attr("aria-selected", "false");
                }else{
                    $(this).addClass('active');
                    $(this).attr("aria-selected", "true");
                }
            }
        })
    }

    selectDayEveryMonth(val){
        if(val==1){
            $("#selDayEveryMonth1").parent().show();
            $("#selDayEveryMonth2a").parent().hide();
        }
    }

    componentDidMount() {
        $("#bookingLoadingSpin").remove();
        this.setState({weeks: this.getAllWeeksOfMonth(this.state.date.getMonth(), this.state.date.getFullYear()), bookingData: this.getEmptyBookingData()});
        this.searchBookingData(new Date());

        var _this = this;

        if(this.props.admin){
            $.get("/admin/user/search", function(result){
                if(result.success){
                    var data = [];

                    for(var i =0;i<result.data.length;i++){
                        if(result.data[i].active){
                            data.push(result.data[i]);
                        }
                    }

                    _this.setState({users: data});
                }
            });
        }

    }

    getAllWeeksOfMonth(month, year){
        var date = new Date();
        date.setYear(year);
        date.setDate(1);
        date.setMonth(month + 1);
        date.setDate(0);

        var days = date.getDate();
        var weeks = this.state.weeks;
        weeks = [];

        weeks.push([
            {'dateOfMonth': ''},
            {'dateOfMonth': ''},
            {'dateOfMonth': ''},
            {'dateOfMonth': ''},
            {'dateOfMonth': ''},
            {'dateOfMonth': ''},
            {'dateOfMonth': ''}
        ]);

        date.setDate(1);
        weeks[weeks.length - 1][date.getDay()].dateOfMonth = date.getDate().toString();

        for(var i = 2; i <= days; i++){

            date.setDate(i);

            if(date.getDay() == 0) {
                weeks.push([
                    {'dateOfMonth': ''},
                    {'dateOfMonth': ''},
                    {'dateOfMonth': ''},
                    {'dateOfMonth': ''},
                    {'dateOfMonth': ''},
                    {'dateOfMonth': ''},
                    {'dateOfMonth': ''}
                ]);
            }

            weeks[weeks.length - 1][date.getDay()].dateOfMonth = date.getDate().toString();
        }

        for(var i = weeks.length; i <= 6; i++){
            weeks.push([
                {'dateOfMonth': ''},
                {'dateOfMonth': ''},
                {'dateOfMonth': ''},
                {'dateOfMonth': ''},
                {'dateOfMonth': ''},
                {'dateOfMonth': ''},
                {'dateOfMonth': ''}
            ]);
        }

        return weeks;
    }

    render() {

        if(this.state.weeks.length == 0){
            var weeks = this.state.weeks;
            for(var i = 0; i < 6; i ++){
                weeks.push([
                    {'dateOfMonth': ''},
                    {'dateOfMonth': ''},
                    {'dateOfMonth': ''},
                    {'dateOfMonth': ''},
                    {'dateOfMonth': ''},
                    {'dateOfMonth': ''},
                    {'dateOfMonth': ''}
                ]);
            }

            this.setState({weeks: weeks});
        }

        const rows = this.state.weeks.map((week) =>
            (week[0].dateOfMonth=='' &&
            week[1].dateOfMonth=='' &&
            week[2].dateOfMonth=='' &&
            week[3].dateOfMonth=='' &&
            week[4].dateOfMonth=='' &&
            week[5].dateOfMonth=='' &&
            week[6].dateOfMonth=='' ?
            (
                <tr className="d-none">
                    <Day date={week[0].dateOfMonth} month={this.state.date.getMonth()} year={this.state.date.getFullYear()} selectedDate={this.state.selectedDate} />
                    <Day date={week[1].dateOfMonth} month={this.state.date.getMonth()} year={this.state.date.getFullYear()} selectedDate={this.state.selectedDate} />
                    <Day date={week[2].dateOfMonth} month={this.state.date.getMonth()} year={this.state.date.getFullYear()} selectedDate={this.state.selectedDate} />
                    <Day date={week[3].dateOfMonth} month={this.state.date.getMonth()} year={this.state.date.getFullYear()} selectedDate={this.state.selectedDate} />
                    <Day date={week[4].dateOfMonth} month={this.state.date.getMonth()} year={this.state.date.getFullYear()} selectedDate={this.state.selectedDate} />
                    <Day date={week[5].dateOfMonth} month={this.state.date.getMonth()} year={this.state.date.getFullYear()} selectedDate={this.state.selectedDate} />
                    <Day date={week[6].dateOfMonth} month={this.state.date.getMonth()} year={this.state.date.getFullYear()} selectedDate={this.state.selectedDate} />
                </tr>
            ) : (
                <tr>
                    <Day selectDate={(e) => this.selectDate(e)} date={week[0].dateOfMonth} month={this.state.date.getMonth()} year={this.state.date.getFullYear()} selectedDate={this.state.selectedDate} />
                    <Day selectDate={(e) => this.selectDate(e)} date={week[1].dateOfMonth} month={this.state.date.getMonth()} year={this.state.date.getFullYear()} selectedDate={this.state.selectedDate} />
                    <Day selectDate={(e) => this.selectDate(e)} date={week[2].dateOfMonth} month={this.state.date.getMonth()} year={this.state.date.getFullYear()} selectedDate={this.state.selectedDate} />
                    <Day selectDate={(e) => this.selectDate(e)} date={week[3].dateOfMonth} month={this.state.date.getMonth()} year={this.state.date.getFullYear()} selectedDate={this.state.selectedDate} />
                    <Day selectDate={(e) => this.selectDate(e)} date={week[4].dateOfMonth} month={this.state.date.getMonth()} year={this.state.date.getFullYear()} selectedDate={this.state.selectedDate} />
                    <Day selectDate={(e) => this.selectDate(e)} date={week[5].dateOfMonth} month={this.state.date.getMonth()} year={this.state.date.getFullYear()} selectedDate={this.state.selectedDate} />
                    <Day selectDate={(e) => this.selectDate(e)} date={week[6].dateOfMonth} month={this.state.date.getMonth()} year={this.state.date.getFullYear()} selectedDate={this.state.selectedDate} />
                </tr>
            ))

        );

        const userOptions = this.state.users.map((user) => (
                <option value={user.id}>{user.name}</option>
            )
        )


        this.refreshPoints();

        return (
            <div>
                <div className="calendar-container">
                    <div>
                        <button type="button" className="btn btn-info" onClick={(e) => this.toggleCalendar(e)}>{this.state.selectedDate.getDate()} {this.props.monthsDisplay[this.state.selectedDate.getMonth()]} {this.state.selectedDate.getFullYear()}</button>
                    </div>
                    <div className="calendar-view">
                        <div className="calendar-frame">
                            <table align="center" className="table table-bordered calendar">
                                <thead>
                                <tr>
                                    <th colSpan={7}><i className="fa fa-chevron-left arrow-prev-month" onClick={(e) => this.prevMonth(e)}></i> {this.props.monthsDisplay[this.state.date.getMonth()]} {this.state.date.getFullYear()} <i className="fa fa-chevron-right arrow-next-month"  onClick={(e) => this.nextMonth(e)}></i></th>
                                </tr>
                                <tr>
                                    <td>{this.props.daysDisplay[0]}</td>
                                    <td>{this.props.daysDisplay[1]}</td>
                                    <td>{this.props.daysDisplay[2]}</td>
                                    <td>{this.props.daysDisplay[3]}</td>
                                    <td>{this.props.daysDisplay[4]}</td>
                                    <td>{this.props.daysDisplay[5]}</td>
                                    <td>{this.props.daysDisplay[6]}</td>
                                </tr>
                                </thead>
                                <tbody>
                                {rows}
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <div className="booking-info">
                    <div className="booking-info-from">
                        <span id="bookingInfoFromTime">{this.state.selectedDate.getFullYear()}-{this.state.selectedDate.getMonth()+1}-{this.state.selectedDate.getDate()} {this.state.selectedFromTime}</span>
                        <span id="bookingInfoToTime">{this.state.selectedToTimeDisplay != "" ? "-" + this.state.selectedToTimeDisplay : ""}</span>
                    </div>
                    <div className="booking-info-space"><span id="bookingInfoSpace">{this.state.selectedSpace}</span></div>
                    {
                        this.state.selected
                            ? (
                            <div className="booking-info-control">
                                {
                                    this.state.selectedToTimeDisplay != "" ?
                                        (
                                            <div>
                                                <div>
                                                    <div id="moreSpaces"></div>
                                                    <button type="button" className="btn btn-success" onClick={(e) => this.addSpace(e)}>Add Space</button>
                                                </div>
                                                {
                                                    this.props.admin && (this.state.existingBookingSpace == '' || this.state.existingBookingTime == '') ?
                                                        (
                                                            <div style={{marginTop: 5}}>
                                                                Select User
                                                                <br></br>
                                                                <select className="form-control" id="selectUser">
                                                                    <option value="">You</option>
                                                                    {userOptions}
                                                                </select>
                                                            </div>
                                                        )
                                                        :
                                                        (
                                                            <div></div>
                                                        )
                                                }

                                                <div><textarea id="txtBookingInfoNotes" placeholder="Notes">{this.state.selectedNotes}</textarea></div>
                                                <div className="repeat-container">
                                                    {
                                                        this.state.existingBookingSpace == '' || this.state.existingBookingTime == '' ?
                                                            <div>
                                                                Repeat
                                                                <ul class="nav nav-pills mb-3" id="repeatTab" role="tablist">
                                                                    <li class="nav-item">
                                                                        <a class="nav-link active" data-type="" id="repeatTabNone" onClick={(e) => this.changeRepeatTab(false)} data-toggle="pill" href="#repeatNone" role="tab" aria-controls="pills-none" aria-selected="true"><i class="fa fa-ban fa-2" aria-hidden="true"></i></a>
                                                                    </li>
                                                                    <li class="nav-item">
                                                                        <a class="nav-link" data-type="day" id="repeatTabDay" onClick={(e) => this.changeRepeatTab(true)} data-toggle="pill" href="#repeatDay" role="tab" aria-controls="pills-day" aria-selected="false">D</a>
                                                                    </li>
                                                                    <li class="nav-item">
                                                                        <a class="nav-link" data-type="week" id="repeatTabWeek" onClick={(e) => this.changeRepeatTab(true)} data-toggle="pill" href="#repeatWeek" role="tab" aria-controls="pills-week" aria-selected="false">W</a>
                                                                    </li>
                                                                    <li class="nav-item">
                                                                        <a class="nav-link" data-type="month" id="repeatTabMonth" onClick={(e) => this.changeRepeatTab(true)} data-toggle="pill" href="#repeatMonth" role="tab" aria-controls="pills-month" aria-selected="false">M</a>
                                                                    </li>
                                                                </ul>
                                                                <div class="tab-content" id="pills-tabContent">
                                                                    <div class="tab-pane fade show active" id="repeatNone" role="tabpanel" aria-labelledby="repeatTabNone"></div>
                                                                    <div class="tab-pane fade" id="repeatDay" role="tabpanel" aria-labelledby="repeatTabDay">
                                                                        <div class="form-check">
                                                                            <input class="form-check-input" type="radio" onClick={(e) => this.selectHowOften(1)} name="radioHowOften" id="radioHowOften1" value="1"></input>
                                                                            <label class="form-check-label" for="radioHowOften1">
                                                                                On weekdays
                                                                            </label>
                                                                        </div>
                                                                        <div class="form-check">
                                                                            <input class="form-check-input" type="radio" onClick={(e) => this.selectHowOften(2)} name="radioHowOften" id="radioHowOften2" value="2"></input>
                                                                            <label class="form-check-label" for="radioHowOften2">
                                                                                On weekend days
                                                                            </label>
                                                                        </div>
                                                                        <div class="form-check">
                                                                            <input class="form-check-input" type="radio" onClick={(e) => this.selectHowOften(3)} name="radioHowOften" id="radioHowOften3" value="3"></input>
                                                                            <label class="form-check-label" for="radioHowOften3">
                                                                                Every
                                                                            </label>
                                                                        </div>
                                                                        <div style={{display: 'none'}} class="input-group mb-2 mr-sm-2">
                                                                            <input type="number" min="1" class="form-control" id="txtOftenDay"></input>
                                                                            <div class="input-group-append">
                                                                                <div class="input-group-text">day(s)</div>
                                                                            </div>
                                                                        </div>
                                                                    </div>
                                                                    <div class="tab-pane fade" id="repeatWeek" role="tabpanel" aria-labelledby="repeatTabWeek">
                                                                        <div>Every</div>
                                                                        <div class="input-group mb-2 mr-sm-2">
                                                                            <input type="number" min="1" class="form-control" id="txtEveryWeek"></input>
                                                                            <div class="input-group-append">
                                                                                <div class="input-group-text">week(s)</div>
                                                                            </div>
                                                                        </div>
                                                                        <div>on</div>
                                                                        <ul class="nav nav-pills mb-3" role="tablist">
                                                                            <li class="nav-item">
                                                                                <a class="nav-link" data-day="0" href="#" role="tab" onClick={(e) => this.selectDayOfWeek(0)} aria-controls="pills-wd0" aria-selected="false">Su</a>
                                                                            </li>
                                                                            <li class="nav-item">
                                                                                <a class="nav-link" data-day="1" href="#" role="tab" onClick={(e) => this.selectDayOfWeek(1)} aria-controls="pills-wd1" aria-selected="false">Mo</a>
                                                                            </li>
                                                                            <li class="nav-item">
                                                                                <a class="nav-link" data-day="2" href="#" role="tab" onClick={(e) => this.selectDayOfWeek(2)} aria-controls="pills-wd2" aria-selected="false">Tu</a>
                                                                            </li>
                                                                            <li class="nav-item">
                                                                                <a class="nav-link" data-day="3" href="#" role="tab" onClick={(e) => this.selectDayOfWeek(3)} aria-controls="pills-wd3" aria-selected="false">We</a>
                                                                            </li>
                                                                            <li class="nav-item">
                                                                                <a class="nav-link" data-day="4" href="#" role="tab" onClick={(e) => this.selectDayOfWeek(4)} aria-controls="pills-wd4" aria-selected="false">Th</a>
                                                                            </li>
                                                                            <li class="nav-item">
                                                                                <a class="nav-link" data-day="5" href="#" role="tab" onClick={(e) => this.selectDayOfWeek(5)} aria-controls="pills-wd5" aria-selected="false">Fr</a>
                                                                            </li>
                                                                            <li class="nav-item">
                                                                                <a class="nav-link" data-day="6" href="#" role="tab" onClick={(e) => this.selectDayOfWeek(6)} aria-controls="pills-wd6" aria-selected="false">Sa</a>
                                                                            </li>
                                                                        </ul>
                                                                    </div>
                                                                    <div class="tab-pane fade" id="repeatMonth" role="tabpanel" aria-labelledby="repeatTabMonth">
                                                                        <div>Every</div>
                                                                        <div class="input-group mb-2 mr-sm-2">
                                                                            <input type="number" min="1" class="form-control" id="txtEveryMonth"></input>
                                                                            <div class="input-group-append">
                                                                                <div class="input-group-text">Month(s)</div>
                                                                            </div>
                                                                        </div>
                                                                        <div>on day of</div>
                                                                        <div class="form-check">
                                                                            <input class="form-check-input" type="radio" name="radioDayEveryMonth" onClick={(e) => this.selectDayEveryMonth(1)} id="radioDayEveryMonth1" value="1"></input>
                                                                            <label class="form-check-label" for="radioDayEveryMonth1">
                                                                                month
                                                                            </label>
                                                                        </div>
                                                                        <div>
                                                                            <select id="selDayEveryMonth1" className="form-control">
                                                                                <option value="1">Day 1</option>
                                                                                <option value="2">Day 2</option>
                                                                                <option value="3">Day 3</option>
                                                                                <option value="4">Day 4</option>
                                                                                <option value="5">Day 5</option>
                                                                                <option value="6">Day 6</option>
                                                                                <option value="7">Day 7</option>
                                                                                <option value="8">Day 8</option>
                                                                                <option value="9">Day 9</option>
                                                                                <option value="10">Day 10</option>
                                                                                <option value="11">Day 11</option>
                                                                                <option value="12">Day 12</option>
                                                                                <option value="13">Day 13</option>
                                                                                <option value="14">Day 14</option>
                                                                                <option value="15">Day 15</option>
                                                                                <option value="16">Day 16</option>
                                                                                <option value="17">Day 17</option>
                                                                                <option value="18">Day 18</option>
                                                                                <option value="19">Day 19</option>
                                                                                <option value="20">Day 20</option>
                                                                                <option value="21">Day 21</option>
                                                                                <option value="22">Day 22</option>
                                                                                <option value="23">Day 23</option>
                                                                                <option value="24">Day 24</option>
                                                                                <option value="25">Day 25</option>
                                                                                <option value="26">Day 26</option>
                                                                                <option value="27">Day 27</option>
                                                                                <option value="28">Day 28</option>
                                                                                <option value="29">Day 29</option>
                                                                                <option value="30">Day 30</option>
                                                                                <option value="31">Day 31</option>
                                                                            </select>
                                                                        </div>
                                                                    </div>
                                                                    <div class="repeat-common-control">
                                                                        <div class="form-check">
                                                                            <input class="form-check-input" type="radio" name="radioEndBy" onClick={(e) => this.selectRepeatEndBy(1)} id="radioEndby1" value="1"></input>
                                                                            <label class="form-check-label" for="radioEndby1">
                                                                                End by
                                                                            </label>
                                                                            <input style={{marginLeft: 20}}  class="form-check-input" type="radio" name="radioEndBy" onClick={(e) => this.selectRepeatEndBy(2)} id="radioEndby2" value="2"></input>
                                                                            <label style={{marginLeft: 40}} class="form-check-label" for="radioEndby2">
                                                                                End after
                                                                            </label>
                                                                        </div>
                                                                        <input type="text" style={{display: 'none'}} id="txtEndBy" class="datepicker datepicker-common form-control" readonly="readonly" value={this.state.selectedDate.getFullYear() + '-' + (this.state.selectedDate.getMonth()+1) + '-' + this.state.selectedDate.getDate()}></input>
                                                                        <div style={{display: 'none'}} class="input-group mb-2 mr-sm-2">
                                                                            <input type="number" min="1" class="form-control" id="txtEndAfter"></input>
                                                                            <div class="input-group-append">
                                                                                <div class="input-group-text">occurrence(s)</div>
                                                                            </div>
                                                                        </div>
                                                                        <div>Except on</div>
                                                                        <div>
                                                                            <input type="text" id="dateExceptOn" class="datepicker form-control" readonly="readonly" placeholder="Select dates"></input>
                                                                        </div>
                                                                        <a href="javascript:void(0)" onClick={(e) => this.clearAllExceptionDate()}><small>clear all exceptions</small></a>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            :
                                                            <div>

                                                            </div>
                                                    }
                                                </div>
                                                <button type="button" className="btn btn-secondary" onClick={(e) => this.clearSelected(e)}>RESET</button>
                                                {
                                                    this.state.existingBookingSpace == '' || this.state.existingBookingTime == ''
                                                        ? (
                                                        <span></span>
                                                    ) : (
                                                        <span>
                                                            &nbsp;
                                                            <button type="button" className="btn btn-danger" onClick={(e) => this.deleteBooking(false)}>REMOVE</button>
                                                            <button type="button" id="btnDeleteRepeat" style={{display:'none', marginLeft: 4}} className="btn btn-danger" onClick={(e) => this.deleteBooking(true)}>REMOVE REPEAT</button>
                                                        </span>

                                                    )
                                                }
                                                &nbsp;
                                                <button type="button" className="btn btn-primary" onClick={(e) => this.saveSession(e)}>SAVE</button>
                                            </div>
                                        )
                                        :
                                        (
                                            <button type="button" className="btn btn-secondary" onClick={(e) => this.clearSelected(e)}>RESET</button>
                                        )
                                }

                            </div>
                            ) :
                            (
                                <div></div>
                            )
                    }
                </div>
                <div id="bookingTimetable" className="timetable-container">
                    <Timetable admin={this.props.admin} bookingData={this.state.bookingData} forbidSessions={this.state.forbidSessions} selectedSpace={this.state.selectedSpace} selectedFromTime={this.state.selectedFromTime} selectedToTime={this.state.selectedToTime} selectTime={(e) => this.selectTime(e)} selectExistingBooking={(e) => this.selectExistingBooking(e)} spaces={this.props.spaces} timespans={this.props.timespans} minutesPerSession={this.props.minutesPerSession} />
                </div>
            </div>);
    }
}



