<Module>
  <ModulePrefs
	title="Project Status - Apparatus Editing"
	title_url="http://ntvmr.uni-muenster.de"
	author_email="scribe777@gmail.com"
	author="Institut für neutestamentliche Textforschung"
	description="Show Project Status and Progress for Apparatus Editing"
	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="-2">
	<EnumValue value="-2" display_value="Smart Default"/>
	<EnumValue value="35" display_value="Selector"/>
	<EnumValue value="200" display_value="Short"/>
	<EnumValue value="300" display_value="Short-Medium"/>
	<EnumValue value="400" display_value="Medium"/>
	<EnumValue value="600" display_value="Tall"/>
	<EnumValue value="-1" display_value="Dynamic"/>
</UserPref>

<UserPref name="taskTypeID" datatype="enum" display_name="Task Type" default_value="-1">
	<EnumValue value="-1" display_value="Use Project Task Type"/>
	<EnumValue value="1" display_value="Imaging"/>
	<EnumValue value="2" display_value="Indexing"/>
	<EnumValue value="3" display_value="Transcribing"/>
	<EnumValue value="4" display_value="Variant Selection"/>
	<EnumValue value="5" display_value="Collation Editing"/>
</UserPref>

<UserPref name="progressTask" datatype="enum" display_name="Progress Task" default_value="1">
	<EnumValue value="1" display_value="Complete"/>
	<EnumValue value="2" display_value="Initial Pass"/>
</UserPref>

<UserPref name="project" datatype="enum" display_name="Base Project" default_value="-1">
	<EnumValue value="-1" display_value="None"/>
<EnumValue value="13" display_value="Summer School Boot Camp"/>
<EnumValue value="28" display_value="M566"/>
<EnumValue value="29" display_value="CoptOT Team"/>
<EnumValue value="17" display_value="Apa Johannes"/>
<EnumValue value="18" display_value="Our Cool Manuscripts"/>
<EnumValue value="19" display_value="Latin Course 101"/>
<EnumValue value="20" display_value="SFB 1136 'Bildung und Religion' and KELLIA"/>
<EnumValue value="21" display_value="My Cool Critical Edition"/>
<EnumValue value="25" display_value="Testamentum Salomonis"/>
<EnumValue value="24" display_value="English Translation"/>
<EnumValue value="26" display_value="Michael the Great"/>
<EnumValue value="27" display_value="Michael Syrus I"/>
<EnumValue value="30" display_value="CoptOT Public"/>
<EnumValue value="31" display_value="Martyrs and Archangels"/>
<EnumValue value="32" display_value="Summer School in Coptic Literature 2018"/>
<EnumValue value="33" display_value="Psalm 90 Edition Project"/>
<EnumValue value="34" display_value="Ethiopic Bible"/>
<EnumValue value="35" display_value="Leviticus"/>
<EnumValue value="36" display_value="Isaiah"/>
<EnumValue value="37" display_value="Isaiah"/>
<EnumValue value="38" display_value="Isaiah Edition"/>
<EnumValue value="39" display_value="Deuteronomium"/>
<EnumValue value="40" display_value="Holy Week Lectionary"/>
<EnumValue value="41" display_value="Old Testament Lectionary"/>
<EnumValue value="42" display_value="Sahidic Euchologia"/>
<EnumValue value="43" display_value="Numeri"/>
<EnumValue value="44" display_value="Psalms"/>
<EnumValue value="46" display_value="Ezekiel"/>
<EnumValue value="47" display_value="Annual Lectionary"/>
<EnumValue value="48" display_value="Annual Gospel Lectionary"/>
<EnumValue value="49" display_value="Sabbato Kyriakai Lectionary"/>
<EnumValue value="50" display_value="Exodus"/>
<EnumValue value="51" display_value="Genesis"/>
<EnumValue value="52" display_value="Micah"/>
<EnumValue value="53" display_value="Judges"/>
<EnumValue value="54" display_value="Ruth"/>
<EnumValue value="55" display_value="Joshua"/>
<EnumValue value="56" display_value="Proverbs"/>
<EnumValue value="57" display_value="Lent Lectionary"/>
<EnumValue value="58" display_value="Holy Week Lectionary Bohairic"/>
<EnumValue value="59" display_value="Galatians"/>
<EnumValue value="60" display_value="Holy Week Lectionary Arabic"/>
<EnumValue value="61" display_value="Ephesians"/>
<EnumValue value="62" display_value="Besa Editions"/>
<EnumValue value="63" display_value="Shenoute Editions"/>
<EnumValue value="64" display_value="Dodekapropheton"/>
<EnumValue value="65" display_value="Jeremiah"/>
<EnumValue value="66" display_value="Bodmer"/>
<EnumValue value="67" display_value="Achmimic Project"/>
<EnumValue value="68" display_value="Daniel"/>
<EnumValue value="69" display_value="Esther"/>
<EnumValue value="70" display_value="Judith"/>
<EnumValue value="71" display_value="Annual Old Testament Lectionary"/>
<EnumValue value="72" display_value="Apa Ioannes"/>
<EnumValue value="73" display_value="Greek Odes"/>
<EnumValue value="74" display_value="Susanna"/>
<EnumValue value="75" display_value="Bel"/>
<EnumValue value="76" display_value="Zephaniah"/>
<EnumValue value="77" display_value="Jonah"/>
<EnumValue value="78" display_value="Obadiah"/>
<EnumValue value="79" display_value="Nahum"/>
<EnumValue value="80" display_value="Haggai"/>
<EnumValue value="81" display_value="Habakkuk"/>
<EnumValue value="82" display_value="Hosea"/>
<EnumValue value="83" display_value="Bohairic Euchologion Cataloguing Project"/>
<EnumValue value="84" display_value="Amos"/>
<EnumValue value="85" display_value="Zechariah"/>
<EnumValue value="86" display_value="Annual Old Testament Lectionary Arabic"/>
<EnumValue value="87" display_value="Joel"/>
<EnumValue value="88" display_value="Job"/>
<EnumValue value="89" display_value="Sirach"/>
<EnumValue value="90" display_value="Ecclesiastes"/>
<EnumValue value="91" display_value="Canticles"/>
<EnumValue value="92" display_value="Tobit"/>
<EnumValue value="93" display_value="Wisdom of Solomon"/>
<EnumValue value="94" display_value="Baruch"/>
<EnumValue value="95" display_value="Lamentations"/>
<EnumValue value="96" display_value="Letter of Jeremiah"/>
</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"/>
	<link rel="stylesheet" type="text/css" href="/community/js/jquery.qtip2/jquery.qtip.min.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" src="/community/js/jquery.qtip2/jquery.qtip.min.js"></script>

