//  Set the current page whose image is being displayed.
//
//  In normal circumstances there is a 'pagenum' CGI parameter which gives
//    the page number to be displayed.
//
//  This 'pagenum' parameter may be specified as zero to request that the
//    first page containing hits be displayed (or the first page of the
//    document, if there are no hits).
//
//  Additionally, if the 'Search Within' form has been used to search within
//    the current document then we instead display the first page with hits,
//    if there are any, regardless of the 'pagenum' parameter.
//
function set_current_page()
{
	var i;

	//  Find the first page with hits, if any
	//
	var firsthitpage = 0;
	for ( i = 1; i <= totalpages; i++ )
	{
		if ( "" + hitcounts[ i ] != "undefined" && hitcounts[ i ] > 0 )
		{
			firsthitpage = i;
			break;
		}
	}

	//  If 'Search Within' has been used then then the 'gotoFirstHit' CGI
	//    parameter will have been set.  Go to the first hit, if any
	//
	if ( gotofirsthit == "Y" && firsthitpage != 0 )
	{
		currentpage = firsthitpage;
	}

	//  Or if the 'pagenum' parameter is explicitly zero, go to the first
	//    hit (if any) or else to the first page
	//
	else if ( pagenum == "0" )
	{
		currentpage = firsthitpage > 0 ? firsthitpage : 1;
	}

	//  Otherwise use any 'pagenum' parameter as the current page
	//
	else if ( pagenum != "" )
	{
		currentpage = parseInt( pagenum );
	}
	
}

//  Output the page list for this document.  Pages with hits are highlighted,
//    and hovering over these displays the number of hits.
//
//  Each item in the list is either a single page or a range of ten or
//    a hundred pages or a thousand pages.  For example, when displaying page 123
//    of a document with 345 pages the list will be:
//
//      1-100
//      101-110 111-120
//      121 122 123 124 125 126 127 128 129 130
//      131-140 141-150 151-160 161-170 171-180 181-190 191-200
//      201-300 301-345
//
function output_page_list()
{
	var pagelist = "";
	var i;

	//  Form the array of page ranges that will be output
	var numranges = 0;
	var rangestartnos = new Array();
	var rangeendnos = new Array();
	var rangehitcounts = new Array();
	var rangetargets = new Array();
	var start, end, rangesize, hitcount, firsthitpage;

/*
	alert( "Forming page list: currentpage = " + currentpage +
	       ", totalpages = " + totalpages );
*/

	for ( start = 1; start <= totalpages; start += rangesize )
	{

		rangesize = 1;


		//  Form the end point of this range
		end = start + rangesize - 1;
		if ( end > totalpages ) end = totalpages;

		//  Count the number of hits in this range, and determine which page
		//    contains the first hit
		hitcount = 0;
		firsthitpage = 0;
		for ( i = start; i <= end; i++ )
		{
			if ( "" + hitcounts[ i ] != "undefined" )
			{
				//  Add the hits on this page to the total
				hitcount += hitcounts[ i ];
				//  Check if this is the first page with any hits
				if ( firsthitpage == 0 ) firsthitpage = i;
			}
		}

		//  Add this range to the arrays
		rangestartnos[ numranges ] = start;
		rangeendnos[ numranges ] = end;
		rangehitcounts[ numranges ] = hitcount;
		rangetargets[ numranges ] = firsthitpage ? firsthitpage : start;
		numranges ++;
	}

	//  Output each range
	for ( i = 0; i < numranges; i++ )
	{
		pagelist += " <nobr>";

		var hitmsg = rangehitcounts[ i ] == 0 ? "" :
		             rangehitcounts[ i ] == 1 ? "1 hit" :
		             "" + rangehitcounts[ i ] + " hits";

		if ( rangestartnos[ i ] != currentpage )
		{
			pagelist += "&nbsp;<a href=\"javascript: goto_page( " +
			            rangetargets[ i ] + " )\" " +
			            ( hitmsg ? " title=\"" + hitmsg + "\"" : "" ) +
			            ">";
		}
		else
		{
			pagelist += "<strong>";
		}

		if ( hitmsg )
		{
			pagelist += "<span class=\"fthitbox\">";
		}

		if ( rangestartnos[ i ] == rangeendnos[ i ] )
		{
			pagelist += "" + rangestartnos[ i ];
		}
		else
		{
			pagelist += "" + rangestartnos[ i ] + "-" + rangeendnos[ i ];
		}

		if ( hitmsg )
		{
			pagelist += "</span>";
		}

		if ( rangestartnos[ i ] != currentpage )
		{
			pagelist += "</a>";
		}
		else
		{
			pagelist += "</strong>";
		}

		pagelist += "</nobr>";
	}

	document.write( pagelist );
}

