/**
 * Created by liyanjun1 on 17/4/1.
 */
var isPower = '/Handler/Users.ashx?action=QueryIsFunByUser';
var selDate = getNowFormatDate();
var selStartTime = "09:00:00";
var selEndTime = "10:00:00";
var meetingResource = [];
var floor_path = '/Handler/Floor.ashx?Action=SelectByWhere'
var floorlist = [];
var meetingroom_path = '/Handler/MeetingRoom.ashx?action=SelectByWhere';
var meetingroom_list = [];
var currentSelectMeeting = 'refreshMeeting';
var currentSelectMeetingId;
var host = "";
var step_meetingroom_list = [];
var step_meetingroom_path = '/Handler/MeetingRoom.ashx?action=SelectAllGroupMeetingroom';
var all_meeting = [];
var all_meeting_path = '/Handler/Meeting.ashx?action=SelectCaledarByDate';
var outside_path = '/Handler/Users.ashx?action=SelectAllGroupOutside';
var outside = [];
var add_tempPerson_path = '/Handler/Users.ashx?action=AddOutside';

function load_floor_data(p) {
    ajax_post(floor_path, { page: p }, function (res) {
        //page
        res.unshift({ Id: "", cla: "", FloorName: "全部楼层" });
        floorlist.upd(res)

        load_meetingroom("");
    })
}
load_floor_data();

function load_meetingroom(floorid) {
    ajax_post(meetingroom_path, { FloorId: floorid }, function (res) {
        //page
        res.unshift({ Id: "", MRName: "全部会议室" });
        meetingroom_list.upd(res);
    })
}

var popmenutimer = null;
function showNewMeetingPopMenu(jsEvent) {
    $('#popnewmeetingmenu')[0].style.position = "absolute";
    $('#popnewmeetingmenu')[0].style.top = jsEvent.pageY + "px";
    $('#popnewmeetingmenu')[0].style.left = jsEvent.pageX + "px";
    $('#popnewmeetingmenu')[0].style.zIndex = 100;
    $('#popnewmeetingmenu').removeClass('hide');
    $('#popnewmeetingmenu').addClass('show');

    if (popmenutimer != null)
        clearInterval(popmenutimer);

    popmenutimer = setInterval(function () {
        $('#popnewmeetingmenu').removeClass('show');
        $('#popnewmeetingmenu').addClass('hide');

        clearInterval(popmenutimer);
        popmenutimer = null;
    }, 1000 * 3);
}

var meetingInfoPopMenuTimer = null;
function showMeetingInfoPopMenu(jsEvent) {
    $('#popmeetinginfomenu')[0].style.position = "absolute";
    $('#popmeetinginfomenu')[0].style.top = jsEvent.pageY + "px";
    $('#popmeetinginfomenu')[0].style.left = jsEvent.pageX + "px";
    $('#popmeetinginfomenu')[0].style.zIndex = 100;
    $('#popmeetinginfomenu').removeClass('hide');
    $('#popmeetinginfomenu').addClass('show');

    if (meetingInfoPopMenuTimer != null)
        clearInterval(meetingInfoPopMenuTimer);

    meetingInfoPopMenuTimer = setInterval(function () {
        $('#popmeetinginfomenu').removeClass('show');
        $('#popmeetinginfomenu').addClass('hide');

        clearInterval(meetingInfoPopMenuTimer);
        meetingInfoPopMenuTimer = null;
    }, 1000 * 3);
}

var meetingInfoOpPopMenuTimer = null;
function showMeetingInfoOPPopMenu(jsEvent) {
    $('#popmeetinginfoopmenu')[0].style.position = "absolute";
    $('#popmeetinginfoopmenu')[0].style.top = jsEvent.pageY + "px";
    $('#popmeetinginfoopmenu')[0].style.left = jsEvent.pageX + "px";
    $('#popmeetinginfoopmenu')[0].style.zIndex = 100;
    $('#popmeetinginfoopmenu').removeClass('hide');
    $('#popmeetinginfoopmenu').addClass('show');

    if (meetingInfoOpPopMenuTimer != null)
        clearInterval(meetingInfoOpPopMenuTimer);

    meetingInfoOpPopMenuTimer = setInterval(function () {
        $('#popmeetinginfoopmenu').removeClass('show');
        $('#popmeetinginfoopmenu').addClass('hide');

        clearInterval(meetingInfoOpPopMenuTimer);
        meetingInfoOpPopMenuTimer = null;
    }, 1000 * 3);
}

var url_events_resource = '../Handler/MeetingRoom.ashx?action=SelectMeetingRoomByRoomInfo';
var url_events = '/Handler/Meeting.ashx?Action=SelectMeetingForCalendar';
var curSelEvent = null;

var selectMeeting = [];
function selectMeetingByOwner() {
    alert("selectMeetingByOwner");
    var myDate = new Date();
    var nowY = myDate.getFullYear();
    var nowM = myDate.getMonth() + 1;
    var nowD = myDate.getDate();
    var beginDate = nowY + "-" + (nowM < 10 ? "0" + nowM : nowM) + "-" + (nowD < 10 ? "0" + nowD : nowD);

    var lw = new Date(myDate.getTime() + 1000 * 60 * 60 * 24 * 30);
    var lastY = lw.getFullYear();
    var lastM = lw.getMonth() + 1;
    var lastD = lw.getDate();
    var endDate = lastY + "-" + (lastM < 10 ? "0" + lastM : lastM) + "-" + (lastD < 10 ? "0" + lastD : lastD);

    ajax_post("/handler/Users.ashx?action=Session", this.login, function (res) {
        if (res.state === "1") {
            ajax_post("/Handler/Meeting.ashx?Action=SelectMeetingByOwner", { Owner: res.data[0].Id, BeginDate: beginDate, EndDate: endDate }, function (res) {
                if (res.state === "1") {
                    for (var i = 0; i < res.data.length; i++) {
                        res.data[i].MeetingDate = getFormatDate(eval(res.data[i].MeetingDate));
                    }
                    selectMeeting.upd(res.data);
                }
            })

        }
        else {
            alert(res.data);
        }
    })


}

var curSearchStarttime, curSearchEndtime;