<script type="text/javascript">

var MARGIN=0;
var displayKind = 'Full';
var baseProjectID = -1;
var projectID = -1;
var taskTypeID = -1;
var progressTask = 1;
var projectName = '';
var projectXML = null;
var siteName = null;

var isAdmin = false;
var isManager = false;

var allowVolunteers = false;


</script>
<style type="text/css" id="statusStyles">
<!--
.progressCanvas {
	position:absolute;
	top:0px;
	left:0px;
	width:100%;
	height:100%;
	filter:alpha(opacity=40);
	-khtml-opacity: 0.40;
	-moz-opacity: 0.40;
	opacity:0.40;
	z-index:-1;"
}
/* 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: .7em .5em .7em .5em;
	border: 1px solid #CCC;
	/*white-space: nowrap;
	overflow: hidden;*/
}

.expanded {
	background-color: #CCC;
}
.verseRow {
	background-color: #DDD;
}

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


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

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

.qtip {
	max-width:40em ! important;
}

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

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

.chapterRow {
	cursor:pointer;
}
.chapterRow:hover {
	background:aliceblue;
}

.unitCount {
	cursor:pointer;
	color: blue;
}

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

.taskUnitsHeader {
}

#taskStageChoicesOptions {
	display: table;
	margin-right: auto;
	margin-left: auto;
}

.stageChoiceDisplay,.stageChoice {
	width:2em;
	text-align:center;
	display:inline-block;
	border-radius: 6px;
}

.stageChoice {
	margin:.2em;
	font-size:200%;
}

.updateStats {
	display:none;
}

.loading {
	display: inline-block;
	margin: 0px auto;
	background-image: url('/community/images/loading.gif');
	background-size: 100%;
	background-repeat: no-repeat;
	height: 1em; width: 1em;
}

.refreshCache, .refreshCacheProject, .refreshCachePublished {
	display: inline-block;
	margin: 0px auto;
	background-image: url('/community/images/update.png');
	background-size: 100%;
	background-repeat: no-repeat;
	height: 1em; width: 1em;
	cursor:pointer;
}

.refreshCachePublished {
	border: 1px solid;
	border-color: red;
	border-radius: 2px;
	background-color: pink;
}

#adminControls, #projectName {
	margin-right:.5em;
	margin-left:.5em;
	margin-top:.5em;
}

#projectName {
	font-weight:bold;
	font-style:italic;
	display:inline-block;
}

#adminControls {
	float: right;
}

.deleteTranscriptionPage {
	float:right;
	display: inline-block;
	margin: 0px auto;
	background-image: url('/community/images/delete.png');
	background-size: 100%;
	background-repeat: no-repeat;
	height: 1em; width: 1em;
	cursor:pointer;
}

.moveTranscriptionPage {
	float:right;
	background-image: url('/community/images/xiao_icon_sprites.png');
	background-position: 0 -1400px;
	background-repeat: no-repeat;
	height: 16px; width: 16px;
	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;
}

.assignmentsTable {
	width: 100%;
}
.assignmentsTable td {
	border-left: none;
	border-right: none;
	border-top: none;
	border-bottom: none;
	padding: .2em .2em .2em .2em;
}
.taskStage {
	float:left;
	width: 2em;
}
.assignee {
	width: 12em;
}

.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;
}


.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);
}

.taskUnitsStats {
        min-width:20em;
        max-height:300px;
        overflow-x:visible;
        overflow-y:auto;
        padding:.5em;
}

.taskUnitsStats td {
        padding-right:.2em;
}

#footer {
	height:40em;
}

.displayKind.displayKindSelector {
	display : none;
}

#summary.displayKindSelector {
	display : block;
}

#summary.displayKindFull {
	display : none;
}

#summary {
	margin-top: 17px;
}


-->
</style>
</head>

<body style="background:none transparent;">
<div id="summary" class="displayKind" style="margin-top: 14px; margin-left: 5px;"><button id="buttonSelector" onclick="selectChapter()"></button></div>

<div id="header" class="displayKind">
	<div id="projectName"></div><div id="adminControls"></div>
	<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" class="displayKind">
	<table class="projectStatus" style="width:100%;">
		<thead>
			<tr><th></th><th>Chapter</th><th>Progress</th><th>Verses</th><th>Avg Verse<br/>Segments</th><th>Total<br/>Segments</th><th>Assigned</th><th>Of Interest</th><th>Problematic</th><th>Reviewed</th><th>Complete</th><th>Private<br/>Comments</th><th>Witness<br/>Comments</th><th>Segment<br/>Comments</th><th>Last Update<br/>(Reading)</th><th>Last Update<br/>(Witness)</th></tr>
		</thead>
		<tfoot>
			<tr><th></th><th>Chapter</th><th>Progress</th><th>Verses</th><th>Avg Verse<br/>Segments</th><th>Total<br/>Segments</th><th>Assigned</th><th>Of Interest</th><th>Problematic</th><th>Reviewed</th><th>Complete</th><th>Private<br/>Comments</th><th>Witness<br/>Comments</th><th>Segment<br/>Comments</th><th>Last Update<br/>(Reading)</th><th>Last Update<br/>(Witness)</th></tr>
		</tfoot>
		<tbody id="statusTable">
		</tbody>
	</table>
	<div id="footer"></div>
</div>
<script>