//  Output the '<img ...>' tag for the page image
//
function output_page_image()
{
	var baseurl = "http://" + window.location.host; //+"http://bsc.private.chadwyck.co.uk";
	var i;
	var startpos, endpos, coordlist, colonpos, pageno, xycoords;
	var allcoords = "";
	var allcontexts = "";

	//  Form the URL for the requested page image
	var url = baseurl +
	          "/imageserver/pageimage.cgi" +
	          "?RECORD=" + recordid +
	          "&PAGENO=" + currentpage +	          
	          ( enlarge ? "&LARGER=Y" : "" );

	/*
	alert( "Called 'output_page_image': recordid = '" + recordid +
	       "', currentpage = " + currentpage +
	       ", hitcounts[ currentpage ] = " + hitcounts[ currentpage ] );
	*/

	//  If there are any hits on the current page, append the parameter
	//    to request hit-highlighting at the indicated locations
	if ( "" + hitcounts[ currentpage ] != "undefined" &&
	     hitcounts[ currentpage ] > 0 )
	{
		// alert( "Processing " + hitcontexts.length + " hit contexts ..." );

		for ( i = 0; i < hitcontexts.length; i++ )
		{
			//  Extract coordinates '[page:x1,y1-x2,y2]' from within brackets
			startpos = hitcontexts[ i ].indexOf( "[" );
			while ( startpos != -1 )
			{
				endpos = hitcontexts[ i ].indexOf( "]", startpos );
				if ( endpos == -1 ) break;

				//  Extract the contents of the brackets
				coordlist = hitcontexts[ i ].substr( startpos + 1,
				                                     endpos - startpos - 1 );

				//  Extract the page number and (x,y) coordinates
				colonpos = coordlist.indexOf( ":" );
				pageno = coordlist.substr( 0, colonpos );
				xycoords = coordlist.substr( colonpos + 1 );

				//  If hit is for current page, add to highlighting list
				if ( "" + pageno == "" + currentpage )
				{
					allcoords += ( allcoords != "" ? ":" : "" ) +
					             xycoords;

					/*
					alert( "From context: '" + hitcontexts[ i ] + "'\n" +
					       "Obtained coords '" + coordlist + "'\n" +
					       "Decomposed to: " +
					       "pageno '" + pageno + "' " +
					       "xycoords '" + xycoords + "'" );
					*/
				}

				//  Advance to next bracketed hit location
				startpos = hitcontexts[ i ].indexOf( "[", endpos );
			}

			if ( "" + pageno == "" + currentpage )
			{
				allcontexts += hitcontexts[ i ] + "<BR/>";
			}
		}
	}

	if ( allcoords != "" ) url += "&COORDS=" + allcoords +
	                              "&COLOUR=FFFF99&MARGIN=32";

	// document.write( "<P>Highlighted contexts are: '" + allcontexts + "'</P>" );

	// document.write( "<P>Highlight coords are: '" + allcoords + "'</P>" );

	var caption = sessno + " " + paperno + " " + title;
	document.write( "<img border=\"1\" " +
	                "src=\"" + url + "\" " +
	                "alt=\"" + caption + ", page " + currentpage +
	                " of " + totalpages + "\">" );
}

//  Navigate to a different page in the current document
//
//  This uses the navigation form at the bottom of the page, which contains
//    the 'Search Within' box, and hidden fields for the state of the
//    currently displayed page.
//
function goto_page( newpage )
{
	var form = document.forms[ "NAVIGATE" ];
	
	//  Update the page number
	form.elements[ "pagenum" ].value = newpage;
form.elements[ "page" ].value = pge;


	//  Submit the form to redisplay with the new image
	form.submit();
}

//  Link from the 'Reading view' page back to the standard 'Full text' page
//
function back_to_full_text_page()
{
	var form = document.forms[ "NAVIGATE" ];

	//  Change form's submission URL to the 'Full text' page
	form.action = "/fulltext/fulltext.do";

	//  Update the page number
	form.elements[ "pagenum" ].value = currentpage;

	//  Switch off the 'show all illustrations' flag
	form.elements[ "showall" ].value = "";

	//  Switch off the 'enlarged image' flag
	form.elements[ "enlarge" ].value = "";

	//  Submit the form to redisplay with the new image
	form.submit();
}

