<?xml version="1.0" encoding="UTF-8" ?>
<%@ page import="java.net.URL" %>
<%
response.setContentType("text/xml");
String userAgent = request.getHeader("user-agent");
boolean mobile = (userAgent != null && userAgent.toLowerCase().indexOf("mobile") > -1);
System.out.println("user-agent: " + userAgent + "; mobile: "+mobile);
%>
<Module>
  <ModulePrefs
	title="Image Viewer"
	author_email="scribe777@gmail.com"
	author="CrossWire"
	description="Papyri Image Viewer"
	screenshot="http://crosswire.org/images/crosswire.gif"
	thumbnail="http://crosswire.org/images/crosswire.gif"
        scrolling="false"
   >
<Optional feature="pubsub-2">
  <Param name="topics">
    <![CDATA[ 
    <Topic title="Image Selection" name="interedition.image.selected"
            description="Show an Image" type="string"
            subscribe="true"/>
    <Topic title="Annotation Add" name="interedition.image.annotation.add"
            description="Adds Annotation To Image" type="string"
            subscribe="true"/>
    <Topic title="Annotation Selected" name="interedition.image.annotation.selected"
            description="Adds Annotation To Image" type="string"
            subscribe="true"/>
    ]]>
  </Param>
</Optional>
  <Optional feature="dynamic-height"/>
  <Optional feature="opensocial-0.8"/>
  <Optional feature="settitle"/>
</ModulePrefs>

<UserPref name="height" datatype="enum" display_name="Gadget Height" default_value="600">
	<EnumValue value="200" display_value="Short"/>
	<EnumValue value="400" display_value="Medium"/>
	<EnumValue value="600" display_value="Tall"/>
</UserPref>
<UserPref name="customCSS" datatype="string" display_name="Add Custom CSS resource to Gadget" default_value="" />
<UserPref name="customJS" datatype="string" display_name="Add Custom JS resource to Gadget" default_value="" />