function getTaskStages(stageDefsString) {
	var stages = [];

	if (!stageDefsString) stageDefsString = "🔾:transparent|🔘:00FF00";
			
	var stageDefs = stageDefsString.split('|');
	for (var i = 0; i < stageDefs.length; ++i) {
		var stageIcon = stageDefs[i].split(':')[0];
		var stageColor = (stageDefs[i].split(':').length > 1) ? stageDefs[i].split(':')[1] : 'transparent';
		var stageProtected = false;
		if (stageIcon.startsWith('*')) {
			stageProtected = true;
			stageIcon = stageIcon.substring(1);
		}
		stages.push({
			display   : stageIcon,
			color     : stageColor,
			protected : stageProtected
		});
	}
	return stages;
}


function getStageHTML(taskID, taskStage, stageDefsString) {
	var stages = getTaskStages(stageDefsString);

	var t = '';
	if (taskStage < stages.length) {
		t += '<div class="stageChoiceDisplay" title="level: '+taskStage+'" style="background-color:'+stages[taskStage].color+';';
		if (!stages[taskStage].protected || isManager) {
			t += 'cursor:pointer;" onclick="changeTaskStage('+taskID+'); return false;';
		}
		t += '">'+stages[taskStage].display+'</div>';
	}
	return t;
}


function changeTaskStage(taskID) {
	var stageDefsString = $(projectXML).attr('taskStageDefinitions');
	var stages = getTaskStages(stageDefsString);
	var stage = parseInt($('tr[data-taskID="'+taskID+'"]').attr('data-taskStage'));
	var docID = parseInt($('tr[data-taskID="'+taskID+'"]').attr('data-docID'));
	var userName = $('tr[data-taskID="'+taskID+'"]').attr('data-assignedTo');
	var t = '';
	var divs = [];
	var toggleChoice = 0;
	for (var i = 0; i < stages.length; ++i) {
		if (!stages[i].protected || isManager) {
			var div = '<div title="level: '+i+'" class="stageChoice"';
			if (i != stage) {
				div += ' onclick="taskStageSelected('+taskID+', '+i+');return false;"';
				toggleChoice = i;
			}
			div += ' style="'+(i != stage?'cursor:pointer;':'opacity:0.5;')+'background-color:'+stages[i].color+'">'+stages[i].display+'</div>';
			divs.push(div);
		}
	}
	if (divs.length == 2) {
		// we only have 1 choice besides current, just toggle
		taskStageSelected(taskID, toggleChoice);
	}
	else {
		$('#taskStageChoicesDescription').html('Status for ' + userName + ' doc: ' + docID);
		$('#taskStageChoicesOptions').html(divs.join(' '));
		$('#taskStageChoices').dialog({
			resizable: false,
			height: "auto",
			modal: true,
			position: {
				my: "left bottom",
				at: "left top",
				of: $('tr[data-taskID="'+taskID+'"]').find('div.taskStage')
			},
		});
	}
}

function taskStageSelected(taskID, stage) {
	if ($('#taskStageChoices').hasClass("ui-dialog-content") && $('#taskStageChoices').dialog("isOpen")) {
		$('#taskStageChoices').dialog('close');
	}

	VMR.serviceRequest('projectmanagement/task/setstage', { taskID : taskID, stage : stage }, function(o) {
		var xml = $.parseXML(o.text);
		var task = $(xml).find('task');
		if ($(task).length) {
			stage = $(task).attr('stage');
			var projectStageDefinitions = $(projectXML).attr('taskStageDefinitions');
			$('tr[data-taskID="'+taskID+'"]').attr('data-taskStage', stage);
			$('tr[data-taskID="'+taskID+'"]').find('div.taskStage').html(
				getStageHTML(taskID, stage, projectStageDefinitions)
			);
		}
	});
}


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

	var workAreaURL = VMR.getRelativeURL('apparatus-manual-editor');
	var objectPart = $(projectXML).attr('objectPart');
	var indexSegs = chapter.split('.');
	var params = '?verse='+chapter+(indexSegs.length==2 ? '.1' : '');
	
	buffer += '<div class="progressBar">';
	buffer += '&nbsp;' + percent + '% '+(reconcile ? 'Reconciled' : 'Complete') + ' (<a href="'+ workAreaURL + 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_'+(reconcile ? 'orange' : '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 += '<canvas class="undrawn progressCanvas'+(reconcile?' reconcile':'')+'" data-docID="'+docID+'" data-userName="'+userName+'" data-map="'+(completedUnitsMap?completedUnitsMap:'')+'" data-percent="'+percent+'"></canvas>';
*/

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


function getAssigneeRowHTML(docID, assignee, total, pct, completedUnitsMap, taskID, taskStage) {

	var projectStageDefinitions = $(projectXML).attr('taskStageDefinitions');

	var h = '<tr data-taskID="'+taskID+'" data-docID="'+docID+'" data-taskStage="'+taskStage+'" data-assignedTo="'+assignee.replace(/[.() ]/g, '_')+'" id="doc'+docID+'_assignee_'+assignee.replace(/[.() ]/g, '_')+'">';
	// progress
	h += '<td class="transcribeStatus" id="doc'+docID+'_'+assignee.replace(/[.() ]/g, '_')+'progress">';
	if (total > 0) {
		h += getProgressHTML(docID, pct, false, assignee, completedUnitsMap);
	}
	else {
		h += '<div class="computing1" title="Computing" onclick="computeAssignment('+docID+', \''+assignee+'\');return false;">&nbsp;</div>';
	}
	h += '</td>';
	// assignee
	h += '<td class="assignee" id="doc'+docID+'worker_'+assignee.replace(/[.() ]/g, '_')+'">';
	// stage
	h += '<div class="taskStage">';
	if (taskID) {
		h += getStageHTML(taskID, taskStage, projectStageDefinitions);
	}
	h += '</div>';
	h += '<a href="/web/' + assignee + '" target="_blank">' + assignee + '</a>';
	if (isManager) {
		h += '<span class="closeButton" title="UnAssign" onclick="removeAssignment('+docID+', \''+assignee+'\');return false;"/>';
	}
	h += '</td>';
	h += '</tr>';
	return h;
}


