<%@ page language="java" contentType="text/xml; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page trimDirectiveWhitespaces="true" %>
<%@ page import="org.crosswire.community.projects.ntmss.data.ProjectManagement" %>
<%@ page import="org.crosswire.community.projects.ntmss.data.ProjectManagement.Project" %>
<%
response.setContentType("text/xml");
%>
<Module>
  <ModulePrefs
	title="Project Status"
	title_url="http://ntvmr.uni-muenster.de"
	author_email="scribe777@gmail.com"
	author="Institut für neutestamentliche Textforschung"
	description="Show Project Assignments and Progress"
	screenshot="http://ntvmr.uni-muenster.de/community/images/listescreenshot.png"
	thumbnail="http://ntvmr.uni-muenster.de/community/images/pageicon.gif"
	scrolling="false"
   >
  <Optional feature="pubsub-2">
  <Param name="topics">
    <![CDATA[ 
    ]]>
  </Param>
</Optional>
  <Optional feature="dynamic-height"/>
  <Optional feature="views"/>
  <Optional feature="opensocial-0.8"/>
</ModulePrefs>

<UserPref name="height" datatype="enum" display_name="Gadget Height" default_value="-1">
	<EnumValue value="200" display_value="Short"/>
	<EnumValue value="400" display_value="Medium"/>
	<EnumValue value="600" display_value="Tall"/>
	<EnumValue value="-1" display_value="Dynamic"/>
</UserPref>

<UserPref name="project" datatype="enum" display_name="Project" default_value="-1">
	<EnumValue value="-1" display_value="None"/>
	<EnumValue value="0" display_value="Indexing"/>
<%
	for (Project p : ProjectManagement.getProjects()) {
%>
	<EnumValue value="<%=p.getProjectID()%>" display_value="<%=p.getProjectName()%>"/>
<%
	}
%>
</UserPref>