$(function () { // document ready
    alert("AAA");
    ajax_post(isPower, { FunId: '100' }, function (res) {
        alert(res.state);
        if (res.state === '1') {
            if (res.data[0].IsHave != '1') {
                location.href = 'home.html';
            }
        }
    });

    selectMeetingByOwner();

    $('.form_time').datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 1,
        minView: 0,
        maxView: 1,
        forceParse: 0,
        minuteStep: 30,
    });


    $('#meeting-date').datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        minView: 2,
        forceParse: 0,
        startDate: new Date(),
        endDate: new Date(new Date().valueOf() + 10 * 60 * 60 * 1000 * 24)
    });
    $('#meeting-date').datetimepicker("setDate", new Date());

    $('#start-time').datetimepicker('setDate', getTimeFromDate(new Date(), "09:00:00"));
    $('#end-time').datetimepicker('setDate', getTimeFromDate(new Date(), "10:00:00"));

    $('#add-meeting-date').datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        minView: 2,
        forceParse: 0,
        startDate: new Date(),
        endDate: new Date(new Date().valueOf() + 10 * 60 * 60 * 1000 * 24)
    });
    $('#add-meeting-date').datetimepicker("setDate", new Date());

    $('#update-meeting-date').datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        minView: 2,
        forceParse: 0
    });

    $('#update-meeting-date').datetimepicker("setDate", new Date());

    //$('#meeting-date').datetimepicker().on('changeDate', function(ev){
    //    var date = getFormatDate(ev.date);

    //    searchMeetingConfig[0].MeetingDate = date;

    //});

    $('#step-meeting-date').datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        minView: 2,
        forceParse: 0,
        startDate: new Date(),
        endDate: new Date(new Date().valueOf() + 10 * 60 * 60 * 1000 * 24)
    });
    $('#step-meeting-date').datetimepicker("setDate", new Date());
    $('#step-start-time').datetimepicker('setDate', getTimeFromDate(new Date(), "09:00:00"));
    $('#step-end-time').datetimepicker('setDate', getTimeFromDate(new Date(), "10:00:00"));
    $('#step-meeting-date').datetimepicker().on('changeDate', function (ev) {
        var date = getFormatDate(ev.date);
        $('#input-step-meeting-date').val(date);

    });


    $('#step-start-time').datetimepicker().on('changeDate', function (ev) {
        var starttime = getFormatTime(ev.date);
        if (starttime === '0:00:00') {
            starttime = '00:00:00';
        }
        if ($('#input-step-end-time').val() <= starttime) {
            //$('#start-time').datetimepicker('setDate', getTimeFromDate(new Date(),searchMeetingConfig[0].StartTime));
            $.toaster({ priority: "danger", title: "时间选择错误", message: "开始时间要小于结束时间！" });
        }
        $('#input-step-start-time').val(starttime);

    });

    $('#step-end-time').datetimepicker().on('changeDate', function (ev) {
        var endtime = getFormatTime(ev.date);
        if (endtime === '0:00:00') {
            endtime = '00:00:00';
        }
        if (endtime <= $('#input-step-start-time').val()) {
            //$('#start-time').datetimepicker('setDate', getTimeFromDate(new Date(),searchMeetingConfig[0].StartTime));
            $.toaster({ priority: "danger", title: "时间选择错误", message: "结束时间要大于开始时间！" });
        }
        $('#input-step-end-time').val(endtime);

    });

    $('#start-time').datetimepicker().on('changeDate', function (ev) {
        var starttime = getFormatTime(ev.date);
        if (starttime === '0:00:00') {
            starttime = '00:00:00';
        }
        if ($('#input-end-time').val() <= starttime) {
            // $('#start-time').datetimepicker('setDate', getTimeFromDate(new Date(),searchMeetingConfig[0].StartTime));
            $.toaster({ priority: "danger", title: "时间选择错误", message: "开始时间要小于结束时间！" });
        }
        searchMeetingConfig[0].StartTime = starttime;

    });

    $('#end-time').datetimepicker().on('changeDate', function (ev) {
        var endtime = getFormatTime(ev.date);
        if (endtime === '0:00:00') {
            endtime = '00:00:00';
        }
        if (endtime <= $('#input-start-time').val()) {
            // $('#end-time').datetimepicker('setDate',getTimeFromDate(new Date(),searchMeetingConfig[0].EndTime));
            //alert("结束时间要大于开始时间！");
            $.toaster({ priority: "danger", title: "时间选择错误", message: "结束时间要大于开始时间！" });
        }
        searchMeetingConfig[0].EndTime = endtime;
    });

    $('#history-start-date').datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        minView: 2,
        forceParse: 0
    });

    $('#history-end-date').datetimepicker({
        language: 'zh-CN',
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        minView: 2,
        forceParse: 0
    });

    var nowDate = getNowFormatDate();
    alert(nowDate);
    $('#calendar').fullCalendar({
        buttonText: { today: '今天', month: '月', week: '周', day: '日' },
        now: nowDate,
        editable: true, // enable draggable events
        aspectRatio: 1.7,
        scrollTime: '08:00', // undo default 8am scrollTime
        editable: true,
        eventLimit: true, // allow "more" link when too many events
        selectable: true,
        minTime: '08:00',
        maxTime: '18:00',
        header: {
            //buttonText: {today:'今天',month:'月会议',week:'周会议',day:'日会议'},
            buttonText: {today:'今天',month:'月会议',week:'周会议',day:'日会议'},
            left: 'today prev,next',
            center: 'title',
            right: 'timelineDay,timelineThreeDays,agendaWeek,month'
        },
        defaultView: 'timelineDay',
        views: {
            timelineThreeDays: {
                type: 'timeline',
                duration: { days: 3 }
            }
        },
        resourceLabelText: '会议室TEST',
        locale: 'zh-cn',
        resources: function (callback) {
            if (currentSelectMeeting === 'currentSelectMeeting') {
                ajax_post("/Handler/Meeting.ashx?action=SelectByMeetingId", { Id: currentSelectMeetingId }, function (res) {
                    callback(res.data);
                })
            } else if (currentSelectMeeting === 'rightSelectMeeting') {
                var itemList = $('.itemList');
                for (var i = 0; i < itemList.length; i++) {
                    if (itemList[i].className.indexOf('active') != -1) {
                        ajax_post(url_events_resource, {
                            MRId: itemList[i].id,
                        }, function (res) {
                            $('#loading').removeClass('show');
                            $('#loading').addClass('hidden');
                            callback(res);
                        })

                    }
                }
            } else if (currentSelectMeeting === 'refreshMeeting') {
                ajax_post(url_events_resource, {}, function (res) {
                    $('#loading').removeClass('show');
                    $('#loading').addClass('hidden');
                    //callback(res);
                    var JSONStr1 = "{\"name\" : \"张三\"}";
                    alert(JSONStr1);
                    var res = "ABC";
                    callback(JSONStr1.name);
                })
            } else {
                var floorid = $('#floor-select-input option:selected').val();
                var meetingroomid = $('#meetingroom-select-input option:selected').val();

                ajax_post(url_events_resource, {
                    FloorId: floorid,
                    MRId: meetingroomid,
                    MeetingDate: $('#input-meeting-date').val(),
                    StartTime: $('#input-start-time').val(),
                    EndTime: $('#input-end-time').val()
                }, function (res) {
                    $('#loading').removeClass('show');
                    $('#loading').addClass('hidden');
                    $('#search_meet_modal').modal('hide').on('hidden.bs.modal', function () { })
                    callback(res);
                })
            }
        },
        events: { // you can also specify a plain string like 'json/events.json'
            url: url_events,
            error: function () {
                $('#script-warning').show();
            }
        },
        eventClick: function (calEvent, jsEvent, view, resource) {

            //alert('Event: ' + calEvent.title);

            curSelEvent = calEvent;

            if (calEvent.editable) {
                showMeetingInfoOPPopMenu(jsEvent);
            }
            else {
                showMeetingInfoPopMenu(jsEvent);
            }
            //$(".border-color").removeClass("border-color");
            //$(this).css('border-color', '#35c4ff');


        },
        eventMouseover: function (calEvent, jsEvent, view) {

            //alert('Event: ' + calEvent.title);
            //alert('Coordinates: ' + jsEvent.pageX + ',' + jsEvent.pageY);
            //alert('View: ' + view.name);

            // change the border color just for fun
            //$(this).css('border-color', 'red');
        },
        select: function (start, end, jsEvent, view, resource) {

            var date = $.fullCalendar.formatDate(start, "YYYY-MM-DD");
            var curtime = getFormatTime(new Date());
            selDate = $.fullCalendar.formatDate(start, "YYYY-MM-DD");
            selStartTime = $.fullCalendar.formatDate(start, "HH:mm:ss");
            selEndTime = $.fullCalendar.formatDate(end, "HH:mm:ss");
            var curdate = getNowFormatDate();
            var curtime = getNowFormatTime();
            if (date <= curdate && curtime >= selStartTime) {
                $.toaster({ priority: "danger", title: "时间过期", message: "您选择的时间已过期！" });
            }
            else {
                meetingResource = resource;

                showNewMeetingPopMenu(jsEvent);

                load_group_servers(meetingResource.OrgCode);
            }
        },
        viewRender: function (view, template) {
            var nowY = view.start._d.getFullYear();
            var nowM = view.start._d.getMonth() + 1;
            var nowD = view.start._d.getDate();
            var startDate = nowY + "-" + (nowM < 10 ? "0" + nowM : nowM) + "-" + (nowD < 10 ? "0" + nowD : nowD);
            curSearchStarttime = startDate;

            var lastY = view.end._d.getFullYear();
            var lastM = view.end._d.getMonth() + 1;
            var lastD = view.end._d.getDate() - 1;
            var endDate = lastY + "-" + (lastM < 10 ? "0" + lastM : lastM) + "-" + (lastD < 10 ? "0" + lastD : lastD);
            curSearchEndtime = endDate;

            ajax_post(host + all_meeting_path, { start: startDate, end: endDate }, function (res) {
                if (res.length != 0) {
                    res.forEach(function (t, n, a) {
                        t.ItemList.forEach(function (t1, n1, a1) {
                            t1.sub_title = t1.title.substr(0, 8);
                            t1.sub_MRName = t1.MRName.substr(0, 8);
                        })
                    })
                }
                all_meeting.upd(res);
            })

        }
    });

    $(".right-detail")[0].style.height = (document.body.clientHeight - 95) + "px";


    $("#refresh").click(function () {
        window.location.reload(true);
    })


});