function loadStatus(bpid) {
	$('#statusTable').html('<tr><td colspan="12"><center><image src="'+VMR.imagesURL+'/loading.gif"/></center><br/><center><h1>Computing Project Status.  Please wait...</h1></center></td></tr>');
	
	var postData = {
		detail : 'users',
		statusChapter : true,
		projectName : siteName
	};
	if (bpid != -1) {
		postData.segmentGroupID = bpid;
	}
	VMR.serviceRequest('projectmanagement/project/get', postData, function(o) {
		projectXML  = $($.parseXML(o.text)).find('project');
		projectName = $(projectXML).attr('name');
		projectID   = $(projectXML).attr('projectID');
		try { taskTypeID  = parseInt(VMR.prefs.getString('taskTypeID')); } catch(e) {}
		if (taskTypeID < 0) taskTypeID  = $(projectXML).attr('taskTypeID');
		isManager   = isAdmin;
		var t = '';
if (displayKind == 'Full') {
		t += '<tr style=""><td colspan="12"><i><b>Chapters:</b> ' + $(projectXML).find('chapter').length + '</i></td></tr>';
}
		$(projectXML).find('chapter').each(function() {
			var chapterHash = $(this).attr('chapterHash');
			var indexContent = $(this).attr('indexContent');
			var totalVerses = parseInt($(this).attr('totalVerses'));
			if (isNaN(totalVerses)) totalVerses = 0;
			var avgSegmentsPerVerse = parseInt($(this).attr('avgSegmentsPerVerse'));
			if (isNaN(avgSegmentsPerVerse)) avgSegmentsPerVerse = 0;
			var assignedUnits = parseInt($(this).attr('assignedUnits'));
			if (isNaN(assignedUnits)) assignedUnits = 0;
			var ofInterestUnits = parseInt($(this).attr('ofInterestUnits'));
			if (isNaN(ofInterestUnits)) ofInterestUnits = 0;
			var problematicUnits = parseInt($(this).attr('problematicUnits'));
			if (isNaN(problematicUnits)) problematicUnits = 0;
			var reviewedUnits = parseInt($(this).attr('reviewedUnits'));
			if (isNaN(reviewedUnits)) reviewedUnits = 0;
			var commentsPrivate = parseInt($(this).attr('commentsPrivate'));
			if (isNaN(commentsPrivate)) commentsPrivate = 0;
			var commentsSegment = parseInt($(this).attr('commentsSegment'));
			if (isNaN(commentsSegment)) commentsSegment = 0;
			var commentsWitness = parseInt($(this).attr('commentsWitness'));
			if (isNaN(commentsWitness)) commentsWitness = 0;
			var completedUnits = parseInt($(this).attr('completedUnits'));
			if (isNaN(completedUnits)) completedUnits = 0;
			var startedUnits = parseInt($(this).attr('startedUnits'));
			if (isNaN(startedUnits)) startedUnits = 0;
			var totalUnits = parseInt($(this).attr('totalUnits'));
			if (isNaN(totalUnits)) totalUnits = 0;
			var lastUpdateReading = $(this).attr('lastUpdateReading');
			var lastUpdateWitness = $(this).attr('lastUpdateWitness');
			var pct = totalUnits > 0 ? (progressTask == 1 ? completedUnits : startedUnits) * 100 / totalUnits : 0;
			pct = Math.round(pct);

			if (!$('#buttonSelector').text().length) {
				$('#buttonSelector').text(indexContent);
				VMR.publish("interedition.biblicalcontent.selected", { indexContent : indexContent });
			}
			t += '<tr class="chapterRow" data-indexcontent="'+indexContent+'" id="chapRow_'+indexContent.replace('.', '_')+'">';
			t += '<td  style="cursor:pointer;" onclick="toggleChapterView(\''+indexContent+'\');">&#x25B6;</td>';
			t += '<td style="text-align:left;">'+indexContent+'</td>';
			t += '<td>' + getProgressHTML(indexContent, pct, false, 'y') + '</td>';
if (displayKind == 'Full') {
			t += '<td style="text-align:right;">'+totalVerses+'</td>';
			t += '<td style="text-align:right;">'+avgSegmentsPerVerse+'</td>';
			t += '<td style="text-align:right;">'+totalUnits+'</td>';
			t += '<td style="text-align:right;">'+assignedUnits+'</td>';
			t += '<td style="text-align:right;">'+ofInterestUnits+'</td>';
			t += '<td style="text-align:right;">'+problematicUnits+'</td>';
			t += '<td style="text-align:right;">'+reviewedUnits+'</td>';
			t += '<td style="text-align:right;">'+completedUnits+'</td>';
			t += '<td style="text-align:right;">'+commentsPrivate+'</td>';
			t += '<td style="text-align:right;">'+commentsWitness+'</td>';
			t += '<td style="text-align:right;">'+commentsSegment+'</td>';
			t += '<td style="text-align:center;">'+lastUpdateReading+'</td>';
			t += '<td style="text-align:center;">'+lastUpdateWitness+'</td>';
}
			t += '</tr>';
		});
		setStatusBody(t);
	});
}

function getStatusDialog() {
	var dialog = parent.document.getElementById('apparatusStatusDialog');
	if (!dialog) {
		var iFrame = window.parent.document.getElementById(window.frameElement.id)
		var newDivInParent = window.parent.document.createElement('div');
		var newStyleInParent = window.parent.document.createElement('div');
		newDivInParent.setAttribute("Id", "apparatusStatusDialog");
		newStyleInParent.setAttribute("Id", "apparatusStatusDialogStyle");
		iFrame.parentElement.appendChild(newStyleInParent);
		iFrame.parentElement.appendChild(newDivInParent);
		var dialog = parent.document.getElementById('apparatusStatusDialog');
		$(dialog).css({
			top: $(dialog).parent().parent().position().top,
			left: $(dialog).parent().parent().position().left,
			position: 'absolute',
			'z-index': 999,
			background: 'seashell',
			overflow: 'auto',
			height: '30em',
			margin : '7px',
			padding : '1px',
			border : 'solid',
		});
		var style = parent.document.getElementById('apparatusStatusDialogStyle');
		$(style).html($('<div/>').append($('#statusStyles')).html());

		$(dialog).hide();
	}
	return dialog;
}

