/* ACLS */
Module_Event_Calendar_ACLS = {};
Module_Event_Calendar_ACLS.__ids = {}

Module_Event_Calendar_ACLS.add = function(event_id, edit_type) {	
	Module_Event_Calendar_ACLS.__ids[event_id] = edit_type;
}

Module_Event_Calendar_ACLS.get = function(event_id) {
	if (Module_Event_Calendar_ACLS.__ids[event_id])
		return Module_Event_Calendar_ACLS.__ids[event_id];
	
	return '';
}
Module_Event_Calendar_ACLS.invalidate = function(event_id) {
	delete Module_Event_Calendar_ACLS.__ids[event_id];
}

Module_Event_Calendar_ACLS.fetch = function(scope, preset_id, event_id, callback) {
	if (Module_Event_Calendar_ACLS.__ids[event_id]) {
		callback.call(scope, Module_Event_Calendar_ACLS.get(event_id));
	} else { 
		//try to fetch
		var data = {
			preset_id: preset_id,
			op: 'event-acl-fetch',
			event_id: event_id
		};
		
		$.post('/ajax.php?s=eventcalendar', data, function(response) {
			if (response && !response.error) {
				Module_Event_Calendar_ACLS.add(event_id, response.edit_type);
				var can_edit = Module_Event_Calendar_ACLS.get(event_id);
				
				callback.call(scope, can_edit);
			}
		}, 'json');
	}
}

Module_Event_Calendar_ACLS.remove = function(event_id) {
	delete Module_Event_Calendar_ACLS.__ids[event_id];
}

/* manager */
Module_Event_Calendar_Manager = {};
Module_Event_Calendar_Manager.__ids = {}

Module_Event_Calendar_Manager.hash = function(event_id, timestamp) {
	return event_id+"-"+timestamp;
}

Module_Event_Calendar_Manager.add = function(event_id, timestamp, event) {
	var hash = this.hash(event_id, timestamp);
	event.role_enabled = parseInt(event.role_enabled);
	event.role_userset = parseInt(event.role_userset);
	event.characters_enable = parseInt(event.characters_enable);
	
	Module_Event_Calendar_Manager.__ids[hash] = event;
}

Module_Event_Calendar_Manager.get = function(event_id, timestamp) {
	var hash = this.hash(event_id, timestamp);
	return Module_Event_Calendar_Manager.__ids[hash];
}
Module_Event_Calendar_Manager.invalidate = function(event_id) {
	for (var key in Module_Event_Calendar_Manager.__ids) {
		rkey = key.split('-');
		if (rkey[0] == event_id) {
			delete Module_Event_Calendar_Manager.__ids[key];
		}
	}
}

Module_Event_Calendar_Manager.fetch = function(scope, preset_id, event_id, timestamp, callback) {
	var hash = this.hash(event_id, timestamp);
	
	if (Module_Event_Calendar_Manager.__ids[hash]) {
		callback.call(scope, Module_Event_Calendar_Manager.__ids[hash], timestamp);
	} else { 
		//try to fetch
		var data = {
			preset_id: preset_id,
			op: 'event-detail-fetch',
			event_id: event_id,
			timestamp: timestamp
		};
		
		$.post('/ajax.php?s=eventcalendar', data, function(response) {
			if (response && !response.error) {
				Module_Event_Calendar_Manager.add(event_id, timestamp, response);
				var event = Module_Event_Calendar_Manager.get(event_id, timestamp);
				
				callback.call(scope, event, timestamp);
			} else {
				Enjin_Core.alert('Failed to fetch the event data');
			}
		}, 'json');
	}
}

Module_Event_Calendar_Manager.remove = function(event_id) {
	delete Module_Event_Calendar_Manager.__ids[event_id];
}


Module_Event_Calendar = function(preset_id, params) {
	this.init(preset_id, params);
}

Module_Event_Calendar.getPopupCurrent = function(el) {
	var preset_id = $(el).closest('.element_popup').attr('presetid');
	
	return this.getInstance(preset_id);
}

Module_Event_Calendar.weekFlags = null;
Module_Event_Calendar.createSummary = function(type, frequence, flag, end) {
	var summary = type.charAt(0).toUpperCase() + type.slice(1);
	var frequence_type = '';
	frequence = parseInt(frequence);
	
	switch(type) {
		case 'daily':
			frequence_type = 'days';
			break;
		case 'weekly':
			frequence_type = 'weeks';
			break;
		case 'monthly':
			frequence_type = 'months';
			break;
		case 'yearly':
			frequence_type = 'years';
			break;
	}
	
	if (type == 'weekly' && flag) {
		var str_flags = [];
		jQuery.each(Module_Event_Calendar.weekFlags, function(key, value) {
			key = parseInt(key);
			if (key & flag)
				str_flags.push(value);
		});
		
		if (str_flags.length > 0)
			summary += ' on '+str_flags.join(', ');
	} else if (frequence > 1) {
		summary += ' every '+frequence+' '+frequence_type;
	}
	
	if (end) {
		summary += ' until '+end.asString('mm/dd/yyyy')
	}
	
	return summary;
}


Module_Event_Calendar.__instances = {};
Module_Event_Calendar.getInstance = function(preset_id) {	
	return Module_Event_Calendar.__instances[preset_id];
}

Module_Event_Calendar.isAdmin = function() {
	return (typeof Module_Event_Calendar_Admin != 'undefined')
			&& Module_Event_Calendar_Admin.can_admin;
}
Module_Event_Calendar.isAdminOwn = function() {
	return (typeof Module_Event_Calendar_Admin != 'undefined')
			&& Module_Event_Calendar_Admin.can_admin_own;
}


Module_Event_Calendar.__initedURL = false;
Module_Event_Calendar.initURL = function() {
	if (Module_Event_Calendar.__initedURL)
		return false;
	
	var loc = document.location+"";
	var index = loc.indexOf('#');
	var ret = false;
	
	if (index > -1)
		ret = Module_Event_Calendar.processUrlHash(loc.substr(index+1));
	
	Module_Event_Calendar.initHistory();
	return ret;
};
Module_Event_Calendar.processUrlHash = function(hash) {
	loc = hash;
	loc = loc.split('/');
	var params = {};
	for (var i=0; i<loc.length; i++) {
		var lloc = loc[i];
		var lpos = lloc.indexOf('=');
		var key = lloc.substr(0, lpos);
		var value = lloc.substr(lpos+1);
		params[key] = value;
	}
	
	if (params.op == 'detail') {
		var calendar = Module_Event_Calendar.getInstance(params.preset_id);
		
		if (!calendar) {
			return false; //wait for other preset
		}
		
		if (!Module_Event_Calendar.__initedURL) {
			Module_Event_Calendar.__initedURL = true;			
		}
		
		calendar.showEvent(params.event_id, params.timestamp);
		return true;
	}
}

Module_Event_Calendar.initHistory = function() {
	var first_callback = true;
	//start history
	$.history.init(function(hash){
		if (first_callback) {
			first_callback = false;
			return;
		}
		
		Module_Event_Calendar.processUrlHash(hash);
	});
}