<Content type="html">
<![CDATA[
<?xml version="1.0" encoding="utf-8"?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US">
<head>
	<title>Project Status</title>

	<link rel="stylesheet" type="text/css" href="/community/js/jquery-ui/jquery-ui.css"/>

	<script type="text/javascript" src="/community/js/jquery/jquery.min.js"></script>
	<script type="text/javascript" src="/community/js/jquery-ui/jquery-ui.min.js"></script>
	<script type="text/javascript" src="/community/js/URI.min.js"></script>
	<script type="text/javascript" src="/community/js/jquery/jquery.cookie.js"></script>
	<script type="text/javascript" src="/community/js/vmr-common.js"></script>

<script type="text/javascript">

var MARGIN=0;
var projectID = 0;
var projectName = '';
var projectXML = null;
var siteName = null;

var isAdmin = false;
var isManager = false;

var allowVolunteers = false;


</script>
<style type="text/css">
<!--

/* seems this has trouble loading a background image via opensocial proxy or something, so we'll just set it to white */
.ui-widget-content {
	background: white !important;
}

table {
	border-collapse: collapse;
}

td, th {
	padding: .5em .5em .2em .5em;
	border: 1px solid #CCC;
	/*white-space: nowrap;
	overflow: hidden;*/
}

thead, tfoot {
	background-color: #CCC;
}


.ui-tabs-nav {
	font-size: 85%;
}

.ui-tabs .ui-tabs-panel {
	padding: .5em .5em;
}

body {
	font-family: arial, sans-serif;
	font-size: 14px;
	background-color: #EEE;
}

a img {
	text-decoration: none;
	border: 0 none;
}

.working {
	width:100%;
	background-image: url('/community/images/loading-small-new.gif');
	background-position: 50%;
	background-repeat: no-repeat;
	cursor:pointer;
}

.computing1 {
	width:100%;
	background-image: url('/community/images/loading-small-new.gif');
	background-position: 50%;
	background-repeat: no-repeat;
	cursor:pointer;
}

.computing2 {
	width:100%;
	background-image: url('/community/images/loading-small-new.gif');
	background-position: 50%;
	background-repeat: no-repeat;
	cursor:pointer;
}

.closeButton {
	float:right;
	background-image: url('/community/images/dialog_sprites.png');
	background-position: 50% -17px;
	background-repeat: no-repeat;
	height: 16px; width: 16px;
	cursor:pointer;
}

.addButton {
	float:left;
	background-image: url('/community/images/dialog_sprites.png');
	background-position: 50% -177px;
	background-repeat: no-repeat;
	height: 16px; width: 16px;
	cursor:pointer;
}

.reconcileButton {
	display: block;
	margin: 0px auto;
	background-image: url('/community/images/merge.png');
	background-size: 100%;
	background-repeat: no-repeat;
	height: 32px; width: 32px;
	cursor:pointer;
}

.reconcileStatus {
	background-color: #EEE;
	border-left: none;
	border-right: none;
	border-top: none;
	border-bottom: none;
}

.assignee {
	text-align:center;
	border-left: none;
	border-top: none;
	border-bottom: none;
}

.transcribeStatus {
	white-space: nowrap;
	border-left: none;
	border-right: none;
	border-top: none;
	border-bottom: none;
}


.firstRowCell {
	border-top: 1px solid #CCC;
	padding-top: .9em ! important;
	padding-bottom: .15em;
}

.midRowCell {
	padding-top: .15em;
	padding-bottom: .15em;
}

.lastRowCell {
	padding-top: .15em;
	padding-bottom: .9em ! important;
}


.reconcileTool {
	border-right: none;
}

.docIDCell {
	text-align:center;
	font-size:130%;
}

.progressBar {
	margin: 0pt; padding: 0pt; width: 100%; white-space: nowrap; text-align: center; position: relative; z-index:0;
	-moz-border-radius: 5px;
	-webkit-border-radius: 5px;
	border-radius: 5px;
	-moz-box-shadow: 0px 0px 4px #222;
	-webkit-box-shadow: 0px 0px 4px #222;
	box-shadow: 0px 0px 4px #222;
	background-image: -moz-linear-gradient(top, #eeeeee, #cccccc);
	background-image: -webkit-gradient(linear,left top,left bottom,color-stop(0, #eeeeee),color-stop(1, #cccccc));
	background-image: -webkit-linear-gradient(top, #eeeeee, #cccccc);
	background-image: -moz-linear-gradient(top, #eeeeee, #cccccc);
	background-image: -ms-linear-gradient(top, #eeeeee, #cccccc);
	background-image: -o-linear-gradient(top, #eeeeee, #cccccc);
}
-->
</style>
</head>

<body>
<div>
<b><i><span id="projectName"><span/></i></b>
<p style="font-size:small;background-color: #EEE;margin-after:0px;">
</p>
</div>
<div style="overflow:auto; border: none 0px; width:100%;min-height:300px;" class="fillPage" id="contentDiv">
	<table class="" style="width:100%;">
		<thead>
			<tr><th></th><th>Status</th><th>Assignment</th><th id="docIDCol">DocID</th><th id="ga_numbercol">Name</th><th id="centurycol">Date</th><th id="Leavescol">Proj Pgs</th><th>Total Pgs</th></tr>
		</thead>
		<tfoot>
			<tr><th></th><th>Status</th><th>Assignment</th><th>DocID</th><th>Name</th><th>Date</th><th>Proj Pgs</th><th>Total Pgs</th></tr>
		</tfoot>
		<tbody id="statusTable">
		</tbody>
	</table>
</div>
<script>


function getProgressHTML(docID, percent, reconcile, userName) {
	var buffer ='';

	var transcribingURL = '/transcribing/'; // VMR.getRelativeURL('transcribing');
	var objectPart = $(projectXML).attr('objectPart');
	var params = '?projectName='+projectName+'&docID='+docID+'&biblicalContent='+objectPart+'&searchType=pages&userName='+userName;
	
	buffer += '<div class="progressBar">';
	buffer += '&nbsp;' + percent + '% '+(reconcile ? 'Reconciled' : 'Complete') + ' (<a href="'+ transcribingURL + params + '" target="_blank">View</a>)';

	if (percent > 0) { // for stupid ie 
		buffer += '<div style="position: absolute; top:0px; left:0px; margin: 0pt; padding: 0pt; background: transparent url(/community/images/statusbar_green.gif) repeat-x scroll 0% 0%; overflow: visible; width: ' + percent + '%; -moz-background-clip: border; -moz-background-origin: padding; -moz-background-inline-policy: continuous; vertical-align: middle; filter:alpha(opacity=40); -khtml-opacity: 0.40; -moz-opacity: 0.40; opacity:0.40; z-index:-1;">';
		buffer += '&nbsp;';
		buffer += '</div>';
	} // for stupid ie 

	buffer += '</div>';
	return buffer;
}


function loadStatus(pid) {
	$('#statusTable').html('<tr><td colspan="8"><center><image src="'+VMR.imagesURL+'/loading.gif"/></center><br/><center><h1>Computing Project Status.  Please wait...</h1></center></td></tr>');
	
	var postData = { detail : 'tasks' };
	if (pid != -1) postData.projectID = pid;
	else postData.projectName = siteName;
	VMR.serviceRequest('projectmanagement/project/get', postData, function(o) {
		projectXML  = $($.parseXML(o.text)).find('project');
		projectName = $(projectXML).attr('name');
		projectID   = $(projectXML).attr('projectID');
		isManager   = isAdmin;
		var t = '<tr style=""><td colspan="8"><i><b>Manuscripts:</b> ' + $(projectXML).find('documentGroup').find('document').length + '</i></td></tr>';
		$(projectXML).find('documentGroup').find('document').each(function() {
			var docID = $(this).attr('docID');
			var gaNum = $(this).attr('gaNum');
			var year = $(this).attr('originYearDescription');
			var prjCount = $(this).attr('totalUnits');
			var docCount = $(this).attr('leavesDescription');
			var rowDetails = '';

			var assignCount = $(this).children('task').length;

			var extra = (assignCount > 1) ? (' rowspan="'+(assignCount+1)+'" ') : '';

			rowDetails += '<td id="doc'+docID+'label" '+extra+' class="docIDCell" onclick="mss_selected(\'' + docID + '\');"><b>' + docID + '</b>';
			if (isManager) {
				rowDetails += '<span class="addButton" title="Assign" onclick="addAssignment('+docID+');"/>';
			}
			rowDetails += '</td>';
			rowDetails += '<td '+extra+' onclick="mss_selected(\'' + docID + '\');"><b>'+ gaNum + '</b></td>';
			rowDetails += '<td '+extra+' onclick="mss_selected(\'' + docID + '\');">'+ year + '</td>';
			rowDetails += '<td id="doc'+docID+'prjpgs" '+extra+' style="text-align:right;" onclick="mss_selected(\'' + docID + '\');">'
if (prjCount) {
			rowDetails += prjCount;
}
else {
			rowDetails += '<div class="computing2" title="Computing" onclick="computeAssignment('+docID+');">&nbsp;</div>';
}
			rowDetails += '</td>';
			rowDetails += '<td '+extra+' onclick="mss_selected(\'' + docID + '\');">'+ docCount + '</td>';

			var assignments = '<tr class="docrow" style="z-index:-99;" id="doc' + docID + '">';
			var assignees = '{ ';
			var tasks = $(this).children('task');
			tasks.each(function(i) {
				var pct = $(this).attr('percentageComplete');
				var total = $(this).attr('totalPages');
				var assignee = $(this).attr('assignedTo');
				if (i > 0) {
					assignments += '<tr style="z-index:-99;">';
				}
				else {
					assignments += '<td class="reconcileTool firstRowCell lastRowCell" '+extra+' onclick="mss_selected(\'' + docID + '\');">';
					if (isManager && tasks.length > 1) {
						assignments += '<span class="reconcileButton" title="Reconcile" onclick="reconcile(' + docID + ');"/>';
					}
					assignments += '</td>';
				}
				assignments += '<td class="transcribeStatus '+(i==0?'firstRowCell':(i!=(tasks.length-1)?' midRowCell':''))+(i==(tasks.length-1)?' lastRowCell':'')+'" id="doc'+docID+'_'+assignee.replace(/[. ]/g, '_')+'progress" onclick="mss_selected(\'' + docID + '\');">';
if (total > 0) {
				assignments += getProgressHTML(docID, pct, false, assignee);
}
else {
				assignments += '<div class="computing1" title="Computing" onclick="computeAssignment('+docID+', \''+assignee+'\');">&nbsp;</div>';
}
				assignments += '</td><td class="assignee '+(i==0?'firstRowCell':(i!=(tasks.length-1)?' midRowCell':''))+(i==(tasks.length-1)?' lastRowCell':'')+'" id="doc'+docID+'worker_'+assignee.replace(/[. ]/g, '_')+'">';
				if (assignee == null || assignee.length < 1) {
					if (allowVolunteers) {
						assignments += '<button onclick="claimResponsibility(\''+ docID + '\');return false;">Claim Responsibility</button>';
					}
					else {
						assignments += '&nbsp;';
					}
				}
				else {
					assignments += '<a href="/web/' + assignee + '" target="_blank">' + assignee + '</a>';
					if (isManager) {
						assignments += '<span class="closeButton" title="UnAssign" onclick="removeAssignment('+docID+', \''+assignee+'\');"/>';
					}
					if (assignees.length) assignees += ', ';
					assignees += ('\'' + assignee + '\'');
				}
				assignments += '</td>';
				if (i==0) {
					assignments += rowDetails;
				}
				assignments += '</tr>'
				if (extra.length > 0 && i == 0) {
					assignments += '<tr>';
					assignments += '<td class="reconcileStatus midRowCell" id="doc'+docID+'_'+siteName.replace(/[. ]/g, '_')+'progress" style="white-space: nowrap;" onclick="mss_selected(\'' + docID + '\');">';
//					assignments += getProgressHTML(docID, pct, false, siteName);
					assignments += '<div class="computing1" title="Computing" onclick="computeAssignment('+docID+', \''+siteName+'\');">&nbsp;</div>';
					assignments += '</tr>';
				}
			});
			assignees += ' }';

			t += assignments;
			if (assignCount < 1) t += '<td class="reconcileTool firstRowCell" onclick="mss_selected(\'' + docID + '\');">&nbsp;</td><td class="transcribeStatus firstRowCell"></td><td class="assignee firstRowCell"></td>' + rowDetails;
			t += '</tr>';
		});
		VMR.clearExpandFillPageClients();
		$('#statusTable').html(t);
		$('#projectName').html($(projectXML).attr('name'));
		VMR.refreshHeight();
		compute();
	});
}


function reconcile(docID) {

	var reconcilerURL = VMR.getRelativeURL('reconciliation');
	var objectPart = $(projectXML).attr('objectPart');
	var params = '?projectName='+projectName+'&docID='+docID+'&biblicalContent='+objectPart+'&searchType=pages';
	$(projectXML).find('documentGroup').find('document[docID='+docID+']').children('task').each(function() {
		var assignee = $(this).attr('assignedTo');
		params += '&transcriber='+assignee;
	});

	reconcilerWindow = window.open(reconcilerURL+params, 'reconcile', 'scrollbars=yes,menubar=yes,height=600,width=800,resizable=yes,toolbar=yes,status=yes');
//	handleReconcilerWindow();
}


function computeAssignment(docID, assignee) {
	
		var postData = {
			projectID     : projectID,
			objectID      : docID,
			taskTypeID    : $(projectXML).attr('taskTypeID'),
			assignedTo    : assignee || 'none',
			detail        : 'progress'
		};
	
		VMR.serviceRequest('projectmanagement/task/get', postData, function(o) {
			var xml = $.parseXML(o.text);
			var task = $(xml).find('task');
			if (assignee) {
				var t = getProgressHTML(docID, $(task).attr('percentageComplete'), assignee == siteName, assignee);
				$('#doc'+docID+'_'+assignee.replace(/[. ]/g, '_')+'progress').html(t);
			}
/*
			else {
				computeAssignment(docID, siteName);
				return;
			}
*/
			$('#doc'+docID+'prjpgs').html($(task).attr('totalUnits'));
			compute();
		});
}


function compute(level) {
	if (!level) level = 1;
	if (level > 5) return;
	if ($('.computing'+level).length > 0) {
		var element = $('.computing'+level)[0];
		$(element).removeClass('computing'+level);
		$(element).addClass('working');
		$(element).trigger('onclick');
	}
	else {
		compute(level+1);
	}
}

function removeAssignment(docID, assignee) {

	if (confirm('Are you sure you want to delete this assignement\n'+assignee+' -> '+ docID + '?')) {
	
		var postData = {
			objectID      : docID,
			taskTypeID    : $(projectXML).attr('taskTypeID'),
			projectID     : projectID,
			assignedTo    : assignee
		};
	
		VMR.serviceRequest('projectmanagement/task/unassign', postData, function(o) {
			var xml = $.parseXML(o.text);
			var error = $(xml).find('error');
			if (error && error.length) {
				alert($(error).attr('message'));
			}
			else {
				alert($(xml).find('success').attr('message'));
				loadStatus(projectID);
			}
		});
	}
}


function selectAssignee(docID) {
	$('#newAssignmentDoc').html(docID);

	t='';
	$(projectXML).find('userGroup').children('user').each(function() {
		t += '<option>'+$(this).text()+'</option>';
	});
	$('#newAssignmentAssignee').html(t);
	$('#newAssignmentDialog').dialog('open');
	$('#newAssignmentDialog').dialog('widget').position({
		my: "left bottom",
		at: "left top",
		of: $('#doc'+docID+'label')
	});
}


function addAssignment(docID, assignee) {

	if (!assignee) {
		selectAssignee(docID);
		return;
	}

	if (confirm('Are you sure you want to create this assignement\n'+assignee+' -> '+ docID + '?')) {
	
		var postData = {
			objectID      : docID,
			taskTypeID    : $(projectXML).attr('taskTypeID'),
			projectID     : projectID,
			assignedTo    : assignee
		};
	
		VMR.serviceRequest('projectmanagement/task/assign', postData, function(o) {
			var xml = $.parseXML(o.text);
			var error = $(xml).find('error');
			if (error && error.length) {
				alert($(error).attr('message'));
			}
			else {
				alert($(xml).find('success').attr('message'));
				loadStatus(projectID);
			}
		});
	}
}


function mss_selected(docID) {
}

function project_selected_callback(topic, data, subscriberData) {
	loadStatus(data);
}


VMR.init(function() {

	VMR.subscribe("interedition.project.selected", project_selected_callback);

	var pid = parseInt(VMR.prefs.getString('project'));

	VMR.serviceRequest('auth/hasrole', { role : 'VMR Administrator' }, function(o) {
		var xml = $.parseXML(o.text);
		if ($(xml).find('role').attr('hasRole') == 'true') {
			isAdmin = true;
		}
		var postData = {
			role : 'Site Administrator',
			userGroupID : parent.Liferay.ThemeDisplay.getScopeGroupId()
		};
		VMR.serviceRequest('auth/hasrole', postData, function(o) {
			var xml = $.parseXML(o.text);
			siteName = $(xml).find('role').attr('userGroupName');
			if ($(xml).find('role').attr('hasRole') == 'true') {
				isAdmin = true;
			}
			loadStatus(pid);
		});
	});

	$('#newAssignmentDialog').dialog({
		autoOpen: false,
		position: 'top',
		width: Math.min(gadgets.window.getViewportDimensions().width-24, 300),
		title: 'Create New Assignment',
		close : function(event, ui) { 
		}
	});

	$('#createAssignmentButton').click(function() {
		$('#newAssignmentDialog').dialog('close');
		addAssignment($('#newAssignmentDoc').html(), $('#newAssignmentAssignee').val());
	});

}, '../../');

</script>
<div style="font-size: small;" id="newAssignmentDialog">
<p style="margin:0px 1px 0px 1px;">
New Assignment for Document: <span id="newAssignmentDoc"></span><br/>
Assign to Project Member:<br/>
<select id="newAssignmentAssignee" style="width:100%;" name="newAssignmentAssignee">
<option></option>
</select>
</p>
<button id="createAssignmentButton">Create Assignment</button>
</div>
</body>
</html>

]]>
</Content>
</Module>