function setStatusBody(t) {
	if (displayKind == 'Full') {
		$('#statusTable').html(t);
		VMR.clearExpandFillPageClients();
		VMR.refreshHeight();
	}
	else if (displayKind == 'Selector') {
		var dialog = getStatusDialog();
		$(dialog).hide();
		$(dialog).html('<table><tbody>' + t + '</tbody></table>');
		$(dialog).find('tr').click(function() {
			var indexContent = $(this).attr('data-indexcontent')+'.1';
			VMR.publish("interedition.biblicalcontent.selected", { indexContent : indexContent });
			$('#buttonSelector').text(indexContent);
			$(dialog).hide();
		});
	}
}

function selectChapter() {
	var dialog = getStatusDialog();
	$(dialog).show();
}


function toggleChapterView(chapterOSISRef) {
	var collapse = $('#chapRow_'+chapterOSISRef.replace('.', '_')+' td:first').hasClass('expanded');
	$('.verseRow').remove();
	$('td.expanded').html('&#x25B6;');
	$('.expanded').removeClass('expanded');

	if (collapse) return; 

	$('#chapRow_'+chapterOSISRef.replace('.', '_')).after('<tr class="waitingRow"><td colspan="12"><center><image src="'+VMR.imagesURL+'/loading.gif"/></center><br/><center><h1>Computing Chapter Status.  Please wait...</h1></center></td></tr>');
	$('#chapRow_'+chapterOSISRef.replace('.', '_')+' td:first').html('&#x25BC;');
	$('#chapRow_'+chapterOSISRef.replace('.', '_')+' td:first').addClass('expanded');
	$('#chapRow_'+chapterOSISRef.replace('.', '_')).addClass('expanded');
	
	var postData = {
		detail : 'users',
		statusChapter : true,
		expandChapterVerses : chapterOSISRef,
		projectID : projectID
	};
	if (baseProjectID != -1) {
		postData.segmentGroupID = baseProjectID;
	}
	VMR.serviceRequest('projectmanagement/project/get', postData, function(o) {
		var xml  = $($.parseXML(o.text)).find('project');
		var t = '';
		$(xml).find('verse').each(function() {
			var verseHash = $(this).attr('verseHash');
			var indexContent = $(this).attr('indexContent');
			var totalVerses = parseInt($(this).attr('totalVerses'));
			if (isNaN(totalVerses)) totalVerses = 0;
			var avgSegmentsPerVerse = parseInt($(this).attr('avgSegmentsPerVerse'));
			if (isNaN(avgSegmentsPerVerse)) avgSegmentsPerVerse = 0;
			var assignedUnits = parseInt($(this).attr('assignedUnits'));
			if (isNaN(assignedUnits)) assignedUnits = 0;
			var ofInterestUnits = parseInt($(this).attr('ofInterestUnits'));
			if (isNaN(ofInterestUnits)) ofInterestUnits = 0;
			var problematicUnits = parseInt($(this).attr('problematicUnits'));
			if (isNaN(problematicUnits)) problematicUnits = 0;
			var reviewedUnits = parseInt($(this).attr('reviewedUnits'));
			if (isNaN(reviewedUnits)) reviewedUnits = 0;
			var completedUnits = parseInt($(this).attr('completedUnits'));
			if (isNaN(completedUnits)) completedUnits = 0;
			var commentsPrivate = parseInt($(this).attr('commentsPrivate'));
			if (isNaN(commentsPrivate)) commentsPrivate = 0;
			var commentsWitness = parseInt($(this).attr('commentsWitness'));
			if (isNaN(commentsWitness)) commentsWitness = 0;
			var commentsSegment = parseInt($(this).attr('commentsSegment'));
			if (isNaN(commentsSegment)) commentsSegment = 0;
			var totalUnits = parseInt($(this).attr('totalUnits'));
			if (isNaN(totalUnits)) totalUnits = 0;
			var lastUpdateReading = $(this).attr('lastUpdateReading');
			var lastUpdateWitness = $(this).attr('lastUpdateWitness');
			var pct = totalUnits > 0 ? (progressTask == 1 ? completedUnits : assignedUnits) * 100 / totalUnits : 0;
			pct = Math.round(pct);

			t += '<tr id="verseRow.'+indexContent+'" class="verseRow">';
			t += '<td></td>';
			t += '<td style="text-align:left;padding-left:2em;font-size:80%;">'+indexContent+'</td>';
			t += '<td style="padding-left:2em;">' + getProgressHTML(indexContent, pct, false, 'y') + '</td>';
			t += '<td style="text-align:right;">'+totalVerses+'</td>';
			t += '<td style="text-align:right;">'+avgSegmentsPerVerse+'</td>';
			t += '<td style="text-align:right;">'+totalUnits+'</td>';
			t += '<td style="text-align:right;">'+assignedUnits+'</td>';
			t += '<td style="text-align:right;" class="unitCount" data-indexContent="'+indexContent+'" data-status="2">'+ofInterestUnits+'</td>';
			t += '<td style="text-align:right;" class="unitCount" data-indexContent="'+indexContent+'" data-status="4">'+problematicUnits+'</td>';
			t += '<td style="text-align:right;">'+reviewedUnits+'</td>';
			t += '<td style="text-align:right;">'+completedUnits+'</td>';
			t += '<td style="text-align:right;" class="unitCount" data-indexContent="'+indexContent+'" data-status="commentsPrivate">'+commentsPrivate+'</td>';
			t += '<td style="text-align:right;" class="unitCount" data-indexContent="'+indexContent+'" data-status="commentsWitness">'+commentsWitness+'</td>';
			t += '<td style="text-align:right;" class="unitCount" data-indexContent="'+indexContent+'" data-status="commentsSegment">'+commentsSegment+'</td>';
			t += '<td style="text-align:center;">'+lastUpdateReading+'</td>';
			t += '<td style="text-align:center;">'+lastUpdateWitness+'</td>';
			t += '</tr>';
		});
		$('.waitingRow').remove();
		$('#chapRow_'+chapterOSISRef.replace('.', '_')).after(t);
		VMR.clearExpandFillPageClients();
		VMR.refreshHeight();
		$('.unitCount').qtip({
			content: {
				text: function(event, api) {
					var node = this;
					var url = VMR.httpRoot + '/vmr/api/variant/apparatus/get/'
							+ '?projectID=' + projectID
							+ '&segmentGroupID=' + baseProjectID
							+ '&augmentGroupID=' + projectID
							+ '&indexContent=' + $(node).attr('data-indexContent');
					var targetStatus = $(node).attr('data-status');
					if (targetStatus.startsWith('comments')) {
						url += '&detail=extra';
					}
					else {
						url += '&includeProjectStatus=' + projectID;
					}
					$.ajax({
						url : url
					})
					.then(function(content) {
						var t = '<div class="statusUnitsHeader">Verse<span style="float:right">'+$(node).attr('data-indexContent')+'</span></div>';
						t += '<div class="statusUnitsStats"><table>';
						t += '<thead><tr><th style="text-align:right;">Verse</th><th style="text-align:center;">Segment</th><th style="text-align:center;white-space:nowrap;">Comment&nbsp;&nbsp;';
						t += '</th></tr></thead>';
						t += '<tbody>';
						var entries = [];
						if (targetStatus === 'commentsPrivate') {
							entries = $(content).find('commentPrivate');
						}
						else if (targetStatus === 'commentsWitness') {
							entries = $(content).find('commentPublic');
						}
						else if (targetStatus === 'commentsSegment') {
							entries = $(content).find('commentSegmentPublic');
						}
						else {
							entries = $(content).find('segmentStatus[statusID="'+targetStatus+'"]');
						}
/*
entries.sort(function(a,b){return parseInt($(a).attr('unitID'))-parseInt($(b).attr('unitID'));});
*/
						var i = 0;
						$(entries).each(function() {
							var segment = $(this).parents('segment');
							var verse = $(segment).attr('indexContent');
							var cd = $(segment).find('contextDescription').text();
							var linkURL = VMR.getRelativeURL('apparatus-manual-editor')+'?verse='+verse+'&segment='+cd;
							if (targetStatus.startsWith('comments')) {
								linkURL += '&highlightDocID=' + $(this).parents('witness').attr('docID');
								cd += ', ' + $(this).parents('witness').attr('primaryName');
							}
							t += '<tr>';
							t += '<td style="">'+verse+'</td>';
							t += '<td style="white-space:nowrap;"><a href="'+linkURL+'" target="manual-editor">'+cd+'</a></td>';
							t += '<td style="">'+$(this).text()+'</td>';
							t += '</tr>';
							++i;
						});
						t += '</tbody></table></div>';
						api.set('content.text', t);
					}, function(xhr, status, error) {
						// Upon failure... set the tooltip content to the status and error value
						api.set('content.text', status + ': ' + error);
					});

					return 'Loading...'; // Set some initial text
				}
			},
			show: {
				delay: 1000
			},
			hide: {
				delay: 1000,
				fixed: true
			},
		});
	});
}


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[primary="true"]').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    : 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);
				var taskID = $(task).attr('taskID');
				var taskStage = $(task).attr('stage');
				var projectStageDefinitions = $(projectXML).attr('taskStageDefinitions');
				$('#doc'+docID+'_'+assignee.replace(/[.() ]/g, '_')+'progress').parent().find('div.taskStage').html(
					getStageHTML(taskID, taskStage, projectStageDefinitions)
				);
			}
