calendar/app/assets/javascripts/calendar.js

1163 lines
42 KiB
JavaScript

window.auto_close_popup = false;
if(window.calendar_variable == undefined){
window.calendar_variable = {};
window.calendar_variable.is_chinese = ( I18n && I18n.locale.indexOf('zh') != -1 );
window.calendar_variable.date_type = 0;
}else{
if(window.calendar_variable.date_type == 1){
window.calendar_variable.is_chinese = false;
}else{
window.calendar_variable.is_chinese = ( I18n && I18n.locale.indexOf('zh') != -1 );
}
}
if(!(window.calendar_variable.dayNames)){
if(window.calendar_variable.is_chinese){
window.calendar_variable.dayNames = ['週日', '週一', '週二', '週三','週四', '週五', '週六'];
window.calendar_variable.dayNamesShort = ['日', '一', '二', '三','四', '五', '六'];
}else{
window.calendar_variable.dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday','Thursday', 'Friday', 'Saturday'];
window.calendar_variable.dayNamesShort = ['Sun', 'Mon', 'Tue', 'Wed','Thu', 'Fri', 'Sat'];
}
}
if(Array.prototype.rotate == undefined){
Array.prototype.rotate = function(n) {
n = n % this.length;
while (this.length && n < 0) n += this.length;
this.push.apply(this, this.splice(0, n));
return this;
}
}
if(window.calendar_variable.is_chinese){
window.calendar_variable.months = [];
for(var i=0;i<12;i++){
window.calendar_variable.months.push((i+1)+"月");
}
}else{
window.calendar_variable.months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
}
if(window.calendar_variable.date_type == 2){
window.calendar_variable.month_year_format = calendar_variable.is_chinese ? 'yy/MM' : 'MM/yy';
window.calendar_variable.date_format = calendar_variable.is_chinese ? 'yy/MM/dd' : 'dd/MM/yy';
window.calendar_variable.date_format_with_short_month = calendar_variable.is_chinese ? 'yy/MM/dd' : 'dd/MM/yy';
window.calendar_variable.date_format_with_week = calendar_variable.is_chinese ? 'yy/MM/dd (W)' : 'W, MM/dd/yy';
window.calendar_variable.short_date = (calendar_variable.is_chinese ? "MM/dd (W)" : "W, dd/MM");
if(window.calendar_variable.time_type == 1){
window.calendar_variable.datetime_format = calendar_variable.is_chinese ? 'yy/MM/dd H:m' : 'dd/MM/yy H:m';
window.calendar_variable.short_date_time = (calendar_variable.is_chinese ? "MM/dd (W) H:m" : "W, dd/MM H:m");
}else{
window.calendar_variable.datetime_format = calendar_variable.is_chinese ? 'yy/MM/dd b h:m' : 'dd/MM/yy h:m b';
window.calendar_variable.short_date_time = (calendar_variable.is_chinese ? "MM/dd (W) b h:m" : "W, dd/MM h:m b");
}
}else{
window.calendar_variable.month_year_format = calendar_variable.is_chinese ? 'y MMM' : 'MMM y';
window.calendar_variable.date_format = calendar_variable.is_chinese ? 'y MMM d' : 'd MMM, y';
window.calendar_variable.date_format_with_short_month = calendar_variable.is_chinese ? 'y M d' : 'd M, y';
window.calendar_variable.date_format_with_week = calendar_variable.is_chinese ? 'y MMM d (W)' : 'W, MMM d, y';
window.calendar_variable.short_date = (calendar_variable.is_chinese ? "MMM d (W)" : "W, d MMM");
if(window.calendar_variable.time_type == 1){
window.calendar_variable.datetime_format = calendar_variable.is_chinese ? 'y MMM d H:m' : 'd MMM, y H:m';
window.calendar_variable.short_date_time = (calendar_variable.is_chinese ? "MMM d (W) H:m" : "W, d MMM H:m");
}else{
window.calendar_variable.datetime_format = calendar_variable.is_chinese ? 'y MMM d b h:m' : 'd MMM, y h:m b';
window.calendar_variable.short_date_time = (calendar_variable.is_chinese ? "MMM d (W) b h:m" : "W, d MMM h:m b");
}
}
window.calendar_variable.date_format_numeric = 'yy/MM/dd';
window.calendar_variable.short_date_numeric = (calendar_variable.is_chinese ? "MM/dd (w)" : "w MM/dd");
if(window.calendar_variable.time_type == 1){
window.calendar_variable.time_format = "H:m";
}else{
window.calendar_variable.time_format = (calendar_variable.is_chinese ? "b h:m" : "h:m b");
}
window.calendar_variable.std_date_format = 'y-MM-d';
window.calendar_variable.short_day = (calendar_variable.is_chinese ? "d (W)" : "W d");
$.fn.fullCalendar = function(args){
var self = this[0]
if(!self.calendar_args)
self.calendar_args = args;
else
args = Object.assign(self.calendar_args, args);
var calendar = new FullCalendar.Calendar(self,args);
calendar.render();
$(window).on("load",function(){
calendar.render();
})
this.calendar = calendar;
self.calendar = calendar;
$.fullCalendar = calendar;
return calendar;
};
function correct_date(date){
var new_date = new Date();
new_date.setTime(date.getTime() + date.getTimezoneOffset() * 60 * 1000);
return new_date;
}
FullCalendar.Calendar.prototype.get_all_events = function(){
this.currentData.all_events = [];
var all_events = this.currentData.all_events;
if(this.currentData.eventStore && this.currentData.eventStore.instances){
var instances = this.currentData.eventStore.instances;
Object.keys(instances).forEach(function(k){
var instance = instances[k];
var range = Object.assign({},instance.range);
range.start = correct_date(range.start);
range.end = correct_date(range.end);
all_events.push(range);
})
}
return this.currentData.all_events;
}
FullCalendar.Calendar.prototype.isAnOverlapEvent = function(eventStartDay, eventEndDay){
eventStartDay = eventStartDay || eventEndDay;
eventEndDay = eventEndDay || eventStartDay;
if((typeof(eventStartDay)).toLowerCase() == "string")
eventStartDay = new Date(eventStartDay);
if((typeof(eventEndDay)).toLowerCase() == "string")
eventEndDay = new Date(eventEndDay);
var events = this.get_all_events();
for (var i = 0; i < events.length; i++) {
var eventA = events[i];
// start-time in between any of the events
if (eventStartDay >= eventA.start && eventStartDay <= eventA.end) {
return true;
}
//end-time in between any of the events
if (eventEndDay >= eventA.start && eventEndDay <= eventA.end) {
return true;
}
//any of the events in between/on the start-time and end-time
if (eventStartDay <= eventA.start && eventEndDay >= eventA.end) {
return true;
}
}
return false;
}
window.getDateString = function(date, format, is_chinese) {
var months = calendar_variable.months;
var week_days = calendar_variable.dayNames;
var getPaddedComp = function(comp) {
return ((parseInt(comp) < 10) ? ('0' + comp) : comp)
},
formattedDate = format,
y = date.getFullYear(),
m = date.getMonth(),
d = date.getDate(),
H = date.getHours(),
M = date.getMinutes(),
s = date.getSeconds(),
S = date.getMilliseconds(),
month_name = months[m],
am_trans = (calendar_variable.is_chinese ? '上午' : 'AM'),
pm_trans = (calendar_variable.is_chinese ? '下午' : 'PM'),
o = {
"yy+": y, //raw year
"y+": y + (calendar_variable.is_chinese ? "年" : ""), // year
"MMM+": month_name, //month
"MM+": getPaddedComp(m + 1), //raw month
"M+": month_name.substring(0,3), //month
"dd+": getPaddedComp(d), //raw day
"d+": (calendar_variable.is_chinese ? (d + "日") : getPaddedComp(d)), //day
"W+": week_days[date.getDay()], //weekday
"w+": (calendar_variable.is_chinese ? week_days[date.getDay()].substr(-1, 1) : week_days[date.getDay()].substr(0, 3)), //weekday
"h+": getPaddedComp((H > 12) ? H % 12 : H), //hour
"H+": getPaddedComp(H), //hour
"m+": getPaddedComp(M), //minute
"s+": getPaddedComp(s), //second
"S+": getPaddedComp(S), //millisecond,
"b+": (H >= 12) ? pm_trans : am_trans
};
for (var k in o) {
if (new RegExp("(" + k + ")").test(format)) {
formattedDate = formattedDate.replace(RegExp.$1, o[k]);
}
}
return formattedDate;
};
var Calendar = function(dom){
var c = this;
this.create_event_btn = $("#create_event_btn");
this.event_create_space = $("#event_create_space");
this.mousePosition = {};
this.title = $("#current_title");
this.calendar_dom = $(dom);
this.nextBtn = $("#next_month_btn");
this.prevBtn = $("#prev_month_btn");
this.todayBtn = $("#today_btn");
this.modeBtns = $(".calendar_mode button");
this.refreshBtn = $("#refresh_btn");
this.dialog = new EventDialog(c);
this.loading = $('#calendar-loading');
this.agenda_space = $("#calendar_agenda");
this.currentView = "dayGridMonth";
this.navigation = $("#navigation");
this.rangeSelection = $("#range_selection");
var agendaView = new AgendaView(c);
var loadeventsonviewchange = false;
this.success_event = null;
this.initialize = function(){
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var change_event = function(_event, delta) {
_event.end = (_event.end ? _event.end : _event.start);
var s = $.fullCalendar.parseDate(c.calendar_dom.find(".fc-view table tbody td:first").data("date"));
var e = $.fullCalendar.parseDate(c.calendar_dom.find(".fc-view table tbody td:first").data("date"));
$.ajax({
url: "/admin/calendars/"+_event.id,
// data: {event:{id:_event.id,start:_event.start,end: _event.end,_s:Math.round(+s / 1000), _e:Math.round(+e / 1000)}},
data: {event:{id:_event.id,start:_event.start,end: _event.end}},
type: 'put' ,
datatype: 'JSON',
error: function(jqXHR, textStatus, errorThrown) {},
success: function(data) {
console.log('event was success updated');
}
});
}
var success_event = function(data,allDay,type,addbtn){
c.dialog.dismiss();
$('.bootstrap-datetimepicker-widget').remove();
c.event_create_space.html(data);
var create_space_height = c.event_create_space.height(),
create_space_width = c.event_create_space.width();
if((create_space_height + c.mousePosition["y"]) >= $(window).height()){
var top_pos = c.mousePosition["y"] - create_space_height
if (top_pos < 0){
c.event_create_space.find('.modal-body').css('height',create_space_height+top_pos)
c.event_create_space.css("top",0 + "px");
}else{
c.event_create_space.css("top",top_pos + "px");
}
}else if(c.mousePosition["y"]+c.event_create_space.height()<$(window).height()){
c.event_create_space.css("top",c.mousePosition["y"] + "px");
}
if((create_space_width + c.mousePosition["x"]) >= $(window).width()){
if (c.mousePosition["x"] - create_space_width < 0){
c.event_create_space.css("left",'0px')
}else{
c.event_create_space.css("left",(c.mousePosition["x"] - create_space_width) + "px");
}
}else{
c.event_create_space.css("left",c.mousePosition["x"] + "px");
}
if(addbtn){
c.event_create_space.css({"right":"8px","bottom":"50px","left":"auto","top":"auto"});
}else{
c.event_create_space.css({"right":"","bottom":""});
}
c.event_create_space.show();
var pickers = $('.default_picker input');
var checked = ($("#all_day_check").is(":checked") ? true : false);
var checked_function = function(c){
var d = new Date()
if(c){
for(i=0;i<pickers.length;i++){
pickers.eq(i).ui_datetimepicker("destroy");
pickers.eq(i).attr('placeholder','yyyy/MM/dd')
var value = pickers.eq(i).val()
if (value != ''){
pickers.eq(i).val(value.split(" ")[0])
}
pickers.eq(i).ui_datepicker({dateFormat: 'yy/mm/dd',show_view: ''})
}
}else{
for(i=0;i<pickers.length;i++){
pickers.eq(i).ui_datepicker("destroy");
pickers.eq(i).attr('placeholder','yyyy/MM/dd HH:mm')
var value = pickers.eq(i).val()
if (value != ''){
pickers.eq(i).val(value + " " + d.getHours() + ":" + d.getMinutes())
}
pickers.eq(i).ui_datetimepicker({
dateFormat: 'yy/mm/dd',
controlType: 'select',
timeInput: true,
oneLine: true,
timeFormat: 'HH:mm'
})
}
}
}
var repeat_function = function(){
if(c.event_create_space.find("#event_period").val() == c.event_create_space.find("#event_period option:eq(0)").val()){
c.event_create_space.find("#event_frequency").attr("disabled","disabled");
}else{
c.event_create_space.find("#event_frequency").removeAttr("disabled");
}
}
$("a.btn-close").one("click",function(){
c.event_create_space.html("").hide();
$('.bootstrap-datetimepicker-widget').remove();
return false;
});
$("#all_day_check").change(function(){
if($(this).is(":checked")){
checked = true;
}else{
checked = false;
}
checked_function(checked);
});
$("#recurring_checkbox").click(function(){
if($(this).is(":checked"))
$("#recurring_panel").show();
else
$("#recurring_panel").hide();
})
$('form[data-remote]').bind("ajax:success",function(evt, data, status){
c.event_create_space.html("").hide();
if(type == "new")
c.renderEvent(data);
if(type == "edit")
c.calendar_dom.fullCalendar("refetchEvents");
});
c.event_create_space.find("#event_period").change(function(){
//repeat_function();
})
//repeat_function();
}
c.success_event = success_event;
var dview = (c.currentView == "agenda" ? "dayGridMonth" : c.currentView);
c.calendar_dom.css("overflow","visible");
c.calendar_dom.fullCalendar({
themeSystem: 'bootstrap',
editable: false,
selectable: true,
width: "100%",
height: $(window).height() - 315,
events: function(args, success_callback, fail_callback) {
var start = args.start;
var end = args.end;
$.ajax({
url: window.location.href,
dataType: 'json',
type: 'GET',
data: {
start: Math.round(start.getTime() / 1000),
end: Math.round(end.getTime() / 1000),
_: Date.now()
},
success: function(json) {
// json = json.map(function(obj){
// obj.start = new Date(obj.start).toJSON();
// obj.end = new Date(obj.end).toJSON();
// return obj;
// })
success_callback(json);
}
});
},
// events: 'https://fullcalendar.io/demo-events.json',
headerToolbar: false,
fixedWeekCount: false,
initialView: dview,
loading: function(bool) {
if (bool) c.loading.show();
else c.loading.hide();
if(this.currentData)
$('#current_title').html(this.currentData.viewTitle);
},
windowResize : function(view){
c.calendar_dom.calendar.refetchEvents();
},
eventTimeFormat: { hour12: (window.calendar_variable.time_type != 1), hour: '2-digit', minute: '2-digit', omitZeroMinute: true, meridiem: 'narrow' },
eventClick: function(eventClickInfo) {
var calEvent = {"event": eventClickInfo.event},
originalEvent = eventClickInfo.jsEvent,
view = eventClickInfo.view,
el = $(eventClickInfo.el);
if(el.hasClass("reserve_btn")){
window.calEvent = calEvent;
var start_time = calEvent.event.start;
var date_str = window.getDateString(start_time,std_date_format);
c.dialog.hide();
var allow_times = calEvent.event._def.extendedProps.allow_times;
window.pick_hire_date(date_str,allow_times);
}else{
c.event_create_space.html("").hide();
c.dialog.dismiss();
c.dialog.inflate(calEvent);
c.dialog.show({"x": originalEvent.clientX,"y": originalEvent.clientY});
}
},
dateClick: function(ev) {
var calendar = this;
var calendar_dom = $(this.el);
if(c.calendar_dom.hasClass("active_picker")){
var date = ev.date,
date_str = getDateString(date,date_time_str_format),
day_element = ev.dayEl,
jsEvent = ev.jsEvent;
var time_str = date_str.split(" ")[1];
var date_str = date_str.split(" ")[0];
calendar_dom.trigger("init_time",[time_str]);
calendar_dom.trigger("select_time",[date_str]);
}
},
select : function(selectionInfo){
var jsEvent = selectionInfo.jsEvent,
view = selectionInfo.view;
var start = selectionInfo.start,
end = selectionInfo.end,
allDay = selectionInfo.allDay,
startString = start.getFullYear() + "/"+ (start.getMonth() + 1 > 9 ? start.getMonth() + 1 : "0" + (start.getMonth() + 1)) + "/" + (start.getDate() > 9 ? start.getDate() : "0" + start.getDate()),
endString = end.getFullYear() + "/" + (end.getMonth() + 1 > 9 ? end.getMonth() + 1 : "0" + (end.getMonth() + 1)) + "/" + (end.getDate() > 9 ? end.getDate() : "0" + end.getDate());
if(!allDay){
startString += " " + (start.getHours() > 9 ? start.getHours() : "0" + start.getHours()) + ":" + (start.getMinutes() > 9 ? start.getMinutes() : "0" + start.getMinutes());
endString += " " + (end.getHours() > 9 ? end.getHours() : "0" + end.getHours()) + ":" + (end.getMinutes() > 9 ? end.getMinutes() : "0" + end.getMinutes());
}else{
startString += " " + start.getHours() + ":" + start.getMinutes();
endString += " " + end.getMinutes() + ":" + end.getMinutes();
}
$.ajax({
type : "get",
url : c.create_event_btn.attr("href"),
data : {"startDate":startString,"endDate":endString,"allDay":allDay},
success : function(data){
success_event(data,allDay,"new");
}
})
},
views: {
timeGridDay: {
titleFormat: function(date_info){
var date = date_info.date.marker;
return getDateString(date, calendar_variable.date_format_with_week);
},
dayHeaderFormat: function(date_info){
return window.calendar_variable.dayNames[date_info.date.marker.getDay()];
}
},
timeGridWeek: {
titleFormat: function(date_info){
var start = date_info.start.marker,
end = date_info.end.marker;
return getDateString(start, calendar_variable.date_format) + ' ~ ' + getDateString(end, calendar_variable.date_format);
},
dayHeaderFormat: function(date_info){
return getDateString(date_info.date.marker, calendar_variable.short_date_numeric);
}
},
dayGridMonth: {
dayMaxEvents: false,
titleFormat: function(date_info){
var date = date_info.date.marker;
return getDateString(date, calendar_variable.month_year_format);
},
dayHeaderFormat: function(date_info){
return window.calendar_variable.dayNamesShort[date_info.date.marker.getDay()];
}
}
},
firstDay: (window.calendar_variable.sunday_first == true ? 0 : 1)
});
c.create_event_btn.click(function(){
$.ajax({
type : "get",
url : $(this).attr("href"),
success : function(data){
success_event(data,false,"new",true);
}
})
return false;
});
c.nextBtn.click(function(){
c.dialog.dismiss();
c.calendar_dom.calendar.next();
c.title.text(c.calendar_dom.calendar.currentData.viewTitle);
});
c.prevBtn.click(function(){
c.dialog.dismiss();
c.calendar_dom.calendar.prev();
c.title.text(c.calendar_dom.calendar.currentData.viewTitle);
});
c.todayBtn.click(function(){
c.dialog.dismiss();
c.calendar_dom.calendar.today();
c.title.text(c.calendar_dom.calendar.currentData.viewTitle);
});
c.modeBtns.click(function(){
c.dialog.dismiss();
toggleViews($(this).data("mode"));
});
c.refreshBtn.click(function(){
c.dialog.dismiss();
if(c.currentView == "agenda")
agendaView.refresh();
else
c.calendar_dom.calendar.refetchEvents();
});
c.calendar_dom.mouseup(function(e){
c.mousePosition = {"x" : e.pageX, "y" : e.pageY};
})
var toggleViews = function(view){
c.modeBtns.removeClass("active");
c.modeBtns.each(function(){
if ($(this).data("mode") == view)
$(this).addClass("active");
});
if(view != "agenda"){
if(c.currentView == "agenda"){
// $("#sec1").addClass("span3").removeClass("span7");
$("#sec2").show();
// $("#sec3").addClass("span4").removeClass("span5");
agendaView.hide();
}
c.calendar_dom.calendar.changeView(view);
}else{
// $("#sec1").addClass("span7").removeClass("span3");
$("#sec2").hide();
// $("#sec3").addClass("span5").removeClass("span4");
agendaView.inflate();
}
c.currentView = view;
if(loadeventsonviewchange){
c.calendar_dom.calendar.refetchEvents();
loadeventsonviewchange = false;
}
c.title.text(c.calendar_dom.calendar.currentData.viewTitle);
// c.calendar_dom.calendar.rerenderEvents(); //Rerender to fix layout
};
if(c.currentView == "agenda"){toggleViews("agenda");loadeventsonviewchange = true;}
};
this.updateEvent = function(eventStick){
c.calendar_dom.fullCalendar("updateEvent",eventStick);
}
this.deleteEvent = function(delete_url,_id){
$.ajax({
type : "delete",
url : delete_url,
success : function(){
c.calendar_dom.fullCalendar("removeEvents",[_id]);
c.dialog.dismiss();
}
})
}
this.editEvent = function(edit_url,allDay){
$.ajax({
type : "get",
url : edit_url,
success : function(data){
c.success_event(data,allDay,"edit",true);
c.dialog.dismiss();
}
})
}
this.renderEvent = function(eventStick){
if(eventStick.recurring === true)
c.calendar_dom.calendar.refetchEvents();
else
c.calendar_dom.calendar.addEvent(eventStick);
};
$(document).ready(function() {
c.initialize();
});
};
var EventDialog = function(calendar,event){
_t = this;
var event_quick_view = null;
var template = "";
var _this_event = null;
this.inflate = function(_event){
if(!_event) throw new UserException("EventStick can't be null!");
_event.allDay = _event.event.allDay;
_event._start = _event.event.start;
_event._end = (_event.event.end ? _event.event.end : _event.event.start);
// var start_date = getDateString(_event._start,calendar_variable.date_format);
// var end_date = getDateString(_event._end,calendar_variable.date_format);
_event.title = _event.event.title;
var extendedProps = _event.event.extendedProps;
Object.keys(extendedProps).forEach(function(k){
_event[k] = extendedProps[k];
})
if(_event.hiring_person_name == undefined)
_event.hiring_person_name = "";
_this_event = _event;
var start_time = "",
end_time = "",
time_string = null;
if(_event.allDay) {
start_time = getDateString(_event._start,calendar_variable.date_format_with_short_month);
if(_event._end)
end_time = getDateString(_event._end,calendar_variable.date_format_with_short_month);
time_string = (_event._start === _event._end || !_event._end ? "<p class='start-date'><i class='icons-calendar' /></i>" + start_time + "</p>" : "<i class='icons-calendar' /></i>" + start_time + "<br><i class='icons-arrow-right-5' /></i>" + end_time + "");
} else {
start_time = getDateString(_event._start,calendar_variable.date_format_with_short_month);
end_time = getDateString(_event._end,calendar_variable.date_format_with_short_month);
var stime = getDateString(_event._start,calendar_variable.time_format),
etime = getDateString(_event._end,calendar_variable.time_format),
same = (start_time == end_time);
if( same ){
time_string = "<p class='date'><i class='icons-calendar' /></i> " +
start_time +
"</p><p class='time'><i class='icons-clock' /></i> " + stime +
" <i class='icons-arrow-right-5' /></i> " + etime ;
}else{
time_string = "<i class='icons-calendar' /></i><span class='start-date'>" + start_time + " " + stime +
"</span><br><i class='icons-arrow-right-5' /></i><span class='end-date'>" +
end_time + " " + etime + "</span>"
}
// time_string = (same ? "<p class='date'><i class='icons-calendar' /> " + start_time + "</p><p class='time'><i class='icons-clock' /> " + stime + " <i class='icons-arrow-right-5' /> " + etime : "<p class='start-date'><i class='icons-arrow-right-2' /> " + start_time + "<span class='pull-right'>" + stime + "</span></p><p class='end-date'><i class='icons-arrow-left-2' /> " + end_time + "<span class='pull-right'>" + etime + "</p>");
}
event_quick_view = $('<div class="calendar-modal" style="display:none;"></div>');
template = '<div class="modal-content">' +
'<div class="modal-header">' +
'<button type="button" class="close event-close-btn" data-dismiss="modal" aria-hidden="true">&times;</button>' +
'<h3>' + (_event.url_linked=='' ? _event.title : ("<a href=\"" +_event.url_linked+"\">"+_event.title+"</a>")) + '</h3>' +
'</div>' +
'<div class="modal-body">' +
'<div class="event_summary">' + time_string + '</br>' + _event.hiring_person_name + '</div>' + _event.note +
(_event.error_message ? ("<br><span style=\"color: #FC4040;\">" + _event.error_message + "</span>") : "")
'</div>' +
'<div class="modal-footer" />' +
'</div>';
if(_event.can_edit){
template += '<div class="modal-footer">' +
'<a href="'+ _event.delete_url +'" class="delete btn btn-primary">Delete</a>' +
'<a href="'+ _event.edit_url +'" class="edit btn btn-primary" >Edit</a>' +
(_event.recurring ? '<a href="'+ _event.edit_url +'?start='+getDateString(_event._start, "yy-MM-dd")+'" class="hide_event btn '+(_event.hide ? 'btn-success' : 'btn-danger')+'" data-new-hide="'+(_event.hide ? 'false' : 'true')+'">' + (_event.hide ? 'Show' : 'Hide') + '</a>' : '')
'</div>';
}
}
this.show = function(pos){
event_quick_view.css({display: 'inline-block',width: '',height: '', position: "fixed", "z-index": "10000"});
var offset;
var padding = 20;
if(pos){
offset = {"left":pos.x,"top":pos.y};
var pos = getPosition(pos);
event_quick_view.offset(offset);
}else{
offset = {"left": padding, "top": padding};
}
event_quick_view.html(template).appendTo("body").show();
event_quick_view.find(".event-close-btn").one("click",function(){_t.dismiss();});
event_quick_view.find("a.delete").one("click",function(){calendar.deleteEvent(_this_event.delete_url,_this_event._id);return false;});
event_quick_view.find("a.edit").one("click",function(){calendar.editEvent(_this_event.edit_url,_this_event.allDay);return false;});
event_quick_view.find("a.hide_event").off("click").on("click", function(){
var _this = $(this);
var new_hide = _this.attr('data-new-hide');
if(new_hide == "true"){
if(!(window.confirm(I18n.locale == 'zh_tw' ? "您確定要隱藏該事件嗎?" : "Are you sure to hide event?"))){
return false;
}
}
$.get(_this.attr('href') + "&hide="+ new_hide).done(function(data){
if(data["success"]){
if(new_hide == "true"){
if($('#display_hide').length != 0 && $('#display_hide').prop('checked')){
_this.removeClass('btn-danger').addClass('btn-success');
_this.text("Show");
_this.attr('data-new-hide', "false");
_this_event.event.setProp('color', _this_event.hide_color);
_this_event.event.setExtendedProp('hide', true);
}else{
_this_event.event.remove();
}
}else{
_this.removeClass('btn-success').addClass('btn-danger');
_this.text("Hide");
_this.attr('data-new-hide', "true");
_this_event.event.setProp('color', _this_event.org_color);
_this_event.event.setExtendedProp('hide', false);
}
event_quick_view.remove();
}else{
alert("Something went wrong!")
}
})
return false;
})
var window_width = $(window).width(),
window_height = $(window).height();
var dialog_width = event_quick_view.width(),
dialog_height = event_quick_view.height();
var new_offset = Object.assign({},offset);
var need_redisplay = false;
var new_width = null, new_height = null;
var padding_top = padding + 40;
if(offset.left + dialog_width > window_width){
new_offset.left = window_width - dialog_width - padding;
need_redisplay = true;
}
if(new_offset.left < padding){
new_width = dialog_width - (padding - new_offset.left);
new_offset.left = padding;
need_redisplay = true;
}
if(offset.top + dialog_height > window_height){
new_offset.top = window_height - dialog_height - padding;
need_redisplay = true;
}
if(new_offset.top < padding_top){
new_height = dialog_height - (padding_top - new_offset.top);
new_offset.top = padding_top;
need_redisplay = true;
}
if(need_redisplay){
event_quick_view.offset(new_offset);
event_quick_view.width(new_width);
event_quick_view.height(new_height);
}
}
this.hide = function(){
calendar.calendar_dom.find('.fc-popover-close').click();
$(event_quick_view).hide();
}
this.dismiss = function(){
if(event_quick_view)
event_quick_view.remove();
}
var getPosition = function(pos){
var x = pos.x,
y = pos.y,
winheight = $(window).height();
if((x + event_quick_view.width()) > $(window).width()){
x = x - event_quick_view.width();
}
if((y + event_quick_view.height()) > winheight){
y = y - event_quick_view.height();
}
return {"x":x,"y":y};
}
if(event)
_t.inflate(event);
}
var UserException = function(message) {
this.message = message;
this.name = "UserException";
this.toString = function(){
return this.message;
}
}
var AgendaView = function(calendar){
var av = this;
var _calendar = calendar;
var agenda_space = _calendar.agenda_space;
var today = new Date();
var minDifference = 6;
var start_month = today.getMonth();
var start_year = today.getFullYear();
var end_month = ((start_month + minDifference) > 11 ? (start_month + minDifference) - 11 : start_month + minDifference);
var end_year = ((start_month + minDifference) > 11 ? start_year+1 : start_year);
var monthNames = window.calendar_variable.months;
var month_template = '<div class="col-md-4">' +
'<h4></h4>' +
'<div class="tiny_calendar">' +
'<table class="table table-condensed table-bordered">' +
'<tbody>' +
'<tr>' +
calendar_variable.dayNamesShort.slice(0).rotate(calendar_variable.sunday_first ? 0 : 1).map(function(title){
return '<th class="week_title">'+title+'</th>';
}).join('') +
'</tr>' +
'</tbody>' +
'</table>' +
'</div>' +
'</div>';
var event_list_template = '<div class="col-md-8 agenda-event">' +
'<table class="table table-condensed table-bordered event_list">' +
'<thead>' +
'<tr>' +
'<th>DateTime</th>' +
'<th>Events</th>' +
'</tr>' +
'</thead>' +
'<tbody>' +
'<tr>' +
'<td colspan="3" class="no_events">No events for this month.</td>' +
'</tr>' +
'</tbody>' +
'</table>' +
'</div>';
var head_template = '<div>' +
'<label>'+(window.calendar_variable.from ? window.calendar_variable.from : 'From')+'</label>' +
'<input class="input-large" id="agenda_start" placeholder="YYYY/MM" type="text" value="'+start_year+'/'+('0'+(start_month+1)).substr(-2,2)+'" title="YYYY/MM" autocomplete="off">'+
'<label>'+(window.calendar_variable.to ? window.calendar_variable.to : 'To')+'</label>' +
'<input class="input-large" id="agenda_end" placeholder="YYYY/MM" type="text" value="'+end_year+'/'+('0'+(end_month+1)).substr(-2,2)+'" title="YYYY/MM" autocomplete="off">'+
'<button id="show_events" class="btn btn-sm bt-filter btn-primary">Show Events</button>' +
'</div>';
var event_template = '<tr>' +
'<td class="event_datetime" />' +
'<td>' +
'<div class="event" />' +
'</td>' +
'</tr>';
// var month_template = '<div class="span4"><h4></h4><div class="tiny_calendar"><table class="table"><tbody><tr><th class="week_title">Sun</th><th class="week_title">Mon</th><th class="week_title">Tue</th><th class="week_title">Wed</th><th class="week_title">Thu</th><th class="week_title">Fri</th><th class="week_title">Sat</th></tr></tbody></table></div></div>';
// var event_list_template = '<div class="span8"><table class="table event_list"><thead><tr height="0"><th class="span3"></th><th class="span2"></th><th class=""></th></tr></thead><tbody><tr><td colspan="3" class="no_events">No events for this month.</td></tr></tbody></table></div>';
// var head_template = '<div><label>From</label> <select name="start_month" class="input-small"></select><select name="start_year" class="input-small"></select><label>To</label> <select name="end_month" class="input-small"></select><select name="end_year" class="input-small"></select><button id="show_events" class="btn bt-filter">Show Events</button></div>';
// var event_template = "<tr><th></th><td class='event_time'></td><td><div class='event'></div></td></tr>";
var cache = false;
var show_event_clicked = false;
this.refresh = function(){
av.inflate(true);
}
this.inflate = function(forceInflation){
loading(true);
_calendar.calendar_dom.hide();
_calendar.navigation.hide();
if(!forceInflation){
if(cache){
av.show();
loading(false);
return;
}
}
agenda_space.empty();
if(!show_event_clicked){
_calendar.rangeSelection.empty();
_calendar.rangeSelection.append(renderHead().html()).show();
_calendar.rangeSelection.find("button#show_events").click(function(){
show_event_clicked = true;
var starts = $("#agenda_start").val().split("/"),
ends = $("#agenda_end").val().split("/");
start_month = parseInt(starts[1]) - 1;
end_month = parseInt(ends[1]) - 1;
start_year = parseInt(starts[0]);
end_year = parseInt(ends[0]);
av.inflate(true);
})
}
show_event_clicked = false;
eventsManager();
var s = start_month,
e = end_month
y = start_year;
e = (e > s && start_year == end_year? e : e + 11);
if(end_year > start_year)
e = e + ((end_year - start_year -1) * 12);
else e--;
for(var i = s;i <= e+1; i++){
var m = new Month(s,y);
s++;
if(s > 11){
s = 0;
y++;
}
if(e == 0)
agenda_space.text("Invalid Range of Dates.")
else
agenda_space.append(m.monthDom);
}
loading(false);
}
this.hide = function(){
cache = true;
_calendar.rangeSelection.hide();
agenda_space.hide();
_calendar.navigation.show();
_calendar.calendar_dom.show();
}
this.show = function(){
_calendar.rangeSelection.show();
agenda_space.show();
}
var copyObject = function(x){
return x.clone();
}
var eventsManager = function(){
var url = "/admin/calendars/agenda",
sd = new Date(start_year,start_month,1),
ed = new Date(end_year,end_month+1,0),
usd = Math.round(sd/1000),
ued = Math.round(ed/1000);
$.ajax({
type : "get",
url : url,
dataType : "json",
data : {"agenda_start":sd.toLocaleString(),"agenda_end":ed.toLocaleString(),"unix_start":usd,"unix_end":ued},
success : function(data){
$("#agenda_start,#agenda_end").datepicker({
dateFormat: "yy/mm",
onChangeMonthYear: function( year, month, inst ){
$(this).val($.datepicker.formatDate('yy/mm', new Date(year, month-1, 1)));
},
gotoCurrent: true
});
$("#agenda_start,#agenda_end").on("focus",function(){
var input = this;
var inst = $(this).data("datepicker");
var year_month = $(input).val().split("/");
if(year_month.length == 2){
inst.selectedYear = parseInt(year_month[0]);
inst.selectedMonth = parseInt(year_month[1]) - 1;
inst.drawYear = inst.selectedYear;
inst.drawMonth = inst.selectedMonth;
inst.currentYear = inst.selectedYear;
inst.currentMonth = inst.selectedMonth;
}
$.datepicker._updateDatepicker(inst);
})
$("#agenda_start,#agenda_end").focus(function () {
$(".ui-datepicker-calendar").hide();
$("#ui-datepicker-div").position({
my: "center top",
at: "center bottom",
of: $(this)
});
});
$.each(data,function(i,e){
var ed = eventDom(e),
calendar_id = e.calendar,
s = new Date(e.start),
e = new Date(e.end),
e_m = ((e.getMonth() > s.getMonth() || s.getMonth() == e.getMonth()) && s.getFullYear() == e.getFullYear() ? e.getMonth() : e.getMonth() + 12)
s_m = s.getMonth(),
s_y = s.getFullYear();
if(e.getFullYear() > s.getFullYear())
e_m = e_m + ((e.getFullYear() - s.getFullYear() -1) * 12);
for(var i = s_m; i < e_m + 1; i++){
var temp_ed = copyObject(ed);
var list = agenda_space.find("div[data-month="+s_m+"][data-year="+s_y+"] table.event_list tbody");
list.append(temp_ed);
s_m++;
if(s_m > 11){
s_m = 0;
s_y++;
}
}
if(s.getDate() == e.getDate() && s.getMonth() == s.getMonth() && e.getFullYear() == e.getFullYear()){
var td = agenda_space.find("td[data-date-node="+s.getDate()+"-"+s.getMonth()+"-"+s.getFullYear()+"]");
td.addClass("has_event").attr("data-calendar-id", calendar_id);
}else{
var timeDiff = Math.abs(e.getTime() - s.getTime()),
diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)),
c_m = s.getMonth(),
c_d = s.getDate(),
c_y = s.getFullYear(),
end_of_c_month = new Date(s.getFullYear(),s.getMonth()+1,0).getDate();
for(var i = 0; i <= diffDays; i++){
var td = agenda_space.find("td[data-date-node="+c_d+"-"+c_m+"-"+c_y+"]");
td.addClass("has_event").attr("data-calendar-id", calendar_id);
c_d++;
if(c_d > end_of_c_month){
c_d = 1;
c_m++;
if(c_m > 11){
c_m = 0;
c_y++;
}
}
}
}
})
agenda_space.find("table.event_list tbody").each(function(){
if($(this).find("tr").length > 1)
$(this).find("td.no_events").parent().remove();
})
$(".edit_event_btn").on("click", function(){
var _this = $(this);
_calendar.editEvent(_this.data('edit-url'), _this.data('allDay'));
return false;
});
// nano scroller here
}
})
var eventDom = function(event){
var e_t = $(event_template),
s = new Date(event.start),
e = new Date(event.end),
datetimeFormat = "";
if(s.getDate() == e.getDate() && s.getMonth() == s.getMonth() && e.getFullYear() == e.getFullYear()){
datetimeFormat = getDateString(s, calendar_variable.short_day);
if(!event.allDay){
datetimeFormat += (' ' + getDateString(s,calendar_variable.time_format) + ' - ' + getDateString(e,calendar_variable.time_format));
}
}else{
if(event.allDay){
datetimeFormat = getDateString(s,calendar_variable.short_date) + ' - ' + getDateString(e,calendar_variable.short_date);
}else{
datetimeFormat = getDateString(s,calendar_variable.short_date_time) + ' - ' + getDateString(e,calendar_variable.short_date_time);
}
}
e_t.find("td.event_datetime").text(datetimeFormat);
var tmp_html = event.title;
if(event.edit_url){
tmp_html = '<a href="javascript:void(0)" class="edit_event_btn" data-edit-url="'+event.edit_url+'" data-allDay="'+event.allDay+'">' + tmp_html + '</a>';
}
e_t.find("div.event").html(tmp_html).css("color",event.color).attr("data-calendar-id", event.calendar);
return e_t;
}
}
var loading = function(bool) {
if (bool) _calendar.loading.css("left",($(window).width()/2 - 60) + "px").show();
else _calendar.loading.hide();
}
var renderHead = function(){
var head = $(head_template);
var start_month_select = head.find("select[name=start_month]");
for(var i = 0; i < 12; i++){
var option = $("<option value='"+i+"'>"+monthNames[i]+"</option>");
if(i == start_month)
option.attr("selected","selected");
start_month_select.append(option);
}
var end_month_select = head.find("select[name=end_month]");
for(var i = 0; i < 12; i++){
var option = $("<option value='"+i+"'>"+monthNames[i]+"</option>");
if(i == end_month)
option.attr("selected","selected");
end_month_select.append(option);
}
var start_year_select = head.find("select[name=start_year]");
var y = start_year - 5;
for(var i = 0; i < 10; i++){
var option = $("<option value='"+y+"'>"+y+"</option>");
if(y == start_year)
option.attr("selected","selected");
start_year_select.append(option);
y++;
}
var end_year_select = head.find("select[name=end_year]");
y = start_year - 5;
for(var i = 0; i < 10; i++){
var option = $("<option value='"+y+"'>"+y+"</option>");
if(y == end_year)
option.attr("selected","selected");
end_year_select.append(option);
y++;
}
return head;
}
var Month = function(month,year){
_this = this;
this.monthDom = $("<div class='row' data-year='"+year+"' data-month='"+month+"'></div>");
var template = $(month_template);
var list_template = $(event_list_template);
var firstDay = new Date(year,month,1);
var lastDay = new Date(year,month+1,0);
var last_inserted_date = 1;
var renderMonth = function(){
var num_of_rows = getNumberOfRows(year,month);
var tbody = template.find("table.table tbody");
for(var i = 0; i < num_of_rows; i++){
var tr = null;
if(i == 0)
tr = makeRow("first");
else if(i == (num_of_rows - 1)){
tr = makeRow("last");
}else{
tr = makeRow("middle");
}
if(tr == null){
break;
}
tbody.append(tr);
}
template.find("h4").text(getDateString(firstDay, calendar_variable.month_year_format));
_this.monthDom.append(template);
_this.monthDom.append(list_template);
}
function getNumberOfRows(year, month) {
var day = 1,
sat_counter = 0,
sunday_counter = 0,
date = new Date(year, month, day);
while(date.getMonth() === month) {
if(date.getDay() === 0) {
sunday_counter++;
}else if(date.getDay() === 6) {
sat_counter++;
}
day++;
date = new Date(year, month, day);
}
return (sunday_counter == 5 && sat_counter == 5 ? 6 : 5);
}
var makeRow = function(position){
if(last_inserted_date <= lastDay.getDate()){
var row = $("<tr></tr>");
switch (position){
case "first":
var offset = firstDay.getDay() - (window.calendar_variable.sunday_first ? 0 : 1);
for(var i = 0;i < 7;i++){
var td = $("<td></td>");
if(i >= offset){
td.text(last_inserted_date);
td.attr("data-date-node",last_inserted_date+"-"+firstDay.getMonth()+"-"+firstDay.getFullYear());
last_inserted_date++;
}
row.append(td);
}
break;
case "middle":
for(var i = 0;i < 7;i++){
var td = $("<td></td>");
td.text(last_inserted_date);
td.attr("data-date-node",last_inserted_date+"-"+firstDay.getMonth()+"-"+firstDay.getFullYear());
last_inserted_date++;
row.append(td);
}
break;
case "last":
var offset = lastDay.getDay() - (window.calendar_variable.sunday_first ? 0 : 1);
for(var i = 0;i < 7;i++){
var td = $("<td></td>");
if(i <= offset){
td.text(last_inserted_date);
td.attr("data-date-node",last_inserted_date+"-"+firstDay.getMonth()+"-"+firstDay.getFullYear());
last_inserted_date++;
}
row.append(td);
}
break;
}
}else{
var row = null;
}
return row;
}
renderMonth();
}
}