<%--
 * Copyright by Intland Software
 *
 * All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of Intland Software. ("Confidential Information"). You
 * shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement
 * you entered into with Intland.
 *
 * $Revision$ $Date$
--%>

<%@ taglib uri="jstl-c" prefix="c" %>

<%--
	JSP fragment for getting notifications when somebody else modified the current identifiable.
 --%>

<%@page import="com.intland.codebeamer.security.ProjectRequestWrapper"%>
<%@page import="com.intland.codebeamer.persistence.dto.base.IdentifiableDto"%>
<%@page import="com.intland.codebeamer.remoting.GroupTypeClassUtils"%>

<%
	Object projectAware = request.getAttribute("PROJECT_AWARE_DTO");
	if (projectAware != null && projectAware instanceof IdentifiableDto) {
		Integer groupType = GroupTypeClassUtils.objectToGroupType(projectAware);
		Integer id = ((IdentifiableDto) projectAware).getId();
		pageContext.setAttribute("groupType", groupType);
		pageContext.setAttribute("id", id);
	}
%>

<c:if test="${! (empty groupType || empty id)}">
	<script type="text/javascript">
	<!--
		var ajaxEventWatcher = {

			/**
			 * The requency how often the ajax query is executed.
			 * This should be less than half of the AjaxEventService.retainEvents to avoid event-loss
			 */
			freq: 10*1000,

			init: function(groupType, id, since) {
				YAHOO.lang.later(ajaxEventWatcher.freq, null, function() { ajaxEventWatcher.queryEvents(groupType, id, since); }, null, true /* repeat */);
			},

			/**
			 * Query the change events from the server
			 */
			queryEvents: function(groupType, id, since) {
				var url = "<c:url value='/ajax/queryEvents.spr'/>";
					url += "?groupType=" + groupType + "&id=" + id + "&since=" + since;
				var callback = {
						cache: false,
					 	success: function(o) {
				 			if (o.responseText != null && o.responseText != "") {
					 			ajaxEventWatcher.showChangeEvent(o.responseText);
				 			}
				 		},
					  	failure: function(o) {/* nothing */}
					  } ;
				var query = YAHOO.util.Connect.asyncRequest('GET', url, callback);
			},

			/**
			 * Show the change-event
			 * @param changeEvent the event message
			 */
			showChangeEvent: function(changeEvent) {
				var msg = "This entity has been <b>" + changeEvent + "</b> meanwhile.";
				// only offer "refresh" link for GET methods, the POST request should not be resent!
				if ("GET" == "<%=request.getMethod()%>") {
					msg += "&nbsp; Do you want to <a href='#' onclick='window.location.reload(); return false;' title='Click to refresh'>refresh</a> it?";
				}
				GlobalMessages.showMessage("warning", msg);
			}

		};

		ajaxEventWatcher.init(${groupType}, ${id}, <%=System.currentTimeMillis()%>);
	//-->
	</script>
</c:if>