/*
			else {
				computeAssignment(docID, siteName);
				return;
			}
*/
			$('#doc'+docID+'prjpgs').html($(task).attr('totalUnits'));
			compute();
		});
}


function refreshCachePublished(i) {
	var statusBar = $('#adminControls').find('.updateStats');
	if (!i) i = 0;
	var docs = $(projectXML).find('documentGroup[primary="true"]').find('document');
	if (i >= docs.length) {
		$(statusBar).html('Finished rebuilding verse cache for all published project transcriptions.');
		return;
	}
	var docID = $(docs.get(i)).attr('docID');
	$(statusBar).html('<div style="display:inline-block;" class="loading">&nbsp;&nbsp;&nbsp;</div> Refreshing verse cache for all published project transcriptions: ' + docID + ' (' + (i+1) + ' of ' + docs.length + ' : ' + Math.floor(i / docs.length * 100) + '%)');
	refreshCache(docID, null, null, function() {
		return refreshCachePublished(i+1);
	});
}


function refreshCacheProject(i) {
	var statusBar = $('#adminControls').find('.updateStats');
	if (!i) i = 0;
	var docs = $(projectXML).find('documentGroup[primary="true"]').find('document');
	if (i >= docs.length) {
		$(statusBar).html('Finished rebuilding verse cache for all project transcriptions.');
		return;
	}
	var docID = $(docs.get(i)).attr('docID');
	$(statusBar).html('<div style="display:inline-block;" class="loading">&nbsp;&nbsp;&nbsp;</div> Refreshing verse cache for all project transcriptions: ' + docID + ' (' + (i+1) + ' of ' + docs.length + ' : ' + Math.floor(i / docs.length * 100) + '%)');
	refreshCache(docID, $(projectXML).attr('name'), null, function() {
		return refreshCacheProject(i+1);
	});
}


