<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 
Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!--jsp:useBean id="jafer" scope="session" class="org.mdcog.jafer.JaferClient" / -->
<%@ page import="java.io.*" %>
<%@ page import="java.util.*" %>
<%@ page import="org.w3c.dom.*" %>
<%@ page import="org.w3c.dom.Node" %>
<%@ page import="javax.mail.internet.MimeBodyPart" %>
<%@ page import="javax.mail.MessagingException" %>
<%@ page import="javax.xml.transform.Templates" %>
<%@ page import="org.jafer.util.xml.DOMFactory" %>
<%@ page import="org.jafer.util.xml.XMLTransformer" %>
<%@ page import="org.jafer.util.xml.XMLSerializer" %>
<%@ page import="org.mdcog.server.UploadHandler" %>
<%@ page import="org.mdcog.server.FileFormItem" %>
<%@ page import="org.jafer.query.QueryBuilder" %>
<%@ page import="org.jafer.record.Field" %>
<%@ page import="org.mdcog.config.MdcConfig" %>
<%@ page import="org.mdcog.jafer.JaferClient" %>
<%@ page import="org.mdcog.db.Persistor" %>
<%@ page import="org.mdcog.databeans.ResultDisplayRow" %>
<%@ page import="org.mdcog.util.*" %>

<%@ page errorPage="error.jsp" %>
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib uri="/WEB-INF/displaytag-12.tld" prefix="display" %>

<jsp:useBean id="tabSet" scope="session" class="org.mdcog.databeans.SearchListBean" />

<jsp:useBean id="formBean" scope="page" class="org.mdcog.databeans.ResultFormBean">
    <jsp:setProperty name="formBean" property="chkId"/>
    <jsp:setProperty name="formBean" property="rlChk"/>
</jsp:useBean>

<jsp:useBean id="readingListBean" scope="session" class="org.mdcog.databeans.ReadingListBean" />
<%!
// Declarations
	public String getField(Map map, String fieldName) {
		String field = (String)map.get(fieldName);
		if (field == null) field = "";
		return field;
	}
        
        public Map getRequestAttributes(HttpServletRequest request) {
		HashMap map = new HashMap();
		Enumeration names = request.getAttributeNames();
		while (names.hasMoreElements()) {
			String name = (String)names.nextElement();
			Object obj = request.getAttribute(name);
			if (obj instanceof String) {
				map.put(name, obj);
			}
		}
		return map;
	}
        
        //For Debugging
        List jaferOutputList = null;
        
        