function OnfoolrChanged(id) {
    load_meetingroom(id);
}

function OnMeetingroomChanged(id) {
    var OrgCode = "";
    for (var i = 0; i < step_meetingroom_list.length; i++) {
        for (var j = 0; j < step_meetingroom_list[i].children.length; j++) {
            if (step_meetingroom_list[i].children[j].id == id) {
                OrgCode = step_meetingroom_list[i].children[j].orgcode;
                break;
            }
        }

        if (OrgCode != "")
            break;
    }

    load_group_servers(OrgCode);
}

var employeedata = [];
var temp_Id = [];

function load_group_employee(MeetingId) {
    ajax_post("/Handler/Users.ashx?Action=SelectAllGroupUsers", { MeetingId: MeetingId }, function (res) {
        employeedata.upd(res);

    })
}

load_group_employee('');

function load_outside(MeetingId) {
    ajax_post(outside_path, { MeetingId: MeetingId }, function (res) {
        outside.upd(res);

        if ($('#add_meet_modal')[0].style.display === 'block') {
            $("#temp_s2_multi_value")[0].innerHTML = "";
            multiTemp = $("#temp_s2_multi_value").select2({
                data: outside,
                tags: true
            });

            multiTemp.val(temp_Id).trigger('change');
        }
        if ($('#update_meet_modal')[0].style.display === 'block') {
            $("#update_temp_s2_multi_value")[0].innerHTML = '';
            update_temp_multiselect = $("#update_temp_s2_multi_value").select2({
                data: outside,
                tags: true
            });

            update_temp_multiselect.val(temp_Id).trigger('change');
        }
        if ($('#addMettingStep')[0].style.display === 'block') {
            $("#step_temp_s2_multi_value")[0].innerHTML = '';
            step_temp_multiselect = $("#step_temp_s2_multi_value").select2({
                data: outside,
                tags: true,
                width: '100%'
            });

            step_temp_multiselect.val(temp_Id).trigger('change');
        }

    })
}

load_outside('');


var search_path;

searchHistorybook = [{
    beginDate: "",
    endDate: ""
}];
//获取当前日期
var myDate = new Date();
var lastDate = new Date(myDate);
var nowY = lastDate.getFullYear();
var nowM = lastDate.getMonth() + 1;
var nowD = lastDate.getDate();
var endDate = nowY + "-" + (nowM < 10 ? "0" + nowM : nowM) + "-" + (nowD < 10 ? "0" + nowD : nowD);//当前日期

//获取三十天前日期
var lw = new Date(myDate - 1000 * 60 * 60 * 24 * 30);//最后一个数字30可改，30天的意思
var lastY = lw.getFullYear();
var lastM = lw.getMonth() + 1;
var lastD = lw.getDate();
var beginDate = lastY + "-" + (lastM < 10 ? "0" + lastM : lastM) + "-" + (lastD < 10 ? "0" + lastD : lastD);//三十天之前日期
searchHistorybook[0].beginDate = beginDate;
searchHistorybook[0].endDate = endDate;



var curDate = getNowFormatDate();

var addMeeting = [{
    Title: "",
    MeetingDate: curDate,
    StartTime: "",
    EndTime: "",
    BookPerson: "",
    MeetingRoomId: "",
    Presenter: "",
    Remark: "",
    Access: "",
    AccessName: "",
    NeedCheckIn: ""
}];

var updateMeeting = [{
    Id: "",
    Title: "",
    MeetingDate: curDate,
    StartTime: "",
    EndTime: "",
    BookPerson: "",
    MeetingRoomId: "",
    Presenter: "",
    NeedCheckIn: ""
}];

var showMeeting = [{
    Id: "",
    Title: "",
    MeetingDate: curDate,
    StartTime: "",
    EndTime: "",
    BookPerson: "",
    MeetingRoomId: "",
    Presenter: "",
    NeedCheckIn: ""
}];

var searchMeetingConfig = [{
    MeetingDate: curDate,
    StartTime: "",
    EndTime: ""
}];

var historybookdata = [];
var pagesize = 10;
search_path = '/Handler/Meeting.ashx?Action=SelectMeetingByDate&rows=' + pagesize;

var page_info = {
    row_cnt: 55,
    row_from: 1,
    row_to: pagesize,
    page_cnt: 22,
    lst: [1],
    cur_page: 1
}
function set_page(res, page_info) {
    page_info.row_cnt = Number(res.records)
    page_info.row_from = Number((res.page - 1) * 10)
    page_info.row_to = Number(res.page * 10)
    page_info.cur_page = Number(res.page)
    page_info.page_cnt = Number(res.total)
    var lst = []
    for (var i = 1; i <= res.total; i++) {
        lst.push(i)
    }
    page_info.lst.upd(lst)
}
function load_data(p, beginDate, endDate) {
    ajax_post(search_path, { page: p, begindate: beginDate, enddate: endDate }, function (res) {
        //page
        if (parseInt(res.records) != 0) {
            for (var i = 0; i < res.rows.length; i++) {
                res.rows[i].MeetingDate = getFormatDate(eval(res.rows[i].MeetingDate));
            }
            historybookdata.upd(res.rows);
            set_page(res, page_info);
        }
        searchHistorybook[0].beginDate = beginDate;
        searchHistorybook[0].endDate = endDate;
        $('#history-start-date input').val(beginDate);
        $('#history-end-date input').val(endDate);

    })

}