function refreshCache(docID, assignee, statusElement, callback) {
	var postData = {
		docID      : docID
	};

	if (assignee) postData.userName = assignee;

	if (statusElement) {
		$(statusElement).show();
		$(statusElement).html('<div style="display:inline-block;" class="loading">&nbsp;&nbsp;&nbsp;</div> Refreshing Database Cache...');
	}
	VMR.serviceRequest('transcript/rebuildversecache/', postData, function(o) {
		var xml = $.parseXML(o.text);
		if (statusElement) {
			var message = $(xml).find('success').attr('message');
			if (!message || !message.length) message = $(xml).find('error').attr('message');
			else message += ' for user: ' + $(xml).find('success').attr('userName');
			$(statusElement).text(message);
		}
		if (callback) callback();
	});
}


function deleteTranscriptionPage(docID, pageID, assignee, statusElement) {
	var postData = {
		docID      : docID,
		pageID     : pageID,
		userName   : assignee
	};

	if (confirm('Are you sure you want to delete this page from the transcription repository: docID: '+docID+'; pageID: '+pageID+'; userName: '+assignee+'?')) {
		if (statusElement) {
			$(statusElement).show();
			$(statusElement).html('<div style="display:inline-block;" class="loading">&nbsp;&nbsp;&nbsp;</div> Deleting transcription page...');
		}
		VMR.serviceRequest('transcript/delete/', postData, function(o) {
			var xml = $.parseXML(o.text);
			if (statusElement) {
				var message = $(xml).find('success').attr('message');
				if (!message || !message.length) message = $(xml).find('error').attr('message');
				else message += ' for user: ' + $(xml).find('success').attr('userName');
				$(statusElement).text(message);
			}
		});
	}
}


function moveTranscriptionPage(docID, pageID, assignee, statusElement) {
	$('#movePagesDialog').dialog({
		open : function() {
			$('#movePagesDocID').html(docID);
			$('#movePagesUserName').html(assignee);
			$('#movePagesStartPageID').val(pageID);
		},
		modal: true,
		position: {
			my: "left bottom",
			at: "left top",
			of: $('#doc'+docID+'label')
		},
		buttons: [
			{
				text: "Ok",
				click: function() {

	if (confirm('Are you sure you want to move this page in the transcription repository: docID: '+docID+'; pageID: '+pageID+'; userName: '+assignee+'?')) {
		if (statusElement) {
			$(statusElement).show();
			$(statusElement).html('<div style="display:inline-block;" class="loading">&nbsp;&nbsp;&nbsp;</div> Moving transcription page...');
		}
		pageID = parseInt($('#movePagesStartPageID').val());
		var pageIDEnd = parseInt($('#movePagesEndPageID').val());
		var toPageID = parseInt($('#movePagesToPageID').val());
		var postData = {
			docID      : docID,
			pageID     : pageID,
			toPageID   : toPageID,
			userName   : assignee
		};
		if (!isNaN(pageIDEnd)) postData.pageIDEnd=pageIDEnd;
		VMR.serviceRequest('transcript/move/', postData, function(o) {
			var xml = null;
			var message = '';
			try {
				xml = $.parseXML(o.text);
				message = $(xml).find('success').attr('message');
				if (!message || !message.length) message = $(xml).find('error').attr('message');
			}
			catch(e) { message = e; }

/*
			if (statusElement) {
				$(statusElement).text(message);
			}
*/
			alert(message);

		});
		$( this ).dialog( "close" );
	}

				}

			}
		]
	});

}


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);
	}
	drawCanvases();
}


function drawCanvases() {
	$('canvas.undrawn').each(function() {
		var p = $(this).attr('data-percent');
		var m = $(this).attr('data-map');
		var d = $(this).attr('data-docID');
		var u = $(this).attr('data-userName');
		var isReconcile = $(this).hasClass('reconcile');
		var ctx=this.getContext("2d");
		var grd=ctx.createLinearGradient(0,0,0,170);
		grd.addColorStop(0,isReconcile?'orange':'lightgreen');
		grd.addColorStop(1,isReconcile?'darkorange':'green');
		ctx.fillStyle=grd;

		if (m && m.length > 0) {
			var drawStart = -1;
			for (var i = 0; i < m.length; ++i) {
				if (m[i] == '-') {
					if (drawStart != -1 && i > 0) {
						ctx.fillRect(this.width*(drawStart/m.length),0,this.width*((i-drawStart)/m.length),this.height);
						drawStart = -1;
					}
				}
				else if (drawStart == -1) drawStart = i;
			}
			if (drawStart != -1) {
				// draw
				ctx.fillRect(this.width*(drawStart/m.length),0,this.width,this.height);
			}
		}
		else ctx.fillRect(0,0,this.width*(p/100),this.height);

		$(this).removeClass('undrawn');
		$(this).qtip({
			content: {
				text: function(event, api) {
					$.ajax({
						url: VMR.httpRoot + '/vmr/api/projectmanagement/task/get/'
							+ '?projectID=' + projectID
							+ '&objectID=' + d
							+ '&taskTypeID=' + taskTypeID
							+ '&assignedTo=' + u
							+ '&detail=progress'
					})
					.then(function(content) {
						var t = '<div class="taskUnitsHeader">DocID<span style="float:right">'+d+'</span></div>';
						t += '<div class="taskUnitsHeader">User<span style="float:right">'+u+'</span></div>';
						t += '<div class="taskUnitsHeader updateStats"></div>';
						t += '<div class="taskUnitsStats"><table>';
						t += '<thead><tr><th style="text-align:right;">PageID</th><th style="text-align:center;">Transcr Repo</th><th style="text-align:center;white-space:nowrap;">DB Cache &nbsp;&nbsp;';
						if (isAdmin) {
							t += '<span class="refreshCache" onclick="refreshCache('+d+',\''+u+'\', $(this).parents(\'.taskUnitsStats\').prev(\'.updateStats\')); return false;">&nbsp;</span>';
						}
						t += '</th></tr></thead>';
						t += '<tbody>';
						var pages = $(content).find('unit').get();
						pages.sort(function(a,b){return parseInt($(a).attr('unitID'))-parseInt($(b).attr('unitID'));});
						var i = 0;
						$(pages).each(function() {
							var status = parseInt($(this).attr('status'));
							
							var pageID = $(this).attr('unitID');
							t += '<tr><td style="text-align:right;">'+pageID+'</td>';
							t += '<td style="text-align:center;color:'+(status & 2 ? 'green;">✔' : 'red;">x');
							if ((status & 2) && isAdmin) {
								t += '<span class="deleteTranscriptionPage" onclick="deleteTranscriptionPage('+d+','+pageID+', \''+u+'\', $(this).parents(\'.taskUnitsStats\').prev(\'.updateStats\')); return false;">&nbsp;</span>';
								t += '<span class="moveTranscriptionPage" onclick="moveTranscriptionPage('+d+','+pageID+', \''+u+'\', $(this).parents(\'.taskUnitsStats\').prev(\'.updateStats\')); return false;">&nbsp;</span>';
							}
							t += '</td>';
							t += '<td style="text-align:center;color:'+(status & 1 ? 'green;">✔' : 'red;">x')+'</td>';
							t += '</tr>';
							++i;
						});
						t += '</tbody></table></div>';
						api.set('content.text', t);
					}, function(xhr, status, error) {
						// Upon failure... set the tooltip content to the status and error value
						api.set('content.text', status + ': ' + error);
					});

					return 'Loading...'; // Set some initial text
				}
			},
			show: {
				delay: 1000
			},
			hide: {
				delay: 1000,
				fixed: true
			}
		});

	});
}