%> <% // Instream code
        boolean clearAll = false;
        if(request.getParameter("clearAllBt") != null) clearAll = true;
        
        if(clearAll) {
            tabSet.clearSearchList();
            //readingListBean.clearFieldsAndList();
        }

	// get or init MdcConfig
	MdcConfig mdcConfig = (MdcConfig)session.getAttribute("mdcconfig");
	if (mdcConfig == null || clearAll) {
		mdcConfig = new MdcConfig();
		session.setAttribute("mdcconfig",mdcConfig);
	}

	// get or init Persistor
	Persistor persistor = (Persistor)session.getAttribute("persistor");
	if (persistor == null || clearAll) {
		persistor = new Persistor(mdcConfig);
		session.setAttribute("persistor",persistor);
	}
	// get or init JaferClient
	JaferClient jafer = (JaferClient)session.getAttribute("jafer");
	if (jafer == null || clearAll) {
		jafer = new JaferClient(mdcConfig,persistor);
		session.setAttribute("jafer",jafer);
	}
        
        //To Store data from Manual addition form
        String rlAction = request.getParameter("rlAction");
        String fldstr;
        String errorMessage = "";
        String xslttype = request.getParameter("xslttype");
        String debugCatches = ""; //For debugging
	if (xslttype == null || clearAll) xslttype = "exporthtml.xq";
	// Process resource input form fields from popup
	if (rlAction != null && rlAction.equals("addanno")) {
		String recno = request.getParameter("recno");
		if (recno != null) {
			int irecno = Integer.parseInt(recno);
			fldstr = request.getParameter("inp_anno"); 
			if (fldstr != null) {
				ResultDisplayRow rdl = (ResultDisplayRow)readingListBean.getDisplayList().get(irecno);
				rdl.setField("ANNOTATION",fldstr);
				//readingListBean.getDisplayList().set(irecno,rdl);
			}
		}
	} else if (rlAction != null && rlAction.equals("addinput")) {
		Map formfields = new HashMap();
                fldstr = request.getParameter("itemtype"); if (fldstr == null) fldstr = "";
		formfields.put("itemtype",fldstr);
		fldstr = request.getParameter("inp_author"); if (fldstr == null) fldstr = "";
		formfields.put("AUTHOR",fldstr);
		fldstr = request.getParameter("inp_title"); if (fldstr == null) fldstr = "";
		formfields.put("TITLE",fldstr);
		fldstr = request.getParameter("inp_abstract"); if (fldstr == null) fldstr = "";
		formfields.put("ABSTRACT",fldstr);
		fldstr = request.getParameter("inp_publisher"); if (fldstr == null) fldstr = "";
		formfields.put("PUBLISHER",fldstr);
		fldstr = request.getParameter("inp_dateIssued"); if (fldstr == null) fldstr = "";
		formfields.put("DATE_ISSUED",fldstr);
		fldstr = request.getParameter("inp_isbn"); if (fldstr == null) fldstr = "";
		formfields.put("ISBN",fldstr);
		fldstr = request.getParameter("inp_issn"); if (fldstr == null) fldstr = "";
		formfields.put("ISSN",fldstr);
		fldstr = request.getParameter("inp_weburl"); if (fldstr == null) fldstr = "";
		formfields.put("WEB_URL",fldstr);
                fldstr = request.getParameter("inp_journal"); if (fldstr == null) fldstr = "";
		formfields.put("journal",fldstr);
                fldstr = request.getParameter("inp_jdate"); if (fldstr == null) fldstr = "";
		formfields.put("jdate",fldstr);
                fldstr = request.getParameter("inp_volume"); if (fldstr == null) fldstr = "";
		formfields.put("volume",fldstr);
                fldstr = request.getParameter("inp_startpage"); if (fldstr == null) fldstr = "";
		formfields.put("startpage",fldstr);
                fldstr = request.getParameter("inp_endpage"); if (fldstr == null) fldstr = "";
		formfields.put("endpage",fldstr);
		ResultDisplayRow newrow = new ResultDisplayRow();
		newrow.setDocSource("manual");
		newrow.setFields(formfields);
		readingListBean.addItem(newrow);
	} else if (rlAction != null && rlAction.equals("loadrl")) { // Process resource input form fields from popup
		String docid = request.getParameter("docid"); 
		if (docid != null && docid.length() > 0) {
			readingListBean.loadResourceList(docid);
			readingListBean.setDocId(docid);
		}
	}
        boolean hasRLFields = false;
        if(
            request.getParameter("rl-author") != null ||
            request.getParameter("rl-owner") != null ||
            request.getParameter("rl-title") != null ||
            request.getParameter("rl-annotation") != null
        ) {
            hasRLFields = true;
        }

	// Process save Resource List form
        if (hasRLFields) {
		fldstr = request.getParameter("rl-author"); if (fldstr == null) fldstr = "";
		readingListBean.setField("rlauthor",fldstr);
		fldstr = request.getParameter("rl-owner"); if (fldstr == null) fldstr = "";
		readingListBean.setField("institution",fldstr);
		fldstr = request.getParameter("rl-title"); if (fldstr == null) fldstr = "";
		readingListBean.setField("rltitle",fldstr);
		fldstr = request.getParameter("rl-annotation"); if (fldstr == null) fldstr = "";
		readingListBean.setField("annotation",fldstr);
		fldstr = request.getParameter("rl-dateCreated"); if (fldstr == null) fldstr = "";
                readingListBean.setField("rlDate",fldstr);
		if (rlAction.equals("save")) {
			readingListBean.setDocId("");
			readingListBean.saveResourceList(readingListBean.getFields());
		} else if (rlAction.equals("update")) {
			readingListBean.saveResourceList(readingListBean.getFields());
		}
	}

	//For Importing Reading list
        String upldmessage = "";
	String ctype = (String)request.getContentType();

	if (ctype != null && ctype.startsWith("multipart/form-data") && request.getParameter("btnUpload") != null) {
		BufferedInputStream bis = null;
		ByteArrayOutputStream baos = null;
		org.xmldb.api.base.Collection colCache = null;
		try {
			// process the multipart and get the uploaded file as a string - xmlstr
			String fileName = UploadHandler.processMultiPart(request);
			FileFormItem fileFormItem= (FileFormItem)request.getAttribute("file");
			MimeBodyPart part = fileFormItem.getBodyPart();
			String useruploadname = fileFormItem.getFileName();
                        //String fileName = fileFormItem.truncateFilename();
			bis = new BufferedInputStream(part.getInputStream());
			baos = new ByteArrayOutputStream();
			int ch = bis.read();
			while (ch != -1) {
				baos.write(ch);
				ch = bis.read();
			}
			String xmlstr = baos.toString();
			// check import format
			Map reqMap = getRequestAttributes(request);
			String impformat = (String)reqMap.get("impformat");
			String docId = "";
			// now process the import file into a set of one or more MODS records depending on the
			// format chosen by the user
			Node outNode = null;
			if (impformat != null && impformat.equals("MODS")) {
				System.out.println("Importing MODS");
				Document doc = DOMFactory.parse(xmlstr);
				outNode = doc.getDocumentElement();
			} else if (impformat != null && impformat.equals("ENDNOTEV7")) {
				System.out.println("Importing ENDNOTE");
				Document doc = DOMFactory.parse(xmlstr);
				File xslfile = new File(pageContext.getServletContext().getRealPath("/en7tomods.xsl"));
				Templates template = XMLTransformer.createTemplate(xslfile);
				Element rootNode = doc.getDocumentElement();
				rootNode.normalize();
				outNode = XMLTransformer.transform(rootNode, template);
			} else if (impformat != null && impformat.equals("ENDNOTEV8")) {
				System.out.println("Importing ENDNOTE");
				Document doc = DOMFactory.parse(xmlstr);
				File xslfile = new File(pageContext.getServletContext().getRealPath("/en8tomods.xsl"));
				Templates template = XMLTransformer.createTemplate(xslfile);
				Element rootNode = doc.getDocumentElement();
				rootNode.normalize();
				outNode = XMLTransformer.transform(rootNode, template);
			} else {
				throw new IOException("Import format not selected.");
			}
			int nimported = 0;
			if (outNode != null) {
				//	StringWriter writer = new StringWriter();
				//	XMLSerializer.out(outNode, "xml", writer);
				//	writer.flush();
				//	String resp = writer.toString();
				ArrayList ImpresultList = new ArrayList();
				NodeList l = ((Element)outNode).getElementsByTagName("mods");
				colCache = persistor.getCacheCollection();
                                for (int i = 0; i < l.getLength(); i++) {
					Node nd = l.item(i);
					Map fieldsMap = ModsUtils.getFields((Element)nd);
					System.out.println("IMP, fieldsmap["+i+"]:"+fieldsMap);
					ResultDisplayRow row = new ResultDisplayRow();
					// Persist record to db
					docId = persistor.storeSearchResultRecord(colCache,nd,fieldsMap);
					row.setDocId(docId);
					row.setDocSource("mdc-cache");
					row.setFields(fieldsMap);
					ImpresultList.add(row);
					nimported++;
				}
				if (ImpresultList.size() > 0) {
					int tab = tabSet.getNextTabNumber();
                                        tabSet.addResultList(impformat+"_"+tab, ImpresultList, null);
					//tabSet.addResultList(fileName+"("+impformat+")", resultList, null);
                                        //tabSet.addResultList(fileName, resultList, null);
				}
			}
			upldmessage = "File uploaded, records:"+nimported+" - Close this window to refresh Search window.";
		} catch (Exception e) {
			upldmessage = "Upload failed, error:"+e.toString();
		} finally {
			if (bis != null) try { bis.close(); } catch (Exception e) {}
			if (baos != null) try { baos.close(); } catch (Exception e) {}
			if (colCache != null) try { colCache.close(); } catch (Exception ex) {}

		}
	}

	//String searchopt = null;
	String filter = null;
	String maintab = request.getParameter("maintab");
	if (maintab != null && maintab.length() > 0 && !clearAll) {
		session.setAttribute("maintab",maintab);
	} else {
		maintab = (String)session.getAttribute("maintab");
		if (maintab == null || clearAll) {
			maintab = "federated";
			session.setAttribute("maintab",maintab);
		}
	}
	Map rlfields = (Map)session.getAttribute("rlfields");
	//if (rlfields == null || clearAll) {
        if (rlfields == null) {
		rlfields = new HashMap();
		session.setAttribute("rlfields",rlfields);
	}
	Map repfields = (Map)session.getAttribute("repfields");
	if (repfields == null || clearAll) {
		repfields = new HashMap();
		session.setAttribute("repfields",repfields);
	}

	filter = request.getParameter("filter");
	if (filter == null) filter = (String)session.getAttribute("filter");
	if (filter == null || clearAll) filter = "";
	session.setAttribute("filter",filter);

	// original search.jsp fields
	int perPage = 50; // maximum results per page.
	String readingListMessage = "";
	String searchMessage = "";
	String searchTabs = "";
	int tab = -1;
        boolean containsSearchInput = false;
        String tabWord = "";
	String remChecked = 
            (request.getParameter("remChecked") == null  || clearAll) 
            ? "false" : request.getParameter("remChecked");
	String keyword = 
            (request.getParameter("keyword") == null  || clearAll) 
            ? "" : request.getParameter("keyword").trim();
        String sTitle = 
            (request.getParameter("searchTitle") == null  || clearAll) 
            ? "" : request.getParameter("searchTitle").trim();
        String sAuthor = 
            (request.getParameter("searchAuthor") == null  || clearAll) 
            ? "" : request.getParameter("searchAuthor").trim();
        String resourceType =
            (request.getParameter("resourceType") == null || clearAll)
            ? "Default" : request.getParameter("resourceType");
        int maxResults = 
            (request.getParameter("maxResults") == null || clearAll)
            ? 25 : Integer.parseInt(request.getParameter("maxResults"));

        if (sAuthor.length() > 0) tabWord = sAuthor;
        if (keyword.length() > 0){
            if(tabWord.length() >0) {
                tabWord += "+" + keyword;
            }else { tabWord = keyword; }
        }
        if (sTitle.length() > 0) {
            if(tabWord.length() > 0) {
                tabWord += "+" + sTitle;
            }else{ tabWord = sTitle; }
        }
        if (tabWord.length() > 0)
            containsSearchInput = true;
      

	// Get the curent tab, either from the tab parameter or figure it out from the keyword
	try{
        if (request.getParameter("tab") != null  && !clearAll) {
		tab = Integer.parseInt(request.getParameter("tab"));// catch NumberFormatException
		tabSet.setCurrentTab(tab);

	} else if (containsSearchInput) {
			tab = tabSet.getTabIndex(tabWord,resourceType);
			if (tab >= 0) {
				tabSet.setCurrentTab(tab);
			}
        }
        }catch(Exception e){
            //debugCatches = "catch1"+e.getMessage();
        }
        /*String[] resTypes = null;
        if(search_types != null && search_types.size() > 0 && !clearAll) {
            resTypes = new String[search_types.size()];
            for(int i=0; i<search_types.size(); i++){
                resTypes[i] = (String)search_types.get(i);
            }
        }*/

	// If a keyword has been entered and it does not match one of the tabs do the search

        try{
        if (containsSearchInput && tab == -1 && !clearAll) {
            //debugCatches += "Reaches stage 3";
		List resultList = null;
		if (maintab == null || maintab.equals("federated")) {

                                resultList = jafer.doFederatedSearch(keyword, sAuthor, sTitle, resourceType, maxResults);
		}

		if (resultList != null) {
                        jaferOutputList = resultList;
			tab = tabSet.getNextTabNumber();
			tabSet.addResultList(tabWord, resultList,resourceType);

		}
	}
        } catch(Exception e) {
            debugCatches = "catch2"+e.getMessage();
        }

	// Generate the tabs
	if (tabSet.getSize() > 0)  {
		searchTabs = "<ul id='tabbed'>";
		for (int i=0; i< tabSet.getSize(); i++) {
			String cssClass = "tab";
			if (i == tabSet.getCurrentTab()) {
				cssClass = "selectedTab";
			}
			String text = tabSet.getKeyword(i);
			int textLength = Math.round(65/tabSet.getSize());
			if (text.length() > textLength) {
				text = text.substring(0, textLength) + "..";
			}
			searchTabs += "<li class='"+cssClass+"'><a href=\"search.jsp?tab="+i+"\">"+text+"</a></li>";
		 }
		 searchTabs += "</ul>";
	}

	// Set lists for display tag
	// First apply filter
	List reslist;
        Vector removeDocIds;
        if (remChecked.equals("true")){
		if (formBean.getRlChk().length > 0) {
			removeDocIds = 
                            readingListBean.removeItems(formBean.getRlChk());
                        tabSet.removeGreenChecks(removeDocIds);
			//readingListMessage += "<p>removed "+formBean.getRlChk().length+" items</p>";
		}
	}
        
	if (filter != null && filter.length() > 0) {
		String filterchk = filter.toLowerCase();
		reslist = new ArrayList();
		reslist.addAll(tabSet.getCurrentTabResults(null));
		Iterator itr = reslist.iterator();
		while (itr.hasNext()) {
			ResultDisplayRow row = (ResultDisplayRow)itr.next();
			Map chkfields = row.getFields();
			Iterator itr2 = chkfields.values().iterator();
			boolean found = false;
			while (itr2.hasNext()) {
				String str = ((String)itr2.next()).toLowerCase();
				//if (str.matches(filter)) 
				if (str.indexOf(filterchk) > -1) {
					found = true;
					break;
				}
			}
			if (!found) itr.remove();
		}
	} else {
            if (formBean.getChkId().length > 0) {
                reslist = tabSet.getCurrentTabResults(formBean.getChkId());
            }else {
                reslist = tabSet.getCurrentTabResults(null);
            }
		
	}
        if(!clearAll){
	request.setAttribute("results", reslist);
        request.setAttribute("rlist",readingListBean.getItems());
        }
        
	// reading list
	readingListBean.setPersistor(persistor);
        
        if (!remChecked.equals("true")){
		// formBean.getChkId returns a String[] of document id's for searchlist records that
		// have been checked for adding to the resource list
		if (formBean.getChkId().length > 0) {
			boolean res = readingListBean.addItems(formBean.getChkId(), reslist);
			if (!res) {
                            readingListMessage = "<p>Sorry, your items were not added.</p>";
                        }else{
				readingListMessage = "<strong>Your selected items have been successfully"+
				" added to the Reading List. Please select the 'Reading List' tab"+
				" at the top of the page to view the Reading list and the selected"+ 
				" items. </strong>";
			}
		}
	}

	String up = (request.getParameter("up") == null) ? "" : request.getParameter("up").trim();
	String down = (request.getParameter("down") == null) ? "" : request.getParameter("down").trim();

	if (up != "") {
		readingListBean.moveItemUp(up);
	}
	if (down != "") {
		readingListBean.moveItemDown(down);
	}
        // get client locale
        java.util.Locale locale = request.getLocale();
 
        // get Dateformat for client's locale
        java.text.DateFormat dateFormat =
            java.text.DateFormat.getDateTimeInstance(
            java.text.DateFormat.SHORT,
            java.text.DateFormat.SHORT, locale);