var serversData = [];
function load_group_servers(OrgCode, ReceiveService) {
    //$('#s2_multi_service_value')[0].innerHTML = "";;
    ajax_post("/Handler/MeetingService.ashx?Action=SelectServiceTypeByOrgCode", { OrgCode: OrgCode, page: 1, rows: 100, Enable: 1 }, function (res) {

        serversData.upd(res);

        $('#step_s2_multi_service_value')[0].innerHTML = "";
        stepservice = $('#step_s2_multi_service_value').select2({
            data: serversData,
            tags: true,
            width: '100%'
        });
        stepservice.val("").trigger('change');

        if (ReceiveService != undefined)
            UpdateMeetingInfoUI(ReceiveService);
    })
}


function load_step_meetingroom(date, beginTime, EndTime) {
    ajax_post(step_meetingroom_path, { Date: date, BeginTime: beginTime, EndTime: EndTime }, function (res) {
        //page
        $('#step_selectmettingroom_s2_multi_value')[0].innerHTML = ''
        step_meetingroom_list.upd(res);
        stepmultiServiceSelect = $('#step_selectmettingroom_s2_multi_value').select2({
            data: step_meetingroom_list,
            tags: true,
            width: '100%',
            maximumSelectionLength: 1
        });
    })
}
//load_step_meetingroom();