//  Link from the standard 'Full text' page to the 'Reading view' page
//
function show_reading_view_page()
{
	var form = document.forms[ "NAVIGATE" ];

	//  Change form's submission URL to the 'Reading view' page
	form.action = "/fulltext/readview.do";

	//  Update the page number
	form.elements[ "pagenum" ].value = currentpage;

	//  Switch off the 'show all illustrations' flag
	form.elements[ "showall" ].value = "";

	//  Switch on the 'enlarged image' flag
	form.elements[ "enlarge" ].value = "Y";

	//  Submit the form to redisplay with the new image
	form.submit();
}


//  Process the submission of the 'Search Within' form.
//
function process_search_within()
{
	var form = document.forms[ "NAVIGATE" ];

	//  Update the form with the current page number
	form.elements[ "pagenum" ].value = currentpage;

	//  Set the 'gotoFirstHit' flag to indicate that the redisplayed page
	//    should display the first hit in preference to the current page
	//
	form.elements[ "gotoFirstHit" ].value = "Y";

	//  Get the search string from the text box and insert it
	//    as the current 'searchWithin' parameter setting
	//
	form.elements[ "searchWithin" ].value = form.elements[ "SEARCHSTRING" ].value

	/*
	alert( "Starting new Search Within for:\n" +
	       form.elements[ "searchWithin" ].value );
	*/

	//  Return 'true' to indicate that form submission should proceed
	return true;
}

//  Cancel any current 'Search Within' operation, redisplaying the current
//    page with its original highlighting (if any)
//
function cancel_search_within()
{
	var form = document.forms[ "NAVIGATE" ];

	//  Update the form with the current page number
	form.elements[ "pagenum" ].value = currentpage;

	//  Discard any 'Search Within' expression
	form.elements[ "searchWithin" ].value = "";

	//  Submit the form to redisplay the current page
	form.submit();
}

//  Navigate to the 'Full Record' page for the displayed record
//
//  This uses the same parameters as the current page for the record ID,
//    and details of the current search.
//
//  An extra parameter 'fulltexthits=N' needs to be added giving the
//    number of hits in the full text (if there are any) so that this
//    can be displayed in the 'View full text' link on the Full Record
//    page.
//
function goto_full_record()
{
	//  Form the URL by changing path to 'fullrec/fullrec.do'
	//
	var newurl = "http://" + window.location.host +
	             "/search/displayCdefCitation.do" + window.location.search;

	//  Count the number of hits in the fulltext, and add an extra
	//    parameter to the URL if there are any
	//
	var i;
	var fulltexthits = 0;
	for ( i = 0; i < hitcounts.length; i++ )
	{
		if ( "" + hitcounts[ i ] != "undefined" )
		{
			fulltexthits += hitcounts[ i ];
		}
	}
	if ( fulltexthits > 0 ) newurl += "&fulltexthits=" + fulltexthits;

	// alert( "URL for Full Record is:\n" + newurl );

	window.location = newurl;
}