function removeAssignment(docID, assignee) {

	if (confirm('Are you sure you want to delete this assignement\n'+assignee+' -> '+ docID + '?')) {
	
		var postData = {
			objectID      : docID,
			taskTypeID    : 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'));
				$('#doc'+docID+'_assignee_'+assignee.replace(/[.() ]/g, '_')).remove();
//				loadStatus(projectID);
			}
		});
	}
}


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

	var t = '';
	$(projectXML).find('userGroup').children('user').each(function() {
		t += '<option>'+$(this).text()+'</option>';
	});
	$('#newAssignmentAssignee').html(t);

	$('#assignOther').prop('checked', false);
	$('#assignOtherName').val('');
	$('#newAssignmentDialog').dialog({
		resizable: false,
		height: "auto",
		modal: true,
		position: {
			my: "left bottom",
			at: "left top",
			of: $('#doc'+docID+'label')
		},
		width: Math.min(gadgets.window.getViewportDimensions().width-24, 300),
		title: 'Create New Assignment',
		buttons: {
			"Create Assignment": function() {
				$( this ).dialog( "close" );
				var assignee = $('#assignOther').is(':checked') ? $('#assignOtherName').val() : $('#newAssignmentAssignee').val();
				addAssignment($('#newAssignmentDoc').html(), assignee);
			},
			Cancel: function() {
				$( this ).dialog( "close" );
			}
		}
	});
}


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    : 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 {
				$('#doc'+docID).children('td').each(function() {
					if (!$(this).hasClass('transcribeStatus') && !$(this).hasClass('assignee')) {
						$(this).attr('rowspan',parseInt($(this).attr('rowspan'))+1);
					}
				});
				$('#assignments'+docID).append(getAssigneeRowHTML(docID, assignee));

				alert($(xml).find('success').attr('message'));
//				loadStatus(projectID);
			}
		});
	}
}


function mss_selected(docID) {
}

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

function biblicalcontent_select_callback(topic, data, subscriberData) {
	if (data.indexContent) {
		$('#buttonSelector').text(data.indexContent);
	}
}

function resetDisplayKind() {
	$('.displayKind').removeClass('displayKindFull displayKindSelector').addClass('displayKind'+displayKind);
}

VMR.init(function() {


	baseProjectID = parseInt(VMR.prefs.getString('project'));
	progressTask = VMR.prefs.getInt('progressTask');

	// smart defaults
	var pageTemplate = VMR.getPageURLSegment();
	if (VMR.preferredHeight == -2) {
		VMR.preferredHeight = -1
		if (pageTemplate == 'edition') {
			VMR.preferredHeight = 35;
		}
		VMR.setupHeight();
	}

	displayKind = VMR.preferredHeight == 35 ? 'Selector' : 'Full';

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

	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;
			}
			resetDisplayKind();
			loadStatus(baseProjectID);
			if (isAdmin) {
				var t = '';
//				t += '<div style="display:inline-block;" class="updateStats"></div> &nbsp; <span class="refreshCacheProject" title="Refresh verse cache for all project reconciled transcriptions." onclick="refreshCacheProject(); return false;">&nbsp;</span>';
//				t += ' &nbsp;&nbsp; <span class="refreshCachePublished" title="Refresh verse cache for all project published transcriptions." onclick="refreshCachePublished(); return false;">&nbsp;</span>';
				$('#adminControls').html(t);
			}
		});
	});


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

</script>
<div style="display:none;" id="newAssignmentDialog">
<p style="margin:0px 1px 0px 1px;">
New Assignment for Document: <span style="font-weight:bold;" id="newAssignmentDoc"></span><br/>
</p>
<p>
Assign to Project Member:<br/></br>
<select id="newAssignmentAssignee" style="width:100%;" name="newAssignmentAssignee">
<option></option>
</select>
</p><p>
<input id="assignOther" type="checkbox" /> Other: <input id="assignOtherName"/>
</p>
</div>

<div style="display:none;" id="taskStageChoices">
<div id="taskStageChoicesDescription">
</div>
<div id="taskStageChoicesOptions">
</div>
</div>

<div style="display:none;" id="movePagesDialog">
<p>Move transcription pages for docID <span id="movePagesDocID">&nbsp;</span>; user: <span id="movePagesUserName">&nbsp;</span></p>
<p>Starting page ID: <input id="movePagesStartPageID"/></p>
<p>Ending page ID: <input id="movePagesEndPageID"/></p>
<p>Move To page ID: <input id="movePagesToPageID"/></p>
</div>


</body>
</html>

]]>
</Content>
</Module>