var app = new Vue({
    el: "#meeting_calendar",
    data: {
        addmeeting: addMeeting,
        updatemeeting: updateMeeting,
        showmeeting: showMeeting,
        foolrlist: floorlist,
        meetingroomlist: meetingroom_list,
        searchmeetingconfig: searchMeetingConfig,
        selectMeeting: selectMeeting,
        historybookdata: historybookdata,
        page_info: page_info,
        searchHistorybook: searchHistorybook,
        serversData: serversData,
        all_meeting: all_meeting
    },
    methods: {
        change_page: function (p) {
            var startdate = $('#history-start-date input').val();
            var enddate = $('#history-end-date input').val();
            load_data(p, startdate, enddate);
        },
        on_search_meeting: function () {
            $('#loading').removeClass('hidden');
            $('#loading').addClass('show');
            currentSelectMeeting = '';

            $('#calendar').fullCalendar('removeResource');
            $('#calendar').fullCalendar('refetchResources');
            $('#calendar').fullCalendar('refetchEvents');
        },
        on_meeting_info: function () {
            if (null != curSelEvent) {
                showMeetingInfoForModal(curSelEvent);
            }
        },
        on_meeting_update: function () {
            if (null != curSelEvent) {
                updateMeetingdateForModal(curSelEvent);
            }
        },
        on_meeting_cancel: function () {
            var r = confirm("是否确定取消会议");
            if (r == true) {
                ajax_post("/Handler/Meeting.ashx?Action=Del", { Ids: curSelEvent.id }, function (res) {
                    if (res.state != 1) {
                        alert("取消会议失败！");
                    }
                    else {
                        currentSelectMeeting = '';
                        $('#calendar').fullCalendar('refetchEvents');
                        $.toaster({ priority: "success", title: "提示：", message: "您已取消会议！" });
                        ajax_post(host + all_meeting_path, { start: curSearchStarttime, end: curSearchEndtime }, function (res) {
                            if (res.length != 0) {
                                res.forEach(function (t, n, a) {
                                    t.ItemList.forEach(function (t1, n1, a1) {
                                        t1.sub_title = t1.title.substr(0, 8);
                                        t1.sub_MRName = t1.MRName.substr(0, 8);
                                    })
                                })
                            }
                            all_meeting.upd(res);
                        })
                    }
                })
            }

        },
        on_create_meeting: function () {
            $('#add_meet_modal').off().modal('show').on('shown.bs.modal', function () {
                temp_Id = [];

                var meetingitme = [{
                    Title: "",
                    MeetingDate: selDate,
                    StartTime: selStartTime,
                    EndTime: selEndTime,
                    BookPerson: $('#username')[0].innerHTML,
                    MeetingRoomId: "",
                    Presenter: "",
                    Remark: "",
                    NeedCheckIn: ""
                }];
                addMeeting.upd(meetingitme);

                $('#Access_text').val("");
                $('#Access').val("");

                $("#s2_multi_value")[0].innerHTML = "";
                multiselect = $("#s2_multi_value").select2({
                    data: employeedata,
                    tags: true
                });

                multiselect.val("").trigger('change');

                $('#s2_multi_service_value')[0].innerHTML = "";
                multiServiceSelect = $('#s2_multi_service_value').select2({
                    data: serversData,
                    tags: true
                });
                multiServiceSelect.val("").trigger('change');

                $("#temp_s2_multi_value")[0].innerHTML = "";
                multiTemp = $("#temp_s2_multi_value").select2({
                    data: outside,
                    tags: true
                });
                multiTemp.val("").trigger('change');

                $('#add-start-time').datetimepicker().on('changeDate', function (ev) {
                    var starttime = getFormatTime(ev.date);
                    if (starttime === '0:00:00') {
                        starttime = '00:00:00';
                    }
                    if ($('#input-add-end-time').val() <= starttime) {
                        $('#add-start-time').datetimepicker('setDate', getTimeFromDate(new Date(), addMeeting[0].StartTime));
                        $.toaster({ priority: "danger", title: "时间选择错误", message: "开始时间要小于结束时间！" });
                    }
                    addMeeting[0].StartTime = starttime;
                });

                $('#add-end-time').datetimepicker().on('changeDate', function (ev) {
                    var endtime = getFormatTime(ev.date);
                    if (endtime === '0:00:00') {
                        endtime = '00:00:00';
                    }
                    if (endtime <= $('#input-add-start-time').val()) {
                        $('#add-end-time').datetimepicker('setDate', getTimeFromDate(new Date(), addMeeting[0].EndTime));
                        //alert("结束时间要大于开始时间！");
                        $.toaster({ priority: "danger", title: "时间选择错误", message: "结束时间要大于开始时间！" });
                    }
                    addMeeting[0].EndTime = endtime;

                });

                $('input[name=NeedCheckIn]').on('change', function () {
                    if ($('input[name=NeedCheckIn]:checked')[0].value === '1') {
                        $('.CheckWay').removeClass('hidden');
                        $('.CheckWay').addClass('show');
                    } else {
                        $('.CheckWay').removeClass('show');
                        $('.CheckWay').addClass('hidden');
                    }
                });

            })

        },
        on_save_meeting: function () {
            $("#add_meet_form").data("bootstrapValidator").validate();
            var isbv = $("#add_meet_form").data("bootstrapValidator").isValid();
            if (!isbv) {
                return;
            }

            $('#loading').removeClass('hidden');
            $('#loading').addClass('show');
            addMeeting[0].MeetingRoomId = meetingResource.id;
            if (multiselect.val() === null || multiselect.val() === "") {
                addMeeting[0].Presenter = '';
            } else {
                addMeeting[0].Presenter = multiselect.val().join(',');
            }
            if (multiServiceSelect.val() === null || multiServiceSelect.val() === "") {
                addMeeting[0].ReceiveService = '';
            } else {
                addMeeting[0].ReceiveService = multiServiceSelect.val().join(',');
            }
            if (multiTemp.val() === null || multiTemp.val() === "") {
                addMeeting[0].Outside = '';
            } else {
                addMeeting[0].Outside = multiTemp.val().join(',');
            }

            addMeeting[0].Access = $('#Access').val();
            addMeeting[0].AccessName = $('#Access_text').val();
            addMeeting[0].MeetingDate = $('#input-add-meeting-date').val();
            addMeeting[0].StartTime = $('#input-add-start-time').val();
            addMeeting[0].EndTime = $('#input-add-end-time').val();
            if ($('input[name=NeedCheckIn]:checked')[0].value === '1') {
                addMeeting[0].NeedCheckIn = $('.CheckWay select').val();
            } else {
                addMeeting[0].NeedCheckIn = $('input[name=NeedCheckIn]:checked')[0].value;
            }

            $('#add_meet_modal').modal('hide').on('hidden.bs.modal', function () {
                ajax_post("/Handler/Meeting.ashx?Action=Insert", addMeeting[0], function (res) {
                    if (res.state != 1) {
                        alert(res.info + ':' + res.data);
                    }
                    else {

                        currentSelectMeeting = '';
                        $('#calendar').fullCalendar('refetchEvents');
                        $.toaster({ priority: "success", title: "提示：", message: "您已成功预定会议！" });
                        ajax_post(host + all_meeting_path, { start: curSearchStarttime, end: curSearchEndtime }, function (res) {
                            if (res.length != 0) {
                                res.forEach(function (t, n, a) {
                                    t.ItemList.forEach(function (t1, n1, a1) {
                                        t1.sub_title = t1.title.substr(0, 8);
                                        t1.sub_MRName = t1.MRName.substr(0, 8);
                                    })
                                })
                            }
                            all_meeting.upd(res);
                        })
                    }
                    $('#loading').removeClass('show');
                    $('#loading').addClass('hidden');
                })
            })
        },
        on_update_meeting: function () {

            $("#update_meet_form").data("bootstrapValidator").validate();
            var isbv = $("#update_meet_form").data("bootstrapValidator").isValid();
            if (!isbv) {
                alert("输入验证失败，请检查输入数据！");
                return;
            }
            $('#loading').removeClass('hidden');
            $('#loading').addClass('show');
            if (update_multiselect.val() === null || update_multiselect.val() === "") {
                updateMeeting[0].Presenter = "";
            } else {
                updateMeeting[0].Presenter = update_multiselect.val().join(',');
            }
            if (update_multiServiceSelect.val() === null || update_multiServiceSelect.val() === "") {
                updateMeeting[0].ReceiveService = '';
            } else {
                updateMeeting[0].ReceiveService = update_multiServiceSelect.val().join(',');
            }
            if (update_temp_multiselect.val() === null || update_temp_multiselect.val() === "") {
                updateMeeting[0].Outside = '';
            } else {
                updateMeeting[0].Outside = update_temp_multiselect.val().join(',');
            }

            updateMeeting[0].Access = $('#update_Access').val();
            updateMeeting[0].AccessName = $('#update_Access_text').val();
            updateMeeting[0].MeetingDate = $('#input-update-meeting-date').val();
            updateMeeting[0].StartTime = $('#input-update-start-time').val();
            updateMeeting[0].EndTime = $('#input-update-end-time').val();
            if ($('input[name=updateNeedCheckIn]:checked')[0].value === '1') {
                updateMeeting[0].NeedCheckIn = $('.updateCheckWay select').val();
            } else {
                updateMeeting[0].NeedCheckIn = $('input[name=updateNeedCheckIn]:checked')[0].value;
            }

            $('#update_meet_modal').modal('hide').on('hidden.bs.modal', function () {
                ajax_post("/Handler/Meeting.ashx?Action=Update", updateMeeting[0],
                    function (res) {
                        if (res.state != 1) {
                            alert(res.info + ':' + res.data);
                        }
                        else {
                            currentSelectMeeting = '';
                            $('#calendar').fullCalendar('refetchEvents');
                            $.toaster({ priority: "success", title: "提示：", message: "您的会议修改成功！" });
                        }
                        $('#loading').removeClass('show');
                        $('#loading').addClass('hidden');
                    })
            });
        },
        on_delete_meeting: function () {
            alert("delete meeting");
        },
        on_search_meeting_By_meeting: function (id) {

            currentSelectMeeting = 'currentSelectMeeting';
            currentSelectMeetingId = id;

            $('#calendar').fullCalendar('removeResource');
            $('#calendar').fullCalendar('refetchResources');
            $('#calendar').fullCalendar('refetchEvents');

        },
        searchhistorymeeting: function () {
            var startdate = $('#history-start-date input').val();
            var enddate = $('#history-end-date input').val();
            load_data(1, startdate, enddate);
        },
        showStep: function () {
            var date = getNowFormatDate();
            var curtime = getFormatTime(new Date());
            var h = curtime.split(':')[0];
            var m = curtime.split(':')[1];
            var starttime, endtime, endH;
            if ((parseInt(h) + 1) > 24) {
                endH = '00';
            } else {
                endH = (parseInt(h) + 1);
            }
            if (endH >= 1 && endH <= 9) {
                endH = "0" + endH;
            }
            if (parseInt(m) >= 0 && parseInt(m) < 30) {
                starttime = h + ":00:00";
                endtime = endH + ":00:00";
            }
            if (parseInt(m) >= 30 && parseInt(m) < 60) {
                starttime = h + ":30:00";
                endtime = endH + ":30:00";
            }
            $('#input-step-start-time').val(starttime);
            $('#input-step-end-time').val(endtime);
            $('#input-step-meeting-date').val(date);

            $('#rootwizard').bootstrapWizard('show', 0);
            $('input[name=stepmeetingtitle]').val("");
            $('input[name=step_Access_text]').val("");
            $('input[name=step_Access]').val("");
            $('input[name=stepRemark]').val("");
            $('#textSuccess')[0].innerHTML = "";
            $('input[name=stepbookperson]').val($('#username')[0].innerHTML);

            $('#step_person_s2_multi_value')[0].innerHTML = "";
            steppersonmultiServiceSelect = $('#step_person_s2_multi_value').select2({
                data: employeedata,
                tags: true,
                width: '100%'
            });

            $('#step_s2_multi_service_value')[0].innerHTML = "";
            stepservice = $('#step_s2_multi_service_value').select2({
                data: serversData,
                tags: true,
                width: '100%'
            });
            steppersonmultiServiceSelect.val("").trigger('change');

            $("#step_temp_s2_multi_value")[0].innerHTML = "";
            stepmultiTemp = $("#step_temp_s2_multi_value").select2({
                data: outside,
                tags: true,
                width: '100%'
            });
            stepmultiTemp.val("").trigger('change');

        },
        zoomDetail: function (e) {
            if (e.target.className === "fa fa-angle-double-right") {
                $('#calendar')[0].style.width = "95%";
                $('.right-detail').removeClass('show');
                $('.right-detail').addClass('hidden');
                $('.double-left').removeClass('hidden');
                $('.double-left').addClass('show');
            } else {
                $('#calendar')[0].style.width = "78%";
                $('.right-detail').removeClass('hidden');
                $('.right-detail').addClass('show');
                $('.double-left').removeClass('show');
                $('.double-left').addClass('hidden');
            }
        },
        zoomitemmeeting: function (e) {
            if (e.target.className === "fa fa-angle-double-down") {
                e.target.className = "fa fa-angle-double-up";
                e.currentTarget.parentNode.nextElementSibling.style.display = 'block';
            } else {
                e.target.className = "fa fa-angle-double-down";
                e.currentTarget.parentNode.nextElementSibling.style.display = 'none';
            }
        },
        onCancel: function (id) {
            var r = confirm("是否确定取消会议");
            if (r == true) {
                ajax_post("/Handler/Meeting.ashx?Action=Del", { Ids: id }, function (res) {
                    if (res.state != 1) {
                        alert("取消会议失败！");
                    }
                    else {
                        currentSelectMeeting = '';
                        $('#calendar').fullCalendar('refetchEvents');
                        $.toaster({ priority: "success", title: "提示：", message: "您已取消会议！" });
                        ajax_post(host + all_meeting_path, { start: curSearchStarttime, end: curSearchEndtime }, function (res) {
                            if (res.length != 0) {
                                res.forEach(function (t, n, a) {
                                    t.ItemList.forEach(function (t1, n1, a1) {
                                        t1.sub_title = t1.title.substr(0, 8);
                                        t1.sub_MRName = t1.MRName.substr(0, 8);
                                    })
                                })
                            }
                            all_meeting.upd(res);
                        })
                    }
                })
            }
        },
        updItemColor: function (e) {
            if (e.target.innerHTML != "取消") {
                for (var i = 0; i < $('.itemList').length; i++) {
                    $('.itemList')[i].style.backgroundColor = '#ffffff';
                    $('.itemList').removeClass('active');
                }
                e.currentTarget.style.backgroundColor = "#e5e5e5";
                $('#' + e.currentTarget.id).addClass('active');
                $('#loading').removeClass('hidden');
                $('#loading').addClass('show');
                currentSelectMeeting = 'rightSelectMeeting';

                $('#calendar').fullCalendar('removeResource');
                $('#calendar').fullCalendar('refetchResources');
                $('#calendar').fullCalendar('refetchEvents');
            }
        },
        showSearch: function () {
            var curtime = getFormatTime(new Date());
            var h = curtime.split(':')[0];
            var m = curtime.split(':')[1];
            var starttime, endtime, endH;
            if ((parseInt(h) + 1) > 24) {
                endH = '00';
            } else {
                endH = (parseInt(h) + 1);
            }
            if (endH >= 1 && endH <= 9) {
                endH = "0" + endH;
            }
            if (parseInt(m) >= 0 && parseInt(m) < 30) {
                starttime = h + ":00:00";
                endtime = endH + ":00:00";
            }
            if (parseInt(m) >= 30 && parseInt(m) < 60) {
                starttime = h + ":30:00";
                endtime = endH + ":30:00";
            }
            $('#input-start-time').val(starttime);
            $('#input-end-time').val(endtime);
        },
        showQRCode: function () {
            $('#phone_modal').off().modal('show').on('shown.bs.modal', function () {
                $('#qrcode_img')[0].innerHTML = location.origin + "/Resources/qrcode/wxrmeeting.png";
                $('#appAddress')[0].innerHTML = location.origin + "/Resources/qrcode/wxrmeeting.png";
            });
        },
        refreshMeeting: function () {
            currentSelectMeeting = 'refreshMeeting';

            $('#calendar').fullCalendar('removeResource');
            $('#calendar').fullCalendar('refetchResources');
            $('#calendar').fullCalendar('refetchEvents');
        },
        addOutside: function () {
            $('#tempPersonModal').off().modal('show').on('shown.bs.modal', function () { });
        },
        addTempperson: function () {
            $("#temp_form").data("bootstrapValidator").validate();
            var isbv = $("#temp_form").data("bootstrapValidator").isValid();
            if (!isbv) {
                alert("输入验证失败，请检查输入数据！");
                return;
            }
            var name = $('input[name=tempname]').val();
            var phone = $('input[name=temptelphone]').val();
            var email = $('input[name=tempemail]').val();
            ajax_post(add_tempPerson_path, { EmpName: name, Email: email, TelePhone: phone }, function (res) {
                if (res.state === '1') {

                    $('#tempPersonModal').modal('hide').on('hidden.bs.modal', function () { });
                    if ($('#add_meet_modal')[0].style.display === 'block') {
                        if (multiTemp.val() != null) {
                            for (var i = 0; i < multiTemp.val().length; i++) {
                                temp_Id.push(multiTemp.val()[i]);
                            }
                        }
                    } else if ($('#update_meet_modal')[0].style.display === 'block') {
                        if (update_temp_multiselect.val() != null) {
                            for (var i = 0; i < update_temp_multiselect.val().length; i++) {
                                temp_Id.push(update_temp_multiselect.val()[i]);
                            }
                        }
                    } else {
                        $("#step_temp_s2_multi_value")[0].innerHTML = "";
                        step_temp_multiselect = $("#step_temp_s2_multi_value").select2({
                            data: outside,
                            tags: true
                        });

                        step_temp_multiselect.val('').trigger('change');
                        if (step_temp_multiselect.val() != null) {
                            for (var i = 0; i < step_temp_multiselect.val().length; i++) {
                                temp_Id.push(step_temp_multiselect.val()[i]);
                            }
                        }
                    }
                    temp_Id.push(res.data.Id);
                    load_outside('');
                }
            })
        }

    }
});