<Content type="html">
<![CDATA[
<head>
	<script type="text/javascript" src="/community/js/jquery/jquery.min.js"></script>
	<script type="text/javascript" src="/community/js/jquery.blockUI.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>
</head>
<body>
<style type="text/css">
body {background-color: transparent;}

#attribution a:link {text-decoration:none;}
#attribution a:visited {text-decoration:none;}
#attribution a:hover {text-decoration:underline;}
#attribution a:active {text-decoration:underline;}
#attribution {
	margin: 0px;
	padding: 0px;
	float:left;
	font-size: 15px;
	white-space:nowrap;
}
#attribution img { float:right; height:42px;}
#attribution div { padding: 5px 0px 0px 0px; display: inline-block; margin-right: 3px; }

</style>

<div style="height:45px;font-family:serif; position: absolute; float:left; clear:right;padding:2px 5px 0px 5px;margin:1px 0px 0px 1px;">
<span id="attribution">
</span>
</div>

<%@ include file="../viewport.jsp" %>
<script>

var pageData = null;
var personalAnnotations = false;
var origTitle = '';

function myLoadImage(image, ltor) {
	offset = image.lastIndexOf('/', image.length-2); offset++;
	site = image.substring(0, offset);
	image = image.substring(offset, image.length);
	init_papyri_viewport(site, image, ltor);
	personalAnnotations = false;
}


function modalWait(message) {
	$.blockUI({ message: '<h2><img src="'+VMR.imagesURL+'/loading.gif" /> '+ message+'</h2>', fadeIn: 0, fadeOut: 0 });
}

function modalUnWait() {
	$.unblockUI();
}

function customAddImageLocation() {
	if (pageData == null) {
		return addImageLocation();
	}
	else {
		return '&site=INTF&image=' +
		pageData.docID + '/' + '0' + '/' +
		pageData.pageID + '/' +
		pageData.surrID + '/' +
		parseInt(pageData.docID) % parseInt(pageData.pageID);
	}
}

function select_callback(topic, data, subscriberData) {

	if (pageData == null) {
		myLoadImage(data);
	}

	else {
		showLoading();
		var postData = {
			sessionHash : $.cookie('ntvmrSession'),
			d : pageData.docID,
			p : pageData.pageID,
			s : pageData.surrID,
			z : parseInt(pageData.docID) % parseInt(pageData.pageID)
		};
		VMR.webRequest(VMR.gadgetsRoot + '/modules/papyri/imageget.jsp', postData, function(o) {
			var imageData = (o.text);
			var offset = imageData.indexOf('|');
			var attribution = null;
			if (offset > -1) {
				attribution = imageData.substring(0, offset);
				imageData = imageData.substring(offset+1);
			}

			var isRawData = imageData.startsWith('enc://');

			// since we delay load, there could have been a feature asked to zoom
			// while we were loading.  This is cleared in 'init_papyri_viewport'
			// so we have to handle it ourselves.  We should probably be using something like loadImage instead
			zoomFeatureOnLoadSave =  zoomFeatureOnLoad;
			if (isRawData) {
				imageData = imageData.substring(6);
				init_papyri_viewport('data:image/jpeg;base64,', imageData);
			}
			else {
				myLoadImage(imageData);
			}
			if (zoomFeatureOnLoadSave) zoomToShowBox(zoomFeatureOnLoadSave);

			if (attribution) setAttribution(attribution);
			personalAnnotations = false;
		});
	}
}


function regionBoxSelected(rb) {
        VMR.publish("interedition.image.annotation.selected", (rb != null)?rb.key:null);
}


function regionBoxModified(rb) {

	if (rb.key.length <= getPrivatePrefix().length
		|| !rb.key.substring || rb.key.substring(0, getPrivatePrefix().length) != getPrivatePrefix()) {

		var data = {};
		data.key = rb.key;
		data.text = rb.text;
		data.x = rb.x;
		data.y = rb.y;
		data.w = rb.w;
		data.h = rb.h;
		VMR.publish("interedition.image.annotation.changed", data);
	}
}


function anno_add_request_callback(topic, data, subscriberData) {
	document.body.style.cursor = 'url('+VMR.imagesURL+'/drawboxcursor.png), auto';
	$('#addAnnotationControl').css('cursor', 'url('+VMR.imagesURL+'/drawboxcursor.png), auto');
	startBoxTool(data, function (box) {
		document.body.style.cursor = 'default';
		$('#addAnnotationControl').css('cursor', 'default');
		VMR.publish("interedition.image.annotation.add.request.completed", box);

	});
}

function anno_add_callback(topic, data, subscriberData) {
	if (data.x) {
		insertBox(data.x,data.y,data.w,data.h,data.text,data.key);
	}
	else	insertTrans(true, data);
}


function anno_focus_callback(topic, data, subscriberData) {
	zoomToShowBox(data);
}


function anno_sel_callback(topic, data, subscriberData) {
	setCurrentBoxByKey(data, true);
}


function anno_lock_callback(topic, data, subscriberData) {
	lockToRegionBox(data);
}


function anno_remove_callback(topic, data, subscriberData) {
	removeBoxByKey(data);
}


function clearViewer() {
	pageData = null;
	var span = document.getElementById('moreControlsBefore');
	span.innerHTML = '';
	span = document.getElementById('moreControlsAfter');
	span.innerHTML = '';
	
	myLoadImage(VMR.imagesURL + '/blank.gif');
	personalAnnotations = false;
	setAttribution('');
}


function manuscript_selected_callback(topic, data, subscriberData) {
	clearViewer();
}

function getAttributionElement() {
	return $('#attribution');
}

function page_selected_callback(topic, data, subscriberData) {
	if (data.hasImage) {
		pageData = data;

		VMR.setPageTitle(pageData.docID + ' ('+pageData.docName+'): '+pageData.pageID+' ('+pageData.pageName+')');

		if (VMR.inLiferay) {
			parent.document.title = origTitle + ' - ' + pageData.docID + ' ('+pageData.docName+'): '+pageData.pageID+' ('+pageData.pageName+')';
			var span = document.getElementById('moreControlsBefore');
			span.innerHTML = '<span class="toolbuttonSpan" onclick="addTempAnnotation();" title="Add Temporary Annotation For Linking or Discussion"><img class="toolbutton" id="addAnnotationControl" src="'+VMR.imagesURL+'/tbicons/30x-Crop.png"/></span>';
			span = document.getElementById('moreControlsAfter');
			span.innerHTML = '<span class="toolbuttonSpan" onclick="discussPageAnnotation(pageData);" title="Discuss This Page"><img class="toolbutton" src="'+VMR.imagesURL+'/tbicons/30x-Chats.png"/></span>';
		}
	}
	else clearViewer();
}


function discussPageAnnotation(pageData) {
	if (!pageData) return;	// assert we've loaded a page

	var pageCategoryName = 'Page '+pageData.pageID + (pageData.pageName && pageData.pageName.length > 0 ? (' (folio '+pageData.pageName+')') : '');
	VMR.assureCategory(0, 'Annotations', 'Manuscript Annotations and Features', function(catID, messageCount) {
		VMR.assureCategory(catID, ''+pageData.docID + ' ('+pageData.docName+')', '', function(catID, messageCount) {
			VMR.assureCategory(catID, pageCategoryName, '', function(catID, messageCount) {
				var makeInitialMessage = !messageCount;
				if (makeInitialMessage || personalAnnotations) {

					var subject = ''+ pageData.docID + ' ('+pageData.docName+') '
							+ pageCategoryName;

					for (var i = 0; i < (makeInitialMessage && personalAnnotations ? 2 : 1); ++i) {
						var x = {};
						// odd magic here that if prefix is 'imageOnly', then we ignore zoom and pan too
						setLinkOnlyPrefixedBoxes(makeInitialMessage && i == 0 ? 'imageOnly' : getPrivatePrefix());
						updateLinkURL(x);
						setLinkOnlyPrefixedBoxes(getPrivatePrefix());
						var body = '<p><a href="'+x.href
							+ '" target="_blank">Jump To Artifact</a></p>'
							+ '<br/>\n\n\n';
						if (!makeInitialMessage || i > 0) {
							body += '<p> You should: <b>Edit this message.</b> '
								+ 'Be sure to leave the above link, edit the Subject, and delete this line.</p>';
						}

						VMR.createMessage(catID, subject + ((makeInitialMessage && i == 0) ? ' General Discussion' : ''), body, (makeInitialMessage && i == 0), function(msgID, postImmediately) {
							if (!postImmediately) {

								var discussURL = URI('forum/-/message_boards/').absoluteTo(parent.window.location.href).toString();
								discussURL += 'message/'+msgID;

								window.open(discussURL,'Discuss',
									  'titlebar=no,toolbar=no,status=no,scrollbars=yes,resizable=yes,menubar=no,location=yes,directories=no,'
									+ 'width=1024,height=768');
							}
						});
					}
				}
			});
		});
	});
}


var counter = 0;
function addTempAnnotation() {
	document.body.style.cursor = 'url('+VMR.imagesURL+'/drawboxcursor.png), auto';
	$('#addAnnotationControl').css('cursor', 'url('+VMR.imagesURL+'/drawboxcursor.png), auto');
	startBoxTool(getPrivatePrefix()+(counter++), function (box) {
		document.body.style.cursor = 'default';
		$('#addAnnotationControl').css('cursor', 'default');
		if (box) personalAnnotations = true;
	});
}




VMR.MARGIN = 2;
VMR.init(function() {
	var customCSS  = VMR.prefs.getString('customCSS');
	var customJS   = VMR.prefs.getString('customJS');

	if (customCSS && customCSS.length) {
		$('head').append('<link rel="stylesheet" type="text/css" href="'+customCSS+'"/>');
	}
	if (customJS && customJS.length) {
		$.getScript(customJS, function(data, textStatus, jqxhr) {});
	}

	VMR.subscribe("interedition.image.selected", select_callback);
	VMR.subscribe("interedition.image.annotation.add", anno_add_callback);
	VMR.subscribe("interedition.image.annotation.add.request", anno_add_request_callback);
	VMR.subscribe("interedition.image.annotation.remove", anno_remove_callback);
	VMR.subscribe("interedition.image.annotation.selected", anno_sel_callback);
	VMR.subscribe("interedition.image.annotation.lockmodify", anno_lock_callback);
	VMR.subscribe("interedition.image.annotation.focus", anno_focus_callback);

	// for pretty names used for discussion
	VMR.subscribe("interedition.page.selected", page_selected_callback);
	// let's clear out our current image if a new manuscript is selected-- maybe this should be done by someone else?
	VMR.subscribe("interedition.manuscript.selected", manuscript_selected_callback);

	if (VMR.inLiferay) origTitle = parent.document.title;

	// TODO: delete if not needed // gadgets.io.getProxyUrl(VMR.imagesURL);
	setImagesURL(VMR.imagesURL);

	setLinkOnlyPrefixedBoxes(getPrivatePrefix());

	setViewerURL(VMR.httpRoot+'modules/papyri/');

	clearViewer();
//	myLoadImage('http://community.crosswire.org/modules/papyri/repo/p52_back.gif');
}, '../../');

</script>
</body>

]]>
</Content>
</Module>