Module_Event_Calendar.prototype = {
	preset_id: null,
	params: null,
	el_calendar_built: false,
	el_container_title: null,
	el_container: null,
	el_main: null,
	el_event_detail: null,
	el_event_detail_title: null,
	el_event_detail_time: null,
	el_event_detail_info: null,
	el_event_detail_description: null,
	el_event_detail_comments: null,
	el_event_detail_attend_list: null,
	el_event_detail_attend_list_container: null,
	el_event_detail_attend_list_count: null,
	el_event_detail_attend_panel: null,
	el_event_detail_attend_panel_list: null,
	el_event_detail_attend_panel_status: null,
	el_event_detail_role_list_container: null,	
	
	el_event_list: null,
	el_event_list_items: null,
	el_menutop_views: null,
	base_url: null,
	event_calendar_reload: true,
	event_list_loaded: false,
	mode_display: 'calendar',
	list_next_param: null,
	needs_regenerate: false,
	
	detail_event_id: null,
	detail_event_timestamp: null,
	detail_event_admin_user_id: null,
	el_eventlist_title: null,
	
	button_next: null,
	button_prev: null,
	event_list_loaded_last: null,
	
	init: function(preset_id, params) {
		var self = this;
		
		this.event_list_loaded_last = {
			have_more: false,
			have_less: false
		};
		this.preset_id = preset_id;
		this.params = params;
		Module_Event_Calendar.__instances[preset_id] = this;
		
		//init popup to avoid relatives inners
		$('.m_eventcalendar.popup-admin-edit').appendTo($(document.body));
		$('.m_eventcalendar.popup-birthday-list').appendTo($(document.body));
		
		var container = $('.m_eventcalendar-'+preset_id);
		var el = $('.m_eventcalendar-'+preset_id+' .calendar-container .container');
		this.el_container_title = $('.m_eventcalendar-'+preset_id+' .calendar-container .block-title .mask');
		this.el_container = $('.m_eventcalendar-'+preset_id+' .calendar-container');
		this.el_main = el;
		this.el_event_list =  $('.m_eventcalendar-'+preset_id+' .calendar-container-event-list');
		this.el_event_list_items =  $('.m_eventcalendar-'+preset_id+' .calendar-container-event-list .block-container .items');
		this.el_list_more =  $('.m_eventcalendar-'+preset_id+' .calendar-container-event-list .block-container .more-link');
		
		this.el_event_detail =  $('.m_eventcalendar-'+preset_id+' .calendar-container-event-detail');;
		this.el_event_detail_title = $('.m_eventcalendar-'+preset_id+' .calendar-container-event-detail .event-title');
		this.el_event_detail_link_invite = $('.m_eventcalendar-'+preset_id+' .calendar-container-event-detail .text-right .link-invite');
		this.el_event_detail_link_edit = $('.m_eventcalendar-'+preset_id+' .calendar-container-event-detail .text-right .link-edit');
		this.el_event_detail_info = $('.m_eventcalendar-'+preset_id+' .calendar-container-event-detail .block-container .detail-main .detail-info');
		this.el_event_detail_image = $('.m_eventcalendar-'+preset_id+' .calendar-container-event-detail .block-container .image-event');
		
		this.el_event_detail_timewrapper = $('.m_eventcalendar-'+preset_id+' .calendar-container-event-detail .block-container .detail-main .detail-date .timewrapper');
		this.el_event_detail_time = $('.m_eventcalendar-'+preset_id+' .calendar-container-event-detail .block-container .detail-main .detail-date .time-non-countdown');
		this.el_event_detail_description = $('.m_eventcalendar-'+preset_id+' .calendar-container-event-detail .block-container .detail-main .detail-description');
		this.el_event_detail_comments = $('.m_eventcalendar-'+preset_id+' .calendar-container-event-detail .comments');
		
		this.el_event_detail_attend_list = $('.m_eventcalendar-'+preset_id+' .calendar-container-event-detail .attend-list-main .scroller');
		this.el_event_detail_attend_list_container = $('.m_eventcalendar-'+preset_id+' .calendar-container-event-detail .attend-list-main');
		this.el_event_detail_attend_list_count = $('.m_eventcalendar-'+preset_id+' .calendar-container-event-detail .attend-list-main .number');
		
		this.el_event_detail_role_list_container = $('.m_eventcalendar-'+preset_id+' .calendar-container-event-detail .attend-list-roles');
		
		this.el_event_detail_attend_panel_status = $('.m_eventcalendar-'+preset_id+' .calendar-container-event-detail .attend-options .attend-status');
		this.el_event_detail_attend_panel = $('.m_eventcalendar-'+preset_id+' .calendar-container-event-detail .attend-options');
		this.el_event_detail_attend_panel_list = $('.m_eventcalendar-'+preset_id+' .calendar-container-event-detail .attend-list');
		
		this.el_list_more =  $('.m_eventcalendar-'+preset_id+' .calendar-container-event-list .block-container .more-link');

		this.el_menutop_views = $('.m_eventcalendar-'+preset_id+' .menu-top .nav-views');
		this.el_eventlist_title = $('.m_eventcalendar-'+preset_id+' .calendar-container-event-list .block-title .text .mask');
		this.base_url = '/ajax.php?s=eventcalendar&preset_id='+this.preset_id+'&op=';		
		
		this.button_next = container.find('.menu-top .nav-buttons .button-next');
		this.button_prev = container.find('.menu-top .nav-buttons .button-prev');
		
		//bind on note
		$('.m_eventcalendar.popup-own-characters').outsideClick({
			callback: function() {
				$(this).hide();
			}
		});
		
		$('.m_eventcalendar.popup-attendance-own-set-type').outsideClick({
			callback: function() {
				$(this).hide();
			}
		});
		$('.m_eventcalendar.popup-own-roles').outsideClick({
			callback: function() {
				$(this).hide();
			}
		});
		
		$('.m_eventcalendar.popup-attendance-own-edit-caption').bind('keydown', function(evt) {
			if (evt.keyCode == 0xD)
				self.editCaptionSubmit(this);
		});
		
		$('.m_eventcalendar.popup-attendance-own-edit-caption').outsideClick({
			callback: function() {
				self.editCaptionSubmit(this);
			}
		});
		
		if (!Module_Event_Calendar.initURL()) {
			//use default view
	        switch(params.default_view) {
	        	case 'month':
	        		this.buildCalendar('month');
	        		this.selectType('month');
	        		break;
		        case 'week':
		        	this.buildCalendar('basicWeek');
		        	this.selectType('basicWeek');
	    			break;
	    		case 'list':
	    			this.showEventList();
	    			this.selectType('event-list-btn');
	    			break;
	    		case 'detail':
	    			this.goDetailToday();
	    			break;
	    		default:
	    			this.buildCalendar('month');
        			break;
	        }
		}
	},
	editCaptionSubmit: function(el) {
		var self = this;
		$(el).hide();
		
		//save the message
		var msg = $.trim($(el).find('input[type=text]').val());
		if (msg != '') {
			//update event
			var event = Module_Event_Calendar_Manager.get(self.detail_event_id, self.detail_event_timestamp);
			event.own.note = msg;
			Module_Event_Calendar_Manager.add(self.detail_event_id, self.detail_event_timestamp, event);
			
			$('.m_eventcalendar.popup-attendance-own-edit-caption').hide();
			var data = {
    			preset_id: self.preset_id,
    			op: 'event-attend-note',
    			event_id: self.detail_event_id,
    			timestamp: self.detail_event_timestamp,
    			user_id: event.own.user_id,
    			text: msg
    		};
    		
    		$.post('/ajax.php?s=eventcalendar', data, function(response) {
    			//update in attendance
    			self.el_event_detail_attend_list.find('.item[userid='+data.user_id+'] .note').text(self.buildSummaryNote(msg, true));
    		});
		}		
	},
	
	disableNav: function() {
		$('.button-today,.button-prev,.button-next').find('input[type=button]').attr('disabled', 'true');
	},
	enableNav: function() {
		$('.button-today,.button-prev,.button-next').find('input[type=button]').removeAttr('disabled');
	},
	
	invalidateViewCalendar: function() {
		this.event_calendar_reload = true;
	},
	invalidateViewList: function() {
		this.event_list_loaded = false;
	},
	
	
	buildCalendar: function(default_view) {
		if (this.el_calendar_built)
			return false;
		
		if (!default_view)
			default_view = 'month';
		
		this.el_calendar_built = true;
		this.event_calendar_reload = false; //as we are going to reload
		
		var self = this;
		var el = $('.m_eventcalendar-'+this.preset_id+' .calendar-container .container');
		el.fullCalendar({
			events: this.base_url+'feed',
			defaultView: default_view,
			header: null,
			//editable: Module_Event_Calendar.isAdmin(),
			agendaWeekItemHeight: 0,
			disableWeekSlotHeight: 1,
			slotMinutes: 60,
			disableResizing: true,
			agendaWeekShowAxis: false,
			agendaWeekItemMinHeight: 22,
			allDaySlot: false,
			timeFormat: {
			    '': 'h:mmt'
			},
			columnFormat: {
				week: self.params.calendar_dateformat_week
			},
			titleFormat: {
				week: self.params.calendar_dateformat_week_title
			},
			updateTitle: function(html) { 
				self.el_container_title.html(html); 
			},
			draggableSlotEventCheckCell: function(cell, origCell) {
				if (cell)
					cell.row = origCell.row;
				
				return cell;
			},
			
	        dayClick: function(date, allDay, jsEvent, view) {
				if (Module_Event_Calendar.isAdmin() 
					|| Module_Event_Calendar.isAdminOwn()) {
					//allow only events from today, check later if is ok
					var today = new Date();
					today.setHours(0);
					today.setMinutes(0);
					today.setSeconds(0);
					today.setMilliseconds(0);
				
					if (date.getTime() >= today.getTime())
						Module_Event_Calendar_Admin.eventAdd(self.preset_id, date);
				}
	        },
	        eventClick: function(calEvent, jsEvent, view) {
	        	if (calEvent.type == 'birthday')
	        		return; //nothing to do
	        	
	        	/*if (Module_Event_Calendar.isAdmin()) {
	        		Module_Event_Calendar_Admin.eventEditByID(self.preset_id, calEvent.id);
	        	} else if (Module_Event_Calendar.isAdminOwn()) {
	        		Module_Event_Calendar_ACLS.fetch(self, self.preset_id, calEvent.id, function(edit_type) {
	        			if (edit_type != '')
	        				Module_Event_Calendar_Admin.eventEditByID(self.preset_id, calEvent.id);
	        			else
	        				self.showEvent(calEvent.id, calEvent.timestamp);
	        		});	 
	        	} else if (calEvent.can_edit) {
	        		Module_Event_Calendar_Admin.eventEditByID(self.preset_id, calEvent.id);
	        	} else {*/
	        		self.showEvent(calEvent.id, calEvent.timestamp);
	        	//}
	        },
	        
	        renderEventContent: function(event) {
	        	if (event.type == 'birthday') {
	        		var html = '';
	        		if (event.total == 1) {
	        			html = '<div class="icon"><!-- --></div><div class="container-title">'+event.extra+'</div>';
	        		} else {
	        			html = '<div class="icon"><!-- --></div><div class="container-title">'+event.title+'</div>';
	        		}
	        		
	        		return html;
	        	}
	        	
	        	return '';
	        },
	        
	        renderEventSeg: function(event, width, style) {
	        	if (event.type != 'birthday' && event.image_url != '') {
	        		event.image_width = parseInt(event.image_width);
	        		var height = event.image_width; //to be square  
	        		
	        		if (width < event.image_width) {
	        			//needs to scale
	        			var ratio = width / event.image_width;
	        			height *= ratio;
	        		}
	        		
	        		if (style)
	        			width += 5; //to add padding for week
	        		else
	        			width -= 2; //to add padding
	        		
	        		var max_length = 40;
	        		var title = event.title;
	        		var html_recurrence = '';
	        		
	        		if (title.length > max_length)
	        			title = title.substr(0, max_length-3)+'...';
	        		
	        		if (event.recurrence && event.recurrence != 'none')
	        			html_recurrence += '<span class="fc-recurrence">R</span>';
	        		
	        		html = '<div class="fc-event-image" style="width: '+width+'px; height: 90px;"><div class="image"><img src="'+event.image_url+'" /></div><div class="desc"><div class="desc-wrapper">'+html_recurrence+event.time_str+'<br />'+title+'</div></div></div>';
	        		if (style)
	        			html = '<div style="'+style+'">'+html+'</div>';
	        		return html;
	        	}
	        	
	        	return '';
	        },
	        
	        renderEventTitlePre: function(event) {	        	
	        	if (event.recurrence != 'none')
	        		return '<span class="fc-recurrence">R</span>';
	        	
	        	return '';
	        },
	        eventMouseover: function(event, evt) {
	        	if (event.type == 'birthday') {
	        		if (event.total > 1) {
	        			var el = $('.m_eventcalendar.popup-birthday-list');
	        			el.find('.inner').empty();
	        			var html = '';
	        			for (var i=0; i<event.total; i++) {
	        				html += '<div class="item">';
	        				html += '<div class="avatar element_avatar simple small">';
	        				html += event.avatar[i];
	        				html += '</div>';
	        				html += '<div class="username">';
	        				html += event.extra[i];
	        				html += '</div>';	        				
	        				html += '<div class="clearing"><!-- --></div>';
	        				html += '</div>';
	        			}
	        			el.find('.inner').append(html);
	        			
	        			//put in proper position
	        			Enjin_Core.prepareEvent(evt);
	        			el.css('top', evt.pageY);
	        			el.css('left', evt.pageX+10);
	        			el.show();
	        		}
	        	} else {
	        		var html = '<div class="ptitle color-'+event.color+'">'+Enjin_Core.htmlentities(event.title)+'</div>';
	        		if (event.hover_description != '') {
						if(event.hover_description.length > 140) var hdesc = event.hover_description.substring(0,138) + "...";
						else hdesc = event.hover_description;
	        			html += '<div class="description">' + hdesc + '</div>';
					}
	        		
	        		if (event.roles.length > 0) {
						var role_html = '<div class="role-list roles">';
						for (j=0; j<event.roles.length; j++) {
							var role_item = event.roles[j];
							
							role_html += '<div class="itemrolesep">';
							if (role_item.icon_uploaded_url != '')
								role_html += '<div class="role-icon role-icon-img"><img src="'+role_item.icon_uploaded_url+'"  alt="'+Enjin_Core.htmlentities(role_item.name)+'"  title="'+Enjin_Core.htmlentities(role_item.name)+'" /></div>'
							else
								role_html += '<div class="role-icon role item-role item'+role_item.icon_default+'" alt="'+Enjin_Core.htmlentities(role_item.name)+'" title="'+Enjin_Core.htmlentities(role_item.name)+'"><!-- --></div>'
									
							role_html += '<div class="lbl-stats">'+role_item.total
							if (parseInt(role_item.limit_count) > 0)
								role_html += '/'+role_item.limit_count;
								
							role_html += '</div>';
							role_html += '<div class="clearing"><!-- --></div>';
							role_html += '</div>';
						}
						role_html += '</div>';		
						
						html += role_html;
	        		}
	        		
	        		/*
	        		if (event.hover_stats) {
	        			html += '<div class="stats">';
	        			html += '<span class="attending">'+event.hover_stats.number_signup_total+' attending</span>';
	        			html += ' <span class="invited">('+event.hover_stats.number_signup_invited+' invited)</span>';
	        			html += '</div>';
	        		}*/
	        		
	        		Enjin_Core.bindTooltip($(evt.currentTarget), html, 'm_eventcalendar m_eventcalendar-stats-hover');
	        	}
	        },
	        eventMouseout: function(event) {
	        	if (event.type == 'birthday') {
        			$('.m_eventcalendar.popup-birthday-list').hide();
	        	}
	        },
	        allowDraggableEvent: function(event) {
	        	if (event.type == 'birthday')
	        		return false;
	        	
	        	if (event.recurrence != 'none')
	        		return false;
	        	
	        	if (self.el_main.fullCalendar( 'getView' ).name != 'agendaWeek')
	        		return false;
	        	
	        	return true;
	        },
	        eventDragStop: function(eventElement, event, ev, ui, cell) {
	        	var event_id = eventElement.id;
	        	var weekday = ui.col;
	        	var date = cell.start.asString('dd/mm/yyyy');
	        	
	        	var data = {
        			preset_id: self.preset_id,
        			op: 'event-week-update',
        			event_id: event_id,
        			date: date,
        			weekday: weekday
        		};
        		
        		$.post('/ajax.php?s=eventcalendar', data, function(response) {
        			self.event_calendar_reload = true;
        		}, 'json');
	        },
	        
	        segMonthPadding: 2
	    });
		
		return true;
	},
	
	getEl: function() {
		return this.el_main;
	},
	
	changeView: function(type) {
		this.mode_display = 'calendar';

		this.el_container.show();
		this.el_event_list.hide();
		this.el_event_detail.hide();
				
		//build calendar if needed
		var built = this.buildCalendar(type);
		
		this.button_prev.show();
		this.button_next.show();
		this.selectType(type);
		
		//just in case
		this.el_event_detail_timewrapper.find('.timewrapper-countdown .countdown').countdown('destroy');
		
		if (!built) {
			this.el_main.fullCalendar( 'changeView', type );
			
			if (this.event_calendar_reload) {
				this.event_calendar_reload = false;
				this.el_main.fullCalendar( 'refetchEvents' );
			}
		}
		
	},
	
	selectType: function(type) {
		this.el_menutop_views.find('.item').removeClass('selected');
		
		if (type)
			this.el_menutop_views.find('.'+type).addClass('selected');		
	},
	
	showEventList: function() {		
		this.mode_display = 'list';
		this.el_container.hide();
		this.el_event_detail.hide();
		this.el_event_list.show();
		this.selectType('event-list-btn');
		
		if (!this.event_list_loaded) {
			this.loadEventList();
		} else {
			if (!this.event_list_loaded_last.have_less)
				this.button_prev.hide();
			if (!this.event_list_loaded_last.have_more)
				this.button_next.hide();			
		}
	},
	
	loadEventList: function(start) {
		var self = this;
		var today = false;
		if (!start) {
			today = true;
			start = Math.floor((new Date()).getTime()*0.001);
		}
		
		var data = {
			start: start,
			today: today?'1':'0'
		};
		
		this.el_event_list_items.empty(); //clean current items
		$.get(this.base_url+'event-list', data, function(response) {
			self.enableNav();
			
			if (today)
				self.params.eventlist_start = 0;
			else
				self.params.eventlist_start = start;			
			
			if (response.have_more)
				self.button_next.show();
			else
				self.button_next.hide();
			
			if (response.have_less)
				self.button_prev.show();
			else
				self.button_prev.hide();
			
			if (!response.error && response.items.length > 0) {
				self.event_list_loaded_last.have_less = response.have_less;
				self.event_list_loaded_last.have_more = response.have_more;
								
				self.event_list_loaded = true;
				self.list_next_param = null;
				
				self.params.eventlist_next = response.tomorrow;
				self.params.eventlist_previous = response.yesterday;
				self.el_eventlist_title.html(response.today_str);
				
				var template;
				var item;
				var aitem;
				var i;
				var j;
				var classes;

				for (var i=0; i<response.items.length; i++) {
					classes = 'eventlist-item';
					item = response.items[i];
					template = $('#template-eventlist-item').clone().removeAttr('id');
					
					if (item.image_url == '')
						template.find('.image-list').remove();
					
					template = template.html(); //just string
					template = template.replace(/\/\*/gi, '');
					template = template.replace(/\*\//gi, '');
					
					var replace = ['date_str', 'time_str', 'color', 'title', 'etime', 'event_id', 'description', 'preset_id', 'image_url'];
					var value = "";
					
					if (i < response.items.length-1)
						classes += ' eventlist-item-middle';
					
					for (j=0; j<replace.length; j++) {
						search = '{%'+replace[j]+'%}';
						var eregi = new RegExp(search, 'g');
						var eregi2 = new RegExp('%7B%'+replace[j]+'%%7D', 'g');
						
						if (replace[j] == 'preset_id') {
							value = self.preset_id;
						} else if (replace[j] == 'title') {
							value = item[replace[j]];
							if (value.length > 40)
								value = Enjin_Core.htmlentities(value.substr(0, 40))+'...';
							else
								value = Enjin_Core.htmlentities(value);
						} else {
							value = item[replace[j]];
						
							if (value == null || typeof value == 'undefined')
								value = '';
							
							if (replace[j] != 'description')
								value = Enjin_Core.htmlentities(value);
						}
						
						template = template.replace(eregi, value);					
						template = template.replace(eregi2, value);					
					}
					
					//add to items
					self.el_event_list_items.append('<div itemid="'+item.event_id+'" class="'+classes+'">'+template+'</div>');
					
					if (!item.can_edit) {
						//remove just in case
						self.el_event_list_items.find('[itemid='+item.event_id+'] .right-links').remove();
					}
					
					var dom = self.el_event_list_items.find('.eventlist-item:last');	
					if (item.attendance.length > 0) {
						for (j=0; j<item.attendance.length; j++) {
							aitem = item.attendance[j];
							dom.find('.atending-list').append('<div class="avatar element_avatar simple verysmall">'+			
									aitem.user_avatar
									+'</div>'
							);
							
							if (j > 0 && (j+1) % 15 == 0) {
								dom.find('.atending-list').append('<br />');
							}
						}
					} else {
						dom.find('.atending-list').remove();
					}
					
					if (item.attending != '') {
						var message = '';
						if (item.attending == 'attending')
							message = "<span class='attending'>You're Attending</span>";
						if (item.attending == 'maybe')
							message = '<span class="maybe">Maybe Attending</span>';
						if (item.attending == 'not_attending')
							message = '<span class="not-attending">Not Attending</span>';
						if (item.attending == 'invited')
							message = '<span class="invited">Invited</span>';

						if (item.attending == 'confirmed')
							message = '<span class="confirmed">Confirmed</span>';
						if (item.attending == 'standby')
							message = '<span class="standby">Standby</span>';
						
						dom.find('.atending-options').html(message+' <a href="javascript:void(0);" onclick="Module_Event_Calendar.getInstance('+self.preset_id+').showEvent('+item.event_id+', '+item.etime+')">(edit)</a>');
					} else if (item.can_signup) {
						dom.find('.atending-options').html('<a href="javascript:void(0);" onclick="Module_Event_Calendar.getInstance('+self.preset_id+').showEvent('+item.event_id+', '+item.etime+')">Signup to event</a>');					
					} else {
						dom.find('.atending-options').remove();
					}
					
					//check roles
					dom.find('.role-list').hide();
					
					if (item.roles) {
						var role_html = '';
						for (j=0; j<item.roles.length; j++) {
							var role_item = item.roles[j];
							
							role_html += '<div class="itemrolesep">';
							if (role_item.icon_uploaded_url != '')
								role_html += '<div class="role-icon role-icon-img"><img src="'+role_item.icon_uploaded_url+'"  alt="'+Enjin_Core.htmlentities(role_item.name)+'"  title="'+Enjin_Core.htmlentities(role_item.name)+'" /></div>'
							else
								role_html += '<div class="role-icon role item-role item'+role_item.icon_default+'" alt="'+Enjin_Core.htmlentities(role_item.name)+'" title="'+Enjin_Core.htmlentities(role_item.name)+'"><!-- --></div>'
									
							role_html += '<div class="lbl-stats">'+role_item.total
							if (parseInt(role_item.limit_count) > 0)
								role_html += '/'+role_item.limit_count;
								
							role_html += '</div>';
							role_html += '<div class="clearing"><!-- --></div>';
							role_html += '</div>';
						}
						
						if (item.roles.length > 0) {
							dom.find('.role-list').html(role_html);
							dom.find('.role-list').show();
						}
					}
					
					
					if (response.have_more)
						self.list_next_param = item.etime;
				}				
			} else {
				self.el_event_list_items.append('<div class="message-empty">No events found</div>');
			}
			
			self.updateListMoreLink();
		}, 'json');	
	},
	
	updateListMoreLink: function() {
		if (this.list_next_param)
			this.el_list_more.show();
		else
			this.el_list_more.hide();
	},
	
	goDetailToday: function() {
		this.showEventDetail();
		this.goToday();
	},
	
	goToday: function() {		
		if (this.mode_display == 'calendar') {
			this.el_main.fullCalendar( 'today' );
		} else if (this.mode_display == 'list') {
			this.disableNav();
			this.loadEventList();
		} else if (this.mode_display == 'detail') {
			this.disableNav();
			var self = this;			
			$.get(this.base_url+'event-detail-get-today', {}, function(response) {
				self.enableNav();
				if (response) {
					Module_Event_Calendar_Manager.add(response.event_id, response.etime, response);
					self.showEvent(response.event_id, response.etime);
				}
			}, 'json');
			
		}
	},
	goPrevious: function() {		
		if (this.mode_display == 'calendar') {
			this.el_main.fullCalendar( 'prev' );
		} else if (this.mode_display == 'list') {
			this.disableNav();
			this.loadEventList(this.params.eventlist_previous);
		} else if (this.mode_display == 'detail') {
			this.disableNav();
			var self = this;
			var data = {
				start: this.detail_event_timestamp	
			};
			
			$.get(this.base_url+'event-detail-get-previous', data, function(response) {
				self.enableNav();
				if (response) {
					Module_Event_Calendar_Manager.add(response.event_id, response.etime, response);
					self.showEvent(response.event_id, response.etime);
				}
			}, 'json');
		}
	},
	goNext: function() {		
		if (this.mode_display == 'calendar') {
			this.el_main.fullCalendar( 'next' );
		} else if (this.mode_display == 'list') {
			this.disableNav();
			this.loadEventList(this.params.eventlist_next);
		} else if (this.mode_display == 'detail') {
			this.disableNav();
			var self = this;
			var data = {
				start: this.detail_event_timestamp	
			};
			
			$.get(this.base_url+'event-detail-get-next', data, function(response) {
				self.enableNav();
				if (response) {
					Module_Event_Calendar_Manager.add(response.event_id, response.etime, response);
					self.showEvent(response.event_id, response.etime);
				}
			}, 'json');			
		}
	},
	
	listReload: function() {
		this.loadEventList(this.params.eventlist_start);
	},
	
	listLoadNext: function()  {
		this.loadEventList(this.list_next_param);
	},
	
	reload: function() {
		//force to regenerate all views
		this.event_calendar_reload = true; 
		this.event_list_loaded = false; //force to render
		
		
		if (this.mode_display == 'calendar') {
			this.event_calendar_reload = false;
			this.el_main.fullCalendar( 'refetchEvents' );
		} else if (this.mode_display == 'detail') {
			//fetch main item
			this.showEvent(this.detail_event_id, this.detail_event_timestamp, true)
		} else if (this.mode_display == 'list') {
			this.listReload();
		}
	},
	
	showEventDetail: function() {
		this.mode_display = 'detail';
		this.el_event_detail.show();
		this.el_container.hide();
		this.el_event_list.hide();
		this.selectType();
	},
	
	showEvent: function(event_id, timestamp, force_reload) {
		var self = this;
		
		this.el_event_detail_attend_panel_status.hide();
		if (Module_Event_Calendar.isAdmin()) {
			Module_Event_Calendar_Admin.inviteSet(this.preset_id, event_id, timestamp);
			
			this.showEventContinue(event_id, timestamp, force_reload);
		} else if (Module_Event_Calendar.isAdminOwn())  {
			this.el_event_detail_link_invite.hide();
			this.el_event_detail_link_edit.hide();
			
    		Module_Event_Calendar_ACLS.fetch(self, self.preset_id, event_id, function(edit_type) {
    			if (edit_type != '') {
    				Module_Event_Calendar_Admin.inviteSet(self.preset_id, event_id, timestamp);
    				self.el_event_detail_link_invite.show();
    				self.el_event_detail_link_edit.show();
    			}
    			
    			self.showEventContinue(event_id, timestamp, force_reload);
    		});
		} else {
			this.el_event_detail_link_invite.hide();
			this.el_event_detail_link_edit.hide();
			
			self.showEventContinue(event_id, timestamp, force_reload);
		}
	},
	
	
	showEventContinue: function(event_id, timestamp, force_reload) {
		this.showEventDetail();
		this.detail_event_id = event_id;
		this.detail_event_timestamp = timestamp;
		
		
		//fetch main item
		Module_Event_Calendar_Manager.fetch(this, this.preset_id, event_id, timestamp, this.onEventFetched);
	},
	
	updateOwnAttendance: function(attendance, event_id, timestamp) {
		if (!event_id)
			event_id = this.detail_event_id;
		if (!timestamp)
			timestamp = this.detail_event_timestamp;
		
		var ptype = this.buildOwnAttendanceType(attendance.type, attendance.admin_displayname?attendance.admin_displayname:'');				
		var event = Module_Event_Calendar_Manager.get(event_id, timestamp);
		var show_roles = false;
		
		if (event.role_enabled) {
			if (Module_Event_Calendar.isAdmin() || Module_Event_Calendar.isAdminOwn()) {
				show_roles = true;
			} else if (event.role_userset) {
				show_roles = true;
			}
		}
		
		if (show_roles)
			this.el_event_detail_attend_panel_status.find('.link-roles').show();
		else
			this.el_event_detail_attend_panel_status.find('.link-roles').hide();
		
		if (event.characters_enable) {
			this.el_event_detail_attend_panel_status.find('.link-character').show();
			
			if (!attendance.signup_character_id) {
				ptype.type = '<a href="javascript:void(0);" onclick="Module_Event_Calendar.getInstance('+this.preset_id+').showCharactersAttendance(event)">Character required for event</a>';
			}
			
		} else {
			this.el_event_detail_attend_panel_status.find('.link-character').hide();
		}
		
		
		//update params
		/*
		if (ptype.message) {
			this.el_event_detail_attend_panel_status.find('.link-status').show();
			this.el_event_detail_attend_panel_status.find('.link-status a').text(ptype.message);
		} else {
			this.el_event_detail_attend_panel_status.find('.link-status').hide();
		}*/
		
		this.el_event_detail_attend_panel_status.find('.msg').html(ptype.type);
		this.el_event_detail_attend_panel.show();
		this.el_event_detail_attend_panel.find('.attend-form').hide();
		this.el_event_detail_attend_panel.find('.attend-status').show();
		event.own = attendance;
		Module_Event_Calendar_Manager.add(event_id, timestamp, event);
	},
	
	buildAttendanceEl: function(attendance, item_css, event_id, timestamp, can_edit_attendance) {
		var html = '';
		var event = Module_Event_Calendar_Manager.get(event_id, timestamp);
		var show_avatar = true;
		type = this.buildAttendanceType(attendance.type);
		
		if (event.characters_enable)
			item_css += ' item-character';
		
		html += '<div class="item'+item_css+'" userid="'+attendance.user_id+'">';
		html += '<div class="attending-type">';
		html += '<div class="text">';			
		html += type;
		html += '</div>';	
		
		var can_admin = Module_Event_Calendar.isAdmin() || can_edit_attendance;
		if (!can_admin  
				&& Module_Event_Calendar.isAdminOwn()
				&& Module_Event_Calendar_ACLS.get(event_id) != '') {
			can_admin = true;
		}
		
		if (can_admin) {
			html += '<div class="admin">';			
			html += '<a href="javascript:void(0);" onclick="Module_Event_Calendar.getInstance('+this.preset_id+').adminEvent(event, this, '+attendance.user_id+')"><!-- --></a>';
			html += '</div>';
		}
		
		html += '<div class="clearing"><!-- --></div>';
		html += '</div>';
		
		if (event.characters_enable && !attendance.character_id)
			show_avatar = false;
		
		if (show_avatar) {
			html += '<div class="avatar element_avatar simple verysmall">';
			html += attendance.user_avatar;
			html += '</div>';
			html += '<div class="username">';
			html += attendance.user_displayname;
			html += '</div>';
		} else {
			html += '<div class="username-not-character">';
			html += '<span class="not">No Character</span> ('+attendance.user_displayname+')';
			html += '</div>';
		}
		
		if (event.characters_enable && attendance.character_id && attendance.user_character_type) {
			html += '<div class="character-level">'+attendance.character_level+'</div>';
			html += '<div class="character-class">'+attendance.user_character_type+'</div>';
		}
		
		if (attendance.roles) {
			html += '<div class="roles">';
			
			var role_id;
			var roledata;
			var is_last = false;
			var css;
			var rolename;
			
			for (var i=0; i<attendance.roles.length; i++) {
				is_last = (i == attendance.roles.length-1)?true:false;
				role_id = attendance.roles[i];
				roledata = event.roles[role_id];
				rolename = Enjin_Core.htmlentities(roledata.name);
				
				css = 'role';
				if (is_last)
					css += ' last';
				
				if (roledata.icon_default != '0'){
					html += '<div rolename="'+rolename+'" class="'+css+' item-role item'+roledata.icon_default+'"><!-- --></div>';
				} else 
					html += '<div rolename="'+rolename+'" class="'+css+'"><img src="'+roledata.icon_uploaded_url+'" /></div>';
				
			}
			
			html += '</div>';	
		}
		
		html += '<div class="note">';
		html += this.buildSummaryNote(attendance.note);
		html += '</div>';	
		html += '<div class="clearing"><!-- --></div>';
		html += '</div>';
		
		return html;
	},
	
	buildSummaryNote: function(note, skip_entities) {
		if (note.length > 48)
			note = note.substr(0, 45)+'...';
		
		if (skip_entities)
			return note;
		
		return Enjin_Core.htmlentities(note);
	},
	
	prepareAttendanceInline: function(el, event_id, timestamp) {
		var self = this;
		
		if (!event_id)
			event_id = this.detail_event_id;
		if (!timestamp)
			timestamp = this.detail_event_timestamp;
		
		var inline = new Enjin_Editor_Inline({
			el: $(el).find('.note'),
			url_save: '/ajax.php?s=eventcalendar',
			url_params: {
				preset_id: this.preset_id,
				op: 'event-attend-note',
				event_id: event_id,
				timestamp: timestamp,
				user_id: $(el).attr('userid')
			}
		});

		$(inline).bind('beforeRenderEditor', function(evt) {
			var event = Module_Event_Calendar_Manager.get(event_id, timestamp);
			var user_id = $(el).attr('userid');
			
			for (var i=0; i<event.attendance.length; i++) {
				if (event.attendance[i].user_id == user_id) {
					inline.default_value = event.attendance[i].note;
				}
			}
		});
		
		
		$(inline).bind('startEdit', function(evt) {
			$(el).find('.note').addClass('input-text');
		});
		
		$(inline).bind('stopEdit', function(evt) {			
			$(el).find('.note').removeClass('input-text');
			var cval = $(el).find('.note').text();
			$(el).find('.note').text(self.buildSummaryNote(cval, true));
			
			var event = Module_Event_Calendar_Manager.get(event_id, timestamp);
			var user_id = $(el).attr('userid');
			
			for (var i=0; i<event.attendance.length; i++) {
				if (event.attendance[i].user_id == user_id) {
					event.attendance[i].note = cval;
				}
			}
			
			Module_Event_Calendar_Manager.add(event_id, timestamp, event);
		});
		
		
		$(el).data('editor', inline);
	},
	
	onEventFetched: function(event, timestamp) {
		var can_signup = true;
		
		var nel = this.el_event_detail_timewrapper.find('.time')
		var nel2 = this.el_event_detail_timewrapper.find('.timewrapper-countdown')
		var nel3 = this.el_event_detail_timewrapper.find('.time-non-countdown')
		nel.removeClass();
		nel.addClass('time');
		nel2.addClass('timewrapper-countdown');
		nel3.addClass('time-non-countdown');
		
		/* check attendance options */
		if (event.can_edit)
			this.el_event_detail_link_edit.show();
		
		if (event.can_edit_attendance)
			this.el_event_detail_link_invite.show();
		
		if (event.have_next)
			this.button_next.show();
		else
			this.button_next.hide();
		
		if (event.have_previous)
			this.button_prev.show();
		else
			this.button_prev.hide();
		
		this.el_event_detail_timewrapper.find('.time').addClass('time-'+event.color);
		this.el_event_detail_title.text(event.name);
		
		//just in case
		this.el_event_detail_timewrapper.find('.timewrapper-countdown .countdown').countdown('destroy'); 
		
		if (event.time_until_countdown) {
			nel3.hide();	
			this.el_event_detail_timewrapper.find('.timewrapper-countdown .countdown').countdown({
				until: new Date(parseInt(event.etime)*1000),
				compact: true, 
			    format: 'dHMS',
			    compactLabels: ['', '', '', ' days']
			}); 
			nel2.show();
		} else {
			nel3.show();
			nel2.hide();
			this.el_event_detail_time.text(event.time_until);
		}
		
		this.el_event_detail_description.html(event.description);
		
		//add all info
		this.el_event_detail_info.find('.item-event-name .info').text(event.name);
		this.el_event_detail_info.find('.item-event-start .info').text(event.time_detail_start);
		this.el_event_detail_info.find('.item-event-end .info').text(event.time_detail_end);
		
		if (event.username_created) {
			this.el_event_detail_info.find('.item-event-created').show();
			this.el_event_detail_info.find('.item-event-created .info').html(event.username_created);
		} else {
			this.el_event_detail_info.find('.item-event-created').hide();
		}
		
		//recurrence
		this.el_event_detail_info.find('.item-event-reoccurs').hide();
		
		if (event.recurrence != "none") {
			var end = parseInt(event.recurrence_time);
			if (end > 0)
				end = new Date(end*1000);
			
			var summary = Module_Event_Calendar.createSummary(event.recurrence, event.recurrence_freq, parseInt(event.recurrence_weekly_flag), end);
			this.el_event_detail_info.find('.item-event-reoccurs .info').text(summary);
			this.el_event_detail_info.find('.item-event-reoccurs').show();
		}
		
		if (event.image_url != '') {
			this.el_event_detail_image.show();
			this.el_event_detail_image.find('img').attr('src', event.image_url);
		} else
			this.el_event_detail_image.hide();
		
		if (event.can_signup == '0') {
			//hide signup part
			can_signup = false;
			this.el_event_detail_attend_panel.hide();
		} else {
			this.el_event_detail_attend_panel.show();
		}
		
		if (can_signup && (event.can_edit || event.can_edit_attendance))
			Module_Event_Calendar_Admin.inviteSet(this.preset_id, event.event_id, timestamp);
		
		
		//reset the attendance part
		this.el_event_detail_attend_list.empty()
		this.el_event_detail_attend_list_count.html(event.attendance_length);
				
		var self = this;
		var html = '';
		var attendance_total = event.attendance.length;
		
		this.el_event_detail_attend_panel.find('.attend-status').hide();
		this.el_event_detail_attend_panel.find('.attend-form').show();
		
		for (var i=0; i<event.attendance.length; i++) {
			var type = '';
			var item_css = '';						
			
			if (i == event.attendance.length-1)
				item_css = ' item-last';
			
			if ( event.attendance[i].user_id == this.params.user_id) {
				this.updateOwnAttendance(event.attendance[i], event.event_id, timestamp);
				//attendance_total--;
								
			} /* else { */
				html += this.buildAttendanceEl(event.attendance[i], item_css, 
						event.event_id, timestamp, event.can_edit_attendance);
			//}
		}
				
		this.el_event_detail_attend_list.html(html);
		
		this.el_event_detail_attend_list.find('.item').each(function(){
			var att_history = [];
			var att_history_comments = [];
			var user_id = $(this).attr('userid');
			
			if (event.attendance_history[user_id]) {
				att_history = event.attendance_history[user_id];
				
				if (event.attendance_history_comments[user_id])
					att_history_comments = event.attendance_history_comments[user_id];
				
				Enjin_Core.bindTooltip($(this).find('.avatar,.username,.attending-type'), self.buildAttendanceHistory(att_history, att_history_comments), 'm_eventcalendar-atthistory');
			}
			self.prepareAttendanceInline(this, event.event_id, timestamp);
			
			//add also to roles
			$(this).find('.roles .role').each(function(){
				Enjin_Core.bindTooltip($(this), Enjin_Core.htmlentities($(this).attr('rolename')), 'm_eventcalendar item-attending role-tooltip');
			});
		});
		
		if (event.attendance.length > 0) {
			this.el_event_detail_attend_list_container.show();
		} else {
			this.el_event_detail_attend_list_container.hide();
		}
		
		//roles part 
		this.el_event_detail_role_list_container.hide();
		if (event.role_enabled != "0" && event.role_id
				&& event.roles_stats) {
			this.el_event_detail_role_list_container.find('.text-right').hide();
			
			var role_html = '';
			for (j=0; j<event.roles_stats.length; j++) {
				var role_item = event.roles_stats[j];
				
				role_html += '<div class="itemrolesep" data-title="'+Enjin_Core.htmlentities(role_item.name)+'">';
				if (role_item.icon_uploaded_url != '')
					role_html += '<div class="role-icon role-icon-img"><img src="'+role_item.icon_uploaded_url+'" /></div>'
				else
					role_html += '<div class="role-icon role item-role item'+role_item.icon_default+'"><!-- --></div>'
						
				role_html += '<div class="lbl-stats">'+role_item.total
				if (parseInt(role_item.limit_count) > 0)
					role_html += '/'+role_item.limit_count;
					
				role_html += '</div>';
				role_html += '<div class="clearing"><!-- --></div>';
				role_html += '</div>';
			}
			
			this.el_event_detail_role_list_container.find('.block-container .role-list .listing').html(role_html);
			
			//check if user have roles
			if (event.user_roles.length > 0) {
				role_html = '';
				this.el_event_detail_role_list_container.find('.text-right .plural').hide();
				if (event.user_roles.length > 1)
					this.el_event_detail_role_list_container.find('.text-right .plural').css('display', 'inline');
				
				for (j=0; j<event.user_roles.length; j++) {
					var role_id = event.user_roles[j];
					var role_item = event.roles[role_id];
					
					if (role_item.icon_uploaded_url != '')
						role_html += '<div class="role-icon role-icon-img" data-title="'+Enjin_Core.htmlentities(role_item.name)+'"><img src="'+role_item.icon_uploaded_url+'" /></div>';
					else
						role_html += '<div class="role-icon role item-role item'+role_item.icon_default+'" data-title="'+Enjin_Core.htmlentities(role_item.name)+'"><!-- --></div>';
				}
				
				this.el_event_detail_role_list_container.find('.text-right .role-icons').html(role_html);
				this.el_event_detail_role_list_container.find('.text-right').show();
			}
			
			if (event.can_edit) {
				this.el_event_detail_role_list_container.find('.block-container .role-list .roles-link').html('<a href="javascript:void(0);" onclick="Module_Event_Calendar.getInstance('+this.preset_id+').editDetailEvent()">Set Roles</a>')
				this.el_event_detail_role_list_container.find('.block-container .role-list .roles-link').show();
			} else
				this.el_event_detail_role_list_container.find('.block-container .role-list .roles-link').hide();
			
			this.el_event_detail_role_list_container.show();
			
			this.el_event_detail_role_list_container.find('.text-right .role-icons .role-icon').each(function() {
				Enjin_Core.bindTooltip($(this), $(this).attr('data-title'), 'm_eventcalendar m_eventcalendar-stats-hover');
			});
			this.el_event_detail_role_list_container.find('.block-container .role-list .listing .itemrolesep').each(function() {
				Enjin_Core.bindTooltip($(this), $(this).attr('data-title'), 'm_eventcalendar m_eventcalendar-stats-hover');
			});
		}		
		
		this.loadComment(event.event_id, timestamp);
	},
	
	buildAttendanceHistory: function(history, history_comments) {
		var css = '';
		var html = '<div class="history-attendance">';
		var at;
		
		if (history_comments.user) {
			html += '<div class="comment-from">';
			html += '<div class="ptitle"><span class="username">'+history_comments.user.displayname+'</span> wrote on '+history_comments.user.when+'</div>';
			html += '<div class="comment">'+history_comments.user.comment+'</div>';
			html += '</div>';
		}
		
		if (history_comments.admin) {
			html += '<div class="comment-from">';
			html += '<div class="ptitle"><span class="username">'+history_comments.admin.displayname+'</span> wrote on '+history_comments.admin.when+'</div>';
			html += '<div class="comment">'+history_comments.admin.comment+'</div>';
			html += '</div>';
		}
		
		
		html += '<div class="history-attendance-items">';
		for (var i=0; i<history.length; i++) {
			css = 'item-history';
			at = history[i];
			if (i == history.length - 1)
				css += ' item-history-'+at.type;
			
			html += '<div class="'+css+'"><div class="type">'+at.type_str+'</div><div class="created">'+at.created+'</div></div>';
		}
		
		html += '</div></div>';
		return html;
	},
	
	buildOwnAttendanceType: function(type, admin_displayname) {
		var htype = '';
		var update_msg = 'Change status';
		
		switch(type) {
			case 'attending':
				htype = '<span class="attending">Attending Event</span>';
				break;
			case 'maybe':
				htype = '<span class="maybe">Maybe Attending Event</span>';
				break;
			case 'not_attending':
				htype = '<span class="not-attending">Not attending Event</span>';
				break;
			case 'invited':
				htype = '<span class="invited">You have been invited to this event</span>';
				update_msg = 'Update your status';
				break;
			case 'confirmed':
				if (admin_displayname)
					htype = '<span class="confirmed">Confirmed ('+admin_displayname+')</span>';
				else
					htype = '<span class="confirmed">Confirmed</span>';
				
				update_msg = 'Update your status';
				break;
			case 'standby':
				if (admin_displayname)
					htype = '<span class="standby">Standby ('+admin_displayname+')</span>';
				else
					htype = '<span class="standby">Standby</span>';
				update_msg = 'Update your status';
				break;
			case 'noshow':
				if (admin_displayname)
					htype = '<span class="noshow">No Show ('+admin_displayname+')</span>';
				else
					htype = '<span class="noshow">No Show</span>';
				update_msg = null;
				break;
		}
		
		return {type: htype, message: update_msg};
	},
	
	buildAttendanceType: function (type) {
		var htype = '';
		switch(type) {
			case 'attending':
				htype = '<span class="attending">Attending</span>';
				break;
			case 'maybe':
				htype = '<span class="maybe">Maybe</span>';
				break;
			case 'not_attending':
				htype = '<span class="not-attending">Not Attending</span>';
				break;
			case 'invited':
				htype = '<span class="invited">Invited</span>';
				break;
			case 'confirmed':
				htype = '<span class="confirmed">Confirmed</span>';
				break;		
			case 'standby':
				htype = '<span class="standby">Stand By</span>';
				break;		
			case 'noshow':
				htype = '<span class="noshow">No Show</span>';
				break;
		}
		
		return htype;
	},
	
	editDetailEvent: function() {
		Module_Event_Calendar_Admin.eventEditByID(this.preset_id, this.detail_event_id);
	},
	
	buildCommentHash: function(event_id, timestamp) {
		return "tim-"+event_id+"-"+timestamp;
	},
	
	loadComment: function(event_id, timestamp) {
		var hash = this.buildCommentHash(event_id, timestamp);
		var event = Module_Event_Calendar_Manager.get(event_id, timestamp);
		
		//hide other containers
		this.el_event_detail_comments.find('.item-comment').hide();
		this.el_event_detail_comments.empty();
		
		if (event.allow_comment == '1') {
			//load the comment				
			this.el_event_detail_comments.enjinComments( {comment_cid: event.comment_cid,disableAdd:!event.comment_allowed} ); 
		}
	},
	
	changeAttend: function(evt) {
		//show again form
		var event = Module_Event_Calendar_Manager.get(this.detail_event_id, this.detail_event_timestamp);
		Enjin_Core.stopBubble(evt);
		Enjin_Core.prepareEvent(evt);
		
		//hide the current status 
		$('.m_eventcalendar.popup-attendance-own-set-type .type').show();
		$('.m_eventcalendar.popup-attendance-own-set-type .type-'+event.own.type).hide();
		$('.m_eventcalendar.popup-attendance-own-set-type').appendTo($(document.body));
		$('.m_eventcalendar.popup-attendance-own-set-type').css('top', evt.pageY);
		$('.m_eventcalendar.popup-attendance-own-set-type').css('left', evt.pageX+10);		
		
		$('.m_eventcalendar.popup-attendance-own-set-type').attr('presetid', this.preset_id);
		$('.m_eventcalendar.popup-attendance-own-set-type').show();
	},
	
	signupEvent: function() {		
		var self = this;
		var data = {
			preset_id: this.preset_id,
			event_id: this.detail_event_id,
			timestamp: this.detail_event_timestamp,
			op: 'event-attend'
		}
		
		$.post('/ajax.php?s=eventcalendar', data, function(response) {
			if (response && response.error == '') {
				//update event
				var attendance_found = false;
				var event = Module_Event_Calendar_Manager.get(self.detail_event_id, self.detail_event_timestamp);
				event.own = response.attendance;
				
				for (var i=0; i<event.attendance.length; i++) {
					if (event.attendance[i].user_id == event.own.user_id) {
						event.attendance[i] = event.own;
						attendance_found = true;
						break;
					}
				}
				
				if (!attendance_found)
					event.attendance.push(event.own);
				
				Module_Event_Calendar_Manager.add(event.event_id, self.detail_event_timestamp, event);
				self.updateOwnAttendance(event.own, self.detail_event_id, self.detail_event_timestamp);
				
				//if have in list, update
				var el = self.el_event_detail_attend_list.find('.item[userid='+event.own.user_id+']');
				if (el.length > 0) {
					var htype = self.buildAttendanceType(event.own.type);
					el.find('.attending-type .text').html(htype);					
					el.find('.note').text(event.own.note);
				} else {
					//create
					var eel = self.buildAttendanceEl(event.own, ' item-last', self.detail_event_id, self.detail_event_timestamp);
					
					//remove previous "last"
					self.el_event_detail_attend_list.find('.item').removeClass('item-last');
					self.el_event_detail_attend_list.append(eel);
					
					el = self.el_event_detail_attend_list.find('.item[userid='+event.own.user_id+']');
					self.prepareAttendanceInline(el);
					
					//just in case 
					self.el_event_detail_attend_list_container.show();
				}
			} else {
				Enjin_Core.alert(response.error);
			}
		}, 'json');		
	},
	
	adminEvent: function(event, el, user_id) {
		Enjin_Core.stopBubble(event);
		
		this.detail_event_admin_user_id = user_id;
		
		var event = Module_Event_Calendar_Manager.get(this.detail_event_id, this.detail_event_timestamp);
		var offset = $(el).offset();
		
		if (event.role_enabled == '1' && event.roles_length > 0) {
			//build roles
			var el_role_icon;
			var el_role;
			var role_data;
			$('.m_eventcalendar.popup-admin-edit .roles-part').show();
			$('.m_eventcalendar.popup-admin-edit .roles-part .roles-list').empty();
			
			jQuery.each(event.roles, function(key, role_data) {
				
				
				if (role_data.icon_uploaded == '1')
					el_role_icon = '<div class="role-icon"><img src="'+role_data.icon_uploaded_url+'" /></div>';
				else
					el_role_icon = '<div class="role-icon"><div class="item-role item'+role_data.icon_default+'"><!-- --></div></div>';
				
				
				el_role = '<div class="link irole">'+
				el_role_icon+
				'<div class="name"><a href="javascript:void(0);" onclick="Module_Event_Calendar_Admin.adminEventRoleAdd('+role_data.evc_role_item_id+')">'+
				Enjin_Core.htmlentities(role_data.name)+
				'</a></div><div class="clearing"><!-- --></div></div>';
				$('.m_eventcalendar.popup-admin-edit .roles-part .roles-list').append(el_role);
			});
		} else {
			$('.m_eventcalendar.popup-admin-edit .roles-part').hide();
		}
		
		$('.m_eventcalendar.popup-admin-edit').show();
		$('.m_eventcalendar.popup-admin-edit').css('top', offset.top);
		$('.m_eventcalendar.popup-admin-edit').css('left', offset.left);
		
		$(document).one('click', function() {
			$('.m_eventcalendar.popup-admin-edit').hide();
		});
		
		var att = null;
		for (var i=0; i<event.attendance.length; i++) {
			if (event.attendance[i].user_id == user_id) {
				att = event.attendance[i];
				break;
			}
		}
		
		$('.m_eventcalendar.popup-admin-edit .type').show(); //show all options
		$('.m_eventcalendar.popup-admin-edit .type-remove-invite').hide();
		
		if (att) {
			$('.m_eventcalendar.popup-admin-edit .type-'+att.type).hide(); //cannot set the same status
			$('.m_eventcalendar.popup-admin-edit .type-noshow').hide();
			
			if (event.can_set_noshow && att.type != 'noshow')
				$('.m_eventcalendar.popup-admin-edit .type-noshow').show();
			
			//if is invited, show the link to remove the invitation, otherwise don't show it
			if (att.type == 'invited')
				$('.m_eventcalendar.popup-admin-edit .type-remove-invite').show();				
		}
		
		Module_Event_Calendar_Admin.adminEventPopup(this.preset_id);
	},
	
	setType: function(type) {
		$('.m_eventcalendar.popup-attendance-own-set-type').hide();
		this.adminEventSetType(type, true);
	},
	
	adminEventChangeNote: function() {
		var event = Module_Event_Calendar_Manager.get(this.detail_event_id, this.detail_event_timestamp);
		var item = this.el_event_detail_attend_list.find('[userid='+this.detail_event_admin_user_id+']');
		this.el_event_detail_attend_list.find('[userid='+this.detail_event_admin_user_id+']').data('editor').showEditor();
	},
	adminEventSetType: function(type, use_logged_user) {
		var event = Module_Event_Calendar_Manager.get(this.detail_event_id, this.detail_event_timestamp);
		var self = this;
		
		//save
		var user_id = use_logged_user?this.params.user_id:this.detail_event_admin_user_id;
		var data = {
			preset_id: this.preset_id,
			op: 'event-attending-type',
			event_id: this.detail_event_id,
			timestamp: this.detail_event_timestamp,
			user_id: user_id,
			type: type
		};		
		$.post('/ajax.php?s=eventcalendar', data, function(response) {
			//change status
			var evattendance = null;
			
			//update event
			for (var i=0; i<event.attendance.length; i++) {
				if (event.attendance[i].user_id == user_id) {
					event.attendance[i].type = type;
					evattendance = event.attendance[i]; 
					break;
				}
			}
			
			if (evattendance && evattendance.user_id == self.params.user_id) {
				self.updateOwnAttendance(evattendance);
			}
			
			Module_Event_Calendar_Manager.add(this.detail_event_id, this.detail_event_timestamp, event);
			
			if (type == 'remove-invitation') {
				self.el_event_detail_attend_list.find('[userid='+user_id+']').remove();
				self.el_event_detail_attend_list.find('.item:last').addClass('item-last');
			} else {
				var htype = self.buildAttendanceType(type);
				self.el_event_detail_attend_list.find('[userid='+user_id+'] .attending-type .text').html(htype);
				
				self.invalidateViewList();
			}
		}, 'json');		
	},
	
	changeRole: function(evt) {
		//build roles
		var event = Module_Event_Calendar_Manager.get(this.detail_event_id, this.detail_event_timestamp);
		var el_role_icon;
		var el_role;
		var role_data;
		var self = this;
		
		Enjin_Core.stopBubble(evt);
		
		//put in proper position
		Enjin_Core.prepareEvent(evt);
		$('.m_eventcalendar.popup-own-roles').appendTo(document.body);
		$('.m_eventcalendar.popup-own-roles').css('top', evt.pageY);
		$('.m_eventcalendar.popup-own-roles').css('left', evt.pageX+10);		
		$('.m_eventcalendar.popup-own-roles .roles').empty();
		
		jQuery.each(event.roles, function(key, role_data) {
			if (role_data.icon_uploaded == '1')
				el_role_icon = '<div class="role-icon"><img src="'+role_data.icon_uploaded_url+'" /></div>';
			else
				el_role_icon = '<div class="role-icon"><div class="item-role item'+role_data.icon_default+'"><!-- --></div></div>';
			
			
			el_role = '<div class="link irole">'+
			el_role_icon+
			'<div class="name"><a href="javascript:void(0);" onclick="Module_Event_Calendar.getInstance('+self.preset_id+').addRoleUser('+role_data.evc_role_item_id+', 1)">'+
			Enjin_Core.htmlentities(role_data.name)+
			'</a></div><div class="clearing"><!-- --></div></div>';
			$('.m_eventcalendar.popup-own-roles .roles').append(el_role);
		});
		
		$('.m_eventcalendar.popup-own-roles .roles').append('<div class="link-clear"><a href="javascript:void(0);" onclick="Module_Event_Calendar.getInstance('+self.preset_id+').clearRoleUser()">Clear Roles</a></div>');
		
		$('.m_eventcalendar.popup-own-roles').show();
	},
	
	clearRoleUser: function() {
		var data = {
			op: 'role-event-clear',
			preset_id: this.preset_id,
			event_id: this.detail_event_id,
			timestamp: this.detail_event_timestamp
		};
		
		$.post('/ajax.php?s=eventcalendar', data, function(response) {
			if (response.error != '0') {
				Enjin_Core.alert(response.message);
			} else {
				//maybe do an optimized way
				$('.m_eventcalendar.popup-own-roles').hide();
				Module_Event_Calendar_Manager.invalidate(data.event_id);
				Module_Event_Calendar.getInstance(data.preset_id).showEvent(data.event_id, data.timestamp);
			}
		}, 'json');	
	},
	
	addRoleUser: function(role_item_id, force_user) {
		var mode_admin = (Module_Event_Calendar.isAdmin() || Module_Event_Calendar.isAdminOwn())?1:0;
		if (force_user) mode_admin = 0;
		
		var data = {
			op: 'role-event-add',
			preset_id: this.preset_id,
			event_id: this.detail_event_id,
			timestamp: this.detail_event_timestamp,
			role_item_id: role_item_id,
			mode_admin: mode_admin
		};
		
		$.post('/ajax.php?s=eventcalendar', data, function(response) {
			if (response.error != '0') {
				Enjin_Core.alert(response.message);
			} else {
				//maybe do an optimized way
				$('.m_eventcalendar.popup-own-roles').hide();
				Module_Event_Calendar_Manager.invalidate(data.event_id);
				Module_Event_Calendar.getInstance(data.preset_id).invalidateViewCalendar();
				Module_Event_Calendar.getInstance(data.preset_id).invalidateViewList();
				Module_Event_Calendar.getInstance(data.preset_id).showEvent(data.event_id, data.timestamp);
			}
		}, 'json');		
	},
	
	editAttendanceNote: function(evt) {
		var el = $('.m_eventcalendar.popup-attendance-own-edit-caption');
		Enjin_Core.stopBubble(evt);
		Enjin_Core.prepareEvent(evt);
		
		var event = Module_Event_Calendar_Manager.get(this.detail_event_id, this.detail_event_timestamp);
		el.find('input[type=text]').val(event.own.note);
		
		el.show();
		el.find('input[type=text]').focus();
		
		//put in proper position
		//@todo check proper position
		el.appendTo(document.body);
		el.css('top', evt.pageY);
		el.css('left', evt.pageX - el.width());
	},
	
	showCharactersAttendance: function(evt) {
		var el = $('.m_eventcalendar.popup-own-characters');
		Enjin_Core.stopBubble(evt);
		Enjin_Core.prepareEvent(evt);
		
		el.find('.inner .items').empty();
		var event = Module_Event_Calendar_Manager.get(this.detail_event_id, this.detail_event_timestamp);
		jQuery.each(event.user_characters, function(key, character) {
			var html = '<div class="item" charid="'+character.character_id+'">';
			html += '<div class="avatar element_avatar simple verysmall">'+character.avatar+'</div>';
			html += '<div class="name"><a href="javascript:void(0);" onclick="Module_Event_Calendar.getInstance('+event.preset_id+').setAttendanceCharacter('+character.character_id+')">'+character.name+'</a></div>';
			html += '<div class="clearing"><!-- --></div>';
			html += '</div>';
			el.find('.inner .items').append(html);
		});
		
		
		el.show();
		
		//put in proper position
		//@todo check proper position
		el.appendTo(document.body);
		el.css('top', evt.pageY);
		el.css('left', evt.pageX+10);
	},
	
	setAttendanceCharacter: function(character_id) {
		$('.m_eventcalendar.popup-own-characters').hide();
		//move character avatar and name into attendance
		var avatar = $('.m_eventcalendar.popup-own-characters').find('[charid='+character_id+'] .avatar').html();
		var name = $('.m_eventcalendar.popup-own-characters').find('[charid='+character_id+'] .name a').html();
		
		var self = this;
		var event = Module_Event_Calendar_Manager.get(this.detail_event_id, this.detail_event_timestamp);
		
		event.own.character_id = character_id;
		event.own.signup_character_id = character_id;
		event.own.user_avatar = avatar;
		event.own.user_displayname = name;
		Module_Event_Calendar_Manager.add(this.detail_event_id, this.detail_event_timestamp, event);
		
		this.el_event_detail_attend_list.find('.item[userid='+this.params.user_id+'] .avatar').html(avatar);
		this.el_event_detail_attend_list.find('.item[userid='+this.params.user_id+'] .username a').html(name);
		
		//backend update
		var data = {
			preset_id: this.preset_id,
			op: 'event-character-set',
			event_id: this.detail_event_id,
			timestamp: this.detail_event_timestamp,
			character_id: character_id
		};
		
		$.post('/ajax.php?s=eventcalendar', data, function(response) {
			self.updateOwnAttendance(event.own, self.detail_event_id, self.detail_event_timestamp);
		}, 'json');
	}
}