function getEventDateTime(datetime) {
    var arr = datetime.split("T");
    return { date: arr[0], time: arr[1] }
}

function showMeetingInfoForModal(event) {

    var date = $.fullCalendar.formatDate(event.start, "YYYY-MM-DD");
    var starttime = $.fullCalendar.formatDate(event.start, "HH:mm:ss");
    var endtime = $.fullCalendar.formatDate(event.end, "HH:mm:ss");

    var Presenter = event.Presenter.split(",");
    var ReceiveService = event.ReceiveService.split(",");
    var TempPerson = event.Outside.split(",");

    var meetingitme = [{
        Id: event.id,
        Title: event.title.split("－")[0],
        MeetingDate: date,
        StartTime: starttime,
        EndTime: endtime,
        BookPerson: event.BookPerson,
        MeetingRoomId: event.resourceId,
        Presenter: event.Presenter.split(","),
        ReceiveService: event.ReceiveService.split(","),
        Remark: event.Remark,
        Access: event.Access
    }];


    showMeeting.upd(meetingitme);
    $('#showmeetinginfo_Access').val(event.Access);
    $('#showmeetinginfo_Access_text').val(event.AccessName);

    if (event.NeedCheckIn === '0') {
        $('input[name=showNeedCheckIn]')[0].checked = true;
        $('.showCheckWay').removeClass('show');
        $('.showCheckWay').addClass('hidden');
    } else {
        $('input[name=showNeedCheckIn]')[1].checked = true;
        $('.showCheckWay').removeClass('hidden');
        $('.showCheckWay').addClass('show');
        $('.showCheckWay select').val(event.NeedCheckIn);
    }


    $('#show_meeting_info_modal').off().modal('show').on('shown.bs.modal', function () {

        load_group_servers(curSelEvent.MeetingRoomOrgCode, ReceiveService);

        $("#showmeetinginfo_s2_multi_value")[0].innerHTML = '';
        update_multiselect = $("#showmeetinginfo_s2_multi_value").select2({
            data: employeedata,
            tags: true
        });

        update_multiselect.val(Presenter).trigger('change');

        $("#show_temp_s2_multi_value")[0].innerHTML = "";
        show_temp_multiselect = $("#show_temp_s2_multi_value").select2({
            data: outside,
            tags: true
        })

        show_temp_multiselect.val(TempPerson).trigger('change');

    })
}