//  Output the list of page numbers representing a particular category
//    of illustration (i.e. Table, Map or Plate) with each page number
//    being a hyperlink.
//
//  When a set of three or more successive pages are illustrations of
//    a given type then these are output as a dash-separated range,
//    with the two numbers being hyperlinks to the start and end pages.
//
//  If the 'showall' CGI parameter is supplied then the list will
//    include all the illustrations.  In its absence only the first
//    ten are shown, with a '... More' link to redisplay the page with
//    all shown.
//
function output_illustration_list( caption, pagelist )
{
	var text = "";

	//  No action if there are no page numbers
	if ( pagelist == "" ) return;

	//  Read the comma-separated page numbers into an array
	var pagenos = new Array();
	var pos = 0;
	var endpos;
	while ( pos < pagelist.length )
	{
		//  Find the comma that terminates the next number
		endpos = pagelist.indexOf( ",", pos );
		if ( endpos == -1 )
		{
			//  Last number in the list
			pagenos[ pagenos.length ] = parseInt( pagelist.substr( pos ) );
			break;
		}
		else
		{
			//  Next number in list
			pagenos[ pagenos.length ] = parseInt( pagelist.substr( pos, endpos - pos ) );
			//  Skip past the terminating comma
			pos = endpos + 1;
		}
	}
	// alert( caption + "\n" + pagenos.join( ", " ) );

	//  Form the successive page numbers and ranges
	var numshown = 0;
	var i, j;
	for ( i = 0; i < pagenos.length; i++ )
	{
		//  If the 'showall' CGI parameter is not specified then truncate
		//    the illustrations list after a certain number
		//
		if ( showall == "" && numshown == 10 )
		{
			text += "&nbsp;...&nbsp;" +
			        "<a href=\"javascript: show_illustrations()\">" +
			        "More images" +
			        "</a>" +
			        "<img src=\"/images/arrowsmall_right.gif\" alt=\"\" " +
			        "border=\"0\" width=\"16\" height=\"7\">";
			break;
		}

		//  Look ahead to find a run of successive pages
		var runlength = 1;
		for ( j = 1; i + j < pagenos.length; j++ )
		{
			if ( pagenos[ i + j ] == pagenos[ i ] + j )
			{
				runlength ++;
			}
			else
			{
				break;
			}
		}

		//  Output a run of three or longer as a dash-separated range
		if ( runlength >= 3 )
		{
			//  Output the range of pages
			if ( text != "" ) text += ", ";
			j = i + runlength - 1;
			text += "<a href=\"javascript:goto_page(" + pagenos[ i ] + ")\">" +
			        pagenos[ i ] + "</a>" +
			        "-" +
			        "<a href=\"javascript:goto_page(" + pagenos[ j ] + ")\">" +
			        pagenos[ j ] + "</a>"
			//  Skip past the page numbers that have been omitted
			i += runlength - 1;
		}

		//  Otherwise output a single page
		else
		{
			//  Output the range of pages
			if ( text != "" ) text += ", ";
			text += "<a href=\"javascript:goto_page(" + pagenos[ i ] + ")\">" +
			        pagenos[ i ] + "</a>";
		}

		//  Increment count of number of pages / ranges displayed
		numshown ++;
	}

	//  If the 'showall' CGI parameter is specified then add a 'Show fewer'
	//    link to hide some of the displayed list
	if ( showall != "" && numshown > 10 )
	{
		text += "&nbsp;&nbsp;&nbsp;" +
		        "<img src=\"/images/arrowsmall_left.gif\" alt=\"\" " +
		        "border=\"0\" width=\"16\" height=\"7\">" +
		        "<a href=\"javascript: hide_illustrations()\">" +
		        "Less images" +
		        "</a>";
	}

	//  Output the caption followed by its list of page numbers
	document.write( "<strong>" + caption + "</strong> " + text + "<br/>" );
}

//  Redisplay the current page with the illustrations lists expanded to
//    show all the pages with illustrations
//
function show_illustrations()
{
	var form = document.forms[ "NAVIGATE" ];

	//  Update the form with the current page number
	form.elements[ "pagenum" ].value = currentpage;

	//  Switch on the 'showall' parameter
	form.elements[ "showall" ].value = "Y";

	//  Submit the form to redisplay the current page
	form.submit();
}

//  Redisplay the current page with the illustrations lists contracted
//    to show only the first few pages with illustrations
//
function hide_illustrations()
{
	var form = document.forms[ "NAVIGATE" ];

	//  Update the form with the current page number
	form.elements[ "pagenum" ].value = currentpage;

	//  Switch off the 'showall' parameter
	form.elements[ "showall" ].value = "";

	//  Submit the form to redisplay the current page
	form.submit();
}

//  Redisplay the current page with a larger page image
//
function enlarge_page_image()
{
	var form = document.forms[ "NAVIGATE" ];

	//  Update the form with the current page number
	form.elements[ "pagenum" ].value = currentpage;

	//  Switch on the 'enlarge' parameter
	form.elements[ "enlarge" ].value = "Y";

	//  Submit the form to redisplay the current page
	form.submit();
}

//  Redisplay the current page with a smaller page image
//
function reduce_page_image()
{
	var form = document.forms[ "NAVIGATE" ];

	//  Update the form with the current page number
	form.elements[ "pagenum" ].value = currentpage;

	//  Switch off the 'enlarge' parameter
	form.elements[ "enlarge" ].value = "";

	//  Submit the form to redisplay the current page
	form.submit();
}