%>
<!-- HTML -->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <title>Reading List Search</title>
        <!-- <meta name="description" content="Annotation" />
        <meta name="keywords" content="MDCOG Annotation" />  -->
        
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <meta http-equiv="Content-Style-Type" content="text/css" />
        <meta name="description" content="MDCOG Search Client" />
        <meta name="keywords" content="MDCOG" />
	
        <script type="text/javascript" src="search.js"></script>
        <script language="javascript">
            function showPopup(url,name) {
            //alert(url);
            var newWindow;
            var props = 'scrollBars=yes,resizable=yes,toolbar=no,menubar=no,location=no,directories=no,width=900,height=700';
            newWindow = window.open(url, name, props);
            }
            function showPopup(url,name,width,height) {
            //alert(url);
            var newWindow;
            var props = 'scrollBars=yes,resizable=yes,toolbar=no,menubar=no,location=no,directories=no,width='+width+',height='+height;
            newWindow = window.open(url, name, props);
            }
            function showImportPopup(url,name) {
            //alert(url);
            var newWindow;
            var props = 'scrollBars=yes,resizable=yes,toolbar=no,menubar=no,location=no,directories=no,width=700,height=230';
            newWindow = window.open(url, name, props);
            }
            function validateCheckboxes1() {
            var chk = "";
            if (document.searchForm.chkId.length == undefined && document.searchForm.chkId.checked) {
            // check if only 1 checkbox
            return "true";
            }		
            for (var i=0; i < document.searchForm.chkId.length; i++) {
            if (document.searchForm.chkId[i].checked) {
            // alert("chkid: "+ document.searchForm.chkId[i].value);
            chk ="true";
            }
            }
            if (chk != "true") {
            alert("please select one or more items");
            }
            return chk;
            }
            function removeAllFilters() {
            document.getElementById("searchForm").filter.value="";
            document.getElementById("searchForm").submit();
            }
            function doUpDown(move, index){
            if(move == "up"){
            document.getElementById("searchForm").up.value = index;
            document.getElementById("searchForm").submit();
            }
            if(move == "down"){
            document.getElementById("searchForm").down.value = index;
            document.getElementById("searchForm").submit();
            }
            }
            function showCreateDoc(baseurl,citeprocurl,docid) {
            // note - we need to sort out proper logic for handling both multiple citeproc and cocoon stylesheets
            // "hardcoded" for now
            //alert("DocID:"+docid);
            if (docid == "undefined" || docid == "") {
            alert("Please save Resource List first.");
            } else {
            var selind = document.forms[0].xsltstyle.selectedIndex;
            var style = document.forms[0].xsltstyle.options[selind].text;
            var xslt = "undefined";
            for (var i=0; i < document.forms[0].xslttype.length; i++) {
            if (document.forms[0].xslttype[i].checked) {
            xslt = document.forms[0].xslttype[i].value;
            }
            }
            if (style == "standard") { // non-citeproc xslt's are hard coded for now - assume others are citeproc
            //alert("opening:"+baseurl+"/"+xslt+"?docid="+docid);
            window.open(baseurl+"/"+xslt+"?docid="+docid);
            } else {
            if (xslt == "exportpdf.pdf") {
            window.open(citeprocurl+"/mdc-xhtml-pdf?citation-style="+style+"&docid="+docid);
            } else {
            window.open(citeprocurl+"/mdc-xhtml?citation-style="+style+"&docid="+docid);
            }
            }
            }
            }
            function showAlert(message){
            alert(message);
            }
            function saveCurrentField(field) {
            document.getElementById("searchForm").focussingField.value = field.name;
            }
            function submitForm() {
            document.getElementById("searchForm").submit();
            }
            //function focusLastField() {
            //var lastField = "<%= request.getParameter("focussingField") %>";
            //document.forms[0][lastField].focus();
            //}
            
        </script>
        <link rel="stylesheet" type="text/css" href="main.css" media="all" />
    </head>
    <body>
    <form id="searchForm" name="searchForm" method="post" action="search.jsp">
        <input type="hidden" name="remChecked" value="false" />
        <input type="hidden" name="rlAction" value="false" />
        <input type="hidden" name="itemtype" value="false" />
        <!-- <input type="hidden" name="up" value="" />
        <input type="hidden" name="down" value="" /> -->
        <input type="hidden" name="focussingField" value="" />
        <!-- fields for manual input -->
        <input type="hidden" name="inp_author" value="false" />
        <input type="hidden" name="inp_title" value="false" />
        <input type="hidden" name="inp_abstract" value="false" />
        <input type="hidden" name="inp_publisher" value="false" />
        <input type="hidden" name="inp_dateIssued" value="false" />
        <input type="hidden" name="inp_isbn" value="false" />
        <input type="hidden" name="inp_issn" value="false" />
        <input type="hidden" name="inp_weburl" value="false" />
        <!-- fields for annotation -->
        <input type="hidden" name="recno" value="" />
        <input type="hidden" name="inp_anno" value="" />
        <input type="hidden" name="docid" value="" />
        <!-- For Journal Articles -->
        <input type="hidden" name="inp_jdate" value="false" />
        <input type="hidden" name="inp_journal" value="false" />
        <input type="hidden" name="inp_volume" value="false" />
        <input type="hidden" name="inp_startpage" value="false" />
        <input type="hidden" name="inp_endpage" value="false" />

        <!-- <span style="float: right;">Link to <a target="_blank" href="http://ask.oucs.ox.ac.uk/ask/index.php/ASK">ASK Repostory</a> (Requires log-in)</span> -->
        <span style="float: right;">
            <a target="_blank" href="testServer.jsp">Test your repository</a>&nbsp;|&nbsp;
            Link to <a target="_blank" href="http://flounder.oucs.ox.ac.uk/mdc2/listRepos.jsp?maintab=input">Reading list repository</a>
        </span>

        <ul id="tabbed">
            <li <% if(maintab == null || maintab.equals("federated")) { %> 
            class="selectedTab" 
            <% } %> ><a href="search.jsp?maintab=federated">Search</a></li>
            <li <% if(maintab.equals("readinglist")){ %>
            class="selectedTab" 
            <% } %> ><a href="search.jsp?maintab=readinglist">Reading List</a></li>
            <!-- <li <% if(maintab.equals("repository")) { %>
            class="selectedTab" 
            <% } %> ><a href="listRepos.jsp?maintab=input">ASK</a></li> -->
        </ul>
        <% if (maintab == null || maintab.equals("federated")){ %>
        <br/>
        <!-- <h1> Search </h1> <br/> -->
        <fieldset>
            <table align="center" width="100%">
                <tr>

                    <td width="35%" style="width:35%">
                        <div>
                            <table> 
                                <tr> <th width="15%">Keyword:</th>
                                <td align="left">
                                    <input type="text" id="keyword" name="keyword" value="<%= keyword %>" size="25" tabindex="1" accesskey="k" />
                                </td> </tr>
                                <tr>
                                <th width="15%">Author:</th>
                                <td align="left">
                                    <input type="text" id="searchAuthor" name="searchAuthor" value="<%= sAuthor %>" size="25" tabindex="2" accesskey="a" />
                                </td> </tr>
                                <tr> <th width="15%">Title:</th>
                                <td align="left">
                                    <input type="text" id="searchTitle" name="searchTitle" value="<%= sTitle %>" size="25" tabindex="3" accesskey="t" />
                                </td> </tr>
                            
                                <tr> <td colspan="2">
                                    <input type="submit" tabindex="4" name="searchBtn" value="Search" onClick="showMessage();"/>
                                </td> </tr>
                            </table>
                        </div>
                    </td>

                    <td width="35%" valign="top" style="width:35%">
                        <div>
                            <table>
                                <tr> <th width="45%">Resource type:</th>
                                    <td>
                                        <select name="resourceType" >
                                            <option <% if (resourceType.equals("Default")) {%> selected="true" <% } %>>Default</option>
                                            <option <% if (resourceType.equals("Books")) {%> selected="true" <% } %>>Books</option>
                                            <option <% if (resourceType.equals("Journals")) {%> selected="true" <% } %>>Journals</option>
                                            <option <% if (resourceType.equals("Images")) {%> selected="true" <% } %>>Images</option>
                                            <option <% if (resourceType.equals("Videos")) {%> selected="true" <% } %>>Videos</option>
                                            <option <% if (resourceType.equals("Reading lists")) {%> selected="true" <% } %>>Reading lists</option>
                                            <option <% if (resourceType.equals("Assessments")) {%> selected="true" <% } %>>Assessments</option>
                                        </select> 
                                    </td>
                                </tr>
                                <tr> <th width="45%">Max. no. of results:</th>
                                    <td>
                                        <select name="maxResults" >
                                            <option <% if (maxResults == 25) {%> selected="true" <% } %>>25</option>
                                            <option <% if (maxResults == 50) {%> selected="true" <% } %>>50</option>
                                            <option <% if (maxResults == 75) {%> selected="true" <% } %>>75</option>
                                            <option <% if (maxResults == 100) {%> selected="true" <% } %>>100</option>
                                        </select> 
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </td>
                    <td width="23%" valign="top">
                        <div id="searchResults">
                    
                            <table border="1">
                                <tr> 
                                    <th> 
                                    <h2 align="center">Import Reading List</h2></th>
                                </tr>
                                <tr> 
                                    <td> 
                                    <!-- <table>
                                    <tr>
                                    <th>Format</th><td>
                                    <select name="impformat">
                                    <option selected="selected" value="MODS">MODS XML</option>
                                    <option value="ENDNOTEV7">EndNote v7 XML</option>
                                    <option value="ENDNOTEV8">EndNote v8+ XML</option>
                                    </select></td>
                                    </tr>
                                    <tr>
                                    <th>Import</th><td><input type="file" size="30" name="file" /></td>
                                    </tr>
                                    </table>
                                    <input type="submit" id="inp_form" name="btnUpload" value="Upload" /> -->
                                    <div align="center"><br/>
                                        <input type="button" id="saveList" value="Import" onclick="showImportPopup('rlImportToTab.jsp','rlImport');" />
                                        <br/>
                                    </div></td>
                                </tr>
                            </table>
                            <!-- <p><font color="blue"><%=upldmessage%></font></p> -->
                        </div>
                    </td>
                </tr>
            </table>
        </fieldset>
        <div style="color:red">
            <strong>
        <%= errorMessage %>
            </strong>
        </div>
        <div id="searchResults">
            
            <br/>
                <h2> Search Results: </h2>
                <div align="right"> 
                    <input type="submit" name="clearAllBt" value="Clear All"/>
                </div>
            </br>
            <fieldset>
                <table align="center">
                    <tr >
                        <td style="width: 570px;">
                            <span style="float: left;">
                                <span>Filter these results:</span>
                                <input type="text" id="saveList" name="filter" size="42" value="<%=filter%>" />
                                <input type="submit" id="saveList"  value="Filter" />
                                <input type="submit" id="saveList" value="Display All" onclick="removeAllFilters(); return false;"
                                <% if (filter.equals("")) { %>
                                disabled="disabled"
                                <%}%>
                                />
                            </span>
                        </td>
                    </tr>
                </table>
            </fieldset>
		<%=searchTabs%>
            <table>
                <tr>
                <td style="width:4%">&nbsp;</td>
                <td class="authorCol"><strong>Author</strong></td>
                <td class="titleCol"><strong>Title</strong></td>
                <td class="dateCol"><strong>Date</strong></td>				
                <td class="publisherCol"><strong>Publisher/Journal</strong></td>
                <td class="smallCol"><strong>ISBN/ISSN</strong></td>
                <!-- <td class="smallCol"><strong>ISSN</strong></td> -->
                </tr>
            </table>
            <div id="resultsDiv">

                <display:table name="results" id="results" class="resultsTable" pagesize="<%=maxResults%>" summary="Table of Search Results">
                    <display:column sortable="false" title="" width="4%">
                    <% if(((ResultDisplayRow)pageContext.getAttribute("results")).getIsSelected()){ %>
                        <div align="center"><img alt="Added" src="green_tick02.png"/></div>
                    <% } else {%> 
                        <label for="chkId_<%=results_rowNum.intValue()-1%>" class="hide">select</label><input name="chkId" type="checkbox" id="chkId_<%=results_rowNum.intValue()-1%>" value="<%=results_rowNum.intValue()-1%>" class="checkbox" />
                    <% } %>
                    </display:column>

                    <display:column sortable="true" title="Author" class="authorCol" ><%=((Map) ((ResultDisplayRow)pageContext.getAttribute("results")).getFields()).get("AUTHOR")%></display:column>

                    <display:column sortable="true" title="Title" class="titleCol">
                    <% String itemPath = ((Map) ((ResultDisplayRow)pageContext.getAttribute("results")).getFields()).get("WEB_URL").toString().trim();
                    String itemTitle = ((Map) ((ResultDisplayRow)pageContext.getAttribute("results")).getFields()).get("TITLE").toString().trim();
                    if (itemPath == null || itemPath.equals("")){%>
                        <%=itemTitle%>
                    <% }else{%>
                        <a target="_blank" href="<%= itemPath %>"> <%= itemTitle %> </a>
                    <% } 
                    if(((ResultDisplayRow)pageContext.getAttribute("results")).getDocSource().equals("manual")){ %>
                        <img alt="Added manually" src="manual.gif"/>
                            <% } %>
                    </display:column>
                    <display:column sortable="true" title="Date" class="dateCol"><%=((Map) ((ResultDisplayRow)pageContext.getAttribute("results")).getFields()).get("DATE_ISSUED")%></display:column>
                    <display:column sortable="true" title="Publisher/Journal" class="publisherCol">
                    <% String pubOrJournal = ((Map) ((ResultDisplayRow)pageContext.getAttribute("results")).getFields()).get("JOURNAL").toString().trim();
                    if (pubOrJournal == null || pubOrJournal.equals("")){
                    pubOrJournal = ((Map) ((ResultDisplayRow)pageContext.getAttribute("results")).getFields()).get("PUBLISHER").toString().trim();
                    } %>
                    <%= pubOrJournal %>
                    </display:column>
                    <display:column sortable="true" title="ISBN/ISSN" class="smallCol">
                    <% String itemISBNorISSN = ((Map) ((ResultDisplayRow)pageContext.getAttribute("results")).getFields()).get("ISBN").toString().trim();
                    if (itemISBNorISSN == null || itemISBNorISSN.equals("")){
                    itemISBNorISSN = ((Map) ((ResultDisplayRow)pageContext.getAttribute("results")).getFields()).get("ISSN").toString().trim();
                    } %>
                    <%= itemISBNorISSN %>
                    </display:column>
                    <display:setProperty name="sort.behavior" value="list" />
                    <display:setProperty name="paging.banner.include_first_last" value="false" />
                    <display:setProperty name="paging.banner.onepage" value="" />
                    <display:setProperty name="paging.banner.placement" value="bottom" />
                    <display:setProperty name="basic.msg.empty_list" value="" />
                    <display:setProperty name="sort.amount" value="list" />
                </display:table>
            </div>
            <input type="button" name="checkAllBt" value="Select All" onClick="checkAll('chkId');"/>
            <input type="submit" id="list1" value="Add Selected Items to Reading List" onclick="showWaitMessage();return validateCheckboxes1();" />
            <%=readingListMessage%>
        </div>
        <% } else if (maintab.equals("readinglist")) { %>
        <br/> 
        <h1> Reading List </h1> <br/>

        <div id="rlSaveFormInp">

            <table>
                <tr>
                    <th>Title</th><td><input type="text" size="60" name="rl-title" value="<%=readingListBean.getField("rltitle")%>" onChange="submitForm();" /> e.g. Material Technology Course</td>
                </tr>
                <tr>
                    <th>Author</th><td><input type="text" size="30" name="rl-author" value="<%=readingListBean.getField("rlauthor")%>" onChange="submitForm();" /> e.g. Fred Bloggs</td>
                </tr>
                <tr>
                    <th>Institution</th><td><input type="text" size="30" name="rl-owner" value="<%=readingListBean.getField("institution")%>" onChange="submitForm();" /> e.g. Oxford University</td>
                </tr>
                <tr>
                    <th>Notes</th><td><textarea cols="60" rows="3" name="rl-annotation"  onChange="submitForm();"><%=readingListBean.getField("annotation")%></textarea>
                    e.g. This reading list provides most of the main ...</td>
                </tr>
                <tr>
                    <th>Date Created</th><td><input type="text" size="15" name="rl-dateCreated" value="<%=
        //(readingListBean.getField("dateCreated").equals(""))?Calendar.getInstance().getTime().toString():readingListBean.getField("dateCreated")
           (readingListBean.getField("dateCreated").equals(""))?dateFormat.format( new java.util.Date()):readingListBean.getField("rlDate")
        %>" onChange="submitForm();" /> e.g. 10/06/06 18:20</td>
                </tr>
            </table>
        </div>


        <div id="readingList">
            <br/>
            <div align="left">
                <input type="button" id="addManualInSearchPage" name="addManualInSearchPage" value="Add Item Manually" onclick="showPopup('rlManual.jsp','rlManual',750,500);" />
                &nbsp;
            </div> <br/>
		
            <table>
                <tr>
                <td style="width:2%">&nbsp;</td>
                <td style="width:3%">&nbsp;</td>
                <td style="width:3%">&nbsp;</td>
                <td class="authorCol"><strong>Author</strong></td>
                <td class="titleCol"><strong>Title</strong></td>
                <td class="publisherCol"><strong>Publisher/Journal</strong></td>                    
                <td class="dateCol"><strong>Date</strong></td>				
                <td class="smallCol"><strong>ISBN/ISSN</strong></td> 
                <td class="smallCol"><strong>Annotate</strong></td>
                </tr>
            </table>

            <!-- generate the table -->
            <div id="readingListResultsDiv">
		<% if (readingListBean.getDisplayList().size() > 0 ) { %>
                <table summary="Your Reading List" class="resultsTable">
                    <!-- <thead>
                    <tr>
                    <th></th>
                    <th></th>
                    <th></th>
                    <th class="authorCol">Author</th>
                    <th class="titleCol">Title</th>
                    <th class="publisherCol">Publisher</th>
                    <th class="dateCol">Issued</th>
                    <th class="smallCol">ISBN</th>
                    <th class="smallCol">ISSN</th>
                    <th class="smallCol">OpenURL</th>
                    </tr>
                    </thead> -->
                    <tbody>
			<%
			for (int i=0 ; i < readingListBean.getDisplayList().size(); i++) {
				ResultDisplayRow rdl = (ResultDisplayRow)readingListBean.getDisplayList().get(i);
			%>
                        <!-- Where from:<%= rdl.getDocSource() %> -->
                        <tr class="<%= (i % 2 == 0) ? "odd":"even"%>">
                            <td><label for="rlChk_<%=i%>" class="hide">select</label><input id="rlChk_<%=i%>" type="checkbox" name="rlChk" value="<%=i%>" class="checkbox" /></td>
                            <!-- <td><a href="#" name="upLink" onclick="doUpDown('up','<%= i %>'); return false"><img alt="up" border="0" src="arrow_up.gif" /></a></td> -->
                            <td><a href="?up=<%=i%>" ><img alt="up" border="0" src="arrow_up.gif" /></a></td>
                            <td><a href="?down=<%=i%>"><img alt="down" border="0" src="arrow_down.gif"/></a></td>

                            <!-- <td><a href="#" name="downLink" onclick="doUpDown('down','<%= i %>'); return false"><img alt="down" border="0" src="arrow_down.gif"/></a></td> -->
                            <td class="authorCol"><%=rdl.getField("AUTHOR") %></td>
                            <td class="titleCol">
                            <% String itemPath = rdl.getField("WEB_URL");
                            String itemTitle = rdl.getField("TITLE");
                            if (itemPath == null || itemPath.equals("")){%>
                                <%=itemTitle%>
                            <% }else{%>
                                <a target="_blank" href="<%= itemPath %>"> <%= itemTitle %> </a>
                            <% } 
                            if(rdl.getDocSource().equals("manual")){ %>
                                <img alt="Added manually" src="manual.gif"/>
                            <% } %>
                            </td>
                            <td class="publisherCol">
                            <% if(rdl.getField("itemtype") == null || (rdl.getField("itemtype").equals("")) || (rdl.getField("itemtype").equals("book"))){%>
                            <%=rdl.getField("PUBLISHER") %>
                            <% } else if (rdl.getField("itemtype").equals("journal")) { %>
                            <%= rdl.getField("journal") %>
                            <% } %>
                            </td>
                            <td class="dateCol"><%=rdl.getField("DATE_ISSUED") %></td>
                            <td class="smallCol">
                            <% if(rdl.getField("itemtype") == null || (rdl.getField("itemtype").equals("")) || (rdl.getField("itemtype").equals("book"))){%>
                            <%=rdl.getField("ISBN") %>
                            <% } else if (rdl.getField("itemtype").equals("journal")) { %>
                            <%= rdl.getField("ISSN") %>
                            <% } %>
                            </td>
                            <!-- <td class="smallCol"><%=rdl.getField("issn") %></td> -->
                            <td><a href="#"><img src="penhand3.gif" border="0" alt="Annotate" onclick="showPopup('rlAnno.jsp?recno=<%=i%>','rlAnno',650,250);" /></a></td>
                        </tr>
			<%}%>
                    </tbody>
                </table>
            <%}%>
            </div>
            <% if (readingListBean.getDocId().length() == 0) { %>
            <input type="submit" id="saveList" value="Save To Repository" onclick="document.searchForm.rlAction.value='save';" />
								<% } else { %>
            <input type="submit" id="saveList" value="Update" onclick="document.searchForm.rlAction.value='update';" />
            <input type="submit" id="saveList" value="Save As New" onclick="document.searchForm.rlAction.value='save';" />
								<% } %>
            <input type="submit" id="removeChecked" name="removeChecked" value="Remove Selected Items" onclick="document.searchForm.remChecked.value = true;" />
        </div>
        
        <br/> <br/>				

        <div id="createDoc" align="center">
            
            <table>
                <tr> 
                    <td colspan="2"> <h2 align="left">Export Reading list</h2></td>
                </tr>
                <tr> 
                    <th><div align="center">Apply Style</div></th>
                    <td><div align="center"> 
                        <select name="xsltstyle" >
                            <option selected="true">standard</option>
                            <option>apa-en</option>
                            <option>note-bib</option>
                            <option>number</option>
                        </select>
                    </div></td>
                    <td colspan="2"> <div align="center"> 
                        <input type="radio" name="xslttype" value="exporthtml.xq" <% if (xslttype == null || xslttype.equals("exporthtml.xq")) { %> checked="true" <% } %>  >
                        HTML</input> 
                        <input type="radio" name="xslttype" value="exportpdf.pdf" <% if (xslttype == null || xslttype.equals("exportpdf.pdf")) { %> checked="true" <% } %>  >
                        PDF</input> 
                        <input type="radio" name="xslttype" value="exportmods.xq" <% if (xslttype == null || xslttype.equals("exportmods.xq")) { %> checked="true" <% } %>  >
                        MODS XML</input> 
                        <input type="radio" name="xslttype" value="exportrtf.rtf" <% if (xslttype == null || xslttype.equals("exportrtf.rtf")) { %> checked="true" <% } %>  >
                        RTF</input> 
                        <input type="radio" name="xslttype" value="exporten.en" <% if (xslttype == null || xslttype.equals("exporten.en")) { %> checked="true" <% } %>  >
                        END NOTE</input> 
                        <input type="button" value="Create" onclick="showCreateDoc('<%=mdcConfig.getXsltUri()%>','<%=mdcConfig.getCiteprocUri()%>','<%=readingListBean.getDocId()%>');" />
                        <!-- <input type="button" id="saveList" value="Resource List..." onclick="showResourcePopup();" /> -->
                    </div></td>
                </tr>
            </table>
        </div>
        
        <!-- <span style="float: left;"><input type="submit" id="removeChecked" name="removeChecked" value="Remove" onclick="document.searchForm.remChecked.value = true;" />
        &nbsp;<input type="button" id="saveList" value="Save List" onclick="showPopup('rlSaveForm.jsp','rlSaveForm');" /></span> -->
                    <% } %>

    </form>
    
    
    <div id="searchingPopUp" style="visibility: hidden;"><b>Search in progress...please 
    wait</b></div>
    
    <div id="waitPopUp" style="visibility: hidden;"><b>Please wait..</b></div>
    <span style="float: right;">Powered by <a target="_blank" href="http://www.jafer.org">JAFER</a></span>    
    </body>
</html>