<%@ taglib uri="/WEB-INF/tlds/webrun.tld" prefix="webrun"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page import="wfr.com.*,wfr.sys.*,wfr.sys.HTMLInterface.*, wfr.rules.WFRAvailableRuleType"%>
<%@ page import="java.util.*"%>
<%@ page import="wfr.exceptions.*"%>
<%@ page import="wfr.util.Logger" %>
<%@ page import="java.io.PrintWriter"%>
<%@ page import="wfr.util.Functions"%>
<%@ page import="wfr.util.WFRConfig"%>
<%@ page import="wfr.util.Resources"%>
<%@ page import="wfr.util.JS"%>
<%!
public String addCalendarBody(int index, String code) {
	String output = "\n\t<div id='calendar-" + code + "' class=\"calendar calendar" + (index > 0 ? "-right" : "") + "\"></div>\n";
	return output;
}
public String getTimeParam(String pName, String defValue, HttpServletRequest request) {
	String value = defValue;
	if((request.getParameter(pName) != null)&&(!"".equals(request.getParameter(pName)))) {
		value = request.getParameter(pName);
		if(value.indexOf(":") < 0) {
			value += ":00";
		}
	}
	return value;
}

public String addCalendarScript(String code, String title, HttpServletRequest request) {
	String minTime = getTimeParam("minTime", "00:00:00", request);
	String maxTime = getTimeParam("maxTime", "24:00:00", request);
	
	String output = "\n" + "calendar_l2s_eventos['" + code + "'] = false;\n" +
	"\n$('#calendar-" + code + "').fullCalendar({\n"+
	"			theme: true,\n" + 
	"			lang: 'pt-br',\n" +
	"			header: {\n" +
	"				left: '',\n" +
	"				center: '',\n" +
	"				right: ''\n" +
	"			},\n" +
	"			minTime: '" + minTime + "',\n" +
	"			maxTime: '" + maxTime + "',\n" +
	"			columnFormat: '[" + title + "]',\n" +
	"			height: (new moment('"+maxTime+ "').subtract(new moment('"+minTime+ "')) + 1) * 50,\n" +
	"			defaultView: 'agendaDay',\n" +
	"			axisFormat: 'HH:mm',\n" +
	"			eventLimit: false,\n" +
	"			editable: false,\n" +
	"			events: function (start, end, timezone, callback) {\n" +
	"				var onGetData = getURLParam('onGetData');\n" +
	"				var startF = _calendarFormatDateTime(start);\n" +
	"				var endF = _calendarFormatDateTime(end);\n" +
	"				var events = callFlow(onGetData, [startF, endF, '" + code + "']);\n" +
	"				var evtArray = eval(events);\n" +
	"				_calendarSetEvents(evtArray, '" + code + "');\n" +
	"				callback(evtArray);\n" +
	"			},\n" +
	"			dayClick: function(date, jsEvent, view) {\n" +
	"				var onDayClick = getURLParam('onDayClick');\n" +
	"				if(!isNull(onDayClick)) {\n" +
	"					callFlow(onDayClick, [_calendarFormatDateTime(date), !date.hasTime(), '" + code + "']);\n" +
	"				}\n" +
	"			},\n" +
	"			eventClick: function(event, jsEvent, view) {\n" +
	"				if(event.blockEvent) return;//Não executa se for evento de bloqueio\n" +
	"					var onEventClick = getURLParam('onEventClick');\n" +
	"					if(!isNull(onEventClick)) {\n" +
	"		            callFlow(onEventClick, [event.id, '" + code + "']);\n" +
	"				  }\n" +
	"			},\n" +
	"			eventResize: function (event, delta, revertFunc, jsEvent, ui, view) {\n" +
	"				var onEventChange = getURLParam('onEventChange');\n" +
	"				if(!isNull(onEventChange)) {\n" +
	"					var result = callFlow(onEventChange, [event.id, event.title, delta.asMinutes(), _calendarFormatDateTime(event.start), _calendarFormatDateTime(event.end), false, '" + code + "']);\n" +
	"					if(result == 'CANCEL') {\n" +
	"					revertFunc();\n" +
	"					}\n" +
	"				}\n" +
	"			},\n" +
	"			eventDrop: function (event, delta, revertFunc, jsEvent, ui, view) {\n" +
	"				if(_calendarIsDayBlocked(event.start, event.allDay, '" + code + "')) {\n" +
	"					revertFunc();\n" +
	"					return;\n" +
	"				}\n" +
	"				var onEventChange = getURLParam('onEventChange');\n" +
	"				if(!isNull(onEventChange)) {\n" +
	"					var result = callFlow(onEventChange, [event.id, event.title, delta.asMinutes(), _calendarFormatDateTime(event.start), _calendarFormatDateTime(event.end), event.allDay, '" + code + "']);\n" +
	"					if(result == 'CANCEL') {\n" +
	"						revertFunc();\n" +
	"					}\n" +
	"				}\n" +
	"		},\n" +
	"		editable: true,\n" +
	"		droppable: true,\n" +
	"		dropAccept: function(e) {\n" +
	"			var event = $(e).data('event');\n" +
	"			console.log(event.calendarId + ' ' + (event.calendarId != '" + code + "'));\n" +
	"			return (event.calendarId != '" + code + "');\n" +
	"		},\n" +
	"		drop: function() {\n" +
	"			var event = $(this).data('event');\n" +
	"			if(event && event.calendarId) {\n" +
	"				$('#calendar-' + event.calendarId).fullCalendar('removeEvents', event.id);\n" +
	"			}\n" +
	"		},\n" +
	"		eventAfterRender: function(event, element, view) {\n" +
	"			$(element).data('event', {id: event.id, calendarId: '"+code+"', title: event.title, stick: false, backgroundColor: event.backgroundColor, borderColor: event.borderColor, textColor: event.textColor, description: event.description});\n" +
	"			$(element).draggable({\n" +
	"				zIndex: 99999,\n" +
	"				revert: false,\n" +
	"				appendTo: '#calendarios',\n" +
	"				helper: function() { var d = $(this).clone();\n" +
	"				$(d).height( $(this).height() + 'px' );\n" +
	"				$(d).width( $(this).width() + 'px' );\n" +
	"				return d; },\n" +
	"				helper2: 'clone',\n" +
	"				helper1: function() { var d = $('<div></div>');\n" +
	"				d.append(event.title);\n" +
	"				return d; },\n" +
	"				revertDuration: 0\n" +
	"			});\n" +
	"		},\n" +
	"		});\n\n";
	return output;
}
%>
<%
	int numCalendarios = 1;
	StringBuilder scriptContent = new StringBuilder();
	StringBuilder bodyContent = new StringBuilder();
	Resources resources = Resources.getInstance(request);
	Logger logger = Logger.getLogger(this.getClass());
	WFRSystem system = null;
	AccessType access = null;
	String sys = request.getParameter("sys");
	HTMLInterface htmlInterface = null;
	HTMLAction action = null;
	try {
		htmlInterface = HTMLInterface.getInstance(request);   
		pageContext.setAttribute("interface", htmlInterface);
		access = htmlInterface.getAccess();
		system = htmlInterface.getSystem();
		request.setAttribute("sys", system);
		request.setAttribute("userName", htmlInterface.getUser());
		wfr.database.DBConnection connection = null;
		wfr.sys.WFRData data = new wfr.sys.WFRData(system);
		if (data != null) {
			try {
				connection = data.connection();       
				Map<String, Boolean> subs = connection.checkAllConnection();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		wfr.rules.Variant[] paramsArray = new wfr.rules.Variant[3];
		paramsArray[0] = wfr.rules.Variant.VARIANT_NULL;
		paramsArray[1] = wfr.rules.Variant.VARIANT_NULL;
		paramsArray[2] = wfr.rules.VariantPool.get("LISTA-CALENDARIOS");

		String ruleName = request.getParameter("onGetData");
		wfr.rules.WFRRuleClient client = new wfr.rules.WFRRuleClient(system, data, null, null);
		wfr.rules.WFRRule rule = system.getRuleManager().getRuleClass(ruleName, client, connection, new wfr.sys.WFRFormData(), false);
		try {
			if (connection != null) {
				connection.startTransactionIfNecessary();
			}

			wfr.rules.Variant rResult = rule.start(paramsArray);
			/*out.write(rResult.getClass().getName());
			out.write(rResult.getString());*/
			List elementList = (List) rResult.getObject();
			if(elementList == null) {
				//out.write("-----NULL------");
			} else {
				numCalendarios = elementList.size();
				for(int i = 0; i < numCalendarios; i++) {
					List dadosItem = (List) elementList.get(i);
					scriptContent.append(addCalendarScript(String.valueOf(dadosItem.get(0)), String.valueOf(dadosItem.get(1)), request));
					bodyContent.append(addCalendarBody(i, String.valueOf(dadosItem.get(0))));
				}
			}

			if (connection != null) {
				connection.commitTransaction();
			}
		} catch (Exception execEx) {
			if (connection != null) {
				connection.rollbackTransaction();
			}
			execEx.printStackTrace();
			throw execEx;
		}
	} catch (Exception ruleEx) {
		out.write("ERRO: " + ruleEx);
		ruleEx.printStackTrace(new java.io.PrintWriter(out));
	}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<!--[if IE]><base href="<% 
String baseURL = request.getRequestURL().toString().replace("/l2s/calendar/index.jsp", "/");
out.print(baseURL); %>"></base><![endif]-->
<!--[if !IE]>--><base href="../.." /><!--<![endif]-->
<link rel='stylesheet' type='text/css' href='l2s/calendar/themes/<% String theme = request.getParameter("theme"); if(theme == null || theme.equals("")) { out.print("cupertino"); }  else { out.print(theme); } %>/theme.css' />
<link rel='stylesheet' type='text/css' href='l2s/calendar/fullcalendar/fullcalendar.css' />
<link rel='stylesheet' type='text/css' href='l2s/calendar/fullcalendar/fullcalendar.print.css' media='print' />
<!--<link rel='stylesheet' type='text/css' href='l2s/calendar/qtip/jquery.qtip.min.css' />-->
<script type="text/javascript" src="l2s/commons/core.js"></script>
<script type='text/javascript' src='l2s/calendar/jquery/jquery.js'></script>
<script type='text/javascript' src='l2s/calendar/jquery/jquery-ui.js'></script>
<script type='text/javascript' src='l2s/calendar/jquery/moment.min.js'></script>
<script type='text/javascript' src='l2s/calendar/fullcalendar/fullcalendar.min.js'></script>
<script type='text/javascript' src='l2s/calendar/fullcalendar/lang-all.js'></script>
<!--<script type='text/javascript' src='l2s/calendar/qtip/jquery.qtip.min.js'></script>
<script type='text/javascript' src='l2s/calendar/qtip/imagesloaded.pkg.min.js'></script>-->
<script type='text/javascript' src='l2s/calendar/calendar.js.jsp'></script>
<script type='text/javascript'>
$(document).ready(function() {
<%=scriptContent%>
});
</script>
<style>

	body {
		margin: 0px 0px;
		padding: 0px;
		font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif;
		font-size: 14px;
		border-spacing: 0px;
	}

	table {
		padding: 0px;
		border: none;
		border-spacing: 0px;
	}

	.calendar {
		min-width: 250px;
		max-width: 900px;
		margin: 0px auto;
		margin-top: -30px;
	}
	
	.calendar-right {
		min-width: 150px;
		max-width: 900px;
		margin: 0px auto;
		margin-top: -30px;
	}

	.calendar-right * .fc-axis {
		display: none;
	}
	
	.fc-day-header {
		white-space: nowrap;
		overflow: hidden;
	}

	.ui-widget-header {
		white-space: nowrap;
		overflow: hidden;
	}

	#calendarios {
		width: 100%;
		min-width: <%=numCalendarios*150+70%>px;
		display: flex;
		flex-flow: row nowrap;
		justify-content: space-around;
	}

	#calendarios > div {
		width: calc(100% / <%=numCalendarios%>);
	}

	.moverItem {
		width: 100px;
		heigth: 80px;
	}
</style>
</head>
<body>
<div id="calendarios">
<%=bodyContent%>
</div>
<script type='text/javascript'>
document._calendar = {
  refresh: function () {
	$( ".calendar" ).each(function( i ) {
		$(this).fullCalendar('refetchEvents');
	});
  },
  gotoDate: function (date) {
	if(typeof date == 'string') {
	  date = new moment(date, "DD/MM/YYYY");
	} else {
	  date = new moment(new Date(date));
	}
	$( ".calendar" ).each(function( i ) {
		$(this).fullCalendar('gotoDate', date);
	});
  },
  changeView: function (format) {
	$( ".calendar" ).each(function( i ) {
		$(this).fullCalendar('changeView', _calendarConvertDescriptionToView(format));
	});
  }
}
</script>
</body>
</html>