//  Output the 'Larger image / Smaller image' link
//
function output_image_size_link()
{
	if ( enlarge )
	{
		//  Image is currently enlarged.
		//    Output the 'Smaller image' link to reduce it
		var link = "<a href=\"javascript: reduce_page_image()\">" +
		           "Smaller image" +
		           "</a>";
	}
	else
	{
		//  Image is currently reduced.
		//    Output the 'Larger image' link to enlarge it.
		var link = "<a href=\"javascript: enlarge_page_image()\">" +
		           "Larger image" +
		           "</a>";
	}

	document.write( link );
}

//  Output the Previous / Next page links
//
function output_prev_next_page_links()
{
	var prevpage = currentpage - 1;
	var nextpage = currentpage + 1;

	var prevlink = "<img src=\"/images/arrowsmall_left.gif\" " +
	               "alt=\"\" width=\"16\" height=\"7\">" +
	               "<a href=\"javascript:goto_page( " + prevpage + " )\">" +
	               "Previous page" +
	               "</a>";
	var nextlink = "<a href=\"javascript:goto_page( " + nextpage + " )\">" +
	               "Next page" +
	               "</a>" +
	               "<img src=\"/images/arrowsmall_right.gif\" " +
	               "alt=\"\" width=\"16\" height=\"7\">";

	var text;
	if (prevpage > 0){
		text = prevlink;
		if (nextpage <= totalpages){
			text = text + "&nbsp;|&nbsp;" + nextlink;
		}
	}
	else if (nextpage <= totalpages){
		text = nextlink;
	}
	else{
		text = "";
	}
	/*if ( currentpage <= 1 )
	{
		text = nextlink;
	}
	else if ( currentpage >= totalpages )
	{
		text = prevlink;
	}
	else
	{
		text = prevlink + "&nbsp;|&nbsp;" + nextlink;
	}*/

	document.write( text );
}

//  Go to the 'Download Document' page for this record.
//
function goto_document_download_page()
{
	var newurl = "/fulltext/docdownload.jsp" +
	             "?id=" + recordid +
	             "&numpages=" + totalpages +
	             "&megabytes=" + Math.ceil( 0.1 * totalpages ) +
	             "&sessno=" + escape( sessno ) +
	             "&paperno=" + escape( paperno ) +
	             "&title=" + escape( title );

	window.location = newurl;
}

//  Display a PDF file containing just the current page image
//
function get_pdf()
{
	var newurl = "http://" + window.location.host +//"http://bsc.private.chadwyck.co.uk" +
	             "/imageserver/pdf_download.cgi" +
	             "?RECORD=" + recordid +	           
	             "&PAGES=" + currentpage +
	 "&TOTALPAGES=" + totalpages +   
         "&WARNING=N" +
	             "&DOWNLOAD=N";
	window.open( newurl, "_blank" );
}

//  Display a PDF file containing just the current page image
//
function get_pdf_newwindow(recid, pag)
{
	var newurl = "http://" + window.location.host +//"http://bsc.private.chadwyck.co.uk" +
	             "/imageserver/pdf_download.cgi" +
	             "?RECORD=" + recid +
            "&PAGES=" + pag +
	             "&WARNING=N" +
	             "&DOWNLOAD=N";
	window.open( newurl, "_blank" );
}

//  Display a PDF file containing just the current page image
//
function get_pagepdf(recid, pag)
{
	var newurl = "http://" + window.location.host +//"http://bsc.private.chadwyck.co.uk" +
	             "/imageserver/pagepdf_download.cgi" +
	             "?RECORD=" + recid +
	             "&PAGES=" + pag +
	             "&WARNING=N" +
	             "&DOWNLOAD=N";
	window.open( newurl, "_blank" );
}
function get_downloadpagepdf(recid, pag)
{
        var newurl = "http://" + window.location.host +//"http://bsc.private.chadwyck.co.uk" +
                     "/imageserver/pagepdf_download.cgi" +
                     "?RECORD=" + recid +
                     "&PAGES=" + pag +
                "&PAGENUMBER=" + currentpage +
                     "&WARNING=N" +
                     "&DOWNLOAD=N";
        window.open( newurl, "_blank" );
}
//  Download the original TIFF image for the current page
//
function get_tiff()
{
	var newurl = "http://" + window.location.host +//"http://bsc.private.chadwyck.co.uk" +
	             "/imageserver/tiff_download.cgi" +
	             "?RECORD=" + recordid +
	             "&PAGENO=" + currentpage;
	window.location = newurl;
}