function UpdateMeetingInfoUI(ReceiveService) {

    $("#showmeetinginfo_s2_multi_service_value")[0].innerHTML = "";

    update_multiServiceSelect = $("#showmeetinginfo_s2_multi_service_value").select2({
        data: serversData,
        tags: true
    });

    update_multiServiceSelect.val(ReceiveService).trigger('change');
}

function updateMeetingdateForModal(event) {
    load_group_employee(event.id);

    var date = $.fullCalendar.formatDate(event.start, "YYYY-MM-DD");
    var starttime = $.fullCalendar.formatDate(event.start, "HH:mm:ss");
    var endtime = $.fullCalendar.formatDate(event.end, "HH:mm:ss");

    var Presenter = event.Presenter.split(",");
    var ReceiveService = event.ReceiveService.split(",");
    var TempPerson = event.Outside.split(",");

    var meetingitme = [{
        Id: event.id,
        Title: event.title.split("－")[0],
        MeetingDate: date,
        StartTime: starttime,
        EndTime: endtime,
        BookPerson: event.BookPerson,
        MeetingRoomId: event.resourceId,
        Presenter: event.Presenter.split(","),
        ReceiveService: event.ReceiveService.split(","),
        Remark: event.Remark,
        Access: event.Access
    }];

    updateMeeting.upd(meetingitme);

    $('#update_Access').val(event.Access);
    $('#update_Access_text').val(event.AccessName);
    if (event.NeedCheckIn === '0') {
        $('input[name=updateNeedCheckIn]')[0].checked = true;
        $('.updateCheckWay').removeClass('show');
        $('.updateCheckWay').addClass('hidden');
    } else {
        $('input[name=updateNeedCheckIn]')[1].checked = true;
        $('.updateCheckWay').removeClass('hidden');
        $('.updateCheckWay').addClass('show');
        $('.updateCheckWay select').val(event.NeedCheckIn);
    }

    $('#update-start-time').datetimepicker().on('changeDate', function (ev) {
        var starttime = getFormatTime(ev.date);
        if (starttime === '0:00:00') {
            starttime = '00:00:00';
        }
        if ($('#input-update-end-time').val() <= starttime) {
            $('#update-start-time').datetimepicker('setDate', getTimeFromDate(new Date(), updateMeeting[0].StartTime));
            $.toaster({ priority: "danger", title: "时间选择错误", message: "开始时间要小于结束时间！" });
        }
        updateMeeting[0].StartTime = starttime;

    });

    $('#update-end-time').datetimepicker().on('changeDate', function (ev) {
        var endtime = getFormatTime(ev.date);
        if (endtime === '0:00:00') {
            endtime = '00:00:00';
        }
        if (endtime <= $('#input-update-start-time').val()) {
            $('#update-end-time').datetimepicker('setDate', getTimeFromDate(new Date(), updateMeeting[0].EndTime));
            //alert("结束时间要大于开始时间！");
            $.toaster({ priority: "danger", title: "时间选择错误", message: "结束时间要大于开始时间！" });
        }
        updateMeeting[0].EndTime = endtime;

    });

    $('#update_meet_modal').off().modal('show').on('shown.bs.modal', function () {
        $("#update_s2_multi_value")[0].innerHTML = "";

        update_multiselect = $("#update_s2_multi_value").select2({
            data: employeedata,
            tags: true
        });

        update_multiselect.val(Presenter).trigger('change');

        $("#update_temp_s2_multi_value")[0].innerHTML = '';
        update_temp_multiselect = $("#update_temp_s2_multi_value").select2({
            data: outside,
            tags: true
        })

        update_temp_multiselect.val(TempPerson).trigger('change');

        $("#update_s2_multi_service_value")[0].innerHTML = '';
        update_multiServiceSelect = $("#update_s2_multi_service_value").select2({
            data: serversData,
            tags: true
        });

        update_multiServiceSelect.val(ReceiveService).trigger('change');

        $('input[name=updateNeedCheckIn]').on('change', function () {
            if ($('input[name=updateNeedCheckIn]:checked')[0].value === '1') {
                $('.updateCheckWay').removeClass('hidden');
                $('.updateCheckWay').addClass('show');
            } else {
                $('.updateCheckWay').removeClass('show');
                $('.updateCheckWay').addClass('hidden');
            }
        });
    })
}


$('#add_meet_form').bootstrapValidator({
    message: 'This value is not valid',
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        meetingtitle: {
            message: '会议标题输入错误！',
            validators: {
                notEmpty: {
                    message: '会议标题不能为空'
                }
            }
        },
        bookperson: {
            message: '预订人填写有误！',
            validators: {
                notEmpty: {
                    message: '预订人不能为空'
                }
            }
        },
    }
});


$('#update_meet_form').bootstrapValidator({
    message: 'This value is not valid',
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        meetingtitle: {
            message: '会议标题输入错误！',
            validators: {
                notEmpty: {
                    message: '会议标题不能为空'
                }
            }
        },
        bookperson: {
            message: '预订人填写有误！',
            validators: {
                notEmpty: {
                    message: '预订人不能为空'
                }
            }
        },
    }
});

$('#step1_form').bootstrapValidator({
    message: 'This value is not valid',
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        stepmeetingtitle: {
            message: '会议标题输入错误！',
            validators: {
                notEmpty: {
                    message: '会议标题不能为空'
                }
            }
        },
        stepbookperson: {
            message: '预订人填写有误！',
            validators: {
                notEmpty: {
                    message: '预订人不能为空'
                }
            }
        },
    }
});

$('#step2_form').bootstrapValidator({
    message: 'This value is not valid',
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        stepmeetingtitle: {
            message: '会议标题输入错误！',
            validators: {
                notEmpty: {
                    message: '会议标题不能为空'
                }
            }
        },
        stepbookperson: {
            message: '预订人填写有误！',
            validators: {
                notEmpty: {
                    message: '预订人不能为空'
                }
            }
        },
    }
});

$('#temp_form').bootstrapValidator({
    message: 'This value is not valid',
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        tempname: {
            message: '员工姓名填写有误！',
            validators: {
                notEmpty: {
                    message: '员工姓名不能为空'
                }
            }
        },
        temptelphone: {
            message: '手机号码填写有误！',
            validators: {
                notEmpty: {
                    message: '手机号码不能为空'
                },
                stringLength: {
                    min: 11,
                    max: 11,
                    message: '请输入11位手机号码'
                },
                regexp: {
                    regexp: /^1[3|5|8]{1}[0-9]{9}$/,
                    message: '请输入正确的手机号码'
                }
            }
        },
        tempemail: {
            message: '邮箱填写有误！',
            validators: {
                notEmpty: {
                    message: '邮箱不能为空'
                },
                emailAddress: {
                    message: '请输入正确的邮件地址如：alex@somaicloud.com'
                }
            }
        }
    }
});

$('document').ready(function () {
    $('.fc-widget-header')[0].style.width = "150px";

    $('#historybook').on('click', function () {
        load_data(1, beginDate, endDate);
    });

    var url = '../Handler/FileTransferHandler.ashx?Action=AttachmentUpload';
    $('#fileupload').fileupload({
        url: url,
        dataType: 'json',
        done: function (e, data) {
            $('#Access_text').val(data.result[0].name);
            $('#Access').val(data.result[0].sourcename);
        }
    });

    $('#update_fileupload').fileupload({
        url: url,
        dataType: 'json',
        done: function (e, data) {
            $('#update_Access_text').val(data.result[0].name);
            $('#update_Access').val(data.result[0].sourcename);
        }
    });

    $('#step_fileupload').fileupload({
        url: url,
        dataType: 'json',
        done: function (e, data) {
            $('#step_Access_text').val(data.result[0].name);
            $('#step_Access').val(data.result[0].sourcename);
        }
    });

    $('#rootwizard').bootstrapWizard({
        tabClass: 'bwizard-steps',
        onTabShow: function (tab, navigation, index) {
            var $total = navigation.find('li').length;
            var $current = index + 1;
            var $percent = ($current / $total) * 100;
            $('#rootwizard').find('.bar').css({ width: $percent + '%' });

            $('input[name=stepNeedCheckIn]').on('change', function () {
                if ($('input[name=stepNeedCheckIn]:checked')[0].value === '1') {
                    $('.stepCheckWay').removeClass('hidden');
                    $('.stepCheckWay').addClass('show');
                } else {
                    $('.stepCheckWay').removeClass('show');
                    $('.stepCheckWay').addClass('hidden');
                }
            });
        },
        onTabClick: function (tab, navigation, index) {
            return false;
        },
        onNext: function (tab, navigation, index) {
            switch (index) {
                case 1: $("#step1_form").data("bootstrapValidator").validate();
                    var isbv = $("#step1_form").data("bootstrapValidator").isValid();
                    if (!isbv) {
                        return false;
                    }
                    var meetingdate = $('input[name=stepMeetingDate]').val();
                    var starttime = $('input[name=stepStartTime]').val();
                    var endtime = $('input[name=stepEndTime]').val();
                    load_step_meetingroom(meetingdate, starttime, endtime);


                    //stepmultiServiceSelect.val("").trigger('change');
                    break;
                case 3: var title = $('input[name=stepmeetingtitle]').val();
                    $('#loading').removeClass('hidden');
                    $('#loading').addClass('show');
                    var meetingdate = $('input[name=stepMeetingDate]').val();
                    var starttime = $('input[name=stepStartTime]').val();
                    var endtime = $('input[name=stepEndTime]').val();
                    var bookperson = $('input[name=stepbookperson]').val();
                    var selroom = $('#step_selectmettingroom_s2_multi_value').val();
                    var selroomname = $('option[value=' + selroom + ']')[0].innerHTML;
                    var selperson = $('#step_person_s2_multi_value').val();
                    var selservice = $('#step_s2_multi_service_value').val();
                    var accesstext = $('#step_Access_text').val();
                    if (accesstext === null || accesstext === "") {
                        accesstext = '无';
                    }
                    var remark = $('textarea[name=stepRemark]').val();
                    if (remark === null || remark === "") {
                        remark = '无';
                    }
                    var personname = '';
                    if (selperson === null || selperson === "") {
                        personname = '无';
                    } else {
                        for (var i = 0; i < selperson.length; i++) {
                            personname = personname + $('option[value=' + selperson[i] + ']')[0].innerHTML + '、';
                        }
                        personname = personname.substr(0, personname.length - 1);
                    }
                    var servicename = '';
                    if (selservice === null || selservice === "") {
                        servicename = '无';
                    } else {
                        for (var i = 0; i < selservice.length; i++) {
                            servicename = servicename + $('option[value=' + selservice[i] + ']')[0].innerHTML + '、';
                        }
                        servicename = servicename.substr(0, servicename.length - 1);
                    }
                    addMeeting[0].Title = title;
                    addMeeting[0].MeetingDate = meetingdate;
                    addMeeting[0].StartTime = starttime;
                    addMeeting[0].EndTime = endtime;
                    addMeeting[0].BookPerson = bookperson;
                    if (stepmultiServiceSelect.val() != null && stepmultiServiceSelect.val() != "") {
                        addMeeting[0].MeetingRoomId = stepmultiServiceSelect.val().join(',');
                    }
                    if (steppersonmultiServiceSelect.val() != null && steppersonmultiServiceSelect.val() != "") {
                        addMeeting[0].Presenter = steppersonmultiServiceSelect.val().join(',');
                    }
                    if (stepservice.val() != null && stepservice.val() != "") {
                        addMeeting[0].ReceiveService = stepservice.val().join(',');
                    }
                    if (stepmultiTemp.val() === null || stepmultiTemp.val() === "") {
                        addMeeting[0].Outside = '';
                    } else {
                        addMeeting[0].Outside = stepmultiTemp.val().join(',');
                    }
                    addMeeting[0].AccessName = $('#step_Access_text').val();
                    addMeeting[0].Access = $('#step_Access').val();
                    addMeeting[0].Remark = $('textarea[name=stepRemark]').val();
                    if ($('input[name=stepNeedCheckIn]:checked')[0].value === '1') {
                        addMeeting[0].NeedCheckIn = $('.stepCheckWay select').val();
                    } else {
                        addMeeting[0].NeedCheckIn = $('input[name=stepNeedCheckIn]:checked')[0].value;
                    }



                    ajax_post("/Handler/Meeting.ashx?Action=Insert", addMeeting[0], function (res) {
                        $('#loading').removeClass('show');
                        $('#loading').addClass('hidden');
                        if (res.state != 1) {
                            //alert("新建会议失败！");
                            $('#textSuccess')[0].innerHTML = res.info;
                        }
                        else {
                            currentSelectMeeting = '';
                            $('#calendar').fullCalendar('refetchEvents');
                            //$.toaster({ priority: "success", title: "提示：", message: "您已成功预定会议！" });
                            $('#textSuccess')[0].innerHTML = '恭喜您，您已成功预定' + selroomname + ',信息如下:<br>会议名称:' + title + ';<br>会议时间:' + meetingdate + ';<br>开始时间:' + starttime + '，结束时间：' + endtime + ';<br>'
                    + '参会人员:' + personname + ';<br>您选择的服务:' + servicename + ';<br>您选择的附件:' + accesstext + ';<br>您的备注:' + remark + ';<br>以上信息我们会以邮件形式发给参会人员。';
                        }
                    })


            }

        }
    }),

    $('#rootwizard .finish').click(function () {
        $('#addMettingStep').modal('hide').on('hidden.bs.modal', function () {

        })
    });

})
